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-server-common/src/main/java/org/sonar/server/webhook/Webhook.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.webhook;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static java.util.Objects.requireNonNull;
import static java.util.Optional.ofNullable;
@Immutable
public class Webhook {
private final String uuid;
private final String projectUuid;
@Nullable
private final String ceTaskUuid;
@Nullable
private final String analysisUuid;
private final String name;
private final String url;
@Nullable
private final String secret;
public Webhook(String uuid, String projectUuid, @Nullable String ceTaskUuid,
@Nullable String analysisUuid, String name, String url, @Nullable String secret) {
this.uuid = uuid;
this.projectUuid = requireNonNull(projectUuid);
this.ceTaskUuid = ceTaskUuid;
this.analysisUuid = analysisUuid;
this.name = requireNonNull(name);
this.url = requireNonNull(url);
this.secret = secret;
}
public String getProjectUuid() {
return projectUuid;
}
public Optional<String> getCeTaskUuid() {
return ofNullable(ceTaskUuid);
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public String getUuid() {
return uuid;
}
public Optional<String> getAnalysisUuid() {
return ofNullable(analysisUuid);
}
public Optional<String> getSecret() {
return ofNullable(secret);
}
}
| 2,255 | 26.512195 | 86 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/WebhookCaller.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;
public interface WebhookCaller {
/**
* Call webhook by sending a HTTP(S) POST request containing
* the JSON payload.
* <br/>
* Errors are silently ignored. They don't generate logs or
* throw exceptions. The error status is stored in the
* returned {@link WebhookDelivery}.
*/
WebhookDelivery call(Webhook webhook, WebhookPayload payload);
}
| 1,247 | 34.657143 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/WebhookCallerImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.webhook;
import java.io.IOException;
import java.util.Optional;
import okhttp3.Credentials;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;
import static java.nio.charset.StandardCharsets.UTF_8;
import static okhttp3.internal.http.StatusLine.HTTP_PERM_REDIRECT;
import static okhttp3.internal.http.StatusLine.HTTP_TEMP_REDIRECT;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
@ServerSide
@ComputeEngineSide
public class WebhookCallerImpl implements WebhookCaller {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final String PROJECT_KEY_HEADER = "X-SonarQube-Project";
private final System2 system;
private final OkHttpClient okHttpClient;
public WebhookCallerImpl(System2 system, OkHttpClient okHttpClient, WebhookCustomDns webhookCustomDns) {
this.system = system;
this.okHttpClient = newClientWithoutRedirect(okHttpClient, webhookCustomDns);
}
@Override
public WebhookDelivery call(Webhook webhook, WebhookPayload payload) {
WebhookDelivery.Builder builder = new WebhookDelivery.Builder();
long startedAt = system.now();
builder
.setAt(startedAt)
.setPayload(payload)
.setWebhook(webhook);
try {
HttpUrl url = HttpUrl.parse(webhook.getUrl());
if (url == null) {
throw new IllegalArgumentException("Webhook URL is not valid: " + webhook.getUrl());
}
builder.setEffectiveUrl(HttpUrlHelper.obfuscateCredentials(webhook.getUrl(), url));
Request request = buildHttpRequest(url, webhook, payload);
try (Response response = execute(request)) {
builder.setHttpStatus(response.code());
}
} catch (Exception e) {
builder.setError(e);
}
return builder
.setDurationInMs((int) (system.now() - startedAt))
.build();
}
private static Request buildHttpRequest(HttpUrl url, Webhook webhook, WebhookPayload payload) {
Request.Builder request = new Request.Builder();
request.url(url);
request.header(PROJECT_KEY_HEADER, payload.getProjectKey());
if (isNotEmpty(url.username())) {
request.header("Authorization", Credentials.basic(url.username(), url.password(), UTF_8));
}
signatureOf(webhook, payload).ifPresent(signature -> request.header("X-Sonar-Webhook-HMAC-SHA256", signature));
RequestBody body = RequestBody.create(JSON, payload.getJson());
request.post(body);
return request.build();
}
private Response execute(Request request) throws IOException {
Response response = okHttpClient.newCall(request).execute();
return switch (response.code()) {
case HTTP_MOVED_PERM, HTTP_MOVED_TEMP, HTTP_TEMP_REDIRECT, HTTP_PERM_REDIRECT ->
// OkHttpClient does not follow the redirect with the same HTTP method. A POST is
// redirected to a GET. Because of that the redirect must be manually
// implemented.
// See:
// https://github.com/square/okhttp/blob/07309c1c7d9e296014268ebd155ebf7ef8679f6c/okhttp/src/main/java/okhttp3/internal/http/RetryAndFollowUpInterceptor.java#L316
// https://github.com/square/okhttp/issues/936#issuecomment-266430151
followPostRedirect(response);
default -> response;
};
}
/**
* Inspired by https://github.com/square/okhttp/blob/parent-3.6.0/okhttp/src/main/java/okhttp3/internal/http/RetryAndFollowUpInterceptor.java#L286
*/
private Response followPostRedirect(Response response) throws IOException {
String location = response.header("Location");
if (location == null) {
throw new IllegalStateException(format("Missing HTTP header 'Location' in redirect of %s", response.request().url()));
}
HttpUrl url = response.request().url().resolve(location);
// Don't follow redirects to unsupported protocols.
if (url == null) {
throw new IllegalStateException(format("Unsupported protocol in redirect of %s to %s", response.request().url(), location));
}
Request.Builder redirectRequest = response.request().newBuilder();
redirectRequest.post(response.request().body());
response.body().close();
return okHttpClient.newCall(redirectRequest.url(url).build()).execute();
}
private static OkHttpClient newClientWithoutRedirect(OkHttpClient client, WebhookCustomDns webhookCustomDns) {
return client.newBuilder()
.followRedirects(false)
.followSslRedirects(false)
.dns(webhookCustomDns)
.build();
}
private static Optional<String> signatureOf(Webhook webhook, WebhookPayload payload) {
return webhook.getSecret()
.map(secret -> new HmacUtils(HmacAlgorithms.HMAC_SHA_256, secret).hmacHex(payload.getJson()));
}
}
| 6,052 | 38.822368 | 170 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/WebhookCustomDns.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.webhook;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;
import okhttp3.Dns;
import org.jetbrains.annotations.NotNull;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
import static org.sonar.api.CoreProperties.SONAR_VALIDATE_WEBHOOKS_DEFAULT_VALUE;
import static org.sonar.api.CoreProperties.SONAR_VALIDATE_WEBHOOKS_PROPERTY;
@ServerSide
@ComputeEngineSide
public class WebhookCustomDns implements Dns {
private final Configuration configuration;
private final NetworkInterfaceProvider networkInterfaceProvider;
public WebhookCustomDns(Configuration configuration, NetworkInterfaceProvider networkInterfaceProvider) {
this.configuration = configuration;
this.networkInterfaceProvider = networkInterfaceProvider;
}
@NotNull
@Override
public List<InetAddress> lookup(@NotNull String host) throws UnknownHostException {
InetAddress address = InetAddress.getByName(host);
if (configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY).orElse(SONAR_VALIDATE_WEBHOOKS_DEFAULT_VALUE)
&& (address.isLoopbackAddress() || address.isAnyLocalAddress() || isLocalAddress(address))) {
throw new IllegalArgumentException("Invalid URL: loopback and wildcard addresses are not allowed for webhooks.");
}
return Collections.singletonList(address);
}
private boolean isLocalAddress(InetAddress address) {
try {
return networkInterfaceProvider.getNetworkInterfaceAddresses().stream()
.anyMatch(a -> a != null && a.equals(address));
} catch (SocketException e) {
throw new IllegalArgumentException("Network interfaces could not be fetched.");
}
}
}
| 2,676 | 37.797101 | 119 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/WebhookDelivery.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.webhook;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static com.google.common.base.Throwables.getRootCause;
import static java.util.Objects.requireNonNull;
/**
* A {@link WebhookDelivery} represents the result of a webhook call.
*/
@Immutable
public class WebhookDelivery {
private final Webhook webhook;
private final WebhookPayload payload;
private final String effectiveUrl;
private final Integer httpStatus;
private final Integer durationInMs;
private final long at;
private final Throwable error;
private WebhookDelivery(Builder builder) {
this.webhook = requireNonNull(builder.webhook);
this.payload = requireNonNull(builder.payload);
this.effectiveUrl = builder.effectiveUrl;
this.httpStatus = builder.httpStatus;
this.durationInMs = builder.durationInMs;
this.at = builder.at;
this.error = builder.error;
}
public Webhook getWebhook() {
return webhook;
}
public WebhookPayload getPayload() {
return payload;
}
public Optional<String> getEffectiveUrl() {
return Optional.ofNullable(effectiveUrl);
}
/**
* @return the HTTP status if {@link #getError()} is empty, else returns
* {@link Optional#empty()}
*/
public Optional<Integer> getHttpStatus() {
return Optional.ofNullable(httpStatus);
}
/**
* @return the duration in milliseconds if {@link #getError()} is empty,
* else returns {@link Optional#empty()}
*/
public Optional<Integer> getDurationInMs() {
return Optional.ofNullable(durationInMs);
}
/**
* @return the date of sending
*/
public long getAt() {
return at;
}
/**
* @return the error raised if the request could not be executed due to a connectivity
* problem or timeout
*/
public Optional<Throwable> getError() {
return Optional.ofNullable(error);
}
/**
* @return the cause message of {@link #getError()}, Optional.empty() is error is not set.
*/
public Optional<String> getErrorMessage() {
return error != null ? Optional.ofNullable(getRootCause(error).getMessage()) : Optional.empty();
}
public boolean isSuccess() {
return httpStatus != null && httpStatus >= 200 && httpStatus < 300;
}
public static class Builder {
private Webhook webhook;
private WebhookPayload payload;
private String effectiveUrl;
private Integer httpStatus;
private Integer durationInMs;
private long at;
private Throwable error;
public Builder setWebhook(Webhook w) {
this.webhook = w;
return this;
}
public Builder setPayload(WebhookPayload payload) {
this.payload = payload;
return this;
}
public Builder setEffectiveUrl(@Nullable String effectiveUrl) {
this.effectiveUrl = effectiveUrl;
return this;
}
public Builder setHttpStatus(@Nullable Integer httpStatus) {
this.httpStatus = httpStatus;
return this;
}
public Builder setDurationInMs(@Nullable Integer durationInMs) {
this.durationInMs = durationInMs;
return this;
}
public Builder setAt(long at) {
this.at = at;
return this;
}
public Builder setError(@Nullable Throwable t) {
this.error = t;
return this;
}
public WebhookDelivery build() {
return new WebhookDelivery(this);
}
}
}
| 4,249 | 26.24359 | 100 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/WebhookDeliveryStorage.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.webhook;
import com.google.common.base.Throwables;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.webhook.WebhookDeliveryDao;
import org.sonar.db.webhook.WebhookDeliveryDto;
/**
* Persist and purge {@link WebhookDelivery} into database
*/
@ServerSide
@ComputeEngineSide
public class WebhookDeliveryStorage {
private static final long ALIVE_DELAY_MS = 30L * 24 * 60 * 60 * 1000;
private final DbClient dbClient;
private final System2 system;
private final UuidFactory uuidFactory;
public WebhookDeliveryStorage(DbClient dbClient, System2 system, UuidFactory uuidFactory) {
this.dbClient = dbClient;
this.system = system;
this.uuidFactory = uuidFactory;
}
public void persist(WebhookDelivery delivery) {
WebhookDeliveryDao dao = dbClient.webhookDeliveryDao();
try (DbSession dbSession = dbClient.openSession(false)) {
dao.insert(dbSession, toDto(delivery));
dbSession.commit();
}
}
public void purge(String projectUuid) {
long beforeDate = system.now() - ALIVE_DELAY_MS;
try (DbSession dbSession = dbClient.openSession(false)) {
dbClient.webhookDeliveryDao().deleteProjectBeforeDate(dbSession, projectUuid, beforeDate);
dbSession.commit();
}
}
private WebhookDeliveryDto toDto(WebhookDelivery delivery) {
WebhookDeliveryDto dto = new WebhookDeliveryDto();
dto.setUuid(uuidFactory.create());
dto.setWebhookUuid(delivery.getWebhook().getUuid());
dto.setProjectUuid(delivery.getWebhook().getProjectUuid());
delivery.getWebhook().getCeTaskUuid().ifPresent(dto::setCeTaskUuid);
delivery.getWebhook().getAnalysisUuid().ifPresent(dto::setAnalysisUuid);
dto.setName(delivery.getWebhook().getName());
dto.setUrl(delivery.getEffectiveUrl().orElse(delivery.getWebhook().getUrl()));
dto.setSuccess(delivery.isSuccess());
dto.setHttpStatus(delivery.getHttpStatus().orElse(null));
dto.setDurationMs(delivery.getDurationInMs().orElse(null));
dto.setErrorStacktrace(delivery.getError().map(Throwables::getStackTraceAsString).orElse(null));
dto.setPayload(delivery.getPayload().getJson());
dto.setCreatedAt(delivery.getAt());
return dto;
}
}
| 3,238 | 37.105882 | 100 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/WebhookModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.webhook;
import org.sonar.core.platform.Module;
public class WebhookModule extends Module {
@Override
protected void configureModule() {
add(
NetworkInterfaceProvider.class,
WebhookCustomDns.class,
WebhookCallerImpl.class,
WebhookDeliveryStorage.class,
WebHooksImpl.class,
WebhookPayloadFactoryImpl.class);
}
}
| 1,227 | 33.111111 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/WebhookPayload.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.webhook;
import javax.annotation.concurrent.Immutable;
import static java.util.Objects.requireNonNull;
@Immutable
public class WebhookPayload {
private final String projectKey;
private final String json;
public WebhookPayload(String projectKey, String json) {
this.projectKey = requireNonNull(projectKey);
this.json = requireNonNull(json);
}
public String getProjectKey() {
return projectKey;
}
public String getJson() {
return json;
}
}
| 1,345 | 28.911111 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/WebhookPayloadFactory.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;
@FunctionalInterface
public interface WebhookPayloadFactory {
WebhookPayload create(ProjectAnalysis analysis);
}
| 995 | 34.571429 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/WebhookPayloadFactoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.webhook;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.platform.Server;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.server.qualitygate.Condition;
import org.sonar.server.qualitygate.EvaluatedCondition;
import org.sonar.server.qualitygate.EvaluatedQualityGate;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.sonar.core.config.CorePropertyDefinitions.SONAR_ANALYSIS;
@ServerSide
@ComputeEngineSide
public class WebhookPayloadFactoryImpl implements WebhookPayloadFactory {
private static final String PROPERTY_STATUS = "status";
private final Server server;
private final System2 system2;
public WebhookPayloadFactoryImpl(Server server, System2 system2) {
this.server = server;
this.system2 = system2;
}
@Override
public WebhookPayload create(ProjectAnalysis analysis) {
Writer string = new StringWriter();
try (JsonWriter writer = JsonWriter.of(string)) {
writer.beginObject();
writeServer(writer);
writeTask(writer, analysis.getCeTask());
writeAnalysis(writer, analysis, system2);
writeProject(analysis, writer, analysis.getProject());
analysis.getBranch().ifPresent(b -> writeBranch(writer, analysis.getProject(), b));
analysis.getQualityGate().ifPresent(qualityGate -> writeQualityGate(writer, qualityGate));
writeAnalysisProperties(writer, analysis.getProperties());
writer.endObject().close();
return new WebhookPayload(analysis.getProject().getKey(), string.toString());
}
}
private void writeServer(JsonWriter writer) {
writer.prop("serverUrl", server.getPublicRootUrl());
}
private static void writeAnalysis(JsonWriter writer, ProjectAnalysis analysis, System2 system2) {
analysis.getAnalysis().ifPresent(a -> {
writer.propDateTime("analysedAt", new Date(a.getDate()));
a.getRevision().ifPresent(rev -> writer.prop("revision", rev));
});
writer.propDateTime("changedAt", new Date(analysis.getUpdatedAt().orElse(system2.now())));
}
private void writeProject(ProjectAnalysis analysis, JsonWriter writer, Project project) {
writer
.name("project")
.beginObject()
.prop("key", project.getKey())
.prop("name", analysis.getProject().getName())
.prop("url", projectUrlOf(project))
.endObject();
}
private static void writeAnalysisProperties(JsonWriter writer, Map<String, String> properties) {
writer
.name("properties")
.beginObject();
properties.entrySet()
.stream()
.filter(prop -> prop.getKey().startsWith(SONAR_ANALYSIS))
.forEach(prop -> writer.prop(prop.getKey(), prop.getValue()));
writer.endObject();
}
private static void writeTask(JsonWriter writer, Optional<CeTask> ceTask) {
ceTask.ifPresent(ceTask1 -> writer.prop("taskId", ceTask1.id()));
writer.prop(PROPERTY_STATUS, ceTask.map(CeTask::status).orElse(CeTask.Status.SUCCESS).toString());
}
private void writeBranch(JsonWriter writer, Project project, Branch branch) {
writer
.name("branch")
.beginObject()
.prop("name", branch.getName().orElse(null))
.prop("type", branch.getType().name())
.prop("isMain", branch.isMain())
.prop("url", branchUrlOf(project, branch))
.endObject();
}
private String projectUrlOf(Project project) {
return format("%s/dashboard?id=%s", server.getPublicRootUrl(), encode(project.getKey()));
}
private String branchUrlOf(Project project, Branch branch) {
Branch.Type branchType = branch.getType();
if (branchType == Branch.Type.BRANCH) {
if (branch.isMain()) {
return projectUrlOf(project);
}
return format("%s/dashboard?id=%s&branch=%s",
server.getPublicRootUrl(), encode(project.getKey()), encode(branch.getName().orElse("")));
}
if (branchType == Branch.Type.PULL_REQUEST) {
return format("%s/dashboard?id=%s&pullRequest=%s",
server.getPublicRootUrl(), encode(project.getKey()), encode(branch.getName().orElse("")));
}
return projectUrlOf(project);
}
private static void writeQualityGate(JsonWriter writer, EvaluatedQualityGate gate) {
writer
.name("qualityGate")
.beginObject()
.prop("name", gate.getQualityGate().getName())
.prop(PROPERTY_STATUS, gate.getStatus().toString())
.name("conditions")
.beginArray();
for (EvaluatedCondition evaluatedCondition : gate.getEvaluatedConditions()) {
Condition condition = evaluatedCondition.getCondition();
writer
.beginObject()
.prop("metric", condition.getMetricKey())
.prop("operator", condition.getOperator().name());
evaluatedCondition.getValue().ifPresent(t -> writer.prop("value", t));
writer
.prop(PROPERTY_STATUS, evaluatedCondition.getStatus().name())
.prop("errorThreshold", condition.getErrorThreshold())
.endObject();
}
writer
.endArray()
.endObject();
}
private static String encode(String toEncode) {
try {
return URLEncoder.encode(toEncode, UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Encoding not supported", e);
}
}
}
| 6,411 | 35.850575 | 102 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/webhook/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.webhook;
import javax.annotation.ParametersAreNonnullByDefault;
| 965 | 37.64 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/almsettings/MultipleAlmFeatureTest.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.almsettings;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarRuntime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(DataProviderRunner.class)
public class MultipleAlmFeatureTest {
private final SonarRuntime sonarRuntime = mock(SonarRuntime.class);
private final MultipleAlmFeature underTest = new MultipleAlmFeature(sonarRuntime);
@Test
public void getName_nameShouldBeCorrect() {
assertEquals("multiple-alm",underTest.getName());
}
@Test
@UseDataProvider("editionsAndMultipleAlmAvailability")
public void isEnabled_shouldOnlyBeEnabledInEnterpriseEditionPlus(SonarEdition edition, boolean shouldBeEnabled) {
when(sonarRuntime.getEdition()).thenReturn(edition);
boolean isAvailable = underTest.isAvailable();
assertThat(isAvailable).isEqualTo(shouldBeEnabled);
}
@DataProvider
public static Object[][] editionsAndMultipleAlmAvailability() {
return new Object[][] {
{SonarEdition.COMMUNITY, false},
{SonarEdition.DEVELOPER, false},
{SonarEdition.ENTERPRISE, true},
{SonarEdition.DATACENTER, true}
};
}
}
| 2,346 | 34.560606 | 115 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/async/AsyncExecutionExecutorServiceImplTest.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.async;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class AsyncExecutionExecutorServiceImplTest {
private AsyncExecutionExecutorServiceImpl underTest = new AsyncExecutionExecutorServiceImpl();
@Test
public void submit_executes_runnable_in_another_thread() {
try (SlowRunnable slowRunnable = new SlowRunnable()) {
underTest.submit(slowRunnable);
assertThat(slowRunnable.executed).isFalse();
}
}
private static final class SlowRunnable implements Runnable, AutoCloseable {
private final CountDownLatch latch = new CountDownLatch(1);
private volatile boolean executed = false;
@Override
public void run() {
try {
latch.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// ignore
}
executed = true;
}
@Override
public void close() {
latch.countDown();
}
}
}
| 1,878 | 30.847458 | 96 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/async/AsyncExecutionImplTest.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.async;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class AsyncExecutionImplTest {
@Rule
public LogTester logTester = new LogTester();
private AsyncExecutionExecutorService synchronousExecutorService = Runnable::run;
private AsyncExecutionImpl underTest = new AsyncExecutionImpl(synchronousExecutorService);
@Test
public void addToQueue_fails_with_NPE_if_Runnable_is_null() {
assertThatThrownBy(() -> underTest.addToQueue(null))
.isInstanceOf(NullPointerException.class);
}
@Test
public void addToQueue_submits_runnable_to_executorService_which_does_not_fail_if_Runnable_argument_throws_exception() {
underTest.addToQueue(() -> {
throw new RuntimeException("Faking an exception thrown by Runnable argument");
});
assertThat(logTester.logs()).hasSize(1);
assertThat(logTester.logs(Level.ERROR)).containsOnly("Asynchronous task failed");
}
@Test
public void addToQueue_submits_runnable_that_fails_if_Runnable_argument_throws_Error() {
Error expected = new Error("Faking an exception thrown by Runnable argument");
Runnable runnable = () -> {
throw expected;
};
assertThatThrownBy(() -> underTest.addToQueue(runnable))
.isInstanceOf(Error.class)
.hasMessage(expected.getMessage());
}
}
| 2,363 | 35.369231 | 122 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/async/AsyncExecutionMBeanImplTest.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.async;
import java.lang.management.ManagementFactory;
import javax.annotation.CheckForNull;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import org.junit.Test;
import org.mockito.Mockito;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class AsyncExecutionMBeanImplTest {
private AsyncExecutionMonitoring asyncExecutionMonitoring = Mockito.mock(AsyncExecutionMonitoring.class);
private AsyncExecutionMBeanImpl underTest = new AsyncExecutionMBeanImpl(asyncExecutionMonitoring);
@Test
public void register_and_unregister() throws Exception {
assertThat(getMBean()).isNull();
underTest.start();
assertThat(getMBean()).isNotNull();
underTest.stop();
assertThat(getMBean()).isNull();
}
@Test
public void getQueueSize_delegates_to_AsyncExecutionMonitoring() {
when(asyncExecutionMonitoring.getQueueSize()).thenReturn(12);
assertThat(underTest.getQueueSize()).isEqualTo(12);
verify(asyncExecutionMonitoring).getQueueSize();
}
@Test
public void getWorkerCount_delegates_to_AsyncExecutionMonitoring() {
when(asyncExecutionMonitoring.getWorkerCount()).thenReturn(12);
assertThat(underTest.getWorkerCount()).isEqualTo(12);
verify(asyncExecutionMonitoring).getWorkerCount();
}
@Test
public void getLargestWorkerCount_delegates_to_AsyncExecutionMonitoring() {
when(asyncExecutionMonitoring.getLargestWorkerCount()).thenReturn(12);
assertThat(underTest.getLargestWorkerCount()).isEqualTo(12);
verify(asyncExecutionMonitoring).getLargestWorkerCount();
}
@CheckForNull
private ObjectInstance getMBean() throws Exception {
try {
return ManagementFactory.getPlatformMBeanServer().getObjectInstance(new ObjectName(AsyncExecutionMBean.OBJECT_NAME));
} catch (InstanceNotFoundException e) {
return null;
}
}
}
| 2,871 | 31.636364 | 123 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/component/index/SuggestionQueryTest.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.component.index;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class SuggestionQueryTest {
@Test
public void should_fail_with_IAE_if_query_is_empty() {
assertThatThrownBy(() -> SuggestionQuery.builder().setQuery(""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Query must be at least two characters long");
}
@Test
public void should_fail_with_IAE_if_query_is_one_character_long() {
assertThatThrownBy(() -> SuggestionQuery.builder().setQuery("a"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Query must be at least two characters long");
}
@Test
public void should_support_query_with_two_characters_long() {
SuggestionQuery query = SuggestionQuery.builder().setQuery("ab").build();
assertThat(query.getQuery()).isEqualTo("ab");
}
@Test
public void should_fail_with_IAE_if_limit_is_negative() {
SuggestionQuery.Builder query = SuggestionQuery.builder().setQuery("ab");
assertThatThrownBy(() -> query.setLimit(-1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Limit has to be strictly positive");
}
@Test
public void should_fail_with_IAE_if_limit_is_zero() {
SuggestionQuery.Builder query = SuggestionQuery.builder().setQuery("ab");
assertThatThrownBy(() -> query.setLimit(0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Limit has to be strictly positive");
}
@Test
public void should_support_positive_limit() {
SuggestionQuery query = SuggestionQuery.builder().setQuery("ab")
.setLimit(1).build();
assertThat(query.getLimit()).isOne();
}
}
| 2,660 | 33.558442 | 77 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/config/ConfigurationProviderTest.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.config;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.config.PropertyDefinition.builder;
@RunWith(DataProviderRunner.class)
public class ConfigurationProviderTest {
private static final String[] EMPTY_STRING_ARRAY = {};
private final String nonDeclaredKey = RandomStringUtils.randomAlphabetic(3);
private final String nonMultivalueKey = RandomStringUtils.randomAlphabetic(3);
private final String multivalueKey = RandomStringUtils.randomAlphabetic(3);
private final MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE,
builder(nonMultivalueKey).multiValues(false).build(),
builder(multivalueKey).multiValues(true).build()));
private ConfigurationProvider underTest = new ConfigurationProvider();
@Test
@UseDataProvider("trimFieldsAndEncodedCommas")
public void getStringArray_split_on_comma_trim_and_support_encoded_comma_as_Settings_getStringArray(String idemUseCase) {
settings.setProperty(nonDeclaredKey, idemUseCase);
settings.setProperty(nonMultivalueKey, idemUseCase);
settings.setProperty(multivalueKey, idemUseCase);
Configuration configuration = underTest.provide(settings);
getStringArrayBehaviorIsTheSame(configuration, nonDeclaredKey);
getStringArrayBehaviorIsTheSame(configuration, nonMultivalueKey);
getStringArrayBehaviorIsTheSame(configuration, multivalueKey);
}
@DataProvider
public static Object[][] trimFieldsAndEncodedCommas() {
return new Object[][] {
{"a"},
{" a"},
{"a "},
{" a "},
{"a,b"},
{" a,b"},
{" a ,b"},
{" a , b"},
{"a ,b"},
{" a, b"},
{"a,b "},
{" a , b "},
{"a%2Cb"},
{"a%2Cb,c"}
};
}
@Test
@UseDataProvider("emptyStrings")
public void getStringArray_parses_empty_string_the_same_Settings_if_unknown_or_non_multivalue_property(String emptyValue) {
settings.setProperty(nonDeclaredKey, emptyValue);
settings.setProperty(nonMultivalueKey, emptyValue);
Configuration configuration = underTest.provide(settings);
getStringArrayBehaviorIsTheSame(configuration, nonDeclaredKey);
getStringArrayBehaviorIsTheSame(configuration, nonMultivalueKey);
}
@Test
@UseDataProvider("emptyStrings")
public void getStringArray_parses_empty_string_differently_from_Settings_ifmultivalue_property(String emptyValue) {
settings.setProperty(multivalueKey, emptyValue);
Configuration configuration = underTest.provide(settings);
getStringArrayBehaviorDiffers(configuration, multivalueKey, EMPTY_STRING_ARRAY);
}
@DataProvider
public static Object[][] emptyStrings() {
return new Object[][] {
{""},
{" "},
{" "},
};
}
@Test
@UseDataProvider("subsequentCommas1")
public void getStringArray_on_unknown_or_non_multivalue_properties_ignores_subsequent_commas_as_Settings(String subsequentCommas) {
settings.setProperty(nonDeclaredKey, subsequentCommas);
settings.setProperty(nonMultivalueKey, subsequentCommas);
Configuration configuration = underTest.provide(settings);
getStringArrayBehaviorIsTheSame(configuration, nonDeclaredKey);
getStringArrayBehaviorIsTheSame(configuration, nonMultivalueKey);
}
@DataProvider
public static Object[][] subsequentCommas1() {
return new Object[][] {
{",,a"},
{",,,a"},
{"a,,b"},
{"a,,,b,c,,d"}
};
}
@Test
@UseDataProvider("subsequentCommas2")
public void getStringArray_on_unknown_or_non_multivalue_properties_ignores_subsequent_commas_differently_from_Settings(String subsequentCommas, String[] expected) {
settings.setProperty(nonDeclaredKey, subsequentCommas);
settings.setProperty(nonMultivalueKey, subsequentCommas);
Configuration configuration = underTest.provide(settings);
getStringArrayBehaviorDiffers(configuration, nonDeclaredKey, expected);
getStringArrayBehaviorDiffers(configuration, nonMultivalueKey, expected);
}
@DataProvider
public static Object[][] subsequentCommas2() {
return new Object[][] {
{",,", EMPTY_STRING_ARRAY},
{",,,", EMPTY_STRING_ARRAY},
{"a,,", arrayOf("a")},
{"a,,,", arrayOf("a")}
};
}
@Test
@UseDataProvider("subsequentCommas3")
public void getStringArray_on_multivalue_properties_ignores_subsequent_commas_differently_from_Settings(String subsequentCommas, String[] expected) {
settings.setProperty(multivalueKey, subsequentCommas);
Configuration configuration = underTest.provide(settings);
getStringArrayBehaviorDiffers(configuration, multivalueKey, expected);
}
@DataProvider
public static Object[][] subsequentCommas3() {
return new Object[][] {
{",,", EMPTY_STRING_ARRAY},
{",,,", EMPTY_STRING_ARRAY},
{"a,,", arrayOf("a")},
{"a,,,", arrayOf("a")},
{",,a", arrayOf("a")},
{",,,a", arrayOf("a")},
{"a,,b", arrayOf("a", "b")},
{"a,,,b", arrayOf("a", "b")},
{"a,,,b,,", arrayOf("a", "b")},
{",,a,,b", arrayOf("a", "b")},
};
}
@Test
@UseDataProvider("emptyFields1")
public void getStringArray_on_unknown_or_non_multivalue_properties_ignores_empty_fields_same_as_settings(String emptyFields, String[] expected) {
settings.setProperty(nonDeclaredKey, emptyFields);
settings.setProperty(nonMultivalueKey, emptyFields);
Configuration configuration = underTest.provide(settings);
getStringArrayBehaviorIsTheSame(configuration, nonDeclaredKey, expected);
getStringArrayBehaviorIsTheSame(configuration, nonMultivalueKey, expected);
}
@DataProvider
public static Object[][] emptyFields1() {
return new Object[][] {
// these are inconsistent behaviors of StringUtils.splitByWholeSeparator used under the hood by Settings
{" , a", arrayOf("a")},
{" ,a,b", arrayOf("a", "b")},
{" ,,a,b", arrayOf("a", "b")}
};
}
@Test
@UseDataProvider("emptyFields2")
public void getStringArray_on_unknown_or_non_multivalue_properties_ignores_empty_fields_differently_from_settings(String emptyFields, String[] expected) {
settings.setProperty(nonDeclaredKey, emptyFields);
settings.setProperty(nonMultivalueKey, emptyFields);
Configuration configuration = underTest.provide(settings);
getStringArrayBehaviorDiffers(configuration, nonDeclaredKey, expected);
getStringArrayBehaviorDiffers(configuration, nonMultivalueKey, expected);
}
@DataProvider
public static Object[][] emptyFields2() {
return new Object[][] {
{", ", EMPTY_STRING_ARRAY},
{" ,", EMPTY_STRING_ARRAY},
{" , ", EMPTY_STRING_ARRAY},
{" , \n ,, \t", EMPTY_STRING_ARRAY},
{" , \t , , ", EMPTY_STRING_ARRAY},
{"a, ", arrayOf("a")},
{" a, ,", arrayOf("a")},
{" , a, ,", arrayOf("a")},
{"a,b, ", arrayOf("a", "b")},
{"a, ,b", arrayOf("a", "b")},
{" ,a, ,b", arrayOf("a", "b")},
{" ,,a, ,b", arrayOf("a", "b")},
{" ,a, ,,b", arrayOf("a", "b")},
{" ,,a, ,,b", arrayOf("a", "b")},
{"a, ,b, ", arrayOf("a", "b")},
{"\t ,a, ,b, ", arrayOf("a", "b")},
};
}
@Test
@UseDataProvider("emptyFields3")
public void getStringArray_on_multivalue_properties_ignores_empty_fields_differently_from_settings(String emptyFields, String[] expected) {
settings.setProperty(multivalueKey, emptyFields);
Configuration configuration = underTest.provide(settings);
getStringArrayBehaviorDiffers(configuration, multivalueKey, expected);
}
@DataProvider
public static Object[][] emptyFields3() {
return new Object[][] {
{", ", EMPTY_STRING_ARRAY},
{" ,", EMPTY_STRING_ARRAY},
{" , ", EMPTY_STRING_ARRAY},
{" , \n ,, \t", EMPTY_STRING_ARRAY},
{" , \t , , ", EMPTY_STRING_ARRAY},
{"a, ", arrayOf("a")},
{" a, ,", arrayOf("a")},
{" , a, ,", arrayOf("a")},
{"a,b, ", arrayOf("a", "b")},
{" ,a,b", arrayOf("a", "b")},
{" ,,a,b", arrayOf("a", "b")},
{"a, ,b", arrayOf("a", "b")},
{" ,a, ,b", arrayOf("a", "b")},
{" ,,a, ,b", arrayOf("a", "b")},
{" ,a, ,,b", arrayOf("a", "b")},
{" ,,a, ,,b", arrayOf("a", "b")},
{"a, ,b, ", arrayOf("a", "b")},
{"\t ,a, ,b, ", arrayOf("a", "b")},
};
}
@Test
@UseDataProvider("quotedStrings1")
public void getStringArray_supports_quoted_strings_when_settings_does_not(String str,
String[] configurationExpected, String[] settingsExpected) {
settings.setProperty(nonDeclaredKey, str);
settings.setProperty(nonMultivalueKey, str);
settings.setProperty(multivalueKey, str);
Configuration configuration = underTest.provide(settings);
getStringArrayBehaviorDiffers(configuration, nonDeclaredKey, configurationExpected, settingsExpected);
getStringArrayBehaviorDiffers(configuration, nonMultivalueKey, configurationExpected, settingsExpected);
getStringArrayBehaviorDiffers(configuration, multivalueKey, configurationExpected, settingsExpected);
}
@DataProvider
public static Object[][] quotedStrings1() {
return new Object[][] {
{"\"\"", arrayOf(""), arrayOf("\"\"")},
{" \"\"", arrayOf(""), arrayOf("\"\"")},
{"\"\" ", arrayOf(""), arrayOf("\"\"")},
{" \"\" ", arrayOf(""), arrayOf("\"\"")},
{"\" \"", arrayOf(" "), arrayOf("\" \"")},
{" \" \" ", arrayOf(" "), arrayOf("\" \"")},
{"\"a \"", arrayOf("a "), arrayOf("\"a \"")},
{"\" a\"", arrayOf(" a"), arrayOf("\" a\"")},
{"\",\"", arrayOf(","), arrayOf("\"", "\"")},
// escaped quote in quoted field
{"\"\"\"\"", arrayOf("\""), arrayOf("\"\"\"\"")},
{"\"a\"\"\"", arrayOf("a\""), arrayOf("\"a\"\"\"")},
{"\"\"\"b\"", arrayOf("\"b"), arrayOf("\"\"\"b\"")},
{"\"a\"\"b\"", arrayOf("a\"b"), arrayOf("\"a\"\"b\"")},
{"\",\",\"a\"", arrayOf(",", "a"), arrayOf("\"", "\"", "\"a\"")},
};
}
private void getStringArrayBehaviorIsTheSame(Configuration configuration, String key) {
assertThat(configuration.getStringArray(key))
.isEqualTo(settings.getStringArray(key));
}
private void getStringArrayBehaviorIsTheSame(Configuration configuration, String key, String[] expected) {
assertThat(configuration.getStringArray(key))
.isEqualTo(expected)
.isEqualTo(settings.getStringArray(key));
}
private void getStringArrayBehaviorDiffers(Configuration configuration, String key, String[] expected) {
assertThat(configuration.getStringArray(key))
.isEqualTo(expected)
.isNotEqualTo(settings.getStringArray(key));
}
private void getStringArrayBehaviorDiffers(Configuration configuration, String key, String[] configurationExpected, String[] settingsExpected) {
String[] conf = configuration.getStringArray(key);
String[] sett = settings.getStringArray(key);
assertThat(conf).isEqualTo(configurationExpected);
assertThat(sett).isEqualTo(settingsExpected);
assertThat(conf).isNotEqualTo(sett);
}
private static String[] arrayOf(String... strs) {
return strs;
}
}
| 12,399 | 35.686391 | 166 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/email/EmailSenderTest.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.email;
import java.net.MalformedURLException;
import java.util.Set;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.junit.Test;
import org.sonar.api.config.EmailSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class EmailSenderTest {
private EmailSettings emailSettings = mock(EmailSettings.class);
private EmailSender<BasicEmail> sender = new EmailSender<>(emailSettings) {
@Override protected void addReportContent(HtmlEmail email, BasicEmail report) throws EmailException, MalformedURLException {
email.setSubject("Email Subject");
}
};
@Test
public void test_email_fields() throws Exception {
BasicEmail basicEmail = new BasicEmail(Set.of("noreply@nowhere"));
when(emailSettings.getSmtpHost()).thenReturn("smtphost");
when(emailSettings.getSmtpPort()).thenReturn(25);
when(emailSettings.getFrom()).thenReturn("noreply@nowhere");
when(emailSettings.getFromName()).thenReturn("My SonarQube");
when(emailSettings.getPrefix()).thenReturn("[SONAR]");
when(emailSettings.getSmtpUsername()).thenReturn("");
when(emailSettings.getSmtpPassword()).thenReturn("");
MultiPartEmail email = sender.createEmail(basicEmail);
assertThat(email.getHostName()).isEqualTo("smtphost");
assertThat(email.getSmtpPort()).isEqualTo("25");
assertThat(email.getSubject()).isEqualTo("Email Subject");
assertThat(email.getFromAddress()).hasToString("My SonarQube <noreply@nowhere>");
assertThat(email.getToAddresses()).isEmpty();
assertThat(email.getCcAddresses()).isEmpty();
assertThat(email.isSSLOnConnect()).isFalse();
assertThat(email.isStartTLSEnabled()).isFalse();
assertThat(email.isStartTLSRequired()).isFalse();
}
@Test
public void support_empty_body() throws Exception {
BasicEmail basicEmail = new BasicEmail(Set.of("noreply@nowhere"));
when(emailSettings.getSmtpHost()).thenReturn("smtphost");
when(emailSettings.getSmtpPort()).thenReturn(465);
when(emailSettings.getFrom()).thenReturn("noreply@nowhere");
MultiPartEmail email = sender.createEmail(basicEmail);
assertThat(email.getSubject()).isEqualTo("Email Subject");
}
@Test
public void support_ssl() throws Exception {
BasicEmail basicEmail = new BasicEmail(Set.of("noreply@nowhere"));
when(emailSettings.getSecureConnection()).thenReturn("SSL");
when(emailSettings.getSmtpHost()).thenReturn("smtphost");
when(emailSettings.getSmtpPort()).thenReturn(466);
when(emailSettings.getFrom()).thenReturn("noreply@nowhere");
when(emailSettings.getSmtpUsername()).thenReturn("login");
when(emailSettings.getSmtpPassword()).thenReturn("pwd");
MultiPartEmail email = sender.createEmail(basicEmail);
assertThat(email.isSSLOnConnect()).isTrue();
assertThat(email.isStartTLSEnabled()).isFalse();
assertThat(email.isStartTLSRequired()).isFalse();
assertThat(email.getHostName()).isEqualTo("smtphost");
assertThat(email.getSmtpPort()).isEqualTo("466");
assertThat(email.getSslSmtpPort()).isEqualTo("466");
}
@Test
public void support_starttls() throws Exception {
BasicEmail basicEmail = new BasicEmail(Set.of("noreply@nowhere"));
when(emailSettings.getSecureConnection()).thenReturn("STARTTLS");
when(emailSettings.getSmtpHost()).thenReturn("smtphost");
when(emailSettings.getSmtpPort()).thenReturn(587);
when(emailSettings.getFrom()).thenReturn("noreply@nowhere");
when(emailSettings.getSmtpUsername()).thenReturn("login");
when(emailSettings.getSmtpPassword()).thenReturn("pwd");
MultiPartEmail email = sender.createEmail(basicEmail);
assertThat(email.isSSLOnConnect()).isFalse();
assertThat(email.isStartTLSEnabled()).isTrue();
assertThat(email.isStartTLSRequired()).isTrue();
assertThat(email.getHostName()).isEqualTo("smtphost");
assertThat(email.getSmtpPort()).isEqualTo("587");
}
@Test
public void send_email() throws Exception {
HtmlEmail email = mock(HtmlEmail.class);
BasicEmail basicEmail = new BasicEmail(Set.of("noreply@nowhere"));
EmailSender<BasicEmail> senderSpy = spy(sender);
doReturn(email).when(senderSpy).createEmail(basicEmail);
senderSpy.send(basicEmail);
verify(email).send();
}
}
| 5,427 | 39.207407 | 128 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/BulkIndexerConcurrentRequestCalculationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import org.assertj.core.api.AbstractIntegerAssert;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BulkIndexerConcurrentRequestCalculationTest {
@Test
public void should_not_parallelize_if_regular_size() {
assertConcurrentRequests(BulkIndexer.Size.REGULAR, cores(4))
.isZero();
}
@Test
public void should_not_parallelize_if_large_indexing_but_few_cores() {
assertConcurrentRequests(BulkIndexer.Size.LARGE, cores(4))
.isZero();
}
/**
* see https://jira.sonarsource.com/browse/SONAR-8075
*/
@Test
public void should_heavily_parallelize_on_96_cores_if_large_indexing() {
assertConcurrentRequests(BulkIndexer.Size.LARGE, cores(96))
.isEqualTo(18);
}
private AbstractIntegerAssert<?> assertConcurrentRequests(BulkIndexer.Size size, BulkIndexer.Runtime2 runtime2) {
return assertThat(size.createHandler(runtime2).getConcurrentRequests());
}
private static BulkIndexer.Runtime2 cores(int cores) {
BulkIndexer.Runtime2 runtime = mock(BulkIndexer.Runtime2.class);
when(runtime.getCores()).thenReturn(cores);
return runtime;
}
}
| 2,105 | 32.967742 | 115 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/DefaultIndexSettingsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import org.elasticsearch.common.settings.Settings;
import org.junit.Test;
import org.sonar.server.es.newindex.DefaultIndexSettings;
import org.sonar.test.TestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SORTABLE_ANALYZER;
public class DefaultIndexSettingsTest {
@Test
public void defaults() {
Settings settings = DefaultIndexSettings.defaults().build();
// test some values
assertThat(settings.get("index.number_of_shards")).isEqualTo("1");
assertThat(settings.get("index.analysis.analyzer." + SORTABLE_ANALYZER.getName() + ".tokenizer")).isEqualTo("keyword");
}
@Test
public void only_statics() {
TestUtils.hasOnlyPrivateConstructors(DefaultIndexSettings.class);
}
}
| 1,670 | 34.553191 | 123 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/DocIdTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import org.junit.Test;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
public class DocIdTest {
@Test
public void equals_is_based_on_index_type_and_id() {
String index = randomAlphabetic(5);
String type = randomAlphabetic(6);
String id = randomAlphabetic(7);
DocId underTest = new DocId(index, type, id);
assertThat(underTest)
.isEqualTo(new DocId(index, type, id))
.isNotEqualTo(new DocId(randomAlphabetic(7), type, id))
.isNotEqualTo(new DocId(index, type, randomAlphabetic(7)))
.isNotEqualTo(new DocId(index, randomAlphabetic(7), id))
.isNotEqualTo(new DocId(randomAlphabetic(7), randomAlphabetic(8), id))
.isNotEqualTo(new DocId(randomAlphabetic(7), type, randomAlphabetic(8)))
.isNotEqualTo(new DocId(index, randomAlphabetic(7), randomAlphabetic(8)))
.isNotEqualTo(new DocId(randomAlphabetic(7), randomAlphabetic(8), randomAlphabetic(9)));
}
@Test
public void hashcode_is_based_on_index_type_and_id() {
String index = randomAlphabetic(5);
String type = randomAlphabetic(6);
String id = randomAlphabetic(7);
DocId underTest = new DocId(index, type, id);
assertThat(underTest.hashCode())
.isEqualTo(new DocId(index, type, id).hashCode())
.isNotEqualTo(new DocId(randomAlphabetic(7), type, id).hashCode())
.isNotEqualTo(new DocId(index, type, randomAlphabetic(7)).hashCode())
.isNotEqualTo(new DocId(index, randomAlphabetic(7), id).hashCode())
.isNotEqualTo(new DocId(randomAlphabetic(7), randomAlphabetic(8), id).hashCode())
.isNotEqualTo(new DocId(randomAlphabetic(7), type, randomAlphabetic(8)).hashCode())
.isNotEqualTo(new DocId(index, randomAlphabetic(7), randomAlphabetic(8)).hashCode())
.isNotEqualTo(new DocId(randomAlphabetic(7), randomAlphabetic(8), randomAlphabetic(9)).hashCode());
}
}
| 2,811 | 42.9375 | 105 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/EsClientProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import org.assertj.core.api.Condition;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.testfixtures.log.LogTester;
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.process.ProcessProperties.Property.CLUSTER_ENABLED;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HTTP_KEYSTORE;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_NAME;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_TYPE;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_SEARCH_HOSTS;
import static org.sonar.process.ProcessProperties.Property.ES_PORT;
import static org.sonar.process.ProcessProperties.Property.SEARCH_HOST;
import static org.sonar.process.ProcessProperties.Property.SEARCH_PORT;
public class EsClientProviderTest {
@Rule
public LogTester logTester = new LogTester();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private MapSettings settings = new MapSettings();
private EsClientProvider underTest = new EsClientProvider();
private String localhostHostname;
@Before
public void setUp() throws Exception {
// mandatory property
settings.setProperty(CLUSTER_NAME.getKey(), "the_cluster_name");
localhostHostname = InetAddress.getLocalHost().getHostName();
}
@Test
public void connection_to_local_es_when_cluster_mode_is_disabled() {
settings.setProperty(CLUSTER_ENABLED.getKey(), false);
settings.setProperty(SEARCH_HOST.getKey(), localhostHostname);
settings.setProperty(SEARCH_PORT.getKey(), 9000);
settings.setProperty(ES_PORT.getKey(), 8080);
EsClient client = underTest.provide(settings.asConfig());
RestHighLevelClient nativeClient = client.nativeClient();
assertThat(nativeClient.getLowLevelClient().getNodes()).hasSize(1);
Node node = nativeClient.getLowLevelClient().getNodes().get(0);
assertThat(node.getHost().getAddress().getHostName()).isEqualTo(localhostHostname);
assertThat(node.getHost().getPort()).isEqualTo(9000);
assertThat(logTester.logs(Level.INFO)).has(new Condition<>(s -> s.contains("Connected to local Elasticsearch: [http://" + localhostHostname + ":9000]"), ""));
}
@Test
public void connection_to_remote_es_nodes_when_cluster_mode_is_enabled_and_local_es_is_disabled() {
settings.setProperty(CLUSTER_ENABLED.getKey(), true);
settings.setProperty(CLUSTER_NODE_TYPE.getKey(), "application");
settings.setProperty(CLUSTER_SEARCH_HOSTS.getKey(), format("%s:8080,%s:8081", localhostHostname, localhostHostname));
EsClient client = underTest.provide(settings.asConfig());
RestHighLevelClient nativeClient = client.nativeClient();
assertThat(nativeClient.getLowLevelClient().getNodes()).hasSize(2);
Node node = nativeClient.getLowLevelClient().getNodes().get(0);
assertThat(node.getHost().getAddress().getHostName()).isEqualTo(localhostHostname);
assertThat(node.getHost().getPort()).isEqualTo(8080);
node = nativeClient.getLowLevelClient().getNodes().get(1);
assertThat(node.getHost().getAddress().getHostName()).isEqualTo(localhostHostname);
assertThat(node.getHost().getPort()).isEqualTo(8081);
assertThat(logTester.logs(Level.INFO))
.has(new Condition<>(s -> s.contains("Connected to remote Elasticsearch: [http://" + localhostHostname + ":8080, http://" + localhostHostname + ":8081]"), ""));
}
@Test
public void es_client_provider_must_throw_IAE_when_incorrect_port_is_used_when_search_disabled() {
settings.setProperty(CLUSTER_ENABLED.getKey(), true);
settings.setProperty(CLUSTER_NODE_TYPE.getKey(), "application");
settings.setProperty(CLUSTER_SEARCH_HOSTS.getKey(), format("%s:100000,%s:8081", localhostHostname, localhostHostname));
assertThatThrownBy(() -> underTest.provide(settings.asConfig()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(format("Port number out of range: %s:100000", localhostHostname));
}
@Test
public void es_client_provider_must_throw_IAE_when_incorrect_port_is_used() {
settings.setProperty(CLUSTER_ENABLED.getKey(), true);
settings.setProperty(CLUSTER_NODE_TYPE.getKey(), "search");
settings.setProperty(SEARCH_HOST.getKey(), "localhost");
settings.setProperty(SEARCH_PORT.getKey(), "100000");
assertThatThrownBy(() -> underTest.provide(settings.asConfig()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Port out of range: 100000");
}
@Test
public void es_client_provider_must_add_default_port_when_not_specified() {
settings.setProperty(CLUSTER_ENABLED.getKey(), true);
settings.setProperty(CLUSTER_NODE_TYPE.getKey(), "application");
settings.setProperty(CLUSTER_SEARCH_HOSTS.getKey(), format("%s,%s:8081", localhostHostname, localhostHostname));
EsClient client = underTest.provide(settings.asConfig());
RestHighLevelClient nativeClient = client.nativeClient();
assertThat(nativeClient.getLowLevelClient().getNodes()).hasSize(2);
Node node = nativeClient.getLowLevelClient().getNodes().get(0);
assertThat(node.getHost().getAddress().getHostName()).isEqualTo(localhostHostname);
assertThat(node.getHost().getPort()).isEqualTo(9001);
node = nativeClient.getLowLevelClient().getNodes().get(1);
assertThat(node.getHost().getAddress().getHostName()).isEqualTo(localhostHostname);
assertThat(node.getHost().getPort()).isEqualTo(8081);
assertThat(logTester.logs(Level.INFO))
.has(new Condition<>(s -> s.contains("Connected to remote Elasticsearch: [http://" + localhostHostname + ":9001, http://" + localhostHostname + ":8081]"), ""));
}
@Test
public void provide_whenHttpEncryptionEnabled_shouldUseHttps() throws GeneralSecurityException, IOException {
settings.setProperty(CLUSTER_ENABLED.getKey(), true);
Path keyStorePath = temp.newFile("keystore.p12").toPath();
EsClientTest.createCertificate("localhost", keyStorePath, "password");
settings.setProperty(CLUSTER_ES_HTTP_KEYSTORE.getKey(), keyStorePath.toString());
settings.setProperty(CLUSTER_NODE_TYPE.getKey(), "application");
settings.setProperty(CLUSTER_SEARCH_HOSTS.getKey(), format("%s,%s:8081", localhostHostname, localhostHostname));
EsClient client = underTest.provide(settings.asConfig());
RestHighLevelClient nativeClient = client.nativeClient();
Node node = nativeClient.getLowLevelClient().getNodes().get(0);
assertThat(node.getHost().getSchemeName()).isEqualTo("https");
assertThat(logTester.logs(Level.INFO))
.has(new Condition<>(s -> s.contains("Connected to remote Elasticsearch: [https://" + localhostHostname + ":9001, https://" + localhostHostname + ":8081]"), ""));
}
}
| 8,068 | 46.464706 | 168 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/EsClientTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.Objects;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.tls.HandshakeCertificates;
import okhttp3.tls.HeldCertificate;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.ArgumentMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class EsClientTest {
private static final String EXAMPLE_CLUSTER_STATS_JSON = "{" +
" \"status\": \"yellow\"," +
" \"nodes\": {" +
" \"count\": {" +
" \"total\": 3" +
" }" +
" }" +
"}";
private static final String EXAMPLE_INDICES_STATS_JSON = "{" +
" \"indices\": {" +
" \"index-1\": {" +
" \"primaries\": {" +
" \"docs\": {" +
" \"count\": 1234" +
" }," +
" \"store\": {" +
" \"size_in_bytes\": 56789" +
" }" +
" }," +
" \"shards\": {" +
" \"shard-1\": {}," +
" \"shard-2\": {}" +
" }" +
" }," +
" \"index-2\": {" +
" \"primaries\": {" +
" \"docs\": {" +
" \"count\": 42" +
" }," +
" \"store\": {" +
" \"size_in_bytes\": 123" +
" }" +
" }," +
" \"shards\": {" +
" \"shard-1\": {}," +
" \"shard-2\": {}" +
" }" +
" }" +
" }" +
"}";
private final static String EXAMPLE_NODE_STATS_JSON = "{" +
" \"nodes\": {" +
" \"YnKPZcbGRamRQGxjErLWoQ\": {" +
" \"name\": \"sonarqube\"," +
" \"host\": \"127.0.0.1\"," +
" \"indices\": {" +
" \"docs\": {" +
" \"count\": 13557" +
" }," +
" \"store\": {" +
" \"size_in_bytes\": 8670970" +
" }," +
" \"query_cache\": {" +
" \"memory_size_in_bytes\": 0" +
" }," +
" \"fielddata\": {" +
" \"memory_size_in_bytes\": 4880" +
" }," +
" \"translog\": {" +
" \"size_in_bytes\": 8274137" +
" }," +
" \"request_cache\": {" +
" \"memory_size_in_bytes\": 0" +
" }" +
" }," +
" \"process\": {" +
" \"open_file_descriptors\": 296," +
" \"max_file_descriptors\": 10240," +
" \"cpu\": {" +
" \"percent\": 7" +
" }" +
" }," +
" \"jvm\": {" +
" \"mem\": {" +
" \"heap_used_in_bytes\": 158487160," +
" \"heap_used_percent\": 30," +
" \"heap_max_in_bytes\": 518979584," +
" \"non_heap_used_in_bytes\": 109066592" +
" }," +
" \"threads\": {" +
" \"count\": 70" +
" }" +
" }," +
" \"fs\": {" +
" \"total\": {" +
" \"total_in_bytes\": 250685575168," +
" \"free_in_bytes\": 142843138048," +
" \"available_in_bytes\": 136144027648" +
" }" +
" }," +
" \"breakers\": {" +
" \"request\": {" +
" \"limit_size_in_bytes\": 311387750," +
" \"estimated_size_in_bytes\": 0" +
" }," +
" \"fielddata\": {" +
" \"limit_size_in_bytes\": 207591833," +
" \"estimated_size_in_bytes\": 4880" +
" }" +
" }" +
" }" +
" }" +
"}";
@Rule
public MockWebServer mockWebServer = new MockWebServer();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
RestClient restClient = mock(RestClient.class);
RestHighLevelClient client = new EsClient.MinimalRestHighLevelClient(restClient);
EsClient underTest = new EsClient(client);
@Test
public void should_close_client() throws IOException {
underTest.close();
verify(restClient).close();
}
@Test
public void should_rethrow_ex_when_close_client_throws() throws IOException {
doThrow(IOException.class).when(restClient).close();
assertThatThrownBy(() -> underTest.close())
.isInstanceOf(ElasticsearchException.class);
}
@Test
public void should_call_node_stats_api() throws Exception {
HttpEntity entity = mock(HttpEntity.class);
when(entity.getContent()).thenReturn(new ByteArrayInputStream(EXAMPLE_NODE_STATS_JSON.getBytes()));
Response response = mock(Response.class);
when(response.getEntity()).thenReturn(entity);
when(restClient.performRequest(argThat(new RawRequestMatcher(
"GET",
"/_nodes/stats/fs,process,jvm,indices,breaker"))))
.thenReturn(response);
assertThat(underTest.nodesStats()).isNotNull();
}
@Test
public void should_rethrow_ex_on_node_stat_fail() throws Exception {
when(restClient.performRequest(argThat(new RawRequestMatcher(
"GET",
"/_nodes/stats/fs,process,jvm,indices,breaker"))))
.thenThrow(IOException.class);
assertThatThrownBy(() -> underTest.nodesStats())
.isInstanceOf(ElasticsearchException.class);
}
@Test
public void should_call_indices_stat_api() throws Exception {
HttpEntity entity = mock(HttpEntity.class);
when(entity.getContent()).thenReturn(new ByteArrayInputStream(EXAMPLE_INDICES_STATS_JSON.getBytes()));
Response response = mock(Response.class);
when(response.getEntity()).thenReturn(entity);
when(restClient.performRequest(argThat(new RawRequestMatcher(
"GET",
"/_stats"))))
.thenReturn(response);
assertThat(underTest.indicesStats()).isNotNull();
}
@Test
public void should_rethrow_ex_on_indices_stat_fail() throws Exception {
when(restClient.performRequest(argThat(new RawRequestMatcher(
"GET",
"/_stats"))))
.thenThrow(IOException.class);
assertThatThrownBy(() -> underTest.indicesStats())
.isInstanceOf(ElasticsearchException.class);
}
@Test
public void should_call_cluster_stat_api() throws Exception {
HttpEntity entity = mock(HttpEntity.class);
when(entity.getContent()).thenReturn(new ByteArrayInputStream(EXAMPLE_CLUSTER_STATS_JSON.getBytes()));
Response response = mock(Response.class);
when(response.getEntity()).thenReturn(entity);
when(restClient.performRequest(argThat(new RawRequestMatcher(
"GET",
"/_cluster/stats"))))
.thenReturn(response);
assertThat(underTest.clusterStats()).isNotNull();
}
@Test
public void should_rethrow_ex_on_cluster_stat_fail() throws Exception {
when(restClient.performRequest(argThat(new RawRequestMatcher(
"GET",
"/_cluster/stats"))))
.thenThrow(IOException.class);
assertThatThrownBy(() -> underTest.clusterStats())
.isInstanceOf(ElasticsearchException.class);
}
@Test
public void should_add_authentication_header() throws InterruptedException {
mockWebServer.enqueue(new MockResponse()
.setResponseCode(200)
.setBody(EXAMPLE_CLUSTER_STATS_JSON)
.setHeader("Content-Type", "application/json"));
String password = "test-password";
EsClient underTest = new EsClient(password, null, null, new HttpHost(mockWebServer.getHostName(), mockWebServer.getPort()));
assertThat(underTest.clusterStats()).isNotNull();
assertThat(mockWebServer.takeRequest().getHeader("Authorization")).isEqualTo("Basic ZWxhc3RpYzp0ZXN0LXBhc3N3b3Jk");
}
@Test
public void newInstance_whenKeyStorePassed_shouldCreateClient() throws GeneralSecurityException, IOException {
mockWebServer.enqueue(new MockResponse()
.setResponseCode(200)
.setBody(EXAMPLE_CLUSTER_STATS_JSON)
.setHeader("Content-Type", "application/json"));
Path keyStorePath = temp.newFile("keystore.p12").toPath();
String password = "password";
HandshakeCertificates certificate = createCertificate(mockWebServer.getHostName(), keyStorePath, password);
mockWebServer.useHttps(certificate.sslSocketFactory(), false);
EsClient underTest = new EsClient(null, keyStorePath.toString(), password,
new HttpHost(mockWebServer.getHostName(), mockWebServer.getPort(), "https"));
assertThat(underTest.clusterStats()).isNotNull();
}
static HandshakeCertificates createCertificate(String hostName, Path keyStorePath, String password) throws GeneralSecurityException, IOException {
HeldCertificate localhostCertificate = new HeldCertificate.Builder()
.addSubjectAlternativeName(hostName)
.build();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(null);
ks.setKeyEntry("alias", localhostCertificate.keyPair().getPrivate(), password.toCharArray(),
new java.security.cert.Certificate[]{localhostCertificate.certificate()});
ks.store(baos, password.toCharArray());
try (OutputStream outputStream = Files.newOutputStream(keyStorePath)) {
outputStream.write(baos.toByteArray());
}
}
return new HandshakeCertificates.Builder()
.heldCertificate(localhostCertificate)
.build();
}
static class RawRequestMatcher implements ArgumentMatcher<Request> {
String endpoint;
String method;
RawRequestMatcher(String method, String endpoint) {
Objects.requireNonNull(endpoint);
Objects.requireNonNull(method);
this.endpoint = endpoint;
this.method = method;
}
@Override
public boolean matches(Request request) {
return endpoint.equals(request.getEndpoint()) && method.equals(request.getMethod());
}
}
}
| 11,263 | 32.724551 | 148 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/EsModuleTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class EsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new EsModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(1);
}
}
| 1,243 | 34.542857 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/EsRequestDetailsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest;
import org.elasticsearch.client.indices.PutMappingRequest;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.core.TimeValue;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class EsRequestDetailsTest {
@Test
public void should_format_SearchRequest() {
SearchRequest searchRequest = Requests.searchRequest("index");
assertThat(EsRequestDetails.computeDetailsAsString(searchRequest))
.isEqualTo("ES search request 'SearchRequest{searchType=QUERY_THEN_FETCH, indices=[index],"
+ " indicesOptions=IndicesOptions[ignore_unavailable=false, allow_no_indices=true,"
+ " expand_wildcards_open=true, expand_wildcards_closed=false, expand_wildcards_hidden=false,"
+ " allow_aliases_to_multiple_indices=true, forbid_closed_indices=true, ignore_aliases=false,"
+ " ignore_throttled=true], types=[], routing='null', preference='null', requestCache=null,"
+ " scroll=null, maxConcurrentShardRequests=0, batchedReduceSize=512, preFilterShardSize=null,"
+ " allowPartialSearchResults=null, localClusterAlias=null, getOrCreateAbsoluteStartMillis=-1,"
+ " ccsMinimizeRoundtrips=true, enableFieldsEmulation=false, source={}}' on indices '[index]'");
}
@Test
public void should_format_search_SearchScrollRequest() {
SearchScrollRequest scrollRequest = Requests.searchScrollRequest("scroll-id")
.scroll(TimeValue.ZERO);
assertThat(EsRequestDetails.computeDetailsAsString(scrollRequest))
.isEqualTo("ES search scroll request for scroll id 'Scroll{keepAlive=0s}'");
}
@Test
public void should_format_DeleteRequest() {
DeleteRequest deleteRequest = new DeleteRequest()
.index("some-index")
.id("some-id");
assertThat(EsRequestDetails.computeDetailsAsString(deleteRequest))
.isEqualTo("ES delete request of doc some-id in index some-index");
}
@Test
public void should_format_RefreshRequest() {
RefreshRequest deleteRequest = new RefreshRequest()
.indices("index-1", "index-2");
assertThat(EsRequestDetails.computeDetailsAsString(deleteRequest))
.isEqualTo("ES refresh request on indices 'index-1,index-2'");
}
@Test
public void should_format_ClearIndicesCacheRequest() {
ClearIndicesCacheRequest clearIndicesCacheRequest = new ClearIndicesCacheRequest()
.indices("index-1")
.fields("field-1")
.queryCache(true)
.fieldDataCache(true)
.requestCache(true);
assertThat(EsRequestDetails.computeDetailsAsString(clearIndicesCacheRequest))
.isEqualTo("ES clear cache request on indices 'index-1' on fields 'field-1' with filter cache with field data cache with request cache");
}
@Test
public void should_format_IndexRequest() {
IndexRequest indexRequest = new IndexRequest()
.index("index-1")
.id("id-1");
assertThat(EsRequestDetails.computeDetailsAsString(indexRequest))
.isEqualTo("ES index request for key 'id-1' on index 'index-1'");
}
@Test
public void should_format_GetRequest() {
GetRequest request = new GetRequest()
.index("index-1")
.id("id-1");
assertThat(EsRequestDetails.computeDetailsAsString(request))
.isEqualTo("ES get request for key 'id-1' on index 'index-1'");
}
@Test
public void should_format_GetIndexRequest() {
GetIndexRequest request = new GetIndexRequest("index-1", "index-2");
assertThat(EsRequestDetails.computeDetailsAsString(request))
.isEqualTo("ES indices exists request on indices 'index-1,index-2'");
}
@Test
public void should_format_CreateIndexRequest() {
CreateIndexRequest request = new CreateIndexRequest("index-1");
assertThat(EsRequestDetails.computeDetailsAsString(request))
.isEqualTo("ES create index 'index-1'");
}
@Test
public void should_format_PutMappingRequest() {
PutMappingRequest request = new PutMappingRequest("index-1");
assertThat(EsRequestDetails.computeDetailsAsString(request))
.isEqualTo("ES put mapping request on indices 'index-1'");
}
@Test
public void should_format_ClusterHealthRequest() {
ClusterHealthRequest request = new ClusterHealthRequest("index-1");
assertThat(EsRequestDetails.computeDetailsAsString(request))
.isEqualTo("ES cluster health request on indices 'index-1'");
}
@Test
public void should_format_IndicesStats() {
assertThat(EsRequestDetails.computeDetailsAsString("index-1", "index-2"))
.isEqualTo("ES indices stats request on indices 'index-1,index-2'");
}
}
| 6,060 | 39.406667 | 143 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/EsUtilsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import java.util.Date;
import java.util.List;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.junit.Test;
import org.sonar.server.issue.index.IssueDoc;
import org.sonar.test.TestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.es.EsUtils.escapeSpecialRegexChars;
public class EsUtilsTest {
@Test
public void convertToDocs_empty() {
SearchHits hits = new SearchHits(new SearchHit[] {}, new TotalHits(0, TotalHits.Relation.EQUAL_TO), 0);
List<BaseDoc> docs = EsUtils.convertToDocs(hits, IssueDoc::new);
assertThat(docs).isEmpty();
}
@Test
public void convertToDocs() {
SearchHits hits = new SearchHits(new SearchHit[] {new SearchHit(16)}, new TotalHits(1, TotalHits.Relation.EQUAL_TO), 1);
List<BaseDoc> docs = EsUtils.convertToDocs(hits, IssueDoc::new);
assertThat(docs).hasSize(1);
}
@Test
public void util_class() {
assertThat(TestUtils.hasOnlyPrivateConstructors(EsUtils.class)).isTrue();
}
@Test
public void es_date_format() {
assertThat(EsUtils.formatDateTime(new Date(1_500_000_000_000L))).startsWith("2017-07-");
assertThat(EsUtils.formatDateTime(null)).isNull();
assertThat(EsUtils.parseDateTime("2017-07-14T04:40:00.000+02:00").getTime()).isEqualTo(1_500_000_000_000L);
assertThat(EsUtils.parseDateTime(null)).isNull();
}
@Test
public void test_escapeSpecialRegexChars() {
assertThat(escapeSpecialRegexChars("")).isEmpty();
assertThat(escapeSpecialRegexChars("foo")).isEqualTo("foo");
assertThat(escapeSpecialRegexChars("FOO")).isEqualTo("FOO");
assertThat(escapeSpecialRegexChars("foo++")).isEqualTo("foo\\+\\+");
assertThat(escapeSpecialRegexChars("foo[]")).isEqualTo("foo\\[\\]");
assertThat(escapeSpecialRegexChars(".*")).isEqualTo("\\.\\*");
assertThat(escapeSpecialRegexChars("foo\\d")).isEqualTo("foo\\\\d");
assertThat(escapeSpecialRegexChars("^")).isEqualTo("\\^");
assertThat(escapeSpecialRegexChars("$")).isEqualTo("\\$");
assertThat(escapeSpecialRegexChars("|")).isEqualTo("\\|");
assertThat(escapeSpecialRegexChars("<")).isEqualTo("\\<");
assertThat(escapeSpecialRegexChars(">")).isEqualTo("\\>");
assertThat(escapeSpecialRegexChars("\"")).isEqualTo("\\\"");
assertThat(escapeSpecialRegexChars("#")).isEqualTo("\\#");
assertThat(escapeSpecialRegexChars("~")).isEqualTo("\\~");
assertThat(escapeSpecialRegexChars("$")).isEqualTo("\\$");
assertThat(escapeSpecialRegexChars("&")).isEqualTo("\\&");
assertThat(escapeSpecialRegexChars("?")).isEqualTo("\\?");
assertThat(escapeSpecialRegexChars("a bit of | & #<\"$ .* ^ everything")).isEqualTo("a bit of \\| \\& \\#\\<\\\"\\$ \\.\\* \\^ everything");
}
}
| 3,691 | 41.436782 | 144 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/FailOnErrorIndexingListenerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.es.IndexingListener.FAIL_ON_ERROR;
public class FailOnErrorIndexingListenerTest {
@Test
public void onFinish_must_throw_ISE_when_an_error_is_present() {
IndexingResult indexingResult = new IndexingResult();
indexingResult.incrementRequests();
assertThatThrownBy(() -> FAIL_ON_ERROR.onFinish(indexingResult))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Unrecoverable indexation failures: 1 errors among 1 requests. "
+ "Check Elasticsearch logs for further details.");
}
@Test
public void onFinish_must_not_throw_any_exception_if_no_failure() {
IndexingResult indexingResult = new IndexingResult();
indexingResult.incrementRequests();
indexingResult.incrementSuccess();
assertThatCode(() -> FAIL_ON_ERROR.onFinish(indexingResult))
.doesNotThrowAnyException();
}
}
| 1,904 | 34.943396 | 82 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexDefinitionContextTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Locale;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.es.newindex.SettingsConfiguration;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder;
@RunWith(DataProviderRunner.class)
public class IndexDefinitionContextTest {
private SettingsConfiguration emptySettingsConfiguration = newBuilder(new MapSettings().asConfig()).build();
@Test
public void create_indices() {
IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext();
context.create(Index.withRelations("issues"), emptySettingsConfiguration);
context.create(Index.simple("users"), emptySettingsConfiguration);
assertThat(context.getIndices().keySet())
.containsOnly("issues", "users");
}
@Test
@UseDataProvider("paarOfIndicesWithSameName")
public void fail_to_create_twice_index_with_given_name(Index index1, Index index2) {
IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext();
context.create(index1, emptySettingsConfiguration);
assertThatThrownBy(() -> context.create(index2, emptySettingsConfiguration))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index already exists: " + index1.getName());
}
@DataProvider
public static Object[][] paarOfIndicesWithSameName() {
String indexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH);
return new Object[][] {
{Index.simple(indexName), Index.simple(indexName)},
{Index.withRelations(indexName), Index.withRelations(indexName)},
{Index.simple(indexName), Index.withRelations(indexName)},
{Index.withRelations(indexName), Index.simple(indexName)},
};
}
}
| 3,041 | 40.108108 | 110 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexDefinitionHashTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import org.junit.Test;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.es.IndexType.IndexMainType;
import org.sonar.server.es.newindex.SettingsConfiguration;
import org.sonar.server.es.newindex.TestNewIndex;
import org.sonar.server.es.newindex.TypeMapping;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED;
public class IndexDefinitionHashTest {
private final SettingsConfiguration settingsConfiguration = settingsConfigurationOf(new MapSettings());
@Test
public void hash_changes_if_mainType_is_different() {
Index simpleIndex = Index.simple("foo");
Index withRelationsIndex = Index.withRelations("foo");
IndexMainType mainTypeBar = IndexMainType.main(simpleIndex, "bar");
TestNewIndex indexSimpleBar = new TestNewIndex(mainTypeBar, settingsConfiguration);
TestNewIndex indexSimpleDonut = new TestNewIndex(IndexMainType.main(simpleIndex, "donut"), settingsConfiguration);
TestNewIndex indexWithRelationsBar = new TestNewIndex(IndexMainType.main(withRelationsIndex, "bar"), settingsConfiguration);
assertThat(hashOf(indexSimpleBar))
.isEqualTo(hashOf(new TestNewIndex(mainTypeBar, settingsConfiguration)))
.isNotEqualTo(hashOf(indexSimpleDonut))
.isNotEqualTo(hashOf(indexWithRelationsBar));
assertThat(hashOf(indexSimpleDonut))
.isNotEqualTo(hashOf(indexWithRelationsBar));
}
@Test
public void hash_changes_if_relations_are_different() {
Index index = Index.withRelations("foo");
IndexMainType mainType = IndexMainType.main(index, "bar");
TestNewIndex indexNoRelation = new TestNewIndex(mainType, settingsConfiguration);
TestNewIndex indexOneRelation = new TestNewIndex(mainType, settingsConfiguration)
.addRelation("donut1");
TestNewIndex indexOneOtherRelation = new TestNewIndex(mainType, settingsConfiguration)
.addRelation("donut2");
TestNewIndex indexTwoRelations = new TestNewIndex(mainType, settingsConfiguration)
.addRelation("donut1")
.addRelation("donut2");
TestNewIndex indexTwoOtherRelations = new TestNewIndex(mainType, settingsConfiguration)
.addRelation("donut1")
.addRelation("donut3");
assertThat(hashOf(indexNoRelation))
.isEqualTo(hashOf(new TestNewIndex(mainType, settingsConfiguration)))
.isNotEqualTo(hashOf(indexOneRelation))
.isNotEqualTo(hashOf(indexOneOtherRelation))
.isNotEqualTo(hashOf(indexTwoRelations))
.isNotEqualTo(hashOf(indexTwoOtherRelations));
assertThat(hashOf(indexOneRelation))
.isEqualTo(hashOf(new TestNewIndex(mainType, settingsConfiguration).addRelation("donut1")))
.isNotEqualTo(hashOf(indexOneOtherRelation))
.isNotEqualTo(hashOf(indexTwoRelations))
.isNotEqualTo(hashOf(indexTwoOtherRelations));
assertThat(hashOf(indexTwoRelations))
.isEqualTo(hashOf(new TestNewIndex(mainType, settingsConfiguration)
.addRelation("donut1")
.addRelation("donut2")))
.isNotEqualTo(hashOf(indexOneRelation))
.isNotEqualTo(hashOf(indexOneOtherRelation))
.isNotEqualTo(hashOf(indexTwoOtherRelations));
}
@Test
public void hash_is_the_same_if_only_relations_order_changes() {
Index index = Index.withRelations("foo");
IndexMainType mainType = IndexMainType.main(index, "bar");
TestNewIndex indexTwoRelations = new TestNewIndex(mainType, settingsConfiguration)
.addRelation("donut1")
.addRelation("donut2")
.addRelation("donut3");
TestNewIndex indexTwoRelationsOtherOrder = new TestNewIndex(mainType, settingsConfiguration)
.addRelation("donut2")
.addRelation("donut1")
.addRelation("donut3");
TestNewIndex indexTwoRelationsOtherOrder2 = new TestNewIndex(mainType, settingsConfiguration)
.addRelation("donut2")
.addRelation("donut3")
.addRelation("donut1");
assertThat(hashOf(indexTwoRelations))
.isEqualTo(hashOf(indexTwoRelationsOtherOrder))
.isEqualTo(hashOf(indexTwoRelationsOtherOrder2));
}
@Test
public void hash_changes_if_fields_on_main_type_mapping_are_different() {
Index index = Index.withRelations("foo");
IndexMainType mainType = IndexMainType.main(index, "bar");
TestNewIndex indexNoField = new TestNewIndex(mainType, settingsConfiguration);
TestNewIndex indexOneField = new TestNewIndex(mainType, settingsConfiguration);
indexOneField.getMainTypeMapping()
.createIntegerField("field1");
TestNewIndex indexOneFieldAgain = new TestNewIndex(mainType, settingsConfiguration);
indexOneFieldAgain.getMainTypeMapping()
.createIntegerField("field1");
TestNewIndex indexOneOtherField = new TestNewIndex(mainType, settingsConfiguration);
indexOneOtherField.getMainTypeMapping()
.createIntegerField("field2");
TestNewIndex indexTwoFields = new TestNewIndex(mainType, settingsConfiguration);
indexTwoFields.getMainTypeMapping()
.createIntegerField("field1")
.createIntegerField("field2");
TestNewIndex indexTwoFieldsAgain = new TestNewIndex(mainType, settingsConfiguration);
indexTwoFieldsAgain.getMainTypeMapping()
.createIntegerField("field1")
.createIntegerField("field2");
TestNewIndex indexTwoOtherFields = new TestNewIndex(mainType, settingsConfiguration);
indexTwoOtherFields.getMainTypeMapping()
.createIntegerField("field1")
.createIntegerField("field3");
assertThat(hashOf(indexNoField))
.isEqualTo(hashOf(new TestNewIndex(mainType, settingsConfiguration)))
.isNotEqualTo(hashOf(indexOneField))
.isNotEqualTo(hashOf(indexOneOtherField))
.isNotEqualTo(hashOf(indexTwoFields))
.isNotEqualTo(hashOf(indexTwoOtherFields));
assertThat(hashOf(indexOneField))
.isEqualTo(hashOf(indexOneFieldAgain))
.isNotEqualTo(hashOf(indexOneOtherField))
.isNotEqualTo(hashOf(indexTwoFields))
.isNotEqualTo(hashOf(indexTwoOtherFields));
assertThat(hashOf(indexTwoFields))
.isEqualTo(hashOf(indexTwoFieldsAgain))
.isNotEqualTo(hashOf(indexOneField))
.isNotEqualTo(hashOf(indexOneOtherField))
.isNotEqualTo(hashOf(indexTwoOtherFields));
}
@Test
public void hash_is_the_same_if_only_fields_order_changes() {
Index index = Index.withRelations("foo");
IndexMainType mainType = IndexMainType.main(index, "bar");
TestNewIndex indexTwoFields = new TestNewIndex(mainType, settingsConfiguration);
indexTwoFields.getMainTypeMapping()
.createBooleanField("donut1")
.createBooleanField("donut2")
.createBooleanField("donut3");
TestNewIndex indexTwoFieldsOtherOrder = new TestNewIndex(mainType, settingsConfiguration);
indexTwoFieldsOtherOrder.getMainTypeMapping()
.createBooleanField("donut2")
.createBooleanField("donut1")
.createBooleanField("donut3");
TestNewIndex indexTwoFieldsOtherOrder2 = new TestNewIndex(mainType, settingsConfiguration);
indexTwoFieldsOtherOrder2.getMainTypeMapping()
.createBooleanField("donut2")
.createBooleanField("donut3")
.createBooleanField("donut1");
assertThat(hashOf(indexTwoFields))
.isEqualTo(hashOf(indexTwoFieldsOtherOrder))
.isEqualTo(hashOf(indexTwoFieldsOtherOrder2));
}
@Test
public void hash_changes_if_field_type_changes() {
Index index = Index.withRelations("foo");
IndexMainType mainType = IndexMainType.main(index, "bar");
String fieldName = "field1";
computeAndVerifyAllDifferentHashesOnMapping(mainType,
(mapping) -> mapping.createBooleanField(fieldName),
(mapping) -> mapping.createIntegerField(fieldName),
(mapping) -> mapping.createByteField(fieldName),
(mapping) -> mapping.createDateTimeField(fieldName),
(mapping) -> mapping.createDoubleField(fieldName),
(mapping) -> mapping.createLongField(fieldName),
(mapping) -> mapping.createShortField(fieldName),
(mapping) -> mapping.createUuidPathField(fieldName),
(mapping) -> mapping.keywordFieldBuilder(fieldName).build(),
(mapping) -> mapping.textFieldBuilder(fieldName).build(),
(mapping) -> mapping.nestedFieldBuilder(fieldName).addKeywordField("bar").build());
}
@Test
public void hash_changes_if_keyword_options_change() {
Index index = Index.withRelations("foo");
IndexMainType mainType = IndexMainType.main(index, "bar");
String fieldName = "field1";
computeAndVerifyAllDifferentHashesOnMapping(mainType,
(mapping) -> mapping.keywordFieldBuilder(fieldName).build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableSortingAndAggregating().build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableSortingAndAggregating().disableNorms().build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableSortingAndAggregating().disableSearch().build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableSortingAndAggregating().disableNorms().disableSearch().build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableNorms().build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableNorms().disableSearch().build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableSearch().build());
}
@Test
public void hash_is_the_same_if_only_order_of_keyword_options_change() {
Index index = Index.withRelations("foo");
IndexMainType mainType = IndexMainType.main(index, "bar");
String fieldName = "field1";
computeAndVerifyAllSameHashesOnMapping(mainType,
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableSortingAndAggregating().disableNorms().build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableNorms().disableSortingAndAggregating().build());
computeAndVerifyAllSameHashesOnMapping(mainType,
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableSortingAndAggregating().disableSearch().build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableSearch().disableSortingAndAggregating().build());
computeAndVerifyAllSameHashesOnMapping(mainType,
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableSearch().disableNorms().build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableNorms().disableSearch().build());
computeAndVerifyAllSameHashesOnMapping(mainType,
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableSortingAndAggregating().disableSearch().disableNorms().build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableSearch().disableNorms().disableSortingAndAggregating().build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableNorms().disableSearch().disableSortingAndAggregating().build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableNorms().disableSortingAndAggregating().disableSearch().build(),
(mapping) -> mapping.keywordFieldBuilder(fieldName).disableSearch().disableSortingAndAggregating().disableNorms().build());
}
@Test
public void hash_changes_if_textFieldBuilder_options_change() {
Index index = Index.withRelations("foo");
IndexMainType mainType = IndexMainType.main(index, "bar");
String fieldName = "field1";
computeAndVerifyAllDifferentHashesOnMapping(mainType,
(mapping) -> mapping.textFieldBuilder(fieldName).build(),
(mapping) -> mapping.textFieldBuilder(fieldName).disableSearch().build(),
(mapping) -> mapping.textFieldBuilder(fieldName).disableNorms().build(),
(mapping) -> mapping.textFieldBuilder(fieldName).disableNorms().disableSearch().build());
}
@Test
public void hash_is_the_same_if_only_order_of_textFieldBuilder_options_change() {
Index index = Index.withRelations("foo");
IndexMainType mainType = IndexMainType.main(index, "bar");
String fieldName = "field1";
computeAndVerifyAllSameHashesOnMapping(mainType,
(mapping) -> mapping.textFieldBuilder(fieldName).disableSearch().disableNorms().build(),
(mapping) -> mapping.textFieldBuilder(fieldName).disableNorms().disableSearch().build());
}
@SafeVarargs
private final void computeAndVerifyAllSameHashesOnMapping(IndexMainType mainType, Consumer<TypeMapping>... fieldTypes) {
List<Consumer<TypeMapping>> fieldTypes1 = Arrays.asList(fieldTypes);
List<TestNewIndex> mainIndices = fieldTypes1.stream()
.map(consumer -> {
TestNewIndex mainTypeMapping = new TestNewIndex(mainType, settingsConfiguration);
consumer.accept(mainTypeMapping.getMainTypeMapping());
return mainTypeMapping;
})
.toList();
List<TestNewIndex> relationIndices = fieldTypes1.stream()
.map(consumer -> {
TestNewIndex relationTypeMapping = new TestNewIndex(mainType, settingsConfiguration);
consumer.accept(relationTypeMapping.createRelationMapping("donut"));
return relationTypeMapping;
})
.toList();
Set<String> mainHashes = mainIndices.stream()
.map(IndexDefinitionHashTest::hashOf)
.collect(toSet());
Set<String> relationHashes = relationIndices.stream()
.map(IndexDefinitionHashTest::hashOf)
.collect(toSet());
assertThat(mainHashes)
// verify hashing is stable
.isEqualTo(mainIndices.stream().map(IndexDefinitionHashTest::hashOf).collect(toSet()))
.doesNotContainAnyElementsOf(relationHashes)
.hasSize(1);
assertThat(relationHashes)
// verify hashing is stable
.isEqualTo(relationIndices.stream().map(IndexDefinitionHashTest::hashOf).collect(toSet()))
.doesNotContainAnyElementsOf(mainHashes)
.hasSize(1);
}
@SafeVarargs
private final void computeAndVerifyAllDifferentHashesOnMapping(IndexMainType mainType, Consumer<TypeMapping>... fieldTypes) {
List<TestNewIndex> mainIndices = Arrays.stream(fieldTypes)
.map(consumer -> {
TestNewIndex mainTypeMapping = new TestNewIndex(mainType, settingsConfiguration);
consumer.accept(mainTypeMapping.getMainTypeMapping());
return mainTypeMapping;
})
.toList();
List<TestNewIndex> relationIndices = Arrays.stream(fieldTypes)
.map(consumer -> {
TestNewIndex relationTypeMapping = new TestNewIndex(mainType, settingsConfiguration);
consumer.accept(relationTypeMapping.createRelationMapping("donut"));
return relationTypeMapping;
})
.toList();
Set<String> mainHashes = mainIndices.stream()
.map(IndexDefinitionHashTest::hashOf)
.collect(toSet());
Set<String> relationHashes = relationIndices.stream()
.map(IndexDefinitionHashTest::hashOf)
.collect(toSet());
assertThat(mainHashes)
// verify hashing is stable
.isEqualTo(mainIndices.stream().map(IndexDefinitionHashTest::hashOf).collect(toSet()))
.doesNotContainAnyElementsOf(relationHashes)
.hasSize(fieldTypes.length);
assertThat(relationHashes)
// verify hashing is stable
.isEqualTo(relationIndices.stream().map(IndexDefinitionHashTest::hashOf).collect(toSet()))
.doesNotContainAnyElementsOf(mainHashes)
.hasSize(fieldTypes.length);
}
@Test
public void hash_changes_if_clustering_is_enabled_or_not() {
Index index = Index.simple("foo");
IndexMainType mainType = IndexMainType.main(index, "bar");
MapSettings empty = new MapSettings();
MapSettings clusterDisabled = new MapSettings().setProperty(CLUSTER_ENABLED.getKey(), false);
MapSettings clusterEnabled = new MapSettings().setProperty(CLUSTER_ENABLED.getKey(), true);
assertThat(hashOf(new TestNewIndex(mainType, settingsConfigurationOf(empty))))
.isEqualTo(hashOf(new TestNewIndex(mainType, settingsConfigurationOf(empty))))
.isEqualTo(hashOf(new TestNewIndex(mainType, settingsConfigurationOf(clusterDisabled))))
.isNotEqualTo(hashOf(new TestNewIndex(mainType, settingsConfigurationOf(clusterEnabled))));
}
@Test
public void hash_changes_if_number_of_shards_changes() {
Index index = Index.simple("foo");
IndexMainType mainType = IndexMainType.main(index, "bar");
Configuration emptySettings = new MapSettings().asConfig();
SettingsConfiguration defaultNbOfShards = SettingsConfiguration.newBuilder(emptySettings)
.build();
SettingsConfiguration specifiedDefaultNbOfShards = SettingsConfiguration.newBuilder(emptySettings)
.setDefaultNbOfShards(5)
.build();
SettingsConfiguration specifyDefaultNbOfShards = SettingsConfiguration.newBuilder(new MapSettings()
.setProperty("sonar.search." + index.getName() + ".shards", 1)
.asConfig())
.setDefaultNbOfShards(1)
.build();
SettingsConfiguration specifiedNbOfShards = SettingsConfiguration.newBuilder(new MapSettings()
.setProperty("sonar.search." + index.getName() + ".shards", 10)
.asConfig())
.setDefaultNbOfShards(5)
.build();
assertThat(hashOf(new TestNewIndex(mainType, defaultNbOfShards)))
// verify hash is stable
.isEqualTo(hashOf(new TestNewIndex(mainType, defaultNbOfShards)))
.isEqualTo(hashOf(new TestNewIndex(mainType, specifyDefaultNbOfShards)))
.isNotEqualTo(hashOf(new TestNewIndex(mainType, specifiedDefaultNbOfShards)))
.isNotEqualTo(hashOf(new TestNewIndex(mainType, specifiedNbOfShards)));
assertThat(hashOf(new TestNewIndex(mainType, specifiedDefaultNbOfShards)))
// verify hash is stable
.isEqualTo(hashOf(new TestNewIndex(mainType, specifiedDefaultNbOfShards)))
.isNotEqualTo(hashOf(new TestNewIndex(mainType, specifyDefaultNbOfShards)));
}
@Test
public void hash_changes_if_refreshInterval_changes() {
Index index = Index.simple("foo");
IndexMainType mainType = IndexMainType.main(index, "bar");
Configuration emptySettings = new MapSettings().asConfig();
SettingsConfiguration defaultRefreshInterval = SettingsConfiguration.newBuilder(emptySettings)
.build();
SettingsConfiguration noRefreshInterval = SettingsConfiguration.newBuilder(emptySettings)
.setRefreshInterval(-1)
.build();
SettingsConfiguration refreshInterval30 = SettingsConfiguration.newBuilder(emptySettings)
.setRefreshInterval(30)
.build();
SettingsConfiguration someRefreshInterval = SettingsConfiguration.newBuilder(emptySettings)
.setRefreshInterval(56)
.build();
assertThat(hashOf(new TestNewIndex(mainType, defaultRefreshInterval)))
// verify hash is stable
.isEqualTo(hashOf(new TestNewIndex(mainType, defaultRefreshInterval)))
.isEqualTo(hashOf(new TestNewIndex(mainType, refreshInterval30)))
.isNotEqualTo(hashOf(new TestNewIndex(mainType, noRefreshInterval)))
.isNotEqualTo(hashOf(new TestNewIndex(mainType, someRefreshInterval)));
assertThat(hashOf(new TestNewIndex(mainType, noRefreshInterval)))
.isNotEqualTo(hashOf(new TestNewIndex(mainType, someRefreshInterval)));
}
private static SettingsConfiguration settingsConfigurationOf(MapSettings settings) {
return SettingsConfiguration.newBuilder(settings.asConfig()).build();
}
private static String hashOf(TestNewIndex newIndex) {
return IndexDefinitionHash.of(newIndex.build());
}
}
| 20,278 | 46.715294 | 129 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Locale;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(DataProviderRunner.class)
public class IndexTest {
@Test
@UseDataProvider("nullOrEmpty")
public void simple_index_constructor_fails_with_IAE_if_index_name_is_null_or_empty(String nullOrEmpty) {
assertThatThrownBy(() -> Index.simple(nullOrEmpty))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index name can't be null nor empty");
}
@Test
@UseDataProvider("nullOrEmpty")
public void withRelations_index_constructor_fails_with_IAE_if_index_name_is_null_or_empty(String nullOrEmpty) {
assertThatThrownBy(() -> Index.withRelations(nullOrEmpty))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index name can't be null nor empty");
}
@DataProvider
public static Object[][] nullOrEmpty() {
return new Object[][] {
{null},
{""}
};
}
@Test
public void simple_index_name_must_not_contain_upper_case_char() {
assertThatThrownBy(() -> Index.simple("Issues"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index name must be lower-case letters or '_all': Issues");
}
@Test
public void withRelations_index_name_must_not_contain_upper_case_char() {
assertThatThrownBy(() -> Index.withRelations("Issues"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index name must be lower-case letters or '_all': Issues");
}
@Test
public void simple_index_name_can_not_contain_underscore_except__all_keyword() {
// doesn't fail
Index.simple("_all");
assertThatThrownBy(() -> Index.simple("_"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index name must be lower-case letters or '_all': _");
}
@Test
public void withRelations_index_name_can_not_contain_underscore_except__all_keyword() {
// doesn't fail
Index.withRelations("_all");
assertThatThrownBy(() -> Index.withRelations("_"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index name must be lower-case letters or '_all': _");
}
@Test
public void simple_index_does_not_accept_relations() {
Index underTest = Index.simple("foo");
assertThat(underTest.acceptsRelations()).isFalse();
}
@Test
public void withRelations_index_does_not_accept_relations() {
Index underTest = Index.withRelations("foo");
assertThat(underTest.acceptsRelations()).isTrue();
}
@Test
public void getName_returns_constructor_parameter() {
String indexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH);
assertThat(Index.simple(indexName).getName()).isEqualTo(indexName);
assertThat(Index.withRelations(indexName).getName()).isEqualTo(indexName);
}
@Test
public void getJoinField_throws_ISE_on_simple_index() {
Index underTest = Index.simple("foo");
assertThatThrownBy(underTest::getJoinField)
.isInstanceOf(IllegalStateException.class)
.hasMessage("Only index accepting relations has a join field");
}
@Test
public void getJoinField_returns_name_based_on_index_name() {
String indexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH);
Index underTest = Index.withRelations(indexName);
assertThat(underTest.getJoinField()).isEqualTo("join_" + indexName);
}
@Test
public void equals_is_based_on_name_and_acceptRelations_flag() {
assertThat(Index.simple("foo"))
.isEqualTo(Index.simple("foo"))
.isNotEqualTo(Index.simple("bar"))
.isNotEqualTo(Index.withRelations("foo"));
}
@Test
public void hashcode_is_based_on_name_and_acceptRelations_flag() {
assertThat(Index.simple("foo").hashCode())
.isEqualTo(Index.simple("foo").hashCode())
.isNotEqualTo(Index.simple("bar").hashCode())
.isNotEqualTo(Index.withRelations("foo").hashCode());
}
}
| 5,110 | 33.302013 | 113 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTypeTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.server.es.IndexType.IndexMainType;
import org.sonar.server.es.IndexType.IndexRelationType;
import org.sonar.server.es.IndexType.SimpleIndexMainType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(DataProviderRunner.class)
public class IndexTypeTest {
@Test
public void parseMainType_from_main_type_without_relations() {
IndexMainType type1 = IndexType.main(Index.simple("foo"), "bar");
assertThat(type1.format()).isEqualTo("foo/bar");
SimpleIndexMainType type2 = IndexType.parseMainType(type1.format());
assertThat(type2)
.extracting(SimpleIndexMainType::getIndex, SimpleIndexMainType::getType)
.containsExactly("foo", "bar");
}
@Test
public void parseMainType_from_maintype_with_relations() {
IndexMainType type1 = IndexType.main(Index.withRelations("foo"), "bar");
assertThat(type1.format()).isEqualTo("foo/bar");
SimpleIndexMainType type2 = IndexType.parseMainType(type1.format());
assertThat(type2)
.extracting(SimpleIndexMainType::getIndex, SimpleIndexMainType::getType)
.containsExactly("foo", "bar");
}
@Test
public void parseMainType_from_relationtype() {
IndexMainType mainType = IndexType.main(Index.withRelations("foo"), "bar");
IndexRelationType type1 = IndexType.relation(mainType, "donut");
assertThat(type1.format()).isEqualTo("foo/_doc");
SimpleIndexMainType type2 = IndexType.parseMainType(type1.format());
assertThat(type2)
.extracting(SimpleIndexMainType::getIndex, SimpleIndexMainType::getType)
.containsExactly("foo", "_doc");
}
@Test
public void parse_throws_IAE_if_invalid_format() {
assertThatThrownBy(() -> IndexType.parseMainType("foo"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unsupported IndexType value: foo");
}
@Test
@UseDataProvider("nullOrEmpty")
public void main_fails_with_IAE_if_index_name_is_null_or_empty(String nullOrEmpty) {
Index index = Index.simple("foo");
assertThatThrownBy(() -> IndexType.main(index, nullOrEmpty))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("type name can't be null nor empty");
}
@Test
@UseDataProvider("nullOrEmpty")
public void relation_fails_with_IAE_if_index_name_is_null_or_empty(String nullOrEmpty) {
Index index = Index.withRelations("foo");
IndexMainType mainType = IndexType.main(index, "foobar");
assertThatThrownBy(() -> IndexType.relation(mainType, nullOrEmpty))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("type name can't be null nor empty");
}
@DataProvider
public static Object[][] nullOrEmpty() {
return new Object[][] {
{null},
{""}
};
}
@Test
public void IndexMainType_equals_and_hashCode() {
IndexMainType type1 = IndexType.main(Index.simple("foo"), "bar");
IndexMainType type1b = IndexType.main(Index.simple("foo"), "bar");
IndexMainType type1c = IndexType.main(Index.withRelations("foo"), "bar");
IndexMainType type2 = IndexType.main(Index.simple("foo"), "baz");
assertThat(type1)
.isEqualTo(type1)
.isEqualTo(type1b)
.isNotEqualTo(type1c)
.isNotEqualTo(type2)
.hasSameHashCodeAs(type1)
.hasSameHashCodeAs(type1b);
assertThat(type1.hashCode()).isNotEqualTo(type1c.hashCode());
assertThat(type2.hashCode()).isNotEqualTo(type1.hashCode());
}
@Test
public void IndexRelationType_equals_and_hashCode() {
IndexMainType mainType1 = IndexType.main(Index.withRelations("foo"), "bar");
IndexMainType mainType2 = IndexType.main(Index.withRelations("foo"), "baz");
IndexRelationType type1 = IndexType.relation(mainType1, "donut");
IndexRelationType type1b = IndexType.relation(mainType1, "donut");
IndexRelationType type2 = IndexType.relation(mainType1, "donuz");
IndexRelationType type3 = IndexType.relation(mainType2, "donut");
assertThat(type1)
.isEqualTo(type1)
.isEqualTo(type1b)
.isNotEqualTo(type2)
.isNotEqualTo(type3)
.hasSameHashCodeAs(type1)
.hasSameHashCodeAs(type1b);
assertThat(type2.hashCode()).isNotEqualTo(type1.hashCode());
assertThat(type3.hashCode())
.isNotEqualTo(type2.hashCode())
.isNotEqualTo(type1.hashCode());
}
}
| 5,467 | 36.197279 | 90 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexersImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.es.EsQueueDto;
import org.sonar.db.project.ProjectDto;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.server.es.Indexers.BranchEvent.DELETION;
import static org.sonar.server.es.Indexers.EntityEvent.CREATION;
public class IndexersImplTest {
@Test
public void commitAndIndexOnEntityEvent_shouldCallIndexerWithSupportedItems() {
List<EsQueueDto> items1 = List.of(EsQueueDto.create("fake/fake1", "P1"), EsQueueDto.create("fake/fake1", "P1"));
List<EsQueueDto> items2 = List.of(EsQueueDto.create("fake/fake2", "P1"));
EventIndexer indexer1 = mock(EventIndexer.class);
EventIndexer indexer2 = mock(EventIndexer.class);
DbSession dbSession = mock(DbSession.class);
IndexersImpl underTest = new IndexersImpl(indexer1, indexer2);
when(indexer1.prepareForRecoveryOnEntityEvent(dbSession, Set.of("P1"), CREATION)).thenReturn(items1);
when(indexer2.prepareForRecoveryOnEntityEvent(dbSession, Set.of("P1"), CREATION)).thenReturn(items2);
underTest.commitAndIndexOnEntityEvent(dbSession, Set.of("P1"), CREATION);
verify(indexer1).index(dbSession, items1);
verify(indexer2).index(dbSession, items2);
}
@Test
public void commitAndIndexOnBranchEvent_shouldCallIndexerWithSupportedItems() {
List<EsQueueDto> items1 = List.of(EsQueueDto.create("fake/fake1", "P1"), EsQueueDto.create("fake/fake1", "P1"));
List<EsQueueDto> items2 = List.of(EsQueueDto.create("fake/fake2", "P1"));
EventIndexer indexer1 = mock(EventIndexer.class);
EventIndexer indexer2 = mock(EventIndexer.class);
DbSession dbSession = mock(DbSession.class);
IndexersImpl underTest = new IndexersImpl(indexer1, indexer2);
when(indexer1.prepareForRecoveryOnBranchEvent(dbSession, Set.of("P1"), DELETION)).thenReturn(items1);
when(indexer2.prepareForRecoveryOnBranchEvent(dbSession, Set.of("P1"), DELETION)).thenReturn(items2);
underTest.commitAndIndexOnBranchEvent(dbSession, Set.of("P1"), DELETION);
verify(indexer1).index(dbSession, items1);
verify(indexer2).index(dbSession, items2);
}
@Test
public void commitAndIndexEntities_shouldIndexAllUuids() {
EventIndexer indexer1 = mock(EventIndexer.class);
DbSession dbSession = mock(DbSession.class);
IndexersImpl underTest = new IndexersImpl(indexer1);
ProjectDto p1 = ComponentTesting.newProjectDto();
underTest.commitAndIndexEntities(dbSession, Set.of(p1), CREATION);
verify(indexer1).prepareForRecoveryOnEntityEvent(dbSession, Set.of(p1.getUuid()), CREATION);
}
@Test
public void commitAndIndexBranches_shouldIndexAllBranchUuids() {
EventIndexer indexer1 = mock(EventIndexer.class);
DbSession dbSession = mock(DbSession.class);
IndexersImpl underTest = new IndexersImpl(indexer1);
BranchDto b1 = new BranchDto().setUuid("b1");
underTest.commitAndIndexBranches(dbSession, Set.of(b1), DELETION);
verify(indexer1).prepareForRecoveryOnBranchEvent(dbSession, Set.of(b1.getUuid()), DELETION);
}
}
| 4,149 | 38.903846 | 116 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexingResultTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import org.assertj.core.data.Offset;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class IndexingResultTest {
private static final Offset<Double> DOUBLE_OFFSET = Offset.offset(0.000001d);
private final IndexingResult underTest = new IndexingResult();
@Test
public void test_empty() {
assertThat(underTest.getFailures()).isZero();
assertThat(underTest.getSuccess()).isZero();
assertThat(underTest.getTotal()).isZero();
assertThat(underTest.getSuccessRatio()).isEqualTo(1.0, DOUBLE_OFFSET);
assertThat(underTest.isSuccess()).isTrue();
}
@Test
public void test_success() {
underTest.incrementRequests();
underTest.incrementRequests();
underTest.incrementSuccess();
underTest.incrementSuccess();
assertThat(underTest.getFailures()).isZero();
assertThat(underTest.getSuccess()).isEqualTo(2);
assertThat(underTest.getTotal()).isEqualTo(2);
assertThat(underTest.getSuccessRatio()).isEqualTo(1.0, DOUBLE_OFFSET);
assertThat(underTest.isSuccess()).isTrue();
}
@Test
public void test_failure() {
underTest.incrementRequests();
underTest.incrementRequests();
assertThat(underTest.getFailures()).isEqualTo(2);
assertThat(underTest.getSuccess()).isZero();
assertThat(underTest.getTotal()).isEqualTo(2);
assertThat(underTest.getSuccessRatio()).isEqualTo(0.0, DOUBLE_OFFSET);
assertThat(underTest.isSuccess()).isFalse();
}
@Test
public void test_partial_failure() {
underTest.incrementRequests();
underTest.incrementRequests();
underTest.incrementRequests();
underTest.incrementRequests();
underTest.incrementSuccess();
assertThat(underTest.getFailures()).isEqualTo(3);
assertThat(underTest.getSuccess()).isOne();
assertThat(underTest.getTotal()).isEqualTo(4);
assertThat(underTest.getSuccessRatio()).isEqualTo(0.25, DOUBLE_OFFSET);
assertThat(underTest.isSuccess()).isFalse();
}
@Test
public void correctness_even_with_no_data() {
assertThat(underTest.getFailures()).isZero();
assertThat(underTest.getSuccess()).isZero();
assertThat(underTest.getTotal()).isZero();
assertThat(underTest.getSuccessRatio()).isEqualTo(1.0);
assertThat(underTest.isSuccess()).isTrue();
}
}
| 3,160 | 33.358696 | 79 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/NewIndexSettingsConfigurationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import java.util.Random;
import org.junit.Test;
import org.sonar.api.config.Configuration;
import org.sonar.server.es.newindex.SettingsConfiguration;
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.server.es.newindex.SettingsConfiguration.newBuilder;
public class NewIndexSettingsConfigurationTest {
private Configuration mockConfiguration = mock(Configuration.class);
@Test
public void newBuilder_fails_with_NPE_when_Configuration_is_null() {
assertThatThrownBy(() -> newBuilder(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("configuration can't be null");
}
@Test
public void setDefaultNbOfShards_fails_with_IAE_if_argument_is_zero() {
SettingsConfiguration.Builder underTest = newBuilder(mockConfiguration);
assertThatThrownBy(() -> underTest.setDefaultNbOfShards(0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("defaultNbOfShards must be >= 1");
}
@Test
public void setDefaultNbOfShards_fails_with_IAE_if_argument_is_less_than_zero() {
SettingsConfiguration.Builder underTest = newBuilder(mockConfiguration);
assertThatThrownBy(() -> underTest.setDefaultNbOfShards(-1 - new Random().nextInt(10)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("defaultNbOfShards must be >= 1");
}
@Test
public void setDefaultNbOfShards_accepts_1() {
SettingsConfiguration.Builder underTest = newBuilder(mockConfiguration);
assertThat(underTest.setDefaultNbOfShards(1).build().getDefaultNbOfShards()).isOne();
}
@Test
public void setDefaultNbOfShards_accepts_any_int_greater_than_1() {
SettingsConfiguration.Builder underTest = newBuilder(mockConfiguration);
int value = 1 + new Random().nextInt(200);
assertThat(underTest.setDefaultNbOfShards(value).build().getDefaultNbOfShards()).isEqualTo(value);
}
@Test
public void getDefaultNbOfShards_returns_1_when_not_explicitly_set() {
assertThat(newBuilder(mockConfiguration).build().getDefaultNbOfShards()).isOne();
}
@Test
public void setRefreshInterval_fails_with_IAE_if_argument_is_zero() {
SettingsConfiguration.Builder underTest = newBuilder(mockConfiguration);
assertThatThrownBy(() -> underTest.setRefreshInterval(0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("refreshInterval must be either -1 or strictly positive");
}
@Test
public void setRefreshInterval_fails_with_IAE_if_argument_is_less_than_minus_1() {
SettingsConfiguration.Builder underTest = newBuilder(mockConfiguration);
assertThatThrownBy(() -> underTest.setRefreshInterval(-2 - new Random().nextInt(10)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("refreshInterval must be either -1 or strictly positive");
}
@Test
public void setRefreshInterval_accepts_minus_1() {
SettingsConfiguration.Builder underTest = newBuilder(mockConfiguration);
assertThat(underTest.setRefreshInterval(-1).build().getRefreshInterval()).isEqualTo(-1);
}
@Test
public void setRefreshInterval_accepts_any_int_greater_than_1() {
SettingsConfiguration.Builder underTest = newBuilder(mockConfiguration);
int value = 1 + new Random().nextInt(200);
assertThat(underTest.setRefreshInterval(value).build().getRefreshInterval()).isEqualTo(value);
}
@Test
public void getRefreshInterval_returns_30_when_not_explicitly_set() {
assertThat(newBuilder(mockConfiguration).build().getRefreshInterval()).isEqualTo(30);
}
}
| 4,505 | 36.239669 | 102 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/SearchOptionsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import java.io.StringWriter;
import org.junit.Test;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.test.JsonAssert;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class SearchOptionsTest {
private SearchOptions underTest = new SearchOptions();
@Test
public void defaults() {
SearchOptions options = new SearchOptions();
assertThat(options.getFacets()).isEmpty();
assertThat(options.getFields()).isEmpty();
assertThat(options.getOffset()).isZero();
assertThat(options.getLimit()).isEqualTo(10);
assertThat(options.getPage()).isOne();
}
@Test
public void page_shortcut_for_limit_and_offset() {
SearchOptions options = new SearchOptions().setPage(3, 10);
assertThat(options.getLimit()).isEqualTo(10);
assertThat(options.getOffset()).isEqualTo(20);
}
@Test
public void page_starts_at_one() {
SearchOptions options = new SearchOptions().setPage(1, 10);
assertThat(options.getLimit()).isEqualTo(10);
assertThat(options.getOffset()).isZero();
assertThat(options.getPage()).isOne();
}
@Test
public void fail_if_page_is_not_strictly_positive() {
assertThatThrownBy(() -> new SearchOptions().setPage(0, 10))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Page must be greater or equal to 1 (got 0)");
}
@Test
public void fail_if_ps_is_zero() {
assertThatThrownBy(() -> new SearchOptions().setPage(1, 0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Page size must be between 1 and 500 (got 0)");
}
@Test
public void fail_if_ps_is_negative() {
assertThatThrownBy(() -> new SearchOptions().setPage(2, -1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Page size must be between 1 and 500 (got -1)");
}
@Test
public void fail_if_ps_is_over_limit() {
assertThatThrownBy(() -> new SearchOptions().setPage(3, SearchOptions.MAX_PAGE_SIZE + 10))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Page size must be between 1 and 500 (got 510)");
}
@Test
public void fail_if_result_after_first_10_000() {
assertThatThrownBy(() -> underTest.setPage(21, 500))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Can return only the first 10000 results. 10500th result asked.");
}
@Test
public void max_limit() {
SearchOptions options = new SearchOptions().setLimit(42);
assertThat(options.getLimit()).isEqualTo(42);
assertThatThrownBy(() -> options.setLimit(SearchOptions.MAX_PAGE_SIZE + 10))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Page size must be between 1 and 500 (got 510)");
}
@Test
public void writeJson() {
SearchOptions options = new SearchOptions().setPage(3, 10);
StringWriter json = new StringWriter();
JsonWriter jsonWriter = JsonWriter.of(json).beginObject();
options.writeJson(jsonWriter, 42L);
jsonWriter.endObject().close();
JsonAssert.assertJson(json.toString()).isSimilarTo("{\"total\": 42, \"p\": 3, \"ps\": 10}");
}
}
| 4,023 | 33.101695 | 96 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/SortingTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import java.util.List;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public class SortingTest {
@Test
public void test_definition() {
Sorting sorting = new Sorting();
sorting.add("fileLine", "file");
sorting.add("fileLine", "line").missingLast().reverse();
List<Sorting.Field> fields = sorting.getFields("fileLine");
assertThat(fields).hasSize(2);
assertThat(fields.get(0).getName()).isEqualTo("file");
assertThat(fields.get(0).isReverse()).isFalse();
assertThat(fields.get(0).isMissingLast()).isFalse();
assertThat(fields.get(1).getName()).isEqualTo("line");
assertThat(fields.get(1).isReverse()).isTrue();
assertThat(fields.get(1).isMissingLast()).isTrue();
}
@Test
public void ascending_sort_on_single_field() {
Sorting sorting = new Sorting();
sorting.add("updatedAt");
List<FieldSortBuilder> fields = sorting.fill("updatedAt", true);
assertThat(fields).hasSize(1);
expectField(fields.get(0), "updatedAt", "_first", SortOrder.ASC);
}
@Test
public void descending_sort_on_single_field() {
Sorting sorting = new Sorting();
sorting.add("updatedAt");
List<FieldSortBuilder> fields = sorting.fill("updatedAt", false);
assertThat(fields).hasSize(1);
expectField(fields.get(0), "updatedAt", "_last", SortOrder.DESC);
}
@Test
public void ascending_sort_on_single_field_with_missing_in_last_position() {
Sorting sorting = new Sorting();
sorting.add("updatedAt").missingLast();
List<FieldSortBuilder> fields = sorting.fill("updatedAt", true);
assertThat(fields).hasSize(1);
expectField(fields.get(0), "updatedAt", "_last", SortOrder.ASC);
}
@Test
public void descending_sort_on_single_field_with_missing_in_last_position() {
Sorting sorting = new Sorting();
sorting.add("updatedAt").missingLast();
List<FieldSortBuilder> fields = sorting.fill("updatedAt", false);
assertThat(fields).hasSize(1);
expectField(fields.get(0), "updatedAt", "_first", SortOrder.DESC);
}
@Test
public void sort_on_multiple_fields() {
// asc => file asc, line asc, severity desc, key asc
Sorting sorting = new Sorting();
sorting.add("fileLine", "file");
sorting.add("fileLine", "line");
sorting.add("fileLine", "severity").reverse();
sorting.add("fileLine", "key").missingLast();
List<FieldSortBuilder> fields = sorting.fill("fileLine", true);
assertThat(fields).hasSize(4);
expectField(fields.get(0), "file", "_first", SortOrder.ASC);
expectField(fields.get(1), "line", "_first", SortOrder.ASC);
expectField(fields.get(2), "severity", "_first", SortOrder.DESC);
expectField(fields.get(3), "key", "_last", SortOrder.ASC);
}
@Test
public void fail_if_unknown_field() {
Sorting sorting = new Sorting();
sorting.add("file");
try {
sorting.fill("unknown", true);
fail();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage()).isEqualTo("Bad sort field: unknown");
}
}
@Test
public void default_sorting() {
Sorting sorting = new Sorting();
sorting.addDefault("file");
List<FieldSortBuilder> fields = sorting.fillDefault();
assertThat(fields).hasSize(1);
}
private void expectField(FieldSortBuilder field, String expectedField, String expectedMissing, SortOrder expectedSort) {
assertThat(field.getFieldName()).isEqualTo(expectedField);
assertThat(field.missing()).isEqualTo(expectedMissing);
assertThat(field.order()).isEqualTo(expectedSort);
}
}
| 4,580 | 33.186567 | 122 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/StartupIndexerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es;
import java.util.Collections;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.es.StartupIndexer.Type.SYNCHRONOUS;
public class StartupIndexerTest {
private final StartupIndexer underTest = () -> null;
@Test
public void getType() {
Assertions.assertThat(underTest.getType()).isEqualTo(SYNCHRONOUS);
}
@Test
public void triggerAsyncIndexOnStartup() {
assertThatThrownBy(() -> underTest.triggerAsyncIndexOnStartup(Collections.emptySet()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("ASYNCHRONOUS StartupIndexer must implement initAsyncIndexOnStartup");
}
@Test
public void indexOnStartup() {
assertThatThrownBy(() -> underTest.indexOnStartup(Collections.emptySet()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("SYNCHRONOUS StartupIndexer must implement indexOnStartup");
}
}
| 1,843 | 34.461538 | 90 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/metadata/MetadataIndexDefinitionBridge.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.metadata;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.es.IndexDefinition;
class MetadataIndexDefinitionBridge implements IndexDefinition {
@Override
public void define(IndexDefinitionContext context) {
new MetadataIndexDefinition(new MapSettings().asConfig()).define(context);
}
}
| 1,194 | 37.548387 | 78 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/FieldAwareTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.newindex;
import java.util.Random;
import java.util.function.BiConsumer;
import java.util.stream.Stream;
import org.junit.Test;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Fail.fail;
public class FieldAwareTest {
@Test
public void indexType_is_a_reserved_field_name_whatever_the_case() {
Stream<BiConsumer<TestFieldAware, String>> fieldSetters = Stream.of(
(testFieldAware, fieldName) -> testFieldAware.createBooleanField(fieldName),
(testFieldAware, fieldName) -> testFieldAware.createByteField(fieldName),
(testFieldAware, fieldName) -> testFieldAware.createDateTimeField(fieldName),
(testFieldAware, fieldName) -> testFieldAware.createDoubleField(fieldName),
(testFieldAware, fieldName) -> testFieldAware.createIntegerField(fieldName),
(testFieldAware, fieldName) -> testFieldAware.createLongField(fieldName),
(testFieldAware, fieldName) -> testFieldAware.keywordFieldBuilder(fieldName).build(),
(testFieldAware, fieldName) -> testFieldAware.textFieldBuilder(fieldName).build(),
(testFieldAware, fieldName) -> testFieldAware.nestedFieldBuilder(fieldName).addKeywordField("foo").build()
);
fieldSetters.forEach(c -> {
TestFieldAware underTest = new TestFieldAware();
// should not fail for other field name
c.accept(underTest, randomAlphabetic(1 + new Random().nextInt(10)));
// fails whatever the case
Stream.of("indexType", "indextype", "InDexType", "INDEXTYPE")
.forEach(illegalFieldName -> {
try {
c.accept(underTest, illegalFieldName);
fail("should have thrown a IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("indexType is a reserved field name");
}
});
});
}
private static class TestFieldAware extends FieldAware<TestFieldAware> {
private String fieldName;
private Object attributes;
@Override
TestFieldAware setFieldImpl(String fieldName, Object attributes) {
this.fieldName = fieldName;
this.attributes = attributes;
return this;
}
}
}
| 3,124 | 40.118421 | 112 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewAuthorizedIndexTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.newindex;
import com.google.common.collect.ImmutableMap;
import java.util.Locale;
import java.util.Map;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.es.Index;
import org.sonar.server.es.IndexType;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder;
public class NewAuthorizedIndexTest {
private String someIndexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH);
private Index someIndex = Index.withRelations(someIndexName);
private MapSettings settings = new MapSettings();
private SettingsConfiguration defaultSettingsConfiguration = newBuilder(settings.asConfig()).build();
@Test
public void constructor_fails_with_IAE_if_index_does_not_support_relations() {
Index simpleIndex = Index.simple(someIndexName);
assertThatThrownBy(() -> new NewAuthorizedIndex(simpleIndex, defaultSettingsConfiguration))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index must accept relations");
}
@Test
public void getMainType_returns_main_type_of_authorization_for_index_of_constructor() {
NewAuthorizedIndex underTest = new NewAuthorizedIndex(someIndex, defaultSettingsConfiguration);
assertThat(underTest.getMainType()).isEqualTo(IndexType.main(someIndex, "auth"));
}
@Test
public void build_fails_if_no_relation_mapping_has_been_created() {
NewAuthorizedIndex underTest = new NewAuthorizedIndex(someIndex, defaultSettingsConfiguration);
assertThatThrownBy(() -> underTest.build())
.isInstanceOf(IllegalStateException.class)
.hasMessage("At least one relation mapping must be defined");
}
@Test
public void build_enforces_routing() {
NewAuthorizedIndex underTest = new NewAuthorizedIndex(someIndex, defaultSettingsConfiguration);
underTest.createTypeMapping(IndexType.relation(underTest.getMainType(), "donut"));
BuiltIndex<NewAuthorizedIndex> builtIndex = underTest.build();
assertThat(getAttributeAsMap(builtIndex, "_routing"))
.containsOnly(entry("required", true));
}
@Test
public void build_defines_type_field() {
NewAuthorizedIndex underTest = new NewAuthorizedIndex(someIndex, defaultSettingsConfiguration);
underTest.createTypeMapping(IndexType.relation(underTest.getMainType(), "donut"));
BuiltIndex<NewAuthorizedIndex> builtIndex = underTest.build();
Map<String, Object> properties = getProperties(builtIndex);
assertThat(getFieldAsMap(properties, "indexType"))
.isEqualTo(ImmutableMap.of(
"type", "keyword",
"norms", false,
"store", false,
"doc_values", false));
}
@Test
public void constructor_creates_mapping_for_authorization_type() {
NewAuthorizedIndex underTest = new NewAuthorizedIndex(someIndex, defaultSettingsConfiguration);
underTest.createTypeMapping(IndexType.relation(underTest.getMainType(), "donut"));
BuiltIndex<NewAuthorizedIndex> builtIndex = underTest.build();
Map<String, Object> properties = getProperties(builtIndex);
assertThat(getFieldAsMap(properties, "auth_groupIds"))
.contains(entry("type", "keyword"));
assertThat(getFieldAsMap(properties, "auth_userIds"))
.contains(entry("type", "keyword"));
assertThat(getFieldAsMap(properties, "auth_allowAnyone"))
.containsOnly(entry("type", "boolean"));
}
private static Map<String, Object> getProperties(BuiltIndex<?> index) {
return getAttributeAsMap(index, "properties");
}
@SuppressWarnings("unchecked")
private static Map<String, Object> getAttributeAsMap(BuiltIndex<?> index, String attributeKey) {
return (Map<String, Object>) index.getAttributes().get(attributeKey);
}
@SuppressWarnings("unchecked")
private Map<String, Object> getFieldAsMap(Map<String, Object> properties, String fieldName) {
return (Map<String, Object>) properties.get(fieldName);
}
}
| 5,014 | 39.12 | 103 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewIndexTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.newindex;
import com.google.common.collect.ImmutableMap;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Map;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.common.settings.Settings;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.es.Index;
import org.sonar.server.es.IndexType;
import org.sonar.server.es.IndexType.IndexMainType;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.data.MapEntry.entry;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED;
import static org.sonar.process.ProcessProperties.Property.SEARCH_REPLICAS;
import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder;
@RunWith(DataProviderRunner.class)
public class NewIndexTest {
private static final String someIndexName = randomAlphabetic(5).toLowerCase();
private MapSettings settings = new MapSettings();
private SettingsConfiguration defaultSettingsConfiguration = newBuilder(settings.asConfig()).build();
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void getRelations_returns_empty_if_no_relation_added(Index index) {
NewIndex<?> newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), defaultSettingsConfiguration);
assertThat(newIndex.getRelations()).isEmpty();
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void does_not_enable_all_field(Index index) {
SimplestNewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), defaultSettingsConfiguration);
// _all field is deprecated in 6.X and will be removed in 7.x and should not be used
assertThat(newIndex.getAttributes().get("_all")).isNull();
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void verify_default_index_settings_in_standalone(Index index) {
Settings underTest = new SimplestNewIndex(IndexType.main(index, "foo"), defaultSettingsConfiguration)
.getSettings().build();
assertThat(underTest.get("index.number_of_shards")).isNotEmpty();
// index.mapper.dynamic is deprecated and should not be set anymore
assertThat(underTest.get("index.mapper.dynamic")).isNull();
assertThat(underTest.get("index.refresh_interval")).isEqualTo("30s");
// setting "mapping.single_type" has been dropped in 6.X because multi type indices are not supported anymore
assertThat(underTest.get("mapping.single_type")).isNull();
assertThat(underTest.get("index.number_of_shards")).isEqualTo("1");
assertThat(underTest.get("index.number_of_replicas")).isEqualTo("0");
assertThat(underTest.get("index.max_ngram_diff")).isEqualTo("13");
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void verify_default_index_settings_in_cluster(Index index) {
settings.setProperty(CLUSTER_ENABLED.getKey(), "true");
Settings underTest = new SimplestNewIndex(IndexType.main(index, "foo"), defaultSettingsConfiguration).getSettings().build();
// _all field is deprecated in ES 6.X and will be removed in 7.X
assertThat(underTest.get("_all")).isNull();
assertThat(underTest.get("index.number_of_shards")).isNotEmpty();
assertThat(underTest.get("index.refresh_interval")).isEqualTo("30s");
// setting "mapping.single_type" has been dropped in 6.X because multi type indices are not supported anymore
assertThat(underTest.get("mapping.single_type")).isNull();
assertThat(underTest.get("index.number_of_shards")).isEqualTo("1");
assertThat(underTest.get("index.number_of_replicas")).isEqualTo("1");
assertThat(underTest.get("index.max_ngram_diff")).isEqualTo("13");
}
@Test
@UseDataProvider("indexAndTypeMappings")
public void define_fields(NewIndex<?> newIndex, TypeMapping typeMapping) {
typeMapping.setField("foo_field", ImmutableMap.of("type", "keyword"));
typeMapping.createBooleanField("boolean_field");
typeMapping.createByteField("byte_field");
typeMapping.createDateTimeField("dt_field");
typeMapping.createDoubleField("double_field");
typeMapping.createIntegerField("int_field");
typeMapping.createLongField("long_field");
typeMapping.createShortField("short_field");
typeMapping.createUuidPathField("uuid_path_field");
assertThat(newIndex.getProperty("foo_field")).isInstanceOf(Map.class);
assertThat((Map) newIndex.getProperty("foo_field")).containsEntry("type", "keyword");
assertThat((Map) newIndex.getProperty("byte_field")).isNotEmpty();
assertThat((Map) newIndex.getProperty("double_field")).isNotEmpty();
assertThat((Map) newIndex.getProperty("dt_field")).isNotEmpty();
assertThat((Map) newIndex.getProperty("int_field")).containsEntry("type", "integer");
assertThat((Map) newIndex.getProperty("long_field")).isNotEmpty();
assertThat((Map) newIndex.getProperty("short_field")).isNotEmpty();
assertThat((Map) newIndex.getProperty("uuid_path_field")).isNotEmpty();
assertThat((Map) newIndex.getProperty("unknown")).isNull();
}
@Test
@UseDataProvider("indexAndTypeMappings")
public void define_string_field(NewIndex<?> newIndex, TypeMapping typeMapping) {
typeMapping.keywordFieldBuilder("basic_field").build();
typeMapping.keywordFieldBuilder("not_searchable_field").disableSearch().build();
typeMapping.keywordFieldBuilder("all_capabilities_field")
.addSubFields(
DefaultIndexSettingsElement.SEARCH_GRAMS_ANALYZER,
DefaultIndexSettingsElement.SEARCH_WORDS_ANALYZER,
DefaultIndexSettingsElement.SORTABLE_ANALYZER)
.build();
typeMapping.keywordFieldBuilder("dumb_text_storage")
.disableSearch()
.disableNorms()
.disableSortingAndAggregating()
.build();
Map<String, Object> props = (Map) newIndex.getProperty("basic_field");
assertThat(props).containsEntry("type", "keyword")
.containsEntry("index", "true");
assertThat(props.get("fields")).isNull();
props = (Map) newIndex.getProperty("not_searchable_field");
assertThat(props)
.containsEntry("type", "keyword")
.containsEntry("index", "false")
.containsEntry("norms", "true")
.containsEntry("store", "false")
.containsEntry("doc_values", "true");
assertThat(props.get("fields")).isNull();
props = (Map) newIndex.getProperty("all_capabilities_field");
assertThat(props).containsEntry("type", "keyword");
// no need to test values, it's not the scope of this test
assertThat((Map) props.get("fields")).isNotEmpty();
props = (Map) newIndex.getProperty("dumb_text_storage");
assertThat(props)
.containsEntry("type", "keyword")
.containsEntry("index", "false")
.containsEntry("norms", "false")
.containsEntry("store", "false")
.containsEntry("doc_values", "false");
assertThat(props.get("fields")).isNull();
}
@Test
@UseDataProvider("indexAndTypeMappings")
public void define_nested_field(NewIndex<?> newIndex, TypeMapping typeMapping) {
typeMapping.nestedFieldBuilder("measures")
.addKeywordField("key")
.addDoubleField("value")
.build();
Map<String, Object> result = (Map) newIndex.getProperty("measures");
assertThat(result).containsEntry("type", "nested");
Map<String, Map<String, Object>> subProperties = (Map) result.get("properties");
assertThat(subProperties.get("key")).containsEntry("type", "keyword");
assertThat(subProperties.get("value")).containsEntry("type", "double");
}
@Test
@UseDataProvider("indexAndTypeMappings")
public void fail_when_nested_with_no_field(NewIndex<?> newIndex, TypeMapping typeMapping) {
NestedFieldBuilder<TypeMapping> nestedFieldBuilder = typeMapping.nestedFieldBuilder("measures");
assertThatThrownBy(() -> nestedFieldBuilder.build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("At least one sub-field must be declared in nested property 'measures'");
}
@Test
@UseDataProvider("indexAndTypeMappings")
public void use_doc_values_by_default(NewIndex<?> newIndex, TypeMapping typeMapping) {
typeMapping.keywordFieldBuilder("the_doc_value").build();
Map<String, Object> props = (Map) newIndex.getProperty("the_doc_value");
assertThat(props)
.containsEntry("type", "keyword")
.containsEntry("doc_values", "true");
}
@DataProvider
public static Object[][] indexAndTypeMappings() {
String indexName = randomAlphabetic(5).toLowerCase();
MapSettings settings = new MapSettings();
SettingsConfiguration defaultSettingsConfiguration = newBuilder(settings.asConfig()).build();
Index index = Index.withRelations(indexName);
IndexMainType mainType = IndexType.main(index, "foo");
SimplestNewIndex newIndex = new SimplestNewIndex(mainType, defaultSettingsConfiguration);
TypeMapping mainMapping = newIndex.createTypeMapping(mainType);
TypeMapping relationMapping = newIndex.createTypeMapping(IndexType.relation(mainType, "bar"));
return new Object[][] {
{newIndex, mainMapping},
{newIndex, relationMapping},
};
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void default_shards_and_replicas(Index index) {
NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), newBuilder(settings.asConfig()).setDefaultNbOfShards(5).build());
assertThat(newIndex.getSettings().get(IndexMetadata.SETTING_NUMBER_OF_SHARDS)).isEqualTo("5");
assertThat(newIndex.getSettings().get(IndexMetadata.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("0");
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void five_shards_and_one_replica_by_default_on_cluster(Index index) {
settings.setProperty(CLUSTER_ENABLED.getKey(), "true");
NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), newBuilder(settings.asConfig()).setDefaultNbOfShards(5).build());
assertThat(newIndex.getSettings().get(IndexMetadata.SETTING_NUMBER_OF_SHARDS)).isEqualTo("5");
assertThat(newIndex.getSettings().get(IndexMetadata.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("1");
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void customize_number_of_shards(Index index) {
settings.setProperty("sonar.search." + index.getName() + ".shards", "3");
NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), newBuilder(settings.asConfig()).setDefaultNbOfShards(5).build());
assertThat(newIndex.getSetting(IndexMetadata.SETTING_NUMBER_OF_SHARDS)).isEqualTo("3");
// keep default value
assertThat(newIndex.getSetting(IndexMetadata.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("0");
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void default_number_of_replicas_on_standalone_instance_must_be_0(Index index) {
NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), newBuilder(settings.asConfig()).setDefaultNbOfShards(5).build());
assertThat(newIndex.getSettings().get(IndexMetadata.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("0");
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void default_number_of_replicas_on_non_enabled_cluster_must_be_0(Index index) {
settings.setProperty(CLUSTER_ENABLED.getKey(), "false");
NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), newBuilder(settings.asConfig()).setDefaultNbOfShards(5).build());
assertThat(newIndex.getSettings().get(IndexMetadata.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("0");
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void default_number_of_replicas_on_cluster_instance_must_be_1(Index index) {
settings.setProperty(CLUSTER_ENABLED.getKey(), "true");
NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), newBuilder(settings.asConfig()).setDefaultNbOfShards(5).build());
assertThat(newIndex.getSettings().get(IndexMetadata.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("1");
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void when_number_of_replicas_on_cluster_is_specified_to_zero_default_value_must_not_be_used(Index index) {
settings.setProperty(CLUSTER_ENABLED.getKey(), "true");
settings.setProperty(SEARCH_REPLICAS.getKey(), "0");
NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), newBuilder(settings.asConfig()).setDefaultNbOfShards(5).build());
assertThat(newIndex.getSettings().get(IndexMetadata.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("0");
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void index_defined_with_specified_number_of_replicas_when_cluster_enabled(Index index) {
settings.setProperty(CLUSTER_ENABLED.getKey(), "true");
settings.setProperty(SEARCH_REPLICAS.getKey(), "3");
NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), newBuilder(settings.asConfig()).setDefaultNbOfShards(5).build());
assertThat(newIndex.getSettings().get(IndexMetadata.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("3");
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void fail_when_replica_customization_cant_be_parsed(Index index) {
settings.setProperty(CLUSTER_ENABLED.getKey(), "true");
settings.setProperty(SEARCH_REPLICAS.getKey(), "ꝱꝲꝳପ");
SettingsConfiguration settingsConfiguration = newBuilder(settings.asConfig()).setDefaultNbOfShards(5).build();
IndexMainType mainType = IndexType.main(index, "foo");
assertThatThrownBy(() -> new SimplestNewIndex(mainType, settingsConfiguration))
.isInstanceOf(IllegalStateException.class)
.hasMessage("The property 'sonar.search.replicas' is not an int value: For input string: \"ꝱꝲꝳପ\"");
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void in_standalone_searchReplicas_is_not_overridable(Index index) {
settings.setProperty(SEARCH_REPLICAS.getKey(), "5");
NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), defaultSettingsConfiguration);
assertThat(newIndex.getSettings().get("index.number_of_replicas")).isEqualTo("0");
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void index_with_source(Index index) {
NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), defaultSettingsConfiguration);
newIndex.setEnableSource(true);
assertThat(newIndex).isNotNull();
assertThat(getAttributeAsMap(newIndex, "_source")).containsExactly(entry("enabled", true));
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void index_without_source(Index index) {
NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), defaultSettingsConfiguration);
newIndex.setEnableSource(false);
assertThat(getAttributeAsMap(newIndex, "_source")).containsExactly(entry("enabled", false));
}
@Test
public void createTypeMapping_with_IndexRelationType_fails_with_ISE_if_index_does_not_allow_relations() {
IndexType.IndexRelationType indexRelationType = IndexType.relation(IndexType.main(Index.withRelations(someIndexName), "bar"), "bar");
Index index = Index.simple(someIndexName);
IndexMainType mainType = IndexType.main(index, "foo");
NewIndex underTest = new NewIndex(index, defaultSettingsConfiguration) {
@Override
public IndexMainType getMainType() {
return mainType;
}
@Override
public BuiltIndex build() {
throw new UnsupportedOperationException("build not implemented");
}
};
assertThatThrownBy(() -> underTest.createTypeMapping(indexRelationType))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Index is not configured to accept relations. Update IndexDefinition.Descriptor instance for this index");
}
@DataProvider
public static Object[][] indexWithAndWithoutRelations() {
return new Object[][] {
{Index.simple(someIndexName)},
{Index.withRelations(someIndexName)}
};
}
private static Map<String, Object> getAttributeAsMap(NewIndex newIndex, String attributeKey) {
return (Map<String, Object>) newIndex.getAttributes().get(attributeKey);
}
private static final class SimplestNewIndex extends NewIndex<SimplestNewIndex> {
private final IndexMainType mainType;
public SimplestNewIndex(IndexMainType mainType, SettingsConfiguration settingsConfiguration) {
super(mainType.getIndex(), settingsConfiguration);
this.mainType = mainType;
}
@Override
public IndexMainType getMainType() {
return mainType;
}
@Override
public BuiltIndex<SimplestNewIndex> build() {
return new BuiltIndex<>(this);
}
}
}
| 17,843 | 43.947103 | 140 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewRegularIndexTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.newindex;
import com.google.common.collect.ImmutableMap;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Locale;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.es.Index;
import org.sonar.server.es.IndexType;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.sonar.server.es.newindex.DefaultIndexSettings.NORMS;
import static org.sonar.server.es.newindex.DefaultIndexSettings.STORE;
import static org.sonar.server.es.newindex.DefaultIndexSettings.TYPE;
import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder;
@RunWith(DataProviderRunner.class)
public class NewRegularIndexTest {
private static final String SOME_INDEX_NAME = randomAlphabetic(10).toLowerCase(Locale.ENGLISH);
private MapSettings settings = new MapSettings();
private SettingsConfiguration defaultSettingsConfiguration = newBuilder(settings.asConfig()).build();
@Test
@UseDataProvider("indexes")
public void getMainType_fails_with_ISE_if_createTypeMapping_with_IndexMainType_has_not_been_called(Index index) {
NewRegularIndex newIndex = new NewRegularIndex(index, defaultSettingsConfiguration);
assertThatThrownBy(() -> newIndex.getMainType())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Main type has not been defined");
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void createTypeMapping_with_IndexMainType_fails_with_ISE_if_called_twice(Index index) {
NewRegularIndex underTest = new NewRegularIndex(index, defaultSettingsConfiguration);
underTest.createTypeMapping(IndexType.main(index, "foo"));
assertThatThrownBy(() -> underTest.createTypeMapping(IndexType.main(index, "foo")))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Main type can only be defined once");
}
@Test
public void createTypeMapping_with_IndexRelationType_fails_with_ISE_if_called_before_createType_with_IndexMainType() {
Index index = Index.withRelations(SOME_INDEX_NAME);
NewRegularIndex underTest = new NewRegularIndex(index, defaultSettingsConfiguration);
assertThatThrownBy(() -> underTest.createTypeMapping(IndexType.relation(IndexType.main(index, "foo"), "bar")))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Mapping for main type must be created first");
}
@Test
public void createTypeMapping_with_IndexRelationType_fails_with_IAE_if_mainType_does_not_match_defined_one() {
Index index = Index.withRelations(SOME_INDEX_NAME);
IndexType.IndexMainType mainType = IndexType.main(index, "foo");
NewRegularIndex underTest = new NewRegularIndex(index, defaultSettingsConfiguration);
underTest.createTypeMapping(mainType);
assertThatThrownBy(() -> underTest.createTypeMapping(IndexType.relation(IndexType.main(index, "donut"), "bar")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("main type of relation must be "+ mainType);
}
@Test
@UseDataProvider("indexWithAndWithoutRelations")
public void build_fails_with_ISE_if_no_mainType_is_defined(Index index) {
NewRegularIndex underTest = new NewRegularIndex(index, defaultSettingsConfiguration);
assertThatThrownBy(() -> underTest.build())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Mapping for main type must be defined");
}
@DataProvider
public static Object[][] indexWithAndWithoutRelations() {
return new Object[][] {
{Index.simple(SOME_INDEX_NAME)},
{Index.withRelations(SOME_INDEX_NAME)}
};
}
@Test
public void build_fails_with_ISE_if_index_accepts_relations_and_none_is_defined() {
Index index = Index.withRelations(SOME_INDEX_NAME);
NewRegularIndex underTest = new NewRegularIndex(index, defaultSettingsConfiguration);
underTest.createTypeMapping(IndexType.main(index, "foo"));
assertThatThrownBy(() -> underTest.build())
.isInstanceOf(IllegalStateException.class)
.hasMessage("At least one relation must be defined when index accepts relations");
}
@Test
public void build_does_not_enforce_routing_if_mainType_does_not_accepts_relations() {
Index someIndex = Index.simple(SOME_INDEX_NAME);
NewRegularIndex underTest = new NewRegularIndex(someIndex, defaultSettingsConfiguration);
underTest.createTypeMapping(IndexType.main(someIndex, "foo"));
BuiltIndex<NewRegularIndex> builtIndex = underTest.build();
assertThat(builtIndex.getAttributes().get("_routing"))
.isNull();
}
@Test
public void build_enforces_routing_if_mainType_accepts_relations() {
Index someIndex = Index.withRelations(SOME_INDEX_NAME);
NewRegularIndex underTest = new NewRegularIndex(someIndex, defaultSettingsConfiguration);
underTest.createTypeMapping(IndexType.main(someIndex, "foo"));
underTest.createTypeMapping(IndexType.relation(underTest.getMainType(), "bar"));
BuiltIndex<NewRegularIndex> builtIndex = underTest.build();
assertThat((Map<String, Object>) builtIndex.getAttributes().get("_routing"))
.contains(entry("required", true));
}
@Test
public void build_does_not_define_type_field_if_index_does_not_accept_relations() {
Index someIndex = Index.simple(SOME_INDEX_NAME);
NewRegularIndex underTest = new NewRegularIndex(someIndex, defaultSettingsConfiguration);
underTest.createTypeMapping(IndexType.main(someIndex, "foo"));
BuiltIndex<NewRegularIndex> builtIndex = underTest.build();
Map<String, Object> properties = (Map<String, Object>) builtIndex.getAttributes().get("properties");
assertThat(properties.get("indexType"))
.isNull();
}
@Test
public void build_defines_type_field_if_index_accepts_relations() {
Index someIndex = Index.withRelations(SOME_INDEX_NAME);
NewRegularIndex underTest = new NewRegularIndex(someIndex, defaultSettingsConfiguration);
underTest.createTypeMapping(IndexType.main(someIndex, "foo"));
underTest.createTypeMapping(IndexType.relation(underTest.getMainType(), "bar"));
BuiltIndex<NewRegularIndex> builtIndex = underTest.build();
Map<String, Object> properties = (Map<String, Object>) builtIndex.getAttributes().get("properties");
assertThat((Map) properties.get("indexType"))
.isEqualTo(ImmutableMap.of(
TYPE, "keyword",
NORMS, false,
STORE, false,
"doc_values", false));
}
@DataProvider
public static Object[][] indexes() {
String someIndexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH);
return new Object[][] {
{Index.simple(someIndexName)},
{Index.withRelations(someIndexName)}
};
}
}
| 7,907 | 40.84127 | 120 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/TestNewIndex.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.newindex;
import org.sonar.server.es.IndexType;
public final class TestNewIndex extends NewIndex<TestNewIndex> {
private final IndexType.IndexMainType mainType;
private final TypeMapping mainTypeMapping;
public TestNewIndex(IndexType.IndexMainType mainType, SettingsConfiguration settingsConfiguration) {
super(mainType.getIndex(), settingsConfiguration);
this.mainType = mainType;
mainTypeMapping = super.createTypeMapping(mainType);
}
@Override
public IndexType.IndexMainType getMainType() {
return mainType;
}
public TypeMapping getMainTypeMapping() {
return mainTypeMapping;
}
@Override
public BuiltIndex<TestNewIndex> build() {
return new BuiltIndex<>(this);
}
public TestNewIndex addRelation(String name) {
super.createTypeMapping(IndexType.relation(mainType, name));
return this;
}
public TypeMapping createRelationMapping(String name) {
return super.createTypeMapping(IndexType.relation(mainType, name));
}
}
| 1,864 | 31.719298 | 102 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/response/ClusterStatsResponseTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ClusterStatsResponseTest {
private static final String EXAMPLE_JSON = "{" +
" \"status\": \"yellow\"," +
" \"nodes\": {" +
" \"count\": {" +
" \"total\": 3" +
" }" +
" }" +
"}";
@Test
public void should_parse_example_json() {
JsonObject jsonObject = getExampleAsJsonObject();
ClusterStatsResponse clusterStatsResponse = ClusterStatsResponse.toClusterStatsResponse(jsonObject);
assertThat(clusterStatsResponse.getHealthStatus()).isEqualTo(ClusterHealthStatus.YELLOW);
assertThat(clusterStatsResponse.getNodeCount()).isEqualTo(3);
}
private static JsonObject getExampleAsJsonObject() {
return new Gson().fromJson(EXAMPLE_JSON, JsonObject.class);
}
}
| 1,829 | 33.528302 | 104 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/response/IndicesStatsResponseTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.Collection;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class IndicesStatsResponseTest {
private static final String EXAMPLE_JSON = "{" +
" \"indices\": {" +
" \"index-1\": {" +
" \"primaries\": {" +
" \"docs\": {" +
" \"count\": 1234" +
" }," +
" \"store\": {" +
" \"size_in_bytes\": 56789" +
" }" +
" }," +
" \"shards\": {" +
" \"shard-1\": {}," +
" \"shard-2\": {}" +
" }" +
" }," +
" \"index-2\": {" +
" \"primaries\": {" +
" \"docs\": {" +
" \"count\": 42" +
" }," +
" \"store\": {" +
" \"size_in_bytes\": 123" +
" }" +
" }," +
" \"shards\": {" +
" \"shard-1\": {}," +
" \"shard-2\": {}" +
" }" +
" }" +
" }" +
"}";
@Test
public void should_parse_example_json() {
JsonObject jsonObject = getExampleAsJsonObject();
IndicesStatsResponse indicesStatsResponse = IndicesStatsResponse.toIndicesStatsResponse(jsonObject);
Collection<IndexStats> allIndexStats = indicesStatsResponse.getAllIndexStats();
assertThat(allIndexStats)
.hasSize(2)
.extracting("name")
.contains("index-1", "index-2");
IndexStats indexStats = allIndexStats.stream().filter(i -> i.getName().equals("index-1")).findFirst().get();
assertThat(indexStats.getDocCount()).isEqualTo(1234);
assertThat(indexStats.getShardsCount()).isEqualTo(2);
assertThat(indexStats.getStoreSizeBytes()).isEqualTo(56789);
indexStats = allIndexStats.stream().filter(i -> i.getName().equals("index-2")).findFirst().get();
assertThat(indexStats.getDocCount()).isEqualTo(42);
assertThat(indexStats.getStoreSizeBytes()).isEqualTo(123);
assertThat(indexStats.getShardsCount()).isEqualTo(2);
}
private static JsonObject getExampleAsJsonObject() {
return new Gson().fromJson(EXAMPLE_JSON, JsonObject.class);
}
}
| 3,046 | 32.855556 | 112 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/response/NodeStatsResponseTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class NodeStatsResponseTest {
private final static String EXAMPLE_JSON = "{" +
" \"nodes\": {" +
" \"YnKPZcbGRamRQGxjErLWoQ\": {" +
" \"name\": \"sonarqube\"," +
" \"host\": \"127.0.0.1\"," +
" \"indices\": {" +
" \"docs\": {" +
" \"count\": 13557" +
" }," +
" \"store\": {" +
" \"size_in_bytes\": 8670970" +
" }," +
" \"query_cache\": {" +
" \"memory_size_in_bytes\": 0" +
" }," +
" \"fielddata\": {" +
" \"memory_size_in_bytes\": 4880" +
" }," +
" \"translog\": {" +
" \"size_in_bytes\": 8274137" +
" }," +
" \"request_cache\": {" +
" \"memory_size_in_bytes\": 0" +
" }" +
" }," +
" \"process\": {" +
" \"open_file_descriptors\": 296," +
" \"max_file_descriptors\": 10240," +
" \"cpu\": {" +
" \"percent\": 7" +
" }" +
" }," +
" \"jvm\": {" +
" \"mem\": {" +
" \"heap_used_in_bytes\": 158487160," +
" \"heap_used_percent\": 30," +
" \"heap_max_in_bytes\": 518979584," +
" \"non_heap_used_in_bytes\": 109066592" +
" }," +
" \"threads\": {" +
" \"count\": 70" +
" }" +
" }," +
" \"fs\": {" +
" \"total\": {" +
" \"total_in_bytes\": 250685575168," +
" \"free_in_bytes\": 142843138048," +
" \"available_in_bytes\": 136144027648" +
" }" +
" }," +
" \"breakers\": {" +
" \"request\": {" +
" \"limit_size_in_bytes\": 311387750," +
" \"estimated_size_in_bytes\": 1" +
" }," +
" \"fielddata\": {" +
" \"limit_size_in_bytes\": 207591833," +
" \"estimated_size_in_bytes\": 4880" +
" }" +
" }" +
" }" +
" }" +
"}";
@Test
public void should_parse_example_json() {
JsonObject jsonObject = getExampleAsJsonObject();
NodeStatsResponse nodeStatsResponse = NodeStatsResponse.toNodeStatsResponse(jsonObject);
assertThat(nodeStatsResponse.getNodeStats()).hasSize(1);
NodeStats nodeStats = nodeStatsResponse.getNodeStats().get(0);
assertThat(nodeStats.getName()).isEqualTo("sonarqube");
assertThat(nodeStats.getHost()).isEqualTo("127.0.0.1");
assertThat(nodeStats.getCpuUsage()).isEqualTo(7);
assertThat(nodeStats.getOpenFileDescriptors()).isEqualTo(296);
assertThat(nodeStats.getMaxFileDescriptors()).isEqualTo(10240);
assertThat(nodeStats.getDiskAvailableBytes()).isEqualTo(136144027648L);
assertThat(nodeStats.getDiskTotalBytes()).isEqualTo(250685575168L);
assertThat(nodeStats.getFieldDataCircuitBreakerLimit()).isEqualTo(207591833);
assertThat(nodeStats.getFieldDataCircuitBreakerEstimation()).isEqualTo(4880);
assertThat(nodeStats.getRequestCircuitBreakerLimit()).isEqualTo(311387750L);
assertThat(nodeStats.getRequestCircuitBreakerEstimation()).isOne();
JvmStats jvmStats = nodeStats.getJvmStats();
assertThat(jvmStats).isNotNull();
assertThat(jvmStats.getHeapUsedPercent()).isEqualTo(30);
assertThat(jvmStats.getHeapUsedInBytes()).isEqualTo(158487160);
assertThat(jvmStats.getHeapMaxInBytes()).isEqualTo(518979584);
assertThat(jvmStats.getNonHeapUsedInBytes()).isEqualTo(109066592);
assertThat(jvmStats.getThreadCount()).isEqualTo(70);
IndicesStats indicesStats = nodeStats.getIndicesStats();
assertThat(indicesStats).isNotNull();
assertThat(indicesStats.getStoreSizeInBytes()).isEqualTo(8670970);
assertThat(indicesStats.getTranslogSizeInBytes()).isEqualTo(8274137);
assertThat(indicesStats.getRequestCacheMemorySizeInBytes()).isZero();
assertThat(indicesStats.getFieldDataMemorySizeInBytes()).isEqualTo(4880);
assertThat(indicesStats.getQueryCacheMemorySizeInBytes()).isZero();
}
private static JsonObject getExampleAsJsonObject() {
return new Gson().fromJson(EXAMPLE_JSON, JsonObject.class);
}
}
| 5,234 | 37.211679 | 92 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/AllFiltersTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.searchrequest;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.junit.Test;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.FilterScope;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.mockito.Mockito.mock;
public class AllFiltersTest {
@Test
public void newalways_returns_a_new_instance() {
int expected = 1 + new Random().nextInt(200);
RequestFiltersComputer.AllFilters[] instances = IntStream.range(0, expected)
.mapToObj(t -> RequestFiltersComputer.newAllFilters())
.toArray(RequestFiltersComputer.AllFilters[]::new);
assertThat(instances).hasSize(expected);
}
@Test
public void addFilter_fails_if_name_is_null() {
FilterScope filterScope = mock(FilterScope.class);
RequestFiltersComputer.AllFilters allFilters = RequestFiltersComputer.newAllFilters();
BoolQueryBuilder boolQuery = boolQuery();
assertThatThrownBy(() -> allFilters.addFilter(null, filterScope, boolQuery))
.isInstanceOf(NullPointerException.class)
.hasMessage("name can't be null");
}
@Test
public void addFilter_fails_if_fieldname_is_null() {
String name = randomAlphabetic(12);
RequestFiltersComputer.AllFilters allFilters = RequestFiltersComputer.newAllFilters();
BoolQueryBuilder boolQuery = boolQuery();
assertThatThrownBy(() -> allFilters.addFilter(name, null, boolQuery))
.isInstanceOf(NullPointerException.class)
.hasMessage("filterScope can't be null");
}
@Test
public void addFilter_fails_if_field_with_name_already_exists() {
String name1 = randomAlphabetic(12);
String name2 = randomAlphabetic(15);
FilterScope filterScope1 = mock(FilterScope.class);
FilterScope filterScope2 = mock(FilterScope.class);
RequestFiltersComputer.AllFilters allFilters = RequestFiltersComputer.newAllFilters();
allFilters.addFilter(name2, filterScope1, boolQuery());
Stream.<ThrowingCallable>of(
// exact same call
() -> allFilters.addFilter(name2, filterScope1, boolQuery()),
// call with a different fieldName
() -> allFilters.addFilter(name2, filterScope2, boolQuery()))
.forEach(t -> assertThatThrownBy(t)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("A filter with name " + name2 + " has already been added"));
}
@Test
public void addFilter_does_not_add_filter_if_QueryBuilder_is_null() {
String name = randomAlphabetic(12);
String name2 = randomAlphabetic(14);
RequestFiltersComputer.AllFilters allFilters = RequestFiltersComputer.newAllFilters();
BoolQueryBuilder query = boolQuery();
allFilters.addFilter(name, mock(FilterScope.class), query)
.addFilter(name2, mock(FilterScope.class), null);
List<QueryBuilder> all = allFilters.stream().toList();
assertThat(all).hasSize(1);
assertThat(all.iterator().next()).isSameAs(query);
}
@Test
public void stream_is_empty_when_addFilter_never_called() {
RequestFiltersComputer.AllFilters allFilters = RequestFiltersComputer.newAllFilters();
assertThat(allFilters.stream()).isEmpty();
}
}
| 4,432 | 38.936937 | 90 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/NestedFieldFilterScopeTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.searchrequest;
import org.junit.Test;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.NestedFieldFilterScope;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.SimpleFieldFilterScope;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class NestedFieldFilterScopeTest {
@Test
public void constructor_fails_with_NPE_if_fieldName_is_null() {
String nestedFieldName = randomAlphabetic(11);
String value = randomAlphabetic(12);
assertThatThrownBy(() -> new NestedFieldFilterScope<>(null, nestedFieldName, value))
.isInstanceOf(NullPointerException.class)
.hasMessage("fieldName can't be null");
}
@Test
public void constructor_fails_with_NPE_if_nestedFieldName_is_null() {
String fieldName = randomAlphabetic(10);
String value = randomAlphabetic(12);
assertThatThrownBy(() -> new NestedFieldFilterScope<>(fieldName, null, value))
.isInstanceOf(NullPointerException.class)
.hasMessage("nestedFieldName can't be null");
}
@Test
public void constructor_fails_with_NPE_if_value_is_null() {
String fieldName = randomAlphabetic(10);
String nestedFieldName = randomAlphabetic(11);
assertThatThrownBy(() -> new NestedFieldFilterScope<>(fieldName, nestedFieldName, null))
.isInstanceOf(NullPointerException.class)
.hasMessage("value can't be null");
}
@Test
public void verify_getters() {
String fieldName = randomAlphabetic(10);
String nestedFieldName = randomAlphabetic(11);
Object value = new Object();
NestedFieldFilterScope<Object> underTest = new NestedFieldFilterScope<>(fieldName, nestedFieldName, value);
assertThat(underTest.getFieldName()).isEqualTo(fieldName);
assertThat(underTest.getNestedFieldName()).isEqualTo(nestedFieldName);
assertThat(underTest.getNestedFieldValue()).isSameAs(value);
}
@Test
public void verify_equals() {
String fieldName = randomAlphabetic(10);
String nestedFieldName = randomAlphabetic(11);
Object value = new Object();
String fieldName2 = randomAlphabetic(12);
String nestedFieldName2 = randomAlphabetic(13);
Object value2 = new Object();
NestedFieldFilterScope<Object> underTest = new NestedFieldFilterScope<>(fieldName, nestedFieldName, value);
assertThat(underTest)
.isEqualTo(underTest)
.isEqualTo(new NestedFieldFilterScope<>(fieldName, nestedFieldName, value))
.isNotNull()
.isNotEqualTo(new Object())
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName2, nestedFieldName, value))
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName, nestedFieldName2, value))
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName, nestedFieldName, value2))
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName2, nestedFieldName2, value))
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName, nestedFieldName2, value2))
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName2, nestedFieldName, value2))
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName2, nestedFieldName2, value2))
.isNotEqualTo(new SimpleFieldFilterScope(fieldName))
.isNotEqualTo(new SimpleFieldFilterScope(fieldName2));
}
@Test
public void verify_hashcode() {
String fieldName = randomAlphabetic(10);
String nestedFieldName = randomAlphabetic(11);
Object value = new Object();
String fieldName2 = randomAlphabetic(12);
String nestedFieldName2 = randomAlphabetic(13);
Object value2 = new Object();
NestedFieldFilterScope<Object> underTest = new NestedFieldFilterScope<>(fieldName, nestedFieldName, value);
assertThat(underTest.hashCode())
.isEqualTo(underTest.hashCode())
.isEqualTo(new NestedFieldFilterScope<>(fieldName, nestedFieldName, value).hashCode());
assertThat(underTest.hashCode())
.isNotEqualTo(new Object().hashCode())
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName2, nestedFieldName, value).hashCode())
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName, nestedFieldName2, value).hashCode())
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName, nestedFieldName, value2).hashCode())
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName2, nestedFieldName2, value).hashCode())
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName, nestedFieldName2, value2).hashCode())
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName2, nestedFieldName, value2).hashCode())
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName2, nestedFieldName2, value2).hashCode())
.isNotEqualTo(new SimpleFieldFilterScope(fieldName).hashCode())
.isNotEqualTo(new SimpleFieldFilterScope(fieldName2)).hashCode();
}
@Test
public void verify_intersect() {
String fieldName = randomAlphabetic(10);
String nestedFieldName = randomAlphabetic(11);
Object value = new Object();
String fieldName2 = randomAlphabetic(12);
String nestedFieldName2 = randomAlphabetic(13);
Object value2 = new Object();
NestedFieldFilterScope<Object> underTest = new NestedFieldFilterScope<>(fieldName, nestedFieldName, value);
assertThat(underTest.intersect(underTest)).isTrue();
assertThat(underTest.intersect(new NestedFieldFilterScope<>(fieldName, nestedFieldName, value))).isTrue();
assertThat(underTest.intersect(new NestedFieldFilterScope<>(fieldName2, nestedFieldName, value))).isFalse();
assertThat(underTest.intersect(new NestedFieldFilterScope<>(fieldName, nestedFieldName2, value))).isFalse();
assertThat(underTest.intersect(new NestedFieldFilterScope<>(fieldName, nestedFieldName, value2))).isFalse();
assertThat(underTest.intersect(new NestedFieldFilterScope<>(fieldName2, nestedFieldName2, value))).isFalse();
assertThat(underTest.intersect(new NestedFieldFilterScope<>(fieldName, nestedFieldName2, value2))).isFalse();
assertThat(underTest.intersect(new NestedFieldFilterScope<>(fieldName2, nestedFieldName, value2))).isFalse();
assertThat(underTest.intersect(new NestedFieldFilterScope<>(fieldName2, nestedFieldName2, value2))).isFalse();
assertThat(underTest.intersect(new SimpleFieldFilterScope(fieldName))).isFalse();
assertThat(underTest.intersect(new SimpleFieldFilterScope(fieldName2))).isFalse();
}
}
| 7,283 | 47.885906 | 114 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/NestedFieldTopAggregationDefinitionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.searchrequest;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(DataProviderRunner.class)
public class NestedFieldTopAggregationDefinitionTest {
public static final Random RANDOM = new Random();
@Test
@UseDataProvider("notOneLevelDeepPaths")
public void constructor_supports_nestedFieldPath_only_one_level_deep(String unsupportedPath) {
String value = randomAlphabetic(7);
boolean sticky = RANDOM.nextBoolean();
assertThatThrownBy(() -> new NestedFieldTopAggregationDefinition<>(unsupportedPath, value, sticky))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Field path should have only one dot: " + unsupportedPath);
}
@DataProvider
public static Object[][] notOneLevelDeepPaths() {
return new Object[][] {
{""},
{" "},
{".."},
{"a.b."},
{"a.b.c"},
{".b.c"},
{"..."}
};
}
@Test
@UseDataProvider("emptyFieldNames")
public void constructor_fails_with_IAE_if_empty_field_name(String unsupportedPath, List<String> expectedParsedFieldNames) {
String value = randomAlphabetic(7);
assertThatThrownBy(() -> new NestedFieldTopAggregationDefinition<>(unsupportedPath, value, true))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("field path \"" + unsupportedPath + "\" should have exactly 2 non empty field names, got: " + expectedParsedFieldNames);
}
@DataProvider
public static Object[][] emptyFieldNames() {
String str1 = randomAlphabetic(6);
return new Object[][] {
{".", emptyList()},
{" . ", emptyList()},
{str1 + ".", singletonList(str1)},
{str1 + ". ", singletonList(str1)},
{"." + str1, singletonList(str1)},
{" . " + str1, singletonList(str1)}
};
}
@Test
public void constructor_parses_nested_field_path() {
String fieldName = randomAlphabetic(5);
String nestedFieldName = randomAlphabetic(6);
String value = randomAlphabetic(7);
boolean sticky = RANDOM.nextBoolean();
NestedFieldTopAggregationDefinition<String> underTest = new NestedFieldTopAggregationDefinition<>(fieldName + "." + nestedFieldName, value, sticky);
assertThat(underTest.getFilterScope().getFieldName()).isEqualTo(fieldName);
assertThat(underTest.getFilterScope().getNestedFieldName()).isEqualTo(nestedFieldName);
assertThat(underTest.getFilterScope().getNestedFieldValue()).isEqualTo(value);
assertThat(underTest.isSticky()).isEqualTo(sticky);
}
@Test
public void constructor_fails_with_NPE_if_nestedFieldPath_is_null() {
String value = randomAlphabetic(7);
boolean sticky = RANDOM.nextBoolean();
assertThatThrownBy(() -> new NestedFieldTopAggregationDefinition<>(null, value, sticky))
.isInstanceOf(NullPointerException.class)
.hasMessage("nestedFieldPath can't be null");
}
@Test
public void constructor_fails_with_NPE_if_value_is_null() {
String value = randomAlphabetic(7);
boolean sticky = RANDOM.nextBoolean();
assertThatThrownBy(() -> new NestedFieldTopAggregationDefinition<>(value, null, sticky))
.isInstanceOf(NullPointerException.class)
.hasMessage("value can't be null");
}
@Test
public void getFilterScope_always_returns_the_same_instance() {
String fieldName = randomAlphabetic(5);
String nestedFieldName = randomAlphabetic(6);
String value = randomAlphabetic(7);
boolean sticky = RANDOM.nextBoolean();
NestedFieldTopAggregationDefinition<String> underTest = new NestedFieldTopAggregationDefinition<>(fieldName + "." + nestedFieldName, value, sticky);
Set<TopAggregationDefinition.FilterScope> filterScopes = IntStream.range(0, 2 + RANDOM.nextInt(200))
.mapToObj(i -> underTest.getFilterScope())
.collect(Collectors.toSet());
assertThat(filterScopes).hasSize(1);
}
}
| 5,318 | 36.723404 | 152 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/RequestFiltersComputerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.searchrequest;
import com.google.common.collect.ImmutableSet;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Test;
import org.sonar.server.es.searchrequest.RequestFiltersComputer.AllFilters;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.FilterScope;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.NestedFieldFilterScope;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.SimpleFieldFilterScope;
import static com.google.common.base.Preconditions.checkState;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.mockito.Mockito.mock;
import static org.sonar.server.es.searchrequest.RequestFiltersComputer.newAllFilters;
import static org.sonar.server.es.searchrequest.TopAggregationDefinition.NON_STICKY;
import static org.sonar.server.es.searchrequest.TopAggregationDefinition.STICKY;
public class RequestFiltersComputerTest {
private static final Random RANDOM = new Random();
@Test
public void getTopAggregationFilters_fails_with_IAE_when_no_TopAggregation_provided_in_constructor() {
RequestFiltersComputer underTest = new RequestFiltersComputer(newAllFilters(), Collections.emptySet());
assertThatThrownBy(() -> underTest.getTopAggregationFilter(mock(TopAggregationDefinition.class)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("topAggregation must have been declared in constructor");
}
@Test
public void getTopAggregationFilters_fails_with_IAE_when_TopAggregation_was_not_provided_in_constructor() {
Set<TopAggregationDefinition<?>> atLeastOneTopAggs = randomNonEmptyTopAggregations(RANDOM::nextBoolean);
RequestFiltersComputer underTest = new RequestFiltersComputer(newAllFilters(), atLeastOneTopAggs);
atLeastOneTopAggs.forEach(underTest::getTopAggregationFilter);
assertThatThrownBy(() -> underTest.getTopAggregationFilter(mock(TopAggregationDefinition.class)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("topAggregation must have been declared in constructor");
}
@Test
public void getQueryFilters_returns_empty_if_AllFilters_is_empty() {
Set<TopAggregationDefinition<?>> atLeastOneTopAggs = randomNonEmptyTopAggregations(RANDOM::nextBoolean);
RequestFiltersComputer underTest = new RequestFiltersComputer(newAllFilters(), atLeastOneTopAggs);
assertThat(underTest.getQueryFilters()).isEmpty();
}
@Test
public void getPostFilters_returns_empty_if_AllFilters_is_empty() {
Set<TopAggregationDefinition<?>> atLeastOneTopAggs = randomNonEmptyTopAggregations(RANDOM::nextBoolean);
RequestFiltersComputer underTest = new RequestFiltersComputer(newAllFilters(), atLeastOneTopAggs);
assertThat(underTest.getPostFilters()).isEmpty();
}
@Test
public void getTopAggregationFilter_returns_empty_if_AllFilters_is_empty() {
Set<TopAggregationDefinition<?>> atLeastOneTopAggs = randomNonEmptyTopAggregations(RANDOM::nextBoolean);
RequestFiltersComputer underTest = new RequestFiltersComputer(newAllFilters(), atLeastOneTopAggs);
atLeastOneTopAggs.forEach(topAgg -> assertThat(underTest.getTopAggregationFilter(topAgg)).isEmpty());
}
@Test
public void getQueryFilters_contains_all_filters_when_no_declared_topAggregation() {
AllFilters allFilters = randomNonEmptyAllFilters();
RequestFiltersComputer underTest = new RequestFiltersComputer(allFilters, Collections.emptySet());
assertThat(underTest.getQueryFilters()).contains(toBoolQuery(allFilters.stream()));
}
@Test
public void getPostFilters_returns_empty_when_no_declared_topAggregation() {
AllFilters allFilters = randomNonEmptyAllFilters();
RequestFiltersComputer underTest = new RequestFiltersComputer(allFilters, Collections.emptySet());
assertThat(underTest.getPostFilters()).isEmpty();
}
@Test
public void getQueryFilters_contains_all_filters_when_no_declared_sticky_topAggregation() {
AllFilters allFilters = randomNonEmptyAllFilters();
Set<TopAggregationDefinition<?>> atLeastOneNonStickyTopAggs = randomNonEmptyTopAggregations(() -> false);
RequestFiltersComputer underTest = new RequestFiltersComputer(allFilters, atLeastOneNonStickyTopAggs);
assertThat(underTest.getQueryFilters()).contains(toBoolQuery(allFilters.stream()));
}
@Test
public void getPostFilters_returns_empty_when_no_declared_sticky_topAggregation() {
AllFilters allFilters = randomNonEmptyAllFilters();
Set<TopAggregationDefinition<?>> atLeastOneNonStickyTopAggs = randomNonEmptyTopAggregations(() -> false);
RequestFiltersComputer underTest = new RequestFiltersComputer(allFilters, atLeastOneNonStickyTopAggs);
assertThat(underTest.getPostFilters()).isEmpty();
}
@Test
public void getTopAggregationFilters_return_empty_when_no_declared_sticky_topAggregation() {
AllFilters allFilters = randomNonEmptyAllFilters();
Set<TopAggregationDefinition<?>> atLeastOneNonStickyTopAggs = randomNonEmptyTopAggregations(() -> false);
RequestFiltersComputer underTest = new RequestFiltersComputer(allFilters, atLeastOneNonStickyTopAggs);
atLeastOneNonStickyTopAggs.forEach(topAgg -> assertThat(underTest.getTopAggregationFilter(topAgg)).isEmpty());
}
@Test
public void filters_on_field_of_sticky_TopAggregation_go_to_PostFilters_and_TopAgg_Filters_on_other_fields() {
AllFilters allFilters = newAllFilters();
// has topAggs and two filters
String field1 = "field1";
SimpleFieldFilterScope filterScopeField1 = new SimpleFieldFilterScope(field1);
SimpleFieldTopAggregationDefinition stickyTopAggField1 = new SimpleFieldTopAggregationDefinition(field1, STICKY);
SimpleFieldTopAggregationDefinition nonStickyTopAggField1 = new SimpleFieldTopAggregationDefinition(field1, NON_STICKY);
QueryBuilder filterField1_1 = newQuery();
QueryBuilder filterField1_2 = newQuery();
allFilters.addFilter("filter_field1_1", filterScopeField1, filterField1_1);
allFilters.addFilter("filter_field1_2", filterScopeField1, filterField1_2);
// has topAggs and one filter
String field2 = "field2";
SimpleFieldFilterScope filterScopeField2 = new SimpleFieldFilterScope(field2);
SimpleFieldTopAggregationDefinition stickyTopAggField2 = new SimpleFieldTopAggregationDefinition(field2, STICKY);
SimpleFieldTopAggregationDefinition nonStickyTopAggField2 = new SimpleFieldTopAggregationDefinition(field2, NON_STICKY);
QueryBuilder filterField2 = newQuery();
allFilters.addFilter("filter_field2", filterScopeField2, filterField2);
// has only non-sticky top-agg and one filter
String field3 = "field3";
SimpleFieldFilterScope filterScopeField3 = new SimpleFieldFilterScope(field3);
SimpleFieldTopAggregationDefinition nonStickyTopAggField3 = new SimpleFieldTopAggregationDefinition(field3, NON_STICKY);
QueryBuilder filterField3 = newQuery();
allFilters.addFilter("filter_field3", filterScopeField3, filterField3);
// has one filter but no top agg
String field4 = "field4";
SimpleFieldFilterScope filterScopeField4 = new SimpleFieldFilterScope(field4);
QueryBuilder filterField4 = newQuery();
allFilters.addFilter("filter_field4", filterScopeField4, filterField4);
// has top-aggs by no filter
String field5 = "field5";
SimpleFieldTopAggregationDefinition stickyTopAggField5 = new SimpleFieldTopAggregationDefinition(field5, STICKY);
SimpleFieldTopAggregationDefinition nonStickyTopAggField5 = new SimpleFieldTopAggregationDefinition(field5, NON_STICKY);
Set<TopAggregationDefinition<?>> declaredTopAggregations = ImmutableSet.of(
stickyTopAggField1, nonStickyTopAggField1,
stickyTopAggField2, nonStickyTopAggField2,
nonStickyTopAggField3,
stickyTopAggField5, nonStickyTopAggField5);
RequestFiltersComputer underTest = new RequestFiltersComputer(allFilters, declaredTopAggregations);
assertThat(underTest.getQueryFilters()).contains(toBoolQuery(filterField3, filterField4));
QueryBuilder[] postFilters = {filterField1_1, filterField1_2, filterField2};
assertThat(underTest.getPostFilters()).contains(toBoolQuery(postFilters));
assertTopAggregationFilter(underTest, stickyTopAggField1, filterField2);
assertTopAggregationFilter(underTest, nonStickyTopAggField1, postFilters);
assertTopAggregationFilter(underTest, stickyTopAggField2, filterField1_1, filterField1_2);
assertTopAggregationFilter(underTest, nonStickyTopAggField2, postFilters);
assertTopAggregationFilter(underTest, nonStickyTopAggField3, postFilters);
assertTopAggregationFilter(underTest, stickyTopAggField5, postFilters);
assertTopAggregationFilter(underTest, nonStickyTopAggField5, postFilters);
}
@Test
public void getTopAggregationFilters_returns_empty_on_sticky_field_TopAgg_when_no_other_sticky_TopAgg() {
AllFilters allFilters = newAllFilters();
// has topAggs and two filters
String field1 = "field1";
SimpleFieldFilterScope filterScopeField1 = new SimpleFieldFilterScope(field1);
SimpleFieldTopAggregationDefinition stickyTopAggField1 = new SimpleFieldTopAggregationDefinition(field1, STICKY);
SimpleFieldTopAggregationDefinition nonStickyTopAggField1 = new SimpleFieldTopAggregationDefinition(field1, NON_STICKY);
QueryBuilder filterField1_1 = newQuery();
QueryBuilder filterField1_2 = newQuery();
allFilters.addFilter("filter_field1_1", filterScopeField1, filterField1_1);
allFilters.addFilter("filter_field1_2", filterScopeField1, filterField1_2);
// has only non-sticky top-agg and one filter
String field2 = "field2";
SimpleFieldFilterScope filterScopeField2 = new SimpleFieldFilterScope(field2);
SimpleFieldTopAggregationDefinition nonStickyTopAggField2 = new SimpleFieldTopAggregationDefinition(field2, NON_STICKY);
QueryBuilder filterField2 = newQuery();
allFilters.addFilter("filter_field2", filterScopeField2, filterField2);
Set<TopAggregationDefinition<?>> declaredTopAggregations = ImmutableSet.of(
stickyTopAggField1, nonStickyTopAggField1,
nonStickyTopAggField2);
RequestFiltersComputer underTest = new RequestFiltersComputer(allFilters, declaredTopAggregations);
assertThat(underTest.getQueryFilters()).contains(toBoolQuery(filterField2));
QueryBuilder[] postFilters = {filterField1_1, filterField1_2};
assertThat(underTest.getPostFilters()).contains(toBoolQuery(postFilters));
assertThat(underTest.getTopAggregationFilter(stickyTopAggField1)).isEmpty();
assertTopAggregationFilter(underTest, nonStickyTopAggField1, postFilters);
assertTopAggregationFilter(underTest, nonStickyTopAggField2, postFilters);
}
@Test
public void filters_on_nestedField_of_sticky_TopAggregation_go_to_PostFilters_and_TopAgg_Filters_on_other_values_of_same_nestField() {
String field1 = "field";
String nestField = "nestedField";
String nestField_value1 = "nestedField_value1";
String nestField_value2 = "nestedField_value2";
String nestField_value3 = "nestedField_value3";
String nestField_value4 = "nestedField_value4";
String nestField_value5 = "nestedField_value5";
AllFilters allFilters = newAllFilters();
// has topAggs and two filters
NestedFieldFilterScope<String> filterScopeNestField_value1 = new NestedFieldFilterScope<>(field1, nestField, nestField_value1);
NestedFieldTopAggregationDefinition<String> stickyTopAggField1 = newNestedFieldTopAggDef(field1, nestField, nestField_value1, STICKY);
NestedFieldTopAggregationDefinition<String> nonStickyTopAggField1 = newNestedFieldTopAggDef(field1, nestField, nestField_value1, NON_STICKY);
QueryBuilder filterField1_1 = newQuery();
QueryBuilder filterField1_2 = newQuery();
allFilters.addFilter("filter_field1_1", filterScopeNestField_value1, filterField1_1);
allFilters.addFilter("filter_field1_2", filterScopeNestField_value1, filterField1_2);
// has topAggs and one filter
NestedFieldFilterScope<String> filterScopeNestField_value2 = new NestedFieldFilterScope<>(field1, nestField, nestField_value2);
NestedFieldTopAggregationDefinition<String> stickyTopAggField2 = newNestedFieldTopAggDef(field1, nestField, nestField_value2, STICKY);
NestedFieldTopAggregationDefinition<String> nonStickyTopAggField2 = newNestedFieldTopAggDef(field1, nestField, nestField_value2, NON_STICKY);
QueryBuilder filterField2 = newQuery();
allFilters.addFilter("filter_field2", filterScopeNestField_value2, filterField2);
// has only non-sticky top-agg and one filter
NestedFieldFilterScope<String> filterScopeField3 = new NestedFieldFilterScope<>(field1, nestField, nestField_value3);
NestedFieldTopAggregationDefinition<String> nonStickyTopAggField3 = newNestedFieldTopAggDef(field1, nestField, nestField_value3, NON_STICKY);
QueryBuilder filterField3 = newQuery();
allFilters.addFilter("filter_field3", filterScopeField3, filterField3);
// has one filter but no top agg
NestedFieldFilterScope<String> filterScopeField4 = new NestedFieldFilterScope<>(field1, nestField, nestField_value4);
QueryBuilder filterField4 = newQuery();
allFilters.addFilter("filter_field4", filterScopeField4, filterField4);
// has top-aggs by no filter
String field5 = "field5";
NestedFieldTopAggregationDefinition<String> stickyTopAggField5 = newNestedFieldTopAggDef(field1, nestField, nestField_value5, STICKY);
NestedFieldTopAggregationDefinition<String> nonStickyTopAggField5 = newNestedFieldTopAggDef(field1, nestField, nestField_value5, NON_STICKY);
Set<TopAggregationDefinition<?>> declaredTopAggregations = ImmutableSet.of(
stickyTopAggField1, nonStickyTopAggField1,
stickyTopAggField2, nonStickyTopAggField2,
nonStickyTopAggField3,
stickyTopAggField5, nonStickyTopAggField5);
RequestFiltersComputer underTest = new RequestFiltersComputer(allFilters, declaredTopAggregations);
assertThat(underTest.getQueryFilters()).contains(toBoolQuery(filterField3, filterField4));
QueryBuilder[] postFilters = {filterField1_1, filterField1_2, filterField2};
assertThat(underTest.getPostFilters()).contains(toBoolQuery(postFilters));
assertTopAggregationFilter(underTest, stickyTopAggField1, filterField2);
assertTopAggregationFilter(underTest, nonStickyTopAggField1, postFilters);
assertTopAggregationFilter(underTest, stickyTopAggField2, filterField1_1, filterField1_2);
assertTopAggregationFilter(underTest, nonStickyTopAggField2, postFilters);
assertTopAggregationFilter(underTest, nonStickyTopAggField3, postFilters);
assertTopAggregationFilter(underTest, stickyTopAggField5, postFilters);
assertTopAggregationFilter(underTest, nonStickyTopAggField5, postFilters);
}
@Test
public void filters_on_nestedField_of_sticky_TopAggregation_go_to_PostFilters_and_TopAgg_Filters_on_other_fields() {
String field1 = "field1";
String field2 = "field2";
String field3 = "field3";
String nestField = "nestedField";
String nestField_value1 = "nestedField_value1";
String nestField_value2 = "nestedField_value2";
AllFilters allFilters = newAllFilters();
// filter without top aggregation
QueryBuilder queryFilter = newQuery("query_filter");
allFilters.addFilter("query_filter", new SimpleFieldFilterScope("text"), queryFilter);
// nestedField of field1 with value1: has topAggs and two filters
NestedFieldFilterScope<String> filterScopeNestField1_value1 = new NestedFieldFilterScope<>(field1, nestField, nestField_value1);
NestedFieldTopAggregationDefinition<String> stickyTopAggNestedField1_value1 = newNestedFieldTopAggDef(field1, nestField, nestField_value1, STICKY);
NestedFieldTopAggregationDefinition<String> nonStickyTopAggNestedField1_value1 = newNestedFieldTopAggDef(field1, nestField, nestField_value1, NON_STICKY);
QueryBuilder filterNestedField1_value1_1 = newQuery("filterNestedField1_value1_1");
QueryBuilder filterNestedField1_value1_2 = newQuery("filterNestedField1_value1_2");
allFilters.addFilter("filter_nested_field1_value1_1", filterScopeNestField1_value1, filterNestedField1_value1_1);
allFilters.addFilter("filter_nested_field1_value1_2", filterScopeNestField1_value1, filterNestedField1_value1_2);
// nestedField of field1 with value2: has topAggs and two filters
NestedFieldFilterScope<String> filterScopeNestField1_value2 = new NestedFieldFilterScope<>(field1, nestField, nestField_value2);
NestedFieldTopAggregationDefinition<String> stickyTopAggNestedField1_value2 = newNestedFieldTopAggDef(field1, nestField, nestField_value2, STICKY);
NestedFieldTopAggregationDefinition<String> nonStickyTopAggNestedField1_value2 = newNestedFieldTopAggDef(field1, nestField, nestField_value2, NON_STICKY);
QueryBuilder filterNestedField1_value2_1 = newQuery("filterNestedField1_value2_1");
QueryBuilder filterNestedField1_value2_2 = newQuery("filterNestedField1_value2_2");
allFilters.addFilter("filter_nested_field1_value2_1", filterScopeNestField1_value2, filterNestedField1_value2_1);
allFilters.addFilter("filter_nested_field1_value2_2", filterScopeNestField1_value2, filterNestedField1_value2_2);
// [EDGE CASE] topAgg directly on field1: has topAggs and two filters
SimpleFieldFilterScope filterScopeField1 = new SimpleFieldFilterScope(field1);
SimpleFieldTopAggregationDefinition stickyTopAggField1 = new SimpleFieldTopAggregationDefinition(field1, STICKY);
SimpleFieldTopAggregationDefinition nonStickyTopAggField1 = new SimpleFieldTopAggregationDefinition(field1, NON_STICKY);
QueryBuilder filterField1_1 = newQuery("filterField1_1");
QueryBuilder filterField1_2 = newQuery("filterField1_2");
allFilters.addFilter("filter_field1_1", filterScopeField1, filterField1_1);
allFilters.addFilter("filter_field1_2", filterScopeField1, filterField1_2);
// other field: has topAggs and two filters too
SimpleFieldFilterScope filterScopeField2 = new SimpleFieldFilterScope(field2);
SimpleFieldTopAggregationDefinition stickyTopAggField2 = new SimpleFieldTopAggregationDefinition(field2, STICKY);
SimpleFieldTopAggregationDefinition nonStickyTopAggField2 = new SimpleFieldTopAggregationDefinition(field2, NON_STICKY);
QueryBuilder filterField2_1 = newQuery("filterField2_1");
QueryBuilder filterField2_2 = newQuery("filterField2_2");
allFilters.addFilter("filter_field2_1", filterScopeField2, filterField2_1);
allFilters.addFilter("filter_field2_2", filterScopeField2, filterField2_2);
// nestedField of another field (even though nestedField name and values are the same): has topAggs and two filters
NestedFieldFilterScope<String> filterScopeNestField3_value = new NestedFieldFilterScope<>(field3, nestField, nestField_value1);
NestedFieldTopAggregationDefinition<String> stickyTopAggNestedField3 = newNestedFieldTopAggDef(field3, nestField, nestField_value1, STICKY);
NestedFieldTopAggregationDefinition<String> nonStickyTopAggNestedField3 = newNestedFieldTopAggDef(field3, nestField, nestField_value1, NON_STICKY);
QueryBuilder filterNestedField3_1 = newQuery("filterNestedField3_1");
QueryBuilder filterNestedField3_2 = newQuery("filterNestedField3_2");
allFilters.addFilter("filter_nested_field3_1", filterScopeNestField3_value, filterNestedField3_1);
allFilters.addFilter("filter_nested_field3_2", filterScopeNestField3_value, filterNestedField3_2);
Set<TopAggregationDefinition<?>> declaredTopAggregations = ImmutableSet.of(
stickyTopAggNestedField1_value1, nonStickyTopAggNestedField1_value1,
stickyTopAggNestedField1_value2, nonStickyTopAggNestedField1_value2,
stickyTopAggField1, nonStickyTopAggField1,
stickyTopAggField2, nonStickyTopAggField2,
stickyTopAggNestedField3, nonStickyTopAggNestedField3);
RequestFiltersComputer underTest = new RequestFiltersComputer(allFilters, declaredTopAggregations);
assertThat(underTest.getQueryFilters()).contains(toBoolQuery(queryFilter));
QueryBuilder[] postFilters = {
filterNestedField1_value1_1, filterNestedField1_value1_2,
filterNestedField1_value2_1, filterNestedField1_value2_2,
filterField1_1, filterField1_2,
filterField2_1, filterField2_2,
filterNestedField3_1, filterNestedField3_2};
assertThat(underTest.getPostFilters()).contains(toBoolQuery(postFilters));
assertTopAggregationFilter(underTest, stickyTopAggNestedField1_value1,
filterNestedField1_value2_1, filterNestedField1_value2_2,
filterField1_1, filterField1_2,
filterField2_1, filterField2_2,
filterNestedField3_1, filterNestedField3_2);
assertTopAggregationFilter(underTest, nonStickyTopAggNestedField1_value1, postFilters);
assertTopAggregationFilter(underTest, stickyTopAggNestedField1_value2,
filterNestedField1_value1_1, filterNestedField1_value1_2,
filterField1_1, filterField1_2,
filterField2_1, filterField2_2,
filterNestedField3_1, filterNestedField3_2);
assertTopAggregationFilter(underTest, nonStickyTopAggNestedField1_value2, postFilters);
assertTopAggregationFilter(underTest, stickyTopAggField1,
filterField2_1, filterField2_2,
filterNestedField3_1, filterNestedField3_2);
assertTopAggregationFilter(underTest, nonStickyTopAggField1, postFilters);
assertTopAggregationFilter(underTest, stickyTopAggField2,
filterNestedField1_value1_1, filterNestedField1_value1_2,
filterNestedField1_value2_1, filterNestedField1_value2_2,
filterField1_1, filterField1_2,
filterNestedField3_1, filterNestedField3_2);
assertTopAggregationFilter(underTest, nonStickyTopAggField2, postFilters);
assertTopAggregationFilter(underTest, stickyTopAggNestedField3,
filterNestedField1_value1_1, filterNestedField1_value1_2,
filterNestedField1_value2_1, filterNestedField1_value2_2,
filterField1_1, filterField1_2,
filterField2_1, filterField2_2);
assertTopAggregationFilter(underTest, nonStickyTopAggNestedField3, postFilters);
}
@Test
public void getTopAggregationFilters_returns_empty_on_sticky_nestedField_TopAgg_when_no_other_sticky_TopAgg() {
String field1 = "field";
String nestField = "nestedField";
String nestField_value1 = "nestedField_value1";
String nestField_value2 = "nestedField_value2";
AllFilters allFilters = newAllFilters();
// has topAggs and two filters
NestedFieldFilterScope<String> filterScopeField1 = new NestedFieldFilterScope<>(field1, nestField, nestField_value1);
NestedFieldTopAggregationDefinition<String> stickyTopAggField1 = newNestedFieldTopAggDef(field1, nestField, nestField_value1, STICKY);
NestedFieldTopAggregationDefinition<String> nonStickyTopAggField1 = newNestedFieldTopAggDef(field1, nestField, nestField_value1, NON_STICKY);
QueryBuilder filterField1_1 = newQuery();
QueryBuilder filterField1_2 = newQuery();
allFilters.addFilter("filter_field1_1", filterScopeField1, filterField1_1);
allFilters.addFilter("filter_field1_2", filterScopeField1, filterField1_2);
// has only non-sticky top-agg and one filter
NestedFieldFilterScope<String> filterScopeField2 = new NestedFieldFilterScope<>(field1, nestField, nestField_value2);
NestedFieldTopAggregationDefinition<String> nonStickyTopAggField2 = newNestedFieldTopAggDef(field1, nestField, nestField_value2, NON_STICKY);
QueryBuilder filterField2 = newQuery();
allFilters.addFilter("filter_field2", filterScopeField2, filterField2);
Set<TopAggregationDefinition<?>> declaredTopAggregations = ImmutableSet.of(
stickyTopAggField1, nonStickyTopAggField1,
nonStickyTopAggField2);
RequestFiltersComputer underTest = new RequestFiltersComputer(allFilters, declaredTopAggregations);
assertThat(underTest.getQueryFilters()).contains(toBoolQuery(filterField2));
QueryBuilder[] postFilters = {filterField1_1, filterField1_2};
assertThat(underTest.getPostFilters()).contains(toBoolQuery(postFilters));
assertThat(underTest.getTopAggregationFilter(stickyTopAggField1)).isEmpty();
assertTopAggregationFilter(underTest, nonStickyTopAggField1, postFilters);
assertTopAggregationFilter(underTest, nonStickyTopAggField2, postFilters);
}
@Test
public void getQueryFilters_returns_empty_when_all_filters_have_sticky_TopAggs() {
AllFilters allFilters = newAllFilters();
// has topAggs and two filters
String field1 = "field1";
SimpleFieldFilterScope filterScopeField1 = new SimpleFieldFilterScope(field1);
SimpleFieldTopAggregationDefinition stickyTopAggField1 = new SimpleFieldTopAggregationDefinition(field1, STICKY);
SimpleFieldTopAggregationDefinition nonStickyTopAggField1 = new SimpleFieldTopAggregationDefinition(field1, NON_STICKY);
QueryBuilder filterField1_1 = newQuery();
QueryBuilder filterField1_2 = newQuery();
allFilters.addFilter("filter_field1_1", filterScopeField1, filterField1_1);
allFilters.addFilter("filter_field1_2", filterScopeField1, filterField1_2);
// has only sticky top-agg and one filter
String field2 = "field2";
SimpleFieldFilterScope filterScopeField2 = new SimpleFieldFilterScope(field2);
SimpleFieldTopAggregationDefinition stickyTopAggField2 = new SimpleFieldTopAggregationDefinition(field2, STICKY);
QueryBuilder filterField2 = newQuery();
allFilters.addFilter("filter_field2", filterScopeField2, filterField2);
Set<TopAggregationDefinition<?>> declaredTopAggregations = ImmutableSet.of(
stickyTopAggField1, nonStickyTopAggField1,
stickyTopAggField2);
RequestFiltersComputer underTest = new RequestFiltersComputer(allFilters, declaredTopAggregations);
assertThat(underTest.getQueryFilters()).isEmpty();
QueryBuilder[] postFilters = {filterField1_1, filterField1_2, filterField2};
assertThat(underTest.getPostFilters()).contains(toBoolQuery(postFilters));
assertTopAggregationFilter(underTest, stickyTopAggField1, filterField2);
assertTopAggregationFilter(underTest, nonStickyTopAggField1, postFilters);
assertTopAggregationFilter(underTest, stickyTopAggField2, filterField1_1, filterField1_2);
}
private static Set<TopAggregationDefinition<?>> randomNonEmptyTopAggregations(Supplier<Boolean> isSticky) {
return IntStream.range(0, 1 + RANDOM.nextInt(20))
.mapToObj(i -> new SimpleFieldTopAggregationDefinition("field_" + i, isSticky.get()))
.collect(toSet());
}
private static BoolQueryBuilder toBoolQuery(QueryBuilder first, QueryBuilder... others) {
return toBoolQuery(Stream.concat(
Stream.of(first), Arrays.stream(others)));
}
private static BoolQueryBuilder toBoolQuery(QueryBuilder[] subQueries) {
return toBoolQuery(Arrays.stream(subQueries));
}
private static BoolQueryBuilder toBoolQuery(Stream<QueryBuilder> stream) {
BoolQueryBuilder res = boolQuery();
stream.forEach(res::must);
checkState(res.hasClauses(), "empty stream is not supported");
return res;
}
private static AllFilters randomNonEmptyAllFilters() {
AllFilters res = newAllFilters();
IntStream.range(0, 1 + RANDOM.nextInt(22))
.forEach(i -> res.addFilter("filter_" + i, mock(FilterScope.class), newQuery()));
return res;
}
private static NestedFieldTopAggregationDefinition<String> newNestedFieldTopAggDef(String field1, String nestField, String nestField_value1, boolean sticky) {
return new NestedFieldTopAggregationDefinition<>(field1 + "." + nestField, nestField_value1, sticky);
}
private static int queryCounter = 0;
/**
* Creates unique queries
*/
private static QueryBuilder newQuery() {
return QueryBuilders.termQuery("query_" + (queryCounter++), "foo");
}
private static QueryBuilder newQuery(String label) {
return QueryBuilders.termQuery("query_" + label, "foo");
}
private static void assertTopAggregationFilter(RequestFiltersComputer underTest,
TopAggregationDefinition<?> topAggregation, QueryBuilder firstFilter, QueryBuilder... otherFilters) {
assertThat(underTest.getTopAggregationFilter(topAggregation)).contains(toBoolQuery(firstFilter, otherFilters));
}
private static void assertTopAggregationFilter(RequestFiltersComputer underTest,
TopAggregationDefinition<?> topAggregation, QueryBuilder[] filters) {
assertThat(underTest.getTopAggregationFilter(topAggregation)).contains(toBoolQuery(filters));
}
}
| 29,788 | 57.755424 | 160 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldFilterScopeTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.searchrequest;
import org.junit.Test;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.NestedFieldFilterScope;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.SimpleFieldFilterScope;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class SimpleFieldFilterScopeTest {
@Test
public void constructor_fails_with_NPE_if_fieldName_is_null() {
assertThatThrownBy(() -> new SimpleFieldFilterScope(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("fieldName can't be null");
}
@Test
public void getFieldName() {
String fieldName = randomAlphabetic(12);
SimpleFieldFilterScope underTest = new SimpleFieldFilterScope(fieldName);
assertThat(underTest.getFieldName()).isEqualTo(fieldName);
}
@Test
public void verify_equals() {
String fieldName1 = randomAlphabetic(11);
String fieldName2 = randomAlphabetic(12);
SimpleFieldFilterScope underTest = new SimpleFieldFilterScope(fieldName1);
assertThat(underTest)
.isEqualTo(underTest)
.isEqualTo(new SimpleFieldFilterScope(fieldName1))
.isNotNull()
.isNotEqualTo(new Object())
.isNotEqualTo(new SimpleFieldFilterScope(fieldName2))
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName1, "foo", "bar"))
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName2, "foo", "bar"));
}
@Test
public void verify_hashcode() {
String fieldName1 = randomAlphabetic(11);
String fieldName2 = randomAlphabetic(12);
SimpleFieldFilterScope underTest = new SimpleFieldFilterScope(fieldName1);
assertThat(underTest.hashCode())
.isEqualTo(underTest.hashCode())
.isEqualTo(new SimpleFieldFilterScope(fieldName1).hashCode());
assertThat(underTest.hashCode())
.isNotEqualTo(new Object().hashCode())
.isNotEqualTo(new SimpleFieldFilterScope(fieldName2).hashCode())
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName1, "foo", "bar").hashCode())
.isNotEqualTo(new NestedFieldFilterScope<>(fieldName1, "foo", "bar").hashCode());
}
@Test
public void verify_intersect() {
String fieldName1 = randomAlphabetic(11);
String fieldName2 = randomAlphabetic(12);
SimpleFieldFilterScope underTest = new SimpleFieldFilterScope(fieldName1);
assertThat(underTest.intersect(underTest)).isTrue();
assertThat(underTest.intersect(new SimpleFieldFilterScope(fieldName1))).isTrue();
assertThat(underTest.intersect(new SimpleFieldFilterScope(fieldName2))).isFalse();
assertThat(underTest.intersect(new NestedFieldFilterScope<>(fieldName1, "foo", "bar"))).isTrue();
assertThat(underTest.intersect(new NestedFieldFilterScope<>(fieldName2, "foo", "bar"))).isFalse();
}
}
| 3,741 | 40.120879 | 102 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldTopAggregationDefinitionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.searchrequest;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Test;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class SimpleFieldTopAggregationDefinitionTest {
private static final Random RANDOM = new Random();
@Test
public void fieldName_cannot_be_null() {
boolean sticky = RANDOM.nextBoolean();
assertThatThrownBy(() -> new SimpleFieldTopAggregationDefinition(null, sticky))
.isInstanceOf(NullPointerException.class)
.hasMessage("fieldName can't be null");
}
@Test
public void getters() {
String fieldName = RandomStringUtils.randomAlphabetic(12);
boolean sticky = new Random().nextBoolean();
SimpleFieldTopAggregationDefinition underTest = new SimpleFieldTopAggregationDefinition(fieldName, sticky);
assertThat(underTest.getFilterScope().getFieldName()).isEqualTo(fieldName);
assertThat(underTest.isSticky()).isEqualTo(sticky);
}
@Test
public void getFilterScope_always_returns_the_same_instance() {
String fieldName = randomAlphabetic(12);
boolean sticky = RANDOM.nextBoolean();
SimpleFieldTopAggregationDefinition underTest = new SimpleFieldTopAggregationDefinition(fieldName, sticky);
Set<TopAggregationDefinition.FilterScope> filterScopes = IntStream.range(0, 2 + RANDOM.nextInt(200))
.mapToObj(i -> underTest.getFilterScope())
.collect(Collectors.toSet());
assertThat(filterScopes).hasSize(1);
}
}
| 2,579 | 36.391304 | 111 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SubAggregationHelperTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.searchrequest;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.junit.Test;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.es.searchrequest.TopAggregationHelperTest.DEFAULT_BUCKET_SIZE;
public class SubAggregationHelperTest {
private static final BucketOrder ES_BUILTIN_TIE_BREAKER = BucketOrder.key(true);
private static final BucketOrder SQ_DEFAULT_BUCKET_ORDER = BucketOrder.count(false);
private AbstractAggregationBuilder<?> customSubAgg = AggregationBuilders.sum("foo");
private SubAggregationHelper underTest = new SubAggregationHelper();
private BucketOrder customOrder = BucketOrder.count(true);
private SubAggregationHelper underTestWithCustomSubAgg = new SubAggregationHelper(customSubAgg);
private SubAggregationHelper underTestWithCustomsSubAggAndOrder = new SubAggregationHelper(customSubAgg, customOrder);
@Test
public void buildTermsAggregation_adds_term_subaggregation_with_minDoc_1_and_default_sort() {
String aggName = randomAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
Stream.of(
underTest,
underTestWithCustomSubAgg)
.forEach(t -> {
TermsAggregationBuilder agg = t.buildTermsAggregation(aggName, topAggregation, null);
assertThat(agg.getName()).isEqualTo(aggName);
assertThat(agg.field()).isEqualTo(topAggregation.getFilterScope().getFieldName());
assertThat(agg.size()).isEqualTo(DEFAULT_BUCKET_SIZE);
assertThat(agg.minDocCount()).isOne();
assertThat(agg.order()).isEqualTo(BucketOrder.compound(SQ_DEFAULT_BUCKET_ORDER, ES_BUILTIN_TIE_BREAKER));
});
}
@Test
public void buildTermsAggregation_adds_custom_order_from_constructor() {
String aggName = randomAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
TermsAggregationBuilder agg = underTestWithCustomsSubAggAndOrder.buildTermsAggregation(aggName, topAggregation, null);
assertThat(agg.getName()).isEqualTo(aggName);
assertThat(agg.field()).isEqualTo(topAggregation.getFilterScope().getFieldName());
assertThat(agg.order()).isEqualTo(BucketOrder.compound(customOrder, ES_BUILTIN_TIE_BREAKER));
}
@Test
public void buildTermsAggregation_adds_custom_sub_agg_from_constructor() {
String aggName = randomAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
Stream.of(
underTestWithCustomSubAgg,
underTestWithCustomsSubAggAndOrder)
.forEach(t -> {
TermsAggregationBuilder agg = t.buildTermsAggregation(aggName, topAggregation, null);
assertThat(agg.getName()).isEqualTo(aggName);
assertThat(agg.field()).isEqualTo(topAggregation.getFilterScope().getFieldName());
assertThat(agg.getSubAggregations()).hasSize(1);
assertThat(agg.getSubAggregations().iterator().next()).isSameAs(customSubAgg);
});
}
@Test
public void buildTermsAggregation_adds_custom_size_if_TermTopAggregation_specifies_one() {
String aggName = randomAlphabetic(10);
int customSize = 1 + new Random().nextInt(400);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
Stream.of(
underTest,
underTestWithCustomSubAgg,
underTestWithCustomsSubAggAndOrder)
.forEach(t -> {
TermsAggregationBuilder agg = t.buildTermsAggregation(aggName, topAggregation, customSize);
assertThat(agg.getName()).isEqualTo(aggName);
assertThat(agg.field()).isEqualTo(topAggregation.getFilterScope().getFieldName());
assertThat(agg.size()).isEqualTo(customSize);
});
}
@Test
public void buildSelectedItemsAggregation_returns_empty_if_no_selected_item() {
String aggName = randomAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
Stream.of(
underTest,
underTestWithCustomSubAgg,
underTestWithCustomsSubAggAndOrder)
.forEach(t -> assertThat(t.buildSelectedItemsAggregation(aggName, topAggregation, new Object[0])).isEmpty());
}
@Test
public void buildSelectedItemsAggregation_does_not_add_custom_order_from_constructor() {
String aggName = randomAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
String[] selected = randomNonEmptySelected();
TermsAggregationBuilder agg = underTestWithCustomsSubAggAndOrder.buildSelectedItemsAggregation(aggName, topAggregation, selected)
.get();
assertThat(agg.getName()).isEqualTo(aggName + "_selected");
assertThat(agg.field()).isEqualTo(topAggregation.getFilterScope().getFieldName());
assertThat(agg.order()).isEqualTo(BucketOrder.compound(SQ_DEFAULT_BUCKET_ORDER, ES_BUILTIN_TIE_BREAKER));
}
@Test
public void buildSelectedItemsAggregation_adds_custom_sub_agg_from_constructor() {
String aggName = randomAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
String[] selected = randomNonEmptySelected();
Stream.of(
underTestWithCustomSubAgg,
underTestWithCustomsSubAggAndOrder)
.forEach(t -> {
TermsAggregationBuilder agg = t.buildSelectedItemsAggregation(aggName, topAggregation, selected).get();
assertThat(agg.getName()).isEqualTo(aggName + "_selected");
assertThat(agg.field()).isEqualTo(topAggregation.getFilterScope().getFieldName());
assertThat(agg.getSubAggregations()).hasSize(1);
assertThat(agg.getSubAggregations().iterator().next()).isSameAs(customSubAgg);
});
}
private static String[] randomNonEmptySelected() {
return IntStream.range(0, 1 + new Random().nextInt(22))
.mapToObj(i -> "selected_" + i)
.toArray(String[]::new);
}
}
| 7,320 | 43.369697 | 133 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/TopAggregationHelperTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.searchrequest;
import java.util.Arrays;
import java.util.Optional;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.MinAggregationBuilder;
import org.junit.Test;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.server.es.searchrequest.TopAggregationHelper.NO_EXTRA_FILTER;
import static org.sonar.server.es.searchrequest.TopAggregationHelper.NO_OTHER_SUBAGGREGATION;
public class TopAggregationHelperTest {
public static final int DEFAULT_BUCKET_SIZE = 10;
private RequestFiltersComputer filtersComputer = mock(RequestFiltersComputer.class);
private SubAggregationHelper subAggregationHelper = mock(SubAggregationHelper.class);
private TopAggregationHelper underTest = new TopAggregationHelper(filtersComputer, subAggregationHelper);
@Test
public void buildTopAggregation_fails_with_ISE_if_no_subaggregation_added_by_lambda() {
String aggregationName = "name";
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
assertThatThrownBy(() -> underTest.buildTopAggregation(aggregationName, topAggregation, NO_EXTRA_FILTER, NO_OTHER_SUBAGGREGATION))
.isInstanceOf(IllegalStateException.class)
.hasMessage("no sub-aggregation has been added to top-aggregation " + aggregationName);
}
@Test
public void buildTopAggregation_adds_subAggregation_from_lambda_parameter() {
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
AggregationBuilder[] subAggs = IntStream.range(0, 1 + new Random().nextInt(12))
.mapToObj(i -> AggregationBuilders.min("subAgg_" + i))
.toArray(AggregationBuilder[]::new);
String topAggregationName = randomAlphabetic(10);
AggregationBuilder aggregationBuilder = underTest.buildTopAggregation(topAggregationName, topAggregation,
NO_EXTRA_FILTER, t -> Arrays.stream(subAggs).forEach(t::subAggregation));
assertThat(aggregationBuilder.getName()).isEqualTo(topAggregationName);
assertThat(aggregationBuilder.getSubAggregations()).hasSize(subAggs.length);
assertThat(aggregationBuilder.getSubAggregations()).containsExactlyInAnyOrder(subAggs);
}
@Test
public void buildTopAggregation_adds_filter_from_FiltersComputer_for_TopAggregation() {
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
SimpleFieldTopAggregationDefinition otherTopAggregation = new SimpleFieldTopAggregationDefinition("acme", false);
BoolQueryBuilder computerFilter = boolQuery();
BoolQueryBuilder otherFilter = boolQuery();
when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.of(computerFilter));
when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter));
MinAggregationBuilder subAggregation = AggregationBuilders.min("donut");
String topAggregationName = randomAlphabetic(10);
FilterAggregationBuilder aggregationBuilder = underTest.buildTopAggregation(topAggregationName, topAggregation,
NO_EXTRA_FILTER, t -> t.subAggregation(subAggregation));
assertThat(aggregationBuilder.getName()).isEqualTo(topAggregationName);
assertThat(aggregationBuilder.getFilter()).isSameAs(computerFilter);
}
@Test
public void buildTopAggregation_has_empty_filter_when_FiltersComputer_returns_empty_for_TopAggregation() {
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
SimpleFieldTopAggregationDefinition otherTopAggregation = new SimpleFieldTopAggregationDefinition("acme", false);
BoolQueryBuilder otherFilter = boolQuery();
when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.empty());
when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter));
MinAggregationBuilder subAggregation = AggregationBuilders.min("donut");
String topAggregationName = randomAlphabetic(10);
FilterAggregationBuilder aggregationBuilder = underTest.buildTopAggregation(topAggregationName, topAggregation,
NO_EXTRA_FILTER, t -> t.subAggregation(subAggregation));
assertThat(aggregationBuilder.getName()).isEqualTo(topAggregationName);
assertThat(aggregationBuilder.getFilter()).isEqualTo(boolQuery()).isNotSameAs(otherFilter);
}
@Test
public void buildTopAggregation_adds_filter_from_FiltersComputer_for_TopAggregation_and_extra_one() {
String topAggregationName = randomAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
SimpleFieldTopAggregationDefinition otherTopAggregation = new SimpleFieldTopAggregationDefinition("acme", false);
BoolQueryBuilder computerFilter = boolQuery();
BoolQueryBuilder otherFilter = boolQuery();
BoolQueryBuilder extraFilter = boolQuery();
when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.of(computerFilter));
when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter));
MinAggregationBuilder subAggregation = AggregationBuilders.min("donut");
FilterAggregationBuilder aggregationBuilder = underTest.buildTopAggregation(topAggregationName, topAggregation,
t -> t.must(extraFilter), t -> t.subAggregation(subAggregation));
assertThat(aggregationBuilder.getName()).isEqualTo(topAggregationName);
assertThat(aggregationBuilder.getFilter()).isEqualTo(computerFilter);
assertThat(((BoolQueryBuilder) aggregationBuilder.getFilter()).must()).containsExactly(extraFilter);
}
@Test
public void buildTopAggregation_does_not_add_subaggregation_from_subAggregationHelper() {
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.empty());
MinAggregationBuilder subAggregation = AggregationBuilders.min("donut");
String topAggregationName = randomAlphabetic(10);
underTest.buildTopAggregation(topAggregationName, topAggregation, NO_EXTRA_FILTER, t -> t.subAggregation(subAggregation));
verifyNoInteractions(subAggregationHelper);
}
@Test
public void buildTermTopAggregation_adds_term_subaggregation_from_subAggregationHelper() {
String topAggregationName = randomAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
TermsAggregationBuilder termSubAgg = AggregationBuilders.terms("foo");
when(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, null)).thenReturn(termSubAgg);
FilterAggregationBuilder aggregationBuilder = underTest.buildTermTopAggregation(
topAggregationName, topAggregation, null,
NO_EXTRA_FILTER, NO_OTHER_SUBAGGREGATION);
assertThat(aggregationBuilder.getName()).isEqualTo(topAggregationName);
assertThat(aggregationBuilder.getSubAggregations()).hasSize(1);
assertThat(aggregationBuilder.getSubAggregations().iterator().next()).isSameAs(termSubAgg);
}
@Test
public void buildTermTopAggregation_adds_subAggregation_from_lambda_parameter() {
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
AggregationBuilder[] subAggs = IntStream.range(0, 1 + new Random().nextInt(12))
.mapToObj(i -> AggregationBuilders.min("subAgg_" + i))
.toArray(AggregationBuilder[]::new);
String topAggregationName = randomAlphabetic(10);
TermsAggregationBuilder termSubAgg = AggregationBuilders.terms("foo");
when(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, null)).thenReturn(termSubAgg);
AggregationBuilder[] allSubAggs = Stream.concat(Arrays.stream(subAggs), Stream.of(termSubAgg)).toArray(AggregationBuilder[]::new);
AggregationBuilder aggregationBuilder = underTest.buildTermTopAggregation(
topAggregationName, topAggregation, null,
NO_EXTRA_FILTER, t -> Arrays.stream(subAggs).forEach(t::subAggregation));
assertThat(aggregationBuilder.getName()).isEqualTo(topAggregationName);
assertThat(aggregationBuilder.getSubAggregations()).hasSize(allSubAggs.length);
assertThat(aggregationBuilder.getSubAggregations()).containsExactlyInAnyOrder(allSubAggs);
}
@Test
public void buildTermTopAggregation_adds_filter_from_FiltersComputer_for_TopAggregation() {
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
SimpleFieldTopAggregationDefinition otherTopAggregation = new SimpleFieldTopAggregationDefinition("acme", false);
BoolQueryBuilder computerFilter = boolQuery();
BoolQueryBuilder otherFilter = boolQuery();
when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.of(computerFilter));
when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter));
String topAggregationName = randomAlphabetic(10);
TermsAggregationBuilder termSubAgg = AggregationBuilders.terms("foo");
when(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, null)).thenReturn(termSubAgg);
FilterAggregationBuilder aggregationBuilder = underTest.buildTermTopAggregation(
topAggregationName, topAggregation, null,
NO_EXTRA_FILTER, NO_OTHER_SUBAGGREGATION);
assertThat(aggregationBuilder.getName()).isEqualTo(topAggregationName);
assertThat(aggregationBuilder.getFilter()).isSameAs(computerFilter);
}
@Test
public void buildTermTopAggregation_has_empty_filter_when_FiltersComputer_returns_empty_for_TopAggregation() {
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
SimpleFieldTopAggregationDefinition otherTopAggregation = new SimpleFieldTopAggregationDefinition("acme", false);
BoolQueryBuilder otherFilter = boolQuery();
when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.empty());
when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter));
String topAggregationName = randomAlphabetic(10);
TermsAggregationBuilder termSubAgg = AggregationBuilders.terms("foo");
when(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, null)).thenReturn(termSubAgg);
FilterAggregationBuilder aggregationBuilder = underTest.buildTermTopAggregation(
topAggregationName, topAggregation, null,
NO_EXTRA_FILTER, NO_OTHER_SUBAGGREGATION);
assertThat(aggregationBuilder.getName()).isEqualTo(topAggregationName);
assertThat(aggregationBuilder.getFilter()).isEqualTo(boolQuery()).isNotSameAs(otherFilter);
}
@Test
public void buildTermTopAggregation_adds_filter_from_FiltersComputer_for_TopAggregation_and_extra_one() {
String topAggregationName = randomAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
SimpleFieldTopAggregationDefinition otherTopAggregation = new SimpleFieldTopAggregationDefinition("acme", false);
BoolQueryBuilder computerFilter = boolQuery();
BoolQueryBuilder otherFilter = boolQuery();
BoolQueryBuilder extraFilter = boolQuery();
when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.of(computerFilter));
when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter));
TermsAggregationBuilder termSubAgg = AggregationBuilders.terms("foo");
when(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, null)).thenReturn(termSubAgg);
FilterAggregationBuilder aggregationBuilder = underTest.buildTermTopAggregation(
topAggregationName, topAggregation, null,
t -> t.must(extraFilter), NO_OTHER_SUBAGGREGATION);
assertThat(aggregationBuilder.getName()).isEqualTo(topAggregationName);
assertThat(aggregationBuilder.getFilter()).isEqualTo(computerFilter);
assertThat(((BoolQueryBuilder) aggregationBuilder.getFilter()).must()).containsExactly(extraFilter);
}
}
| 13,961 | 56.694215 | 134 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/es/textsearch/ComponentTextSearchQueryFactoryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.es.textsearch;
import org.elasticsearch.index.query.QueryBuilder;
import org.junit.Test;
import org.sonar.server.es.textsearch.ComponentTextSearchQueryFactory.ComponentTextSearchQuery;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.es.textsearch.ComponentTextSearchQueryFactory.createQuery;
import static org.sonar.test.JsonAssert.assertJson;
public class ComponentTextSearchQueryFactoryTest {
@Test
public void create_query() {
QueryBuilder result = createQuery(ComponentTextSearchQuery.builder()
.setQueryText("SonarQube").setFieldKey("key").setFieldName("name").build(),
ComponentTextSearchFeatureRepertoire.KEY);
assertJson(result.toString()).isSimilarTo("{" +
" \"bool\" : {" +
" \"must\" : [{" +
" \"bool\" : {" +
" \"should\" : [{" +
" \"match\" : {" +
" \"key.sortable_analyzer\" : {" +
" \"query\" : \"SonarQube\"," +
" \"boost\" : 50.0\n" +
" }" +
" }" +
" }]" +
" }" +
" }]" +
" }" +
"}");
}
@Test
public void fail_to_create_query_when_no_feature() {
assertThatThrownBy(() -> {
createQuery(ComponentTextSearchQuery.builder()
.setQueryText("SonarQube").setFieldKey("key").setFieldName("name").build());
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("features cannot be empty");
}
@Test
public void fail_to_create_query_when_no_query_text() {
assertThatThrownBy(() -> ComponentTextSearchQuery.builder().setFieldKey("key").setFieldName("name").build())
.isInstanceOf(NullPointerException.class)
.hasMessage("query text cannot be null");
}
@Test
public void fail_to_create_query_when_no_field_key() {
assertThatThrownBy(() -> ComponentTextSearchQuery.builder().setQueryText("SonarQube").setFieldName("name").build())
.isInstanceOf(NullPointerException.class)
.hasMessage("field key cannot be null");
}
@Test
public void fail_to_create_query_when_no_field_name() {
assertThatThrownBy(() -> ComponentTextSearchQuery.builder().setQueryText("SonarQube").setFieldKey("key").build())
.isInstanceOf(NullPointerException.class)
.hasMessage("field name cannot be null");
}
}
| 3,236 | 35.784091 | 119 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/extension/CoreExtensionBootstraperTest.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.extension;
import org.junit.Test;
import org.sonar.api.platform.Server;
import org.sonar.core.platform.SpringComponentContainer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
public class CoreExtensionBootstraperTest {
private final SpringComponentContainer componentContainer = new SpringComponentContainer();
private final CoreExtensionBridge bridge = mock(CoreExtensionBridge.class);
private final CoreExtensionBootstraper underTest = new CoreExtensionBootstraper(componentContainer);
@Test
public void onServerStart_calls_startPlugin_if_Bridge_exists_in_container() {
componentContainer.add(bridge);
componentContainer.startComponents();
underTest.onServerStart(mock(Server.class));
verify(bridge).getPluginName();
verify(bridge).startPlugin(componentContainer);
verifyNoMoreInteractions(bridge);
}
@Test
public void onServerStart_does_not_call_startPlugin_if_Bridge_does_not_exist_in_container() {
componentContainer.startComponents();
underTest.onServerStart(mock(Server.class));
verifyNoMoreInteractions(bridge);
}
}
| 2,050 | 36.290909 | 102 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/extension/CoreExtensionStopperTest.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.extension;
import org.junit.Test;
import org.sonar.core.platform.SpringComponentContainer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
public class CoreExtensionStopperTest {
private final SpringComponentContainer componentContainer = new SpringComponentContainer();
private final CoreExtensionBridge bridge = mock(CoreExtensionBridge.class);
private final CoreExtensionStopper underTest = new CoreExtensionStopper(componentContainer);
@Test
public void stop_calls_stopPlugin_if_Bridge_exists_in_container() {
componentContainer.add(bridge);
componentContainer.startComponents();
underTest.stop();
verify(bridge).getPluginName();
verify(bridge).stopPlugin();
verifyNoMoreInteractions(bridge);
}
@Test
public void stop_does_not_call_stopPlugin_if_Bridge_does_not_exist_in_container() {
componentContainer.startComponents();
underTest.stop();
verifyNoMoreInteractions(bridge);
}
}
| 1,907 | 34.333333 | 94 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/IssueFieldsSetterTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.apache.commons.lang.time.DateUtils;
import org.junit.Test;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.Duration;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.FieldDiffs;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.db.protobuf.DbCommons;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.protobuf.DbIssues.MessageFormattingType;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserIdDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByUserBuilder;
import static org.sonar.db.protobuf.DbIssues.MessageFormattingType.CODE;
import static org.sonar.db.user.UserTesting.newUserDto;
import static org.sonar.server.issue.IssueFieldsSetter.ASSIGNEE;
import static org.sonar.server.issue.IssueFieldsSetter.RESOLUTION;
import static org.sonar.server.issue.IssueFieldsSetter.SEVERITY;
import static org.sonar.server.issue.IssueFieldsSetter.STATUS;
import static org.sonar.server.issue.IssueFieldsSetter.TECHNICAL_DEBT;
import static org.sonar.server.issue.IssueFieldsSetter.TYPE;
import static org.sonar.server.issue.IssueFieldsSetter.UNUSED;
public class IssueFieldsSetterTest {
private final String DEFAULT_RULE_DESCRIPTION_CONTEXT_KEY = "spring";
private final DefaultIssue issue = new DefaultIssue();
private final IssueChangeContext context = issueChangeContextByUserBuilder(new Date(), "user_uuid").build();
private final IssueFieldsSetter underTest = new IssueFieldsSetter();
@Test
public void assign() {
UserDto user = newUserDto().setLogin("emmerik").setName("Emmerik");
boolean updated = underTest.assign(issue, user, context);
assertThat(updated).isTrue();
assertThat(issue.assignee()).isEqualTo(user.getUuid());
assertThat(issue.mustSendNotifications()).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get(ASSIGNEE);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isEqualTo(user.getName());
}
@Test
public void unassign() {
issue.setAssigneeUuid("user_uuid");
boolean updated = underTest.assign(issue, null, context);
assertThat(updated).isTrue();
assertThat(issue.assignee()).isNull();
assertThat(issue.mustSendNotifications()).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get(ASSIGNEE);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isNull();
}
@Test
public void change_assignee() {
UserDto user = newUserDto().setLogin("emmerik").setName("Emmerik");
issue.setAssigneeUuid("user_uuid");
boolean updated = underTest.assign(issue, user, context);
assertThat(updated).isTrue();
assertThat(issue.assignee()).isEqualTo(user.getUuid());
assertThat(issue.mustSendNotifications()).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get(ASSIGNEE);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isEqualTo(user.getName());
}
@Test
public void not_change_assignee() {
UserDto user = newUserDto().setLogin("morgan").setName("Morgan");
issue.setAssigneeUuid(user.getUuid());
boolean updated = underTest.assign(issue, user, context);
assertThat(updated).isFalse();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_new_assignee() {
boolean updated = underTest.setNewAssignee(issue, new UserIdDto("user_uuid", "user_login"), context);
assertThat(updated).isTrue();
assertThat(issue.assignee()).isEqualTo("user_uuid");
assertThat(issue.assigneeLogin()).isEqualTo("user_login");
assertThat(issue.mustSendNotifications()).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get(ASSIGNEE);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isEqualTo("user_uuid");
}
@Test
public void not_set_new_assignee_if_new_assignee_is_null() {
boolean updated = underTest.setNewAssignee(issue, null, context);
assertThat(updated).isFalse();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void fail_with_ISE_when_setting_new_assignee_on_already_assigned_issue() {
issue.setAssigneeUuid("user_uuid");
UserIdDto userId = new UserIdDto("another_user_uuid", "another_user_login");
assertThatThrownBy(() -> underTest.setNewAssignee(issue, userId, context))
.isInstanceOf(IllegalStateException.class)
.hasMessage("It's not possible to update the assignee with this method, please use assign()");
}
@Test
public void set_type() {
issue.setType(RuleType.CODE_SMELL);
boolean updated = underTest.setType(issue, RuleType.BUG, context);
assertThat(updated).isTrue();
assertThat(issue.type()).isEqualTo(RuleType.BUG);
assertThat(issue.manualSeverity()).isFalse();
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(TYPE);
assertThat(diff.oldValue()).isEqualTo(RuleType.CODE_SMELL);
assertThat(diff.newValue()).isEqualTo(RuleType.BUG);
}
@Test
public void set_severity() {
boolean updated = underTest.setSeverity(issue, "BLOCKER", context);
assertThat(updated).isTrue();
assertThat(issue.severity()).isEqualTo("BLOCKER");
assertThat(issue.manualSeverity()).isFalse();
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(SEVERITY);
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("BLOCKER");
}
@Test
public void set_past_severity() {
issue.setSeverity("BLOCKER");
boolean updated = underTest.setPastSeverity(issue, "INFO", context);
assertThat(updated).isTrue();
assertThat(issue.severity()).isEqualTo("BLOCKER");
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(SEVERITY);
assertThat(diff.oldValue()).isEqualTo("INFO");
assertThat(diff.newValue()).isEqualTo("BLOCKER");
}
@Test
public void update_severity() {
issue.setSeverity("BLOCKER");
boolean updated = underTest.setSeverity(issue, "MINOR", context);
assertThat(updated).isTrue();
assertThat(issue.severity()).isEqualTo("MINOR");
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(SEVERITY);
assertThat(diff.oldValue()).isEqualTo("BLOCKER");
assertThat(diff.newValue()).isEqualTo("MINOR");
}
@Test
public void not_change_severity() {
issue.setSeverity("MINOR");
boolean updated = underTest.setSeverity(issue, "MINOR", context);
assertThat(updated).isFalse();
assertThat(issue.mustSendNotifications()).isFalse();
assertThat(issue.currentChange()).isNull();
}
@Test
public void not_revert_manual_severity() {
issue.setSeverity("MINOR").setManualSeverity(true);
try {
underTest.setSeverity(issue, "MAJOR", context);
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Severity can't be changed");
}
}
@Test
public void set_manual_severity() {
issue.setSeverity("BLOCKER");
boolean updated = underTest.setManualSeverity(issue, "MINOR", context);
assertThat(updated).isTrue();
assertThat(issue.severity()).isEqualTo("MINOR");
assertThat(issue.manualSeverity()).isTrue();
assertThat(issue.mustSendNotifications()).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get(SEVERITY);
assertThat(diff.oldValue()).isEqualTo("BLOCKER");
assertThat(diff.newValue()).isEqualTo("MINOR");
}
@Test
public void not_change_manual_severity() {
issue.setSeverity("MINOR").setManualSeverity(true);
boolean updated = underTest.setManualSeverity(issue, "MINOR", context);
assertThat(updated).isFalse();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void unset_line() {
int line = 1 + new Random().nextInt(500);
issue.setLine(line);
boolean updated = underTest.unsetLine(issue, context);
assertThat(updated).isTrue();
assertThat(issue.isChanged()).isTrue();
assertThat(issue.line()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
assertThat(issue.currentChange())
.extracting(f -> f.diffs().size())
.isEqualTo(1);
FieldDiffs.Diff diff = issue.currentChange().diffs().get("line");
assertThat(diff.oldValue()).isEqualTo(line);
assertThat(diff.newValue()).isEqualTo("");
}
@Test
public void unset_line_has_no_effect_if_line_is_already_null() {
issue.setLine(null);
boolean updated = underTest.unsetLine(issue, context);
assertThat(updated).isFalse();
assertThat(issue.line()).isNull();
assertThat(issue.isChanged()).isFalse();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_past_line() {
issue.setLine(42);
boolean updated = underTest.setPastLine(issue, 123);
assertThat(updated).isTrue();
assertThat(issue.isChanged()).isTrue();
assertThat(issue.line()).isEqualTo(42);
assertThat(issue.mustSendNotifications()).isFalse();
// do not save change
assertThat(issue.currentChange()).isNull();
}
@Test
public void set_past_line_has_no_effect_if_line_already_had_value() {
issue.setLine(42);
boolean updated = underTest.setPastLine(issue, 42);
assertThat(updated).isFalse();
assertThat(issue.isChanged()).isFalse();
assertThat(issue.line()).isEqualTo(42);
assertThat(issue.mustSendNotifications()).isFalse();
// do not save change
assertThat(issue.currentChange()).isNull();
}
@Test
public void change_locations_if_primary_text_rage_changed() {
DbCommons.TextRange range = DbCommons.TextRange.newBuilder().setStartLine(1).build();
DbIssues.Locations locations = DbIssues.Locations.newBuilder()
.setTextRange(range)
.build();
DbIssues.Locations locations2 = locations.toBuilder().setTextRange(range.toBuilder().setEndLine(2).build()).build();
issue.setLocations(locations);
boolean updated = underTest.setLocations(issue, locations2);
assertThat(updated).isTrue();
assertThat((Object) issue.getLocations()).isEqualTo(locations2);
assertThat(issue.locationsChanged()).isTrue();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void change_locations_if_secondary_text_rage_changed() {
DbCommons.TextRange range = DbCommons.TextRange.newBuilder().setStartLine(1).build();
DbIssues.Locations locations = DbIssues.Locations.newBuilder()
.addFlow(DbIssues.Flow.newBuilder()
.addLocation(DbIssues.Location.newBuilder().setTextRange(range))
.build())
.build();
issue.setLocations(locations);
DbIssues.Locations.Builder builder = locations.toBuilder();
builder.getFlowBuilder(0).getLocationBuilder(0).setTextRange(range.toBuilder().setEndLine(2));
boolean updated = underTest.setLocations(issue, builder.build());
assertThat(updated).isTrue();
}
@Test
public void change_locations_if_secondary_message_changed() {
DbIssues.Locations locations = DbIssues.Locations.newBuilder()
.addFlow(DbIssues.Flow.newBuilder()
.addLocation(DbIssues.Location.newBuilder().setMsg("msg1"))
.build())
.build();
issue.setLocations(locations);
DbIssues.Locations.Builder builder = locations.toBuilder();
builder.getFlowBuilder(0).getLocationBuilder(0).setMsg("msg2");
boolean updated = underTest.setLocations(issue, builder.build());
assertThat(updated).isTrue();
}
@Test
public void change_locations_if_different_flow_count() {
DbIssues.Locations locations = DbIssues.Locations.newBuilder()
.addFlow(DbIssues.Flow.newBuilder()
.addLocation(DbIssues.Location.newBuilder())
.build())
.build();
issue.setLocations(locations);
DbIssues.Locations.Builder builder = locations.toBuilder();
builder.clearFlow();
boolean updated = underTest.setLocations(issue, builder.build());
assertThat(updated).isTrue();
}
@Test
public void do_not_change_locations_if_primary_hash_changed() {
DbCommons.TextRange range = DbCommons.TextRange.newBuilder().setStartLine(1).build();
DbIssues.Locations locations = DbIssues.Locations.newBuilder()
.setTextRange(range)
.setChecksum("1")
.build();
issue.setLocations(locations);
boolean updated = underTest.setLocations(issue, locations.toBuilder().setChecksum("2").build());
assertThat(updated).isFalse();
}
@Test
public void do_not_change_locations_if_secondary_hash_changed() {
DbCommons.TextRange range = DbCommons.TextRange.newBuilder().setStartLine(1).build();
DbIssues.Locations locations = DbIssues.Locations.newBuilder()
.addFlow(DbIssues.Flow.newBuilder()
.addLocation(DbIssues.Location.newBuilder().setTextRange(range))
.build())
.setChecksum("1")
.build();
issue.setLocations(locations);
DbIssues.Locations.Builder builder = locations.toBuilder();
builder.getFlowBuilder(0).getLocationBuilder(0).setChecksum("2");
boolean updated = underTest.setLocations(issue, builder.build());
assertThat(updated).isFalse();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_locations_for_the_first_time() {
issue.setLocations(null);
boolean updated = underTest.setLocations(issue, "[1-4]");
assertThat(updated).isTrue();
assertThat(issue.getLocations().toString()).isEqualTo("[1-4]");
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_resolution() {
boolean updated = underTest.setResolution(issue, "OPEN", context);
assertThat(updated).isTrue();
assertThat(issue.resolution()).isEqualTo("OPEN");
FieldDiffs.Diff diff = issue.currentChange().get(RESOLUTION);
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("OPEN");
assertThat(issue.mustSendNotifications()).isTrue();
}
@Test
public void not_change_resolution() {
issue.setResolution("FIXED");
boolean updated = underTest.setResolution(issue, "FIXED", context);
assertThat(updated).isFalse();
assertThat(issue.resolution()).isEqualTo("FIXED");
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_status() {
boolean updated = underTest.setStatus(issue, "OPEN", context);
assertThat(updated).isTrue();
assertThat(issue.status()).isEqualTo("OPEN");
FieldDiffs.Diff diff = issue.currentChange().get(STATUS);
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("OPEN");
assertThat(issue.mustSendNotifications()).isTrue();
}
@Test
public void not_change_status() {
issue.setStatus("CLOSED");
boolean updated = underTest.setStatus(issue, "CLOSED", context);
assertThat(updated).isFalse();
assertThat(issue.status()).isEqualTo("CLOSED");
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_gap_to_fix() {
boolean updated = underTest.setGap(issue, 3.14, context);
assertThat(updated).isTrue();
assertThat(issue.isChanged()).isTrue();
assertThat(issue.gap()).isEqualTo(3.14);
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void not_set_gap_to_fix_if_unchanged() {
issue.setGap(3.14);
boolean updated = underTest.setGap(issue, 3.14, context);
assertThat(updated).isFalse();
assertThat(issue.isChanged()).isFalse();
assertThat(issue.gap()).isEqualTo(3.14);
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_past_gap() {
issue.setGap(3.14);
boolean updated = underTest.setPastGap(issue, 1.0, context);
assertThat(updated).isTrue();
assertThat(issue.gap()).isEqualTo(3.14);
// do not save change
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_past_technical_debt() {
Duration newDebt = Duration.create(15 * 8 * 60);
Duration previousDebt = Duration.create(10 * 8 * 60);
issue.setEffort(newDebt);
boolean updated = underTest.setPastEffort(issue, previousDebt, context);
assertThat(updated).isTrue();
assertThat(issue.effort()).isEqualTo(newDebt);
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(TECHNICAL_DEBT);
assertThat(diff.oldValue()).isEqualTo(10L * 8 * 60);
assertThat(diff.newValue()).isEqualTo(15L * 8 * 60);
}
@Test
public void set_past_technical_debt_without_previous_value() {
Duration newDebt = Duration.create(15 * 8 * 60);
issue.setEffort(newDebt);
boolean updated = underTest.setPastEffort(issue, null, context);
assertThat(updated).isTrue();
assertThat(issue.effort()).isEqualTo(newDebt);
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(TECHNICAL_DEBT);
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo(15L * 8 * 60);
}
@Test
public void set_past_technical_debt_with_null_new_value() {
issue.setEffort(null);
Duration previousDebt = Duration.create(10 * 8 * 60);
boolean updated = underTest.setPastEffort(issue, previousDebt, context);
assertThat(updated).isTrue();
assertThat(issue.effort()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(TECHNICAL_DEBT);
assertThat(diff.oldValue()).isEqualTo(10L * 8 * 60);
assertThat(diff.newValue()).isNull();
}
@Test
public void setCodeVariants_whenCodeVariantAdded_shouldBeUpdated() {
Set<String> currentCodeVariants = new HashSet<>(Arrays.asList("linux"));
Set<String> newCodeVariants = new HashSet<>(Arrays.asList("linux", "windows"));
issue.setCodeVariants(newCodeVariants);
boolean updated = underTest.setCodeVariants(issue, currentCodeVariants, context);
assertThat(updated).isTrue();
assertThat(issue.codeVariants()).contains("linux", "windows");
FieldDiffs.Diff diff = issue.currentChange().get("code_variants");
assertThat(diff.oldValue()).isEqualTo("linux");
assertThat(diff.newValue()).isEqualTo("linux windows");
assertThat(issue.mustSendNotifications()).isTrue();
}
@Test
public void setCodeVariants_whenCodeVariantsUnchanged_shouldNotBeUpdated() {
Set<String> currentCodeVariants = new HashSet<>(Arrays.asList("linux", "windows"));
Set<String> newCodeVariants = new HashSet<>(Arrays.asList("windows", "linux"));
issue.setCodeVariants(newCodeVariants);
boolean updated = underTest.setCodeVariants(issue, currentCodeVariants, context);
assertThat(updated).isFalse();
assertThat(issue.currentChange()).isNull();
}
@Test
public void set_message() {
boolean updated = underTest.setMessage(issue, "the message", context);
assertThat(updated).isTrue();
assertThat(issue.isChanged()).isTrue();
assertThat(issue.message()).isEqualTo("the message");
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_past_message() {
issue.setMessage("new message");
boolean updated = underTest.setPastMessage(issue, "past message", null, context);
assertThat(updated).isTrue();
assertThat(issue.message()).isEqualTo("new message");
// do not save change
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_past_message_formatting() {
issue.setMessage("past message");
DbIssues.MessageFormattings newFormatting = formattings(formatting(0, 3, CODE));
DbIssues.MessageFormattings pastFormatting = formattings(formatting(0, 7, CODE));
issue.setMessageFormattings(newFormatting);
boolean updated = underTest.setPastMessage(issue, "past message", pastFormatting, context);
assertThat(updated).isTrue();
assertThat(issue.message()).isEqualTo("past message");
assertThat((DbIssues.MessageFormattings) issue.getMessageFormattings()).isEqualTo(newFormatting);
// do not save change
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_past_message_formatting_no_changes() {
issue.setMessage("past message");
DbIssues.MessageFormattings sameFormatting = formattings(formatting(0, 3, CODE));
issue.setMessageFormattings(sameFormatting);
boolean updated = underTest.setPastMessage(issue, "past message", sameFormatting, context);
assertThat(updated).isFalse();
assertThat(issue.message()).isEqualTo("past message");
assertThat((DbIssues.MessageFormattings) issue.getMessageFormattings()).isEqualTo(sameFormatting);
// do not save change
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void message_formatting_different_size_is_changed(){
issue.setMessageFormattings(formattings(formatting(0,3,CODE)));
boolean updated = underTest.setLocations(issue, formattings(formatting(0,3,CODE), formatting(4,6,CODE)));
assertThat(updated).isTrue();
}
@Test
public void message_formatting_different_start_is_changed(){
issue.setMessageFormattings(formattings(formatting(0,3,CODE)));
boolean updated = underTest.setLocations(issue, formattings(formatting(1,3,CODE)));
assertThat(updated).isTrue();
}
@Test
public void message_formatting_different_end_is_changed(){
issue.setMessageFormattings(formattings(formatting(0,3,CODE)));
boolean updated = underTest.setLocations(issue, formattings(formatting(0,4,CODE)));
assertThat(updated).isTrue();
}
private static DbIssues.MessageFormatting formatting(int start, int end, MessageFormattingType type) {
return DbIssues.MessageFormatting
.newBuilder()
.setStart(start)
.setEnd(end)
.setType(type)
.build();
}
private static DbIssues.MessageFormattings formattings(DbIssues.MessageFormatting... messageFormatting) {
return DbIssues.MessageFormattings.newBuilder()
.addAllMessageFormatting(List.of(messageFormatting))
.build();
}
@Test
public void set_author() {
boolean updated = underTest.setAuthorLogin(issue, "eric", context);
assertThat(updated).isTrue();
assertThat(issue.authorLogin()).isEqualTo("eric");
FieldDiffs.Diff diff = issue.currentChange().get("author");
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("eric");
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_new_author() {
boolean updated = underTest.setNewAuthor(issue, "simon", context);
assertThat(updated).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get("author");
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("simon");
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void not_set_new_author_if_new_author_is_null() {
boolean updated = underTest.setNewAuthor(issue, null, context);
assertThat(updated).isFalse();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void fail_with_ISE_when_setting_new_author_on_issue() {
issue.setAuthorLogin("simon");
assertThatThrownBy(() -> underTest.setNewAuthor(issue, "julien", context))
.isInstanceOf(IllegalStateException.class)
.hasMessage("It's not possible to update the author with this method, please use setAuthorLogin()");
}
@Test
public void setIssueComponent_has_no_effect_if_component_uuid_is_not_changed() {
String componentKey = "key";
String componentUuid = "uuid";
issue.setComponentUuid(componentUuid);
issue.setComponentKey(componentKey);
underTest.setIssueComponent(issue, componentUuid, componentKey, context.date());
assertThat(issue.componentUuid()).isEqualTo(componentUuid);
assertThat(issue.componentKey()).isEqualTo(componentKey);
assertThat(issue.isChanged()).isFalse();
assertThat(issue.updateDate()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void setIssueComponent_changes_component_uuid() {
String oldComponentUuid = "a";
String newComponentUuid = "b";
String componentKey = "key";
issue.setComponentUuid(oldComponentUuid);
underTest.setIssueComponent(issue, newComponentUuid, componentKey, context.date());
assertThat(issue.componentUuid()).isEqualTo(newComponentUuid);
assertThat(issue.componentKey()).isEqualTo(componentKey);
assertThat(issue.isChanged()).isTrue();
assertThat(issue.updateDate()).isEqualTo(DateUtils.truncate(context.date(), Calendar.SECOND));
}
@Test
public void setRuleDescriptionContextKey_setContextKeyIfPreviousValueIsNull() {
issue.setRuleDescriptionContextKey(DEFAULT_RULE_DESCRIPTION_CONTEXT_KEY);
boolean updated = underTest.setRuleDescriptionContextKey(issue, null);
assertThat(updated).isTrue();
assertThat(issue.getRuleDescriptionContextKey()).contains(DEFAULT_RULE_DESCRIPTION_CONTEXT_KEY);
}
@Test
public void setRuleDescriptionContextKey_dontSetContextKeyIfPreviousValueIsTheSame() {
issue.setRuleDescriptionContextKey(DEFAULT_RULE_DESCRIPTION_CONTEXT_KEY);
boolean updated = underTest.setRuleDescriptionContextKey(issue, DEFAULT_RULE_DESCRIPTION_CONTEXT_KEY);
assertThat(updated).isFalse();
assertThat(issue.getRuleDescriptionContextKey()).contains(DEFAULT_RULE_DESCRIPTION_CONTEXT_KEY);
}
@Test
public void setRuleDescriptionContextKey_dontSetContextKeyIfBothValuesAreNull() {
issue.setRuleDescriptionContextKey(null);
boolean updated = underTest.setRuleDescriptionContextKey(issue, null);
assertThat(updated).isFalse();
assertThat(issue.getRuleDescriptionContextKey()).isEmpty();
}
@Test
public void setRuleDescriptionContextKey_setContextKeyIfValuesAreDifferent() {
issue.setRuleDescriptionContextKey(DEFAULT_RULE_DESCRIPTION_CONTEXT_KEY);
boolean updated = underTest.setRuleDescriptionContextKey(issue, "hibernate");
assertThat(updated).isTrue();
assertThat(issue.getRuleDescriptionContextKey()).contains(DEFAULT_RULE_DESCRIPTION_CONTEXT_KEY);
}
}
| 28,004 | 36.844595 | 120 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/SearchRequestTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import org.junit.Test;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
public class SearchRequestTest {
@Test
public void settersAndGetters() {
SearchRequest underTest = new SearchRequest()
.setIssues(singletonList("anIssueKey"))
.setSeverities(asList("MAJOR", "MINOR"))
.setStatuses(singletonList("CLOSED"))
.setResolutions(singletonList("FALSE-POSITIVE"))
.setResolved(true)
.setProjectKeys(singletonList("project-a"))
.setDirectories(singletonList("aDirPath"))
.setFiles(asList("file-a", "file-b"))
.setAssigneesUuid(asList("user-a", "user-b"))
.setScopes(asList("MAIN", "TEST"))
.setLanguages(singletonList("xoo"))
.setTags(asList("tag1", "tag2"))
.setAssigned(true)
.setCreatedAfter("2013-04-16T09:08:24+0200")
.setCreatedBefore("2013-04-17T09:08:24+0200")
.setRules(asList("key-a", "key-b"))
.setSort("CREATION_DATE")
.setAsc(true)
.setInNewCodePeriod(true)
.setOwaspTop10For2021(asList("a2", "a3"))
.setOwaspAsvs40(asList("1.1.1", "4.2.2"))
.setOwaspAsvsLevel(2)
.setPciDss32(asList("1", "4"))
.setPciDss40(asList("3", "5"))
.setCodeVariants(asList("variant1", "variant2"));
assertThat(underTest.getIssues()).containsOnlyOnce("anIssueKey");
assertThat(underTest.getSeverities()).containsExactly("MAJOR", "MINOR");
assertThat(underTest.getStatuses()).containsExactly("CLOSED");
assertThat(underTest.getResolutions()).containsExactly("FALSE-POSITIVE");
assertThat(underTest.getResolved()).isTrue();
assertThat(underTest.getProjectKeys()).containsExactly("project-a");
assertThat(underTest.getDirectories()).containsExactly("aDirPath");
assertThat(underTest.getFiles()).containsExactly("file-a", "file-b");
assertThat(underTest.getAssigneeUuids()).containsExactly("user-a", "user-b");
assertThat(underTest.getScopes()).containsExactly("MAIN", "TEST");
assertThat(underTest.getLanguages()).containsExactly("xoo");
assertThat(underTest.getTags()).containsExactly("tag1", "tag2");
assertThat(underTest.getAssigned()).isTrue();
assertThat(underTest.getCreatedAfter()).isEqualTo("2013-04-16T09:08:24+0200");
assertThat(underTest.getCreatedBefore()).isEqualTo("2013-04-17T09:08:24+0200");
assertThat(underTest.getRules()).containsExactly("key-a", "key-b");
assertThat(underTest.getSort()).isEqualTo("CREATION_DATE");
assertThat(underTest.getAsc()).isTrue();
assertThat(underTest.getInNewCodePeriod()).isTrue();
assertThat(underTest.getOwaspTop10For2021()).containsExactly("a2", "a3");
assertThat(underTest.getOwaspAsvs40()).containsExactly("1.1.1", "4.2.2");
assertThat(underTest.getOwaspAsvsLevel()).isEqualTo(2);
assertThat(underTest.getPciDss32()).containsExactly("1", "4");
assertThat(underTest.getPciDss40()).containsExactly("3", "5");
assertThat(underTest.getCodeVariants()).containsExactly("variant1", "variant2");
}
@Test
public void setScopesAcceptsNull() {
SearchRequest underTest = new SearchRequest().setScopes(null);
assertThat(underTest.getScopes()).isNull();
}
}
| 4,132 | 43.44086 | 84 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/TaintCheckerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.config.Configuration;
import org.sonar.api.rules.RuleType;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.protobuf.DbCommons;
import org.sonar.db.protobuf.DbIssues;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.server.issue.TaintChecker.EXTRA_TAINT_REPOSITORIES;
public class TaintCheckerTest {
private final Configuration configuration = mock(Configuration.class);
private final TaintChecker underTest = new TaintChecker(configuration);
@Test
public void test_getTaintIssuesOnly() {
List<IssueDto> taintIssues = underTest.getTaintIssuesOnly(getIssues());
assertThat(taintIssues).hasSize(6);
assertThat(taintIssues.get(0).getKey()).isEqualTo("taintIssue1");
assertThat(taintIssues.get(1).getKey()).isEqualTo("taintIssue2");
assertThat(taintIssues.get(2).getKey()).isEqualTo("taintIssue3");
assertThat(taintIssues.get(3).getKey()).isEqualTo("taintIssue4");
assertThat(taintIssues.get(4).getKey()).isEqualTo("taintIssue5");
assertThat(taintIssues.get(5).getKey()).isEqualTo("taintIssue6");
}
@Test
public void test_getStandardIssuesOnly() {
List<IssueDto> standardIssues = underTest.getStandardIssuesOnly(getIssues());
assertThat(standardIssues).hasSize(3);
assertThat(standardIssues.get(0).getKey()).isEqualTo("standardIssue1");
assertThat(standardIssues.get(1).getKey()).isEqualTo("standardIssue2");
assertThat(standardIssues.get(2).getKey()).isEqualTo("standardIssue3");
}
@Test
public void test_mapIssuesByTaintStatus() {
Map<Boolean, List<IssueDto>> issuesByTaintStatus = underTest.mapIssuesByTaintStatus(getIssues());
assertThat(issuesByTaintStatus.keySet()).hasSize(2);
assertThat(issuesByTaintStatus.get(true)).hasSize(6);
assertThat(issuesByTaintStatus.get(false)).hasSize(3);
assertThat(issuesByTaintStatus.get(true).get(0).getKey()).isEqualTo("taintIssue1");
assertThat(issuesByTaintStatus.get(true).get(1).getKey()).isEqualTo("taintIssue2");
assertThat(issuesByTaintStatus.get(true).get(2).getKey()).isEqualTo("taintIssue3");
assertThat(issuesByTaintStatus.get(true).get(3).getKey()).isEqualTo("taintIssue4");
assertThat(issuesByTaintStatus.get(true).get(4).getKey()).isEqualTo("taintIssue5");
assertThat(issuesByTaintStatus.get(true).get(5).getKey()).isEqualTo("taintIssue6");
assertThat(issuesByTaintStatus.get(false).get(0).getKey()).isEqualTo("standardIssue1");
assertThat(issuesByTaintStatus.get(false).get(1).getKey()).isEqualTo("standardIssue2");
assertThat(issuesByTaintStatus.get(false).get(2).getKey()).isEqualTo("standardIssue3");
}
@Test
public void test_getTaintRepositories() {
assertThat(underTest.getTaintRepositories())
.hasSize(6)
.containsExactlyInAnyOrder("roslyn.sonaranalyzer.security.cs", "javasecurity", "jssecurity",
"tssecurity", "phpsecurity", "pythonsecurity");
}
@Test
public void test_getTaintRepositories_withExtraReposFromConfiguration() {
when(configuration.hasKey(EXTRA_TAINT_REPOSITORIES)).thenReturn(true);
when(configuration.getStringArray(EXTRA_TAINT_REPOSITORIES)).thenReturn(new String[]{"extra-1", "extra-2"});
TaintChecker underTest = new TaintChecker(configuration);
assertThat(underTest.getTaintRepositories())
.hasSize(8)
.containsExactlyInAnyOrder("roslyn.sonaranalyzer.security.cs", "javasecurity", "jssecurity",
"tssecurity", "phpsecurity", "pythonsecurity", "extra-1", "extra-2");
}
@Test
public void test_isTaintVulnerability() {
DefaultIssue taintWithoutLocation = createIssueWithRepository("noTaintIssue", "roslyn.sonaranalyzer.security.cs")
.toDefaultIssue();
DefaultIssue taint = createIssueWithRepository("taintIssue", "roslyn.sonaranalyzer.security.cs")
.setLocations(DbIssues.Locations.newBuilder()
.setTextRange(DbCommons.TextRange.newBuilder().build())
.build())
.toDefaultIssue();
DefaultIssue issue = createIssueWithRepository("standardIssue", "java")
.setLocations(DbIssues.Locations.newBuilder()
.setTextRange(DbCommons.TextRange.newBuilder().build())
.build())
.toDefaultIssue();
DefaultIssue hotspot = createIssueWithRepository("hotspot", "roslyn.sonaranalyzer.security.cs",
RuleType.SECURITY_HOTSPOT).toDefaultIssue();
assertThat(underTest.isTaintVulnerability(taintWithoutLocation)).isFalse();
assertThat(underTest.isTaintVulnerability(taint)).isTrue();
assertThat(underTest.isTaintVulnerability(issue)).isFalse();
assertThat(underTest.isTaintVulnerability(hotspot)).isFalse();
}
private List<IssueDto> getIssues() {
List<IssueDto> issues = new ArrayList<>();
issues.add(createIssueWithRepository("taintIssue1", "roslyn.sonaranalyzer.security.cs"));
issues.add(createIssueWithRepository("taintIssue2", "javasecurity"));
issues.add(createIssueWithRepository("taintIssue3", "jssecurity"));
issues.add(createIssueWithRepository("taintIssue4", "tssecurity"));
issues.add(createIssueWithRepository("taintIssue5", "phpsecurity"));
issues.add(createIssueWithRepository("taintIssue6", "pythonsecurity"));
issues.add(createIssueWithRepository("standardIssue1", "java"));
issues.add(createIssueWithRepository("standardIssue2", "python"));
issues.add(createIssueWithRepository("standardIssue3", "js"));
return issues;
}
private IssueDto createIssueWithRepository(String issueKey, String repository) {
return createIssueWithRepository(issueKey, repository, null);
}
private IssueDto createIssueWithRepository(String issueKey, String repository, @Nullable RuleType ruleType) {
IssueDto issueDto = new IssueDto();
issueDto.setStatus("OPEN");
issueDto.setKee(issueKey);
issueDto.setRuleKey(repository, "S1");
issueDto.setType(ruleType == null ? RuleType.VULNERABILITY : ruleType);
return issueDto;
}
}
| 7,069 | 42.913043 | 117 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/index/IssueIndexDefinitionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.index;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.es.Index;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.IndexType;
import org.sonar.server.es.newindex.NewIndex;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.permission.index.IndexAuthorizationConstants.TYPE_AUTHORIZATION;
public class IssueIndexDefinitionTest {
IndexDefinition.IndexDefinitionContext underTest = new IndexDefinition.IndexDefinitionContext();
@Test
public void define() {
IssueIndexDefinition def = new IssueIndexDefinition(new MapSettings().asConfig());
def.define(underTest);
assertThat(underTest.getIndices()).hasSize(1);
NewIndex<?> issuesIndex = underTest.getIndices().get("issues");
IndexType.IndexMainType mainType = IndexType.main(Index.withRelations("issues"), TYPE_AUTHORIZATION);
assertThat(issuesIndex.getMainType()).isEqualTo(mainType);
assertThat(issuesIndex.getRelationsStream())
.containsOnly(IndexType.relation(mainType, "issue"));
// no cluster by default
assertThat(issuesIndex.getSetting("index.number_of_shards")).isEqualTo("5");
assertThat(issuesIndex.getSetting("index.number_of_replicas")).isEqualTo("0");
}
}
| 2,159 | 39.754717 | 105 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/index/SecurityStandardCategoryStatisticsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.index;
import java.util.ArrayList;
import org.junit.Test;
import static java.util.OptionalInt.empty;
import static org.assertj.core.api.Assertions.assertThat;
public class SecurityStandardCategoryStatisticsTest {
@Test
public void hasMoreRules_default_false() {
SecurityStandardCategoryStatistics standardCategoryStatistics = new SecurityStandardCategoryStatistics(
"cat", 0, empty(), 0,
0, 5, null, null
);
assertThat(standardCategoryStatistics.hasMoreRules()).isFalse();
}
@Test
public void hasMoreRules_is_updatable() {
SecurityStandardCategoryStatistics standardCategoryStatistics = new SecurityStandardCategoryStatistics(
"cat", 0, empty(), 0,
0, 5, null, null
);
standardCategoryStatistics.setHasMoreRules(true);
assertThat(standardCategoryStatistics.hasMoreRules()).isTrue();
}
@Test
public void test_getters() {
SecurityStandardCategoryStatistics standardCategoryStatistics = new SecurityStandardCategoryStatistics(
"cat", 1, empty(), 0,
0, 5, new ArrayList<>(), "version"
).setLevel("1");
standardCategoryStatistics.setActiveRules(3);
standardCategoryStatistics.setTotalRules(3);
assertThat(standardCategoryStatistics.getCategory()).isEqualTo("cat");
assertThat(standardCategoryStatistics.getVulnerabilities()).isEqualTo(1);
assertThat(standardCategoryStatistics.getVulnerabilityRating()).isEmpty();
assertThat(standardCategoryStatistics.getToReviewSecurityHotspots()).isZero();
assertThat(standardCategoryStatistics.getReviewedSecurityHotspots()).isZero();
assertThat(standardCategoryStatistics.getSecurityReviewRating()).isEqualTo(5);
assertThat(standardCategoryStatistics.getChildren()).isEmpty();
assertThat(standardCategoryStatistics.getActiveRules()).isEqualTo(3);
assertThat(standardCategoryStatistics.getTotalRules()).isEqualTo(3);
assertThat(standardCategoryStatistics.getVersion()).isPresent();
assertThat(standardCategoryStatistics.getVersion().get()).contains("version");
assertThat(standardCategoryStatistics.getLevel().get()).contains("1");
assertThat(standardCategoryStatistics.hasMoreRules()).isFalse();
}
}
| 3,066 | 39.893333 | 107 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssueNotificationHandlerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ListMultimap;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.AnalysisChange;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Change;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Rule;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange;
import org.sonar.server.notification.NotificationDispatcherMetadata;
import org.sonar.server.notification.NotificationManager;
import org.sonar.server.notification.email.EmailNotificationChannel;
import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest;
import static java.util.stream.Collectors.toSet;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anySet;
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.mockito.Mockito.when;
import static org.sonar.core.util.stream.MoreCollectors.index;
import static org.sonar.core.util.stream.MoreCollectors.unorderedIndex;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newRandomNotAHotspotRule;
import static org.sonar.server.notification.NotificationDispatcherMetadata.GLOBAL_NOTIFICATION;
import static org.sonar.server.notification.NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION;
import static org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject.ALL_MUST_HAVE_ROLE_USER;
@RunWith(DataProviderRunner.class)
public class ChangesOnMyIssueNotificationHandlerTest {
private static final String CHANGE_ON_MY_ISSUES_DISPATCHER_KEY = "ChangesOnMyIssue";
private static final String NO_CHANGE_AUTHOR = null;
private NotificationManager notificationManager = mock(NotificationManager.class);
private EmailNotificationChannel emailNotificationChannel = mock(EmailNotificationChannel.class);
private IssuesChangesNotificationSerializer serializer = new IssuesChangesNotificationSerializer();
private ChangesOnMyIssueNotificationHandler underTest = new ChangesOnMyIssueNotificationHandler(
notificationManager, emailNotificationChannel, serializer);
private Class<Set<EmailDeliveryRequest>> emailDeliveryRequestSetType = (Class<Set<EmailDeliveryRequest>>) (Object) Set.class;
private ArgumentCaptor<Set<EmailDeliveryRequest>> emailDeliveryRequestSetCaptor = ArgumentCaptor.forClass(emailDeliveryRequestSetType);
@Test
public void getMetadata_returns_same_instance_as_static_method() {
assertThat(underTest.getMetadata()).containsSame(ChangesOnMyIssueNotificationHandler.newMetadata());
}
@Test
public void verify_changeOnMyIssues_notification_dispatcher_key() {
NotificationDispatcherMetadata metadata = ChangesOnMyIssueNotificationHandler.newMetadata();
assertThat(metadata.getDispatcherKey()).isEqualTo(CHANGE_ON_MY_ISSUES_DISPATCHER_KEY);
}
@Test
public void changeOnMyIssues_notification_is_enable_at_global_level() {
NotificationDispatcherMetadata metadata = ChangesOnMyIssueNotificationHandler.newMetadata();
assertThat(metadata.getProperty(GLOBAL_NOTIFICATION)).isEqualTo("true");
}
@Test
public void changeOnMyIssues_notification_is_enable_at_project_level() {
NotificationDispatcherMetadata metadata = ChangesOnMyIssueNotificationHandler.newMetadata();
assertThat(metadata.getProperty(PER_PROJECT_NOTIFICATION)).isEqualTo("true");
}
@Test
public void getNotificationClass_is_IssueChangeNotification() {
assertThat(underTest.getNotificationClass()).isEqualTo(IssuesChangesNotification.class);
}
@Test
public void deliver_has_no_effect_if_notifications_is_empty() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
int deliver = underTest.deliver(Collections.emptyList());
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager, emailNotificationChannel);
}
@Test
public void deliver_has_no_effect_if_emailNotificationChannel_is_disabled() {
when(emailNotificationChannel.isActivated()).thenReturn(false);
Set<IssuesChangesNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> mock(IssuesChangesNotification.class))
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
notifications.forEach(Mockito::verifyNoInteractions);
}
@Test
public void deliver_has_no_effect_if_no_notification_has_assignee() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<ChangedIssue> issues = IntStream.range(0, 1 + new Random().nextInt(2))
.mapToObj(i -> new ChangedIssue.Builder("issue_key_" + i)
.setNewStatus("foo")
.setAssignee(null)
.setRule(newRule())
.setProject(newProject(i + ""))
.build())
.collect(toSet());
IssuesChangesNotificationBuilder builder = new IssuesChangesNotificationBuilder(issues, new UserChange(new Random().nextLong(), new User("user_uuid", "user_login", null)));
int deliver = underTest.deliver(ImmutableSet.of(serializer.serialize(builder)));
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_has_no_effect_if_all_issues_are_assigned_to_the_changeAuthor() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<UserChange> userChanges = IntStream.range(0, 1 + new Random().nextInt(3))
.mapToObj(i -> new UserChange(new Random().nextLong(), new User("user_uuid_" + i, "user_login_" + i, null)))
.collect(toSet());
Set<IssuesChangesNotificationBuilder> notificationBuilders = userChanges.stream()
.map(userChange -> {
Set<ChangedIssue> issues = IntStream.range(0, 1 + new Random().nextInt(2))
.mapToObj(i -> new ChangedIssue.Builder("issue_key_" + i + userChange.getUser().getUuid())
.setNewStatus("foo")
.setAssignee(userChange.getUser())
.setRule(newRule())
.setProject(newProject(i + ""))
.build())
.collect(toSet());
return new IssuesChangesNotificationBuilder(issues, userChange);
})
.collect(toSet());
Set<IssuesChangesNotification> notifications = notificationBuilders.stream()
.map(t -> serializer.serialize(t))
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_ChangesOnMyIssues_notifications() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Project project = newProject();
Set<ChangedIssue> issues = IntStream.range(0, 1 + new Random().nextInt(2))
.mapToObj(i -> new ChangedIssue.Builder("issue_key_" + i)
.setNewStatus("foo")
.setAssignee(newUser("assignee_" + i))
.setRule(newRule())
.setProject(project)
.build())
.collect(toSet());
IssuesChangesNotificationBuilder builder = new IssuesChangesNotificationBuilder(issues, new UserChange(new Random().nextLong(), new User("user_uuid", "user_login", null)));
int deliver = underTest.deliver(ImmutableSet.of(serializer.serialize(builder)));
assertThat(deliver).isZero();
Set<String> assigneeLogins = issues.stream().map(i -> i.getAssignee().get().getLogin()).collect(toSet());
verify(notificationManager).findSubscribedEmailRecipients(CHANGE_ON_MY_ISSUES_DISPATCHER_KEY, project.getKey(), assigneeLogins, ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_checks_by_projectKeys_if_notifications_have_subscribed_assignee_to_ChangesOnMyIssues_notifications() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<ChangedIssue> issues = IntStream.range(0, 1 + new Random().nextInt(2))
.mapToObj(i -> new ChangedIssue.Builder("issue_key_" + i)
.setNewStatus("foo")
.setAssignee(newUser("" + i))
.setRule(newRule())
.setProject(newProject(i + ""))
.build())
.collect(toSet());
IssuesChangesNotificationBuilder builder = new IssuesChangesNotificationBuilder(issues, new UserChange(new Random().nextLong(), new User("user_uuid", "user_login", null)));
int deliver = underTest.deliver(ImmutableSet.of(serializer.serialize(builder)));
assertThat(deliver).isZero();
issues.stream()
.collect(MoreCollectors.index(ChangedIssue::getProject))
.asMap()
.forEach((key, value) -> {
String projectKey = key.getKey();
Set<String> assigneeLogins = value.stream().map(i -> i.getAssignee().get().getLogin()).collect(toSet());
verify(notificationManager).findSubscribedEmailRecipients(CHANGE_ON_MY_ISSUES_DISPATCHER_KEY, projectKey, assigneeLogins, ALL_MUST_HAVE_ROLE_USER);
});
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
@UseDataProvider("userOrAnalysisChange")
public void deliver_creates_a_notification_per_assignee_with_only_his_issues_on_the_single_project(Change userOrAnalysisChange) {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Project project = newProject();
User assignee1 = newUser("assignee_1");
User assignee2 = newUser("assignee_2");
Set<ChangedIssue> assignee1Issues = IntStream.range(0, 10)
.mapToObj(i -> newChangedIssue("1_issue_key_" + i, assignee1, project))
.collect(toSet());
Set<ChangedIssue> assignee2Issues = IntStream.range(0, 10)
.mapToObj(i -> newChangedIssue("2_issue_key_" + i, assignee2, project))
.collect(toSet());
Set<IssuesChangesNotification> notifications = Stream.of(
// notification with only assignee1 5 notifications
new IssuesChangesNotificationBuilder(assignee1Issues.stream().limit(5).collect(toSet()), userOrAnalysisChange),
// notification with only assignee2 6 notifications
new IssuesChangesNotificationBuilder(assignee2Issues.stream().limit(6).collect(toSet()), userOrAnalysisChange),
// notification with 4 assignee1 and 3 assignee2 notifications
new IssuesChangesNotificationBuilder(
Stream.concat(assignee1Issues.stream().skip(6), assignee2Issues.stream().skip(7)).collect(toSet()),
userOrAnalysisChange))
.map(t -> serializer.serialize(t))
.collect(toSet());
when(notificationManager.findSubscribedEmailRecipients(CHANGE_ON_MY_ISSUES_DISPATCHER_KEY, project.getKey(), ImmutableSet.of(assignee1.getLogin(), assignee2.getLogin()),
ALL_MUST_HAVE_ROLE_USER))
.thenReturn(ImmutableSet.of(emailRecipientOf(assignee1.getLogin()), emailRecipientOf(assignee2.getLogin())));
int deliveredCount = new Random().nextInt(100);
when(emailNotificationChannel.deliverAll(anySet())).thenReturn(deliveredCount);
int deliver = underTest.deliver(notifications);
assertThat(deliver).isEqualTo(deliveredCount);
verify(notificationManager).findSubscribedEmailRecipients(CHANGE_ON_MY_ISSUES_DISPATCHER_KEY,
project.getKey(), ImmutableSet.of(assignee1.getLogin(), assignee2.getLogin()), ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verify(emailNotificationChannel).deliverAll(emailDeliveryRequestSetCaptor.capture());
verifyNoMoreInteractions(emailNotificationChannel);
Set<EmailDeliveryRequest> emailDeliveryRequests = emailDeliveryRequestSetCaptor.getValue();
assertThat(emailDeliveryRequests).hasSize(4);
ListMultimap<String, EmailDeliveryRequest> emailDeliveryRequestByEmail = emailDeliveryRequests.stream()
.collect(index(EmailDeliveryRequest::recipientEmail));
List<EmailDeliveryRequest> assignee1Requests = emailDeliveryRequestByEmail.get(emailOf(assignee1.getLogin()));
assertThat(assignee1Requests)
.hasSize(2)
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification())
.extracting(ChangesOnMyIssuesNotification::getChange)
.containsOnly(userOrAnalysisChange);
assertThat(assignee1Requests)
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification())
.extracting(ChangesOnMyIssuesNotification::getChangedIssues)
.containsOnly(
assignee1Issues.stream().limit(5).collect(unorderedIndex(t -> project, t -> t)),
assignee1Issues.stream().skip(6).collect(unorderedIndex(t -> project, t -> t)));
List<EmailDeliveryRequest> assignee2Requests = emailDeliveryRequestByEmail.get(emailOf(assignee2.getLogin()));
assertThat(assignee2Requests)
.hasSize(2)
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification())
.extracting(ChangesOnMyIssuesNotification::getChange)
.containsOnly(userOrAnalysisChange);
assertThat(assignee2Requests)
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification())
.extracting(ChangesOnMyIssuesNotification::getChangedIssues)
.containsOnly(
assignee2Issues.stream().limit(6).collect(unorderedIndex(t -> project, t -> t)),
assignee2Issues.stream().skip(7).collect(unorderedIndex(t -> project, t -> t)));
}
@Test
@UseDataProvider("userOrAnalysisChange")
public void deliver_ignores_issues_which_assignee_is_the_changeAuthor(Change userOrAnalysisChange) {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Project project1 = newProject();
Project project2 = newProject();
User assignee1 = newUser("assignee_1");
User assignee2 = newUser("assignee_2");
Set<ChangedIssue> assignee1Issues = IntStream.range(0, 10)
.mapToObj(i -> newChangedIssue("1_issue_key_" + i, assignee1, project1))
.collect(toSet());
Set<ChangedIssue> assignee2Issues = IntStream.range(0, 10)
.mapToObj(i -> newChangedIssue("2_issue_key_" + i, assignee2, project2))
.collect(toSet());
UserChange assignee2Change1 = new UserChange(new Random().nextLong(), assignee2);
Set<IssuesChangesNotification> notifications = Stream.of(
// notification from assignee1 with issues from assignee1 only
new IssuesChangesNotificationBuilder(
assignee1Issues.stream().limit(4).collect(toSet()),
new UserChange(new Random().nextLong(), assignee1)),
// notification from assignee2 with issues from assignee1 and assignee2
new IssuesChangesNotificationBuilder(
Stream.concat(
assignee1Issues.stream().skip(4).limit(2),
assignee2Issues.stream().limit(4))
.collect(toSet()),
assignee2Change1),
// notification from assignee2 with issues from assignee2 only
new IssuesChangesNotificationBuilder(
assignee2Issues.stream().skip(4).limit(3).collect(toSet()),
new UserChange(new Random().nextLong(), assignee2)),
// notification from other change with issues from assignee1 and assignee2)
new IssuesChangesNotificationBuilder(
Stream.concat(
assignee1Issues.stream().skip(6),
assignee2Issues.stream().skip(7))
.collect(toSet()),
userOrAnalysisChange))
.map(t -> serializer.serialize(t))
.collect(toSet());
when(notificationManager.findSubscribedEmailRecipients(
CHANGE_ON_MY_ISSUES_DISPATCHER_KEY, project1.getKey(), ImmutableSet.of(assignee1.getLogin()), ALL_MUST_HAVE_ROLE_USER))
.thenReturn(ImmutableSet.of(emailRecipientOf(assignee1.getLogin())));
when(notificationManager.findSubscribedEmailRecipients(
CHANGE_ON_MY_ISSUES_DISPATCHER_KEY, project2.getKey(), ImmutableSet.of(assignee2.getLogin()), ALL_MUST_HAVE_ROLE_USER))
.thenReturn(ImmutableSet.of(emailRecipientOf(assignee2.getLogin())));
int deliveredCount = new Random().nextInt(100);
when(emailNotificationChannel.deliverAll(anySet())).thenReturn(deliveredCount);
int deliver = underTest.deliver(notifications);
assertThat(deliver).isEqualTo(deliveredCount);
verify(notificationManager).findSubscribedEmailRecipients(CHANGE_ON_MY_ISSUES_DISPATCHER_KEY,
project1.getKey(), ImmutableSet.of(assignee1.getLogin()), ALL_MUST_HAVE_ROLE_USER);
verify(notificationManager).findSubscribedEmailRecipients(CHANGE_ON_MY_ISSUES_DISPATCHER_KEY,
project2.getKey(), ImmutableSet.of(assignee2.getLogin()), ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verify(emailNotificationChannel).deliverAll(emailDeliveryRequestSetCaptor.capture());
verifyNoMoreInteractions(emailNotificationChannel);
Set<EmailDeliveryRequest> emailDeliveryRequests = emailDeliveryRequestSetCaptor.getValue();
assertThat(emailDeliveryRequests).hasSize(3);
ListMultimap<String, EmailDeliveryRequest> emailDeliveryRequestByEmail = emailDeliveryRequests.stream()
.collect(index(EmailDeliveryRequest::recipientEmail));
List<EmailDeliveryRequest> assignee1Requests = emailDeliveryRequestByEmail.get(emailOf(assignee1.getLogin()));
assertThat(assignee1Requests)
.hasSize(2)
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification())
.extracting(ChangesOnMyIssuesNotification::getChange)
.containsOnly(userOrAnalysisChange, assignee2Change1);
assertThat(assignee1Requests)
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification())
.extracting(ChangesOnMyIssuesNotification::getChangedIssues)
.containsOnly(
assignee1Issues.stream().skip(4).limit(2).collect(unorderedIndex(t -> project1, t -> t)),
assignee1Issues.stream().skip(6).collect(unorderedIndex(t -> project1, t -> t)));
List<EmailDeliveryRequest> assignee2Requests = emailDeliveryRequestByEmail.get(emailOf(assignee2.getLogin()));
assertThat(assignee2Requests)
.hasSize(1)
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification())
.extracting(ChangesOnMyIssuesNotification::getChange)
.containsOnly(userOrAnalysisChange);
assertThat(assignee2Requests)
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification())
.extracting(ChangesOnMyIssuesNotification::getChangedIssues)
.containsOnly(assignee2Issues.stream().skip(7).collect(unorderedIndex(t -> project2, t -> t)));
}
@DataProvider
public static Object[][] userOrAnalysisChange() {
User changeAuthor = new User(randomAlphabetic(12), randomAlphabetic(10), randomAlphabetic(11));
return new Object[][] {
{new AnalysisChange(new Random().nextLong())},
{new UserChange(new Random().nextLong(), changeAuthor)},
};
}
private static Project newProject() {
String base = randomAlphabetic(6);
return newProject(base);
}
private static Project newProject(String base) {
return new Project.Builder("prj_uuid_" + base)
.setKey("prj_key_" + base)
.setProjectName("prj_name_" + base)
.build();
}
private static User newUser(String name) {
return new User(name + "_uuid", name + "login", name);
}
private static ChangedIssue newChangedIssue(String key, User assignee1, Project project) {
return new ChangedIssue.Builder(key)
.setNewStatus("foo")
.setAssignee(assignee1)
.setRule(newRule())
.setProject(project)
.build();
}
private static Rule newRule() {
return newRandomNotAHotspotRule(randomAlphabetic(5));
}
private static Set<IssuesChangesNotification> randomSetOfNotifications(@Nullable String projectKey, @Nullable String assignee, @Nullable String changeAuthor) {
return IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(projectKey, assignee, changeAuthor))
.collect(Collectors.toSet());
}
private static IssuesChangesNotification newNotification(@Nullable String projectKey, @Nullable String assignee, @Nullable String changeAuthor) {
return mock(IssuesChangesNotification.class);
}
private static NotificationManager.EmailRecipient emailRecipientOf(String login) {
return new NotificationManager.EmailRecipient(login, emailOf(login));
}
private static String emailOf(String login) {
return login + "@plouf";
}
}
| 22,788 | 48.32684 | 176 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesEmailTemplateTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import com.google.common.collect.ImmutableSet;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.elasticsearch.common.util.set.Sets;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.EmailSettings;
import org.sonar.api.notifications.Notification;
import org.sonar.api.rules.RuleType;
import org.sonar.core.i18n.I18n;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.AnalysisChange;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Change;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Rule;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange;
import org.sonar.test.html.HtmlFragmentAssert;
import org.sonar.test.html.HtmlListAssert;
import org.sonar.test.html.HtmlParagraphAssert;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
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.api.issue.Issue.STATUS_CLOSED;
import static org.sonar.api.issue.Issue.STATUS_CONFIRMED;
import static org.sonar.api.issue.Issue.STATUS_OPEN;
import static org.sonar.api.issue.Issue.STATUS_REOPENED;
import static org.sonar.api.issue.Issue.STATUS_RESOLVED;
import static org.sonar.api.issue.Issue.STATUS_REVIEWED;
import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newAnalysisChange;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newBranch;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newChangedIssue;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newProject;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newRandomNotAHotspotRule;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newRule;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newSecurityHotspotRule;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newUserChange;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.randomRuleTypeHotspotExcluded;
@RunWith(DataProviderRunner.class)
public class ChangesOnMyIssuesEmailTemplateTest {
private static final String[] ISSUE_STATUSES = {STATUS_OPEN, STATUS_RESOLVED, STATUS_CONFIRMED, STATUS_REOPENED, STATUS_CLOSED};
private static final String[] SECURITY_HOTSPOTS_STATUSES = {STATUS_TO_REVIEW, STATUS_REVIEWED};
private I18n i18n = mock(I18n.class);
private EmailSettings emailSettings = mock(EmailSettings.class);
private ChangesOnMyIssuesEmailTemplate underTest = new ChangesOnMyIssuesEmailTemplate(i18n, emailSettings);
@Test
public void format_returns_null_on_Notification() {
EmailMessage emailMessage = underTest.format(mock(Notification.class));
assertThat(emailMessage).isNull();
}
@Test
public void formats_fails_with_ISE_if_change_from_Analysis_and_no_issue() {
AnalysisChange analysisChange = newAnalysisChange();
assertThatThrownBy(() -> underTest.format(new ChangesOnMyIssuesNotification(analysisChange, Collections.emptySet())))
.isInstanceOf(IllegalStateException.class)
.hasMessage("changedIssues can't be empty");
}
@Test
public void format_sets_message_id_with_project_key_of_first_issue_in_set_when_change_from_Analysis() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newProject("prj_" + i), newRandomNotAHotspotRule("rule_" + i)))
.collect(toSet());
AnalysisChange analysisChange = newAnalysisChange();
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, changedIssues));
assertThat(emailMessage.getMessageId()).isEqualTo("changes-on-my-issues/" + changedIssues.iterator().next().getProject().getKey());
}
@Test
public void format_sets_subject_with_project_name_of_first_issue_in_set_when_change_from_Analysis() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newProject("prj_" + i), newRandomNotAHotspotRule("rule_" + i)))
.collect(toSet());
AnalysisChange analysisChange = IssuesChangesNotificationBuilderTesting.newAnalysisChange();
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, changedIssues));
Project project = changedIssues.iterator().next().getProject();
assertThat(emailMessage.getSubject()).isEqualTo("Analysis has changed some of your issues in " + project.getProjectName());
}
@Test
public void format_sets_subject_with_project_name_and_branch_name_of_first_issue_in_set_when_change_from_Analysis() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newBranch("prj_" + i, "br_" + i), newRandomNotAHotspotRule("rule_" + i)))
.collect(toSet());
AnalysisChange analysisChange = newAnalysisChange();
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, changedIssues));
Project project = changedIssues.iterator().next().getProject();
assertThat(emailMessage.getSubject()).isEqualTo("Analysis has changed some of your issues in " + project.getProjectName() + ", " + project.getBranchName().get());
}
@Test
public void format_set_html_message_with_header_dealing_with_plural_when_change_from_Analysis() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newProject("prj_" + i), newRandomNotAHotspotRule("rule_" + i)))
.collect(toSet());
AnalysisChange analysisChange = newAnalysisChange();
EmailMessage singleIssueMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, changedIssues.stream().limit(1).collect(toSet())));
EmailMessage multiIssueMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, changedIssues));
HtmlFragmentAssert.assertThat(singleIssueMessage.getMessage())
.hasParagraph("Hi,")
.hasParagraph("An analysis has updated an issue assigned to you:");
HtmlFragmentAssert.assertThat(multiIssueMessage.getMessage())
.hasParagraph("Hi,")
.hasParagraph("An analysis has updated issues assigned to you:");
}
@Test
public void format_sets_static_message_id_when_change_from_User() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newProject("prj_" + i), newRandomNotAHotspotRule("rule_" + i)))
.collect(toSet());
UserChange userChange = newUserChange();
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(userChange, changedIssues));
assertThat(emailMessage.getMessageId()).isEqualTo("changes-on-my-issues");
}
@Test
public void format_sets_static_subject_when_change_from_User() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newProject("prj_" + i), newRandomNotAHotspotRule("rule_" + i)))
.collect(toSet());
UserChange userChange = newUserChange();
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(userChange, changedIssues));
assertThat(emailMessage.getSubject()).isEqualTo("A manual update has changed some of your issues/hotspots");
}
@Test
public void format_set_html_message_with_header_dealing_with_plural_issues_when_change_from_User() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newProject("prj_" + i), newRandomNotAHotspotRule("rule_" + i)))
.collect(toSet());
UserChange userChange = newUserChange();
EmailMessage singleIssueMessage = underTest.format(new ChangesOnMyIssuesNotification(
userChange, changedIssues.stream().limit(1).collect(toSet())));
EmailMessage multiIssueMessage = underTest.format(new ChangesOnMyIssuesNotification(userChange, changedIssues));
HtmlFragmentAssert.assertThat(singleIssueMessage.getMessage())
.hasParagraph("Hi,")
.withoutLink()
.hasParagraph("A manual change has updated an issue assigned to you:")
.withoutLink();
HtmlFragmentAssert.assertThat(multiIssueMessage.getMessage())
.hasParagraph("Hi,")
.withoutLink()
.hasParagraph("A manual change has updated issues assigned to you:")
.withoutLink();
}
@Test
public void format_set_html_message_with_header_dealing_with_plural_security_hotspots_when_change_from_User() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newProject("prj_" + i), newSecurityHotspotRule("rule_" + i)))
.collect(toSet());
UserChange userChange = newUserChange();
EmailMessage singleIssueMessage = underTest.format(new ChangesOnMyIssuesNotification(
userChange, changedIssues.stream().limit(1).collect(toSet())));
EmailMessage multiIssueMessage = underTest.format(new ChangesOnMyIssuesNotification(userChange, changedIssues));
HtmlFragmentAssert.assertThat(singleIssueMessage.getMessage())
.hasParagraph("Hi,")
.withoutLink()
.hasParagraph("A manual change has updated a hotspot assigned to you:")
.withoutLink();
HtmlFragmentAssert.assertThat(multiIssueMessage.getMessage())
.hasParagraph("Hi,")
.withoutLink()
.hasParagraph("A manual change has updated hotspots assigned to you:")
.withoutLink();
}
@Test
public void format_set_html_message_with_header_dealing_with_plural_security_hotspots_and_issues_when_change_from_User() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newProject("prj_" + i), newRandomNotAHotspotRule("rule_" + i)))
.collect(toSet());
Set<ChangedIssue> changedHotspots = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newProject("prj_" + i), newSecurityHotspotRule("rule_" + i)))
.collect(toSet());
Set<ChangedIssue> issuesAndHotspots = Sets.union(changedIssues, changedHotspots);
UserChange userChange = newUserChange();
EmailMessage multiIssueMessage = underTest.format(new ChangesOnMyIssuesNotification(userChange, issuesAndHotspots));
HtmlFragmentAssert.assertThat(multiIssueMessage.getMessage())
.hasParagraph("Hi,")
.withoutLink()
.hasParagraph("A manual change has updated issues/hotspots assigned to you:")
.withoutLink();
}
@Test
@UseDataProvider("issueStatuses")
public void format_set_html_message_with_footer_when_issue_change_from_user(String issueStatus) {
UserChange userChange = newUserChange();
format_set_html_message_with_footer(userChange, issueStatus, c -> c
// skip content
.hasParagraph() // skip project header
.hasList(), // rule list,
randomRuleTypeHotspotExcluded());
}
@Test
@UseDataProvider("issueStatuses")
public void format_set_html_message_with_footer_when_issue_change_from_analysis(String issueStatus) {
AnalysisChange analysisChange = newAnalysisChange();
format_set_html_message_with_footer(analysisChange, issueStatus, c -> c
.hasParagraph() // status
.hasList(), // rule list,
randomRuleTypeHotspotExcluded());
}
@Test
@UseDataProvider("securityHotspotsStatuses")
public void format_set_html_message_with_footer_when_security_hotspot_change_from_analysis(String securityHotspotStatus) {
AnalysisChange analysisChange = newAnalysisChange();
format_set_html_message_with_footer(analysisChange, securityHotspotStatus, c -> c
.hasParagraph()
.hasList(), // rule list
SECURITY_HOTSPOT);
}
@Test
@UseDataProvider("securityHotspotsStatuses")
public void format_set_html_message_with_footer_when_security_hotspot_change_from_user(String securityHotspotStatus) {
UserChange userChange = newUserChange();
format_set_html_message_with_footer(userChange, securityHotspotStatus, c -> c
.hasParagraph()
.hasList(), // rule list
SECURITY_HOTSPOT);
}
@DataProvider
public static Object[][] issueStatuses() {
return Arrays.stream(ISSUE_STATUSES)
.map(t -> new Object[] {t})
.toArray(Object[][]::new);
}
@DataProvider
public static Object[][] securityHotspotsStatuses() {
return Arrays.stream(SECURITY_HOTSPOTS_STATUSES)
.map(t -> new Object[] {t})
.toArray(Object[][]::new);
}
private void format_set_html_message_with_footer(Change change, String issueStatus, Function<HtmlParagraphAssert, HtmlListAssert> skipContent, RuleType ruleType) {
String wordingNotification = randomAlphabetic(20);
String host = randomAlphabetic(15);
when(i18n.message(Locale.ENGLISH, "notification.dispatcher.ChangesOnMyIssue", "notification.dispatcher.ChangesOnMyIssue"))
.thenReturn(wordingNotification);
when(emailSettings.getServerBaseURL()).thenReturn(host);
Project project = newProject("foo");
Rule rule = newRule("bar", ruleType);
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", issueStatus, project, rule))
.collect(toSet());
EmailMessage singleIssueMessage = underTest.format(new ChangesOnMyIssuesNotification(
change, changedIssues.stream().limit(1).collect(toSet())));
EmailMessage multiIssueMessage = underTest.format(new ChangesOnMyIssuesNotification(change, changedIssues));
Stream.of(singleIssueMessage, multiIssueMessage)
.forEach(issueMessage -> {
HtmlParagraphAssert htmlAssert = HtmlFragmentAssert.assertThat(issueMessage.getMessage())
.hasParagraph().hasParagraph(); // skip header
// skip content
HtmlListAssert htmlListAssert = skipContent.apply(htmlAssert);
String footerText = "You received this email because you are subscribed to \"" + wordingNotification + "\" notifications from SonarQube."
+ " Click here to edit your email preferences.";
htmlListAssert.hasEmptyParagraph()
.hasParagraph(footerText)
.withSmallOn(footerText)
.withLink("here", host + "/account/notifications")
.noMoreBlock();
});
}
@Test
public void format_set_html_message_with_issues_grouped_by_status_closed_or_any_other_when_change_from_analysis() {
Project project = newProject("foo");
Rule rule = newRandomNotAHotspotRule("bar");
Set<ChangedIssue> changedIssues = Arrays.stream(ISSUE_STATUSES)
.map(status -> newChangedIssue(status + "", status, project, rule))
.collect(toSet());
AnalysisChange analysisChange = newAnalysisChange();
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, changedIssues));
HtmlListAssert htmlListAssert = HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph("Closed issue:")
.withoutLink()
.hasList("Rule " + rule.getName() + " - See the single issue")
.withLinkOn("See the single issue")
.hasParagraph("Open issues:")
.withoutLink()
.hasList("Rule " + rule.getName() + " - See all " + (ISSUE_STATUSES.length - 1) + " issues")
.withLinkOn("See all " + (ISSUE_STATUSES.length - 1) + " issues");
verifyEnd(htmlListAssert);
}
@Test
public void format_set_html_message_with_issue_status_title_handles_plural_when_change_from_analysis() {
Project project = newProject("foo");
Rule rule = newRandomNotAHotspotRule("bar");
Set<ChangedIssue> closedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(status -> newChangedIssue(status + "", STATUS_CLOSED, project, rule))
.collect(toSet());
Set<ChangedIssue> openIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(status -> newChangedIssue(status + "", STATUS_OPEN, project, rule))
.collect(toSet());
AnalysisChange analysisChange = newAnalysisChange();
EmailMessage closedIssuesMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, closedIssues));
EmailMessage openIssuesMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, openIssues));
HtmlListAssert htmlListAssert = HtmlFragmentAssert.assertThat(closedIssuesMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph("Closed issues:")
.hasList();
verifyEnd(htmlListAssert);
htmlListAssert = HtmlFragmentAssert.assertThat(openIssuesMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph("Open issues:")
.hasList();
verifyEnd(htmlListAssert);
}
@Test
public void formats_returns_html_message_for_single_issue_on_master_when_analysis_change() {
Project project = newProject("1");
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
ChangedIssue changedIssue = newChangedIssue("key", randomValidStatus(), project, ruleName, randomRuleTypeHotspotExcluded());
AnalysisChange analysisChange = newAnalysisChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, ImmutableSet.of(changedIssue)));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph()// skip title based on status
.hasList("Rule " + ruleName + " - See the single issue")
.withLink("See the single issue", host + "/project/issues?id=" + project.getKey() + "&issues=" + changedIssue.getKey() + "&open=" + changedIssue.getKey())
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
public void user_input_content_should_be_html_escape() {
Project project = new Project.Builder("uuid").setProjectName("</projectName>").setKey("project_key").build();
String ruleName = "</RandomRule>";
String host = randomAlphabetic(15);
Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded());
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, randomValidStatus(), project, rule))
.collect(toList());
UserChange userChange = newUserChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(userChange, ImmutableSet.copyOf(changedIssues)));
assertThat(emailMessage.getMessage())
.doesNotContain(project.getProjectName())
.contains(escapeHtml(project.getProjectName()))
.doesNotContain(ruleName)
.contains(escapeHtml(ruleName));
String expectedHref = host + "/project/issues?id=" + project.getKey()
+ "&issues=" + changedIssues.stream().map(ChangedIssue::getKey).collect(joining("%2C"));
String expectedLinkText = "See all " + changedIssues.size() + " issues";
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName())
.hasList("Rule " + ruleName + " - " + expectedLinkText)
.withLink(expectedLinkText, expectedHref)
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
public void formats_returns_html_message_for_single_issue_on_master_when_user_change() {
Project project = newProject("1");
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
ChangedIssue changedIssue = newChangedIssue("key", randomValidStatus(), project, ruleName, randomRuleTypeHotspotExcluded());
UserChange userChange = newUserChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(userChange, ImmutableSet.of(changedIssue)));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName())
.hasList("Rule " + ruleName + " - See the single issue")
.withLink("See the single issue", host + "/project/issues?id=" + project.getKey() + "&issues=" + changedIssue.getKey() + "&open=" + changedIssue.getKey())
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
public void formats_returns_html_message_for_single_issue_on_branch_when_analysis_change() {
String branchName = randomAlphabetic(6);
Project project = newBranch("1", branchName);
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
String key = "key";
ChangedIssue changedIssue = newChangedIssue(key, randomValidStatus(), project, ruleName, randomRuleTypeHotspotExcluded());
AnalysisChange analysisChange = newAnalysisChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, ImmutableSet.of(changedIssue)));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph()// skip title based on status
.hasList("Rule " + ruleName + " - See the single issue")
.withLink("See the single issue",
host + "/project/issues?id=" + project.getKey() + "&branch=" + branchName + "&issues=" + changedIssue.getKey() + "&open=" + changedIssue.getKey())
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
public void formats_returns_html_message_for_single_issue_on_branch_when_user_change() {
String branchName = randomAlphabetic(6);
Project project = newBranch("1", branchName);
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
String key = "key";
ChangedIssue changedIssue = newChangedIssue(key, randomValidStatus(), project, ruleName, randomRuleTypeHotspotExcluded());
UserChange userChange = newUserChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(userChange, ImmutableSet.of(changedIssue)));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName() + ", " + branchName)
.hasList("Rule " + ruleName + " - See the single issue")
.withLink("See the single issue",
host + "/project/issues?id=" + project.getKey() + "&branch=" + branchName + "&issues=" + changedIssue.getKey() + "&open=" + changedIssue.getKey())
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_master_when_analysis_change() {
Project project = newProject("1");
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded());
String issueStatus = randomValidStatus();
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, issueStatus, project, rule))
.collect(toList());
AnalysisChange analysisChange = newAnalysisChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, ImmutableSet.copyOf(changedIssues)));
String expectedHref = host + "/project/issues?id=" + project.getKey()
+ "&issues=" + changedIssues.stream().map(ChangedIssue::getKey).collect(joining("%2C"));
String expectedLinkText = "See all " + changedIssues.size() + " issues";
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph() // skip title based on status
.hasList("Rule " + ruleName + " - " + expectedLinkText)
.withLink(expectedLinkText, expectedHref)
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_master_when_user_change() {
Project project = newProject("1");
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded());
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, randomValidStatus(), project, rule))
.collect(toList());
UserChange userChange = newUserChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(userChange, ImmutableSet.copyOf(changedIssues)));
String expectedHref = host + "/project/issues?id=" + project.getKey()
+ "&issues=" + changedIssues.stream().map(ChangedIssue::getKey).collect(joining("%2C"));
String expectedLinkText = "See all " + changedIssues.size() + " issues";
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName())
.hasList("Rule " + ruleName + " - " + expectedLinkText)
.withLink(expectedLinkText, expectedHref)
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_branch_when_analysis_change() {
String branchName = randomAlphabetic(19);
Project project = newBranch("1", branchName);
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded());
String status = randomValidStatus();
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, status, project, rule))
.collect(toList());
AnalysisChange analysisChange = newAnalysisChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, ImmutableSet.copyOf(changedIssues)));
String expectedHref = host + "/project/issues?id=" + project.getKey() + "&branch=" + branchName
+ "&issues=" + changedIssues.stream().map(ChangedIssue::getKey).collect(joining("%2C"));
String expectedLinkText = "See all " + changedIssues.size() + " issues";
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph()// skip title based on status
.hasList("Rule " + ruleName + " - " + expectedLinkText)
.withLink(expectedLinkText, expectedHref)
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_branch_when_user_change() {
String branchName = randomAlphabetic(19);
Project project = newBranch("1", branchName);
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
Rule rule = newRandomNotAHotspotRule(ruleName);
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, randomValidStatus(), project, rule))
.collect(toList());
UserChange userChange = newUserChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(userChange, ImmutableSet.copyOf(changedIssues)));
String expectedHref = host + "/project/issues?id=" + project.getKey() + "&branch=" + branchName
+ "&issues=" + changedIssues.stream().map(ChangedIssue::getKey).collect(joining("%2C"));
String expectedLinkText = "See all " + changedIssues.size() + " issues";
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName() + ", " + branchName)
.hasList("Rule " + ruleName + " - " + expectedLinkText)
.withLink(expectedLinkText, expectedHref)
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
public void formats_returns_html_message_with_projects_ordered_by_name_when_user_change() {
Project project1 = newProject("1");
Project project1Branch1 = newBranch("1", "a");
Project project1Branch2 = newBranch("1", "b");
Project project2 = newProject("B");
Project project2Branch1 = newBranch("B", "a");
Project project3 = newProject("C");
String host = randomAlphabetic(15);
List<ChangedIssue> changedIssues = Stream.of(project1, project1Branch1, project1Branch2, project2, project2Branch1, project3)
.map(project -> newChangedIssue("issue_" + project.getUuid(), randomValidStatus(), project, newRule(randomAlphabetic(2), randomRuleTypeHotspotExcluded())))
.collect(toList());
Collections.shuffle(changedIssues);
UserChange userChange = newUserChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(userChange, ImmutableSet.copyOf(changedIssues)));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project1.getProjectName())
.hasList()
.hasParagraph(project1Branch1.getProjectName() + ", " + project1Branch1.getBranchName().get())
.hasList()
.hasParagraph(project1Branch2.getProjectName() + ", " + project1Branch2.getBranchName().get())
.hasList()
.hasParagraph(project2.getProjectName())
.hasList()
.hasParagraph(project2Branch1.getProjectName() + ", " + project2Branch1.getBranchName().get())
.hasList()
.hasParagraph(project3.getProjectName())
.hasList()
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
public void formats_returns_html_message_with_rules_ordered_by_name_when_analysis_change() {
Project project = newProject("1");
Rule rule1 = newRandomNotAHotspotRule("1");
Rule rule2 = newRandomNotAHotspotRule("a");
Rule rule3 = newRandomNotAHotspotRule("b");
Rule rule4 = newRandomNotAHotspotRule("X");
String host = randomAlphabetic(15);
String issueStatus = randomValidStatus();
List<ChangedIssue> changedIssues = Stream.of(rule1, rule2, rule3, rule4)
.map(rule -> newChangedIssue("issue_" + rule.getName(), issueStatus, project, rule))
.collect(toList());
Collections.shuffle(changedIssues);
AnalysisChange analysisChange = newAnalysisChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, ImmutableSet.copyOf(changedIssues)));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph()// skip title based on status
.hasList(
"Rule " + rule1.getName() + " - See the single issue",
"Rule " + rule2.getName() + " - See the single issue",
"Rule " + rule3.getName() + " - See the single issue",
"Rule " + rule4.getName() + " - See the single issue")
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
public void formats_returns_html_message_with_rules_ordered_by_name_user_change() {
Project project = newProject("1");
Rule rule1 = newRandomNotAHotspotRule("1");
Rule rule2 = newRandomNotAHotspotRule("a");
Rule rule3 = newRandomNotAHotspotRule("b");
Rule rule4 = newRandomNotAHotspotRule("X");
Rule hotspot1 = newSecurityHotspotRule("S");
Rule hotspot2 = newSecurityHotspotRule("Z");
Rule hotspot3 = newSecurityHotspotRule("N");
Rule hotspot4 = newSecurityHotspotRule("M");
String host = randomAlphabetic(15);
List<ChangedIssue> changedIssues = Stream.of(rule1, rule2, rule3, rule4, hotspot1, hotspot2, hotspot3, hotspot4)
.map(rule -> newChangedIssue("issue_" + rule.getName(), randomValidStatus(), project, rule))
.collect(toList());
Collections.shuffle(changedIssues);
UserChange userChange = newUserChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(userChange, ImmutableSet.copyOf(changedIssues)));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph()
.hasParagraph()
.hasParagraph() // skip project name
.hasList(
"Rule " + rule1.getName() + " - See the single issue",
"Rule " + rule2.getName() + " - See the single issue",
"Rule " + rule3.getName() + " - See the single issue",
"Rule " + rule4.getName() + " - See the single issue")
.hasEmptyParagraph()
.hasList(
"Rule " + hotspot1.getName() + " - See the single hotspot",
"Rule " + hotspot2.getName() + " - See the single hotspot",
"Rule " + hotspot3.getName() + " - See the single hotspot",
"Rule " + hotspot4.getName() + " - See the single hotspot")
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
public void formats_returns_html_message_with_multiple_links_by_rule_of_groups_of_up_to_40_issues_when_analysis_change() {
Project project1 = newProject("1");
Rule rule1 = newRandomNotAHotspotRule("1");
Rule rule2 = newRandomNotAHotspotRule("a");
String host = randomAlphabetic(15);
String issueStatusClosed = STATUS_CLOSED;
String otherIssueStatus = STATUS_RESOLVED;
List<ChangedIssue> changedIssues = Stream.of(
IntStream.range(0, 39).mapToObj(i -> newChangedIssue("39_" + i, issueStatusClosed, project1, rule1)),
IntStream.range(0, 40).mapToObj(i -> newChangedIssue("40_" + i, issueStatusClosed, project1, rule2)),
IntStream.range(0, 81).mapToObj(i -> newChangedIssue("1-40_41-80_1_" + i, otherIssueStatus, project1, rule2)),
IntStream.range(0, 6).mapToObj(i -> newChangedIssue("6_" + i, otherIssueStatus, project1, rule1)))
.flatMap(t -> t)
.collect(toList());
Collections.shuffle(changedIssues);
AnalysisChange analysisChange = newAnalysisChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(analysisChange, ImmutableSet.copyOf(changedIssues)));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph("Closed issues:") // skip title based on status
.hasList(
"Rule " + rule1.getName() + " - See all 39 issues",
"Rule " + rule2.getName() + " - See all 40 issues")
.withLink("See all 39 issues",
host + "/project/issues?id=" + project1.getKey()
+ "&issues=" + IntStream.range(0, 39).mapToObj(i -> "39_" + i).sorted().collect(joining("%2C")))
.withLink("See all 40 issues",
host + "/project/issues?id=" + project1.getKey()
+ "&issues=" + IntStream.range(0, 40).mapToObj(i -> "40_" + i).sorted().collect(joining("%2C")))
.hasParagraph("Open issues:")
.hasList(
"Rule " + rule2.getName() + " - See issues 1-40 41-80 81",
"Rule " + rule1.getName() + " - See all 6 issues")
.withLink("1-40",
host + "/project/issues?id=" + project1.getKey()
+ "&issues=" + IntStream.range(0, 81).mapToObj(i -> "1-40_41-80_1_" + i).sorted().limit(40).collect(joining("%2C")))
.withLink("41-80",
host + "/project/issues?id=" + project1.getKey()
+ "&issues=" + IntStream.range(0, 81).mapToObj(i -> "1-40_41-80_1_" + i).sorted().skip(40).limit(40).collect(joining("%2C")))
.withLink("81",
host + "/project/issues?id=" + project1.getKey()
+ "&issues=" + "1-40_41-80_1_9" + "&open=" + "1-40_41-80_1_9")
.withLink("See all 6 issues",
host + "/project/issues?id=" + project1.getKey()
+ "&issues=" + IntStream.range(0, 6).mapToObj(i -> "6_" + i).sorted().collect(joining("%2C")))
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
public void formats_returns_html_message_with_multiple_links_by_rule_of_groups_of_up_to_40_issues_and_hotspots_when_user_change() {
Project project1 = newProject("1");
Project project2 = newProject("V");
Project project2Branch = newBranch("V", "AB");
Rule rule1 = newRule("1", randomRuleTypeHotspotExcluded());
Rule rule2 = newRule("a", randomRuleTypeHotspotExcluded());
Rule hotspot1 = newSecurityHotspotRule("h1");
Rule hotspot2 = newSecurityHotspotRule("h2");
String status = randomValidStatus();
String host = randomAlphabetic(15);
List<ChangedIssue> changedIssues = Stream.of(
IntStream.range(0, 39).mapToObj(i -> newChangedIssue("39_" + i, status, project1, rule1)),
IntStream.range(0, 40).mapToObj(i -> newChangedIssue("40_" + i, status, project1, rule2)),
IntStream.range(0, 81).mapToObj(i -> newChangedIssue("1-40_41-80_1_" + i, status, project2, rule2)),
IntStream.range(0, 6).mapToObj(i -> newChangedIssue("6_" + i, status, project2Branch, rule1)),
IntStream.range(0, 39).mapToObj(i -> newChangedIssue("39_" + i, STATUS_REVIEWED, project1, hotspot1)),
IntStream.range(0, 40).mapToObj(i -> newChangedIssue("40_" + i, STATUS_REVIEWED, project1, hotspot2)),
IntStream.range(0, 81).mapToObj(i -> newChangedIssue("1-40_41-80_1_" + i, STATUS_TO_REVIEW, project2, hotspot2)),
IntStream.range(0, 6).mapToObj(i -> newChangedIssue("6_" + i, STATUS_TO_REVIEW, project2Branch, hotspot1)))
.flatMap(t -> t)
.collect(toList());
Collections.shuffle(changedIssues);
UserChange userChange = newUserChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new ChangesOnMyIssuesNotification(userChange, ImmutableSet.copyOf(changedIssues)));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project1.getProjectName())
.hasList()
.withItemTexts(
"Rule " + rule1.getName() + " - See all 39 issues",
"Rule " + rule2.getName() + " - See all 40 issues")
.withLink("See all 39 issues",
host + "/project/issues?id=" + project1.getKey()
+ "&issues=" + IntStream.range(0, 39).mapToObj(i -> "39_" + i).sorted().collect(joining("%2C")))
.withLink("See all 40 issues",
host + "/project/issues?id=" + project1.getKey()
+ "&issues=" + IntStream.range(0, 40).mapToObj(i -> "40_" + i).sorted().collect(joining("%2C")))
.hasEmptyParagraph()
.hasList()
.withItemTexts(
"Rule " + hotspot1.getName() + " - See all 39 hotspots",
"Rule " + hotspot2.getName() + " - See all 40 hotspots")
.withLink("See all 39 hotspots",
host + "/security_hotspots?id=" + project1.getKey()
+ "&hotspots=" + IntStream.range(0, 39).mapToObj(i -> "39_" + i).sorted().collect(joining("%2C")))
.withLink("See all 40 hotspots",
host + "/security_hotspots?id=" + project1.getKey()
+ "&hotspots=" + IntStream.range(0, 40).mapToObj(i -> "40_" + i).sorted().collect(joining("%2C")))
.hasParagraph(project2.getProjectName())
.hasList(
"Rule " + rule2.getName() + " - See issues 1-40 41-80 81")
.withLink("1-40",
host + "/project/issues?id=" + project2.getKey()
+ "&issues=" + IntStream.range(0, 81).mapToObj(i -> "1-40_41-80_1_" + i).sorted().limit(40).collect(joining("%2C")))
.withLink("41-80",
host + "/project/issues?id=" + project2.getKey()
+ "&issues=" + IntStream.range(0, 81).mapToObj(i -> "1-40_41-80_1_" + i).sorted().skip(40).limit(40).collect(joining("%2C")))
.withLink("81",
host + "/project/issues?id=" + project2.getKey()
+ "&issues=" + "1-40_41-80_1_9" + "&open=" + "1-40_41-80_1_9")
.hasEmptyParagraph()
.hasList("Rule " + hotspot2.getName() + " - See hotspots 1-40 41-80 81")
.withLink("1-40",
host + "/security_hotspots?id=" + project2.getKey()
+ "&hotspots=" + IntStream.range(0, 81).mapToObj(i -> "1-40_41-80_1_" + i).sorted().limit(40).collect(joining("%2C")))
.withLink("41-80",
host + "/security_hotspots?id=" + project2.getKey()
+ "&hotspots=" + IntStream.range(0, 81).mapToObj(i -> "1-40_41-80_1_" + i).sorted().skip(40).limit(40).collect(joining("%2C")))
.withLink("81",
host + "/security_hotspots?id=" + project2.getKey()
+ "&hotspots=" + "1-40_41-80_1_9")
.hasParagraph(project2Branch.getProjectName() + ", " + project2Branch.getBranchName().get())
.hasList(
"Rule " + rule1.getName() + " - See all 6 issues")
.withLink("See all 6 issues",
host + "/project/issues?id=" + project2Branch.getKey() + "&branch=" + project2Branch.getBranchName().get()
+ "&issues=" + IntStream.range(0, 6).mapToObj(i -> "6_" + i).sorted().collect(joining("%2C")))
.hasEmptyParagraph()
.hasList("Rule " + hotspot1.getName() + " - See all 6 hotspots")
.withLink("See all 6 hotspots",
host + "/security_hotspots?id=" + project2Branch.getKey() + "&branch=" + project2Branch.getBranchName().get()
+ "&hotspots=" + IntStream.range(0, 6).mapToObj(i -> "6_" + i).sorted().collect(joining("%2C")))
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
private static String randomValidStatus() {
return ISSUE_STATUSES[new Random().nextInt(ISSUE_STATUSES.length)];
}
private void verifyEnd(HtmlListAssert htmlListAssert) {
htmlListAssert
.hasEmptyParagraph()
.hasParagraph()
.noMoreBlock();
}
}
| 44,800 | 49.394826 | 166 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesNotificationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import com.google.common.collect.ImmutableSet;
import java.util.Random;
import org.junit.Test;
import org.sonar.api.notifications.Notification;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.AnalysisChange;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newRandomNotAHotspotRule;
public class ChangesOnMyIssuesNotificationTest {
@Test
public void key_is_ChangesOnMyIssues() {
ChangesOnMyIssuesNotification underTest = new ChangesOnMyIssuesNotification(
new UserChange(new Random().nextLong(), new User(randomAlphabetic(2), randomAlphabetic(3), randomAlphabetic(4))),
ImmutableSet.of());
assertThat(underTest.getType()).isEqualTo("ChangesOnMyIssues");
}
@Test
public void equals_is_based_on_change_and_issues() {
AnalysisChange analysisChange = new AnalysisChange(new Random().nextLong());
ChangedIssue changedIssue = IssuesChangesNotificationBuilderTesting.newChangedIssue("doo", IssuesChangesNotificationBuilderTesting.newProject("prj"),
newRandomNotAHotspotRule("rul"));
ChangesOnMyIssuesNotification underTest = new ChangesOnMyIssuesNotification(analysisChange, ImmutableSet.of(changedIssue));
assertThat(underTest)
.isEqualTo(new ChangesOnMyIssuesNotification(analysisChange, ImmutableSet.of(changedIssue)))
.isNotEqualTo(mock(Notification.class))
.isNotNull()
.isNotEqualTo(new ChangesOnMyIssuesNotification(new AnalysisChange(analysisChange.getDate() + 10), ImmutableSet.of(changedIssue)))
.isNotEqualTo(new ChangesOnMyIssuesNotification(analysisChange, ImmutableSet.of()));
}
@Test
public void hashcode_is_based_on_change_and_issues() {
AnalysisChange analysisChange = new AnalysisChange(new Random().nextLong());
ChangedIssue changedIssue = IssuesChangesNotificationBuilderTesting.newChangedIssue("doo", IssuesChangesNotificationBuilderTesting.newProject("prj"),
newRandomNotAHotspotRule("rul"));
ChangesOnMyIssuesNotification underTest = new ChangesOnMyIssuesNotification(analysisChange, ImmutableSet.of(changedIssue));
assertThat(underTest.hashCode())
.isEqualTo(new ChangesOnMyIssuesNotification(analysisChange, ImmutableSet.of(changedIssue)).hashCode())
.isNotEqualTo(mock(Notification.class).hashCode())
.isNotEqualTo(new ChangesOnMyIssuesNotification(new AnalysisChange(analysisChange.getDate() + 10), ImmutableSet.of(changedIssue)).hashCode())
.isNotEqualTo(new ChangesOnMyIssuesNotification(analysisChange, ImmutableSet.of())).hashCode();
}
}
| 3,896 | 50.276316 | 153 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/EmailMessageTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import org.junit.Test;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
public class EmailMessageTest {
private EmailMessage underTest = new EmailMessage();
@Test
public void setHtmlMessage_sets_message_and_html_to_true() {
String message = randomAlphabetic(12);
underTest.setHtmlMessage(message);
assertThat(underTest.getMessage()).isEqualTo(message);
assertThat(underTest.isHtml()).isTrue();
}
@Test
public void setPlainTextMessage_sets_message_and_html_to_false() {
String message = randomAlphabetic(12);
underTest.setPlainTextMessage(message);
assertThat(underTest.getMessage()).isEqualTo(message);
assertThat(underTest.isHtml()).isFalse();
}
}
| 1,675 | 32.52 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FPOrWontFixNotificationHandlerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ListMultimap;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Random;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.sonar.api.issue.Issue;
import org.sonar.server.issue.notification.FPOrWontFixNotification.FpOrWontFix;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Change;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange;
import org.sonar.server.notification.NotificationDispatcherMetadata;
import org.sonar.server.notification.NotificationManager;
import org.sonar.server.notification.email.EmailNotificationChannel;
import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest;
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.toSet;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.api.issue.Issue.RESOLUTION_FALSE_POSITIVE;
import static org.sonar.api.issue.Issue.RESOLUTION_WONT_FIX;
import static org.sonar.core.util.stream.MoreCollectors.index;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newProject;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newRandomNotAHotspotRule;
import static org.sonar.server.notification.NotificationDispatcherMetadata.GLOBAL_NOTIFICATION;
import static org.sonar.server.notification.NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION;
import static org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject.ALL_MUST_HAVE_ROLE_USER;
@RunWith(DataProviderRunner.class)
public class FPOrWontFixNotificationHandlerTest {
private static final String DO_NOT_FIX_ISSUE_CHANGE_DISPATCHER_KEY = "NewFalsePositiveIssue";
private NotificationManager notificationManager = mock(NotificationManager.class);
private EmailNotificationChannel emailNotificationChannel = mock(EmailNotificationChannel.class);
private IssuesChangesNotificationSerializer serializerMock = mock(IssuesChangesNotificationSerializer.class);
private IssuesChangesNotificationSerializer serializer = spy(new IssuesChangesNotificationSerializer());
private Class<Set<EmailDeliveryRequest>> requestSetType = (Class<Set<EmailDeliveryRequest>>) (Class<?>) Set.class;
private FPOrWontFixNotificationHandler underTest = new FPOrWontFixNotificationHandler(notificationManager, emailNotificationChannel, serializer);
@Test
public void getMetadata_returns_same_instance_as_static_method() {
assertThat(underTest.getMetadata()).containsSame(FPOrWontFixNotificationHandler.newMetadata());
}
@Test
public void verify_fpOrWontFixIssues_notification_dispatcher_key() {
NotificationDispatcherMetadata metadata = FPOrWontFixNotificationHandler.newMetadata();
assertThat(metadata.getDispatcherKey()).isEqualTo(DO_NOT_FIX_ISSUE_CHANGE_DISPATCHER_KEY);
}
@Test
public void fpOrWontFixIssues_notification_is_disabled_at_global_level() {
NotificationDispatcherMetadata metadata = FPOrWontFixNotificationHandler.newMetadata();
assertThat(metadata.getProperty(GLOBAL_NOTIFICATION)).isEqualTo("false");
}
@Test
public void fpOrWontFixIssues_notification_is_enable_at_project_level() {
NotificationDispatcherMetadata metadata = FPOrWontFixNotificationHandler.newMetadata();
assertThat(metadata.getProperty(PER_PROJECT_NOTIFICATION)).isEqualTo("true");
}
@Test
public void getNotificationClass_is_IssueChangeNotification() {
assertThat(underTest.getNotificationClass()).isEqualTo(IssuesChangesNotification.class);
}
@Test
public void deliver_has_no_effect_if_emailNotificationChannel_is_disabled() {
when(emailNotificationChannel.isActivated()).thenReturn(false);
Set<IssuesChangesNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> mock(IssuesChangesNotification.class))
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
notifications.forEach(Mockito::verifyNoInteractions);
}
@Test
public void deliver_parses_every_notification_in_order() {
Set<IssuesChangesNotification> notifications = IntStream.range(0, 5 + new Random().nextInt(10))
.mapToObj(i -> mock(IssuesChangesNotification.class))
.collect(toSet());
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(serializerMock.from(any(IssuesChangesNotification.class))).thenReturn(mock(IssuesChangesNotificationBuilder.class));
FPOrWontFixNotificationHandler underTest = new FPOrWontFixNotificationHandler(notificationManager, emailNotificationChannel, serializerMock);
underTest.deliver(notifications);
notifications.forEach(notification -> verify(serializerMock).from(notification));
}
@Test
public void deliver_fails_with_IAE_if_serializer_throws_IAE() {
Set<IssuesChangesNotification> notifications = IntStream.range(0, 3 + new Random().nextInt(10))
.mapToObj(i -> mock(IssuesChangesNotification.class))
.collect(toSet());
when(emailNotificationChannel.isActivated()).thenReturn(true);
IllegalArgumentException expected = new IllegalArgumentException("faking serializer#from throwing a IllegalArgumentException");
when(serializerMock.from(any(IssuesChangesNotification.class)))
.thenReturn(mock(IssuesChangesNotificationBuilder.class))
.thenReturn(mock(IssuesChangesNotificationBuilder.class))
.thenThrow(expected);
FPOrWontFixNotificationHandler underTest = new FPOrWontFixNotificationHandler(notificationManager, emailNotificationChannel, serializerMock);
try {
underTest.deliver(notifications);
fail("should have throws IAE");
} catch (IllegalArgumentException e) {
verify(serializerMock, times(3)).from(any(IssuesChangesNotification.class));
assertThat(e).isSameAs(expected);
}
}
@Test
public void deliver_has_no_effect_if_no_issue_has_new_resolution() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Change changeMock = mock(Change.class);
Set<IssuesChangesNotification> notifications = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(j -> new IssuesChangesNotificationBuilder(randomIssues(t -> t.setNewResolution(null)).collect(toSet()), changeMock))
.map(serializer::serialize)
.collect(toSet());
reset(serializer);
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verify(serializer, times(notifications.size())).from(any(IssuesChangesNotification.class));
verifyNoInteractions(changeMock);
verifyNoMoreInteractions(serializer);
verifyNoInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
@UseDataProvider("notFPorWontFixResolution")
public void deliver_has_no_effect_if_no_issue_has_FP_or_wontfix_resolution(String newResolution) {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Change changeMock = mock(Change.class);
Set<IssuesChangesNotification> notifications = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(j -> new IssuesChangesNotificationBuilder(randomIssues(t -> t.setNewResolution(newResolution)).collect(toSet()), changeMock))
.map(serializer::serialize)
.collect(toSet());
reset(serializer);
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verify(serializer, times(notifications.size())).from(any(IssuesChangesNotification.class));
verifyNoInteractions(changeMock);
verifyNoMoreInteractions(serializer);
verifyNoInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
}
@DataProvider
public static Object[][] notFPorWontFixResolution() {
return new Object[][] {
{""},
{randomAlphabetic(9)},
{Issue.RESOLUTION_FIXED},
{Issue.RESOLUTION_REMOVED}
};
}
@Test
@UseDataProvider("FPorWontFixResolution")
public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_FPorWontFix_notifications(String newResolution) {
Project projectKey1 = newProject(randomAlphabetic(4));
Project projectKey2 = newProject(randomAlphabetic(5));
Project projectKey3 = newProject(randomAlphabetic(6));
Project projectKey4 = newProject(randomAlphabetic(7));
Change changeMock = mock(Change.class);
// some notifications with some issues on project1
Stream<IssuesChangesNotificationBuilder> project1Notifications = IntStream.range(0, 1 + new Random().nextInt(2))
.mapToObj(j -> new IssuesChangesNotificationBuilder(
randomIssues(t -> t.setProject(projectKey1).setNewResolution(newResolution)).collect(toSet()),
changeMock));
// some notifications with some issues on project2
Stream<IssuesChangesNotificationBuilder> project2Notifications = IntStream.range(0, 1 + new Random().nextInt(2))
.mapToObj(j -> new IssuesChangesNotificationBuilder(
randomIssues(t -> t.setProject(projectKey2).setNewResolution(newResolution)).collect(toSet()),
changeMock));
// some notifications with some issues on project3 and project 4
Stream<IssuesChangesNotificationBuilder> project3And4Notifications = IntStream.range(0, 1 + new Random().nextInt(2))
.mapToObj(j -> new IssuesChangesNotificationBuilder(
Stream.concat(
randomIssues(t -> t.setProject(projectKey3).setNewResolution(newResolution)),
randomIssues(t -> t.setProject(projectKey4).setNewResolution(newResolution)))
.collect(toSet()),
changeMock));
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<IssuesChangesNotification> notifications = Stream.of(project1Notifications, project2Notifications, project3And4Notifications)
.flatMap(t -> t)
.map(serializer::serialize)
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verify(notificationManager).findSubscribedEmailRecipients(DO_NOT_FIX_ISSUE_CHANGE_DISPATCHER_KEY, projectKey1.getKey(), ALL_MUST_HAVE_ROLE_USER);
verify(notificationManager).findSubscribedEmailRecipients(DO_NOT_FIX_ISSUE_CHANGE_DISPATCHER_KEY, projectKey2.getKey(), ALL_MUST_HAVE_ROLE_USER);
verify(notificationManager).findSubscribedEmailRecipients(DO_NOT_FIX_ISSUE_CHANGE_DISPATCHER_KEY, projectKey3.getKey(), ALL_MUST_HAVE_ROLE_USER);
verify(notificationManager).findSubscribedEmailRecipients(DO_NOT_FIX_ISSUE_CHANGE_DISPATCHER_KEY, projectKey4.getKey(), ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
verifyNoInteractions(changeMock);
}
@Test
@UseDataProvider("FPorWontFixResolution")
public void deliver_does_not_send_email_request_for_notifications_a_subscriber_is_the_changeAuthor_of(String newResolution) {
Project project = newProject(randomAlphabetic(5));
User subscriber1 = newUser("subscriber1");
User subscriber2 = newUser("subscriber2");
User subscriber3 = newUser("subscriber3");
User otherChangeAuthor = newUser("otherChangeAuthor");
// subscriber1 is the changeAuthor of some notifications with issues assigned to subscriber1 only
Set<IssuesChangesNotificationBuilder> subscriber1Notifications = IntStream.range(0, 1 + new Random().nextInt(2))
.mapToObj(j -> new IssuesChangesNotificationBuilder(
randomIssues(t -> t.setProject(project).setNewResolution(newResolution).setAssignee(subscriber2)).collect(toSet()),
newUserChange(subscriber1)))
.collect(toSet());
// subscriber1 is the changeAuthor of some notifications with issues assigned to subscriber1 and subscriber2
Set<IssuesChangesNotificationBuilder> subscriber1and2Notifications = IntStream.range(0, 1 + new Random().nextInt(2))
.mapToObj(j -> new IssuesChangesNotificationBuilder(
Stream.concat(
randomIssues(t -> t.setProject(project).setNewResolution(newResolution).setAssignee(subscriber2)),
randomIssues(t -> t.setProject(project).setNewResolution(newResolution).setAssignee(subscriber1)))
.collect(toSet()),
newUserChange(subscriber1)))
.collect(toSet());
// subscriber2 is the changeAuthor of some notifications with issues assigned to subscriber2 only
Set<IssuesChangesNotificationBuilder> subscriber2Notifications = IntStream.range(0, 1 + new Random().nextInt(2))
.mapToObj(j -> new IssuesChangesNotificationBuilder(
randomIssues(t -> t.setProject(project).setNewResolution(newResolution).setAssignee(subscriber2)).collect(toSet()),
newUserChange(subscriber2)))
.collect(toSet());
// subscriber2 is the changeAuthor of some notifications with issues assigned to subscriber2 and subscriber 3
Set<IssuesChangesNotificationBuilder> subscriber2And3Notifications = IntStream.range(0, 1 + new Random().nextInt(2))
.mapToObj(j -> new IssuesChangesNotificationBuilder(
Stream.concat(
randomIssues(t -> t.setProject(project).setNewResolution(newResolution).setAssignee(subscriber2)),
randomIssues(t -> t.setProject(project).setNewResolution(newResolution).setAssignee(subscriber3)))
.collect(toSet()),
newUserChange(subscriber2)))
.collect(toSet());
// subscriber3 is the changeAuthor of no notification
// otherChangeAuthor has some notifications
Set<IssuesChangesNotificationBuilder> otherChangeAuthorNotifications = IntStream.range(0, 1 + new Random().nextInt(2))
.mapToObj(j -> new IssuesChangesNotificationBuilder(randomIssues(t -> t.setProject(project).setNewResolution(newResolution)).collect(toSet()),
newUserChange(otherChangeAuthor)))
.collect(toSet());
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<String> subscriberLogins = ImmutableSet.of(subscriber1.getLogin(), subscriber2.getLogin(), subscriber3.getLogin());
when(notificationManager.findSubscribedEmailRecipients(DO_NOT_FIX_ISSUE_CHANGE_DISPATCHER_KEY, project.getKey(), ALL_MUST_HAVE_ROLE_USER))
.thenReturn(subscriberLogins.stream().map(FPOrWontFixNotificationHandlerTest::emailRecipientOf).collect(toSet()));
int deliveredCount = new Random().nextInt(200);
when(emailNotificationChannel.deliverAll(anySet()))
.thenReturn(deliveredCount)
.thenThrow(new IllegalStateException("deliver should be called only once"));
Set<IssuesChangesNotification> notifications = Stream.of(
subscriber1Notifications.stream(),
subscriber1and2Notifications.stream(),
subscriber2Notifications.stream(),
subscriber2And3Notifications.stream(),
otherChangeAuthorNotifications.stream())
.flatMap(t -> t)
.map(serializer::serialize)
.collect(toSet());
reset(serializer);
int deliver = underTest.deliver(notifications);
assertThat(deliver).isEqualTo(deliveredCount);
verify(notificationManager).findSubscribedEmailRecipients(DO_NOT_FIX_ISSUE_CHANGE_DISPATCHER_KEY, project.getKey(), ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
ArgumentCaptor<Set<EmailDeliveryRequest>> captor = ArgumentCaptor.forClass(requestSetType);
verify(emailNotificationChannel).deliverAll(captor.capture());
verifyNoMoreInteractions(emailNotificationChannel);
ListMultimap<String, EmailDeliveryRequest> requestsByRecipientEmail = captor.getValue().stream()
.collect(index(EmailDeliveryRequest::recipientEmail));
assertThat(requestsByRecipientEmail.get(emailOf(subscriber1.getLogin())))
.containsOnly(
Stream.of(
subscriber2Notifications.stream()
.map(notif -> newEmailDeliveryRequest(notif, subscriber1, toFpOrWontFix(newResolution))),
subscriber2And3Notifications.stream()
.map(notif -> newEmailDeliveryRequest(notif, subscriber1, toFpOrWontFix(newResolution))),
otherChangeAuthorNotifications.stream()
.map(notif -> newEmailDeliveryRequest(notif, subscriber1, toFpOrWontFix(newResolution))))
.flatMap(t -> t)
.toArray(EmailDeliveryRequest[]::new));
assertThat(requestsByRecipientEmail.get(emailOf(subscriber2.getLogin())))
.containsOnly(
Stream.of(
subscriber1Notifications.stream()
.map(notif -> newEmailDeliveryRequest(notif, subscriber2, toFpOrWontFix(newResolution))),
subscriber1and2Notifications.stream()
.map(notif -> newEmailDeliveryRequest(notif, subscriber2, toFpOrWontFix(newResolution))),
otherChangeAuthorNotifications.stream()
.map(notif -> newEmailDeliveryRequest(notif, subscriber2, toFpOrWontFix(newResolution))))
.flatMap(t -> t)
.toArray(EmailDeliveryRequest[]::new));
assertThat(requestsByRecipientEmail.get(emailOf(subscriber3.getLogin())))
.containsOnly(
Stream.of(
subscriber1Notifications.stream()
.map(notif -> newEmailDeliveryRequest(notif, subscriber3, toFpOrWontFix(newResolution))),
subscriber1and2Notifications.stream()
.map(notif -> newEmailDeliveryRequest(notif, subscriber3, toFpOrWontFix(newResolution))),
subscriber2Notifications.stream()
.map(notif -> newEmailDeliveryRequest(notif, subscriber3, toFpOrWontFix(newResolution))),
subscriber2And3Notifications.stream()
.map(notif -> newEmailDeliveryRequest(notif, subscriber3, toFpOrWontFix(newResolution))),
otherChangeAuthorNotifications.stream()
.map(notif -> newEmailDeliveryRequest(notif, subscriber3, toFpOrWontFix(newResolution))))
.flatMap(t -> t)
.toArray(EmailDeliveryRequest[]::new));
assertThat(requestsByRecipientEmail.get(emailOf(otherChangeAuthor.getLogin())))
.isEmpty();
}
@Test
@UseDataProvider("oneOrMoreProjectCounts")
public void deliver_send_a_separated_email_request_for_FPs_and_Wont_Fix_issues(int projectCount) {
Set<Project> projects = IntStream.range(0, projectCount).mapToObj(i -> newProject("prk_key_" + i)).collect(toSet());
User subscriber1 = newUser("subscriber1");
User changeAuthor = newUser("changeAuthor");
Set<ChangedIssue> fpIssues = projects.stream()
.flatMap(project -> randomIssues(t -> t.setProject(project).setNewResolution(RESOLUTION_FALSE_POSITIVE).setAssignee(subscriber1)))
.collect(toSet());
Set<ChangedIssue> wontFixIssues = projects.stream()
.flatMap(project -> randomIssues(t -> t.setProject(project).setNewResolution(RESOLUTION_WONT_FIX).setAssignee(subscriber1)))
.collect(toSet());
UserChange userChange = newUserChange(changeAuthor);
IssuesChangesNotificationBuilder fpAndWontFixNotifications = new IssuesChangesNotificationBuilder(
Stream.concat(fpIssues.stream(), wontFixIssues.stream()).collect(toSet()),
userChange);
when(emailNotificationChannel.isActivated()).thenReturn(true);
projects.forEach(project -> when(notificationManager.findSubscribedEmailRecipients(DO_NOT_FIX_ISSUE_CHANGE_DISPATCHER_KEY, project.getKey(), ALL_MUST_HAVE_ROLE_USER))
.thenReturn(singleton(emailRecipientOf(subscriber1.getLogin()))));
int deliveredCount = new Random().nextInt(200);
when(emailNotificationChannel.deliverAll(anySet()))
.thenReturn(deliveredCount)
.thenThrow(new IllegalStateException("deliver should be called only once"));
Set<IssuesChangesNotification> notifications = singleton(serializer.serialize(fpAndWontFixNotifications));
reset(serializer);
int deliver = underTest.deliver(notifications);
assertThat(deliver).isEqualTo(deliveredCount);
projects
.forEach(project -> verify(notificationManager).findSubscribedEmailRecipients(DO_NOT_FIX_ISSUE_CHANGE_DISPATCHER_KEY, project.getKey(), ALL_MUST_HAVE_ROLE_USER));
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
ArgumentCaptor<Set<EmailDeliveryRequest>> captor = ArgumentCaptor.forClass(requestSetType);
verify(emailNotificationChannel).deliverAll(captor.capture());
verifyNoMoreInteractions(emailNotificationChannel);
ListMultimap<String, EmailDeliveryRequest> requestsByRecipientEmail = captor.getValue().stream()
.collect(index(EmailDeliveryRequest::recipientEmail));
assertThat(requestsByRecipientEmail.get(emailOf(subscriber1.getLogin())))
.containsOnly(
new EmailDeliveryRequest(emailOf(subscriber1.getLogin()), new FPOrWontFixNotification(
userChange, wontFixIssues, FpOrWontFix.WONT_FIX)),
new EmailDeliveryRequest(emailOf(subscriber1.getLogin()), new FPOrWontFixNotification(
userChange, fpIssues, FpOrWontFix.FP)));
}
@DataProvider
public static Object[][] oneOrMoreProjectCounts() {
return new Object[][] {
{1},
{2 + new Random().nextInt(3)},
};
}
private static EmailDeliveryRequest newEmailDeliveryRequest(IssuesChangesNotificationBuilder notif, User user, FpOrWontFix resolution) {
return new EmailDeliveryRequest(
emailOf(user.getLogin()),
new FPOrWontFixNotification(notif.getChange(), notif.getIssues(), resolution));
}
private static FpOrWontFix toFpOrWontFix(String newResolution) {
if (newResolution.equals(Issue.RESOLUTION_WONT_FIX)) {
return FpOrWontFix.WONT_FIX;
}
if (newResolution.equals(RESOLUTION_FALSE_POSITIVE)) {
return FpOrWontFix.FP;
}
throw new IllegalArgumentException("unsupported resolution " + newResolution);
}
private static long counter = 233_343;
private static UserChange newUserChange(User subscriber1) {
return new UserChange(counter += 100, subscriber1);
}
public User newUser(String subscriber1) {
return new User(subscriber1, subscriber1 + "_login", subscriber1 + "_name");
}
@DataProvider
public static Object[][] FPorWontFixResolution() {
return new Object[][] {
{RESOLUTION_FALSE_POSITIVE},
{Issue.RESOLUTION_WONT_FIX}
};
}
private static Stream<ChangedIssue> randomIssues(Consumer<ChangedIssue.Builder> consumer) {
return IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> {
ChangedIssue.Builder builder = new ChangedIssue.Builder("key_" + i)
.setAssignee(new User(randomAlphabetic(3), randomAlphabetic(4), randomAlphabetic(5)))
.setNewStatus(randomAlphabetic(12))
.setNewResolution(randomAlphabetic(13))
.setRule(newRandomNotAHotspotRule(randomAlphabetic(8)))
.setProject(new Project.Builder(randomAlphabetic(9))
.setKey(randomAlphabetic(10))
.setProjectName(randomAlphabetic(11))
.build());
consumer.accept(builder);
return builder.build();
});
}
private static NotificationManager.EmailRecipient emailRecipientOf(String assignee1) {
return new NotificationManager.EmailRecipient(assignee1, emailOf(assignee1));
}
private static String emailOf(String assignee1) {
return assignee1 + "@baffe";
}
}
| 25,611 | 50.429719 | 170 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FPOrWontFixNotificationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Test;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.AnalysisChange;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Rule;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.issue.notification.FPOrWontFixNotification.FpOrWontFix.FP;
import static org.sonar.server.issue.notification.FPOrWontFixNotification.FpOrWontFix.WONT_FIX;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newRandomNotAHotspotRule;
public class FPOrWontFixNotificationTest {
@Test
public void equals_is_based_on_issues_change_and_resolution() {
Rule rule = newRandomNotAHotspotRule("rule_name");
Project project = new Project.Builder("prj_uuid").setKey("prj_key").setProjectName("prj_name").build();
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> new ChangedIssue.Builder("key_" + i)
.setNewStatus("status")
.setRule(rule)
.setProject(project)
.build())
.collect(Collectors.toSet());
AnalysisChange change = new AnalysisChange(12);
User user = new User("uuid", "login", null);
FPOrWontFixNotification underTest = new FPOrWontFixNotification(change, changedIssues, WONT_FIX);
assertThat(underTest)
.isEqualTo(new FPOrWontFixNotification(change, changedIssues, WONT_FIX))
.isEqualTo(new FPOrWontFixNotification(change, ImmutableSet.copyOf(changedIssues), WONT_FIX))
.isNotEqualTo(new Object())
.isNotNull()
.isNotEqualTo(new FPOrWontFixNotification(change, Collections.emptySet(), WONT_FIX))
.isNotEqualTo(new FPOrWontFixNotification(change, ImmutableSet.of(changedIssues.iterator().next()), WONT_FIX))
.isNotEqualTo(new FPOrWontFixNotification(new AnalysisChange(14), changedIssues, WONT_FIX))
.isNotEqualTo(new FPOrWontFixNotification(new IssuesChangesNotificationBuilder.UserChange(12, user), changedIssues, WONT_FIX))
.isNotEqualTo(new FPOrWontFixNotification(change, changedIssues, FP));
}
@Test
public void hashcode_is_based_on_issues_change_and_resolution() {
Rule rule = newRandomNotAHotspotRule("rule_name");
Project project = new Project.Builder("prj_uuid").setKey("prj_key").setProjectName("prj_name").build();
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> new ChangedIssue.Builder("key_" + i)
.setNewStatus("status")
.setRule(rule)
.setProject(project)
.build())
.collect(Collectors.toSet());
AnalysisChange change = new AnalysisChange(12);
User user = new User("uuid", "login", null);
FPOrWontFixNotification underTest = new FPOrWontFixNotification(change, changedIssues, WONT_FIX);
assertThat(underTest.hashCode())
.isEqualTo(new FPOrWontFixNotification(change, changedIssues, WONT_FIX).hashCode())
.isEqualTo(new FPOrWontFixNotification(change, ImmutableSet.copyOf(changedIssues), WONT_FIX).hashCode())
.isNotEqualTo(new Object().hashCode())
.isNotEqualTo(new FPOrWontFixNotification(change, Collections.emptySet(), WONT_FIX).hashCode())
.isNotEqualTo(new FPOrWontFixNotification(change, ImmutableSet.of(changedIssues.iterator().next()), WONT_FIX).hashCode())
.isNotEqualTo(new FPOrWontFixNotification(new AnalysisChange(14), changedIssues, WONT_FIX).hashCode())
.isNotEqualTo(new FPOrWontFixNotification(new IssuesChangesNotificationBuilder.UserChange(12, user), changedIssues, WONT_FIX).hashCode())
.isNotEqualTo(new FPOrWontFixNotification(change, changedIssues, FP)).hashCode();
}
}
| 5,030 | 52.521277 | 143 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FpOrWontFixEmailTemplateTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import com.google.common.collect.ImmutableSet;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.EmailSettings;
import org.sonar.api.notifications.Notification;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.core.i18n.I18n;
import org.sonar.server.issue.notification.FPOrWontFixNotification.FpOrWontFix;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.AnalysisChange;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Change;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Rule;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange;
import org.sonar.test.html.HtmlFragmentAssert;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.server.issue.notification.FPOrWontFixNotification.FpOrWontFix.FP;
import static org.sonar.server.issue.notification.FPOrWontFixNotification.FpOrWontFix.WONT_FIX;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newRandomNotAHotspotRule;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newSecurityHotspotRule;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.randomRuleTypeHotspotExcluded;
@RunWith(DataProviderRunner.class)
public class FpOrWontFixEmailTemplateTest {
private I18n i18n = mock(I18n.class);
private EmailSettings emailSettings = mock(EmailSettings.class);
private FpOrWontFixEmailTemplate underTest = new FpOrWontFixEmailTemplate(i18n, emailSettings);
@Test
public void format_returns_null_on_Notification() {
EmailMessage emailMessage = underTest.format(mock(Notification.class));
assertThat(emailMessage).isNull();
}
@Test
public void format_sets_message_id_specific_to_fp() {
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(mock(Change.class), Collections.emptySet(), FP));
assertThat(emailMessage.getMessageId()).isEqualTo("fp-issue-changes");
}
@Test
public void format_sets_message_id_specific_to_wont_fix() {
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(mock(Change.class), Collections.emptySet(), WONT_FIX));
assertThat(emailMessage.getMessageId()).isEqualTo("wontfix-issue-changes");
}
@Test
public void format_sets_subject_specific_to_fp() {
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(mock(Change.class), Collections.emptySet(), FP));
assertThat(emailMessage.getSubject()).isEqualTo("Issues marked as False Positive");
}
@Test
public void format_sets_subject_specific_to_wont_fix() {
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(mock(Change.class), Collections.emptySet(), WONT_FIX));
assertThat(emailMessage.getSubject()).isEqualTo("Issues marked as Won't Fix");
}
@Test
public void format_sets_from_to_name_of_author_change_when_available() {
UserChange change = new UserChange(new Random().nextLong(), new User(randomAlphabetic(5), randomAlphabetic(6), randomAlphabetic(7)));
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, Collections.emptySet(), WONT_FIX));
assertThat(emailMessage.getFrom()).isEqualTo(change.getUser().getName().get());
}
@Test
public void format_sets_from_to_login_of_author_change_when_name_is_not_available() {
UserChange change = new UserChange(new Random().nextLong(), new User(randomAlphabetic(5), randomAlphabetic(6), null));
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, Collections.emptySet(), WONT_FIX));
assertThat(emailMessage.getFrom()).isEqualTo(change.getUser().getLogin());
}
@Test
public void format_sets_from_to_null_when_analysisChange() {
AnalysisChange change = new AnalysisChange(new Random().nextLong());
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, Collections.emptySet(), WONT_FIX));
assertThat(emailMessage.getFrom()).isNull();
}
@Test
@UseDataProvider("userOrAnalysisChange")
public void formats_returns_html_message_with_only_footer_and_header_when_no_issue_for_FPs(Change change) {
formats_returns_html_message_with_only_footer_and_header_when_no_issue(change, FP, "False Positive");
}
@Test
@UseDataProvider("userOrAnalysisChange")
public void formats_returns_html_message_with_only_footer_and_header_when_no_issue_for_Wont_fixs(Change change) {
formats_returns_html_message_with_only_footer_and_header_when_no_issue(change, WONT_FIX, "Won't Fix");
}
public void formats_returns_html_message_with_only_footer_and_header_when_no_issue(Change change, FpOrWontFix fpOrWontFix, String fpOrWontFixLabel) {
String wordingNotification = randomAlphabetic(20);
String host = randomAlphabetic(15);
when(i18n.message(Locale.ENGLISH, "notification.dispatcher.NewFalsePositiveIssue", "notification.dispatcher.NewFalsePositiveIssue"))
.thenReturn(wordingNotification);
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, Collections.emptySet(), fpOrWontFix));
String footerText = "You received this email because you are subscribed to \"" + wordingNotification + "\" notifications from SonarQube."
+ " Click here to edit your email preferences.";
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph("Hi,")
.withoutLink()
.hasParagraph("A manual change has resolved an issue as " + fpOrWontFixLabel + ":")
.withoutLink()
.hasEmptyParagraph()
.hasParagraph(footerText)
.withSmallOn(footerText)
.withLink("here", host + "/account/notifications")
.noMoreBlock();
}
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_single_issue_on_master(Change change, FpOrWontFix fpOrWontFix) {
Project project = newProject("1");
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
ChangedIssue changedIssue = newChangedIssue("key", project, ruleName, randomRuleTypeHotspotExcluded());
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, ImmutableSet.of(changedIssue), fpOrWontFix));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName())
.hasList("Rule " + ruleName + " - See the single issue")
.withLink("See the single issue", host + "/project/issues?id=" + project.getKey() + "&issues=" + changedIssue.getKey() + "&open=" + changedIssue.getKey())
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_single_hotspot_on_master(Change change, FpOrWontFix fpOrWontFix) {
Project project = newProject("1");
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
ChangedIssue changedIssue = newChangedIssue("key", project, ruleName, SECURITY_HOTSPOT);
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, ImmutableSet.of(changedIssue), fpOrWontFix));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName())
.hasList("Rule " + ruleName + " - See the single hotspot")
.withLink("See the single hotspot", host + "/project/issues?id=" + project.getKey() + "&issues=" + changedIssue.getKey() + "&open=" + changedIssue.getKey())
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_single_issue_on_branch(Change change, FpOrWontFix fpOrWontFix) {
String branchName = randomAlphabetic(6);
Project project = newBranch("1", branchName);
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
String key = "key";
ChangedIssue changedIssue = newChangedIssue(key, project, ruleName, randomRuleTypeHotspotExcluded());
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, ImmutableSet.of(changedIssue), fpOrWontFix));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName() + ", " + branchName)
.hasList("Rule " + ruleName + " - See the single issue")
.withLink("See the single issue",
host + "/project/issues?id=" + project.getKey() + "&branch=" + branchName + "&issues=" + changedIssue.getKey() + "&open=" + changedIssue.getKey())
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_single_hotspot_on_branch(Change change, FpOrWontFix fpOrWontFix) {
String branchName = randomAlphabetic(6);
Project project = newBranch("1", branchName);
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
String key = "key";
ChangedIssue changedIssue = newChangedIssue(key, project, ruleName, SECURITY_HOTSPOT);
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, ImmutableSet.of(changedIssue), fpOrWontFix));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName() + ", " + branchName)
.hasList("Rule " + ruleName + " - See the single hotspot")
.withLink("See the single hotspot",
host + "/project/issues?id=" + project.getKey() + "&branch=" + branchName + "&issues=" + changedIssue.getKey() + "&open=" + changedIssue.getKey())
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_master(Change change, FpOrWontFix fpOrWontFix) {
Project project = newProject("1");
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
Rule rule = newRandomNotAHotspotRule(ruleName);
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, project, rule))
.collect(toList());
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, ImmutableSet.copyOf(changedIssues), fpOrWontFix));
String expectedHref = host + "/project/issues?id=" + project.getKey()
+ "&issues=" + changedIssues.stream().map(ChangedIssue::getKey).collect(joining("%2C"));
String expectedLinkText = "See all " + changedIssues.size() + " issues";
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName())
.hasList("Rule " + ruleName + " - " + expectedLinkText)
.withLink(expectedLinkText, expectedHref)
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_multiple_hotspots_of_same_rule_on_same_project_on_master(Change change, FpOrWontFix fpOrWontFix) {
Project project = newProject("1");
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
Rule rule = newSecurityHotspotRule(ruleName);
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, project, rule))
.collect(toList());
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, ImmutableSet.copyOf(changedIssues), fpOrWontFix));
String expectedHref = host + "/project/issues?id=" + project.getKey()
+ "&issues=" + changedIssues.stream().map(ChangedIssue::getKey).collect(joining("%2C"));
String expectedLinkText = "See all " + changedIssues.size() + " hotspots";
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName())
.hasList("Rule " + ruleName + " - " + expectedLinkText)
.withLink(expectedLinkText, expectedHref)
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_branch(Change change, FpOrWontFix fpOrWontFix) {
String branchName = randomAlphabetic(19);
Project project = newBranch("1", branchName);
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
Rule rule = newRandomNotAHotspotRule(ruleName);
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, project, rule))
.collect(toList());
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, ImmutableSet.copyOf(changedIssues), fpOrWontFix));
String expectedHref = host + "/project/issues?id=" + project.getKey() + "&branch=" + branchName
+ "&issues=" + changedIssues.stream().map(ChangedIssue::getKey).collect(joining("%2C"));
String expectedLinkText = "See all " + changedIssues.size() + " issues";
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName() + ", " + branchName)
.hasList("Rule " + ruleName + " - " + expectedLinkText)
.withLink(expectedLinkText, expectedHref)
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_multiple_hotspots_of_same_rule_on_same_project_on_branch(Change change, FpOrWontFix fpOrWontFix) {
String branchName = randomAlphabetic(19);
Project project = newBranch("1", branchName);
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
Rule rule = newSecurityHotspotRule(ruleName);
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, project, rule))
.collect(toList());
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, ImmutableSet.copyOf(changedIssues), fpOrWontFix));
String expectedHref = host + "/project/issues?id=" + project.getKey() + "&branch=" + branchName
+ "&issues=" + changedIssues.stream().map(ChangedIssue::getKey).collect(joining("%2C"));
String expectedLinkText = "See all " + changedIssues.size() + " hotspots";
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName() + ", " + branchName)
.hasList("Rule " + ruleName + " - " + expectedLinkText)
.withLink(expectedLinkText, expectedHref)
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_with_projects_ordered_by_name(Change change, FpOrWontFix fpOrWontFix) {
Project project1 = newProject("1");
Project project1Branch1 = newBranch("1", "a");
Project project1Branch2 = newBranch("1", "b");
Project project2 = newProject("B");
Project project2Branch1 = newBranch("B", "a");
Project project3 = newProject("C");
String host = randomAlphabetic(15);
List<ChangedIssue> changedIssues = Stream.of(project1, project1Branch1, project1Branch2, project2, project2Branch1, project3)
.map(project -> newChangedIssue("issue_" + project.getUuid(), project, newRandomNotAHotspotRule(randomAlphabetic(2))))
.collect(toList());
Collections.shuffle(changedIssues);
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, ImmutableSet.copyOf(changedIssues), fpOrWontFix));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project1.getProjectName())
.hasList()
.hasParagraph(project1Branch1.getProjectName() + ", " + project1Branch1.getBranchName().get())
.hasList()
.hasParagraph(project1Branch2.getProjectName() + ", " + project1Branch2.getBranchName().get())
.hasList()
.hasParagraph(project2.getProjectName())
.hasList()
.hasParagraph(project2Branch1.getProjectName() + ", " + project2Branch1.getBranchName().get())
.hasList()
.hasParagraph(project3.getProjectName())
.hasList()
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_with_rules_ordered_by_name(Change change, FpOrWontFix fpOrWontFix) {
Project project = newProject("1");
Rule rule1 = newRandomNotAHotspotRule("1");
Rule rule2 = newRandomNotAHotspotRule("a");
Rule rule3 = newRandomNotAHotspotRule("b");
Rule rule4 = newRandomNotAHotspotRule("X");
String host = randomAlphabetic(15);
List<ChangedIssue> changedIssues = Stream.of(rule1, rule2, rule3, rule4)
.map(rule -> newChangedIssue("issue_" + rule.getName(), project, rule))
.collect(toList());
Collections.shuffle(changedIssues);
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, ImmutableSet.copyOf(changedIssues), fpOrWontFix));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project.getProjectName())
.hasList(
"Rule " + rule1.getName() + " - See the single issue",
"Rule " + rule2.getName() + " - See the single issue",
"Rule " + rule3.getName() + " - See the single issue",
"Rule " + rule4.getName() + " - See the single issue")
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_with_multiple_links_by_rule_of_groups_of_up_to_40_issues(Change change, FpOrWontFix fpOrWontFix) {
Project project1 = newProject("1");
Project project2 = newProject("V");
Project project2Branch = newBranch("V", "AB");
Rule rule1 = newRandomNotAHotspotRule("1");
Rule rule2 = newRandomNotAHotspotRule("a");
String host = randomAlphabetic(15);
List<ChangedIssue> changedIssues = Stream.of(
IntStream.range(0, 39).mapToObj(i -> newChangedIssue("39_" + i, project1, rule1)),
IntStream.range(0, 40).mapToObj(i -> newChangedIssue("40_" + i, project1, rule2)),
IntStream.range(0, 81).mapToObj(i -> newChangedIssue("1-40_41-80_1_" + i, project2, rule2)),
IntStream.range(0, 6).mapToObj(i -> newChangedIssue("6_" + i, project2Branch, rule1)))
.flatMap(t -> t)
.collect(toList());
Collections.shuffle(changedIssues);
when(emailSettings.getServerBaseURL()).thenReturn(host);
EmailMessage emailMessage = underTest.format(new FPOrWontFixNotification(change, ImmutableSet.copyOf(changedIssues), fpOrWontFix));
HtmlFragmentAssert.assertThat(emailMessage.getMessage())
.hasParagraph().hasParagraph() // skip header
.hasParagraph(project1.getProjectName())
.hasList()
.withItemTexts(
"Rule " + rule1.getName() + " - See all 39 issues",
"Rule " + rule2.getName() + " - See all 40 issues")
.withLink("See all 39 issues",
host + "/project/issues?id=" + project1.getKey()
+ "&issues=" + IntStream.range(0, 39).mapToObj(i -> "39_" + i).sorted().collect(joining("%2C")))
.withLink("See all 40 issues",
host + "/project/issues?id=" + project1.getKey()
+ "&issues=" + IntStream.range(0, 40).mapToObj(i -> "40_" + i).sorted().collect(joining("%2C")))
.hasParagraph(project2.getProjectName())
.hasList("Rule " + rule2.getName() + " - See issues 1-40 41-80 81")
.withLink("1-40",
host + "/project/issues?id=" + project2.getKey()
+ "&issues=" + IntStream.range(0, 81).mapToObj(i -> "1-40_41-80_1_" + i).sorted().limit(40).collect(joining("%2C")))
.withLink("41-80",
host + "/project/issues?id=" + project2.getKey()
+ "&issues=" + IntStream.range(0, 81).mapToObj(i -> "1-40_41-80_1_" + i).sorted().skip(40).limit(40).collect(joining("%2C")))
.withLink("81",
host + "/project/issues?id=" + project2.getKey()
+ "&issues=" + "1-40_41-80_1_9" + "&open=" + "1-40_41-80_1_9")
.hasParagraph(project2Branch.getProjectName() + ", " + project2Branch.getBranchName().get())
.hasList("Rule " + rule1.getName() + " - See all 6 issues")
.withLink("See all 6 issues",
host + "/project/issues?id=" + project2Branch.getKey() + "&branch=" + project2Branch.getBranchName().get()
+ "&issues=" + IntStream.range(0, 6).mapToObj(i -> "6_" + i).sorted().collect(joining("%2C")))
.hasParagraph().hasParagraph() // skip footer
.noMoreBlock();
}
@DataProvider
public static Object[][] userOrAnalysisChange() {
AnalysisChange analysisChange = new AnalysisChange(new Random().nextLong());
UserChange userChange = new UserChange(new Random().nextLong(), new User(randomAlphabetic(5), randomAlphabetic(6),
new Random().nextBoolean() ? null : randomAlphabetic(7)));
return new Object[][] {
{analysisChange},
{userChange}
};
}
@DataProvider
public static Object[][] fpOrWontFixValuesByUserOrAnalysisChange() {
AnalysisChange analysisChange = new AnalysisChange(new Random().nextLong());
UserChange userChange = new UserChange(new Random().nextLong(), new User(randomAlphabetic(5), randomAlphabetic(6),
new Random().nextBoolean() ? null : randomAlphabetic(7)));
return new Object[][] {
{analysisChange, FP},
{analysisChange, WONT_FIX},
{userChange, FP},
{userChange, WONT_FIX}
};
}
private static ChangedIssue newChangedIssue(String key, Project project, String ruleName, RuleType ruleType) {
return newChangedIssue(key, project, newRule(ruleName, ruleType));
}
private static ChangedIssue newChangedIssue(String key, Project project, Rule rule) {
return new ChangedIssue.Builder(key)
.setNewStatus(randomAlphabetic(19))
.setProject(project)
.setRule(rule)
.build();
}
private static Rule newRule(String ruleName, RuleType ruleType) {
return new Rule(RuleKey.of(randomAlphabetic(6), randomAlphabetic(7)), ruleType, ruleName);
}
private static Project newProject(String uuid) {
return new Project.Builder(uuid).setProjectName(uuid + "_name").setKey(uuid + "_key").build();
}
private static Project newBranch(String uuid, String branchName) {
return new Project.Builder(uuid).setProjectName(uuid + "_name").setKey(uuid + "_key").setBranchName(branchName).build();
}
}
| 26,001 | 48.907869 | 162 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/IssuesChangesNotificationBuilderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.System2;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.AnalysisChange;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Rule;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(DataProviderRunner.class)
public class IssuesChangesNotificationBuilderTest {
@Test
public void IssuesChangesNotificationBuilder_getters() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 10).mapToObj(i -> new ChangedIssue.Builder("key" + i)
.setRule(newRule("repository", "key", RuleType.CODE_SMELL, "name"))
.setProject(new Project.Builder("uuid" + i).setKey("key").setProjectName("name").setBranchName("branch-name").build())
.setNewStatus("status")
.setNewResolution("resolution")
.setAssignee(new User("uuid" + i, "login", "name"))
.build())
.collect(Collectors.toSet());
AnalysisChange analysisChange = new AnalysisChange(1_000_000_000L);
IssuesChangesNotificationBuilder builder = new IssuesChangesNotificationBuilder(changedIssues, analysisChange);
assertThat(builder.getIssues()).isEqualTo(changedIssues);
assertThat(builder.getChange()).isEqualTo(analysisChange);
}
@Test
public void fail_if_changed_issues_empty() {
AnalysisChange analysisChange = new AnalysisChange(1_000_000_000L);
Set<ChangedIssue> issues = Collections.emptySet();
assertThatThrownBy(() -> new IssuesChangesNotificationBuilder(issues, analysisChange))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("issues can't be empty");
}
@Test
public void fail_if_change_is_null() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 10).mapToObj(i -> new ChangedIssue.Builder("key" + i)
.setRule(newRule("repository", "key", RuleType.CODE_SMELL, "name"))
.setProject(new Project.Builder("uuid" + i).setKey("key").setProjectName("name").setBranchName("branch-name").build())
.setNewStatus("status")
.setNewResolution("resolution")
.setAssignee(new User("uuid" + i, "login", "name"))
.build())
.collect(Collectors.toSet());
assertThatThrownBy(() -> new IssuesChangesNotificationBuilder(changedIssues, null))
.isInstanceOf(NullPointerException.class)
.hasMessage("change can't be null");
}
@Test
public void UserChange_toString() {
long date = 1_000_000_000L;
UserChange userChange = new UserChange(date, new User("user_uuid", "user_login", null));
assertThat(userChange)
.hasToString("UserChange{date=1000000000, user=User{uuid='user_uuid', login='user_login', name='null'}}");
}
@Test
public void UserChange_equals() {
long now = System2.INSTANCE.now();
String uuid_1 = "uuid-1";
String login_1 = "login-1";
String name_1 = "name-1";
UserChange userChange1 = new UserChange(now, new User(uuid_1, login_1, name_1));
UserChange userChange2 = new UserChange(now, new User(uuid_1, login_1, name_1));
assertThat(userChange1)
.isEqualTo(userChange2)
.isEqualTo(userChange1);
}
@DataProvider
public static Object[][] userData() {
return new Object[][] {
{new UserChange(1L, new User("uuid-2", "login-1", "name-1"))},
{new UserChange(1L, new User("uuid-1", "login-2", "name-1"))},
{new UserChange(1L, new User("uuid-1", "login-1", "name-2"))},
{new UserChange(1L, new User("uuid-2", "login-2", "name-1"))},
{new UserChange(1L, new User("uuid-1", "login-2", "name-2"))},
{new UserChange(1L, new User("uuid-2", "login-2", "name-2"))},
{new UserChange(1L, new User("uuid-1", "login-2", null))},
{new UserChange(1L, new User("uuid-2", "login-1", null))},
{new UserChange(1L, new User("uuid-2", "login-2", null))},
{null},
{new Object()},
};
}
@Test
@UseDataProvider("userData")
public void UserChange_not_equal(Object object) {
long now = System2.INSTANCE.now();
String uuid_1 = "uuid-1";
String login_1 = "login-1";
String name_1 = "name-1";
UserChange userChange1 = new UserChange(now, new User(uuid_1, login_1, name_1));
assertThat(userChange1).isNotEqualTo(object);
}
@Test
public void UserChange_isAuthorLogin() {
long now = System2.INSTANCE.now();
String uuid = "uuid-1";
String login = "login-1";
String name = "name-1";
UserChange userChange = new UserChange(now, new User(uuid, login, name));
assertThat(userChange.isAuthorLogin("other-login")).isFalse();
assertThat(userChange.isAuthorLogin("login-1")).isTrue();
}
@Test
public void UserChange_getUser() {
long now = System2.INSTANCE.now();
String uuid = "uuid-1";
String login = "login-1";
String name = "name-1";
UserChange userChange = new UserChange(now, new User(uuid, login, name));
assertThat(userChange.getUser()).isNotNull();
assertThat(userChange.getUser().getLogin()).isEqualTo(login);
assertThat(userChange.getUser().getName()).hasValue(name);
assertThat(userChange.getUser().getUuid()).isEqualTo(uuid);
}
@Test
public void AnalysisChange_toString() {
long date = 1_000_000_000L;
AnalysisChange userChange = new AnalysisChange(date);
assertThat(userChange).hasToString("AnalysisChange{1000000000}");
}
@Test
public void AnalysisChange_equals() {
AnalysisChange analysisChange1 = new AnalysisChange(1_000_000_000L);
AnalysisChange analysisChange2 = new AnalysisChange(1_000_000_000L);
assertThat(analysisChange1)
.isEqualTo(analysisChange2)
.isEqualTo(analysisChange1);
}
@Test
public void AnalysisChange_not_equals() {
AnalysisChange analysisChange1 = new AnalysisChange(1_000_000_000L);
AnalysisChange analysisChange2 = new AnalysisChange(2_000_000_000L);
assertThat(analysisChange1).isNotEqualTo(analysisChange2);
}
@Test
public void AnalysisChange_not_equal_with_null() {
AnalysisChange analysisChange1 = new AnalysisChange(1_000_000_000L);
assertThat(analysisChange1).isNotNull();
}
@Test
public void AnalysisChange_not_equal_with_Object() {
AnalysisChange analysisChange1 = new AnalysisChange(1_000_000_000L);
assertThat(analysisChange1).isNotEqualTo(new Object());
}
@Test
public void AnalysisChange_isAuthorLogin() {
AnalysisChange analysisChange1 = new AnalysisChange(1_000_000_000L);
assertThat(analysisChange1.isAuthorLogin("login")).isFalse();
}
@Test
public void Project_toString() {
Project project = new Project.Builder("uuid")
.setKey("key")
.setProjectName("name")
.setBranchName("branch-name")
.build();
assertThat(project)
.hasToString("Project{uuid='uuid', key='key', projectName='name', branchName='branch-name'}");
}
@Test
public void Project_equals() {
Project project1 = new Project.Builder("uuid")
.setKey("key")
.setProjectName("name")
.setBranchName("branch-name")
.build();
Project project2 = new Project.Builder("uuid")
.setKey("key")
.setProjectName("name")
.setBranchName("branch-name")
.build();
assertThat(project1)
.isEqualTo(project2)
.isEqualTo(project1);
}
@DataProvider
public static Object[][] projectData() {
return new Object[][] {
{new Project.Builder("uuid2").setKey("key1").setProjectName("name1").setBranchName("branch-name1").build()},
{new Project.Builder("uuid1").setKey("key2").setProjectName("name1").setBranchName("branch-name1").build()},
{new Project.Builder("uuid1").setKey("key1").setProjectName("name2").setBranchName("branch-name1").build()},
{new Project.Builder("uuid1").setKey("key1").setProjectName("name1").setBranchName("branch-name2").build()},
{new Project.Builder("uuid2").setKey("key2").setProjectName("name1").setBranchName("branch-name1").build()},
{new Project.Builder("uuid1").setKey("key2").setProjectName("name2").setBranchName("branch-name1").build()},
{new Project.Builder("uuid1").setKey("key1").setProjectName("name2").setBranchName("branch-name2").build()},
{new Project.Builder("uuid2").setKey("key2").setProjectName("name2").setBranchName("branch-name1").build()},
{new Project.Builder("uuid2").setKey("key2").setProjectName("name2").setBranchName("branch-name2").build()},
{null},
{new Object()},
};
}
@Test
@UseDataProvider("projectData")
public void Project_not_equal(Object object) {
Project project1 = new Project.Builder("uuid1")
.setKey("key1")
.setProjectName("name1")
.setBranchName("branch-name1")
.build();
assertThat(project1).isNotEqualTo(object);
}
@Test
public void Project_getters() {
Project project1 = new Project.Builder("uuid")
.setKey("key")
.setProjectName("name")
.setBranchName("branch-name")
.build();
assertThat(project1.getKey()).isEqualTo("key");
assertThat(project1.getProjectName()).isEqualTo("name");
assertThat(project1.getUuid()).isEqualTo("uuid");
assertThat(project1.getBranchName()).hasValue("branch-name");
}
@Test
public void Rule_toString() {
Rule rule = newRule("repository", "key", RuleType.CODE_SMELL, "name");
assertThat(rule)
.hasToString("Rule{key=repository:key, type=CODE_SMELL, name='name'}");
}
@Test
public void Rule_equals() {
Rule rule1 = newRule("repository", "key", RuleType.CODE_SMELL, "name");
Rule rule2 = newRule("repository", "key", RuleType.CODE_SMELL, "name");
assertThat(rule1)
.isEqualTo(rule2)
.isEqualTo(rule1);
}
@DataProvider
public static Object[][] ruleData() {
return new Object[][] {
{newRule("repository2", "key1", RuleType.CODE_SMELL, "name1")},
{newRule("repository1", "key2", RuleType.CODE_SMELL, "name1")},
{newRule("repository1", "key1", RuleType.BUG, "name1")},
{newRule("repository1", "key1", RuleType.CODE_SMELL, "name2")},
{newRule("repository2", "key2", RuleType.CODE_SMELL, "name1")},
{newRule("repository1", "key2", RuleType.BUG, "name1")},
{newRule("repository1", "key1", RuleType.BUG, "name2")},
{newRule("repository2", "key2", RuleType.BUG, "name2")},
{newRule("repository1", "key1", null, "name1")},
{null},
{new Object()},
};
}
@Test
@UseDataProvider("ruleData")
public void Rule_not_equal(Object object) {
Rule rule = newRule("repository1", "key1", RuleType.CODE_SMELL, "name1");
assertThat(rule.equals(object)).isFalse();
}
@Test
public void Rule_getters() {
Rule rule = newRule("repository", "key", RuleType.CODE_SMELL, "name");
assertThat(rule.getKey()).isEqualTo(RuleKey.of("repository", "key"));
assertThat(rule.getName()).isEqualTo("name");
assertThat(rule.getRuleType()).isEqualTo(RuleType.CODE_SMELL);
}
@Test
public void ChangedIssue_toString() {
ChangedIssue changedIssue = new ChangedIssue.Builder("key")
.setRule(newRule("repository", "key", RuleType.CODE_SMELL, "name"))
.setProject(new Project.Builder("uuid").setKey("key").setProjectName("name").setBranchName("branch-name").build())
.setNewStatus("status")
.setNewResolution("resolution")
.setAssignee(new User("uuid", "login", "name"))
.build();
assertThat(changedIssue)
.hasToString("ChangedIssue{key='key', newStatus='status', newResolution='resolution', " +
"assignee=User{uuid='uuid', login='login', name='name'}, " +
"rule=Rule{key=repository:key, type=CODE_SMELL, name='name'}, " +
"project=Project{uuid='uuid', key='key', projectName='name', branchName='branch-name'}}");
}
@Test
public void ChangedIssue_equals() {
ChangedIssue changedIssue1 = new ChangedIssue.Builder("key")
.setRule(newRule("repository", "key", RuleType.CODE_SMELL, "name"))
.setProject(new Project.Builder("uuid").setKey("key").setProjectName("name").setBranchName("branch-name").build())
.setNewStatus("status")
.setNewResolution("resolution")
.setAssignee(new User("uuid", "login", "name"))
.build();
ChangedIssue changedIssue2 = new ChangedIssue.Builder("key")
.setRule(newRule("repository", "key", RuleType.CODE_SMELL, "name"))
.setProject(new Project.Builder("uuid").setKey("key").setProjectName("name").setBranchName("branch-name").build())
.setNewStatus("status")
.setNewResolution("resolution")
.setAssignee(new User("uuid", "login", "name"))
.build();
assertThat(changedIssue1)
.isEqualTo(changedIssue2)
.isEqualTo(changedIssue1);
}
@DataProvider
public static Object[][] changedIssueData() {
return new Object[][] {
{new ChangedIssue.Builder("key1")
.setRule(newRule("repository", "key", RuleType.CODE_SMELL, "name"))
.setProject(new Project.Builder("uuid").setKey("key").setProjectName("name").setBranchName("branch-name").build())
.setNewStatus("status")
.setNewResolution("resolution")
.setAssignee(new User("uuid", "login", "name"))
.build()},
{new ChangedIssue.Builder("key")
.setRule(newRule("repository1", "key", RuleType.CODE_SMELL, "name"))
.setProject(new Project.Builder("uuid").setKey("key").setProjectName("name").setBranchName("branch-name").build())
.setNewStatus("status")
.setNewResolution("resolution")
.setAssignee(new User("uuid", "login", "name"))
.build()},
{new ChangedIssue.Builder("key")
.setRule(newRule("repository", "key", RuleType.CODE_SMELL, "name"))
.setProject(new Project.Builder("uuid1").setKey("key").setProjectName("name").setBranchName("branch-name").build())
.setNewStatus("status")
.setNewResolution("resolution")
.setAssignee(new User("uuid", "login", "name"))
.build()},
{new ChangedIssue.Builder("key")
.setRule(newRule("repository", "key", RuleType.CODE_SMELL, "name"))
.setProject(new Project.Builder("uuid").setKey("key").setProjectName("name").setBranchName("branch-name").build())
.setNewStatus("status1")
.setNewResolution("resolution")
.setAssignee(new User("uuid", "login", "name"))
.build()},
{new ChangedIssue.Builder("key")
.setRule(newRule("repository", "key", RuleType.CODE_SMELL, "name"))
.setProject(new Project.Builder("uuid").setKey("key").setProjectName("name").setBranchName("branch-name").build())
.setNewStatus("status")
.setNewResolution("resolution1")
.setAssignee(new User("uuid", "login", "name"))
.build()},
{new ChangedIssue.Builder("key")
.setRule(newRule("repository", "key", RuleType.CODE_SMELL, "name"))
.setProject(new Project.Builder("uuid").setKey("key").setProjectName("name").setBranchName("branch-name").build())
.setNewStatus("status")
.setNewResolution("resolution")
.setAssignee(new User("uuid1", "login", "name"))
.build()},
{null},
{new Object()},
};
}
@Test
@UseDataProvider("changedIssueData")
public void ChangedIssue_not_equal(Object object) {
ChangedIssue changedIssue = new ChangedIssue.Builder("key")
.setRule(newRule("repository", "key", RuleType.CODE_SMELL, "name"))
.setProject(new Project.Builder("uuid").setKey("key").setProjectName("name").setBranchName("branch-name").build())
.setNewStatus("status")
.setNewResolution("resolution")
.setAssignee(new User("uuid", "login", "name"))
.build();
assertThat(changedIssue).isNotEqualTo(object);
}
@Test
public void ChangedIssue_getters() {
Project project = new Project.Builder("uuid").setKey("key").setProjectName("name").setBranchName("branch-name").build();
Rule rule = newRule("repository", "key", RuleType.CODE_SMELL, "name");
User user = new User("uuid", "login", "name");
ChangedIssue changedIssue = new ChangedIssue.Builder("key")
.setRule(rule)
.setProject(project)
.setNewStatus("status")
.setNewResolution("resolution")
.setAssignee(user)
.build();
assertThat(changedIssue.getKey()).isEqualTo("key");
assertThat(changedIssue.getNewStatus()).isEqualTo("status");
assertThat(changedIssue.getAssignee()).hasValue(user);
assertThat(changedIssue.getNewResolution()).hasValue("resolution");
assertThat(changedIssue.getProject()).isEqualTo(project);
assertThat(changedIssue.getRule()).isEqualTo(rule);
}
private static Rule newRule(String repository, String key, RuleType type, String name) {
return new Rule(RuleKey.of(repository, key), type, name);
}
}
| 18,405 | 38.413276 | 124 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/IssuesChangesNotificationModuleTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class IssuesChangesNotificationModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new IssuesChangesNotificationModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(7);
}
}
| 1,307 | 34.351351 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/IssuesChangesNotificationSerializerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import java.util.Random;
import java.util.Set;
import java.util.stream.IntStream;
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.System2;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newProject;
public class IssuesChangesNotificationSerializerTest {
private IssuesChangesNotificationSerializer underTest = new IssuesChangesNotificationSerializer();
@Test
public void should_serialize_issues_from_rules_with_analysis_change() {
long now = System2.INSTANCE.now();
IssuesChangesNotificationBuilder.AnalysisChange change = new IssuesChangesNotificationBuilder.AnalysisChange(now);
Set<IssuesChangesNotificationBuilder.ChangedIssue> issues = IntStream.range(1, 4)
.mapToObj(i -> new IssuesChangesNotificationBuilder.ChangedIssue.Builder("issue_key_" + i)
.setNewStatus("foo")
.setAssignee(null)
.setRule(newRule("repository", "key" + i, RuleType.valueOf(i), "name" + i))
.setProject(newProject(i + ""))
.build())
.collect(toSet());
IssuesChangesNotificationBuilder builder = new IssuesChangesNotificationBuilder(issues, change);
IssuesChangesNotification serialized = underTest.serialize(builder);
IssuesChangesNotificationBuilder deserialized = underTest.from(serialized);
assertThat(deserialized.getChange()).isEqualTo(builder.getChange());
assertThat(deserialized.getIssues()).isEqualTo(builder.getIssues());
}
@Test
public void should_serialize_issues_from_rules() {
Set<IssuesChangesNotificationBuilder.ChangedIssue> issues = IntStream.range(1, 4)
.mapToObj(i -> new IssuesChangesNotificationBuilder.ChangedIssue.Builder("issue_key_" + i)
.setNewStatus("foo")
.setAssignee(null)
.setRule(newRule("repository", "key" + i, RuleType.valueOf(i), "name" + i))
.setProject(newProject(i + ""))
.build())
.collect(toSet());
IssuesChangesNotificationBuilder builder = new IssuesChangesNotificationBuilder(issues,
new IssuesChangesNotificationBuilder.UserChange(new Random().nextLong(), new IssuesChangesNotificationBuilder.User("user_uuid", "user_login", null)));
IssuesChangesNotification serialized = underTest.serialize(builder);
IssuesChangesNotificationBuilder deserialized = underTest.from(serialized);
assertThat(deserialized.getChange()).isEqualTo(builder.getChange());
assertThat(deserialized.getIssues()).isEqualTo(builder.getIssues());
}
@Test
public void should_serialize_issues_from_different_external_rules() {
Set<IssuesChangesNotificationBuilder.ChangedIssue> issues = IntStream.range(0, 3)
.mapToObj(i -> new IssuesChangesNotificationBuilder.ChangedIssue.Builder("issue_key_" + i)
.setNewStatus("foo")
.setAssignee(null)
.setRule(newRule("repository", "key" + i, null, "name"))
.setProject(newProject(i + ""))
.build())
.collect(toSet());
IssuesChangesNotificationBuilder builder = new IssuesChangesNotificationBuilder(issues,
new IssuesChangesNotificationBuilder.UserChange(new Random().nextLong(), new IssuesChangesNotificationBuilder.User("user_uuid", "user_login", null)));
IssuesChangesNotification serialized = underTest.serialize(builder);
IssuesChangesNotificationBuilder deserialized = underTest.from(serialized);
assertThat(deserialized.getChange()).isEqualTo(builder.getChange());
assertThat(deserialized.getIssues()).isEqualTo(builder.getIssues());
}
@Test
public void should_serialize_issues_from_same_external_rules() {
Set<IssuesChangesNotificationBuilder.ChangedIssue> issues = IntStream.range(0, 3)
.mapToObj(i -> new IssuesChangesNotificationBuilder.ChangedIssue.Builder("issue_key_" + i)
.setNewStatus("foo")
.setAssignee(null)
.setRule(newRule("repository", "key", null, "name"))
.setProject(newProject(i + ""))
.build())
.collect(toSet());
IssuesChangesNotificationBuilder builder = new IssuesChangesNotificationBuilder(issues,
new IssuesChangesNotificationBuilder.UserChange(new Random().nextLong(), new IssuesChangesNotificationBuilder.User("user_uuid", "user_login", null)));
IssuesChangesNotification serialized = underTest.serialize(builder);
IssuesChangesNotificationBuilder deserialized = underTest.from(serialized);
assertThat(deserialized.getChange()).isEqualTo(builder.getChange());
assertThat(deserialized.getIssues()).isEqualTo(builder.getIssues());
}
@Test
public void should_serialize_hotspot() {
Set<IssuesChangesNotificationBuilder.ChangedIssue> issues = IntStream.range(0, 3)
.mapToObj(i -> new IssuesChangesNotificationBuilder.ChangedIssue.Builder("issue_key_" + i)
.setNewStatus("foo")
.setAssignee(null)
.setRule(newRule("repository", "key", RuleType.SECURITY_HOTSPOT, "name"))
.setProject(newProject(i + ""))
.build())
.collect(toSet());
IssuesChangesNotificationBuilder builder = new IssuesChangesNotificationBuilder(issues,
new IssuesChangesNotificationBuilder.UserChange(new Random().nextLong(), new IssuesChangesNotificationBuilder.User("user_uuid", "user_login", null)));
IssuesChangesNotification serialized = underTest.serialize(builder);
IssuesChangesNotificationBuilder deserialized = underTest.from(serialized);
assertThat(deserialized.getChange()).isEqualTo(builder.getChange());
assertThat(deserialized.getIssues()).isEqualTo(builder.getIssues());
}
private static IssuesChangesNotificationBuilder.Rule newRule(String repository, String key, RuleType type, String name) {
return new IssuesChangesNotificationBuilder.Rule(RuleKey.of(repository, key), type, name);
}
}
| 6,816 | 46.671329 | 156 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/IssuesChangesNotificationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class IssuesChangesNotificationTest {
private IssuesChangesNotification notification = new IssuesChangesNotification();
@Test
public void verify_type() {
assertThat(notification.getType()).isEqualTo("issues-changes");
}
}
| 1,216 | 32.805556 | 83 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/MyNewIssuesEmailTemplateTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.EmailSettings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.notifications.Notification;
import org.sonar.api.platform.Server;
import org.sonar.server.l18n.I18nRule;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.COMPONENT;
import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.EFFORT;
import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.RULE;
import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.RULE_TYPE;
import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.TAG;
public class MyNewIssuesEmailTemplateTest {
@Rule
public I18nRule i18n = new I18nRule()
.put("issue.type.BUG", "Bug")
.put("issue.type.CODE_SMELL", "Code Smell")
.put("issue.type.VULNERABILITY", "Vulnerability");
private MapSettings settings = new MapSettings();
private Server server = mock(Server.class);
private MyNewIssuesEmailTemplate underTest = new MyNewIssuesEmailTemplate(new EmailSettings(settings.asConfig(), server), i18n);
@Before
public void setUp() {
when(server.getPublicRootUrl()).thenReturn("http://nemo.sonarsource.org");
}
@Test
public void no_format_if_not_the_correct_notif() {
Notification notification = new Notification("new-issues");
EmailMessage message = underTest.format(notification);
assertThat(message).isNull();
}
@Test
public void format_email_with_all_fields_filled() {
Notification notification = newNotification(32);
addTags(notification);
addRules(notification);
addComponents(notification);
EmailMessage message = underTest.format(notification);
// TODO datetime to be completed when test is isolated from JVM timezone
assertThat(message.getMessage()).startsWith(
"Project: Struts\n" +
"\n" +
"32 new issues (new debt: 1d3h)\n" +
"\n" +
" Type\n" +
" Bug: 1 Vulnerability: 3 Code Smell: 0\n" +
"\n" +
" Rules\n" +
" Rule the Universe (Clojure): 42\n" +
" Rule the World (Java): 5\n" +
"\n" +
" Tags\n" +
" oscar: 3\n" +
" cesar: 10\n" +
"\n" +
" Most impacted files\n" +
" /path/to/file: 3\n" +
" /path/to/directory: 7\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/project/issues?id=org.apache%3Astruts&assignees=lo.gin&createdAt=2010-05-18");
}
@Test
public void message_id() {
Notification notification = newNotification(32);
EmailMessage message = underTest.format(notification);
assertThat(message.getMessageId()).isEqualTo("my-new-issues/org.apache:struts");
}
@Test
public void subject() {
Notification notification = newNotification(32);
EmailMessage message = underTest.format(notification);
assertThat(message.getSubject()).isEqualTo("You have 32 new issues on project Struts");
}
@Test
public void subject_on_branch() {
Notification notification = newNotification(32)
.setFieldValue("branch", "feature1");
EmailMessage message = underTest.format(notification);
assertThat(message.getSubject()).isEqualTo("You have 32 new issues on project Struts (feature1)");
}
@Test
public void format_email_with_no_assignees_tags_nor_components() {
Notification notification = newNotification(32)
.setFieldValue("projectVersion", "52.0");
EmailMessage message = underTest.format(notification);
// TODO datetime to be completed when test is isolated from JVM timezone
assertThat(message.getMessage())
.startsWith("Project: Struts\n" +
"Version: 52.0\n" +
"\n" +
"32 new issues (new debt: 1d3h)\n" +
"\n" +
" Type\n" +
" Bug: 1 Vulnerability: 3 Code Smell: 0\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/project/issues?id=org.apache%3Astruts&assignees=lo.gin&createdAt=2010-05-18");
}
@Test
public void format_email_with_issue_on_branch() {
Notification notification = newNotification(32)
.setFieldValue("projectVersion", "52.0")
.setFieldValue("branch", "feature1");
EmailMessage message = underTest.format(notification);
// TODO datetime to be completed when test is isolated from JVM timezone
assertThat(message.getMessage())
.startsWith("Project: Struts\n" +
"Branch: feature1\n" +
"Version: 52.0\n" +
"\n" +
"32 new issues (new debt: 1d3h)\n" +
"\n" +
" Type\n" +
" Bug: 1 Vulnerability: 3 Code Smell: 0\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/project/issues?id=org.apache%3Astruts&assignees=lo.gin&branch=feature1&createdAt=2010-05-18");
}
@Test
public void format_email_supports_single_issue() {
Notification notification = newNotification(1);
EmailMessage message = underTest.format(notification);
assertThat(message.getSubject())
.isEqualTo("You have 1 new issue on project Struts");
assertThat(message.getMessage())
.contains("1 new issue (new debt: 1d3h)\n");
}
@Test
public void format_supports_null_version() {
Notification notification = newNotification(32)
.setFieldValue("branch", "feature1");
EmailMessage message = underTest.format(notification);
// TODO datetime to be completed when test is isolated from JVM timezone
assertThat(message.getMessage())
.startsWith("Project: Struts\n" +
"Branch: feature1\n" +
"\n" +
"32 new issues (new debt: 1d3h)\n" +
"\n" +
" Type\n" +
" Bug: 1 Vulnerability: 3 Code Smell: 0\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/project/issues?id=org.apache%3Astruts&assignees=lo.gin&branch=feature1&createdAt=2010-05-18");
}
@Test
public void do_not_add_footer_when_properties_missing() {
Notification notification = new Notification(MyNewIssuesNotification.MY_NEW_ISSUES_NOTIF_TYPE)
.setFieldValue(RULE_TYPE + ".count", "32")
.setFieldValue("projectName", "Struts");
EmailMessage message = underTest.format(notification);
assertThat(message.getMessage()).doesNotContain("See it");
}
private Notification newNotification(int count) {
return new Notification(MyNewIssuesNotification.MY_NEW_ISSUES_NOTIF_TYPE)
.setFieldValue("projectName", "Struts")
.setFieldValue("projectKey", "org.apache:struts")
.setFieldValue("projectDate", "2010-05-18T14:50:45+0000")
.setFieldValue("assignee", "lo.gin")
.setFieldValue(EFFORT + ".count", "1d3h")
.setFieldValue(RULE_TYPE + ".count", String.valueOf(count))
.setFieldValue(RULE_TYPE + ".BUG.count", "1")
.setFieldValue(RULE_TYPE + ".VULNERABILITY.count", "3")
.setFieldValue(RULE_TYPE + ".CODE_SMELL.count", "0");
}
private void addTags(Notification notification) {
notification
.setFieldValue(TAG + ".1.label", "oscar")
.setFieldValue(TAG + ".1.count", "3")
.setFieldValue(TAG + ".2.label", "cesar")
.setFieldValue(TAG + ".2.count", "10");
}
private void addComponents(Notification notification) {
notification
.setFieldValue(COMPONENT + ".1.label", "/path/to/file")
.setFieldValue(COMPONENT + ".1.count", "3")
.setFieldValue(COMPONENT + ".2.label", "/path/to/directory")
.setFieldValue(COMPONENT + ".2.count", "7");
}
private void addRules(Notification notification) {
notification
.setFieldValue(RULE + ".1.label", "Rule the Universe (Clojure)")
.setFieldValue(RULE + ".1.count", "42")
.setFieldValue(RULE + ".2.label", "Rule the World (Java)")
.setFieldValue(RULE + ".2.count", "5");
}
private void assertStartsWithFile(String message, String resourcePath) throws IOException {
String fileContent = IOUtils.toString(getClass().getResource(resourcePath), StandardCharsets.UTF_8);
assertThat(sanitizeString(message)).startsWith(sanitizeString(fileContent));
}
/**
* sanitize EOL and tabs if git clone is badly configured
*/
private static String sanitizeString(String s) {
return s.replaceAll("\\r\\n|\\r|\\s+", "");
}
}
| 9,561 | 35.636015 | 148 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/MyNewIssuesNotificationHandlerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import java.util.Collections;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.server.notification.NotificationDispatcherMetadata;
import org.sonar.server.notification.NotificationManager;
import org.sonar.server.notification.NotificationManager.EmailRecipient;
import org.sonar.server.notification.email.EmailNotificationChannel;
import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest;
import static com.google.common.collect.ImmutableSet.of;
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.server.notification.NotificationDispatcherMetadata.GLOBAL_NOTIFICATION;
import static org.sonar.server.notification.NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION;
import static org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject.ALL_MUST_HAVE_ROLE_USER;
public class MyNewIssuesNotificationHandlerTest {
private static final String MY_NEW_ISSUES_DISPATCHER_KEY = "SQ-MyNewIssues";
private NotificationManager notificationManager = mock(NotificationManager.class);
private EmailNotificationChannel emailNotificationChannel = mock(EmailNotificationChannel.class);
private MyNewIssuesNotificationHandler underTest = new MyNewIssuesNotificationHandler(notificationManager, emailNotificationChannel);
@Test
public void getMetadata_returns_same_instance_as_static_method() {
assertThat(underTest.getMetadata()).containsSame(MyNewIssuesNotificationHandler.newMetadata());
}
@Test
public void verify_myNewIssues_notification_dispatcher_key() {
NotificationDispatcherMetadata metadata = MyNewIssuesNotificationHandler.newMetadata();
assertThat(metadata.getDispatcherKey()).isEqualTo(MY_NEW_ISSUES_DISPATCHER_KEY);
}
@Test
public void myNewIssues_notification_is_enable_at_global_level() {
NotificationDispatcherMetadata metadata = MyNewIssuesNotificationHandler.newMetadata();
assertThat(metadata.getProperty(GLOBAL_NOTIFICATION)).isEqualTo("true");
}
@Test
public void myNewIssues_notification_is_enable_at_project_level() {
NotificationDispatcherMetadata metadata = MyNewIssuesNotificationHandler.newMetadata();
assertThat(metadata.getProperty(PER_PROJECT_NOTIFICATION)).isEqualTo("true");
}
@Test
public void getNotificationClass_is_MyNewIssuesNotification() {
assertThat(underTest.getNotificationClass()).isEqualTo(MyNewIssuesNotification.class);
}
@Test
public void deliver_has_no_effect_if_notifications_is_empty() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
int deliver = underTest.deliver(Collections.emptyList());
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager, emailNotificationChannel);
}
@Test
public void deliver_has_no_effect_if_emailNotificationChannel_is_disabled() {
when(emailNotificationChannel.isActivated()).thenReturn(false);
Set<MyNewIssuesNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> mock(MyNewIssuesNotification.class))
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
notifications.forEach(Mockito::verifyNoInteractions);
}
@Test
public void deliver_has_no_effect_if_no_notification_has_projectKey() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<MyNewIssuesNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> newNotification(null, null))
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
notifications.forEach(notification -> {
verify(notification).getProjectKey();
verifyNoMoreInteractions(notification);
});
}
@Test
public void deliver_has_no_effect_if_no_notification_has_assignee() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<MyNewIssuesNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> newNotification(randomAlphabetic(5 + i), null))
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
notifications.forEach(notification -> {
verify(notification).getProjectKey();
verify(notification).getAssignee();
verifyNoMoreInteractions(notification);
});
}
@Test
public void deliver_has_no_effect_if_no_notification_has_subscribed_assignee_to_MyNewIssue_notifications() {
String projectKey = randomAlphabetic(12);
String assignee = randomAlphabetic(10);
MyNewIssuesNotification notification = newNotification(projectKey, assignee);
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey, of(assignee), ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emptySet());
int deliver = underTest.deliver(Collections.singleton(notification));
assertThat(deliver).isZero();
verify(notificationManager).findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey, of(assignee), ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_ignores_notification_without_projectKey() {
String projectKey = randomAlphabetic(10);
Set<MyNewIssuesNotification> withProjectKey = IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(projectKey, randomAlphabetic(11 + i)))
.collect(toSet());
Set<MyNewIssuesNotification> noProjectKey = IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(null, randomAlphabetic(11 + i)))
.collect(toSet());
Set<MyNewIssuesNotification> noProjectKeyNoAssignee = randomSetOfNotifications(null, null);
Set<EmailRecipient> authorizedRecipients = withProjectKey.stream()
.map(n -> new EmailRecipient(n.getAssignee(), n.getAssignee() + "@foo"))
.collect(toSet());
Set<EmailDeliveryRequest> expectedRequests = withProjectKey.stream()
.map(n -> new EmailDeliveryRequest(n.getAssignee() + "@foo", n))
.collect(toSet());
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<String> assignees = withProjectKey.stream().map(MyNewIssuesNotification::getAssignee).collect(toSet());
when(notificationManager.findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey, assignees, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(authorizedRecipients);
Set<MyNewIssuesNotification> notifications = Stream.of(withProjectKey.stream(), noProjectKey.stream(), noProjectKeyNoAssignee.stream())
.flatMap(t -> t)
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verify(notificationManager).findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey, assignees, ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verify(emailNotificationChannel).deliverAll(expectedRequests);
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_ignores_notification_without_assignee() {
String projectKey = randomAlphabetic(10);
Set<MyNewIssuesNotification> withAssignee = IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(projectKey, randomAlphabetic(11 + i)))
.collect(toSet());
Set<MyNewIssuesNotification> noAssignee = randomSetOfNotifications(projectKey, null);
Set<MyNewIssuesNotification> noProjectKeyNoAssignee = randomSetOfNotifications(null, null);
Set<EmailRecipient> authorizedRecipients = withAssignee.stream()
.map(n -> new EmailRecipient(n.getAssignee(), n.getAssignee() + "@foo"))
.collect(toSet());
Set<EmailDeliveryRequest> expectedRequests = withAssignee.stream()
.map(n -> new EmailDeliveryRequest(n.getAssignee() + "@foo", n))
.collect(toSet());
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<String> assignees = withAssignee.stream().map(MyNewIssuesNotification::getAssignee).collect(toSet());
when(notificationManager.findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey, assignees, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(authorizedRecipients);
Set<MyNewIssuesNotification> notifications = Stream.of(withAssignee.stream(), noAssignee.stream(), noProjectKeyNoAssignee.stream())
.flatMap(t -> t)
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verify(notificationManager).findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey, assignees, ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verify(emailNotificationChannel).deliverAll(expectedRequests);
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_MyNewIssue_notifications() {
String projectKey1 = randomAlphabetic(10);
String assignee1 = randomAlphabetic(11);
String projectKey2 = randomAlphabetic(12);
String assignee2 = randomAlphabetic(13);
Set<MyNewIssuesNotification> notifications1 = randomSetOfNotifications(projectKey1, assignee1);
Set<MyNewIssuesNotification> notifications2 = randomSetOfNotifications(projectKey2, assignee2);
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey1, of(assignee1), ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emptySet());
when(notificationManager.findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey2, of(assignee2),ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emptySet());
int deliver = underTest.deliver(Stream.concat(notifications1.stream(), notifications2.stream()).collect(toSet()));
assertThat(deliver).isZero();
verify(notificationManager).findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey1, of(assignee1), ALL_MUST_HAVE_ROLE_USER);
verify(notificationManager).findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey2, of(assignee2), ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_ignores_notifications_which_assignee_has_no_subscribed_to_MyNewIssue_notifications() {
String projectKey = randomAlphabetic(5);
String assignee1 = randomAlphabetic(6);
String assignee2 = randomAlphabetic(7);
Set<String> assignees = of(assignee1, assignee2);
// assignee1 is not authorized
Set<MyNewIssuesNotification> assignee1Notifications = randomSetOfNotifications(projectKey, assignee1);
// assignee2 is authorized
Set<MyNewIssuesNotification> assignee2Notifications = randomSetOfNotifications(projectKey, assignee2);
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey, assignees, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(of(emailRecipientOf(assignee2)));
Set<EmailDeliveryRequest> expectedRequests = assignee2Notifications.stream()
.map(t -> new EmailDeliveryRequest(emailOf(t.getAssignee()), t))
.collect(toSet());
int deliveredCount = new Random().nextInt(expectedRequests.size());
when(emailNotificationChannel.deliverAll(expectedRequests)).thenReturn(deliveredCount);
int deliver = underTest.deliver(Stream.concat(assignee1Notifications.stream(), assignee2Notifications.stream()).collect(toSet()));
assertThat(deliver).isEqualTo(deliveredCount);
verify(notificationManager).findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey, assignees, ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verify(emailNotificationChannel).deliverAll(expectedRequests);
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_returns_sum_of_delivery_counts_when_multiple_projects() {
String projectKey1 = randomAlphabetic(5);
String projectKey2 = randomAlphabetic(6);
String projectKey3 = randomAlphabetic(7);
String assignee1 = randomAlphabetic(8);
String assignee2 = randomAlphabetic(9);
String assignee3 = randomAlphabetic(10);
// assignee1 has subscribed to project1 only, no notification on project3
Set<MyNewIssuesNotification> assignee1Project1 = randomSetOfNotifications(projectKey1, assignee1);
Set<MyNewIssuesNotification> assignee1Project2 = randomSetOfNotifications(projectKey2, assignee1);
// assignee2 is subscribed to project1 and project2, notifications on all projects
Set<MyNewIssuesNotification> assignee2Project1 = randomSetOfNotifications(projectKey1, assignee2);
Set<MyNewIssuesNotification> assignee2Project2 = randomSetOfNotifications(projectKey2, assignee2);
Set<MyNewIssuesNotification> assignee2Project3 = randomSetOfNotifications(projectKey3, assignee2);
// assignee3 is subscribed to project2 only, no notification on project1
Set<MyNewIssuesNotification> assignee3Project2 = randomSetOfNotifications(projectKey2, assignee3);
Set<MyNewIssuesNotification> assignee3Project3 = randomSetOfNotifications(projectKey3, assignee3);
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey1, of(assignee1, assignee2), ALL_MUST_HAVE_ROLE_USER))
.thenReturn(of(emailRecipientOf(assignee1), emailRecipientOf(assignee2)));
when(notificationManager.findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey2, of(assignee1, assignee2, assignee3), ALL_MUST_HAVE_ROLE_USER))
.thenReturn(of(emailRecipientOf(assignee2), emailRecipientOf(assignee3)));
when(notificationManager.findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey3, of(assignee2, assignee3), ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emptySet());
Set<EmailDeliveryRequest> expectedRequests = Stream.of(
assignee1Project1.stream(), assignee2Project1.stream(), assignee2Project2.stream(), assignee3Project2.stream())
.flatMap(t -> t)
.map(t -> new EmailDeliveryRequest(emailOf(t.getAssignee()), t))
.collect(toSet());
int deliveredCount = new Random().nextInt(expectedRequests.size());
when(emailNotificationChannel.deliverAll(expectedRequests)).thenReturn(deliveredCount);
Set<MyNewIssuesNotification> notifications = Stream.of(
assignee1Project1.stream(), assignee1Project2.stream(),
assignee2Project1.stream(), assignee2Project2.stream(),
assignee2Project3.stream(), assignee3Project2.stream(), assignee3Project3.stream())
.flatMap(t -> t)
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isEqualTo(deliveredCount);
verify(notificationManager).findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey1, of(assignee1, assignee2), ALL_MUST_HAVE_ROLE_USER);
verify(notificationManager).findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey2, of(assignee1, assignee2, assignee3), ALL_MUST_HAVE_ROLE_USER);
verify(notificationManager).findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey3, of(assignee2, assignee3), ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verify(emailNotificationChannel).deliverAll(expectedRequests);
verifyNoMoreInteractions(emailNotificationChannel);
}
private static Set<MyNewIssuesNotification> randomSetOfNotifications(@Nullable String projectKey, @Nullable String assignee) {
return IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(projectKey, assignee))
.collect(Collectors.toSet());
}
private static MyNewIssuesNotification newNotification(@Nullable String projectKey, @Nullable String assignee) {
MyNewIssuesNotification notification = mock(MyNewIssuesNotification.class);
when(notification.getProjectKey()).thenReturn(projectKey);
when(notification.getAssignee()).thenReturn(assignee);
return notification;
}
private static EmailRecipient emailRecipientOf(String assignee1) {
return new EmailRecipient(assignee1, emailOf(assignee1));
}
private static String emailOf(String assignee1) {
return assignee1 + "@bar";
}
}
| 18,904 | 51.223757 | 167 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/MyNewIssuesNotificationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import org.junit.Test;
import org.sonar.api.utils.Durations;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTesting;
import org.sonar.server.issue.notification.NewIssuesNotification.DetailsSupplier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.sonar.server.issue.notification.AbstractNewIssuesEmailTemplate.FIELD_ASSIGNEE;
public class MyNewIssuesNotificationTest {
private MyNewIssuesNotification underTest = new MyNewIssuesNotification(mock(Durations.class), mock(DetailsSupplier.class));
@Test
public void set_assignee() {
UserDto user = UserTesting.newUserDto();
underTest.setAssignee(user);
assertThat(underTest.getFieldValue(FIELD_ASSIGNEE))
.isEqualTo(underTest.getAssignee())
.isEqualTo(user.getLogin());
}
@Test
public void set_with_a_specific_type() {
assertThat(underTest.getType()).isEqualTo(MyNewIssuesNotification.MY_NEW_ISSUES_NOTIF_TYPE);
}
}
| 1,885 | 34.584906 | 126 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesEmailTemplateTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.EmailSettings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.notifications.Notification;
import org.sonar.api.platform.Server;
import org.sonar.server.l18n.I18nRule;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.ASSIGNEE;
import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.COMPONENT;
import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.EFFORT;
import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.RULE;
import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.RULE_TYPE;
import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.TAG;
public class NewIssuesEmailTemplateTest {
@Rule
public I18nRule i18n = new I18nRule()
.put("issue.type.BUG", "Bug")
.put("issue.type.CODE_SMELL", "Code Smell")
.put("issue.type.VULNERABILITY", "Vulnerability");
private MapSettings settings = new MapSettings();
private Server server = mock(Server.class);
private NewIssuesEmailTemplate template = new NewIssuesEmailTemplate(new EmailSettings(settings.asConfig(), server), i18n);
@Before
public void setUp() {
when(server.getPublicRootUrl()).thenReturn("http://nemo.sonarsource.org");
}
@Test
public void no_format_is_not_the_correct_notification() {
Notification notification = new Notification("my-new-issues");
EmailMessage message = template.format(notification);
assertThat(message).isNull();
}
@Test
public void message_id() {
Notification notification = newNotification(32);
EmailMessage message = template.format(notification);
assertThat(message.getMessageId()).isEqualTo("new-issues/org.apache:struts");
}
@Test
public void subject() {
Notification notification = newNotification(32);
EmailMessage message = template.format(notification);
assertThat(message.getSubject()).isEqualTo("Struts: 32 new issues (new debt: 1d3h)");
}
@Test
public void subject_on_branch() {
Notification notification = newNotification(32)
.setFieldValue("branch", "feature1");
EmailMessage message = template.format(notification);
assertThat(message.getSubject()).isEqualTo("Struts (feature1): 32 new issues (new debt: 1d3h)");
}
@Test
public void format_email_with_all_fields_filled() {
Notification notification = newNotification(32)
.setFieldValue("projectVersion", "42.1.1");
addAssignees(notification);
addRules(notification);
addTags(notification);
addComponents(notification);
EmailMessage message = template.format(notification);
// TODO datetime to be completed when test is isolated from JVM timezone
assertThat(message.getMessage())
.startsWith("Project: Struts\n" +
"Version: 42.1.1\n" +
"\n" +
"32 new issues (new debt: 1d3h)\n" +
"\n" +
" Type\n" +
" Bug: 1 Vulnerability: 10 Code Smell: 3\n" +
"\n" +
" Assignees\n" +
" robin.williams: 5\n" +
" al.pacino: 7\n" +
"\n" +
" Rules\n" +
" Rule the Universe (Clojure): 42\n" +
" Rule the World (Java): 5\n" +
"\n" +
" Tags\n" +
" oscar: 3\n" +
" cesar: 10\n" +
"\n" +
" Most impacted files\n" +
" /path/to/file: 3\n" +
" /path/to/directory: 7\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/project/issues?id=org.apache%3Astruts&createdAt=2010-05-1");
}
@Test
public void format_email_with_no_assignees_tags_nor_components_nor_version() {
Notification notification = newNotification(32);
EmailMessage message = template.format(notification);
// TODO datetime to be completed when test is isolated from JVM timezone
assertThat(message.getMessage())
.startsWith("Project: Struts\n" +
"\n" +
"32 new issues (new debt: 1d3h)\n" +
"\n" +
" Type\n" +
" Bug: 1 Vulnerability: 10 Code Smell: 3\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/project/issues?id=org.apache%3Astruts&createdAt=2010-05-1");
}
@Test
public void format_email_supports_single_issue() {
Notification notification = newNotification(1);
EmailMessage message = template.format(notification);
assertThat(message.getSubject())
.isEqualTo("Struts: 1 new issue (new debt: 1d3h)");
assertThat(message.getMessage())
.contains("1 new issue (new debt: 1d3h)\n");
}
@Test
public void format_email_with_issue_on_branch() {
Notification notification = newNotification(32)
.setFieldValue("branch", "feature1");
EmailMessage message = template.format(notification);
// TODO datetime to be completed when test is isolated from JVM timezone
assertThat(message.getMessage())
.startsWith("Project: Struts\n" +
"Branch: feature1\n" +
"\n" +
"32 new issues (new debt: 1d3h)\n" +
"\n" +
" Type\n" +
" Bug: 1 Vulnerability: 10 Code Smell: 3\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/project/issues?id=org.apache%3Astruts&branch=feature1&createdAt=2010-05-1");
}
@Test
public void format_email_with_issue_on_branch_with_version() {
Notification notification = newNotification(32)
.setFieldValue("branch", "feature1")
.setFieldValue("projectVersion", "42.1.1");
EmailMessage message = template.format(notification);
// TODO datetime to be completed when test is isolated from JVM timezone
assertThat(message.getMessage())
.startsWith("Project: Struts\n" +
"Branch: feature1\n" +
"Version: 42.1.1\n" +
"\n" +
"32 new issues (new debt: 1d3h)\n" +
"\n" +
" Type\n" +
" Bug: 1 Vulnerability: 10 Code Smell: 3\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/project/issues?id=org.apache%3Astruts&branch=feature1&createdAt=2010-05-1");
}
@Test
public void do_not_add_footer_when_properties_missing() {
Notification notification = new Notification(NewIssuesNotification.TYPE)
.setFieldValue(RULE_TYPE + ".count", "32")
.setFieldValue("projectName", "Struts");
EmailMessage message = template.format(notification);
assertThat(message.getMessage()).doesNotContain("See it");
}
private Notification newNotification(int count) {
return new Notification(NewIssuesNotification.TYPE)
.setFieldValue("projectName", "Struts")
.setFieldValue("projectKey", "org.apache:struts")
.setFieldValue("projectDate", "2010-05-18T14:50:45+0000")
.setFieldValue(EFFORT + ".count", "1d3h")
.setFieldValue(RULE_TYPE + ".count", String.valueOf(count))
.setFieldValue(RULE_TYPE + ".BUG.count", "1")
.setFieldValue(RULE_TYPE + ".CODE_SMELL.count", "3")
.setFieldValue(RULE_TYPE + ".VULNERABILITY.count", "10");
}
private void addAssignees(Notification notification) {
notification
.setFieldValue(ASSIGNEE + ".1.label", "robin.williams")
.setFieldValue(ASSIGNEE + ".1.count", "5")
.setFieldValue(ASSIGNEE + ".2.label", "al.pacino")
.setFieldValue(ASSIGNEE + ".2.count", "7");
}
private void addTags(Notification notification) {
notification
.setFieldValue(TAG + ".1.label", "oscar")
.setFieldValue(TAG + ".1.count", "3")
.setFieldValue(TAG + ".2.label", "cesar")
.setFieldValue(TAG + ".2.count", "10");
}
private void addComponents(Notification notification) {
notification
.setFieldValue(COMPONENT + ".1.label", "/path/to/file")
.setFieldValue(COMPONENT + ".1.count", "3")
.setFieldValue(COMPONENT + ".2.label", "/path/to/directory")
.setFieldValue(COMPONENT + ".2.count", "7");
}
private void addRules(Notification notification) {
notification
.setFieldValue(RULE + ".1.label", "Rule the Universe (Clojure)")
.setFieldValue(RULE + ".1.count", "42")
.setFieldValue(RULE + ".2.label", "Rule the World (Java)")
.setFieldValue(RULE + ".2.count", "5");
}
private void assertStartsWithFile(String message, String resourcePath) throws IOException {
String fileContent = IOUtils.toString(getClass().getResource(resourcePath), StandardCharsets.UTF_8);
assertThat(sanitizeString(message)).startsWith(sanitizeString(fileContent));
}
/**
* sanitize EOL and tabs if git clone is badly configured
*/
private static String sanitizeString(String s) {
return s.replaceAll("\\r\\n|\\r|\\s+", "");
}
}
| 9,964 | 35.236364 | 130 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesNotificationHandlerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import java.util.Collections;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.server.notification.NotificationDispatcherMetadata;
import org.sonar.server.notification.NotificationManager;
import org.sonar.server.notification.NotificationManager.EmailRecipient;
import org.sonar.server.notification.email.EmailNotificationChannel;
import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest;
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.server.notification.NotificationDispatcherMetadata.GLOBAL_NOTIFICATION;
import static org.sonar.server.notification.NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION;
import static org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject.ALL_MUST_HAVE_ROLE_USER;
public class NewIssuesNotificationHandlerTest {
private static final String NEW_ISSUES_DISPATCHER_KEY = "NewIssues";
private NotificationManager notificationManager = mock(NotificationManager.class);
private EmailNotificationChannel emailNotificationChannel = mock(EmailNotificationChannel.class);
private NewIssuesNotificationHandler underTest = new NewIssuesNotificationHandler(notificationManager, emailNotificationChannel);
@Test
public void getMetadata_returns_same_instance_as_static_method() {
assertThat(underTest.getMetadata()).containsSame(NewIssuesNotificationHandler.newMetadata());
}
@Test
public void verify_myNewIssues_notification_dispatcher_key() {
NotificationDispatcherMetadata metadata = NewIssuesNotificationHandler.newMetadata();
assertThat(metadata.getDispatcherKey()).isEqualTo(NEW_ISSUES_DISPATCHER_KEY);
}
@Test
public void myNewIssues_notification_is_disabled_at_global_level() {
NotificationDispatcherMetadata metadata = NewIssuesNotificationHandler.newMetadata();
assertThat(metadata.getProperty(GLOBAL_NOTIFICATION)).isEqualTo("false");
}
@Test
public void myNewIssues_notification_is_enable_at_project_level() {
NotificationDispatcherMetadata metadata = NewIssuesNotificationHandler.newMetadata();
assertThat(metadata.getProperty(PER_PROJECT_NOTIFICATION)).isEqualTo("true");
}
@Test
public void getNotificationClass_is_NewIssuesNotification() {
assertThat(underTest.getNotificationClass()).isEqualTo(NewIssuesNotification.class);
}
@Test
public void deliver_has_no_effect_if_notifications_is_empty() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
int deliver = underTest.deliver(Collections.emptyList());
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager, emailNotificationChannel);
}
@Test
public void deliver_has_no_effect_if_emailNotificationChannel_is_disabled() {
when(emailNotificationChannel.isActivated()).thenReturn(false);
Set<NewIssuesNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> mock(NewIssuesNotification.class))
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
notifications.forEach(Mockito::verifyNoInteractions);
}
@Test
public void deliver_has_no_effect_if_no_notification_has_projectKey() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<NewIssuesNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> newNotification(null))
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
notifications.forEach(notification -> {
verify(notification).getProjectKey();
verifyNoMoreInteractions(notification);
});
}
@Test
public void deliver_has_no_effect_if_no_notification_has_subscribed_recipients_to_NewIssue_notifications() {
String projectKey = randomAlphabetic(12);
NewIssuesNotification notification = newNotification(projectKey);
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emptySet());
int deliver = underTest.deliver(Collections.singleton(notification));
assertThat(deliver).isZero();
verify(notificationManager).findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_ignores_notification_without_projectKey() {
String projectKey = randomAlphabetic(10);
Set<NewIssuesNotification> withProjectKey = IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(projectKey))
.collect(toSet());
Set<NewIssuesNotification> noProjectKey = IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(null))
.collect(toSet());
Set<EmailRecipient> emailRecipients = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> "user_" + i)
.map(login -> new EmailRecipient(login, emailOf(login)))
.collect(toSet());
Set<EmailDeliveryRequest> expectedRequests = emailRecipients.stream()
.flatMap(emailRecipient -> withProjectKey.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.email(), notif)))
.collect(toSet());
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emailRecipients);
Set<NewIssuesNotification> notifications = Stream.of(withProjectKey.stream(), noProjectKey.stream())
.flatMap(t -> t)
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verify(notificationManager).findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verify(emailNotificationChannel).deliverAll(expectedRequests);
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_NewIssue_notifications() {
String projectKey1 = randomAlphabetic(10);
String projectKey2 = randomAlphabetic(11);
Set<NewIssuesNotification> notifications1 = randomSetOfNotifications(projectKey1);
Set<NewIssuesNotification> notifications2 = randomSetOfNotifications(projectKey2);
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<EmailRecipient> emailRecipients1 = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> "user1_" + i)
.map(login -> new EmailRecipient(login, emailOf(login)))
.collect(toSet());
Set<EmailRecipient> emailRecipients2 = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> "user2_" + i)
.map(login -> new EmailRecipient(login, emailOf(login)))
.collect(toSet());
when(notificationManager.findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey1, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emailRecipients1);
when(notificationManager.findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey2, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emailRecipients2);
Set<EmailDeliveryRequest> expectedRequests = Stream.concat(
emailRecipients1.stream()
.flatMap(emailRecipient -> notifications1.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.email(), notif))),
emailRecipients2.stream()
.flatMap(emailRecipient -> notifications2.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.email(), notif))))
.collect(toSet());
int deliver = underTest.deliver(Stream.concat(notifications1.stream(), notifications2.stream()).collect(toSet()));
assertThat(deliver).isZero();
verify(notificationManager).findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey1, ALL_MUST_HAVE_ROLE_USER);
verify(notificationManager).findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey2, ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verify(emailNotificationChannel).deliverAll(expectedRequests);
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_send_notifications_to_all_subscribers_of_all_projects() {
String projectKey1 = randomAlphabetic(10);
String projectKey2 = randomAlphabetic(11);
Set<NewIssuesNotification> notifications1 = randomSetOfNotifications(projectKey1);
Set<NewIssuesNotification> notifications2 = randomSetOfNotifications(projectKey2);
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey1, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emptySet());
when(notificationManager.findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey2, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emptySet());
int deliver = underTest.deliver(Stream.concat(notifications1.stream(), notifications2.stream()).collect(toSet()));
assertThat(deliver).isZero();
verify(notificationManager).findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey1, ALL_MUST_HAVE_ROLE_USER);
verify(notificationManager).findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey2, ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
}
private static Set<NewIssuesNotification> randomSetOfNotifications(@Nullable String projectKey) {
return IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(projectKey))
.collect(Collectors.toSet());
}
private static NewIssuesNotification newNotification(@Nullable String projectKey) {
NewIssuesNotification notification = mock(NewIssuesNotification.class);
when(notification.getProjectKey()).thenReturn(projectKey);
return notification;
}
private static String emailOf(String assignee1) {
return assignee1 + "@donut";
}
}
| 12,254 | 46.5 | 131 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesStatisticsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import org.junit.Test;
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.Duration;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.server.issue.notification.NewIssuesStatistics.Metric;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class NewIssuesStatisticsTest {
private final Random random = new Random();
private RuleType randomRuleTypeExceptHotspot = RuleType.values()[random.nextInt(RuleType.values().length - 1)];
private NewIssuesStatistics underTest = new NewIssuesStatistics(Issue::isNew);
@Test
public void add_fails_with_NPE_if_RuleType_is_null() {
String assignee = randomAlphanumeric(10);
DefaultIssue issue = new DefaultIssue().setType(null).setAssigneeUuid(assignee).setNew(new Random().nextBoolean());
assertThatThrownBy(() -> underTest.add(issue))
.isInstanceOf(NullPointerException.class);
}
@Test
public void add_issues_with_correct_global_statistics() {
DefaultIssue issue = new DefaultIssue()
.setAssigneeUuid("maynard")
.setComponentUuid("file-uuid")
.setNew(true)
.setType(RuleType.BUG)
.setRuleKey(RuleKey.of("SonarQube", "rule-the-world"))
.setTags(Lists.newArrayList("bug", "owasp"))
.setEffort(Duration.create(5L));
underTest.add(issue);
underTest.add(issue.setAssigneeUuid("james"));
underTest.add(issue.setAssigneeUuid("keenan"));
assertThat(countDistributionTotal(Metric.ASSIGNEE, "maynard")).isOne();
assertThat(countDistributionTotal(Metric.ASSIGNEE, "james")).isOne();
assertThat(countDistributionTotal(Metric.ASSIGNEE, "keenan")).isOne();
assertThat(countDistributionTotal(Metric.ASSIGNEE, "wrong.login")).isNull();
assertThat(countDistributionTotal(Metric.COMPONENT, "file-uuid")).isEqualTo(3);
assertThat(countDistributionTotal(Metric.COMPONENT, "wrong-uuid")).isNull();
assertThat(countDistributionTotal(Metric.RULE_TYPE, RuleType.BUG.name())).isEqualTo(3);
assertThat(countDistributionTotal(Metric.RULE_TYPE, RuleType.CODE_SMELL.name())).isNull();
assertThat(countDistributionTotal(Metric.TAG, "owasp")).isEqualTo(3);
assertThat(countDistributionTotal(Metric.TAG, "wrong-tag")).isNull();
assertThat(countDistributionTotal(Metric.RULE, "SonarQube:rule-the-world")).isEqualTo(3);
assertThat(countDistributionTotal(Metric.RULE, "SonarQube:has-a-fake-rule")).isNull();
assertThat(underTest.globalStatistics().effort().getTotal()).isEqualTo(15L);
assertThat(underTest.globalStatistics().hasIssues()).isTrue();
assertThat(underTest.hasIssues()).isTrue();
assertThat(underTest.getAssigneesStatistics().get("maynard").hasIssues()).isTrue();
}
@Test
public void add_counts_issue_per_RuleType_on_current_analysis_globally_and_per_assignee() {
String assignee = randomAlphanumeric(10);
Arrays.stream(RuleType.values())
.map(ruleType -> new DefaultIssue().setType(ruleType).setAssigneeUuid(assignee).setNew(true))
.forEach(underTest::add);
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.RULE_TYPE);
DistributedMetricStatsInt assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).getDistributedMetricStats(Metric.RULE_TYPE);
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> Arrays.stream(RuleType.values()).forEach(ruleType -> assertStats(distribution, ruleType.name(), 1, 1)));
}
@Test
public void add_counts_issue_per_RuleType_off_current_analysis_globally_and_per_assignee() {
String assignee = randomAlphanumeric(10);
Arrays.stream(RuleType.values())
.map(ruleType -> new DefaultIssue().setType(ruleType).setAssigneeUuid(assignee).setNew(false))
.forEach(underTest::add);
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.RULE_TYPE);
DistributedMetricStatsInt assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).getDistributedMetricStats(Metric.RULE_TYPE);
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> Arrays.stream(RuleType.values()).forEach(ruleType -> assertStats(distribution, ruleType.name(), 0, 1)));
}
@Test
public void add_counts_issue_per_component_on_current_analysis_globally_and_per_assignee() {
List<String> componentUuids = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
String assignee = randomAlphanumeric(10);
componentUuids.stream()
.map(componentUuid -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setComponentUuid(componentUuid).setAssigneeUuid(assignee).setNew(true))
.forEach(underTest::add);
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.COMPONENT);
DistributedMetricStatsInt assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).getDistributedMetricStats(Metric.COMPONENT);
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> componentUuids.forEach(componentUuid -> assertStats(distribution, componentUuid, 1, 1)));
}
@Test
public void add_counts_issue_per_component_off_current_analysis_globally_and_per_assignee() {
List<String> componentUuids = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
String assignee = randomAlphanumeric(10);
componentUuids.stream()
.map(componentUuid -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setComponentUuid(componentUuid).setAssigneeUuid(assignee).setNew(false))
.forEach(underTest::add);
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.COMPONENT);
NewIssuesStatistics.Stats stats = underTest.getAssigneesStatistics().get(assignee);
DistributedMetricStatsInt assigneeDistribution = stats.getDistributedMetricStats(Metric.COMPONENT);
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> componentUuids.forEach(componentUuid -> assertStats(distribution, componentUuid, 0, 1)));
}
@Test
public void add_does_not_count_component_if_null_neither_globally_nor_per_assignee() {
String assignee = randomAlphanumeric(10);
underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setComponentUuid(null).setAssigneeUuid(assignee).setNew(new Random().nextBoolean()));
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.COMPONENT);
DistributedMetricStatsInt assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).getDistributedMetricStats(Metric.COMPONENT);
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> {
assertThat(distribution.getTotal()).isZero();
assertThat(distribution.getForLabel(null)).isEmpty();
});
}
@Test
public void add_counts_issue_per_ruleKey_on_current_analysis_globally_and_per_assignee() {
String repository = randomAlphanumeric(3);
List<String> ruleKeys = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
String assignee = randomAlphanumeric(10);
ruleKeys.stream()
.map(ruleKey -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setRuleKey(RuleKey.of(repository, ruleKey)).setAssigneeUuid(assignee).setNew(true))
.forEach(underTest::add);
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.RULE);
NewIssuesStatistics.Stats stats = underTest.getAssigneesStatistics().get(assignee);
DistributedMetricStatsInt assigneeDistribution = stats.getDistributedMetricStats(Metric.RULE);
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> ruleKeys.forEach(ruleKey -> assertStats(distribution, RuleKey.of(repository, ruleKey).toString(), 1, 1)));
}
@Test
public void add_counts_issue_per_ruleKey_off_current_analysis_globally_and_per_assignee() {
String repository = randomAlphanumeric(3);
List<String> ruleKeys = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
String assignee = randomAlphanumeric(10);
ruleKeys.stream()
.map(ruleKey -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setRuleKey(RuleKey.of(repository, ruleKey)).setAssigneeUuid(assignee).setNew(false))
.forEach(underTest::add);
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.RULE);
DistributedMetricStatsInt assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).getDistributedMetricStats(Metric.RULE);
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> ruleKeys.forEach(ruleKey -> assertStats(distribution, RuleKey.of(repository, ruleKey).toString(), 0, 1)));
}
@Test
public void add_does_not_count_ruleKey_if_null_neither_globally_nor_per_assignee() {
String assignee = randomAlphanumeric(10);
underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setRuleKey(null).setAssigneeUuid(assignee).setNew(new Random().nextBoolean()));
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.RULE);
DistributedMetricStatsInt assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).getDistributedMetricStats(Metric.RULE);
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> {
assertThat(distribution.getTotal()).isZero();
assertThat(distribution.getForLabel(null)).isEmpty();
});
}
@Test
public void add_counts_issue_per_assignee_on_current_analysis_globally_and_per_assignee() {
List<String> assignees = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
assignees.stream()
.map(assignee -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setAssigneeUuid(assignee).setNew(true))
.forEach(underTest::add);
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.ASSIGNEE);
assignees.forEach(assignee -> assertStats(globalDistribution, assignee, 1, 1));
assignees.forEach(assignee -> {
NewIssuesStatistics.Stats stats = underTest.getAssigneesStatistics().get(assignee);
DistributedMetricStatsInt assigneeStats = stats.getDistributedMetricStats(Metric.ASSIGNEE);
assertThat(assigneeStats.getOnCurrentAnalysis()).isOne();
assertThat(assigneeStats.getTotal()).isOne();
assignees.forEach(s -> {
Optional<MetricStatsInt> forLabelOpts = assigneeStats.getForLabel(s);
if (s.equals(assignee)) {
assertThat(forLabelOpts).isPresent();
MetricStatsInt forLabel = forLabelOpts.get();
assertThat(forLabel.getOnCurrentAnalysis()).isOne();
assertThat(forLabel.getTotal()).isOne();
} else {
assertThat(forLabelOpts).isEmpty();
}
});
});
}
@Test
public void add_counts_issue_per_assignee_off_current_analysis_globally_and_per_assignee() {
List<String> assignees = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
assignees.stream()
.map(assignee -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setAssigneeUuid(assignee).setNew(false))
.forEach(underTest::add);
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.ASSIGNEE);
assignees.forEach(assignee -> assertStats(globalDistribution, assignee, 0, 1));
assignees.forEach(assignee -> {
NewIssuesStatistics.Stats stats = underTest.getAssigneesStatistics().get(assignee);
DistributedMetricStatsInt assigneeStats = stats.getDistributedMetricStats(Metric.ASSIGNEE);
assertThat(assigneeStats.getOnCurrentAnalysis()).isZero();
assertThat(assigneeStats.getTotal()).isOne();
assignees.forEach(s -> {
Optional<MetricStatsInt> forLabelOpts = assigneeStats.getForLabel(s);
if (s.equals(assignee)) {
assertThat(forLabelOpts).isPresent();
MetricStatsInt forLabel = forLabelOpts.get();
assertThat(forLabel.getOnCurrentAnalysis()).isZero();
assertThat(forLabel.getTotal()).isOne();
} else {
assertThat(forLabelOpts).isEmpty();
}
});
});
}
@Test
public void add_does_not_assignee_if_empty_neither_globally_nor_per_assignee() {
underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setAssigneeUuid(null).setNew(new Random().nextBoolean()));
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.ASSIGNEE);
assertThat(globalDistribution.getTotal()).isZero();
assertThat(globalDistribution.getForLabel(null)).isEmpty();
assertThat(underTest.getAssigneesStatistics()).isEmpty();
}
@Test
public void add_counts_issue_per_tags_on_current_analysis_globally_and_per_assignee() {
List<String> tags = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
String assignee = randomAlphanumeric(10);
underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setTags(tags).setAssigneeUuid(assignee).setNew(true));
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.TAG);
DistributedMetricStatsInt assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).getDistributedMetricStats(Metric.TAG);
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> tags.forEach(tag -> assertStats(distribution, tag, 1, 1)));
}
@Test
public void add_counts_issue_per_tags_off_current_analysis_globally_and_per_assignee() {
List<String> tags = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
String assignee = randomAlphanumeric(10);
underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setTags(tags).setAssigneeUuid(assignee).setNew(false));
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.TAG);
DistributedMetricStatsInt assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).getDistributedMetricStats(Metric.TAG);
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> tags.forEach(tag -> assertStats(distribution, tag, 0, 1)));
}
@Test
public void add_does_not_count_tags_if_empty_neither_globally_nor_per_assignee() {
String assignee = randomAlphanumeric(10);
underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setTags(Collections.emptyList()).setAssigneeUuid(assignee).setNew(new Random().nextBoolean()));
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.TAG);
DistributedMetricStatsInt assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).getDistributedMetricStats(Metric.TAG);
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> {
assertThat(distribution.getTotal()).isZero();
assertThat(distribution.getForLabel(null)).isEmpty();
});
}
@Test
public void add_sums_effort_on_current_analysis_globally_and_per_assignee() {
Random random = new Random();
List<Integer> efforts = IntStream.range(0, 1 + random.nextInt(10)).mapToObj(i -> 10_000 * i).toList();
int expected = efforts.stream().mapToInt(s -> s).sum();
String assignee = randomAlphanumeric(10);
efforts.stream()
.map(effort -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setEffort(Duration.create(effort)).setAssigneeUuid(assignee).setNew(true))
.forEach(underTest::add);
MetricStatsLong globalDistribution = underTest.globalStatistics().effort();
MetricStatsLong assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).effort();
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> {
assertThat(distribution.getOnCurrentAnalysis()).isEqualTo(expected);
assertThat(distribution.getOffCurrentAnalysis()).isZero();
assertThat(distribution.getTotal()).isEqualTo(expected);
});
}
@Test
public void add_sums_effort_off_current_analysis_globally_and_per_assignee() {
Random random = new Random();
List<Integer> efforts = IntStream.range(0, 1 + random.nextInt(10)).mapToObj(i -> 10_000 * i).toList();
int expected = efforts.stream().mapToInt(s -> s).sum();
String assignee = randomAlphanumeric(10);
efforts.stream()
.map(effort -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setEffort(Duration.create(effort)).setAssigneeUuid(assignee).setNew(false))
.forEach(underTest::add);
MetricStatsLong globalDistribution = underTest.globalStatistics().effort();
MetricStatsLong assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).effort();
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> {
assertThat(distribution.getOnCurrentAnalysis()).isZero();
assertThat(distribution.getOffCurrentAnalysis()).isEqualTo(expected);
assertThat(distribution.getTotal()).isEqualTo(expected);
});
}
@Test
public void add_does_not_sum_effort_if_null_neither_globally_nor_per_assignee() {
String assignee = randomAlphanumeric(10);
underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setEffort(null).setAssigneeUuid(assignee).setNew(new Random().nextBoolean()));
MetricStatsLong globalDistribution = underTest.globalStatistics().effort();
MetricStatsLong assigneeDistribution = underTest.getAssigneesStatistics().get(assignee).effort();
Stream.of(globalDistribution, assigneeDistribution)
.forEach(distribution -> assertThat(distribution.getTotal()).isZero());
}
@Test
public void do_not_have_issues_when_no_issue_added() {
assertThat(underTest.globalStatistics().hasIssues()).isFalse();
}
@Test
public void verify_toString() {
String componentUuid = randomAlphanumeric(2);
String tag = randomAlphanumeric(3);
String assignee = randomAlphanumeric(4);
int effort = 10 + new Random().nextInt(5);
RuleKey ruleKey = RuleKey.of(randomAlphanumeric(5), randomAlphanumeric(6));
underTest.add(new DefaultIssue()
.setType(randomRuleTypeExceptHotspot)
.setComponentUuid(componentUuid)
.setTags(ImmutableSet.of(tag))
.setAssigneeUuid(assignee)
.setRuleKey(ruleKey)
.setEffort(Duration.create(effort)));
assertThat(underTest.toString())
.isEqualTo("NewIssuesStatistics{" +
"assigneesStatistics={" + assignee + "=" +
"Stats{distributions={" +
"RULE_TYPE=DistributedMetricStatsInt{globalStats=MetricStatsInt{on=1, off=0}, " +
"statsPerLabel={" + randomRuleTypeExceptHotspot.name() + "=MetricStatsInt{on=1, off=0}}}, " +
"TAG=DistributedMetricStatsInt{globalStats=MetricStatsInt{on=1, off=0}, " +
"statsPerLabel={" + tag + "=MetricStatsInt{on=1, off=0}}}, " +
"COMPONENT=DistributedMetricStatsInt{globalStats=MetricStatsInt{on=1, off=0}, " +
"statsPerLabel={" + componentUuid + "=MetricStatsInt{on=1, off=0}}}, " +
"ASSIGNEE=DistributedMetricStatsInt{globalStats=MetricStatsInt{on=1, off=0}, " +
"statsPerLabel={" + assignee + "=MetricStatsInt{on=1, off=0}}}, " +
"RULE=DistributedMetricStatsInt{globalStats=MetricStatsInt{on=1, off=0}, " +
"statsPerLabel={" + ruleKey.toString() + "=MetricStatsInt{on=1, off=0}}}}, " +
"effortStats=MetricStatsLong{on=" + effort + ", off=0}}}, " +
"globalStatistics=Stats{distributions={" +
"RULE_TYPE=DistributedMetricStatsInt{globalStats=MetricStatsInt{on=1, off=0}, " +
"statsPerLabel={" + randomRuleTypeExceptHotspot.name() + "=MetricStatsInt{on=1, off=0}}}, " +
"TAG=DistributedMetricStatsInt{globalStats=MetricStatsInt{on=1, off=0}, " +
"statsPerLabel={" + tag + "=MetricStatsInt{on=1, off=0}}}, " +
"COMPONENT=DistributedMetricStatsInt{globalStats=MetricStatsInt{on=1, off=0}, " +
"statsPerLabel={" + componentUuid + "=MetricStatsInt{on=1, off=0}}}, " +
"ASSIGNEE=DistributedMetricStatsInt{globalStats=MetricStatsInt{on=1, off=0}, " +
"statsPerLabel={" + assignee + "=MetricStatsInt{on=1, off=0}}}, " +
"RULE=DistributedMetricStatsInt{globalStats=MetricStatsInt{on=1, off=0}, " +
"statsPerLabel={" + ruleKey.toString() + "=MetricStatsInt{on=1, off=0}}}}, " +
"effortStats=MetricStatsLong{on=" + effort + ", off=0}}}");
}
@CheckForNull
private Integer countDistributionTotal(Metric metric, String label) {
return underTest.globalStatistics()
.getDistributedMetricStats(metric)
.getForLabel(label)
.map(MetricStatsInt::getTotal)
.orElse(null);
}
private void assertStats(DistributedMetricStatsInt distribution, String label, int onCurrentAnalysis, int total) {
Optional<MetricStatsInt> statsOption = distribution.getForLabel(label);
assertThat(statsOption.isPresent()).describedAs("distribution for label %s not found", label).isTrue();
MetricStatsInt stats = statsOption.get();
assertThat(stats.getOnCurrentAnalysis()).isEqualTo(onCurrentAnalysis);
assertThat(stats.getTotal()).isEqualTo(total);
}
}
| 23,254 | 53.207459 | 169 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/HasResolutionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import org.junit.Test;
import org.sonar.api.issue.Issue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class HasResolutionTest {
Issue issue = mock(Issue.class);
@Test
public void should_match() {
HasResolution condition = new HasResolution(Issue.RESOLUTION_FIXED, Issue.RESOLUTION_FALSE_POSITIVE);
when(issue.resolution()).thenReturn("FIXED");
assertThat(condition.matches(issue)).isTrue();
when(issue.resolution()).thenReturn("FALSE-POSITIVE");
assertThat(condition.matches(issue)).isTrue();
when(issue.resolution()).thenReturn("Fixed");
assertThat(condition.matches(issue)).isFalse();
}
}
| 1,619 | 33.468085 | 105 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/IsBeingClosedTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import org.junit.Test;
import org.sonar.core.issue.DefaultIssue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.issue.workflow.IsBeingClosed.INSTANCE;
public class IsBeingClosedTest {
@Test
public void should_be_end_of_life() {
DefaultIssue issue = new DefaultIssue();
assertThat(INSTANCE.matches(issue.setBeingClosed(true))).isTrue();
assertThat(INSTANCE.matches(issue.setBeingClosed(false))).isFalse();
}
}
| 1,358 | 34.763158 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/IsUnResolvedTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import org.junit.Test;
import org.sonar.api.issue.Issue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class IsUnResolvedTest {
Issue issue = mock(Issue.class);
@Test
public void should_match() {
IsUnResolved condition = new IsUnResolved();
assertThat(condition.matches(issue)).isTrue();
when(issue.resolution()).thenReturn("FIXED");
assertThat(condition.matches(issue)).isFalse();
}
}
| 1,400 | 31.581395 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/IssueWorkflowForSecurityHotspotsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang.time.DateUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.RuleKey;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.FieldDiffs;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.server.issue.IssueFieldsSetter;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.issue.DefaultTransitions.RESET_AS_TO_REVIEW;
import static org.sonar.api.issue.DefaultTransitions.RESOLVE_AS_ACKNOWLEDGED;
import static org.sonar.api.issue.DefaultTransitions.RESOLVE_AS_REVIEWED;
import static org.sonar.api.issue.DefaultTransitions.RESOLVE_AS_SAFE;
import static org.sonar.api.issue.Issue.RESOLUTION_ACKNOWLEDGED;
import static org.sonar.api.issue.Issue.RESOLUTION_FIXED;
import static org.sonar.api.issue.Issue.RESOLUTION_REMOVED;
import static org.sonar.api.issue.Issue.RESOLUTION_SAFE;
import static org.sonar.api.issue.Issue.STATUS_CLOSED;
import static org.sonar.api.issue.Issue.STATUS_REVIEWED;
import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByScanBuilder;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByUserBuilder;
import static org.sonar.db.rule.RuleTesting.XOO_X1;
import static org.sonar.server.issue.workflow.IssueWorkflowTest.emptyIfNull;
@RunWith(DataProviderRunner.class)
public class IssueWorkflowForSecurityHotspotsTest {
private static final IssueChangeContext SOME_CHANGE_CONTEXT = issueChangeContextByUserBuilder(new Date(), "USER1").build();
private static final List<String> RESOLUTION_TYPES = List.of(RESOLUTION_FIXED, RESOLUTION_SAFE, RESOLUTION_ACKNOWLEDGED);
private final IssueFieldsSetter updater = new IssueFieldsSetter();
private final IssueWorkflow underTest = new IssueWorkflow(new FunctionExecutor(updater), updater);
@Test
@UseDataProvider("anyResolutionIncludingNone")
public void to_review_hotspot_with_any_resolution_can_be_resolved_as_safe_or_fixed(@Nullable String resolution) {
underTest.start();
DefaultIssue hotspot = newHotspot(STATUS_TO_REVIEW, resolution);
List<Transition> transitions = underTest.outTransitions(hotspot);
assertThat(keys(transitions)).containsExactlyInAnyOrder(RESOLVE_AS_REVIEWED, RESOLVE_AS_SAFE, RESOLVE_AS_ACKNOWLEDGED);
}
@DataProvider
public static Object[][] anyResolutionIncludingNone() {
return Stream.of(
Issue.RESOLUTIONS.stream(),
Issue.SECURITY_HOTSPOT_RESOLUTIONS.stream(),
Stream.of(randomAlphabetic(12), null))
.flatMap(t -> t)
.map(t -> new Object[] {t})
.toArray(Object[][]::new);
}
@Test
public void reviewed_as_fixed_hotspot_can_be_resolved_as_safe_or_put_back_to_review() {
underTest.start();
DefaultIssue hotspot = newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED);
List<Transition> transitions = underTest.outTransitions(hotspot);
assertThat(keys(transitions)).containsExactlyInAnyOrder(RESOLVE_AS_SAFE, RESET_AS_TO_REVIEW, RESOLVE_AS_ACKNOWLEDGED);
}
@Test
public void reviewed_as_safe_hotspot_can_be_resolved_as_fixed_or_put_back_to_review() {
underTest.start();
DefaultIssue hotspot = newHotspot(STATUS_REVIEWED, RESOLUTION_SAFE);
List<Transition> transitions = underTest.outTransitions(hotspot);
assertThat(keys(transitions)).containsExactlyInAnyOrder(RESOLVE_AS_REVIEWED, RESET_AS_TO_REVIEW, RESOLVE_AS_ACKNOWLEDGED);
}
@Test
@UseDataProvider("anyResolutionButSafeOrFixed")
public void reviewed_with_any_resolution_but_safe_or_fixed_can_not_be_changed(String resolution) {
underTest.start();
DefaultIssue hotspot = newHotspot(STATUS_REVIEWED, resolution);
List<Transition> transitions = underTest.outTransitions(hotspot);
assertThat(transitions).isEmpty();
}
@DataProvider
public static Object[][] anyResolutionButSafeOrFixed() {
return Stream.of(
Issue.RESOLUTIONS.stream(),
Issue.SECURITY_HOTSPOT_RESOLUTIONS.stream(),
Stream.of(randomAlphabetic(12)))
.flatMap(t -> t)
.filter(t -> !RESOLUTION_TYPES.contains(t))
.map(t -> new Object[] {t})
.toArray(Object[][]::new);
}
@Test
public void doManualTransition_to_review_hostpot_is_resolved_as_fixed() {
underTest.start();
DefaultIssue hotspot = newHotspot(STATUS_TO_REVIEW, null);
boolean result = underTest.doManualTransition(hotspot, RESOLVE_AS_REVIEWED, SOME_CHANGE_CONTEXT);
assertThat(result).isTrue();
assertThat(hotspot.getStatus()).isEqualTo(STATUS_REVIEWED);
assertThat(hotspot.resolution()).isEqualTo(RESOLUTION_FIXED);
}
@Test
public void doManualTransition_reviewed_as_safe_hostpot_is_resolved_as_fixed() {
underTest.start();
DefaultIssue hotspot = newHotspot(STATUS_REVIEWED, RESOLUTION_SAFE);
boolean result = underTest.doManualTransition(hotspot, RESOLVE_AS_REVIEWED, SOME_CHANGE_CONTEXT);
assertThat(result).isTrue();
assertThat(hotspot.getStatus()).isEqualTo(STATUS_REVIEWED);
assertThat(hotspot.resolution()).isEqualTo(RESOLUTION_FIXED);
}
@Test
public void doManualTransition_to_review_hostpot_is_resolved_as_safe() {
underTest.start();
DefaultIssue hotspot = newHotspot(STATUS_TO_REVIEW, null);
boolean result = underTest.doManualTransition(hotspot, RESOLVE_AS_SAFE, SOME_CHANGE_CONTEXT);
assertThat(result).isTrue();
assertThat(hotspot.getStatus()).isEqualTo(STATUS_REVIEWED);
assertThat(hotspot.resolution()).isEqualTo(RESOLUTION_SAFE);
}
@Test
public void doManualTransition_reviewed_as_fixed_hostpot_is_resolved_as_safe() {
underTest.start();
DefaultIssue hotspot = newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED);
boolean result = underTest.doManualTransition(hotspot, RESOLVE_AS_SAFE, SOME_CHANGE_CONTEXT);
assertThat(result).isTrue();
assertThat(hotspot.getStatus()).isEqualTo(STATUS_REVIEWED);
assertThat(hotspot.resolution()).isEqualTo(RESOLUTION_SAFE);
}
@Test
public void doManualTransition_reviewed_as_fixed_hostpot_is_put_back_to_review() {
underTest.start();
DefaultIssue hotspot = newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED);
boolean result = underTest.doManualTransition(hotspot, RESET_AS_TO_REVIEW, SOME_CHANGE_CONTEXT);
assertThat(result).isTrue();
assertThat(hotspot.getStatus()).isEqualTo(STATUS_TO_REVIEW);
assertThat(hotspot.resolution()).isNull();
}
@Test
public void doManualTransition_reviewed_as_safe_hostpot_is_put_back_to_review() {
underTest.start();
DefaultIssue hotspot = newHotspot(STATUS_REVIEWED, RESOLUTION_SAFE);
boolean result = underTest.doManualTransition(hotspot, RESET_AS_TO_REVIEW, SOME_CHANGE_CONTEXT);
assertThat(result).isTrue();
assertThat(hotspot.getStatus()).isEqualTo(STATUS_TO_REVIEW);
assertThat(hotspot.resolution()).isNull();
}
@Test
public void reset_as_to_review_from_reviewed() {
underTest.start();
DefaultIssue hotspot = newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED);
boolean result = underTest.doManualTransition(hotspot, RESET_AS_TO_REVIEW, SOME_CHANGE_CONTEXT);
assertThat(result).isTrue();
assertThat(hotspot.type()).isEqualTo(SECURITY_HOTSPOT);
assertThat(hotspot.getStatus()).isEqualTo(STATUS_TO_REVIEW);
assertThat(hotspot.resolution()).isNull();
}
@Test
public void automatically_close_resolved_security_hotspots_in_status_to_review() {
underTest.start();
DefaultIssue hotspot = newHotspot(STATUS_TO_REVIEW, null)
.setNew(false)
.setBeingClosed(true);
Date now = new Date();
underTest.doAutomaticTransition(hotspot, issueChangeContextByScanBuilder(now).build());
assertThat(hotspot.resolution()).isEqualTo(RESOLUTION_FIXED);
assertThat(hotspot.status()).isEqualTo(STATUS_CLOSED);
assertThat(hotspot.closeDate()).isNotNull();
assertThat(hotspot.updateDate()).isEqualTo(DateUtils.truncate(now, Calendar.SECOND));
}
@Test
@UseDataProvider("safeOrFixedResolutions")
public void automatically_close_hotspot_resolved_as_fixed_or_safe(String resolution) {
underTest.start();
DefaultIssue hotspot = newHotspot(STATUS_REVIEWED, resolution)
.setNew(false)
.setBeingClosed(true);
Date now = new Date();
underTest.doAutomaticTransition(hotspot, issueChangeContextByScanBuilder(now).build());
assertThat(hotspot.resolution()).isEqualTo(RESOLUTION_FIXED);
assertThat(hotspot.status()).isEqualTo(STATUS_CLOSED);
assertThat(hotspot.closeDate()).isNotNull();
assertThat(hotspot.updateDate()).isEqualTo(DateUtils.truncate(now, Calendar.SECOND));
}
@DataProvider
public static Object[][] safeOrFixedResolutions() {
return new Object[][] {
{RESOLUTION_SAFE},
{RESOLUTION_FIXED}
};
}
@Test
public void automatically_reopen_closed_security_hotspots() {
DefaultIssue hotspot1 = newClosedHotspot(RESOLUTION_REMOVED);
setStatusPreviousToClosed(hotspot1, STATUS_REVIEWED, RESOLUTION_SAFE, RESOLUTION_REMOVED);
DefaultIssue hotspot2 = newClosedHotspot(RESOLUTION_FIXED);
setStatusPreviousToClosed(hotspot2, STATUS_TO_REVIEW, null, RESOLUTION_FIXED);
Date now = new Date();
underTest.start();
underTest.doAutomaticTransition(hotspot1, issueChangeContextByScanBuilder(now).build());
underTest.doAutomaticTransition(hotspot2, issueChangeContextByScanBuilder(now).build());
assertThat(hotspot1.updateDate()).isNotNull();
assertThat(hotspot1.status()).isEqualTo(STATUS_REVIEWED);
assertThat(hotspot1.resolution()).isEqualTo(RESOLUTION_SAFE);
assertThat(hotspot2.updateDate()).isNotNull();
assertThat(hotspot2.status()).isEqualTo(STATUS_TO_REVIEW);
assertThat(hotspot2.resolution()).isNull();
}
@Test
public void doAutomaticTransition_does_nothing_on_security_hotspots_in_to_review_status() {
DefaultIssue hotspot = newHotspot(STATUS_TO_REVIEW, null)
.setKey("ABCDE")
.setRuleKey(XOO_X1);
underTest.start();
underTest.doAutomaticTransition(hotspot, issueChangeContextByScanBuilder(new Date()).build());
assertThat(hotspot.status()).isEqualTo(STATUS_TO_REVIEW);
assertThat(hotspot.resolution()).isNull();
}
private Collection<String> keys(List<Transition> transitions) {
return transitions.stream().map(Transition::key).toList();
}
private static void setStatusPreviousToClosed(DefaultIssue hotspot, String previousStatus, @Nullable String previousResolution, @Nullable String newResolution) {
addStatusChange(hotspot, new Date(), previousStatus, STATUS_CLOSED, previousResolution, newResolution);
}
private static void addStatusChange(DefaultIssue issue, Date date, String previousStatus, String newStatus, @Nullable String previousResolution, @Nullable String newResolution) {
issue.addChange(new FieldDiffs()
.setCreationDate(date)
.setDiff("status", previousStatus, newStatus)
.setDiff("resolution", emptyIfNull(previousResolution), emptyIfNull(newResolution)));
}
private static DefaultIssue newClosedHotspot(String resolution) {
return newHotspot(STATUS_CLOSED, resolution)
.setKey("ABCDE")
.setRuleKey(RuleKey.of("js", "S001"))
.setNew(false)
.setCloseDate(new Date(5_999_999L));
}
private static DefaultIssue newHotspot(String status, @Nullable String resolution) {
return new DefaultIssue()
.setType(SECURITY_HOTSPOT)
.setStatus(status)
.setResolution(resolution);
}
}
| 12,898 | 38.811728 | 180 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/IssueWorkflowTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import com.google.common.collect.Collections2;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.annotation.Nullable;
import org.apache.commons.lang.time.DateUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.issue.DefaultTransitions;
import org.sonar.api.rule.RuleKey;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.FieldDiffs;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.server.issue.IssueFieldsSetter;
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang.time.DateUtils.addDays;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
import static org.sonar.api.issue.Issue.RESOLUTION_FALSE_POSITIVE;
import static org.sonar.api.issue.Issue.RESOLUTION_FIXED;
import static org.sonar.api.issue.Issue.RESOLUTION_REMOVED;
import static org.sonar.api.issue.Issue.RESOLUTION_WONT_FIX;
import static org.sonar.api.issue.Issue.STATUS_CLOSED;
import static org.sonar.api.issue.Issue.STATUS_CONFIRMED;
import static org.sonar.api.issue.Issue.STATUS_OPEN;
import static org.sonar.api.issue.Issue.STATUS_REOPENED;
import static org.sonar.api.issue.Issue.STATUS_RESOLVED;
import static org.sonar.api.issue.Issue.STATUS_REVIEWED;
import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByScanBuilder;
@RunWith(DataProviderRunner.class)
public class IssueWorkflowTest {
private IssueFieldsSetter updater = new IssueFieldsSetter();
private IssueWorkflow underTest = new IssueWorkflow(new FunctionExecutor(updater), updater);
@Test
public void list_statuses() {
underTest.start();
List<String> expectedStatus = new ArrayList<>();
// issues statuses
expectedStatus.addAll(Arrays.asList(STATUS_OPEN, STATUS_CONFIRMED, STATUS_REOPENED, STATUS_RESOLVED, STATUS_CLOSED));
// hostpots statuses
expectedStatus.addAll(Arrays.asList(STATUS_TO_REVIEW, STATUS_REVIEWED));
assertThat(underTest.statusKeys()).containsExactlyInAnyOrder(expectedStatus.toArray(new String[]{}));
}
@Test
public void list_out_transitions_from_status_open() {
underTest.start();
DefaultIssue issue = new DefaultIssue().setStatus(STATUS_OPEN);
List<Transition> transitions = underTest.outTransitions(issue);
assertThat(keys(transitions)).containsOnly("confirm", "falsepositive", "resolve", "wontfix");
}
@Test
public void list_out_transitions_from_status_confirmed() {
underTest.start();
DefaultIssue issue = new DefaultIssue().setStatus(STATUS_CONFIRMED);
List<Transition> transitions = underTest.outTransitions(issue);
assertThat(keys(transitions)).containsOnly("unconfirm", "falsepositive", "resolve", "wontfix");
}
@Test
public void list_out_transitions_from_status_resolved() {
underTest.start();
DefaultIssue issue = new DefaultIssue().setStatus(STATUS_RESOLVED);
List<Transition> transitions = underTest.outTransitions(issue);
assertThat(keys(transitions)).containsOnly("reopen");
}
@Test
public void list_out_transitions_from_status_reopen() {
underTest.start();
DefaultIssue issue = new DefaultIssue().setStatus(STATUS_REOPENED);
List<Transition> transitions = underTest.outTransitions(issue);
assertThat(keys(transitions)).containsOnly("confirm", "resolve", "falsepositive", "wontfix");
}
@Test
public void list_no_out_transition_from_status_closed() {
underTest.start();
DefaultIssue issue = new DefaultIssue().setStatus(STATUS_CLOSED).setRuleKey(RuleKey.of("java", "R1 "));
List<Transition> transitions = underTest.outTransitions(issue);
assertThat(transitions).isEmpty();
}
@Test
public void fail_if_unknown_status_when_listing_transitions() {
underTest.start();
DefaultIssue issue = new DefaultIssue().setStatus("xxx");
try {
underTest.outTransitions(issue);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Unknown status: xxx");
}
}
@Test
public void automatically_close_resolved_issue() {
underTest.start();
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
.setRuleKey(RuleKey.of("js", "S001"))
.setResolution(RESOLUTION_FIXED)
.setStatus(STATUS_RESOLVED)
.setNew(false)
.setBeingClosed(true);
Date now = new Date();
underTest.doAutomaticTransition(issue, issueChangeContextByScanBuilder(now).build());
assertThat(issue.resolution()).isEqualTo(RESOLUTION_FIXED);
assertThat(issue.status()).isEqualTo(STATUS_CLOSED);
assertThat(issue.closeDate()).isNotNull();
assertThat(issue.updateDate()).isEqualTo(DateUtils.truncate(now, Calendar.SECOND));
}
@Test
@UseDataProvider("allStatusesLeadingToClosed")
public void automatically_reopen_closed_issue_to_its_previous_status_from_changelog(String previousStatus) {
DefaultIssue[] issues = Arrays.stream(SUPPORTED_RESOLUTIONS_FOR_UNCLOSING)
.map(resolution -> {
DefaultIssue issue = newClosedIssue(resolution);
setStatusPreviousToClosed(issue, previousStatus);
return issue;
})
.toArray(DefaultIssue[]::new);
Date now = new Date();
underTest.start();
Arrays.stream(issues).forEach(issue -> {
underTest.doAutomaticTransition(issue, issueChangeContextByScanBuilder(now).build());
assertThat(issue.status()).isEqualTo(previousStatus);
assertThat(issue.updateDate()).isEqualTo(DateUtils.truncate(now, Calendar.SECOND));
assertThat(issue.closeDate()).isNull();
assertThat(issue.isChanged()).isTrue();
});
}
@Test
@UseDataProvider("allStatusesLeadingToClosed")
public void automatically_reopen_closed_issue_to_most_recent_previous_status_from_changelog(String previousStatus) {
DefaultIssue[] issues = Arrays.stream(SUPPORTED_RESOLUTIONS_FOR_UNCLOSING)
.map(resolution -> {
DefaultIssue issue = newClosedIssue(resolution);
Date now = new Date();
addStatusChange(issue, addDays(now, -60), STATUS_OPEN, STATUS_CONFIRMED);
addStatusChange(issue, addDays(now, -10), STATUS_CONFIRMED, previousStatus);
setStatusPreviousToClosed(issue, previousStatus);
return issue;
})
.toArray(DefaultIssue[]::new);
Date now = new Date();
underTest.start();
Arrays.stream(issues).forEach(issue -> {
underTest.doAutomaticTransition(issue, issueChangeContextByScanBuilder(now).build());
assertThat(issue.status()).isEqualTo(previousStatus);
assertThat(issue.updateDate()).isEqualTo(DateUtils.truncate(now, Calendar.SECOND));
assertThat(issue.closeDate()).isNull();
assertThat(issue.isChanged()).isTrue();
});
}
@Test
@UseDataProvider("allResolutionsBeforeClosing")
public void automatically_reopen_closed_issue_to_previous_resolution_from_changelog(String resolutionBeforeClosed) {
String randomPreviousStatus = ALL_STATUSES_LEADING_TO_CLOSED[new Random().nextInt(ALL_STATUSES_LEADING_TO_CLOSED.length)];
DefaultIssue[] issues = Arrays.stream(SUPPORTED_RESOLUTIONS_FOR_UNCLOSING)
.map(resolution -> {
DefaultIssue issue = newClosedIssue(resolution);
addResolutionAndStatusChange(issue, new Date(), randomPreviousStatus, STATUS_CLOSED, resolutionBeforeClosed, resolution);
return issue;
})
.toArray(DefaultIssue[]::new);
Date now = new Date();
underTest.start();
Arrays.stream(issues).forEach(issue -> {
underTest.doAutomaticTransition(issue, issueChangeContextByScanBuilder(now).build());
assertThat(issue.status()).isEqualTo(randomPreviousStatus);
assertThat(issue.resolution()).isEqualTo(resolutionBeforeClosed);
assertThat(issue.updateDate()).isEqualTo(DateUtils.truncate(now, Calendar.SECOND));
assertThat(issue.closeDate()).isNull();
assertThat(issue.isChanged()).isTrue();
});
}
@Test
public void automatically_reopen_closed_issue_to_no_resolution_if_no_previous_one_changelog() {
String randomPreviousStatus = ALL_STATUSES_LEADING_TO_CLOSED[new Random().nextInt(ALL_STATUSES_LEADING_TO_CLOSED.length)];
DefaultIssue[] issues = Arrays.stream(SUPPORTED_RESOLUTIONS_FOR_UNCLOSING)
.map(resolution -> {
DefaultIssue issue = newClosedIssue(resolution);
setStatusPreviousToClosed(issue, randomPreviousStatus);
return issue;
})
.toArray(DefaultIssue[]::new);
Date now = new Date();
underTest.start();
Arrays.stream(issues).forEach(issue -> {
underTest.doAutomaticTransition(issue, issueChangeContextByScanBuilder(now).build());
assertThat(issue.status()).isEqualTo(randomPreviousStatus);
assertThat(issue.resolution()).isNull();
assertThat(issue.updateDate()).isEqualTo(DateUtils.truncate(now, Calendar.SECOND));
assertThat(issue.closeDate()).isNull();
assertThat(issue.isChanged()).isTrue();
});
}
@Test
@UseDataProvider("allResolutionsBeforeClosing")
public void automatically_reopen_closed_issue_to_previous_resolution_of_closing_the_issue_if_most_recent_of_all_resolution_changes(String resolutionBeforeClosed) {
String randomPreviousStatus = ALL_STATUSES_LEADING_TO_CLOSED[new Random().nextInt(ALL_STATUSES_LEADING_TO_CLOSED.length)];
DefaultIssue[] issues = Arrays.stream(SUPPORTED_RESOLUTIONS_FOR_UNCLOSING)
.map(resolution -> {
DefaultIssue issue = newClosedIssue(resolution);
Date now = new Date();
addResolutionChange(issue, addDays(now, -60), null, RESOLUTION_FALSE_POSITIVE);
addResolutionChange(issue, addDays(now, -10), RESOLUTION_FALSE_POSITIVE, resolutionBeforeClosed);
addResolutionAndStatusChange(issue, now, randomPreviousStatus, STATUS_CLOSED, resolutionBeforeClosed, resolution);
return issue;
})
.toArray(DefaultIssue[]::new);
Date now = new Date();
underTest.start();
Arrays.stream(issues).forEach(issue -> {
underTest.doAutomaticTransition(issue, issueChangeContextByScanBuilder(now).build());
assertThat(issue.status()).isEqualTo(randomPreviousStatus);
assertThat(issue.resolution()).isEqualTo(resolutionBeforeClosed);
assertThat(issue.updateDate()).isEqualTo(DateUtils.truncate(now, Calendar.SECOND));
assertThat(issue.closeDate()).isNull();
assertThat(issue.isChanged()).isTrue();
});
}
@DataProvider
public static Object[][] allResolutionsBeforeClosing() {
return Arrays.stream(ALL_RESOLUTIONS_BEFORE_CLOSING)
.map(t -> new Object[] {t})
.toArray(Object[][]::new);
}
@Test
public void do_not_automatically_reopen_closed_issue_which_have_no_previous_status_in_changelog() {
DefaultIssue[] issues = Arrays.stream(SUPPORTED_RESOLUTIONS_FOR_UNCLOSING)
.map(IssueWorkflowTest::newClosedIssue)
.toArray(DefaultIssue[]::new);
Date now = new Date();
underTest.start();
Arrays.stream(issues).forEach(issue -> {
underTest.doAutomaticTransition(issue, issueChangeContextByScanBuilder(now).build());
assertThat(issue.status()).isEqualTo(STATUS_CLOSED);
assertThat(issue.updateDate()).isNull();
});
}
private static final String[] ALL_STATUSES_LEADING_TO_CLOSED = new String[] {STATUS_OPEN, STATUS_REOPENED, STATUS_CONFIRMED, STATUS_RESOLVED};
private static final String[] ALL_RESOLUTIONS_BEFORE_CLOSING = new String[] {
null,
RESOLUTION_FIXED,
RESOLUTION_WONT_FIX,
RESOLUTION_FALSE_POSITIVE
};
private static final String[] SUPPORTED_RESOLUTIONS_FOR_UNCLOSING = new String[] {RESOLUTION_FIXED, RESOLUTION_REMOVED};
@DataProvider
public static Object[][] allStatusesLeadingToClosed() {
return Arrays.stream(ALL_STATUSES_LEADING_TO_CLOSED)
.map(t -> new Object[] {t})
.toArray(Object[][]::new);
}
@Test
public void close_open_dead_issue() {
underTest.start();
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
.setResolution(null)
.setStatus(STATUS_OPEN)
.setNew(false)
.setBeingClosed(true);
Date now = new Date();
underTest.doAutomaticTransition(issue, issueChangeContextByScanBuilder(now).build());
assertThat(issue.resolution()).isEqualTo(RESOLUTION_FIXED);
assertThat(issue.status()).isEqualTo(STATUS_CLOSED);
assertThat(issue.closeDate()).isNotNull();
assertThat(issue.updateDate()).isEqualTo(DateUtils.truncate(now, Calendar.SECOND));
}
@Test
public void close_reopened_dead_issue() {
underTest.start();
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
.setResolution(null)
.setStatus(STATUS_REOPENED)
.setNew(false)
.setBeingClosed(true);
Date now = new Date();
underTest.doAutomaticTransition(issue, issueChangeContextByScanBuilder(now).build());
assertThat(issue.resolution()).isEqualTo(RESOLUTION_FIXED);
assertThat(issue.status()).isEqualTo(STATUS_CLOSED);
assertThat(issue.closeDate()).isNotNull();
assertThat(issue.updateDate()).isEqualTo(DateUtils.truncate(now, Calendar.SECOND));
}
@Test
public void close_confirmed_dead_issue() {
underTest.start();
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
.setResolution(null)
.setStatus(STATUS_CONFIRMED)
.setNew(false)
.setBeingClosed(true);
Date now = new Date();
underTest.doAutomaticTransition(issue, issueChangeContextByScanBuilder(now).build());
assertThat(issue.resolution()).isEqualTo(RESOLUTION_FIXED);
assertThat(issue.status()).isEqualTo(STATUS_CLOSED);
assertThat(issue.closeDate()).isNotNull();
assertThat(issue.updateDate()).isEqualTo(DateUtils.truncate(now, Calendar.SECOND));
}
@Test
public void fail_if_unknown_status_on_automatic_trans() {
underTest.start();
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
.setResolution(RESOLUTION_FIXED)
.setStatus("xxx")
.setNew(false)
.setBeingClosed(true);
IssueChangeContext issueChangeContext = issueChangeContextByScanBuilder(new Date()).build();
assertThatThrownBy(() -> underTest.doAutomaticTransition(issue, issueChangeContext))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Unknown status: xxx [issue=ABCDE]");
}
@Test
public void flag_as_false_positive() {
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
.setStatus(STATUS_OPEN)
.setRuleKey(RuleKey.of("java", "AvoidCycle"))
.setAssigneeUuid("morgan");
underTest.start();
underTest.doManualTransition(issue, DefaultTransitions.FALSE_POSITIVE, issueChangeContextByScanBuilder(new Date()).build());
assertThat(issue.resolution()).isEqualTo(RESOLUTION_FALSE_POSITIVE);
assertThat(issue.status()).isEqualTo(STATUS_RESOLVED);
// should remove assignee
assertThat(issue.assignee()).isNull();
}
@Test
public void wont_fix() {
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
.setStatus(STATUS_OPEN)
.setRuleKey(RuleKey.of("java", "AvoidCycle"))
.setAssigneeUuid("morgan");
underTest.start();
underTest.doManualTransition(issue, DefaultTransitions.WONT_FIX, issueChangeContextByScanBuilder(new Date()).build());
assertThat(issue.resolution()).isEqualTo(RESOLUTION_WONT_FIX);
assertThat(issue.status()).isEqualTo(STATUS_RESOLVED);
// should remove assignee
assertThat(issue.assignee()).isNull();
}
private static DefaultIssue newClosedIssue(String resolution) {
return new DefaultIssue()
.setKey("ABCDE")
.setRuleKey(RuleKey.of("js", "S001"))
.setResolution(resolution)
.setStatus(STATUS_CLOSED)
.setNew(false)
.setCloseDate(new Date(5_999_999L));
}
private static void setStatusPreviousToClosed(DefaultIssue issue, String previousStatus) {
addStatusChange(issue, new Date(), previousStatus, STATUS_CLOSED);
}
private static void addStatusChange(DefaultIssue issue, Date date, String previousStatus, String newStatus) {
issue.addChange(new FieldDiffs().setCreationDate(date).setDiff("status", previousStatus, newStatus));
}
private void addResolutionChange(DefaultIssue issue, Date creationDate,
@Nullable String previousResolution, @Nullable String newResolution) {
checkArgument(previousResolution != null || newResolution != null, "At least one resolution must be non null");
FieldDiffs fieldDiffs = new FieldDiffs().setCreationDate(creationDate)
.setDiff("resolution", emptyIfNull(previousResolution), emptyIfNull(newResolution));
issue.addChange(fieldDiffs);
}
private void addResolutionAndStatusChange(DefaultIssue issue, Date creationDate,
String previousStatus, String newStatus,
@Nullable String previousResolution, @Nullable String newResolution) {
checkArgument(previousResolution != null || newResolution != null, "At least one resolution must be non null");
FieldDiffs fieldDiffs = new FieldDiffs().setCreationDate(creationDate)
.setDiff("status", previousStatus, newStatus)
.setDiff("resolution", emptyIfNull(previousResolution), emptyIfNull(newResolution));
issue.addChange(fieldDiffs);
}
static String emptyIfNull(@Nullable String newResolution) {
return newResolution == null ? "" : newResolution;
}
private Collection<String> keys(List<Transition> transitions) {
return Collections2.transform(transitions, Transition::key);
}
}
| 18,772 | 38.274059 | 165 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/NotConditionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.api.issue.Issue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class NotConditionTest {
Condition target = Mockito.mock(Condition.class);
Issue issue = mock(Issue.class);
@Test
public void should_match_opposite() {
NotCondition condition = new NotCondition(target);
when(target.matches(any(Issue.class))).thenReturn(true);
assertThat(condition.matches(issue)).isFalse();
when(target.matches(any(Issue.class))).thenReturn(false);
assertThat(condition.matches(issue)).isTrue();
}
}
| 1,616 | 33.404255 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/SetCloseDateTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class SetCloseDateTest {
@Test
public void should_set_close_date() {
SetCloseDate function = SetCloseDate.INSTANCE;
Function.Context context = mock(Function.Context.class);
function.execute(context);
verify(context, times(1)).setCloseDate();
}
}
| 1,308 | 34.378378 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/SetClosedTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import org.junit.Test;
import org.sonar.api.issue.Issue;
import org.sonar.core.issue.DefaultIssue;
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.server.issue.workflow.SetClosed.INSTANCE;
public class SetClosedTest {
private Function.Context context = mock(Function.Context.class);
@Test
public void should_resolve_as_fixed() {
Issue issue = new DefaultIssue().setBeingClosed(true).setOnDisabledRule(false);
when(context.issue()).thenReturn(issue);
INSTANCE.execute(context);
verify(context, times(1)).setResolution(Issue.RESOLUTION_FIXED);
}
@Test
public void should_resolve_as_removed_when_rule_is_disabled() {
Issue issue = new DefaultIssue().setBeingClosed(true).setOnDisabledRule(true);
when(context.issue()).thenReturn(issue);
INSTANCE.execute(context);
verify(context, times(1)).setResolution(Issue.RESOLUTION_REMOVED);
}
@Test
public void line_number_must_be_unset() {
Issue issue = new DefaultIssue().setBeingClosed(true).setLine(10);
when(context.issue()).thenReturn(issue);
INSTANCE.execute(context);
verify(context).unsetLine();
}
}
| 2,144 | 34.75 | 83 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/SetResolutionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class SetResolutionTest {
@Test
public void execute() {
SetResolution function = new SetResolution("FIXED");
Function.Context context = mock(Function.Context.class);
function.execute(context);
verify(context, times(1)).setResolution("FIXED");
}
}
| 1,309 | 34.405405 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/StateMachineTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StateMachineTest {
@Test
public void keep_order_of_state_keys() {
StateMachine machine = StateMachine.builder().states("OPEN", "RESOLVED", "CLOSED").build();
assertThat(machine.stateKeys()).containsSubsequence("OPEN", "RESOLVED", "CLOSED");
}
@Test
public void stateKey() {
StateMachine machine = StateMachine.builder()
.states("OPEN", "RESOLVED", "CLOSED")
.transition(Transition.builder("resolve").from("OPEN").to("RESOLVED").build())
.build();
assertThat(machine.state("OPEN")).isNotNull();
assertThat(machine.state("OPEN").transition("resolve")).isNotNull();
}
}
| 1,601 | 34.6 | 95 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/StateTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class StateTest {
private Transition t1 = Transition.builder("close").from("OPEN").to("CLOSED").build();
@Test
public void key_should_be_set() {
assertThatThrownBy(() -> new State("", new Transition[0]))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("State key must be set");
}
@Test
public void no_duplicated_out_transitions() {
assertThatThrownBy(() -> new State("CLOSE", new Transition[] {t1, t1}))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Transition 'close' is declared several times from the originating state 'CLOSE'");
}
@Test
public void fail_when_transition_is_unknown() {
State state = new State("VALIDATED", new Transition[0]);
assertThatThrownBy(() -> state.transition("Unknown Transition"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Transition from state VALIDATED does not exist: Unknown Transition");
}
}
| 1,928 | 34.722222 | 101 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/TransitionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import org.junit.Test;
import org.sonar.api.web.UserRole;
import org.sonar.core.issue.DefaultIssue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TransitionTest {
Condition condition1 = mock(Condition.class);
Condition condition2 = mock(Condition.class);
Function function1 = mock(Function.class);
Function function2 = mock(Function.class);
@Test
public void test_builder() {
Transition transition = Transition.builder("close")
.from("OPEN").to("CLOSED")
.conditions(condition1, condition2)
.functions(function1, function2)
.requiredProjectPermission(UserRole.ISSUE_ADMIN)
.build();
assertThat(transition.key()).isEqualTo("close");
assertThat(transition.from()).isEqualTo("OPEN");
assertThat(transition.to()).isEqualTo("CLOSED");
assertThat(transition.conditions()).containsOnly(condition1, condition2);
assertThat(transition.functions()).containsOnly(function1, function2);
assertThat(transition.automatic()).isFalse();
assertThat(transition.requiredProjectPermission()).isEqualTo(UserRole.ISSUE_ADMIN);
}
@Test
public void test_simplest_transition() {
Transition transition = Transition.builder("close")
.from("OPEN").to("CLOSED")
.build();
assertThat(transition.key()).isEqualTo("close");
assertThat(transition.from()).isEqualTo("OPEN");
assertThat(transition.to()).isEqualTo("CLOSED");
assertThat(transition.conditions()).isEmpty();
assertThat(transition.functions()).isEmpty();
assertThat(transition.requiredProjectPermission()).isNull();
}
@Test
public void key_should_be_set() {
try {
Transition.builder("").from("OPEN").to("CLOSED").build();
fail();
} catch (Exception e) {
assertThat(e).hasMessage("Transition key must be set");
}
}
@Test
public void key_should_be_lower_case() {
try {
Transition.builder("CLOSE").from("OPEN").to("CLOSED").build();
fail();
} catch (Exception e) {
assertThat(e).hasMessage("Transition key must be lower-case");
}
}
@Test
public void originating_status_should_be_set() {
try {
Transition.builder("close").from("").to("CLOSED").build();
fail();
} catch (Exception e) {
assertThat(e).hasMessage("Originating status must be set");
}
}
@Test
public void destination_status_should_be_set() {
try {
Transition.builder("close").from("OPEN").to("").build();
fail();
} catch (Exception e) {
assertThat(e).hasMessage("Destination status must be set");
}
}
@Test
public void should_verify_conditions() {
DefaultIssue issue = new DefaultIssue();
Transition transition = Transition.builder("close")
.from("OPEN").to("CLOSED")
.conditions(condition1, condition2)
.build();
when(condition1.matches(issue)).thenReturn(true);
when(condition2.matches(issue)).thenReturn(false);
assertThat(transition.supports(issue)).isFalse();
when(condition1.matches(issue)).thenReturn(true);
when(condition2.matches(issue)).thenReturn(true);
assertThat(transition.supports(issue)).isTrue();
}
@Test
public void test_equals_and_hashCode() {
Transition t1 = Transition.create("resolve", "OPEN", "RESOLVED");
Transition t2 = Transition.create("resolve", "REOPENED", "RESOLVED");
Transition t3 = Transition.create("confirm", "OPEN", "CONFIRMED");
assertThat(t1)
.isNotEqualTo(t2)
.isNotEqualTo(t3)
.isEqualTo(t1)
.hasSameHashCodeAs(t1);
}
@Test
public void test_toString() {
Transition t1 = Transition.create("resolve", "OPEN", "RESOLVED");
assertThat(t1).hasToString("OPEN->resolve->RESOLVED");
}
@Test
public void test_automatic_transition() {
Transition transition = Transition.builder("close")
.from("OPEN").to("CLOSED")
.automatic()
.build();
assertThat(transition.automatic()).isTrue();
}
}
| 4,959 | 31.418301 | 87 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/UnsetAssigneeTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.sonar.server.issue.workflow.UnsetAssignee.INSTANCE;
public class UnsetAssigneeTest {
@Test
public void unassign() {
Function.Context context = mock(Function.Context.class);
INSTANCE.execute(context);
verify(context, times(1)).setAssignee(null);
}
}
| 1,319 | 33.736842 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/UnsetCloseDateTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.workflow;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class UnsetCloseDateTest {
@Test
public void should_unset_close_date() {
UnsetCloseDate function = UnsetCloseDate.INSTANCE;
Function.Context context = mock(Function.Context.class);
function.execute(context);
verify(context, times(1)).unsetCloseDate();
}
}
| 1,319 | 33.736842 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/l18n/ServerI18nTest.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.l18n;
import java.util.List;
import java.util.Locale;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.core.extension.CoreExtension;
import org.sonar.core.extension.CoreExtensionRepository;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ServerI18nTest {
private TestSystem2 system2 = new TestSystem2();
private ServerI18n underTest;
@Before
public void before() {
PluginRepository pluginRepository = mock(PluginRepository.class);
List<PluginInfo> plugins = singletonList(newPlugin("checkstyle"));
when(pluginRepository.getPluginInfos()).thenReturn(plugins);
CoreExtensionRepository coreExtensionRepository = mock(CoreExtensionRepository.class);
Stream<CoreExtension> coreExtensions = Stream.of(newCoreExtension("coreext"), newCoreExtension("othercorext"));
when(coreExtensionRepository.loadedCoreExtensions()).thenReturn(coreExtensions);
underTest = new ServerI18n(pluginRepository, system2, coreExtensionRepository);
underTest.doStart(getClass().getClassLoader());
}
@Test
public void get_english_labels() {
assertThat(underTest.message(Locale.ENGLISH, "any", null)).isEqualTo("Any");
assertThat(underTest.message(Locale.ENGLISH, "coreext.rule1.name", null)).isEqualTo("Rule one");
}
@Test
public void get_english_labels_when_default_locale_is_not_english() {
Locale defaultLocale = Locale.getDefault();
try {
Locale.setDefault(Locale.FRENCH);
assertThat(underTest.message(Locale.ENGLISH, "any", null)).isEqualTo("Any");
assertThat(underTest.message(Locale.ENGLISH, "coreext.rule1.name", null)).isEqualTo("Rule one");
} finally {
Locale.setDefault(defaultLocale);
}
}
@Test
public void get_labels_from_french_pack() {
assertThat(underTest.message(Locale.FRENCH, "coreext.rule1.name", null)).isEqualTo("Rule un");
assertThat(underTest.message(Locale.FRENCH, "any", null)).isEqualTo("Tous");
}
private static PluginInfo newPlugin(String key) {
PluginInfo plugin = mock(PluginInfo.class);
when(plugin.getKey()).thenReturn(key);
return plugin;
}
private static CoreExtension newCoreExtension(String name) {
CoreExtension res = mock(CoreExtension.class);
when(res.getName()).thenReturn(name);
return res;
}
}
| 3,474 | 35.968085 | 115 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/log/ServerLoggingTest.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.log;
import ch.qos.logback.classic.Level;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.io.File;
import java.io.IOException;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.db.Database;
import org.sonar.process.logging.LogLevelConfig;
import org.sonar.process.logging.LogbackHelper;
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.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.api.utils.log.LoggerLevel.DEBUG;
import static org.sonar.api.utils.log.LoggerLevel.ERROR;
import static org.sonar.api.utils.log.LoggerLevel.INFO;
import static org.sonar.api.utils.log.LoggerLevel.TRACE;
import static org.sonar.api.utils.log.LoggerLevel.WARN;
import static org.sonar.process.ProcessProperties.Property.PATH_LOGS;
@RunWith(DataProviderRunner.class)
public class ServerLoggingTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private final String rootLoggerName = RandomStringUtils.randomAlphabetic(20);
private LogbackHelper logbackHelper = spy(new LogbackHelper());
private MapSettings settings = new MapSettings();
private final ServerProcessLogging serverProcessLogging = mock(ServerProcessLogging.class);
private final Database database = mock(Database.class);
private ServerLogging underTest = new ServerLogging(logbackHelper, settings.asConfig(), serverProcessLogging, database);
@Rule
public LogTester logTester = new LogTester();
@Test
public void getLogsDir() throws IOException {
File dir = temp.newFolder();
settings.setProperty(PATH_LOGS.getKey(), dir.getAbsolutePath());
assertThat(underTest.getLogsDir()).isEqualTo(dir);
}
@Test
public void getRootLoggerLevel() {
logTester.setLevel(TRACE);
assertThat(underTest.getRootLoggerLevel()).isEqualTo(TRACE);
}
@Test
@UseDataProvider("supportedSonarApiLevels")
public void changeLevel_calls_changeRoot_with_LogLevelConfig_and_level_converted_to_logback_class_then_log_INFO_message(LoggerLevel level) {
LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(rootLoggerName).build();
when(serverProcessLogging.getLogLevelConfig()).thenReturn(logLevelConfig);
underTest.changeLevel(level);
verify(logbackHelper).changeRoot(logLevelConfig, Level.valueOf(level.name()));
}
@Test
public void changeLevel_to_trace_enables_db_logging() {
LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(rootLoggerName).build();
when(serverProcessLogging.getLogLevelConfig()).thenReturn(logLevelConfig);
reset(database);
underTest.changeLevel(INFO);
verify(database).enableSqlLogging(false);
reset(database);
underTest.changeLevel(DEBUG);
verify(database).enableSqlLogging(false);
reset(database);
underTest.changeLevel(TRACE);
verify(database).enableSqlLogging(true);
}
@DataProvider
public static Object[][] supportedSonarApiLevels() {
return new Object[][] {
{INFO},
{DEBUG},
{TRACE}
};
}
@Test
public void changeLevel_fails_with_IAE_when_level_is_ERROR() {
assertThatThrownBy(() -> underTest.changeLevel(ERROR))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("ERROR log level is not supported (allowed levels are [TRACE, DEBUG, INFO])");
}
@Test
public void changeLevel_fails_with_IAE_when_level_is_WARN() {
assertThatThrownBy(() -> underTest.changeLevel(WARN))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("WARN log level is not supported (allowed levels are [TRACE, DEBUG, INFO])");
}
}
| 5,041 | 36.073529 | 142 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/loginmessage/LoginMessageFeatureTest.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.loginmessage;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarRuntime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(DataProviderRunner.class)
public class LoginMessageFeatureTest {
private final SonarRuntime sonarRuntime = mock(SonarRuntime.class);
private final LoginMessageFeature underTest = new LoginMessageFeature(sonarRuntime);
@Test
@UseDataProvider("editionsAndLoginMessageFeatureAvailability")
public void isAvailable_shouldOnlyBeEnabledInEnterpriseEditionPlus(SonarEdition edition, boolean shouldBeEnabled) {
when(sonarRuntime.getEdition()).thenReturn(edition);
boolean isAvailable = underTest.isAvailable();
assertThat(isAvailable).isEqualTo(shouldBeEnabled);
}
@Test
public void getName_ShouldReturn_RegulatoryReports() {
assertEquals("login-message", underTest.getName());
}
@DataProvider
public static Object[][] editionsAndLoginMessageFeatureAvailability() {
return new Object[][] {
{SonarEdition.COMMUNITY, false},
{SonarEdition.DEVELOPER, false},
{SonarEdition.ENTERPRISE, true},
{SonarEdition.DATACENTER, true}
};
}
}
| 2,381 | 35.090909 | 117 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/management/DelegatingManagedInstanceServiceTest.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.management;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.sonar.db.DbSession;
import static java.util.Collections.emptySet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DelegatingManagedInstanceServiceTest {
@Mock
private DbSession dbSession;
@Test
public void getProviderName_whenNotManaged_shouldThrow() {
DelegatingManagedInstanceService managedInstanceService = new DelegatingManagedInstanceService(emptySet());
assertThatThrownBy(() -> managedInstanceService.getProviderName())
.isInstanceOf(IllegalStateException.class)
.hasMessage("This instance is not managed.");
}
@Test
public void getProviderName_whenManaged_shouldReturnName() {
DelegatingManagedInstanceService managedInstanceService = new DelegatingManagedInstanceService(Set.of(new AlwaysManagedInstanceService()));
assertThat(managedInstanceService.getProviderName()).isEqualTo("Always");
}
@Test
public void isInstanceExternallyManaged_whenNoManagedInstanceService_returnsFalse() {
DelegatingManagedInstanceService managedInstanceService = new DelegatingManagedInstanceService(emptySet());
assertThat(managedInstanceService.isInstanceExternallyManaged()).isFalse();
}
@Test
public void isInstanceExternallyManaged_whenAllManagedInstanceServiceReturnsFalse_returnsFalse() {
Set<ManagedInstanceService> delegates = Set.of(new NeverManagedInstanceService(), new NeverManagedInstanceService());
DelegatingManagedInstanceService managedInstanceService = new DelegatingManagedInstanceService(delegates);
assertThat(managedInstanceService.isInstanceExternallyManaged()).isFalse();
}
@Test
public void isInstanceExternallyManaged_whenOneManagedInstanceServiceReturnsTrue_returnsTrue() {
Set<ManagedInstanceService> delegates = Set.of(new NeverManagedInstanceService(), new AlwaysManagedInstanceService());
DelegatingManagedInstanceService managedInstanceService = new DelegatingManagedInstanceService(delegates);
assertThat(managedInstanceService.isInstanceExternallyManaged()).isTrue();
}
@Test
public void getUserUuidToManaged_whenNoDelegates_setAllUsersAsNonManaged() {
Set<String> userUuids = Set.of("a", "b");
DelegatingManagedInstanceService managedInstanceService = new DelegatingManagedInstanceService(emptySet());
Map<String, Boolean> userUuidToManaged = managedInstanceService.getUserUuidToManaged(dbSession, userUuids);
assertThat(userUuidToManaged).containsExactlyInAnyOrderEntriesOf(Map.of("a", false, "b", false));
}
@Test
public void getUserUuidToManaged_delegatesToRightService_andPropagateAnswer() {
Set<String> userUuids = Set.of("a", "b");
Map<String, Boolean> serviceResponse = Map.of("a", false, "b", true);
ManagedInstanceService anotherManagedInstanceService = getManagedInstanceService(userUuids, serviceResponse);
DelegatingManagedInstanceService managedInstanceService = new DelegatingManagedInstanceService(Set.of(new NeverManagedInstanceService(), anotherManagedInstanceService));
Map<String, Boolean> userUuidToManaged = managedInstanceService.getUserUuidToManaged(dbSession, userUuids);
assertThat(userUuidToManaged).containsExactlyInAnyOrderEntriesOf(serviceResponse);
}
@Test
public void getGroupUuidToManaged_whenNoDelegates_setAllUsersAsNonManaged() {
Set<String> groupUuids = Set.of("a", "b");
DelegatingManagedInstanceService managedInstanceService = new DelegatingManagedInstanceService(emptySet());
Map<String, Boolean> groupUuidToManaged = managedInstanceService.getGroupUuidToManaged(dbSession, groupUuids);
assertThat(groupUuidToManaged).containsExactlyInAnyOrderEntriesOf(Map.of("a", false, "b", false));
}
@Test
public void isUserManaged_delegatesToRightService_andPropagateAnswer() {
DelegatingManagedInstanceService managedInstanceService = new DelegatingManagedInstanceService(Set.of(new NeverManagedInstanceService(), new AlwaysManagedInstanceService()));
assertThat(managedInstanceService.isUserManaged(dbSession, "login")).isTrue();
}
@Test
public void isUserManaged_whenNoDelegates_returnsFalse() {
DelegatingManagedInstanceService managedInstanceService = new DelegatingManagedInstanceService(Set.of());
assertThat(managedInstanceService.isUserManaged(dbSession, "login")).isFalse();
}
@Test
public void getGroupUuidToManaged_delegatesToRightService_andPropagateAnswer() {
Set<String> groupUuids = Set.of("a", "b");
Map<String, Boolean> serviceResponse = Map.of("a", false, "b", true);
ManagedInstanceService anotherManagedInstanceService = getManagedInstanceService(groupUuids, serviceResponse);
DelegatingManagedInstanceService managedInstanceService = new DelegatingManagedInstanceService(Set.of(new NeverManagedInstanceService(), anotherManagedInstanceService));
Map<String, Boolean> groupUuidToManaged = managedInstanceService.getGroupUuidToManaged(dbSession, groupUuids);
assertThat(groupUuidToManaged).containsExactlyInAnyOrderEntriesOf(serviceResponse);
}
@Test
public void getGroupUuidToManaged_ifMoreThanOneDelegatesActivated_throws() {
Set<ManagedInstanceService> managedInstanceServices = Set.of(new AlwaysManagedInstanceService(), new AlwaysManagedInstanceService());
DelegatingManagedInstanceService delegatingManagedInstanceService = new DelegatingManagedInstanceService(managedInstanceServices);
assertThatIllegalStateException()
.isThrownBy(() -> delegatingManagedInstanceService.getGroupUuidToManaged(dbSession, Set.of("a")))
.withMessage("The instance can't be managed by more than one identity provider and 2 were found.");
}
@Test
public void getUserUuidToManaged_ifMoreThanOneDelegatesActivated_throws() {
Set<ManagedInstanceService> managedInstanceServices = Set.of(new AlwaysManagedInstanceService(), new AlwaysManagedInstanceService());
DelegatingManagedInstanceService delegatingManagedInstanceService = new DelegatingManagedInstanceService(managedInstanceServices);
assertThatIllegalStateException()
.isThrownBy(() -> delegatingManagedInstanceService.getUserUuidToManaged(dbSession, Set.of("a")))
.withMessage("The instance can't be managed by more than one identity provider and 2 were found.");
}
@Test
public void getManagedUsersSqlFilter_whenNoDelegates_throws() {
Set<ManagedInstanceService> managedInstanceServices = emptySet();
DelegatingManagedInstanceService delegatingManagedInstanceService = new DelegatingManagedInstanceService(managedInstanceServices);
assertThatIllegalStateException()
.isThrownBy(() -> delegatingManagedInstanceService.getManagedUsersSqlFilter(true))
.withMessage("This instance is not managed.");
}
@Test
public void getManagedUsersSqlFilter_delegatesToRightService_andPropagateAnswer() {
AlwaysManagedInstanceService alwaysManagedInstanceService = new AlwaysManagedInstanceService();
DelegatingManagedInstanceService managedInstanceService = new DelegatingManagedInstanceService(Set.of(new NeverManagedInstanceService(), alwaysManagedInstanceService));
assertThat(managedInstanceService.getManagedUsersSqlFilter(true)).isNotNull().isEqualTo(alwaysManagedInstanceService.getManagedUsersSqlFilter(
true));
}
@Test
public void getManagedGroupsSqlFilter_whenNoDelegates_throws() {
Set<ManagedInstanceService> managedInstanceServices = emptySet();
DelegatingManagedInstanceService delegatingManagedInstanceService = new DelegatingManagedInstanceService(managedInstanceServices);
assertThatIllegalStateException()
.isThrownBy(() -> delegatingManagedInstanceService.getManagedGroupsSqlFilter(true))
.withMessage("This instance is not managed.");
}
@Test
public void getManagedGroupsSqlFilter_delegatesToRightService_andPropagateAnswer() {
AlwaysManagedInstanceService alwaysManagedInstanceService = new AlwaysManagedInstanceService();
DelegatingManagedInstanceService managedInstanceService = new DelegatingManagedInstanceService(Set.of(new NeverManagedInstanceService(), alwaysManagedInstanceService));
assertThat(managedInstanceService.getManagedGroupsSqlFilter(true)).isNotNull().isEqualTo(alwaysManagedInstanceService.getManagedGroupsSqlFilter(
true));
}
private ManagedInstanceService getManagedInstanceService(Set<String> userUuids, Map<String, Boolean> uuidToManaged) {
ManagedInstanceService anotherManagedInstanceService = mock(ManagedInstanceService.class);
when(anotherManagedInstanceService.isInstanceExternallyManaged()).thenReturn(true);
when(anotherManagedInstanceService.getGroupUuidToManaged(dbSession, userUuids)).thenReturn(uuidToManaged);
when(anotherManagedInstanceService.getUserUuidToManaged(dbSession, userUuids)).thenReturn(uuidToManaged);
return anotherManagedInstanceService;
}
private static class NeverManagedInstanceService implements ManagedInstanceService {
@Override
public boolean isInstanceExternallyManaged() {
return false;
}
@Override
public String getProviderName() {
return "Never";
}
@Override
public Map<String, Boolean> getUserUuidToManaged(DbSession dbSession, Set<String> userUuids) {
return null;
}
@Override
public Map<String, Boolean> getGroupUuidToManaged(DbSession dbSession, Set<String> groupUuids) {
return null;
}
@Override
public String getManagedUsersSqlFilter(boolean filterByManaged) {
return null;
}
@Override
public String getManagedGroupsSqlFilter(boolean filterByManaged) {
return null;
}
@Override
public boolean isUserManaged(DbSession dbSession, String login) {
return false;
}
}
private static class AlwaysManagedInstanceService implements ManagedInstanceService {
@Override
public boolean isInstanceExternallyManaged() {
return true;
}
@Override
public String getProviderName() {
return "Always";
}
@Override
public Map<String, Boolean> getUserUuidToManaged(DbSession dbSession, Set<String> userUuids) {
return null;
}
@Override
public Map<String, Boolean> getGroupUuidToManaged(DbSession dbSession, Set<String> groupUuids) {
return null;
}
@Override
public String getManagedUsersSqlFilter(boolean filterByManaged) {
return "any filter";
}
@Override
public String getManagedGroupsSqlFilter(boolean filterByManaged) {
return "any filter";
}
@Override
public boolean isUserManaged(DbSession dbSession, String login) {
return true;
}
}
}
| 11,889 | 41.464286 | 178 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/measure/DebtRatingGridTest.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.measure;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.measure.Rating.A;
import static org.sonar.server.measure.Rating.B;
import static org.sonar.server.measure.Rating.C;
import static org.sonar.server.measure.Rating.D;
import static org.sonar.server.measure.Rating.E;
public class DebtRatingGridTest {
private DebtRatingGrid ratingGrid;
@Before
public void setUp() {
double[] gridValues = new double[] {0.1, 0.2, 0.5, 1};
ratingGrid = new DebtRatingGrid(gridValues);
}
@Test
public void return_rating_matching_density() {
assertThat(ratingGrid.getRatingForDensity(0)).isEqualTo(A);
assertThat(ratingGrid.getRatingForDensity(0.05)).isEqualTo(A);
assertThat(ratingGrid.getRatingForDensity(0.09999999)).isEqualTo(A);
assertThat(ratingGrid.getRatingForDensity(0.1)).isEqualTo(A);
assertThat(ratingGrid.getRatingForDensity(0.15)).isEqualTo(B);
assertThat(ratingGrid.getRatingForDensity(0.2)).isEqualTo(B);
assertThat(ratingGrid.getRatingForDensity(0.25)).isEqualTo(C);
assertThat(ratingGrid.getRatingForDensity(0.5)).isEqualTo(C);
assertThat(ratingGrid.getRatingForDensity(0.65)).isEqualTo(D);
assertThat(ratingGrid.getRatingForDensity(1)).isEqualTo(D);
assertThat(ratingGrid.getRatingForDensity(1.01)).isEqualTo(E);
}
@Test
public void density_matching_exact_grid_values() {
assertThat(ratingGrid.getRatingForDensity(0.1)).isEqualTo(A);
assertThat(ratingGrid.getRatingForDensity(0.2)).isEqualTo(B);
assertThat(ratingGrid.getRatingForDensity(0.5)).isEqualTo(C);
assertThat(ratingGrid.getRatingForDensity(1)).isEqualTo(D);
}
@Test
public void convert_int_to_rating() {
assertThat(Rating.valueOf(1)).isEqualTo(A);
assertThat(Rating.valueOf(2)).isEqualTo(B);
assertThat(Rating.valueOf(3)).isEqualTo(C);
assertThat(Rating.valueOf(4)).isEqualTo(D);
assertThat(Rating.valueOf(5)).isEqualTo(E);
}
@Test
public void fail_on_invalid_density() {
assertThatThrownBy(() -> ratingGrid.getRatingForDensity(-1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid value '-1.0'");
}
@Test
public void fail_to_concert_invalid_value() {
assertThatThrownBy(() -> Rating.valueOf(10))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_on_invalid_grid() {
assertThatThrownBy(() -> {
ratingGrid = new DebtRatingGrid(new double[] {0.1, 0.2, 0.5});
})
.isInstanceOf(IllegalStateException.class)
.hasMessage("Rating grid should contains 4 values");
}
}
| 3,579 | 36.291667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/metric/UnanalyzedLanguageMetricsTest.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.metric;
import java.util.List;
import org.junit.Test;
import org.sonar.api.measures.Metric;
import static org.assertj.core.api.Assertions.assertThat;
public class UnanalyzedLanguageMetricsTest {
@Test
public void count_metrics() {
UnanalyzedLanguageMetrics coreCustomMetrics = new UnanalyzedLanguageMetrics();
List<Metric> metrics = coreCustomMetrics.getMetrics();
assertThat(metrics).hasSize(2);
}
}
| 1,292 | 33.026316 | 82 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/notification/DefaultNotificationManagerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.notification;
import com.google.common.collect.ImmutableSet;
import java.io.InvalidClassException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.sonar.api.notifications.Notification;
import org.sonar.api.notifications.NotificationChannel;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.EmailSubscriberDto;
import org.sonar.db.notification.NotificationQueueDao;
import org.sonar.db.notification.NotificationQueueDto;
import org.sonar.db.permission.AuthorizationDao;
import org.sonar.db.property.PropertiesDao;
import org.sonar.server.notification.NotificationManager.EmailRecipient;
import org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject;
import static com.google.common.collect.Sets.newHashSet;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
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.anyBoolean;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject.ALL_MUST_HAVE_ROLE_USER;
public class DefaultNotificationManagerTest {
private DefaultNotificationManager underTest;
private PropertiesDao propertiesDao = mock(PropertiesDao.class);
private NotificationDispatcher dispatcher = mock(NotificationDispatcher.class);
private NotificationChannel emailChannel = mock(NotificationChannel.class);
private NotificationChannel twitterChannel = mock(NotificationChannel.class);
private NotificationQueueDao notificationQueueDao = mock(NotificationQueueDao.class);
private AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
private DbClient dbClient = mock(DbClient.class);
private DbSession dbSession = mock(DbSession.class);
private System2 system2 = mock(System2.class);
@Before
public void setUp() {
when(dispatcher.getKey()).thenReturn("NewViolations");
when(emailChannel.getKey()).thenReturn("Email");
when(twitterChannel.getKey()).thenReturn("Twitter");
when(dbClient.openSession(anyBoolean())).thenReturn(dbSession);
when(dbClient.propertiesDao()).thenReturn(propertiesDao);
when(dbClient.notificationQueueDao()).thenReturn(notificationQueueDao);
when(dbClient.authorizationDao()).thenReturn(authorizationDao);
when(system2.now()).thenReturn(0L);
underTest = new DefaultNotificationManager(new NotificationChannel[] {emailChannel, twitterChannel}, dbClient);
}
@Test
public void shouldProvideChannelList() {
assertThat(underTest.getChannels()).containsOnly(emailChannel, twitterChannel);
underTest = new DefaultNotificationManager(new NotificationChannel[] {}, dbClient);
assertThat(underTest.getChannels()).isEmpty();
}
@Test
public void shouldPersist() {
Notification notification = new Notification("test");
underTest.scheduleForSending(notification);
verify(notificationQueueDao, only()).insert(any(List.class));
}
@Test
public void shouldGetFromQueueAndDelete() {
Notification notification = new Notification("test");
NotificationQueueDto dto = NotificationQueueDto.toNotificationQueueDto(notification);
List<NotificationQueueDto> dtos = Arrays.asList(dto);
when(notificationQueueDao.selectOldest(1)).thenReturn(dtos);
assertThat(underTest.<Notification>getFromQueue()).isNotNull();
InOrder inOrder = inOrder(notificationQueueDao);
inOrder.verify(notificationQueueDao).selectOldest(1);
inOrder.verify(notificationQueueDao).delete(dtos);
}
// SONAR-4739
@Test
public void shouldNotFailWhenUnableToDeserialize() throws Exception {
NotificationQueueDto dto1 = mock(NotificationQueueDto.class);
when(dto1.toNotification()).thenThrow(new InvalidClassException("Pouet"));
List<NotificationQueueDto> dtos = Arrays.asList(dto1);
when(notificationQueueDao.selectOldest(1)).thenReturn(dtos);
underTest = spy(underTest);
assertThat(underTest.<Notification>getFromQueue()).isNull();
assertThat(underTest.<Notification>getFromQueue()).isNull();
verify(underTest, times(1)).logDeserializationIssue();
}
@Test
public void findSubscribedEmailRecipients_fails_with_NPE_if_projectKey_is_null() {
String dispatcherKey = randomAlphabetic(12);
assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, null, ALL_MUST_HAVE_ROLE_USER))
.isInstanceOf(NullPointerException.class)
.hasMessage("projectKey is mandatory");
}
@Test
public void findSubscribedEmailRecipients_with_logins_fails_with_NPE_if_projectKey_is_null() {
String dispatcherKey = randomAlphabetic(12);
assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, null, ImmutableSet.of(), ALL_MUST_HAVE_ROLE_USER))
.isInstanceOf(NullPointerException.class)
.hasMessage("projectKey is mandatory");
}
@Test
public void findSubscribedEmailRecipients_with_logins_fails_with_NPE_if_logins_is_null() {
String dispatcherKey = randomAlphabetic(12);
String projectKey = randomAlphabetic(6);
assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey, null, ALL_MUST_HAVE_ROLE_USER))
.isInstanceOf(NullPointerException.class)
.hasMessage("logins can't be null");
}
@Test
public void findSubscribedEmailRecipients_with_logins_returns_empty_if_login_set_is_empty() {
String dispatcherKey = randomAlphabetic(12);
String projectKey = randomAlphabetic(6);
Set<EmailRecipient> recipients = underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey, ImmutableSet.of(), ALL_MUST_HAVE_ROLE_USER);
assertThat(recipients).isEmpty();
}
@Test
public void findSubscribedEmailRecipients_returns_empty_if_no_email_recipients_in_project_for_dispatcher_key() {
String dispatcherKey = randomAlphabetic(12);
String globalPermission = randomAlphanumeric(4);
String projectPermission = randomAlphanumeric(5);
String projectKey = randomAlphabetic(6);
when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey))
.thenReturn(Collections.emptySet());
Set<EmailRecipient> emailRecipients = underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey,
new SubscriberPermissionsOnProject(globalPermission, projectPermission));
assertThat(emailRecipients).isEmpty();
verify(authorizationDao, times(0)).keepAuthorizedLoginsOnEntity(any(DbSession.class), anySet(), anyString(), anyString());
}
@Test
public void findSubscribedEmailRecipients_with_logins_returns_empty_if_no_email_recipients_in_project_for_dispatcher_key() {
String dispatcherKey = randomAlphabetic(12);
String globalPermission = randomAlphanumeric(4);
String projectPermission = randomAlphanumeric(5);
String projectKey = randomAlphabetic(6);
Set<String> logins = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> "login_" + i)
.collect(Collectors.toSet());
when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey, logins))
.thenReturn(Collections.emptySet());
Set<EmailRecipient> emailRecipients = underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey, logins,
new SubscriberPermissionsOnProject(globalPermission, projectPermission));
assertThat(emailRecipients).isEmpty();
verify(authorizationDao, times(0)).keepAuthorizedLoginsOnEntity(any(DbSession.class), anySet(), anyString(), anyString());
}
@Test
public void findSubscribedEmailRecipients_applies_distinct_permission_filtering_global_or_project_subscribers() {
String dispatcherKey = randomAlphabetic(12);
String globalPermission = randomAlphanumeric(4);
String projectPermission = randomAlphanumeric(5);
String projectKey = randomAlphabetic(6);
when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey))
.thenReturn(
newHashSet(EmailSubscriberDto.create("user1", false, "user1@foo"), EmailSubscriberDto.create("user3", false, "user3@foo"),
EmailSubscriberDto.create("user3", true, "user3@foo")));
when(authorizationDao.keepAuthorizedLoginsOnEntity(dbSession, newHashSet("user3", "user4"), projectKey, globalPermission))
.thenReturn(newHashSet("user3"));
when(authorizationDao.keepAuthorizedLoginsOnEntity(dbSession, newHashSet("user1", "user3"), projectKey, projectPermission))
.thenReturn(newHashSet("user1", "user3"));
Set<EmailRecipient> emailRecipients = underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey,
new SubscriberPermissionsOnProject(globalPermission, projectPermission));
assertThat(emailRecipients)
.isEqualTo(ImmutableSet.of(new EmailRecipient("user1", "user1@foo"), new EmailRecipient("user3", "user3@foo")));
// code is optimized to perform only 2 SQL requests for all channels
verify(authorizationDao, times(1)).keepAuthorizedLoginsOnEntity(eq(dbSession), anySet(), anyString(), eq(globalPermission));
verify(authorizationDao, times(1)).keepAuthorizedLoginsOnEntity(eq(dbSession), anySet(), anyString(), eq(projectPermission));
}
@Test
public void findSubscribedEmailRecipients_with_logins_applies_distinct_permission_filtering_global_or_project_subscribers() {
String dispatcherKey = randomAlphabetic(12);
String globalPermission = randomAlphanumeric(4);
String projectPermission = randomAlphanumeric(5);
String projectKey = randomAlphabetic(6);
Set<String> logins = ImmutableSet.of("user1", "user2", "user3");
when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey, logins))
.thenReturn(
newHashSet(EmailSubscriberDto.create("user1", false, "user1@foo"), EmailSubscriberDto.create("user3", false, "user3@foo"),
EmailSubscriberDto.create("user3", true, "user3@foo")));
when(authorizationDao.keepAuthorizedLoginsOnEntity(dbSession, newHashSet("user3", "user4"), projectKey, globalPermission))
.thenReturn(newHashSet("user3"));
when(authorizationDao.keepAuthorizedLoginsOnEntity(dbSession, newHashSet("user1", "user3"), projectKey, projectPermission))
.thenReturn(newHashSet("user1", "user3"));
Set<EmailRecipient> emailRecipients = underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey, logins,
new SubscriberPermissionsOnProject(globalPermission, projectPermission));
assertThat(emailRecipients)
.isEqualTo(ImmutableSet.of(new EmailRecipient("user1", "user1@foo"), new EmailRecipient("user3", "user3@foo")));
// code is optimized to perform only 2 SQL requests for all channels
verify(authorizationDao, times(1)).keepAuthorizedLoginsOnEntity(eq(dbSession), anySet(), anyString(), eq(globalPermission));
verify(authorizationDao, times(1)).keepAuthorizedLoginsOnEntity(eq(dbSession), anySet(), anyString(), eq(projectPermission));
}
@Test
public void findSubscribedEmailRecipients_does_not_call_db_for_project_permission_filtering_if_there_is_no_project_subscriber() {
String dispatcherKey = randomAlphabetic(12);
String globalPermission = randomAlphanumeric(4);
String projectPermission = randomAlphanumeric(5);
String projectKey = randomAlphabetic(6);
Set<EmailSubscriberDto> subscribers = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> EmailSubscriberDto.create("user" + i, true, "user" + i + "@sonarsource.com"))
.collect(Collectors.toSet());
Set<String> logins = subscribers.stream().map(EmailSubscriberDto::getLogin).collect(Collectors.toSet());
when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey))
.thenReturn(subscribers);
when(authorizationDao.keepAuthorizedLoginsOnEntity(dbSession, logins, projectKey, globalPermission))
.thenReturn(logins);
Set<EmailRecipient> emailRecipients = underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey,
new SubscriberPermissionsOnProject(globalPermission, projectPermission));
Set<EmailRecipient> expected = subscribers.stream().map(i -> new EmailRecipient(i.getLogin(), i.getEmail())).collect(Collectors.toSet());
assertThat(emailRecipients)
.isEqualTo(expected);
verify(authorizationDao, times(1)).keepAuthorizedLoginsOnEntity(eq(dbSession), anySet(), anyString(), eq(globalPermission));
verify(authorizationDao, times(0)).keepAuthorizedLoginsOnEntity(eq(dbSession), anySet(), anyString(), eq(projectPermission));
}
@Test
public void findSubscribedEmailRecipients_with_logins_does_not_call_db_for_project_permission_filtering_if_there_is_no_project_subscriber() {
String dispatcherKey = randomAlphabetic(12);
String globalPermission = randomAlphanumeric(4);
String projectPermission = randomAlphanumeric(5);
String projectKey = randomAlphabetic(6);
Set<EmailSubscriberDto> subscribers = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> EmailSubscriberDto.create("user" + i, true, "user" + i + "@sonarsource.com"))
.collect(Collectors.toSet());
Set<String> logins = subscribers.stream().map(EmailSubscriberDto::getLogin).collect(Collectors.toSet());
when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey, logins))
.thenReturn(subscribers);
when(authorizationDao.keepAuthorizedLoginsOnEntity(dbSession, logins, projectKey, globalPermission))
.thenReturn(logins);
Set<EmailRecipient> emailRecipients = underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey, logins,
new SubscriberPermissionsOnProject(globalPermission, projectPermission));
Set<EmailRecipient> expected = subscribers.stream().map(i -> new EmailRecipient(i.getLogin(), i.getEmail())).collect(Collectors.toSet());
assertThat(emailRecipients)
.isEqualTo(expected);
verify(authorizationDao, times(1)).keepAuthorizedLoginsOnEntity(eq(dbSession), anySet(), anyString(), eq(globalPermission));
verify(authorizationDao, times(0)).keepAuthorizedLoginsOnEntity(eq(dbSession), anySet(), anyString(), eq(projectPermission));
}
@Test
public void findSubscribedEmailRecipients_does_not_call_DB_for_project_permission_filtering_if_there_is_no_global_subscriber() {
String dispatcherKey = randomAlphabetic(12);
String globalPermission = randomAlphanumeric(4);
String projectPermission = randomAlphanumeric(5);
String projectKey = randomAlphabetic(6);
Set<EmailSubscriberDto> subscribers = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> EmailSubscriberDto.create("user" + i, false, "user" + i + "@sonarsource.com"))
.collect(Collectors.toSet());
Set<String> logins = subscribers.stream().map(EmailSubscriberDto::getLogin).collect(Collectors.toSet());
when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey))
.thenReturn(subscribers);
when(authorizationDao.keepAuthorizedLoginsOnEntity(dbSession, logins, projectKey, projectPermission))
.thenReturn(logins);
Set<EmailRecipient> emailRecipients = underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey,
new SubscriberPermissionsOnProject(globalPermission, projectPermission));
Set<EmailRecipient> expected = subscribers.stream().map(i -> new EmailRecipient(i.getLogin(), i.getEmail())).collect(Collectors.toSet());
assertThat(emailRecipients)
.isEqualTo(expected);
verify(authorizationDao, times(0)).keepAuthorizedLoginsOnEntity(eq(dbSession), anySet(), anyString(), eq(globalPermission));
verify(authorizationDao, times(1)).keepAuthorizedLoginsOnEntity(eq(dbSession), anySet(), anyString(), eq(projectPermission));
}
@Test
public void findSubscribedEmailRecipients_with_logins_does_not_call_DB_for_project_permission_filtering_if_there_is_no_global_subscriber() {
String dispatcherKey = randomAlphabetic(12);
String globalPermission = randomAlphanumeric(4);
String projectPermission = randomAlphanumeric(5);
String projectKey = randomAlphabetic(6);
Set<EmailSubscriberDto> subscribers = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> EmailSubscriberDto.create("user" + i, false, "user" + i + "@sonarsource.com"))
.collect(Collectors.toSet());
Set<String> logins = subscribers.stream().map(EmailSubscriberDto::getLogin).collect(Collectors.toSet());
when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey, logins))
.thenReturn(subscribers);
when(authorizationDao.keepAuthorizedLoginsOnEntity(dbSession, logins, projectKey, projectPermission))
.thenReturn(logins);
Set<EmailRecipient> emailRecipients = underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey, logins,
new SubscriberPermissionsOnProject(globalPermission, projectPermission));
Set<EmailRecipient> expected = subscribers.stream().map(i -> new EmailRecipient(i.getLogin(), i.getEmail())).collect(Collectors.toSet());
assertThat(emailRecipients)
.isEqualTo(expected);
verify(authorizationDao, times(0)).keepAuthorizedLoginsOnEntity(eq(dbSession), anySet(), anyString(), eq(globalPermission));
verify(authorizationDao, times(1)).keepAuthorizedLoginsOnEntity(eq(dbSession), anySet(), anyString(), eq(projectPermission));
}
}
| 19,379 | 52.241758 | 148 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.