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-ce/src/test/java/org/sonar/ce/container/CePluginJarExploderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.container;
import java.io.File;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.core.platform.ExplodedPlugin;
import org.sonar.core.platform.PluginInfo;
import org.sonar.server.platform.ServerFileSystem;
import static org.apache.commons.io.FileUtils.sizeOfDirectory;
import static org.assertj.core.api.Assertions.assertThat;
public class CePluginJarExploderTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
DumbFileSystem fs = new DumbFileSystem(temp);
CePluginJarExploder underTest = new CePluginJarExploder(fs);
@Test
public void explode_jar_to_temp_directory() {
PluginInfo info = PluginInfo.create(plugin1Jar());
ExplodedPlugin exploded = underTest.explode(info);
// all the files loaded by classloaders (JAR + META-INF/libs/*.jar) are copied to a dedicated temp directory
File copiedJar = exploded.getMain();
assertThat(exploded.getKey()).isEqualTo("test");
assertThat(copiedJar).isFile().exists();
assertThat(copiedJar.getParentFile()).isDirectory().hasName("test");
assertThat(copiedJar.getParentFile().getParentFile()).isDirectory().hasName("ce-exploded-plugins");
}
@Test
public void plugins_do_not_overlap() {
PluginInfo info1 = PluginInfo.create(plugin1Jar());
PluginInfo info2 = PluginInfo.create(plugin2Jar());
ExplodedPlugin exploded1 = underTest.explode(info1);
ExplodedPlugin exploded2 = underTest.explode(info2);
assertThat(exploded1.getKey()).isEqualTo("test");
assertThat(exploded1.getMain()).isFile().exists().hasName("sonar-test-plugin-0.1-SNAPSHOT.jar");
assertThat(exploded2.getKey()).isEqualTo("test2");
assertThat(exploded2.getMain()).isFile().exists().hasName("sonar-test2-plugin-0.1-SNAPSHOT.jar");
}
@Test
public void explode_is_reentrant() throws Exception {
PluginInfo info = PluginInfo.create(plugin1Jar());
ExplodedPlugin exploded1 = underTest.explode(info);
long dirSize1 = sizeOfDirectory(exploded1.getMain().getParentFile());
ExplodedPlugin exploded2 = underTest.explode(info);
long dirSize2 = sizeOfDirectory(exploded2.getMain().getParentFile());
assertThat(exploded2.getMain().getCanonicalPath()).isEqualTo(exploded1.getMain().getCanonicalPath());
assertThat(dirSize1).isEqualTo(dirSize2);
}
private File plugin1Jar() {
return new File("src/test/plugins/sonar-test-plugin/target/sonar-test-plugin-0.1-SNAPSHOT.jar");
}
private File plugin2Jar() {
return new File("src/test/plugins/sonar-test2-plugin/target/sonar-test2-plugin-0.1-SNAPSHOT.jar");
}
private static class DumbFileSystem implements ServerFileSystem {
private final TemporaryFolder temp;
private File tempDir;
public DumbFileSystem(TemporaryFolder temp) {
this.temp = temp;
}
@Override
public File getHomeDir() {
throw new UnsupportedOperationException();
}
@Override
public File getTempDir() {
if (tempDir == null) {
try {
this.tempDir = temp.newFolder();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
return tempDir;
}
@Override
public File getDeployedPluginsDir() {
throw new UnsupportedOperationException();
}
@Override
public File getDownloadedPluginsDir() {
throw new UnsupportedOperationException();
}
@Override
public File getInstalledExternalPluginsDir() {
throw new UnsupportedOperationException();
}
@Override
public File getInstalledBundledPluginsDir() {
throw new UnsupportedOperationException();
}
@Override
public File getPluginIndex() {
throw new UnsupportedOperationException();
}
@Override
public File getUninstalledPluginsDir() {
throw new UnsupportedOperationException();
}
}
}
| 4,768 | 31.006711 | 112 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/container/CePluginRepositoryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.container;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mockito;
import org.sonar.api.Plugin;
import org.sonar.core.platform.ExplodedPlugin;
import org.sonar.core.platform.PluginClassLoader;
import org.sonar.server.platform.ServerFileSystem;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CePluginRepositoryTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private ServerFileSystem fs = mock(ServerFileSystem.class, Mockito.RETURNS_DEEP_STUBS);
private PluginClassLoader pluginClassLoader = new DumbPluginClassLoader();
private CePluginJarExploder cePluginJarExploder = new CePluginJarExploder(fs);
private CePluginRepository underTest = new CePluginRepository(fs, pluginClassLoader, cePluginJarExploder);
@After
public void tearDown() {
underTest.stop();
}
@Test
public void empty_plugins() throws Exception {
// empty folder
when(fs.getInstalledExternalPluginsDir()).thenReturn(temp.newFolder());
underTest.start();
assertThat(underTest.getPluginInfos()).isEmpty();
assertThat(underTest.hasPlugin("foo")).isFalse();
}
@Test
public void load_plugins() throws IOException {
String pluginKey = "test";
when(fs.getTempDir()).thenReturn(temp.newFolder());
when(fs.getInstalledExternalPluginsDir()).thenReturn(new File("src/test/plugins/sonar-test-plugin/target"));
underTest.start();
assertThat(underTest.getPluginInfos()).extracting("key").containsOnly(pluginKey);
assertThat(underTest.getPluginInfo(pluginKey).getKey()).isEqualTo(pluginKey);
assertThat(underTest.getPluginInstance(pluginKey)).isNotNull();
assertThat(underTest.getPluginInstances()).isNotEmpty();
assertThat(underTest.hasPlugin(pluginKey)).isTrue();
}
@Test
public void getPluginInfo_fails_if_plugin_does_not_exist() throws Exception {
// empty folder
when(fs.getInstalledExternalPluginsDir()).thenReturn(temp.newFolder());
underTest.start();
assertThatThrownBy(() -> underTest.getPluginInfo("foo"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Plugin [foo] does not exist");
}
@Test
public void getPluginInstance_fails_if_plugin_does_not_exist() throws Exception {
// empty folder
when(fs.getInstalledExternalPluginsDir()).thenReturn(temp.newFolder());
underTest.start();
assertThatThrownBy(() -> underTest.getPluginInstance("foo"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Plugin [foo] does not exist");
}
@Test
public void getPluginInstance_throws_ISE_if_repo_is_not_started() {
assertThatThrownBy(() -> underTest.getPluginInstance("foo"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("not started yet");
}
@Test
public void getPluginInfo_throws_ISE_if_repo_is_not_started() {
assertThatThrownBy(() -> underTest.getPluginInfo("foo"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("not started yet");
}
@Test
public void hasPlugin_throws_ISE_if_repo_is_not_started() {
assertThatThrownBy(() -> underTest.hasPlugin("foo"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("not started yet");
}
@Test
public void getPluginInfos_throws_ISE_if_repo_is_not_started() {
assertThatThrownBy(() -> underTest.getPluginInfos())
.isInstanceOf(IllegalStateException.class)
.hasMessage("not started yet");
}
private static class DumbPluginClassLoader extends PluginClassLoader {
public DumbPluginClassLoader() {
super(null);
}
/**
* Does nothing except returning the specified list of plugins
*/
@Override
public Map<String, Plugin> load(Map<String, ExplodedPlugin> infoByKeys) {
Map<String, Plugin> result = new HashMap<>();
for (String pluginKey : infoByKeys.keySet()) {
result.put(pluginKey, mock(Plugin.class));
}
return result;
}
@Override
public void unload(Collection<Plugin> plugins) {
}
}
}
| 5,227 | 32.729032 | 112 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/db/ReadOnlyPropertiesDaoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.db;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.MyBatis;
import org.sonar.db.property.PropertyDto;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoMoreInteractions;
public class ReadOnlyPropertiesDaoTest {
private MyBatis myBatis = mock(MyBatis.class);
private DbSession dbSession = mock(DbSession.class);
private PropertyDto propertyDto = mock(PropertyDto.class);
private PropertyDto oldPropertyDto = mock(PropertyDto.class);
private UuidFactory uuidFactory = new SequenceUuidFactory();
private ReadOnlyPropertiesDao underTest = new ReadOnlyPropertiesDao(myBatis, System2.INSTANCE, uuidFactory);
@Test
public void insertProperty() {
underTest.saveProperty(dbSession, propertyDto, null, null, null, null);
assertNoInteraction();
}
@Test
public void insertProperty1() {
underTest.saveProperty(propertyDto);
assertNoInteraction();
}
@Test
public void deleteProjectProperty() {
underTest.deleteProjectProperty(null, null, null, null, null, null);
assertNoInteraction();
}
@Test
public void deleteProjectProperty1() {
underTest.deleteProjectProperty(dbSession, null, null, null, null, null);
assertNoInteraction();
}
@Test
public void deleteGlobalProperty() {
underTest.deleteGlobalProperty(null, dbSession);
assertNoInteraction();
}
@Test
public void renamePropertyKey() {
underTest.renamePropertyKey(null, null);
assertNoInteraction();
}
@Test
public void saveProperty() {
underTest.saveProperty(oldPropertyDto);
assertNoInteraction();
}
private void assertNoInteraction() {
verifyNoMoreInteractions(myBatis, dbSession, propertyDto);
}
}
| 2,726 | 27.40625 | 110 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/httpd/CeHttpServerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.httpd;
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Properties;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.entity.StringEntity;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.process.sharedmemoryfile.DefaultProcessCommands;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.process.ProcessEntryPoint.PROPERTY_PROCESS_INDEX;
import static org.sonar.process.ProcessEntryPoint.PROPERTY_SHARED_PATH;
public class CeHttpServerTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private static final RuntimeException FAILING_ACTION = new IllegalStateException("Simulating the action failed");
private CeHttpServer underTest;
private File sharedDir;
@Before
public void setUp() throws Exception {
this.sharedDir = temp.newFolder();
Properties properties = new Properties();
properties.setProperty(PROPERTY_PROCESS_INDEX, "1");
properties.setProperty(PROPERTY_SHARED_PATH, sharedDir.getAbsolutePath());
underTest = new CeHttpServer(properties, Arrays.asList(new PomPomAction(), new FailingAction()));
underTest.start();
}
@After
public void tearDown() {
underTest.stop();
}
@Test
public void start_publishes_URL_in_IPC() {
try (DefaultProcessCommands commands = DefaultProcessCommands.secondary(this.sharedDir, 1)) {
assertThat(commands.getHttpUrl()).startsWith("http://127.0.0.1:");
}
}
@Test
public void return_http_response_with_code_404_and_exception_message_as_body_when_url_has_no_matching_action() throws IOException {
String action = "/dfdsfdsfsdsd";
Response response = call(underTest.getUrl() + action);
assertThat(response.code()).isEqualTo(404);
}
@Test
public void action_is_matched_on_exact_URL() throws IOException {
Response response = call(underTest.getUrl() + "/pompom");
assertIsPomPomResponse(response);
}
@Test
public void action_is_matched_on_URL_ignoring_case() throws IOException {
Response response = call(underTest.getUrl() + "/pOMpoM");
assertThat(response.code()).isEqualTo(404);
}
@Test
public void action_is_matched_on_URL_with_parameters() throws IOException {
Response response = call(underTest.getUrl() + "/pompom?toto=2");
assertIsPomPomResponse(response);
}
@Test
public void start_starts_http_server_and_publishes_URL_in_IPC() throws Exception {
Response response = call(underTest.getUrl() + "/pompom?toto=2");
assertIsPomPomResponse(response);
}
@Test
public void stop_stops_http_server() {
underTest.stop();
assertThatThrownBy(() -> call(underTest.getUrl()))
.isInstanceOfAny(ConnectException.class, SocketTimeoutException.class);
}
@Test
public void return_http_response_with_code_500_and_exception_message_as_body_when_action_throws_exception() throws IOException {
Response response = call(underTest.getUrl() + "/failing");
assertThat(response.code()).isEqualTo(500);
assertThat(response.body().string()).isEqualTo(FAILING_ACTION.getMessage());
}
private void assertIsPomPomResponse(Response response) throws IOException {
assertThat(response.code()).isEqualTo(200);
assertThat(IOUtils.toString(response.body().byteStream())).isEqualTo("ok");
}
private static Response call(String url) throws IOException {
Request request = new Request.Builder().get().url(url).build();
return new OkHttpClient().newCall(request).execute();
}
private static class PomPomAction implements HttpAction {
@Override
public String getContextPath() {
return "/pompom";
}
@Override
public void handle(HttpRequest request, HttpResponse response) {
response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK);
response.setEntity(new StringEntity("ok", StandardCharsets.UTF_8));
}
}
private static class FailingAction implements HttpAction {
@Override
public String getContextPath() {
return "/failing";
}
@Override
public void handle(HttpRequest request, HttpResponse response) {
throw FAILING_ACTION;
}
}
}
| 5,523 | 32.277108 | 133 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/httpd/CeHttpUtils.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.httpd;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.protocol.HttpContext;
import org.jetbrains.annotations.NotNull;
import org.mockito.ArgumentCaptor;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public final class CeHttpUtils {
private CeHttpUtils() {
// prevents instantiation
}
private static HttpResponse performRequestOnHandler(HttpAction handler, HttpRequest request) throws HttpException {
HttpResponse mockResponse = mock(HttpResponse.class);
HttpContext mockContext = mock(HttpContext.class);
handler.handle(request, mockResponse, mockContext);
return mockResponse;
}
@NotNull
private static HttpRequest buildGetRequest() {
return new BasicHttpRequest("GET", "");
}
@NotNull
private static HttpPost buildPostRequest(List<NameValuePair> urlArgs, List<NameValuePair> bodyArgs) {
final URI requestUri;
try {
requestUri = new URIBuilder()
.setScheme("http")
.setHost("localhost")
.addParameters(urlArgs)
.build();
} catch (URISyntaxException urise) {
throw new IllegalStateException("built URI is not valid, this should not be possible", urise);
}
HttpPost request = new HttpPost(requestUri);
request.setEntity(new UrlEncodedFormEntity(bodyArgs, StandardCharsets.UTF_8));
return request;
}
private static byte[] extractResponseBody(HttpResponse mockResponse) throws IOException {
final ArgumentCaptor<HttpEntity> httpEntityCaptor = ArgumentCaptor.forClass(HttpEntity.class);
verify(mockResponse).setEntity(httpEntityCaptor.capture());
return IOUtils.buffer(httpEntityCaptor.getValue().getContent()).readAllBytes();
}
private static void verifyStatusCode(int expectedCode, HttpResponse mockResponse) {
verify(mockResponse).setStatusLine(any(), eq(expectedCode));
}
public static void testHandlerForGetWithoutResponseBody(HttpAction handler, int expectedCode) throws HttpException {
HttpRequest request = buildGetRequest();
HttpResponse mockResponse = performRequestOnHandler(handler, request);
verifyStatusCode(expectedCode, mockResponse);
}
public static byte[] testHandlerForGetWithResponseBody(HttpAction handler, int expectedCode) throws HttpException, IOException {
HttpRequest request = buildGetRequest();
HttpResponse mockResponse = performRequestOnHandler(handler, request);
verifyStatusCode(expectedCode, mockResponse);
return extractResponseBody(mockResponse);
}
public static void testHandlerForPostWithoutResponseBody(
HttpAction httpAction, List<NameValuePair> urlArgs, List<NameValuePair> bodyArgs, int expectedCode) throws HttpException {
HttpPost request = buildPostRequest(urlArgs, bodyArgs);
HttpResponse mockResponse = performRequestOnHandler(httpAction, request);
verifyStatusCode(expectedCode, mockResponse);
}
public static byte[] testHandlerForPostWithResponseBody(
HttpAction httpAction, List<NameValuePair> urlArgs, List<NameValuePair> bodyArgs, int expectedCode) throws HttpException, IOException {
HttpPost request = buildPostRequest(urlArgs, bodyArgs);
HttpResponse mockResponse = performRequestOnHandler(httpAction, request);
verifyStatusCode(expectedCode, mockResponse);
return extractResponseBody(mockResponse);
}
}
| 4,833 | 39.966102 | 139 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/logging/CeProcessLoggingTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.logging;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.joran.spi.JoranException;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.stream.Stream;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.process.Props;
import org.sonar.process.logging.LogbackHelper;
import org.sonar.process.logging.PatternLayoutEncoder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.slf4j.Logger.ROOT_LOGGER_NAME;
import static org.sonar.process.ProcessProperties.Property.PATH_LOGS;
public class CeProcessLoggingTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private File logDir;
private Props props = new Props(new Properties());
private CeProcessLogging underTest = new CeProcessLogging();
@Before
public void setUp() throws IOException {
logDir = temp.newFolder();
props.set(PATH_LOGS.getKey(), logDir.getAbsolutePath());
}
@AfterClass
public static void resetLogback() throws JoranException {
new LogbackHelper().resetFromXml("/logback-test.xml");
}
@Test
public void do_not_log_to_console() {
LoggerContext ctx = underTest.configure(props);
Logger root = ctx.getLogger(Logger.ROOT_LOGGER_NAME);
Appender appender = root.getAppender("CONSOLE");
assertThat(appender).isNull();
}
@Test
public void startup_logger_prints_to_only_to_system_out() {
LoggerContext ctx = underTest.configure(props);
Logger startup = ctx.getLogger("startup");
assertThat(startup.isAdditive()).isFalse();
Appender appender = startup.getAppender("CONSOLE");
assertThat(appender).isInstanceOf(ConsoleAppender.class);
ConsoleAppender<ILoggingEvent> consoleAppender = (ConsoleAppender<ILoggingEvent>) appender;
assertThat(consoleAppender.getTarget()).isEqualTo("System.out");
assertThat(consoleAppender.getEncoder()).isInstanceOf(PatternLayoutEncoder.class);
PatternLayoutEncoder patternEncoder = (PatternLayoutEncoder) consoleAppender.getEncoder();
assertThat(patternEncoder.getPattern()).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level app[][%logger{20}] %msg%n");
}
@Test
public void log_to_ce_file() {
LoggerContext ctx = underTest.configure(props);
Logger root = ctx.getLogger(Logger.ROOT_LOGGER_NAME);
Appender<ILoggingEvent> appender = root.getAppender("file_ce");
assertThat(appender).isInstanceOf(FileAppender.class);
FileAppender fileAppender = (FileAppender) appender;
assertThat(fileAppender.getFile()).isEqualTo(new File(logDir, "ce.log").getAbsolutePath());
assertThat(fileAppender.getEncoder()).isInstanceOf(PatternLayoutEncoder.class);
PatternLayoutEncoder encoder = (PatternLayoutEncoder) fileAppender.getEncoder();
assertThat(encoder.getPattern()).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level ce[%X{ceTaskUuid}][%logger{20}] %msg%n");
}
@Test
public void default_level_for_root_logger_is_INFO() {
LoggerContext ctx = underTest.configure(props);
verifyRootLogLevel(ctx, Level.INFO);
}
@Test
public void root_logger_level_changes_with_global_property() {
props.set("sonar.log.level", "TRACE");
LoggerContext ctx = underTest.configure(props);
verifyRootLogLevel(ctx, Level.TRACE);
}
@Test
public void root_logger_level_changes_with_ce_property() {
props.set("sonar.log.level.ce", "TRACE");
LoggerContext ctx = underTest.configure(props);
verifyRootLogLevel(ctx, Level.TRACE);
}
@Test
public void root_logger_level_is_configured_from_ce_property_over_global_property() {
props.set("sonar.log.level", "TRACE");
props.set("sonar.log.level.ce", "DEBUG");
LoggerContext ctx = underTest.configure(props);
verifyRootLogLevel(ctx, Level.DEBUG);
}
@Test
public void root_logger_level_changes_with_ce_property_and_is_case_insensitive() {
props.set("sonar.log.level.ce", "debug");
LoggerContext ctx = underTest.configure(props);
verifyRootLogLevel(ctx, Level.DEBUG);
}
@Test
public void sql_logger_level_changes_with_global_property_and_is_case_insensitive() {
props.set("sonar.log.level", "InFO");
LoggerContext ctx = underTest.configure(props);
verifySqlLogLevel(ctx, Level.INFO);
}
@Test
public void sql_logger_level_changes_with_ce_property_and_is_case_insensitive() {
props.set("sonar.log.level.ce", "TrACe");
LoggerContext ctx = underTest.configure(props);
verifySqlLogLevel(ctx, Level.TRACE);
}
@Test
public void sql_logger_level_changes_with_ce_sql_property_and_is_case_insensitive() {
props.set("sonar.log.level.ce.sql", "debug");
LoggerContext ctx = underTest.configure(props);
verifySqlLogLevel(ctx, Level.DEBUG);
}
@Test
public void sql_logger_level_is_configured_from_ce_sql_property_over_ce_property() {
props.set("sonar.log.level.ce.sql", "debug");
props.set("sonar.log.level.ce", "TRACE");
LoggerContext ctx = underTest.configure(props);
verifySqlLogLevel(ctx, Level.DEBUG);
}
@Test
public void sql_logger_level_is_configured_from_ce_sql_property_over_global_property() {
props.set("sonar.log.level.ce.sql", "debug");
props.set("sonar.log.level", "TRACE");
LoggerContext ctx = underTest.configure(props);
verifySqlLogLevel(ctx, Level.DEBUG);
}
@Test
public void sql_logger_level_is_configured_from_ce_property_over_global_property() {
props.set("sonar.log.level.ce", "debug");
props.set("sonar.log.level", "TRACE");
LoggerContext ctx = underTest.configure(props);
verifySqlLogLevel(ctx, Level.DEBUG);
}
@Test
public void es_logger_level_changes_with_global_property_and_is_case_insensitive() {
props.set("sonar.log.level", "InFO");
LoggerContext ctx = underTest.configure(props);
verifyEsLogLevel(ctx, Level.INFO);
}
@Test
public void es_logger_level_changes_with_ce_property_and_is_case_insensitive() {
props.set("sonar.log.level.ce", "TrACe");
LoggerContext ctx = underTest.configure(props);
verifyEsLogLevel(ctx, Level.TRACE);
}
@Test
public void es_logger_level_changes_with_ce_es_property_and_is_case_insensitive() {
props.set("sonar.log.level.ce.es", "debug");
LoggerContext ctx = underTest.configure(props);
verifyEsLogLevel(ctx, Level.DEBUG);
}
@Test
public void es_logger_level_is_configured_from_ce_es_property_over_ce_property() {
props.set("sonar.log.level.ce.es", "debug");
props.set("sonar.log.level.ce", "TRACE");
LoggerContext ctx = underTest.configure(props);
verifyEsLogLevel(ctx, Level.DEBUG);
}
@Test
public void es_logger_level_is_configured_from_ce_es_property_over_global_property() {
props.set("sonar.log.level.ce.es", "debug");
props.set("sonar.log.level", "TRACE");
LoggerContext ctx = underTest.configure(props);
verifyEsLogLevel(ctx, Level.DEBUG);
}
@Test
public void es_logger_level_is_configured_from_ce_property_over_global_property() {
props.set("sonar.log.level.ce", "debug");
props.set("sonar.log.level", "TRACE");
LoggerContext ctx = underTest.configure(props);
verifyEsLogLevel(ctx, Level.DEBUG);
}
@Test
public void jmx_logger_level_changes_with_global_property_and_is_case_insensitive() {
props.set("sonar.log.level", "InFO");
LoggerContext ctx = underTest.configure(props);
verifyJmxLogLevel(ctx, Level.INFO);
}
@Test
public void jmx_logger_level_changes_with_jmx_property_and_is_case_insensitive() {
props.set("sonar.log.level.ce", "TrACe");
LoggerContext ctx = underTest.configure(props);
verifyJmxLogLevel(ctx, Level.TRACE);
}
@Test
public void jmx_logger_level_changes_with_ce_jmx_property_and_is_case_insensitive() {
props.set("sonar.log.level.ce.jmx", "debug");
LoggerContext ctx = underTest.configure(props);
verifyJmxLogLevel(ctx, Level.DEBUG);
}
@Test
public void jmx_logger_level_is_configured_from_ce_jmx_property_over_ce_property() {
props.set("sonar.log.level.ce.jmx", "debug");
props.set("sonar.log.level.ce", "TRACE");
LoggerContext ctx = underTest.configure(props);
verifyJmxLogLevel(ctx, Level.DEBUG);
}
@Test
public void jmx_logger_level_is_configured_from_ce_jmx_property_over_global_property() {
props.set("sonar.log.level.ce.jmx", "debug");
props.set("sonar.log.level", "TRACE");
LoggerContext ctx = underTest.configure(props);
verifyJmxLogLevel(ctx, Level.DEBUG);
}
@Test
public void jmx_logger_level_is_configured_from_ce_property_over_global_property() {
props.set("sonar.log.level.ce", "debug");
props.set("sonar.log.level", "TRACE");
LoggerContext ctx = underTest.configure(props);
verifyJmxLogLevel(ctx, Level.DEBUG);
}
@Test
public void root_logger_level_defaults_to_INFO_if_ce_property_has_invalid_value() {
props.set("sonar.log.level.ce", "DodoDouh!");
LoggerContext ctx = underTest.configure(props);
verifyRootLogLevel(ctx, Level.INFO);
}
@Test
public void sql_logger_level_defaults_to_INFO_if_ce_sql_property_has_invalid_value() {
props.set("sonar.log.level.ce.sql", "DodoDouh!");
LoggerContext ctx = underTest.configure(props);
verifySqlLogLevel(ctx, Level.INFO);
}
@Test
public void es_logger_level_defaults_to_INFO_if_ce_es_property_has_invalid_value() {
props.set("sonar.log.level.ce.es", "DodoDouh!");
LoggerContext ctx = underTest.configure(props);
verifyEsLogLevel(ctx, Level.INFO);
}
@Test
public void jmx_loggers_level_defaults_to_INFO_if_ce_jmx_property_has_invalid_value() {
props.set("sonar.log.level.ce.jmx", "DodoDouh!");
LoggerContext ctx = underTest.configure(props);
verifyJmxLogLevel(ctx, Level.INFO);
}
@Test
public void fail_with_IAE_if_global_property_unsupported_level() {
props.set("sonar.log.level", "ERROR");
assertThatThrownBy(() -> underTest.configure(props))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("log level ERROR in property sonar.log.level is not a supported value (allowed levels are [TRACE, DEBUG, INFO])");
}
@Test
public void fail_with_IAE_if_ce_property_unsupported_level() {
props.set("sonar.log.level.ce", "ERROR");
assertThatThrownBy(() -> underTest.configure(props))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("log level ERROR in property sonar.log.level.ce is not a supported value (allowed levels are [TRACE, DEBUG, INFO])");
}
@Test
public void fail_with_IAE_if_ce_sql_property_unsupported_level() {
props.set("sonar.log.level.ce.sql", "ERROR");
assertThatThrownBy(() -> underTest.configure(props))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("log level ERROR in property sonar.log.level.ce.sql is not a supported value (allowed levels are [TRACE, DEBUG, INFO])");
}
@Test
public void fail_with_IAE_if_ce_es_property_unsupported_level() {
props.set("sonar.log.level.ce.es", "ERROR");
assertThatThrownBy(() -> underTest.configure(props))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("log level ERROR in property sonar.log.level.ce.es is not a supported value (allowed levels are [TRACE, DEBUG, INFO])");
}
@Test
public void fail_with_IAE_if_ce_jmx_property_unsupported_level() {
props.set("sonar.log.level.ce.jmx", "ERROR");
assertThatThrownBy(() -> underTest.configure(props))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("log level ERROR in property sonar.log.level.ce.jmx is not a supported value (allowed levels are [TRACE, DEBUG, INFO])");
}
@Test
public void configure_defines_hardcoded_levels() {
LoggerContext context = underTest.configure(props);
verifyImmutableLogLevels(context);
}
@Test
public void configure_defines_hardcoded_levels_unchanged_by_global_property() {
props.set("sonar.log.level", "TRACE");
LoggerContext context = underTest.configure(props);
verifyImmutableLogLevels(context);
}
@Test
public void configure_defines_hardcoded_levels_unchanged_by_ce_property() {
props.set("sonar.log.level.ce", "TRACE");
LoggerContext context = underTest.configure(props);
verifyImmutableLogLevels(context);
}
@Test
public void configure_turns_off_some_MsSQL_driver_logger() {
LoggerContext context = underTest.configure(props);
Stream.of("com.microsoft.sqlserver.jdbc.internals",
"com.microsoft.sqlserver.jdbc.ResultSet",
"com.microsoft.sqlserver.jdbc.Statement",
"com.microsoft.sqlserver.jdbc.Connection")
.forEach(loggerName -> assertThat(context.getLogger(loggerName).getLevel()).isEqualTo(Level.OFF));
}
private void verifyRootLogLevel(LoggerContext ctx, Level expected) {
assertThat(ctx.getLogger(ROOT_LOGGER_NAME).getLevel()).isEqualTo(expected);
}
private void verifySqlLogLevel(LoggerContext ctx, Level expected) {
assertThat(ctx.getLogger("sql").getLevel()).isEqualTo(expected);
}
private void verifyEsLogLevel(LoggerContext ctx, Level expected) {
assertThat(ctx.getLogger("es").getLevel()).isEqualTo(expected);
}
private void verifyJmxLogLevel(LoggerContext ctx, Level expected) {
assertThat(ctx.getLogger("javax.management.remote.timeout").getLevel()).isEqualTo(expected);
assertThat(ctx.getLogger("javax.management.remote.misc").getLevel()).isEqualTo(expected);
assertThat(ctx.getLogger("javax.management.remote.rmi").getLevel()).isEqualTo(expected);
assertThat(ctx.getLogger("javax.management.mbeanserver").getLevel()).isEqualTo(expected);
assertThat(ctx.getLogger("sun.rmi.loader").getLevel()).isEqualTo(expected);
assertThat(ctx.getLogger("sun.rmi.transport.tcp").getLevel()).isEqualTo(expected);
assertThat(ctx.getLogger("sun.rmi.transport.misc").getLevel()).isEqualTo(expected);
assertThat(ctx.getLogger("sun.rmi.server.call").getLevel()).isEqualTo(expected);
assertThat(ctx.getLogger("sun.rmi.dgc").getLevel()).isEqualTo(expected);
}
private void verifyImmutableLogLevels(LoggerContext ctx) {
assertThat(ctx.getLogger("org.apache.ibatis").getLevel()).isEqualTo(Level.WARN);
assertThat(ctx.getLogger("java.sql").getLevel()).isEqualTo(Level.WARN);
assertThat(ctx.getLogger("java.sql.ResultSet").getLevel()).isEqualTo(Level.WARN);
assertThat(ctx.getLogger("org.elasticsearch").getLevel()).isEqualTo(Level.INFO);
assertThat(ctx.getLogger("org.elasticsearch.node").getLevel()).isEqualTo(Level.INFO);
assertThat(ctx.getLogger("org.elasticsearch.http").getLevel()).isEqualTo(Level.INFO);
assertThat(ctx.getLogger("ch.qos.logback").getLevel()).isEqualTo(Level.WARN);
assertThat(ctx.getLogger("org.apache.catalina").getLevel()).isEqualTo(Level.INFO);
assertThat(ctx.getLogger("org.apache.coyote").getLevel()).isEqualTo(Level.INFO);
assertThat(ctx.getLogger("org.apache.jasper").getLevel()).isEqualTo(Level.INFO);
assertThat(ctx.getLogger("org.apache.tomcat").getLevel()).isEqualTo(Level.INFO);
}
}
| 16,285 | 33.504237 | 139 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/logging/ChangeLogLevelHttpActionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.logging;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.http.HttpException;
import org.apache.http.HttpStatus;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Test;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.httpd.CeHttpUtils;
import org.sonar.server.log.ServerLogging;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class ChangeLogLevelHttpActionTest {
private ServerLogging serverLogging = mock(ServerLogging.class);
private ChangeLogLevelHttpAction underTest = new ChangeLogLevelHttpAction(serverLogging);
@Test
public void serves_METHOD_NOT_ALLOWED_error_when_method_is_not_POST() throws HttpException, IOException {
CeHttpUtils.testHandlerForGetWithoutResponseBody(underTest, HttpStatus.SC_METHOD_NOT_ALLOWED);
}
@Test
public void serves_BAD_REQUEST_error_when_parameter_level_is_missing() throws IOException, HttpException {
byte[] responseBody = CeHttpUtils.testHandlerForPostWithResponseBody(underTest, List.of(), List.of(), HttpStatus.SC_BAD_REQUEST);
assertThat(new String(responseBody, StandardCharsets.UTF_8)).isEqualTo("Parameter 'level' is missing");
}
@Test
public void serves_BAD_REQUEST_error_when_value_of_parameter_level_is_not_LEVEL_in_uppercase() throws IOException, HttpException {
byte[] responseBody = CeHttpUtils.testHandlerForPostWithResponseBody(
underTest, List.of(new BasicNameValuePair("level", "info")), List.of(), HttpStatus.SC_BAD_REQUEST);
assertThat(new String(responseBody, StandardCharsets.UTF_8)).isEqualTo("Value 'info' for parameter 'level' is invalid");
}
@Test
public void changes_server_logging_if_level_is_ERROR() throws HttpException, IOException {
CeHttpUtils.testHandlerForPostWithoutResponseBody(
underTest, List.of(new BasicNameValuePair("level", "ERROR")), List.of(), HttpStatus.SC_OK);
verify(serverLogging).changeLevel(LoggerLevel.ERROR);
}
@Test
public void changes_server_logging_if_level_is_INFO() throws HttpException, IOException {
CeHttpUtils.testHandlerForPostWithoutResponseBody(
underTest, List.of(new BasicNameValuePair("level", "INFO")), List.of(), HttpStatus.SC_OK);
verify(serverLogging).changeLevel(LoggerLevel.INFO);
}
@Test
public void changes_server_logging_if_level_is_DEBUG() throws HttpException, IOException {
CeHttpUtils.testHandlerForPostWithoutResponseBody(
underTest, List.of(new BasicNameValuePair("level", "DEBUG")), List.of(), HttpStatus.SC_OK);
verify(serverLogging).changeLevel(LoggerLevel.DEBUG);
}
@Test
public void changes_server_logging_if_level_is_TRACE() throws HttpException, IOException {
CeHttpUtils.testHandlerForPostWithoutResponseBody(
underTest, List.of(new BasicNameValuePair("level", "TRACE")), List.of(), HttpStatus.SC_OK);
verify(serverLogging).changeLevel(LoggerLevel.TRACE);
}
}
| 3,891 | 41.769231 | 133 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/monitoring/CEQueueStatusImplConcurrentTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.monitoring;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class CEQueueStatusImplConcurrentTest {
private ExecutorService executorService = Executors.newFixedThreadPool(10, new ThreadFactory() {
private int cnt = 0;
@Override
public Thread newThread(Runnable r) {
return new Thread(r, CEQueueStatusImplConcurrentTest.class.getSimpleName() + cnt++);
}
});
private CEQueueStatusImpl underTest = new CEQueueStatusImpl(mock(DbClient.class), mock(System2.class));
@After
public void tearDown() {
executorService.shutdownNow();
}
@Test
public void test_concurrent_modifications_in_any_order() throws InterruptedException {
for (Runnable runnable : buildShuffleCallsToUnderTest()) {
executorService.submit(runnable);
}
executorService.awaitTermination(1, TimeUnit.SECONDS);
assertThat(underTest.getInProgressCount()).isOne();
assertThat(underTest.getErrorCount()).isEqualTo(17);
assertThat(underTest.getSuccessCount()).isEqualTo(80);
assertThat(underTest.getProcessingTime()).isEqualTo(177);
}
private List<Runnable> buildShuffleCallsToUnderTest() {
List<Runnable> res = new ArrayList<>();
for (int i = 0; i < 98; i++) {
res.add(new AddInProgressRunnable());
}
for (int i = 0; i < 80; i++) {
res.add(new AddSuccessRunnable());
}
for (int i = 0; i < 17; i++) {
res.add(new AddErrorRunnable());
}
Collections.shuffle(res);
return res;
}
private class AddInProgressRunnable implements Runnable {
@Override
public void run() {
underTest.addInProgress();
}
}
private class AddErrorRunnable implements Runnable {
@Override
public void run() {
underTest.addError(1);
}
}
private class AddSuccessRunnable implements Runnable {
@Override
public void run() {
underTest.addSuccess(2);
}
}
}
| 3,169 | 29.776699 | 105 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/monitoring/CEQueueStatusImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.monitoring;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.ce.CeQueueDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CEQueueStatusImplTest extends CommonCEQueueStatusImplTest {
private CEQueueStatusImpl underTest = new CEQueueStatusImpl(getDbClient(), mock(System2.class));
public CEQueueStatusImplTest() {
super(mock(DbClient.class, Mockito.RETURNS_DEEP_STUBS));
}
@Override
protected CEQueueStatusImpl getUnderTest() {
return underTest;
}
@Test
public void count_Pending_from_database() {
when(getDbClient().ceQueueDao().countByStatus(any(), eq(CeQueueDto.Status.PENDING))).thenReturn(42);
assertThat(underTest.getPendingCount()).isEqualTo(42);
}
}
| 1,849 | 33.90566 | 104 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/monitoring/CeTasksMBeanImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.monitoring;
import com.google.common.collect.ImmutableSet;
import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.Optional;
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.CheckForNull;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import org.sonar.ce.configuration.CeConfiguration;
import org.sonar.ce.taskprocessor.CeWorker;
import org.sonar.ce.taskprocessor.CeWorkerController;
import org.sonar.ce.taskprocessor.CeWorkerFactory;
import org.sonar.process.Jmx;
import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.ce.monitoring.CeTasksMBean.OBJECT_NAME;
public class CeTasksMBeanImplTest {
private static final long PENDING_COUNT = 2;
private static final long PENDING_TIME = 10_000L;
private static final long IN_PROGRESS_COUNT = 5;
private static final long ERROR_COUNT = 10;
private static final long SUCCESS_COUNT = 13;
private static final long PROCESSING_TIME = 987;
private static final int WORKER_MAX_COUNT = 666;
private static final int WORKER_COUNT = 56;
private static final Set<CeWorker> WORKERS = IntStream.range(0, 2 + new Random().nextInt(10))
.mapToObj(i -> RandomStringUtils.randomAlphabetic(15))
.map(uuid -> {
CeWorker res = mock(CeWorker.class);
when(res.getUUID()).thenReturn(uuid);
return res;
})
.collect(Collectors.toSet());
private final CeWorkerController ceWorkerController = mock(CeWorkerController.class);
private final CeTasksMBeanImpl underTest = new CeTasksMBeanImpl(new DumbCEQueueStatus(), new DumbCeConfiguration(), new DumbCeWorkerFactory(), ceWorkerController);
@BeforeClass
public static void beforeClass() {
// if any other class starts a container where CeTasksMBeanImpl is added, it will have been registered
Jmx.unregister(OBJECT_NAME);
}
@Test
public void register_and_unregister() throws Exception {
assertThat(getMBean()).isNull();
underTest.start();
assertThat(getMBean()).isNotNull();
underTest.stop();
assertThat(getMBean()).isNull();
}
/**
* Dumb implementation of CEQueueStatus which returns constant values for get methods and throws UnsupportedOperationException
* for other methods.
*/
@CheckForNull
private ObjectInstance getMBean() throws Exception {
try {
return ManagementFactory.getPlatformMBeanServer().getObjectInstance(new ObjectName(OBJECT_NAME));
} catch (InstanceNotFoundException e) {
return null;
}
}
@Test
public void get_methods_delegate_to_the_CEQueueStatus_instance() {
assertThat(underTest.getPendingCount()).isEqualTo(PENDING_COUNT);
assertThat(underTest.getLongestTimePending()).isEqualTo(PENDING_TIME);
assertThat(underTest.getInProgressCount()).isEqualTo(IN_PROGRESS_COUNT);
assertThat(underTest.getErrorCount()).isEqualTo(ERROR_COUNT);
assertThat(underTest.getSuccessCount()).isEqualTo(SUCCESS_COUNT);
assertThat(underTest.getProcessingTime()).isEqualTo(PROCESSING_TIME);
}
@Test
public void getWorkerCount_delegates_to_the_CEConfiguration_instance() {
assertThat(underTest.getWorkerCount()).isEqualTo(WORKER_COUNT);
}
@Test
public void getWorkerMaxCount_delegates_to_the_CEConfiguration_instance() {
assertThat(underTest.getWorkerMaxCount()).isEqualTo(WORKER_MAX_COUNT);
}
@Test
public void getWorkerUuids_returns_ordered_list_of_uuids_of_worker_from_CeWorkerFactory_instance() {
List<String> workerUuids = underTest.getWorkerUuids();
assertThat(workerUuids).
isEqualTo(WORKERS.stream().map(CeWorker::getUUID).sorted().toList())
// ImmutableSet can not be serialized
.isNotInstanceOf(ImmutableSet.class);
}
@Test
public void getEnabledWorkerUuids_returns_ordered_list_of_uuids_of_worker_from_CeWorkerFactory_instance_filtered_on_enabled_ones() {
int enabledWorkerCount = new Random().nextInt(WORKERS.size());
int i = 0;
CeWorker[] enabledWorkers = new CeWorker[enabledWorkerCount];
for (CeWorker worker : WORKERS) {
if (i < enabledWorkerCount) {
enabledWorkers[i] = worker;
when(ceWorkerController.isEnabled(worker)).thenReturn(true);
} else {
when(ceWorkerController.isEnabled(worker)).thenReturn(false);
}
i++;
}
List<String> enabledWorkerUuids = underTest.getEnabledWorkerUuids();
assertThat(enabledWorkerUuids)
.isEqualTo(Stream.of(enabledWorkers).map(CeWorker::getUUID).sorted().toList())
// ImmutableSet can not be serialized
.isNotInstanceOf(ImmutableSet.class);
}
@Test
public void export_system_info() {
ProtobufSystemInfo.Section section = underTest.toProtobuf();
assertThat(section.getName()).isEqualTo("Compute Engine Tasks");
assertThat(section.getAttributesCount()).isEqualTo(9);
}
private static class DumbCEQueueStatus implements CEQueueStatus {
@Override
public long getPendingCount() {
return PENDING_COUNT;
}
@Override
public Optional<Long> getLongestTimePending() {
return Optional.of(PENDING_TIME);
}
@Override
public long addInProgress() {
return methodNotImplemented();
}
@Override
public long getInProgressCount() {
return IN_PROGRESS_COUNT;
}
@Override
public long addError(long processingTime) {
return methodNotImplemented();
}
@Override
public long getErrorCount() {
return ERROR_COUNT;
}
@Override
public long addSuccess(long processingTime) {
return methodNotImplemented();
}
@Override
public long getSuccessCount() {
return SUCCESS_COUNT;
}
@Override
public long getProcessingTime() {
return PROCESSING_TIME;
}
@Override
public boolean areWorkersPaused() {
return false;
}
private long methodNotImplemented() {
throw new UnsupportedOperationException("Not Implemented");
}
}
private static class DumbCeConfiguration implements CeConfiguration {
@Override
public int getWorkerMaxCount() {
return WORKER_MAX_COUNT;
}
@Override
public int getWorkerCount() {
return WORKER_COUNT;
}
@Override
public long getQueuePollingDelay() {
throw new UnsupportedOperationException("getQueuePollingDelay is not implemented");
}
@Override
public long getCleanTasksInitialDelay() {
throw new UnsupportedOperationException("getCleanCeTasksInitialDelay is not implemented");
}
@Override
public long getCleanTasksDelay() {
throw new UnsupportedOperationException("getCleanCeTasksDelay is not implemented");
}
@Override
public long getGracefulStopTimeoutInMs() {
return 6 * 60 * 60 * 1_000L;
}
}
private static class DumbCeWorkerFactory implements CeWorkerFactory {
@Override
public CeWorker create(int ordinal) {
throw new UnsupportedOperationException("create should not be called");
}
@Override
public Set<CeWorker> getWorkers() {
return WORKERS;
}
}
}
| 8,351 | 30.516981 | 165 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/monitoring/CommonCEQueueStatusImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.monitoring;
import java.util.Optional;
import java.util.Random;
import org.junit.Test;
import org.sonar.db.DbClient;
import org.sonar.server.property.InternalProperties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
public abstract class CommonCEQueueStatusImplTest {
private static final int SOME_RANDOM_MAX = 96535;
private static final int SOME_PROCESSING_TIME = 8723;
private DbClient dbClient;
protected CommonCEQueueStatusImplTest(DbClient dbClient) {
this.dbClient = dbClient;
}
public DbClient getDbClient() {
return dbClient;
}
protected abstract CEQueueStatusImpl getUnderTest();
@Test
public void verify_just_created_instance_metrics() {
assertThat(getUnderTest().getInProgressCount()).isZero();
assertThat(getUnderTest().getErrorCount()).isZero();
assertThat(getUnderTest().getSuccessCount()).isZero();
assertThat(getUnderTest().getProcessingTime()).isZero();
}
@Test
public void addInProgress_increases_InProgress() {
getUnderTest().addInProgress();
assertThat(getUnderTest().getInProgressCount()).isOne();
assertThat(getUnderTest().getErrorCount()).isZero();
assertThat(getUnderTest().getSuccessCount()).isZero();
assertThat(getUnderTest().getProcessingTime()).isZero();
}
@Test
public void addInProgress_any_number_of_call_change_by_1_per_call() {
int calls = new Random().nextInt(SOME_RANDOM_MAX);
for (int i = 0; i < calls; i++) {
getUnderTest().addInProgress();
}
assertThat(getUnderTest().getInProgressCount()).isEqualTo(calls);
assertThat(getUnderTest().getProcessingTime()).isZero();
}
@Test
public void addError_throws_IAE_if_time_is_less_than_0() {
assertThatThrownBy(() -> getUnderTest().addError(-1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Processing time can not be < 0");
}
@Test
public void addError_increases_Error_and_decreases_InProgress_by_1_without_check_on_InProgress() {
getUnderTest().addError(SOME_PROCESSING_TIME);
assertThat(getUnderTest().getInProgressCount()).isEqualTo(-1);
assertThat(getUnderTest().getErrorCount()).isOne();
assertThat(getUnderTest().getSuccessCount()).isZero();
assertThat(getUnderTest().getProcessingTime()).isEqualTo(SOME_PROCESSING_TIME);
}
@Test
public void addError_any_number_of_call_change_by_1_per_call() {
int calls = new Random().nextInt(SOME_RANDOM_MAX);
for (int i = 0; i < calls; i++) {
getUnderTest().addError(1);
}
assertThat(getUnderTest().getErrorCount()).isEqualTo(calls);
assertThat(getUnderTest().getInProgressCount()).isEqualTo(-calls);
assertThat(getUnderTest().getProcessingTime()).isEqualTo(calls);
}
@Test
public void addSuccess_throws_IAE_if_time_is_less_than_0() {
assertThatThrownBy(() -> getUnderTest().addSuccess(-1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Processing time can not be < 0");
}
@Test
public void addSuccess_increases_Error_and_decreases_InProgress_by_1_without_check_on_InProgress() {
getUnderTest().addSuccess(SOME_PROCESSING_TIME);
assertThat(getUnderTest().getInProgressCount()).isEqualTo(-1);
assertThat(getUnderTest().getErrorCount()).isZero();
assertThat(getUnderTest().getSuccessCount()).isOne();
assertThat(getUnderTest().getProcessingTime()).isEqualTo(SOME_PROCESSING_TIME);
}
@Test
public void addSuccess_any_number_of_call_change_by_1_per_call() {
int calls = new Random().nextInt(SOME_RANDOM_MAX);
for (int i = 0; i < calls; i++) {
getUnderTest().addSuccess(1);
}
assertThat(getUnderTest().getSuccessCount()).isEqualTo(calls);
assertThat(getUnderTest().getInProgressCount()).isEqualTo(-calls);
assertThat(getUnderTest().getProcessingTime()).isEqualTo(calls);
}
@Test
public void workers_pause_is_loaded_from_db() {
when(dbClient.internalPropertiesDao().selectByKey(any(), eq(InternalProperties.COMPUTE_ENGINE_PAUSE))).thenReturn(Optional.of("true"));
assertThat(getUnderTest().areWorkersPaused()).isTrue();
}
@Test
public void workers_pause_is_false_by_default() {
assertThat(getUnderTest().areWorkersPaused()).isFalse();
}
}
| 5,281 | 34.689189 | 139 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/platform/CECoreExtensionsInstallerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.platform;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.stream.Stream;
import org.junit.Test;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.ScannerSide;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.server.ServerSide;
import org.sonar.core.extension.CoreExtension;
import org.sonar.core.extension.CoreExtensionRepository;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.core.extension.CoreExtensionsInstaller.noAdditionalSideFilter;
import static org.sonar.core.extension.CoreExtensionsInstaller.noExtensionFilter;
public class CECoreExtensionsInstallerTest {
private SonarRuntime sonarRuntime = mock(SonarRuntime.class);
private CoreExtensionRepository coreExtensionRepository = mock(CoreExtensionRepository.class);
private CECoreExtensionsInstaller underTest = new CECoreExtensionsInstaller(sonarRuntime, coreExtensionRepository);
@Test
public void install_only_adds_ComputeEngineSide_annotated_extension_to_container() {
when(coreExtensionRepository.loadedCoreExtensions()).thenReturn(Stream.of(
new CoreExtension() {
@Override
public String getName() {
return "foo";
}
@Override
public void load(Context context) {
context.addExtensions(CeClass.class, ScannerClass.class, WebServerClass.class,
NoAnnotationClass.class, OtherAnnotationClass.class, MultipleAnnotationClass.class);
}
}));
ListContainer container = new ListContainer();
underTest.install(container, noExtensionFilter(), noAdditionalSideFilter());
assertThat(container.getAddedObjects())
.hasSize(2)
.contains(CeClass.class, MultipleAnnotationClass.class);
}
@ComputeEngineSide
public static final class CeClass {
}
@ServerSide
public static final class WebServerClass {
}
@ScannerSide
public static final class ScannerClass {
}
@ServerSide
@ComputeEngineSide
@ScannerSide
public static final class MultipleAnnotationClass {
}
public static final class NoAnnotationClass {
}
@DarkSide
public static final class OtherAnnotationClass {
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DarkSide {
}
}
| 3,441 | 30.009009 | 117 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/platform/DatabaseCompatibilityTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.platform;
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 org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.server.platform.db.migration.version.DatabaseVersion;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
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.platform.db.migration.version.DatabaseVersion.Status.FRESH_INSTALL;
import static org.sonar.server.platform.db.migration.version.DatabaseVersion.Status.UP_TO_DATE;
@RunWith(DataProviderRunner.class)
public class DatabaseCompatibilityTest {
private DatabaseVersion databaseVersion = mock(DatabaseVersion.class);
private DatabaseCompatibility underTest = new DatabaseCompatibility(databaseVersion);
@Test
@UseDataProvider("anyStatusButUpToDateOrFreshInstall")
public void start_throws_ISE_if_status_is_not_UP_TO_DATE_nor_FRESH_INSTALL(DatabaseVersion.Status status) {
when(databaseVersion.getStatus()).thenReturn(status);
assertThatThrownBy(() -> underTest.start())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Compute Engine can't start unless Database is up to date");
}
@DataProvider
public static Object[][] anyStatusButUpToDateOrFreshInstall() {
return Arrays.stream(DatabaseVersion.Status.values())
.filter(t -> t != UP_TO_DATE && t != FRESH_INSTALL)
.map(t -> new Object[] {t})
.toArray(Object[][]::new);
}
@Test
public void start_has_no_effect_if_status_is_UP_TO_DATE() {
when(databaseVersion.getStatus()).thenReturn(UP_TO_DATE);
underTest.start();
verify(databaseVersion).getStatus();
verifyNoMoreInteractions(databaseVersion);
}
@Test
public void start_has_no_effect_if_status_is_FRESH_INSTALL() {
when(databaseVersion.getStatus()).thenReturn(DatabaseVersion.Status.FRESH_INSTALL);
underTest.start();
verify(databaseVersion).getStatus();
verifyNoMoreInteractions(databaseVersion);
}
@Test
public void stop_has_no_effect() {
underTest.stop();
verifyNoInteractions(databaseVersion);
}
}
| 3,278 | 35.433333 | 109 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/queue/CeQueueInitializerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.queue;
import org.junit.Test;
import org.sonar.api.platform.Server;
import org.sonar.ce.CeDistributedInformation;
import org.sonar.ce.cleaning.CeCleaningScheduler;
import org.sonar.ce.taskprocessor.CeProcessingScheduler;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
public class CeQueueInitializerTest {
private Server server = mock(Server.class);
private CeProcessingScheduler processingScheduler = mock(CeProcessingScheduler.class);
private CeCleaningScheduler cleaningScheduler = mock(CeCleaningScheduler.class);
private CeQueueInitializer underTest = new CeQueueInitializer(processingScheduler, cleaningScheduler, mock(CeDistributedInformation.class));
@Test
public void clean_queue_then_start_scheduler_of_workers() {
underTest.onServerStart(server);
verify(processingScheduler).startScheduling();
verify(cleaningScheduler).startScheduling();
}
@Test
public void onServerStart_has_no_effect_if_called_twice_to_support_medium_test_doing_startup_tasks_multiple_times() {
underTest.onServerStart(server);
reset(processingScheduler, cleaningScheduler);
underTest.onServerStart(server);
verifyNoInteractions(processingScheduler, cleaningScheduler);
}
}
| 2,209 | 36.457627 | 142 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/queue/PurgeCeActivitiesTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.queue;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.purge.PurgeDao;
import org.sonar.db.purge.PurgeProfiler;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class PurgeCeActivitiesTest {
private DbClient dbClient = mock(DbClient.class);
private PurgeDao purgeDao = mock(PurgeDao.class);
private DbSession dbSession = mock(DbSession.class);
private PurgeProfiler profiler = mock(PurgeProfiler.class);
private PurgeCeActivities underTest = new PurgeCeActivities(dbClient, profiler);
@Test
public void starts_calls_purgeDao_and_commit() {
when(dbClient.purgeDao()).thenReturn(purgeDao);
when(dbClient.openSession(false)).thenReturn(dbSession);
underTest.start();
InOrder inOrder = Mockito.inOrder(purgeDao, dbSession);
inOrder.verify(purgeDao).purgeCeActivities(dbSession, profiler);
inOrder.verify(purgeDao).purgeCeScannerContexts(dbSession, profiler);
inOrder.verify(dbSession).commit();
inOrder.verify(dbSession).close();
inOrder.verifyNoMoreInteractions();
}
}
| 2,039 | 35.428571 | 82 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/security/PluginCeRuleTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.security;
import java.security.Permission;
import java.security.SecurityPermission;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class PluginCeRuleTest {
private final PluginCeRule rule = new PluginCeRule();
private final Permission allowedRuntime = new RuntimePermission("getFileSystemAttributes");
private final Permission deniedRuntime = new RuntimePermission("getClassLoader");
private final Permission allowedSecurity = new SecurityPermission("getProperty.key");
private final Permission deniedSecurity = new SecurityPermission("setPolicy");
@Test
public void rule_restricts_denied_permissions() {
assertThat(rule.implies(deniedSecurity)).isFalse();
assertThat(rule.implies(deniedRuntime)).isFalse();
}
@Test
public void rule_allows_permissions() {
assertThat(rule.implies(allowedSecurity)).isTrue();
assertThat(rule.implies(allowedRuntime)).isTrue();
}
}
| 1,811 | 37.553191 | 93 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/systeminfo/SystemInfoHttpActionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.systeminfo;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.apache.http.HttpException;
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
import org.sonar.ce.httpd.CeHttpUtils;
import org.sonar.process.systeminfo.JvmStateSection;
import org.sonar.process.systeminfo.SystemInfoSection;
import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo;
import static org.assertj.core.api.Assertions.assertThat;
public class SystemInfoHttpActionTest {
private SystemInfoSection stateProvider1 = new JvmStateSection("state1");
private SystemInfoSection stateProvider2 = new JvmStateSection("state2");
private SystemInfoHttpAction underTest;
@Before
public void setUp() {
underTest = new SystemInfoHttpAction(Arrays.asList(stateProvider1, stateProvider2));
}
@Test
public void serves_METHOD_NOT_ALLOWED_error_when_method_is_not_GET() throws HttpException, IOException {
CeHttpUtils.testHandlerForPostWithoutResponseBody(underTest, List.of(), List.of(), HttpStatus.SC_METHOD_NOT_ALLOWED);
}
@Test
public void serves_data_from_SystemInfoSections() throws Exception {
byte[] responsePayload = CeHttpUtils.testHandlerForGetWithResponseBody(underTest, HttpStatus.SC_OK);
ProtobufSystemInfo.SystemInfo systemInfo = ProtobufSystemInfo.SystemInfo.parseFrom(responsePayload);
assertThat(systemInfo.getSectionsCount()).isEqualTo(2);
assertThat(systemInfo.getSections(0).getName()).isEqualTo("state1");
assertThat(systemInfo.getSections(1).getName()).isEqualTo("state2");
}
}
| 2,453 | 39.229508 | 121 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeProcessingSchedulerImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.taskprocessor;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableScheduledFuture;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.sonar.ce.configuration.CeConfigurationRule;
import static com.google.common.collect.ImmutableList.copyOf;
import static java.util.Collections.emptySet;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.ce.taskprocessor.CeWorker.Result.DISABLED;
import static org.sonar.ce.taskprocessor.CeWorker.Result.NO_TASK;
import static org.sonar.ce.taskprocessor.CeWorker.Result.TASK_PROCESSED;
public class CeProcessingSchedulerImplTest {
private static final Error ERROR_TO_INTERRUPT_CHAINING = new Error("Error should stop scheduling");
// due to risks of infinite chaining of tasks/futures, a timeout is required for safety
@Rule
public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60));
@Rule
public CeConfigurationRule ceConfiguration = new CeConfigurationRule();
private CeWorker ceWorker = mock(CeWorker.class);
private CeWorkerFactory ceWorkerFactory = new TestCeWorkerFactory(ceWorker);
private StubCeProcessingSchedulerExecutorService processingExecutorService = new StubCeProcessingSchedulerExecutorService();
private SchedulerCall regularDelayedPoll = new SchedulerCall(ceWorker, 2000L, MILLISECONDS);
private SchedulerCall extendedDelayedPoll = new SchedulerCall(ceWorker, 30000L, MILLISECONDS);
private SchedulerCall notDelayedPoll = new SchedulerCall(ceWorker);
private CeWorkerController ceWorkerController = new CeWorkerControllerImpl(ceConfiguration);
private CeProcessingSchedulerImpl underTest = new CeProcessingSchedulerImpl(ceConfiguration, processingExecutorService, ceWorkerFactory, ceWorkerController);
@Test
public void polls_without_delay_when_CeWorkerCallable_returns_TASK_PROCESSED() throws Exception {
when(ceWorker.call())
.thenReturn(TASK_PROCESSED)
.thenThrow(ERROR_TO_INTERRUPT_CHAINING);
startSchedulingAndRun();
assertThat(processingExecutorService.getSchedulerCalls()).containsOnly(
regularDelayedPoll,
notDelayedPoll);
}
@Test
public void polls_without_delay_when_CeWorkerCallable_throws_Exception_but_not_Error() throws Exception {
when(ceWorker.call())
.thenThrow(new Exception("Exception is followed by a poll without delay"))
.thenThrow(ERROR_TO_INTERRUPT_CHAINING);
startSchedulingAndRun();
assertThat(processingExecutorService.getSchedulerCalls()).containsExactly(
regularDelayedPoll,
notDelayedPoll);
}
@Test
public void polls_with_regular_delay_when_CeWorkerCallable_returns_NO_TASK() throws Exception {
when(ceWorker.call())
.thenReturn(NO_TASK)
.thenThrow(ERROR_TO_INTERRUPT_CHAINING);
startSchedulingAndRun();
assertThat(processingExecutorService.getSchedulerCalls()).containsExactly(
regularDelayedPoll,
regularDelayedPoll);
}
@Test
public void polls_with_extended_delay_when_CeWorkerCallable_returns_DISABLED() throws Exception {
when(ceWorker.call())
.thenReturn(DISABLED)
.thenThrow(ERROR_TO_INTERRUPT_CHAINING);
startSchedulingAndRun();
assertThat(processingExecutorService.getSchedulerCalls()).containsExactly(
regularDelayedPoll,
extendedDelayedPoll);
}
@Test
public void startScheduling_schedules_CeWorkerCallable_at_fixed_rate_run_head_of_queue() throws Exception {
when(ceWorker.call())
.thenReturn(TASK_PROCESSED)
.thenReturn(TASK_PROCESSED)
.thenReturn(NO_TASK)
.thenReturn(TASK_PROCESSED)
.thenReturn(NO_TASK)
.thenThrow(new Exception("IAE should not cause scheduling to stop"))
.thenReturn(NO_TASK)
.thenReturn(NO_TASK)
.thenReturn(NO_TASK)
.thenThrow(ERROR_TO_INTERRUPT_CHAINING);
startSchedulingAndRun();
assertThat(processingExecutorService.getSchedulerCalls()).containsExactly(
regularDelayedPoll,
notDelayedPoll,
notDelayedPoll,
regularDelayedPoll,
notDelayedPoll,
regularDelayedPoll,
notDelayedPoll,
regularDelayedPoll,
regularDelayedPoll,
regularDelayedPoll);
}
@Test
public void gracefulStopScheduling_cancels_next_polling_and_does_not_add_any_new_one() throws Exception {
when(ceWorker.call())
.thenReturn(NO_TASK)
.thenReturn(TASK_PROCESSED)
.thenReturn(NO_TASK)
.thenReturn(NO_TASK)
.thenReturn(NO_TASK)
.thenReturn(NO_TASK)
.thenReturn(NO_TASK)
.thenThrow(ERROR_TO_INTERRUPT_CHAINING);
underTest.startScheduling();
int cancelledTaskFutureCount = 0;
int i = 0;
while (processingExecutorService.futures.peek() != null) {
Future<?> future = processingExecutorService.futures.poll();
if (future.isCancelled()) {
cancelledTaskFutureCount++;
} else {
future.get();
}
// call for graceful after second delayed polling
if (i == 1) {
underTest.gracefulStopScheduling();
}
i++;
}
assertThat(cancelledTaskFutureCount).isOne();
assertThat(processingExecutorService.getSchedulerCalls()).containsExactly(
regularDelayedPoll,
regularDelayedPoll,
notDelayedPoll,
regularDelayedPoll);
}
@Test
public void stopScheduling_cancels_next_polling_and_does_not_add_any_new_one() throws Exception {
when(ceWorker.call())
.thenReturn(NO_TASK)
.thenReturn(TASK_PROCESSED)
.thenReturn(NO_TASK)
.thenReturn(NO_TASK)
.thenReturn(NO_TASK)
.thenReturn(NO_TASK)
.thenReturn(NO_TASK)
.thenThrow(ERROR_TO_INTERRUPT_CHAINING);
underTest.startScheduling();
int cancelledTaskFutureCount = 0;
int i = 0;
while (processingExecutorService.futures.peek() != null) {
Future<?> future = processingExecutorService.futures.poll();
if (future.isCancelled()) {
cancelledTaskFutureCount++;
} else {
future.get();
}
// call stop after second delayed polling
if (i == 1) {
underTest.hardStopScheduling();
}
i++;
}
assertThat(cancelledTaskFutureCount).isOne();
assertThat(processingExecutorService.getSchedulerCalls()).containsExactly(
regularDelayedPoll,
regularDelayedPoll,
notDelayedPoll,
regularDelayedPoll);
}
@Test
public void when_workerCount_is_more_than_1_as_many_CeWorkerCallable_are_scheduled() throws Exception {
int workerCount = Math.abs(new Random().nextInt(10)) + 1;
ceConfiguration.setWorkerThreadCount(workerCount);
CeWorker[] workers = new CeWorker[workerCount];
for (int i = 0; i < workerCount; i++) {
workers[i] = mock(CeWorker.class);
when(workers[i].call())
.thenReturn(NO_TASK)
.thenThrow(ERROR_TO_INTERRUPT_CHAINING);
}
ListenableScheduledFuture listenableScheduledFuture = mock(ListenableScheduledFuture.class);
CeProcessingSchedulerExecutorService processingExecutorService = mock(CeProcessingSchedulerExecutorService.class);
when(processingExecutorService.schedule(any(CeWorker.class), any(Long.class), any(TimeUnit.class))).thenReturn(listenableScheduledFuture);
CeWorkerFactory ceWorkerFactory = spy(new TestCeWorkerFactory(workers));
CeProcessingSchedulerImpl underTest = new CeProcessingSchedulerImpl(ceConfiguration, processingExecutorService, ceWorkerFactory, ceWorkerController);
when(processingExecutorService.schedule(ceWorker, ceConfiguration.getQueuePollingDelay(), MILLISECONDS))
.thenReturn(listenableScheduledFuture);
underTest.startScheduling();
// No exception from TestCeWorkerFactory must be thrown
// Verify that schedule has been called on all workers
for (int i = 0; i < workerCount; i++) {
verify(processingExecutorService).schedule(workers[i], ceConfiguration.getQueuePollingDelay(), MILLISECONDS);
}
verify(listenableScheduledFuture, times(workerCount)).addListener(any(Runnable.class), eq(MoreExecutors.directExecutor()));
for (int i = 0; i < workerCount; i++) {
verify(ceWorkerFactory).create(i);
}
}
private void startSchedulingAndRun() throws ExecutionException, InterruptedException {
underTest.startScheduling();
// execute future synchronously
processingExecutorService.runFutures();
}
private static class TestCeWorkerFactory implements CeWorkerFactory {
private final Iterator<CeWorker> ceWorkers;
private TestCeWorkerFactory(CeWorker... ceWorkers) {
this.ceWorkers = copyOf(ceWorkers).iterator();
}
@Override
public CeWorker create(int ordinal) {
// This will throw an NoSuchElementException if there are too many calls
return ceWorkers.next();
}
@Override
public Set<CeWorker> getWorkers() {
return emptySet();
}
}
/**
* A synchronous implementation of {@link CeProcessingSchedulerExecutorService} which exposes a synchronous
* method to execute futures it creates and exposes a method to retrieve logs of calls to
* {@link CeProcessingSchedulerExecutorService#schedule(Callable, long, TimeUnit)} which is used by
* {@link CeProcessingSchedulerImpl}.
*/
private static class StubCeProcessingSchedulerExecutorService implements CeProcessingSchedulerExecutorService {
private final Queue<Future<?>> futures = new ConcurrentLinkedQueue<>();
private final ListeningScheduledExecutorService delegate = MoreExecutors.listeningDecorator(new SynchronousStubExecutorService());
private final List<SchedulerCall> schedulerCalls = new ArrayList<>();
public List<SchedulerCall> getSchedulerCalls() {
return schedulerCalls;
}
public void runFutures() throws ExecutionException, InterruptedException {
while (futures.peek() != null) {
Future<?> future = futures.poll();
if (!future.isCancelled()) {
future.get();
}
}
}
@Override
public <V> ListenableScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
this.schedulerCalls.add(new SchedulerCall(callable, delay, unit));
return delegate.schedule(callable, delay, unit);
}
@Override
public <T> ListenableFuture<T> submit(Callable<T> task) {
this.schedulerCalls.add(new SchedulerCall(task));
return delegate.submit(task);
}
@Override
public void stop() {
throw new UnsupportedOperationException("stop() not implemented");
}
// ////////////// delegated methods ////////////////
@Override
public ListenableScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return delegate.schedule(command, delay, unit);
}
@Override
public ListenableScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
return delegate.scheduleAtFixedRate(command, initialDelay, period, unit);
}
@Override
public ListenableScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit);
}
@Override
public void shutdown() {
delegate.shutdown();
}
@Override
public List<Runnable> shutdownNow() {
return delegate.shutdownNow();
}
@Override
public boolean isShutdown() {
return delegate.isShutdown();
}
@Override
public boolean isTerminated() {
return delegate.isTerminated();
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return delegate.awaitTermination(timeout, unit);
}
@Override
public <T> ListenableFuture<T> submit(Runnable task, T result) {
return delegate.submit(task, result);
}
@Override
public ListenableFuture<?> submit(Runnable task) {
return delegate.submit(task);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
return delegate.invokeAll(tasks);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException {
return delegate.invokeAll(tasks, timeout, unit);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
return delegate.invokeAny(tasks);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return delegate.invokeAny(tasks, timeout, unit);
}
@Override
public void execute(Runnable command) {
delegate.execute(command);
}
/**
* A partial (only 3 methods) implementation of ScheduledExecutorService which stores futures it creates into
* {@link StubCeProcessingSchedulerExecutorService#futures}.
*/
private class SynchronousStubExecutorService implements ScheduledExecutorService {
@Override
public ScheduledFuture<?> schedule(final Runnable command, long delay, TimeUnit unit) {
ScheduledFuture<Void> res = new AbstractPartiallyImplementedScheduledFuture<Void>() {
@Override
public Void get() {
command.run();
return null;
}
};
futures.add(res);
return res;
}
@Override
public <V> ScheduledFuture<V> schedule(final Callable<V> callable, long delay, TimeUnit unit) {
ScheduledFuture<V> res = new AbstractPartiallyImplementedScheduledFuture<V>() {
@Override
public V get() throws ExecutionException {
try {
return callable.call();
} catch (Exception e) {
throw new ExecutionException(e);
}
}
};
futures.add(res);
return res;
}
@Override
public <T> Future<T> submit(final Callable<T> task) {
Future<T> res = new AbstractPartiallyImplementedFuture<T>() {
@Override
public T get() throws ExecutionException {
try {
return task.call();
} catch (Exception e) {
throw new ExecutionException(e);
}
}
};
futures.add(res);
return res;
}
@Override
public void execute(Runnable command) {
command.run();
}
/////////// unsupported operations ///////////
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
throw new UnsupportedOperationException("scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) not implemented");
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
throw new UnsupportedOperationException("scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) not implemented");
}
@Override
public void shutdown() {
// Nothing to do
}
@Override
public List<Runnable> shutdownNow() {
throw new UnsupportedOperationException("shutdownNow() not implemented");
}
@Override
public boolean isShutdown() {
throw new UnsupportedOperationException("isShutdown() not implemented");
}
@Override
public boolean isTerminated() {
throw new UnsupportedOperationException("isTerminated() not implemented");
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) {
throw new UnsupportedOperationException("awaitTermination(long timeout, TimeUnit unit) not implemented");
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
throw new UnsupportedOperationException("submit(Runnable task, T result) not implemented");
}
@Override
public Future<?> submit(Runnable task) {
throw new UnsupportedOperationException("submit(Runnable task) not implemented");
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
throw new UnsupportedOperationException("invokeAll(Collection<? extends Callable<T>> tasks) not implemented");
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) {
throw new UnsupportedOperationException("invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) not implemented");
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) {
throw new UnsupportedOperationException("invokeAny(Collection<? extends Callable<T>> tasks) not implemented");
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) {
throw new UnsupportedOperationException("invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) not implemented");
}
}
}
private static abstract class AbstractPartiallyImplementedScheduledFuture<V> extends AbstractPartiallyImplementedFuture<V> implements ScheduledFuture<V> {
@Override
public long getDelay(TimeUnit unit) {
throw new UnsupportedOperationException("getDelay(TimeUnit unit) not implemented");
}
@Override
public int compareTo(Delayed o) {
throw new UnsupportedOperationException("compareTo(Delayed o) not implemented");
}
}
private static abstract class AbstractPartiallyImplementedFuture<T> implements Future<T> {
private boolean cancelled = false;
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
this.cancelled = true;
return true;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public boolean isDone() {
throw new UnsupportedOperationException("isDone() not implemented");
}
@Override
public T get(long timeout, TimeUnit unit) {
throw new UnsupportedOperationException("get(long timeout, TimeUnit unit) not implemented");
}
}
/**
* Used to log parameters of calls to {@link CeProcessingSchedulerExecutorService#schedule(Callable, long, TimeUnit)}
*/
@Immutable
private static final class SchedulerCall {
private final Callable<?> callable;
private final long delay;
private final TimeUnit unit;
private SchedulerCall(Callable<?> callable, long delay, TimeUnit unit) {
this.callable = callable;
this.delay = delay;
this.unit = unit;
}
private SchedulerCall(Callable<?> callable) {
this.callable = callable;
this.delay = -63366;
this.unit = TimeUnit.NANOSECONDS;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SchedulerCall that = (SchedulerCall) o;
return delay == that.delay && callable == that.callable && unit.equals(that.unit);
}
@Override
public int hashCode() {
return Objects.hash(callable, delay, unit);
}
@Override
public String toString() {
return "SchedulerCall{" +
"callable=" + callable +
", delay=" + delay +
", unit=" + unit +
'}';
}
}
}
| 21,852 | 33.360063 | 164 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskInterrupterProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.taskprocessor;
import java.lang.reflect.Field;
import java.util.Random;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.CeTaskInterrupter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
public class CeTaskInterrupterProviderTest {
private final MapSettings settings = new MapSettings();
private final CeWorkerController ceWorkerController = mock(CeWorkerController.class);
private final System2 system2 = mock(System2.class);
private final CeTaskInterrupterProvider underTest = new CeTaskInterrupterProvider();
@Test
public void provide_returns_a_SimpleCeTaskInterrupter_instance_if_configuration_is_empty() {
CeTaskInterrupter instance = underTest.provide(settings.asConfig(), ceWorkerController, system2);
assertThat(instance)
.isInstanceOf(SimpleCeTaskInterrupter.class);
}
@Test
public void provide_returns_a_TimeoutCeTaskInterrupter_instance_if_property_taskTimeout_has_a_value() throws IllegalAccessException, NoSuchFieldException {
int timeout = 1 + new Random().nextInt(2222);
settings.setProperty("sonar.ce.task.timeoutSeconds", timeout);
CeTaskInterrupter instance = underTest.provide(settings.asConfig(), ceWorkerController, system2);
assertThat(instance)
.isInstanceOf(TimeoutCeTaskInterrupter.class);
assertThat(readField(instance, "taskTimeoutThreshold"))
.isEqualTo(timeout * 1_000L);
assertThat(readField(instance, "ceWorkerController"))
.isSameAs(ceWorkerController);
assertThat(readField(instance, "system2"))
.isSameAs(system2);
}
@Test
public void provide_fails_with_ISE_if_property_is_not_a_long() {
settings.setProperty("sonar.ce.task.timeoutSeconds", "foo");
assertThatThrownBy(() -> underTest.provide(settings.asConfig(), ceWorkerController, system2))
.isInstanceOf(IllegalStateException.class)
.hasMessage("The property 'sonar.ce.task.timeoutSeconds' is not an long value: For input string: \"foo\"");
}
@Test
public void provide_fails_with_ISE_if_property_is_zero() {
settings.setProperty("sonar.ce.task.timeoutSeconds", "0");
assertThatThrownBy(() -> underTest.provide(settings.asConfig(), ceWorkerController, system2))
.isInstanceOf(IllegalStateException.class)
.hasMessage("The property 'sonar.ce.task.timeoutSeconds' must be a long value >= 1. Got '0'");
}
@Test
public void provide_fails_with_ISE_if_property_is_less_than_zero() {
int negativeValue = -(1 + new Random().nextInt(1_212));
settings.setProperty("sonar.ce.task.timeoutSeconds", negativeValue);
assertThatThrownBy(() -> underTest.provide(settings.asConfig(), ceWorkerController, system2))
.isInstanceOf(IllegalStateException.class)
.hasMessage("The property 'sonar.ce.task.timeoutSeconds' must be a long value >= 1. Got '" + negativeValue + "'");
}
private static Object readField(CeTaskInterrupter instance, String fieldName) throws NoSuchFieldException, IllegalAccessException {
Class<?> clazz = instance.getClass();
Field timeoutField = clazz.getDeclaredField(fieldName);
timeoutField.setAccessible(true);
return timeoutField.get(instance);
}
}
| 4,212 | 40.712871 | 157 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskInterrupterWorkerExecutionListenerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.taskprocessor;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Random;
import org.junit.Test;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskInterrupter;
import org.sonar.db.ce.CeActivityDto;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class CeTaskInterrupterWorkerExecutionListenerTest {
private CeTaskInterrupter ceTaskInterrupter = mock(CeTaskInterrupter.class);
private CeTaskInterrupterWorkerExecutionListener underTest = new CeTaskInterrupterWorkerExecutionListener(ceTaskInterrupter);
@Test
public void onStart_delegates_to_ceTaskInterrupter_onStart() {
CeTask ceTask = mock(CeTask.class);
underTest.onStart(ceTask);
verify(ceTaskInterrupter).onStart(same(ceTask));
}
@Test
public void onEnd_delegates_to_ceTaskInterrupter_onEnd() {
CeTask ceTask = mock(CeTask.class);
CeActivityDto.Status randomStatus = CeActivityDto.Status.values()[new Random().nextInt(CeActivityDto.Status.values().length)];
underTest.onEnd(ceTask, randomStatus, Duration.of(1, ChronoUnit.SECONDS), null, null);
verify(ceTaskInterrupter).onEnd(same(ceTask));
}
}
| 2,102 | 36.553571 | 130 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskLoggingWorkerExecutionListenerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.taskprocessor;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Random;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.log.CeTaskLogging;
import org.sonar.db.ce.CeActivityDto;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
public class CeTaskLoggingWorkerExecutionListenerTest {
private CeTaskLogging ceTaskLogging = Mockito.spy(CeTaskLogging.class);
private CeLoggingWorkerExecutionListener underTest = new CeLoggingWorkerExecutionListener(ceTaskLogging);
@Test
public void onStart_calls_initForTask_with_method_argument() {
CeTask ceTask = Mockito.mock(CeTask.class);
underTest.onStart(ceTask);
verify(ceTaskLogging).initForTask(ceTask);
verifyNoMoreInteractions(ceTaskLogging);
}
@Test
public void onEnd_calls_clearForTask() {
underTest.onEnd(mock(CeTask.class),
CeActivityDto.Status.values()[new Random().nextInt(CeActivityDto.Status.values().length)],
Duration.of(1, ChronoUnit.SECONDS), null, null);
verify(ceTaskLogging).clearForTask();
verifyNoMoreInteractions(ceTaskLogging);
}
}
| 2,107 | 34.728814 | 107 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskProcessorModuleTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.taskprocessor;
import org.junit.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.sonar.ce.notification.ReportAnalysisFailureNotificationExecutionListener;
import org.sonar.core.platform.ExtensionContainer;
public class CeTaskProcessorModuleTest {
private CeTaskProcessorModule underTest = new CeTaskProcessorModule();
@Test
public void defines_module() {
var container = mock(ExtensionContainer.class);
underTest.configure(container);
verify(container).add(CeTaskProcessorRepositoryImpl.class);
verify(container).add(CeLoggingWorkerExecutionListener.class);
verify(container).add(ReportAnalysisFailureNotificationExecutionListener.class);
verify(container).add(any(CeTaskInterrupterProvider.class));
verify(container).add(CeTaskInterrupterWorkerExecutionListener.class);
verify(container).add(CeWorkerFactoryImpl.class);
verify(container).add(CeWorkerControllerImpl.class);
verify(container).add(CeProcessingSchedulerExecutorServiceImpl.class);
verify(container).add(CeProcessingSchedulerImpl.class);
}
}
| 2,025 | 39.52 | 84 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskProcessorRepositoryImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.taskprocessor;
import com.google.common.collect.ImmutableSet;
import java.util.Set;
import org.junit.Test;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskResult;
import org.sonar.ce.task.taskprocessor.CeTaskProcessor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class CeTaskProcessorRepositoryImplTest {
private static final String SOME_CE_TASK_TYPE = "some type";
private static final String SOME_COMPONENT_KEY = "key";
@Test
public void constructor_accepts_empty_array_argument() {
new CeTaskProcessorRepositoryImpl(new CeTaskProcessor[] {});
}
@Test
public void constructor_throws_IAE_if_two_TaskProcessor_handle_the_same_CeTask_type() {
assertThatThrownBy(() -> {
new CeTaskProcessorRepositoryImpl(new CeTaskProcessor[] {
new SomeProcessor1(SOME_CE_TASK_TYPE),
new SomeProcessor2(SOME_CE_TASK_TYPE)
});
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage(
"There can be only one CeTaskProcessor instance registered as the processor for CeTask type " + SOME_CE_TASK_TYPE + ". " +
"More than one found. Please fix your configuration: " + SomeProcessor1.class.getName() + ", " + SomeProcessor2.class.getName()
);
}
@Test
public void constructor_throws_IAE_if_multiple_TaskProcessor_overlap_their_supported_CeTask_type() {
assertThatThrownBy(() -> {
new CeTaskProcessorRepositoryImpl(new CeTaskProcessor[] {
new SomeProcessor2(SOME_CE_TASK_TYPE + "_2", SOME_CE_TASK_TYPE),
new SomeProcessor1(SOME_CE_TASK_TYPE, SOME_CE_TASK_TYPE + "_3")
});
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage(
"There can be only one CeTaskProcessor instance registered as the processor for CeTask type " + SOME_CE_TASK_TYPE + ". " +
"More than one found. Please fix your configuration: " + SomeProcessor1.class.getName() + ", " + SomeProcessor2.class.getName()
);
}
@Test
public void getForTask_returns_absent_if_repository_is_empty() {
CeTaskProcessorRepositoryImpl underTest = new CeTaskProcessorRepositoryImpl(new CeTaskProcessor[] {});
assertThat(underTest.getForCeTask(createCeTask(SOME_CE_TASK_TYPE, SOME_COMPONENT_KEY))).isEmpty();
}
@Test
public void getForTask_returns_absent_if_repository_does_not_contain_matching_TaskProcessor() {
CeTaskProcessorRepositoryImpl underTest = new CeTaskProcessorRepositoryImpl(new CeTaskProcessor[] {
createCeTaskProcessor(SOME_CE_TASK_TYPE + "_1"),
createCeTaskProcessor(SOME_CE_TASK_TYPE + "_2", SOME_CE_TASK_TYPE + "_3"),
});
assertThat(underTest.getForCeTask(createCeTask(SOME_CE_TASK_TYPE, SOME_COMPONENT_KEY))).isEmpty();
}
@Test
public void getForTask_returns_TaskProcessor_based_on_CeTask_type_only() {
CeTaskProcessor taskProcessor = createCeTaskProcessor(SOME_CE_TASK_TYPE);
CeTaskProcessorRepositoryImpl underTest = new CeTaskProcessorRepositoryImpl(new CeTaskProcessor[] {taskProcessor});
assertThat(underTest.getForCeTask(createCeTask(SOME_CE_TASK_TYPE, SOME_COMPONENT_KEY))).containsSame(taskProcessor);
assertThat(underTest.getForCeTask(createCeTask(SOME_CE_TASK_TYPE, SOME_COMPONENT_KEY + "2"))).containsSame(taskProcessor);
}
@Test
public void getForTask_returns_TaskProcessor_even_if_it_is_not_specific() {
CeTaskProcessor taskProcessor = createCeTaskProcessor(SOME_CE_TASK_TYPE + "_1", SOME_CE_TASK_TYPE, SOME_CE_TASK_TYPE + "_3");
CeTaskProcessorRepositoryImpl underTest = new CeTaskProcessorRepositoryImpl(new CeTaskProcessor[] {taskProcessor});
assertThat(underTest.getForCeTask(createCeTask(SOME_CE_TASK_TYPE, SOME_COMPONENT_KEY))).containsSame(taskProcessor);
}
private CeTaskProcessor createCeTaskProcessor(final String... ceTaskTypes) {
return new HandleTypeOnlyTaskProcessor(ceTaskTypes);
}
private static CeTask createCeTask(String ceTaskType, String key) {
CeTask.Component component = new CeTask.Component("uuid_" + key, key, "name_" + key);
CeTask.Component entity = new CeTask.Component("uuid_entity_" + key, key, "name_" + key);
return new CeTask.Builder()
.setType(ceTaskType)
.setUuid("task_uuid_" + key)
.setComponent(component)
.setEntity(entity)
.build();
}
private static class HandleTypeOnlyTaskProcessor implements CeTaskProcessor {
private final String[] ceTaskTypes;
public HandleTypeOnlyTaskProcessor(String... ceTaskTypes) {
this.ceTaskTypes = ceTaskTypes;
}
@Override
public Set<String> getHandledCeTaskTypes() {
return ImmutableSet.copyOf(ceTaskTypes);
}
@Override
public CeTaskResult process(CeTask task) {
throw new UnsupportedOperationException("Process is not implemented");
}
}
private static class SomeProcessor1 extends HandleTypeOnlyTaskProcessor {
public SomeProcessor1(String... ceTaskTypes) {
super(ceTaskTypes);
}
}
private static class SomeProcessor2 extends HandleTypeOnlyTaskProcessor {
public SomeProcessor2(String... ceTaskTypes) {
super(ceTaskTypes);
}
}
}
| 6,040 | 39.817568 | 135 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskProcessorRepositoryRule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.taskprocessor;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.junit.rules.ExternalResource;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskResult;
import org.sonar.ce.task.taskprocessor.CeTaskProcessor;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
/**
* A {@link org.junit.Rule} that implements the {@link CeTaskProcessorRepository} interface and
* requires consumer to explicitly define if a specific Task type has an associated {@link CeTaskProcessor} or not.
*/
public class CeTaskProcessorRepositoryRule extends ExternalResource implements CeTaskProcessorRepository {
private final Map<String, CeTaskProcessor> index = new HashMap<>();
@Override
protected void after() {
index.clear();
}
public CeTaskProcessorRepositoryRule setNoProcessorForTask(String taskType) {
index.put(requireNonNull(taskType), NoCeTaskProcessor.INSTANCE);
return this;
}
public CeTaskProcessorRepositoryRule setProcessorForTask(String taskType, CeTaskProcessor taskProcessor) {
index.put(requireNonNull(taskType), requireNonNull(taskProcessor));
return this;
}
@Override
public Optional<CeTaskProcessor> getForCeTask(CeTask ceTask) {
CeTaskProcessor taskProcessor = index.get(ceTask.getType());
checkState(taskProcessor != null, "CeTaskProcessor was not set in rule for task %s", ceTask);
return taskProcessor instanceof NoCeTaskProcessor ? Optional.empty() : Optional.of(taskProcessor);
}
private enum NoCeTaskProcessor implements CeTaskProcessor {
INSTANCE;
private static final String UOE_MESSAGE = "NoCeTaskProcessor does not implement any method since it not supposed to be ever used";
@Override
public Set<String> getHandledCeTaskTypes() {
throw new UnsupportedOperationException(UOE_MESSAGE);
}
@Override
public CeTaskResult process(CeTask task) {
throw new UnsupportedOperationException(UOE_MESSAGE);
}
}
}
| 2,919 | 35.5 | 134 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeWorkerControllerImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.taskprocessor;
import java.util.Random;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.configuration.CeConfigurationRule;
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.reset;
import static org.mockito.Mockito.when;
public class CeWorkerControllerImplTest {
private Random random = new Random();
/** 1 <= workerCount <= 5 */
private int randomWorkerCount = 1 + random.nextInt(5);
@Rule
public CeConfigurationRule ceConfigurationRule = new CeConfigurationRule()
.setWorkerCount(randomWorkerCount);
@Rule
public LogTester logTester = new LogTester();
private CeWorker ceWorker = mock(CeWorker.class);
private CeWorkerControllerImpl underTest = new CeWorkerControllerImpl(ceConfigurationRule);
@Test
public void isEnabled_returns_true_if_worker_ordinal_is_less_than_CeConfiguration_workerCount() {
int ordinal = randomWorkerCount + Math.min(-1, -random.nextInt(randomWorkerCount));
when(ceWorker.getOrdinal()).thenReturn(ordinal);
assertThat(underTest.isEnabled(ceWorker))
.as("For ordinal " + ordinal + " and workerCount " + randomWorkerCount)
.isTrue();
}
@Test
public void isEnabled_returns_false_if_worker_ordinal_is_equal_to_CeConfiguration_workerCount() {
when(ceWorker.getOrdinal()).thenReturn(randomWorkerCount);
assertThat(underTest.isEnabled(ceWorker)).isFalse();
}
@Test
public void isEnabled_returns_true_if_ordinal_is_invalid() {
int ordinal = -1 - random.nextInt(3);
when(ceWorker.getOrdinal()).thenReturn(ordinal);
assertThat(underTest.isEnabled(ceWorker))
.as("For invalid ordinal " + ordinal + " and workerCount " + randomWorkerCount)
.isTrue();
}
@Test
public void constructor_writes_no_info_log_if_workerCount_is_1() {
ceConfigurationRule.setWorkerCount(1);
logTester.clear();
new CeWorkerControllerImpl(ceConfigurationRule);
assertThat(logTester.logs()).isEmpty();
}
@Test
public void constructor_writes_info_log_if_workerCount_is_greater_than_1() {
int newWorkerCount = randomWorkerCount + 1;
ceConfigurationRule.setWorkerCount(newWorkerCount);
logTester.clear();
new CeWorkerControllerImpl(ceConfigurationRule);
verifyInfoLog(newWorkerCount);
}
@Test
public void workerCount_is_always_reloaded() {
when(ceWorker.getOrdinal()).thenReturn(1);
ceConfigurationRule.setWorkerCount(1);
assertThat(underTest.isEnabled(ceWorker)).isFalse();
ceConfigurationRule.setWorkerCount(2);
assertThat(underTest.isEnabled(ceWorker)).isTrue();
}
@Test
public void getCeWorkerIn_returns_empty_if_worker_is_unregistered_in_CeWorkerController() {
CeWorker ceWorker = mock(CeWorker.class);
Thread currentThread = Thread.currentThread();
Thread otherThread = new Thread();
mockWorkerIsRunningOnNoThread(ceWorker);
assertThat(underTest.getCeWorkerIn(currentThread)).isEmpty();
assertThat(underTest.getCeWorkerIn(otherThread)).isEmpty();
mockWorkerIsRunningOnThread(ceWorker, currentThread);
assertThat(underTest.getCeWorkerIn(currentThread)).isEmpty();
assertThat(underTest.getCeWorkerIn(otherThread)).isEmpty();
mockWorkerIsRunningOnThread(ceWorker, otherThread);
assertThat(underTest.getCeWorkerIn(currentThread)).isEmpty();
assertThat(underTest.getCeWorkerIn(otherThread)).isEmpty();
}
@Test
public void getCeWorkerIn_returns_empty_if_worker_registered_in_CeWorkerController_but_has_no_current_thread() {
CeWorker ceWorker = mock(CeWorker.class);
Thread currentThread = Thread.currentThread();
Thread otherThread = new Thread();
underTest.registerProcessingFor(ceWorker);
mockWorkerIsRunningOnNoThread(ceWorker);
assertThat(underTest.getCeWorkerIn(currentThread)).isEmpty();
assertThat(underTest.getCeWorkerIn(otherThread)).isEmpty();
}
@Test
public void getCeWorkerIn_returns_thread_if_worker_registered_in_CeWorkerController_but_has_a_current_thread() {
CeWorker ceWorker = mock(CeWorker.class);
Thread currentThread = Thread.currentThread();
Thread otherThread = new Thread();
underTest.registerProcessingFor(ceWorker);
mockWorkerIsRunningOnThread(ceWorker, currentThread);
assertThat(underTest.getCeWorkerIn(currentThread)).contains(ceWorker);
assertThat(underTest.getCeWorkerIn(otherThread)).isEmpty();
mockWorkerIsRunningOnThread(ceWorker, otherThread);
assertThat(underTest.getCeWorkerIn(currentThread)).isEmpty();
assertThat(underTest.getCeWorkerIn(otherThread)).contains(ceWorker);
}
private void mockWorkerIsRunningOnThread(CeWorker ceWorker, Thread thread) {
reset(ceWorker);
when(ceWorker.isExecutedBy(thread)).thenReturn(true);
}
private void mockWorkerIsRunningOnNoThread(CeWorker ceWorker) {
reset(ceWorker);
when(ceWorker.isExecutedBy(any())).thenReturn(false);
}
private void verifyInfoLog(int workerCount) {
assertThat(logTester.logs()).hasSize(1);
assertThat(logTester.logs(Level.INFO))
.containsOnly("Compute Engine will use " + workerCount + " concurrent workers to process tasks");
}
}
| 6,179 | 34.722543 | 114 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeWorkerFactoryImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.taskprocessor;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.IntStream;
import org.junit.Test;
import org.sonar.ce.queue.InternalCeQueue;
import org.sonar.core.util.UuidFactoryImpl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class CeWorkerFactoryImplTest {
private int randomOrdinal = new Random().nextInt(20);
private CeWorkerFactoryImpl underTest = new CeWorkerFactoryImpl(mock(InternalCeQueue.class),
mock(CeTaskProcessorRepository.class), UuidFactoryImpl.INSTANCE, mock(CeWorkerController.class));
@Test
public void create_return_CeWorker_object_with_specified_ordinal() {
CeWorker ceWorker = underTest.create(randomOrdinal);
assertThat(ceWorker.getOrdinal()).isEqualTo(randomOrdinal);
}
@Test
public void create_returns_CeWorker_with_listeners_passed_to_factory_constructor() throws NoSuchFieldException, IllegalAccessException {
CeWorker.ExecutionListener executionListener1 = mock(CeWorker.ExecutionListener.class);
CeWorker.ExecutionListener executionListener2 = mock(CeWorker.ExecutionListener.class);
CeWorkerFactoryImpl underTest = new CeWorkerFactoryImpl(mock(InternalCeQueue.class),
mock(CeTaskProcessorRepository.class), UuidFactoryImpl.INSTANCE, mock(CeWorkerController.class),
new CeWorker.ExecutionListener[] {executionListener1, executionListener2});
CeWorker ceWorker = underTest.create(randomOrdinal);
Field f = CeWorkerImpl.class.getDeclaredField("listeners");
f.setAccessible(true);
assertThat((List<CeWorker.ExecutionListener>) f.get(ceWorker)).containsExactly(
executionListener1, executionListener2);
}
@Test
public void create_allows_multiple_calls_with_same_ordinal() {
IntStream.range(0, new Random().nextInt(50)).forEach(ignored -> {
CeWorker ceWorker = underTest.create(randomOrdinal);
assertThat(ceWorker.getOrdinal()).isEqualTo(randomOrdinal);
});
}
@Test
public void each_call_must_return_a_new_ceworker_with_unique_uuid() {
Set<CeWorker> ceWorkers = new HashSet<>();
Set<String> ceWorkerUUIDs = new HashSet<>();
for (int i = 0; i < 10; i++) {
CeWorker ceWorker = underTest.create(i);
ceWorkers.add(ceWorker);
ceWorkerUUIDs.add(ceWorker.getUUID());
}
assertThat(ceWorkers).hasSize(10);
assertThat(ceWorkerUUIDs).hasSize(10);
}
@Test
public void ceworker_created_by_factory_must_contain_uuid() {
CeWorker ceWorker = underTest.create(randomOrdinal);
assertThat(ceWorker.getUUID()).isNotEmpty();
}
@Test
public void getWorkers_returns_empty_if_create_has_not_been_called_before() {
assertThat(underTest.getWorkers()).isEmpty();
}
@Test
public void CeWorkerFactory_must_returns_the_workers_returned_by_created() {
Set<CeWorker> expected = new HashSet<>();
for (int i = 0; i < 1 + new Random().nextInt(10); i++) {
expected.add(underTest.create(i));
}
assertThat(underTest.getWorkers()).isEqualTo(expected);
}
}
| 3,988 | 35.935185 | 138 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/ComputingThread.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.taskprocessor;
class ComputingThread extends Thread {
private boolean kill = false;
public ComputingThread(String name) {
setName(name);
}
private long fibo(int i) {
if (kill) {
return i;
}
if (i == 0) {
return 0;
}
if (i == 1) {
return 1;
}
return fibo(i - 1) + fibo(i - 2);
}
@Override
public void run() {
for (int i = 2; i < 50; i++) {
fibo(i);
if (kill) {
break;
}
}
}
public void kill() {
this.kill = true;
}
}
| 1,393 | 23.892857 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/SimpleCeTaskInterrupterTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.taskprocessor;
import org.junit.Test;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskCanceledException;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
public class SimpleCeTaskInterrupterTest {
private SimpleCeTaskInterrupter underTest = new SimpleCeTaskInterrupter();
@Test
public void check_throws_CeTaskCanceledException_if_provided_thread_is_interrupted() throws InterruptedException {
String threadName = randomAlphabetic(30);
ComputingThread t = new ComputingThread(threadName);
try {
t.start();
// will not fail
underTest.check(t);
t.interrupt();
assertThatThrownBy(() -> underTest.check(t))
.isInstanceOf(CeTaskCanceledException.class)
.hasMessage("CeWorker executing in Thread '" + threadName + "' has been interrupted");
} finally {
t.kill();
t.join(1_000);
}
}
@Test
public void onStart_has_no_effect() {
CeTask ceTask = mock(CeTask.class);
underTest.onStart(ceTask);
verifyNoInteractions(ceTask);
}
@Test
public void onEnd_has_no_effect() {
CeTask ceTask = mock(CeTask.class);
underTest.onEnd(ceTask);
verifyNoInteractions(ceTask);
}
}
| 2,255 | 29.08 | 116 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/TimeoutCeTaskInterrupterTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.taskprocessor;
import java.util.Optional;
import java.util.Random;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskCanceledException;
import org.sonar.ce.task.CeTaskTimeoutException;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TimeoutCeTaskInterrupterTest {
@Rule
public LogTester logTester = new LogTester();
private int timeoutInSeconds = 1 + new Random().nextInt(20);
private int timeoutInMs = timeoutInSeconds * 1_000;
private CeWorkerController ceWorkerController = mock(CeWorkerController.class);
private System2 system2 = mock(System2.class);
private CeWorker ceWorker = mock(CeWorker.class);
private CeTask ceTask = mock(CeTask.class);
private TimeoutCeTaskInterrupter underTest = new TimeoutCeTaskInterrupter(timeoutInMs, ceWorkerController, system2);
@Test
public void constructor_fails_with_IAE_if_timeout_is_0() {
assertThatThrownBy(() -> new TimeoutCeTaskInterrupter(0, ceWorkerController, system2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("threshold must be >= 1");
}
@Test
public void constructor_fails_with_IAE_if_timeout_is_less_than_0() {
long timeout = - (1 + new Random().nextInt(299));
assertThatThrownBy(() -> new TimeoutCeTaskInterrupter(timeout, ceWorkerController, system2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("threshold must be >= 1");
}
@Test
public void constructor_log_timeout_in_ms_at_INFO_level() {
int timeout = 1 + new Random().nextInt(9_999);
new TimeoutCeTaskInterrupter(timeout, ceWorkerController, system2);
assertThat(logTester.logs()).hasSize(1);
assertThat(logTester.logs(Level.INFO))
.containsExactly("Compute Engine Task timeout enabled: " + timeout + " ms");
}
@Test
public void check_fails_with_ISE_if_thread_is_not_running_a_CeWorker() {
Thread t = newThreadWithRandomName();
assertThatThrownBy(() -> underTest.check(t))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Could not find the CeTask being executed in thread '" + t.getName() + "'");
}
@Test
public void check_fails_with_ISE_if_thread_is_not_running_a_CeWorker_with_no_current_CeTask() {
Thread t = newThreadWithRandomName();
mockWorkerOnThread(t, ceWorker);
assertThatThrownBy(() -> underTest.check(t))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Could not find the CeTask being executed in thread '" + t.getName() + "'");
}
@Test
public void check_fails_with_ISE_if_thread_is_executing_a_CeTask_but_on_start_has_not_been_called_on_it() {
String taskUuid = randomAlphabetic(15);
Thread t = new Thread();
mockWorkerOnThread(t, ceWorker);
mockWorkerWithTask(ceTask);
when(ceTask.getUuid()).thenReturn(taskUuid);
assertThatThrownBy(() -> underTest.check(t))
.isInstanceOf(IllegalStateException.class)
.hasMessage("No start time recorded for task " + taskUuid);
}
@Test
public void check_fails_with_ISE_if_thread_is_executing_a_CeTask_but_on_start_and_on_end_have_not_been_called_on_it() {
String taskUuid = randomAlphabetic(15);
Thread t = new Thread();
mockWorkerOnThread(t, ceWorker);
mockWorkerWithTask(ceTask);
when(ceTask.getUuid()).thenReturn(taskUuid);
underTest.onStart(this.ceTask);
underTest.onEnd(this.ceTask);
assertThatThrownBy(() -> underTest.check(t))
.isInstanceOf(IllegalStateException.class)
.hasMessage("No start time recorded for task " + taskUuid);
}
@Test
public void check_throws_CeTaskCanceledException_if_provided_thread_is_interrupted() throws InterruptedException {
String threadName = randomAlphabetic(30);
ComputingThread t = new ComputingThread(threadName);
mockWorkerOnThread(t, ceWorker);
mockWorkerWithTask(ceTask);
underTest.onStart(ceTask);
try {
t.start();
// will not fail as thread is not interrupted nor timed out
underTest.check(t);
t.interrupt();
assertThatThrownBy(() -> underTest.check(t))
.isInstanceOf(CeTaskCanceledException.class)
.hasMessage("CeWorker executing in Thread '" + threadName + "' has been interrupted");
} finally {
t.kill();
t.join(1_000);
}
}
@Test
public void check_throws_CeTaskTimeoutException_if_check_called_later_than_timeout_milliseconds_after_on_start() {
Thread thread = newThreadWithRandomName();
mockWorkerOnThread(thread, ceWorker);
mockWorkerWithTask(ceTask);
long now = 3_776_663_999L;
when(system2.now()).thenReturn(now);
underTest.onStart(ceTask);
// timeout not passed => no exception thrown
int beforeTimeoutOffset = 1 + new Random().nextInt(timeoutInMs - 1);
when(system2.now()).thenReturn(now + timeoutInMs - beforeTimeoutOffset);
underTest.check(thread);
int afterTimeoutOffset = new Random().nextInt(7_112);
when(system2.now()).thenReturn(now + timeoutInMs + afterTimeoutOffset);
assertThatThrownBy(() -> underTest.check(thread))
.isInstanceOf(CeTaskTimeoutException.class)
.hasMessage("Execution of task timed out after " + (timeoutInMs + afterTimeoutOffset) + " ms");
}
@Test
public void check_throws_CeTaskCanceledException_if_provided_thread_is_interrupted_even_if_timed_out() throws InterruptedException {
String threadName = randomAlphabetic(30);
ComputingThread t = new ComputingThread(threadName);
mockWorkerOnThread(t, ceWorker);
mockWorkerWithTask(ceTask);
long now = 3_776_663_999L;
when(system2.now()).thenReturn(now);
underTest.onStart(ceTask);
try {
t.start();
t.interrupt();
// will not fail as thread is not interrupted nor timed out
int afterTimeoutOffset = new Random().nextInt(7_112);
when(system2.now()).thenReturn(now + timeoutInMs + afterTimeoutOffset);
assertThatThrownBy(() -> underTest.check(t))
.isInstanceOf(CeTaskCanceledException.class)
.hasMessage("CeWorker executing in Thread '" + threadName + "' has been interrupted");
} finally {
t.kill();
t.join(1_000);
}
}
private static Thread newThreadWithRandomName() {
String threadName = randomAlphabetic(30);
Thread t = new Thread();
t.setName(threadName);
return t;
}
private void mockWorkerOnThread(Thread t, CeWorker ceWorker) {
when(ceWorkerController.getCeWorkerIn(t)).thenReturn(Optional.of(ceWorker));
}
private void mockWorkerWithTask(CeTask ceTask) {
when(ceWorker.getCurrentTask()).thenReturn(Optional.of(ceTask));
}
}
| 7,832 | 35.602804 | 134 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/plugins/sonar-test-plugin/src/TestPlugin.java | import org.sonar.api.SonarPlugin;
import java.util.Collections;
import java.util.List;
public class TestPlugin extends SonarPlugin {
public List getExtensions() {
return Collections.emptyList();
}
}
| 210 | 16.583333 | 45 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/plugins/sonar-test2-plugin/src/Test2Plugin.java | import org.sonar.api.SonarPlugin;
import java.util.Collections;
import java.util.List;
public class Test2Plugin extends SonarPlugin {
public List getExtensions() {
return Collections.emptyList();
}
}
| 211 | 16.666667 | 46 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/it/java/org/sonar/db/DatabaseUtilsIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.dialect.Oracle;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.db.DatabaseUtils.ORACLE_DRIVER_NAME;
import static org.sonar.db.DatabaseUtils.checkThatNotTooManyConditions;
import static org.sonar.db.DatabaseUtils.closeQuietly;
import static org.sonar.db.DatabaseUtils.getColumnMetadata;
import static org.sonar.db.DatabaseUtils.getDriver;
import static org.sonar.db.DatabaseUtils.log;
import static org.sonar.db.DatabaseUtils.tableColumnExists;
import static org.sonar.db.DatabaseUtils.tableExists;
import static org.sonar.db.DatabaseUtils.toUniqueAndSortedList;
public class DatabaseUtilsIT {
private static final String DEFAULT_SCHEMA = "public";
private static final String SCHEMA_MIGRATIONS_TABLE = "SCHEMA_MIGRATIONS";
@Rule
public CoreDbTester dbTester = CoreDbTester.createForSchema(DatabaseUtilsIT.class, "sql.sql", false);
@Rule
public LogTester logTester = new LogTester();
@Test
public void findExistingIndex_whenTableBothInLowerAndUpperCase_shouldFindIndex() throws SQLException {
String indexName = "lower_case_name";
try (Connection connection = dbTester.openConnection()) {
assertThat(DatabaseUtils.findExistingIndex(connection, SCHEMA_MIGRATIONS_TABLE, indexName)).contains(indexName);
assertThat(DatabaseUtils.findExistingIndex(connection, SCHEMA_MIGRATIONS_TABLE.toLowerCase(Locale.US), indexName)).contains(indexName);
}
}
@Test
public void findExistingIndex_whenMixedCasesInTableAndIndexName_shouldFindIndex() throws SQLException {
String indexName = "UPPER_CASE_NAME";
try (Connection connection = dbTester.openConnection()) {
assertThat(DatabaseUtils.findExistingIndex(connection, SCHEMA_MIGRATIONS_TABLE, indexName)).contains(indexName);
assertThat(DatabaseUtils.findExistingIndex(connection, SCHEMA_MIGRATIONS_TABLE, indexName.toLowerCase(Locale.US))).contains(indexName);
assertThat(DatabaseUtils.findExistingIndex(connection, SCHEMA_MIGRATIONS_TABLE.toLowerCase(Locale.US), indexName.toLowerCase(Locale.US))).contains(indexName);
}
}
@Test
public void findExistingIndex_whenPassingOnlyPartOfIndexName_shouldFindIndexAndReturnFullName() throws SQLException {
String indexName = "INDEX_NAME";
try (Connection connection = dbTester.openConnection()) {
assertThat(DatabaseUtils.findExistingIndex(connection, SCHEMA_MIGRATIONS_TABLE, indexName)).contains("idx_1234_index_name");
assertThat(DatabaseUtils.findExistingIndex(connection, SCHEMA_MIGRATIONS_TABLE.toLowerCase(Locale.US), indexName)).contains("idx_1234_index_name");
assertThat(DatabaseUtils.findExistingIndex(connection, SCHEMA_MIGRATIONS_TABLE.toLowerCase(Locale.US), indexName.toLowerCase(Locale.US))).contains("idx_1234_index_name");
assertThat(DatabaseUtils.findExistingIndex(connection, SCHEMA_MIGRATIONS_TABLE, "index")).isEmpty();
assertThat(DatabaseUtils.findExistingIndex(connection, SCHEMA_MIGRATIONS_TABLE, "index_name_2")).isEmpty();
assertThat(DatabaseUtils.findExistingIndex(connection, SCHEMA_MIGRATIONS_TABLE, "index_name_")).isEmpty();
}
}
@Test
public void tableColumnExists_whenTableNameLowerCaseColumnUpperCase_shouldFindColumn() throws SQLException {
String tableName = "tablea";
String columnName = "COLUMNA";
try (Connection connection = dbTester.openConnection()) {
assertThat(tableColumnExists(connection, tableName, columnName)).isTrue();
}
}
@Test
public void tableColumnExists_whenArgumentInUpperCase_shouldFindColumn() throws SQLException {
String tableName = "TABLEA";
String columnName = "COLUMNA";
try (Connection connection = dbTester.openConnection()) {
assertThat(tableColumnExists(connection, tableName, columnName)).isTrue();
}
}
@Test
public void tableColumnExists_whenArgumentsInLowerCase_shouldFindColumn() throws SQLException {
String tableName = "tablea";
String columnName = "columna";
try (Connection connection = dbTester.openConnection()) {
assertThat(tableColumnExists(connection, tableName, columnName)).isTrue();
}
}
@Test
public void tableColumnExists_whenTableNameInUpperCaseAndColumnInLowerCase_shouldFindColumn() throws SQLException {
String tableName = "TABLEA";
String columnName = "columna";
try (Connection connection = dbTester.openConnection()) {
assertThat(tableColumnExists(connection, tableName, columnName)).isTrue();
}
}
@Test
public void getColumnMetadata_whenTableNameLowerCaseColumnUpperCase_shouldFindColumn() throws SQLException {
String tableName = "tablea";
String columnName = "COLUMNA";
try (Connection connection = dbTester.openConnection()) {
assertThat(getColumnMetadata(connection, tableName, columnName)).isNotNull();
}
}
@Test
public void getColumnMetadata_whenArgumentInUpperCase_shouldFindColumn() throws SQLException {
String tableName = "TABLEA";
String columnName = "COLUMNA";
try (Connection connection = dbTester.openConnection()) {
assertThat(getColumnMetadata(connection, tableName, columnName)).isNotNull();
}
}
@Test
public void closeQuietly_shouldCloseConnection() throws SQLException {
try (Connection connection = dbTester.openConnection()) {
assertThat(isClosed(connection)).isFalse();
closeQuietly(connection);
assertThat(isClosed(connection)).isTrue();
}
}
@Test
public void closeQuietly_shouldNotFailOnNullArgument() {
assertThatCode(() -> closeQuietly((Connection) null)).doesNotThrowAnyException();
}
@Test
public void closeQuietly_whenStatementAndResultSetOpen_shouldCloseBoth() throws SQLException {
try (Connection connection = dbTester.openConnection(); PreparedStatement statement = connection.prepareStatement(selectDual())) {
ResultSet rs = statement.executeQuery();
closeQuietly(rs);
closeQuietly(statement);
assertThat(isClosed(statement)).isTrue();
assertThat(isClosed(rs)).isTrue();
}
}
@Test
public void closeQuietly_whenConnectionThrowsException_shouldNotThrowException() throws SQLException {
Connection connection = mock(Connection.class);
doThrow(new SQLException()).when(connection).close();
closeQuietly(connection);
// no failure
verify(connection).close(); // just to be sure
}
@Test
public void closeQuietly_whenStatementThrowsException_shouldNotThrowException() throws SQLException {
Statement statement = mock(Statement.class);
doThrow(new SQLException()).when(statement).close();
closeQuietly(statement);
// no failure
verify(statement).close(); // just to be sure
}
@Test
public void closeQuietly_whenResultSetThrowsException_shouldNotThrowException() throws SQLException {
ResultSet rs = mock(ResultSet.class);
doThrow(new SQLException()).when(rs).close();
closeQuietly(rs);
// no failure
verify(rs).close(); // just to be sure
}
@Test
public void toUniqueAndSortedList_whenNullPassed_shouldThrowNullPointerException() {
assertThatThrownBy(() -> toUniqueAndSortedList(null))
.isInstanceOf(NullPointerException.class);
}
@Test
public void toUniqueAndSortedList_whenNullPassedInsideTheList_shouldThrowNullPointerException() {
assertThatThrownBy(() -> toUniqueAndSortedList(List.of("A", null, "C")))
.isInstanceOf(NullPointerException.class);
}
@Test
public void toUniqueAndSortedList_whenNullPassedInsideTheSet_shouldThrowNullPointerException() {
assertThatThrownBy(() -> toUniqueAndSortedList(Set.of("A", null, "C")))
.isInstanceOf(NullPointerException.class);
}
@Test
public void toUniqueAndSortedList_shouldEnforceNaturalOrder() {
assertThat(toUniqueAndSortedList(List.of("A", "B", "C"))).containsExactly("A", "B", "C");
assertThat(toUniqueAndSortedList(List.of("B", "A", "C"))).containsExactly("A", "B", "C");
assertThat(toUniqueAndSortedList(List.of("B", "C", "A"))).containsExactly("A", "B", "C");
}
@Test
public void toUniqueAndSortedList_shouldRemoveDuplicates() {
assertThat(toUniqueAndSortedList(List.of("A", "A", "A"))).containsExactly("A");
assertThat(toUniqueAndSortedList(List.of("A", "C", "A"))).containsExactly("A", "C");
assertThat(toUniqueAndSortedList(List.of("C", "C", "B", "B", "A", "N", "C", "A"))).containsExactly("A", "B", "C", "N");
}
@Test
public void toUniqueAndSortedList_shouldRemoveDuplicatesAndEnforceNaturalOrder() {
assertThat(
toUniqueAndSortedList(List.of(myComparable(2), myComparable(5), myComparable(2), myComparable(4), myComparable(-1), myComparable(10))))
.containsExactly(
myComparable(-1), myComparable(2), myComparable(4), myComparable(5), myComparable(10));
}
@Test
public void getDriver_whenIssuesWithDriver_shouldLeaveAMessageInTheLogs() throws SQLException {
Connection connection = mock(Connection.class);
DatabaseMetaData metaData = mock(DatabaseMetaData.class);
when(connection.getMetaData()).thenReturn(metaData);
when(metaData.getDriverName()).thenThrow(new SQLException());
getDriver(connection);
assertThat(logTester.logs(Level.WARN)).contains("Fail to determine database driver.");
}
@Test
public void findExistingIndex_whenResultSetThrowsException_shouldThrowExceptionToo() throws SQLException {
String indexName = "idx";
String schema = "TEST-SONAR";
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.next()).thenThrow(new SQLException());
assertThatThrownBy(() -> findExistingIndex(indexName, schema, resultSet, true))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Can not check that table test_table exists");
}
@Test
public void findExistingIndex_whenExistingIndexOnOracleDoubleQuotedSchema_shouldReturnIndex() throws SQLException {
String indexName = "idx";
String schema = "TEST-SONAR";
ResultSet resultSet = newResultSet(true, indexName, schema);
Optional<String> foundIndex = findExistingIndex(indexName, schema, resultSet, true);
assertThat(foundIndex).hasValue(indexName);
}
@Test
public void findExistingIndex_whenExistingIndexOnDefaultSchema_shouldReturnIndex() throws SQLException {
String indexName = "idx";
String schema = DEFAULT_SCHEMA;
ResultSet resultSet = newResultSet(true, indexName, schema);
Optional<String> foundIndex = findExistingIndex(indexName, schema, resultSet, true);
assertThat(foundIndex).hasValue(indexName);
}
@Test
public void findExistingIndex_whenNoExistingIndexOnOracleDoubleQuotedSchema_shouldNotReturnIndex() throws SQLException {
String indexName = "idx";
String schema = "TEST-SONAR";
ResultSet resultSet = newResultSet(false, null, null);
Optional<String> foundIndex = findExistingIndex(indexName, schema, resultSet, true);
assertThat(foundIndex).isEmpty();
}
@Test
public void findExistingIndex_whenNoMatchingIndexOnOracleDoubleQuotedSchema_shouldNotReturnIndex() throws SQLException {
String indexName = "idx";
String schema = "TEST-SONAR";
ResultSet resultSet = newResultSet(true, "different", "different");
Optional<String> foundIndex = findExistingIndex(indexName, schema, resultSet, true);
assertThat(foundIndex).isEmpty();
}
@Test
public void findExistingIndex_whenExistingIndexAndSchemaPassed_shouldFindIndex() throws SQLException {
String indexName = "idx";
String schema = DEFAULT_SCHEMA;
ResultSet resultSet = newResultSet(true, indexName, schema);
Optional<String> foundIndex = findExistingIndex(indexName, schema, resultSet, false);
assertThat(foundIndex).hasValue(indexName);
}
@Test
public void executeLargeInputs_whenALotOfElementsPassed_shouldProcessAllItems() {
List<Integer> inputs = new ArrayList<>();
List<String> expectedOutputs = new ArrayList<>();
for (int i = 0; i < 2010; i++) {
inputs.add(i);
expectedOutputs.add(Integer.toString(i));
}
List<String> outputs = DatabaseUtils.executeLargeInputs(inputs, input -> {
// Check that each partition is only done on 1000 elements max
assertThat(input).hasSizeLessThanOrEqualTo(1000);
return input.stream().map(String::valueOf).toList();
});
assertThat(outputs).isEqualTo(expectedOutputs);
}
@Test
public void executeLargeInputsWithFunctionAsInput_whenEmptyList_shouldReturnEmpty() {
List<String> outputs = DatabaseUtils.executeLargeInputs(Collections.emptyList(), (Function<List<Integer>, List<String>>) input -> {
fail("No partition should be made on empty list");
return Collections.emptyList();
});
assertThat(outputs).isEmpty();
}
@Test
public void executeLargeUpdates_whenEmptyList_shouldFail() {
DatabaseUtils.executeLargeUpdates(Collections.<Integer>emptyList(), input -> fail("No partition should be made on empty list"));
}
@Test
public void executeLargeInputs_whenPartitionSizeIsCustom_shouldParitionAccordingly() {
List<List<Integer>> partitions = new ArrayList<>();
List<Integer> outputs = DatabaseUtils.executeLargeInputs(
List.of(1, 2, 3),
partition -> {
partitions.add(partition);
return partition;
},
i -> i / 500);
assertThat(outputs).containsExactly(1, 2, 3);
assertThat(partitions).containsExactly(List.of(1, 2), List.of(3));
}
@Test
public void executeLargeUpdates_whenALotOfElementsPassed_shouldProcessAllItems() {
List<Integer> inputs = new ArrayList<>();
for (int i = 0; i < 2010; i++) {
inputs.add(i);
}
List<Integer> processed = new ArrayList<>();
DatabaseUtils.executeLargeUpdates(inputs, input -> {
assertThat(input).hasSizeLessThanOrEqualTo(1000);
processed.addAll(input);
});
assertThat(processed).containsExactlyElementsOf(inputs);
}
@Test
public void logging_whenSomeExceptionThrown_shouldContainThemInTheLog() {
SQLException root = new SQLException("this is root", "123");
SQLException next = new SQLException("this is next", "456");
root.setNextException(next);
log(LoggerFactory.getLogger(getClass()), root);
assertThat(logTester.logs(Level.ERROR)).contains("SQL error: 456. Message: this is next");
}
@Test
public void tableExists_whenTableInTheMetadata_shouldReturnTrue() throws Exception {
try (Connection connection = dbTester.openConnection()) {
assertThat(tableExists("SCHEMA_MIGRATIONS", connection)).isTrue();
assertThat(tableExists("schema_migrations", connection)).isTrue();
assertThat(tableExists("schema_MIGRATIONS", connection)).isTrue();
assertThat(tableExists("foo", connection)).isFalse();
}
}
@Test
public void tableExists_whenGetSchemaThrowException_shouldNotFail() throws Exception {
try (Connection connection = spy(dbTester.openConnection())) {
doThrow(AbstractMethodError.class).when(connection).getSchema();
assertThat(tableExists("SCHEMA_MIGRATIONS", connection)).isTrue();
assertThat(tableExists("schema_migrations", connection)).isTrue();
assertThat(tableExists("schema_MIGRATIONS", connection)).isTrue();
assertThat(tableExists("foo", connection)).isFalse();
}
}
@Test//is_using_getSchema_when_not_using_h2
public void tableExists_whenNotUsingH2_shouldReturnTrue() throws Exception {
try (Connection connection = spy(dbTester.openConnection())) {
// DatabaseMetaData mock
DatabaseMetaData metaData = mock(DatabaseMetaData.class);
doReturn("xxx").when(metaData).getDriverName();
// ResultSet mock
ResultSet resultSet = mock(ResultSet.class);
doReturn(true, false).when(resultSet).next();
doReturn(SCHEMA_MIGRATIONS_TABLE).when(resultSet).getString("TABLE_NAME");
doReturn(resultSet).when(metaData).getTables(any(), eq("yyyy"), any(), any());
// Connection mock
doReturn("yyyy").when(connection).getSchema();
doReturn(metaData).when(connection).getMetaData();
assertThat(tableExists(SCHEMA_MIGRATIONS_TABLE, connection)).isTrue();
}
}
@Test
public void checkThatNotTooManyConditions_whenLessThan1000Items_shouldNotThrowException() {
checkThatNotTooManyConditions(null, "unused");
checkThatNotTooManyConditions(Collections.emptySet(), "unused");
checkThatNotTooManyConditions(Collections.nCopies(10, "foo"), "unused");
checkThatNotTooManyConditions(Collections.nCopies(1_000, "foo"), "unused");
}
@Test
public void checkThatNotTooManyConditions_whenMoreThan1000ItemsInTheList_shouldNotThrowException() {
List<String> list = Collections.nCopies(1_001, "foo");
assertThatThrownBy(() -> checkThatNotTooManyConditions(list, "the message"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("the message");
}
private Optional<String> findExistingIndex(String indexName, String schema, ResultSet resultSet, boolean isOracle) throws SQLException {
Connection connection = mock(Connection.class);
DatabaseMetaData metaData = mock(DatabaseMetaData.class);
if (isOracle) {
when(metaData.getDriverName()).thenReturn(ORACLE_DRIVER_NAME);
}
when(metaData.getIndexInfo(anyString(), eq(DEFAULT_SCHEMA.equals(schema) ? schema : null), anyString(), anyBoolean(), anyBoolean())).thenReturn(resultSet);
when(connection.getMetaData()).thenReturn(metaData);
when(connection.getSchema()).thenReturn(schema);
when(connection.getCatalog()).thenReturn("catalog");
return DatabaseUtils.findExistingIndex(connection, "test_table", indexName);
}
private ResultSet newResultSet(boolean hasNext, String indexName, String schema) throws SQLException {
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.next()).thenReturn(hasNext).thenReturn(false);
when(resultSet.getString("INDEX_NAME")).thenReturn(indexName);
when(resultSet.getString("TABLE_SCHEM")).thenReturn(schema);
return resultSet;
}
private static DatabaseUtilsIT.MyComparable myComparable(int ordinal) {
return new DatabaseUtilsIT.MyComparable(ordinal);
}
private static final class MyComparable implements Comparable<MyComparable> {
private final int ordinal;
private MyComparable(int ordinal) {
this.ordinal = ordinal;
}
@Override
public int compareTo(MyComparable o) {
return ordinal - o.ordinal;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MyComparable that = (MyComparable) o;
return ordinal == that.ordinal;
}
@Override
public int hashCode() {
return Objects.hash(ordinal);
}
}
/**
* Connection.isClosed() has been introduced in java 1.6
*/
private boolean isClosed(Connection c) {
try {
c.createStatement().execute(selectDual());
return false;
} catch (Exception e) {
return true;
}
}
/**
* Statement.isClosed() has been introduced in java 1.6
*/
private boolean isClosed(Statement s) {
try {
s.execute("SELECT 1");
return false;
} catch (Exception e) {
return true;
}
}
/**
* ResultSet.isClosed() has been introduced in java 1.6
*/
private boolean isClosed(ResultSet rs) {
try {
rs.next();
return false;
} catch (Exception e) {
return true;
}
}
private String selectDual() {
String sql = "SELECT 1";
if (Oracle.ID.equals(dbTester.database().getDialect().getId())) {
sql = "SELECT 1 FROM DUAL";
}
return sql;
}
}
| 21,750 | 36.501724 | 176 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/it/java/org/sonar/db/ResultSetIteratorIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.NoSuchElementException;
import org.junit.Rule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public class ResultSetIteratorIT {
@Rule
public CoreDbTester dbTester = CoreDbTester.createForSchema(ResultSetIteratorIT.class, "schema.sql");
@Test
public void create_iterator_from_statement() throws Exception {
insert(10, "AB");
insert(20, "AB");
insert(30, "AB");
try (Connection connection = dbTester.openConnection()) {
PreparedStatement stmt = connection.prepareStatement("select * from issues order by id");
FirstIntColumnIterator iterator = new FirstIntColumnIterator(stmt);
assertThat(iterator.hasNext()).isTrue();
// calling multiple times hasNext() is ok
assertThat(iterator.hasNext()).isTrue();
assertThat(iterator.next()).isEqualTo(10);
assertThat(iterator.hasNext()).isTrue();
assertThat(iterator.next()).isEqualTo(20);
// call next() without calling hasNext()
assertThat(iterator.next()).isEqualTo(30);
assertThat(iterator.hasNext()).isFalse();
try {
iterator.next();
fail();
} catch (NoSuchElementException e) {
// ok
}
iterator.close();
// statement is closed by ResultSetIterator
assertThat(stmt.isClosed()).isTrue();
}
}
@Test
public void iterate_empty_list() throws Exception {
insert(10, "AB");
insert(20, "AB");
insert(30, "AB");
try (Connection connection = dbTester.openConnection()) {
PreparedStatement stmt = connection.prepareStatement("select * from issues where id < 0");
FirstIntColumnIterator iterator = new FirstIntColumnIterator(stmt);
assertThat(iterator.hasNext()).isFalse();
}
}
@Test
public void create_iterator_from_result_set() throws Exception {
insert(10, "AB");
insert(20, "AB");
insert(30, "AB");
try (Connection connection = dbTester.openConnection()) {
PreparedStatement stmt = connection.prepareStatement("select * from issues order by id");
ResultSet rs = stmt.executeQuery();
FirstIntColumnIterator iterator = new FirstIntColumnIterator(rs);
assertThat(iterator.next()).isEqualTo(10);
assertThat(iterator.next()).isEqualTo(20);
assertThat(iterator.next()).isEqualTo(30);
iterator.close();
assertThat(rs.isClosed()).isTrue();
stmt.close();
}
}
@Test
public void remove_row_is_not_supported() throws Exception {
try (Connection connection = dbTester.openConnection()) {
PreparedStatement stmt = connection.prepareStatement("select * from issues order by id");
FirstIntColumnIterator iterator = new FirstIntColumnIterator(stmt);
try {
iterator.remove();
fail();
} catch (UnsupportedOperationException ok) {
// ok
}
iterator.close();
}
}
@Test
public void fail_to_read_row() throws Exception {
insert(10, "AB");
insert(20, "AB");
insert(30, "AB");
try (Connection connection = dbTester.openConnection()) {
PreparedStatement stmt = connection.prepareStatement("select * from issues order by id");
FailIterator iterator = new FailIterator(stmt);
assertThat(iterator.hasNext()).isTrue();
try {
iterator.next();
fail();
} catch (IllegalStateException e) {
assertThat(e.getCause()).isInstanceOf(SQLException.class);
}
iterator.close();
}
}
private static class FirstIntColumnIterator extends ResultSetIterator<Integer> {
public FirstIntColumnIterator(PreparedStatement stmt) throws SQLException {
super(stmt);
}
public FirstIntColumnIterator(ResultSet rs) {
super(rs);
}
@Override
protected Integer read(ResultSet rs) throws SQLException {
return rs.getInt(1);
}
}
private static class FailIterator extends ResultSetIterator<Integer> {
public FailIterator(PreparedStatement stmt) throws SQLException {
super(stmt);
}
@Override
protected Integer read(ResultSet rs) throws SQLException {
// column does not exist
return rs.getInt(1234);
}
}
private void insert(int id, String key) {
dbTester.executeInsert(
"ISSUES",
"ID", id,
"KEE", key
);
}
}
| 5,351 | 27.92973 | 103 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/ColumnMetadata.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
public record ColumnMetadata(String name, boolean nullable, int sqlType, int limit) {
}
| 955 | 37.24 | 85 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/Database.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import javax.sql.DataSource;
import org.sonar.api.Startable;
import org.sonar.db.dialect.Dialect;
/**
* @since 2.12
*/
public interface Database extends Startable {
/**
* Returns the configured datasource. Null as long as start() is not executed.
*/
DataSource getDataSource();
/**
* @return the dialect or null if start() has not been executed
*/
Dialect getDialect();
void enableSqlLogging(boolean enable);
}
| 1,304 | 30.071429 | 80 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/DatabaseUtils.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.IntSupplier;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
public class DatabaseUtils {
private static final String TABLE_NOT_EXIST_MESSAGE = "Can not check that table %s exists";
public static final int PARTITION_SIZE_FOR_ORACLE = 1000;
public static final String ORACLE_DRIVER_NAME = "Oracle JDBC driver";
public static final Pattern ORACLE_OBJECT_NAME_RULE = Pattern.compile("\"[^\"\\u0000]+\"|\\p{L}[\\p{L}\\p{N}_$#@]*");
public static final String INDEX_NAME_VARIATION = "^idx_\\d+_%s$";
/**
* @see DatabaseMetaData#getTableTypes()
*/
private static final String[] TABLE_TYPE = {"TABLE"};
protected DatabaseUtils() {
throw new IllegalStateException("Utility class");
}
public static void closeQuietly(@Nullable Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
LoggerFactory.getLogger(DatabaseUtils.class).warn("Fail to close connection", e);
// ignore
}
}
}
public static void closeQuietly(@Nullable Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
LoggerFactory.getLogger(DatabaseUtils.class).warn("Fail to close statement", e);
// ignore
}
}
}
public static void closeQuietly(@Nullable ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
LoggerFactory.getLogger(DatabaseUtils.class).warn("Fail to close result set", e);
// ignore
}
}
}
/**
* Partition by 1000 elements a list of input and execute a function on each part.
* <p>
* The goal is to prevent issue with ORACLE when there's more than 1000 elements in a 'in ('X', 'Y', ...)'
* and with MsSQL when there's more than 2000 parameters in a query
*/
public static <OUTPUT, INPUT extends Comparable<INPUT>> List<OUTPUT> executeLargeInputs(Collection<INPUT> input, Function<List<INPUT>, List<OUTPUT>> function) {
return executeLargeInputs(input, function, i -> i);
}
/**
* Partition by 1000 elements a list of input and execute a function on each part.
* <p>
* The goal is to prevent issue with ORACLE when there's more than 1000 elements in a 'in ('X', 'Y', ...)'
* and with MsSQL when there's more than 2000 parameters in a query
*/
public static <OUTPUT, INPUT extends Comparable<INPUT>> List<OUTPUT> executeLargeInputs(Collection<INPUT> input, Function<List<INPUT>, List<OUTPUT>> function,
IntFunction<Integer> partitionSizeManipulations) {
return executeLargeInputs(input, function, size -> size == 0 ? Collections.emptyList() : new ArrayList<>(size), partitionSizeManipulations);
}
public static <OUTPUT, INPUT extends Comparable<INPUT>> Set<OUTPUT> executeLargeInputsIntoSet(Collection<INPUT> input, Function<List<INPUT>, Set<OUTPUT>> function,
IntFunction<Integer> partitionSizeManipulations) {
return executeLargeInputs(input, function, size -> size == 0 ? Collections.emptySet() : new HashSet<>(size), partitionSizeManipulations);
}
private static <OUTPUT, INPUT extends Comparable<INPUT>, RESULT extends Collection<OUTPUT>> RESULT executeLargeInputs(Collection<INPUT> input,
Function<List<INPUT>, RESULT> function, java.util.function.IntFunction<RESULT> outputInitializer, IntFunction<Integer> partitionSizeManipulations) {
if (input.isEmpty()) {
return outputInitializer.apply(0);
}
RESULT results = outputInitializer.apply(input.size());
for (List<INPUT> partition : toUniqueAndSortedPartitions(input, partitionSizeManipulations)) {
RESULT subResults = function.apply(partition);
if (subResults != null) {
results.addAll(subResults);
}
}
return results;
}
/**
* Partition by 1000 elements a list of input and execute a consumer on each part.
* <p>
* The goal is to prevent issue with ORACLE when there's more than 1000 elements in a 'in ('X', 'Y', ...)'
* and with MsSQL when there's more than 2000 parameters in a query
*/
public static <INPUT extends Comparable<INPUT>> void executeLargeUpdates(Collection<INPUT> inputs, Consumer<List<INPUT>> consumer) {
executeLargeUpdates(inputs, consumer, i -> i);
}
/**
* Partition by 1000 elements a list of input and execute a consumer on each part.
* <p>
* The goal is to prevent issue with ORACLE when there's more than 1000 elements in a 'in ('X', 'Y', ...)'
* and with MsSQL when there's more than 2000 parameters in a query
*
* @param inputs the whole list of elements to be partitioned
* @param consumer the mapper method to be executed, for example {@code mapper(dbSession)::selectByUuids}
* @param partitionSizeManipulations the function that computes the number of usages of a partition, for example
* {@code partitionSize -> partitionSize / 2} when the partition of elements
* in used twice in the SQL request.
*/
public static <INPUT extends Comparable<INPUT>> void executeLargeUpdates(Collection<INPUT> inputs, Consumer<List<INPUT>> consumer,
IntFunction<Integer> partitionSizeManipulations) {
Iterable<List<INPUT>> partitions = toUniqueAndSortedPartitions(inputs, partitionSizeManipulations);
for (List<INPUT> partition : partitions) {
consumer.accept(partition);
}
}
/**
* Ensure values {@code inputs} are unique (which avoids useless arguments) and sorted before creating the partition.
*/
public static <INPUT extends Comparable<INPUT>> Iterable<List<INPUT>> toUniqueAndSortedPartitions(Collection<INPUT> inputs) {
return toUniqueAndSortedPartitions(inputs, i -> i);
}
/**
* Ensure values {@code inputs} are unique (which avoids useless arguments) and sorted before creating the partition.
*/
public static <INPUT extends Comparable<INPUT>> Iterable<List<INPUT>> toUniqueAndSortedPartitions(Collection<INPUT> inputs, IntFunction<Integer> partitionSizeManipulations) {
int partitionSize = partitionSizeManipulations.apply(PARTITION_SIZE_FOR_ORACLE);
return Iterables.partition(toUniqueAndSortedList(inputs), partitionSize);
}
/**
* Ensure values {@code inputs} are unique (which avoids useless arguments) and sorted so that there is little
* variations of SQL requests over time as possible with a IN clause and/or a group of OR clauses. Such requests can
* then be more easily optimized by the SGDB engine.
*/
public static <INPUT extends Comparable<INPUT>> List<INPUT> toUniqueAndSortedList(Iterable<INPUT> inputs) {
if (inputs instanceof Set) {
// inputs are unique but order is not enforced
return Ordering.natural().immutableSortedCopy(inputs);
}
// inputs are not unique and order is not guaranteed
return Ordering.natural().immutableSortedCopy(Sets.newHashSet(inputs));
}
/**
* Partition by 1000 elements a list of input and execute a consumer on each part.
* <p>
* The goal is to prevent issue with ORACLE when there's more than 1000 elements in a 'in ('X', 'Y', ...)'
* and with MsSQL when there's more than 2000 parameters in a query
*/
public static <T> void executeLargeInputsWithoutOutput(Collection<T> input, Consumer<List<T>> consumer) {
if (input.isEmpty()) {
return;
}
List<List<T>> partitions = Lists.partition(new ArrayList<>(input), PARTITION_SIZE_FOR_ORACLE);
for (List<T> partition : partitions) {
consumer.accept(partition);
}
}
/**
* Logback does not log exceptions associated to {@link java.sql.SQLException#getNextException()}.
* See http://jira.qos.ch/browse/LOGBACK-775
*/
public static void log(Logger logger, SQLException e) {
SQLException next = e.getNextException();
while (next != null) {
logger.error("SQL error: {}. Message: {}", next.getSQLState(), next.getMessage());
next = next.getNextException();
}
}
@CheckForNull
public static Long getLong(ResultSet rs, String columnName) throws SQLException {
long l = rs.getLong(columnName);
return rs.wasNull() ? null : l;
}
@CheckForNull
public static Double getDouble(ResultSet rs, String columnName) throws SQLException {
double d = rs.getDouble(columnName);
return rs.wasNull() ? null : d;
}
@CheckForNull
public static Integer getInt(ResultSet rs, String columnName) throws SQLException {
int i = rs.getInt(columnName);
return rs.wasNull() ? null : i;
}
@CheckForNull
public static String getString(ResultSet rs, String columnName) throws SQLException {
String s = rs.getString(columnName);
return rs.wasNull() ? null : s;
}
@CheckForNull
public static Long getLong(ResultSet rs, int columnIndex) throws SQLException {
long l = rs.getLong(columnIndex);
return rs.wasNull() ? null : l;
}
@CheckForNull
public static Double getDouble(ResultSet rs, int columnIndex) throws SQLException {
double d = rs.getDouble(columnIndex);
return rs.wasNull() ? null : d;
}
@CheckForNull
public static Integer getInt(ResultSet rs, int columnIndex) throws SQLException {
int i = rs.getInt(columnIndex);
return rs.wasNull() ? null : i;
}
@CheckForNull
public static String getString(ResultSet rs, int columnIndex) throws SQLException {
String s = rs.getString(columnIndex);
return rs.wasNull() ? null : s;
}
@CheckForNull
public static Date getDate(ResultSet rs, int columnIndex) throws SQLException {
Timestamp t = rs.getTimestamp(columnIndex);
return rs.wasNull() ? null : new Date(t.getTime());
}
/**
* @param table case-insensitive name of table
* @return true if a table exists with this name, otherwise false
* @throws SQLException
*/
public static boolean tableExists(String table, Connection connection) {
return doTableExists(table, connection) ||
doTableExists(table.toLowerCase(Locale.ENGLISH), connection) ||
doTableExists(table.toUpperCase(Locale.ENGLISH), connection);
}
private static boolean doTableExists(String table, Connection connection) {
String schema = getSchema(connection);
// table type is used to speed-up Oracle by removing introspection of system tables and aliases.
try (ResultSet rs = connection.getMetaData().getTables(connection.getCatalog(), schema, table, TABLE_TYPE)) {
while (rs.next()) {
String name = rs.getString("TABLE_NAME");
if (table.equalsIgnoreCase(name)) {
return true;
}
}
return false;
} catch (SQLException e) {
throw wrapSqlException(e, TABLE_NOT_EXIST_MESSAGE, table);
}
}
public static boolean indexExistsIgnoreCase(String table, String index, Connection connection) {
return doIndexExistsIgnoreIndexCase(table, index, connection) ||
doIndexExistsIgnoreIndexCase(table.toLowerCase(Locale.ENGLISH), index, connection) ||
doIndexExistsIgnoreIndexCase(table.toUpperCase(Locale.ENGLISH), index, connection);
}
private static boolean doIndexExistsIgnoreIndexCase(String table, String index, Connection connection) {
return findIndex(connection, table, index).isPresent();
}
/**
* Finds an index by searching by its lower case or upper case name. If an index is found, it's name is returned with the matching case.
* This is useful when we need to drop an index that could exist with either lower case or upper case name.
* See SONAR-13594
* Related to ticket SONAR-17737, some index name can be changed to pattern idx_{number}_index_name. We also want to be able to identify and return them
*/
public static Optional<String> findExistingIndex(Connection connection, String tableName, String indexName) {
Predicate<String> indexSelector = idx -> indexName.equalsIgnoreCase(idx) || indexMatchesPattern(idx, format(INDEX_NAME_VARIATION, indexName));
return findIndex(connection, tableName.toLowerCase(Locale.US), indexSelector)
.or(() -> findIndex(connection, tableName.toUpperCase(Locale.US), indexSelector));
}
private static boolean indexMatchesPattern(@Nullable String idx, String pattern) {
return idx != null && Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(idx).matches();
}
private static Optional<String> findIndex(Connection connection, String tableName, String indexName) {
return findIndex(connection, tableName, indexName::equalsIgnoreCase);
}
private static Optional<String> findIndex(Connection connection, String tableName, Predicate<String> indexMatcher) {
String schema = getSchema(connection);
if (StringUtils.isNotEmpty(schema)) {
String driverName = getDriver(connection);
// Fix for double quoted schema name in Oracle
if (ORACLE_DRIVER_NAME.equals(driverName) && !ORACLE_OBJECT_NAME_RULE.matcher(schema).matches()) {
return getOracleIndex(connection, tableName, indexMatcher, schema);
}
}
return getIndex(connection, tableName, indexMatcher, schema);
}
private static Optional<String> getIndex(Connection connection, String tableName, Predicate<String> indexMatcher, @Nullable String schema) {
try (ResultSet rs = connection.getMetaData().getIndexInfo(connection.getCatalog(), schema, tableName, false, true)) {
while (rs.next()) {
String idx = rs.getString("INDEX_NAME");
if (indexMatcher.test(idx)) {
return Optional.of(idx);
}
}
return Optional.empty();
} catch (SQLException e) {
throw wrapSqlException(e, TABLE_NOT_EXIST_MESSAGE, tableName);
}
}
private static Optional<String> getOracleIndex(Connection connection, String tableName, Predicate<String> indexMatcher, @Nonnull String schema) {
try (ResultSet rs = connection.getMetaData().getIndexInfo(connection.getCatalog(), null, tableName, false, true)) {
while (rs.next()) {
String idx = rs.getString("INDEX_NAME");
String tableSchema = rs.getString("TABLE_SCHEM");
if (schema.equalsIgnoreCase(tableSchema) && indexMatcher.test(idx)) {
return Optional.of(idx);
}
}
return Optional.empty();
} catch (SQLException e) {
throw wrapSqlException(e, TABLE_NOT_EXIST_MESSAGE, tableName);
}
}
public static boolean tableColumnExists(Connection connection, String tableName, String columnName) {
try {
return columnExists(connection, tableName.toLowerCase(Locale.US), columnName)
|| columnExists(connection, tableName.toUpperCase(Locale.US), columnName);
} catch (SQLException e) {
throw wrapSqlException(e, "Can not check that column %s exists", columnName);
}
}
private static boolean columnExists(Connection connection, String tableName, String columnName) throws SQLException {
String schema = getSchema(connection);
try (ResultSet rs = connection.getMetaData().getColumns(connection.getCatalog(), schema, tableName, null)) {
while (rs.next()) {
// this is wrong and could lead to bugs, there is no point of going through each column - only one column contains column name
// see the contract (javadoc) of java.sql.DatabaseMetaData.getColumns
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
String name = rs.getString(i);
if (columnName.equalsIgnoreCase(name)) {
return true;
}
}
}
return false;
}
}
@CheckForNull
public static ColumnMetadata getColumnMetadata(Connection connection, String tableName, String columnName) throws SQLException {
ColumnMetadata columnMetadataLowerCase = getColumnMetadataWithCaseSensitiveTableName(connection, tableName.toLowerCase(Locale.US), columnName);
if (columnMetadataLowerCase != null) {
return columnMetadataLowerCase;
}
return getColumnMetadataWithCaseSensitiveTableName(connection, tableName.toUpperCase(Locale.US), columnName);
}
@CheckForNull
public static ColumnMetadata getColumnMetadataWithCaseSensitiveTableName(Connection connection, String tableName, String columnName) throws SQLException {
String schema = getSchema(connection);
try (ResultSet rs = connection.getMetaData().getColumns(connection.getCatalog(), schema, tableName, null)) {
while (rs.next()) {
String name = rs.getString(4);
int type = rs.getInt(5);
int limit = rs.getInt(7);
boolean nullable = rs.getBoolean(11);
if (columnName.equalsIgnoreCase(name)) {
return new ColumnMetadata(name, nullable, type, limit);
}
}
return null;
}
}
@CheckForNull
static String getDriver(Connection connection) {
try {
return connection.getMetaData().getDriverName();
} catch (SQLException e) {
LoggerFactory.getLogger(DatabaseUtils.class).warn("Fail to determine database driver.", e);
return null;
}
}
@CheckForNull
private static String getSchema(Connection connection) {
String schema = null;
try {
// Using H2 with a JDBC TCP connection is throwing an exception
// See org.h2.engine.SessionRemote#getCurrentSchemaName()
if (!"H2 JDBC Driver".equals(connection.getMetaData().getDriverName())) {
schema = connection.getSchema();
}
} catch (SQLException e) {
LoggerFactory.getLogger(DatabaseUtils.class).warn("Fail to determine schema. Keeping it null for searching tables", e);
}
return schema;
}
public static IllegalStateException wrapSqlException(SQLException e, String message, Object... messageArgs) {
return new IllegalStateException(format(message, messageArgs), e);
}
/**
* This method can be used as a method reference, for not to have to handle the checked exception {@link SQLException}
*/
public static Consumer<String> setStrings(PreparedStatement stmt, IntSupplier index) {
return value -> {
try {
stmt.setString(index.getAsInt(), value);
} catch (SQLException e) {
Throwables.propagate(e);
}
};
}
/**
* @throws IllegalArgumentException if the collection is not null and has strictly more
* than {@link #PARTITION_SIZE_FOR_ORACLE} values.
*/
public static void checkThatNotTooManyConditions(@Nullable Collection<?> values, String message) {
if (values != null) {
checkArgument(values.size() <= PARTITION_SIZE_FOR_ORACLE, message);
}
}
}
| 20,454 | 40.074297 | 176 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/DefaultDatabase.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import ch.qos.logback.classic.Level;
import com.google.common.annotations.VisibleForTesting;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.config.internal.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.DialectUtils;
import org.sonar.db.profiling.NullConnectionInterceptor;
import org.sonar.db.profiling.ProfiledConnectionInterceptor;
import org.sonar.db.profiling.ProfiledDataSource;
import org.sonar.process.logging.LogbackHelper;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static org.sonar.process.ProcessProperties.Property.JDBC_EMBEDDED_PORT;
import static org.sonar.process.ProcessProperties.Property.JDBC_MAX_IDLE_TIMEOUT;
import static org.sonar.process.ProcessProperties.Property.JDBC_MAX_KEEP_ALIVE_TIME;
import static org.sonar.process.ProcessProperties.Property.JDBC_MAX_LIFETIME;
import static org.sonar.process.ProcessProperties.Property.JDBC_MIN_IDLE;
import static org.sonar.process.ProcessProperties.Property.JDBC_PASSWORD;
import static org.sonar.process.ProcessProperties.Property.JDBC_URL;
import static org.sonar.process.ProcessProperties.Property.JDBC_USERNAME;
import static org.sonar.process.ProcessProperties.Property.JDBC_VALIDATION_TIMEOUT;
/**
* @since 2.12
*/
public class DefaultDatabase implements Database {
private static final String IGNORED_KEYWORDS_OPTION = ";NON_KEYWORDS=VALUE";
private static final Logger LOG = LoggerFactory.getLogger(DefaultDatabase.class);
private static final String DEFAULT_URL = "jdbc:h2:tcp://localhost/sonar" + IGNORED_KEYWORDS_OPTION;
private static final String SONAR_JDBC = "sonar.jdbc.";
private static final String SONAR_JDBC_DIALECT = "sonar.jdbc.dialect";
private static final String SONAR_JDBC_DRIVER = "sonar.jdbc.driverClassName";
private static final String SONAR_JDBC_MAX_ACTIVE = "sonar.jdbc.maxActive";
private static final String SONAR_JDBC_MAX_WAIT = "sonar.jdbc.maxWait";
private static final Set<String> DEPRECATED_SONAR_PROPERTIES = Set.of(
"sonar.jdbc.maxIdle",
"sonar.jdbc.minEvictableIdleTimeMillis",
"sonar.jdbc.timeBetweenEvictionRunsMillis");
private static final Set<String> ALLOWED_SONAR_PROPERTIES = Set.of(
JDBC_USERNAME.getKey(),
JDBC_PASSWORD.getKey(),
JDBC_EMBEDDED_PORT.getKey(),
JDBC_URL.getKey(),
JDBC_MIN_IDLE.getKey(),
SONAR_JDBC_MAX_WAIT,
SONAR_JDBC_MAX_ACTIVE,
// allowed hikari cp direct properties
// see: https://github.com/brettwooldridge/HikariCP#frequently-used
SONAR_JDBC_DRIVER,
"sonar.jdbc.dataSource.user",
"sonar.jdbc.dataSource.password",
"sonar.jdbc.dataSource.portNumber",
"sonar.jdbc.jdbcUrl",
"sonar.jdbc.connectionTimeout",
"sonar.jdbc.maximumPoolSize",
"sonar.jdbc.minimumIdle",
"sonar.jdbc.schema",
JDBC_VALIDATION_TIMEOUT.getKey(),
"sonar.jdbc.catalog",
"sonar.jdbc.initializationFailTimeout",
JDBC_MAX_LIFETIME.getKey(),
"sonar.jdbc.leakDetectionThreshold",
JDBC_MAX_KEEP_ALIVE_TIME.getKey(),
JDBC_MAX_IDLE_TIMEOUT.getKey()
);
private static final Map<String, String> SONAR_JDBC_TO_HIKARI_PROPERTY_MAPPINGS = Map.of(
JDBC_USERNAME.getKey(), "dataSource.user",
JDBC_PASSWORD.getKey(), "dataSource.password",
JDBC_EMBEDDED_PORT.getKey(), "dataSource.portNumber",
JDBC_URL.getKey(), "jdbcUrl",
SONAR_JDBC_MAX_WAIT, "connectionTimeout",
SONAR_JDBC_MAX_ACTIVE, "maximumPoolSize",
JDBC_MIN_IDLE.getKey(), "minimumIdle");
private final LogbackHelper logbackHelper;
private final Settings settings;
private ProfiledDataSource datasource;
private Dialect dialect;
private Properties properties;
public DefaultDatabase(LogbackHelper logbackHelper, Settings settings) {
this.logbackHelper = logbackHelper;
this.settings = settings;
}
@Override
public void start() {
initSettings();
try {
initDataSource();
checkConnection();
} catch (Exception e) {
throw new IllegalStateException("Fail to connect to database", e);
}
}
@VisibleForTesting
void initSettings() {
properties = new Properties();
completeProperties(settings, properties, SONAR_JDBC);
completeDefaultProperty(properties, JDBC_URL.getKey(), DEFAULT_URL);
doCompleteProperties(properties);
String jdbcUrl = properties.getProperty(JDBC_URL.getKey());
dialect = DialectUtils.find(properties.getProperty(SONAR_JDBC_DIALECT), jdbcUrl);
properties.setProperty(SONAR_JDBC_DRIVER, dialect.getDefaultDriverClassName());
}
private void initDataSource() {
LOG.info("Create JDBC data source for {}", properties.getProperty(JDBC_URL.getKey(), DEFAULT_URL));
HikariDataSource ds = createHikariDataSource();
datasource = new ProfiledDataSource(ds, NullConnectionInterceptor.INSTANCE);
enableSqlLogging(datasource, logbackHelper.getLoggerLevel("sql") == Level.TRACE);
}
private HikariDataSource createHikariDataSource() {
HikariConfig config = new HikariConfig(extractCommonsHikariProperties(properties));
if (!dialect.getConnectionInitStatements().isEmpty()) {
config.setConnectionInitSql(dialect.getConnectionInitStatements().get(0));
}
config.setConnectionTestQuery(dialect.getValidationQuery());
return new HikariDataSource(config);
}
private void checkConnection() {
Connection connection = null;
try {
connection = datasource.getConnection();
dialect.init(connection.getMetaData());
} catch (SQLException e) {
throw new IllegalStateException("Can not connect to database. Please check connectivity and settings (see the properties prefixed by 'sonar.jdbc.').", e);
} finally {
DatabaseUtils.closeQuietly(connection);
}
}
@Override
public void stop() {
if (datasource != null) {
datasource.close();
}
}
@Override
public final Dialect getDialect() {
return dialect;
}
@Override
public final DataSource getDataSource() {
return datasource;
}
public final Properties getProperties() {
return properties;
}
@Override
public void enableSqlLogging(boolean enable) {
enableSqlLogging(datasource, enable);
}
private static void enableSqlLogging(ProfiledDataSource ds, boolean enable) {
ds.setConnectionInterceptor(enable ? ProfiledConnectionInterceptor.INSTANCE : NullConnectionInterceptor.INSTANCE);
}
/**
* Override this method to add JDBC properties at runtime
*/
protected void doCompleteProperties(Properties properties) {
// open-close principle
}
private static void completeProperties(Settings settings, Properties properties, String prefix) {
List<String> jdbcKeys = settings.getKeysStartingWith(prefix);
for (String jdbcKey : jdbcKeys) {
String value = settings.getString(jdbcKey);
properties.setProperty(jdbcKey, value);
}
}
@VisibleForTesting
static Properties extractCommonsHikariProperties(Properties properties) {
Properties result = new Properties();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String key = (String) entry.getKey();
if (!ALLOWED_SONAR_PROPERTIES.contains(key)) {
if (DEPRECATED_SONAR_PROPERTIES.contains(key)) {
LOG.warn("Property [{}] has no effect as pool connection implementation changed, check 9.7 upgrade notes.", key);
}
continue;
}
if (StringUtils.startsWith(key, SONAR_JDBC)) {
String resolvedKey = toHikariPropertyKey(key);
String existingValue = (String) result.setProperty(resolvedKey, (String) entry.getValue());
checkState(existingValue == null || existingValue.equals(entry.getValue()),
"Duplicate property declaration for resolved jdbc key '%s': conflicting values are '%s' and '%s'", resolvedKey, existingValue, entry.getValue());
result.setProperty(resolvedKey, (String) entry.getValue());
}
}
return result;
}
private static void completeDefaultProperty(Properties props, String key, String defaultValue) {
if (props.getProperty(key) == null) {
props.setProperty(key, defaultValue);
}
}
private static String toHikariPropertyKey(String key) {
if (SONAR_JDBC_TO_HIKARI_PROPERTY_MAPPINGS.containsKey(key)) {
return SONAR_JDBC_TO_HIKARI_PROPERTY_MAPPINGS.get(key);
}
return StringUtils.removeStart(key, SONAR_JDBC);
}
@Override
public String toString() {
return format("Database[%s]", properties != null ? properties.getProperty(JDBC_URL.getKey()) : "?");
}
}
| 9,758 | 36.534615 | 160 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/ResultSetIterator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import java.io.Closeable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Forward-only {@link java.util.Iterator} over a {@link java.sql.ResultSet}. Rows are
* lazily loaded. The underlying ResultSet must be closed by calling the method
* {@link #close()}
* <p/>
* As a safeguard, the ResultSet is automatically closed after the last element has
* been retrieved via {@link #next()} or {@link #hasNext()} is called (which will return false).
* This automagic behavior is not enough to remove explicit calls to {@link #close()}
* from caller methods. Errors raised before end of traversal must still be handled.
*/
public abstract class ResultSetIterator<E> implements Iterator<E>, Closeable {
private final ResultSet rs;
private final PreparedStatement stmt;
private volatile boolean didNext = false;
private volatile boolean hasNext = false;
private volatile boolean closed = false;
public ResultSetIterator(PreparedStatement stmt) throws SQLException {
this.stmt = stmt;
this.rs = stmt.executeQuery();
}
protected ResultSetIterator(ResultSet rs) {
this.stmt = null;
this.rs = rs;
}
@Override
public boolean hasNext() {
if (closed) {
return false;
}
if (!didNext) {
hasNext = doNextQuietly();
if (hasNext) {
didNext = true;
} else {
close();
}
}
return hasNext;
}
@Override
public E next() {
if (!hasNext()) {
close();
throw new NoSuchElementException();
}
try {
return read(rs);
} catch (SQLException e) {
throw new IllegalStateException("Fail to read result set row", e);
} finally {
hasNext = doNextQuietly();
if (!hasNext) {
close();
}
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void close() {
closed = true;
DatabaseUtils.closeQuietly(rs);
DatabaseUtils.closeQuietly(stmt);
}
protected abstract E read(ResultSet rs) throws SQLException;
private boolean doNextQuietly() {
try {
return rs.next();
} catch (SQLException e) {
throw new IllegalStateException("Fail to read row of JDBC result set", e);
}
}
}
| 3,213 | 27.192982 | 96 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/RowNotFoundException.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
/**
* The RuntimeException thrown by default when a element is not found at the DAO layer.
* When selecting by id or key, the methods respect one of the following pattern:
* <ul>
* <li>selectOrFailByKey return the element or throws a RowNotFoundException</li>
* <li>selectByUuid return an Optional (now) or a nullable element (legacy)</li>
* </ul>
*/
public class RowNotFoundException extends RuntimeException {
public RowNotFoundException(String message) {
super(message);
}
}
| 1,363 | 37.971429 | 87 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/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.db;
import javax.annotation.ParametersAreNonnullByDefault;
| 953 | 37.16 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/dialect/AbstractDialect.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.dialect;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.Version;
abstract class AbstractDialect implements Dialect {
private final String id;
private final String defaultDriverClassName;
private final String trueSqlValue;
private final String falseSqlValue;
private final String validationQuery;
protected AbstractDialect(String id, String defaultDriverClassName, String trueSqlValue, String falseSqlValue,
String validationQuery) {
this.id = id;
this.defaultDriverClassName = defaultDriverClassName;
this.trueSqlValue = trueSqlValue;
this.falseSqlValue = falseSqlValue;
this.validationQuery = validationQuery;
}
@Override
public String getId() {
return id;
}
@Override
public String getDefaultDriverClassName() {
return defaultDriverClassName;
}
@Override
public final String getTrueSqlValue() {
return trueSqlValue;
}
@Override
public final String getFalseSqlValue() {
return falseSqlValue;
}
@Override
public String getSqlFromDual() {
return "";
}
@Override
public final String getValidationQuery() {
return validationQuery;
}
@Override
public List<String> getConnectionInitStatements() {
return Collections.emptyList();
}
@Override
public boolean supportsUpsert() {
return false;
}
Version checkDbVersion(DatabaseMetaData metaData, Version minSupported) throws SQLException {
int major = metaData.getDatabaseMajorVersion();
int minor = metaData.getDatabaseMinorVersion();
Version version = Version.create(major, minor, 0);
if (version.compareTo(minSupported) < 0) {
throw MessageException.of(String.format(
"Unsupported %s version: %s. Minimal supported version is %s.", getId(), version, minSupported));
}
return version;
}
}
| 2,809 | 28.270833 | 112 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/dialect/Dialect.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.dialect;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.List;
import org.sonar.api.utils.MessageException;
public interface Dialect {
String getId();
/**
* Used to autodetect dialect from connection URL
*/
boolean matchesJdbcUrl(String jdbcConnectionURL);
String getDefaultDriverClassName();
List<String> getConnectionInitStatements();
String getTrueSqlValue();
String getFalseSqlValue();
String getSqlFromDual();
/**
* Query used to validate the jdbc connection.
*/
String getValidationQuery();
/**
* Fetch size to be used when scrolling large result sets.
*/
default int getScrollDefaultFetchSize() {
return 200;
}
/**
* Indicates whether DB migration can be perform on the DB vendor implementation associated with the current dialect.
*/
boolean supportsMigration();
boolean supportsUpsert();
/**
* This method is called when connecting for the first
* time to the database.
*
* @throws MessageException when validation error must be displayed to user
* @throws SQLException in case of error to run the validations
*/
void init(DatabaseMetaData metaData) throws SQLException;
}
| 2,075 | 27.054054 | 119 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/dialect/DialectUtils.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.dialect;
import com.google.common.collect.ImmutableSet;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.utils.MessageException;
public final class DialectUtils {
private static final Set<Supplier<Dialect>> DIALECTS = ImmutableSet.of(H2::new, Oracle::new, PostgreSql::new, MsSql::new);
private DialectUtils() {
// only static stuff
}
public static Dialect find(String dialectId, String jdbcConnectionUrl) {
Optional<Dialect> match = StringUtils.isNotBlank(dialectId) ? findById(dialectId) : findByJdbcUrl(jdbcConnectionUrl);
return match.orElseThrow(() -> MessageException.of(
"Unable to determine database dialect to use within sonar with dialect " + dialectId + " jdbc url " + jdbcConnectionUrl));
}
private static Optional<Dialect> findByJdbcUrl(String jdbcConnectionUrl) {
return findDialect(dialect -> dialect != null && dialect.matchesJdbcUrl(StringUtils.trimToEmpty(jdbcConnectionUrl)));
}
private static Optional<Dialect> findById(String dialectId) {
return findDialect(dialect -> dialect != null && dialect.getId().equals(dialectId));
}
private static Optional<Dialect> findDialect(Predicate<Dialect> predicate) {
return DIALECTS.stream()
.map(Supplier::get)
.filter(predicate)
.findFirst();
}
}
| 2,285 | 37.745763 | 128 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/dialect/H2.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.dialect;
import java.sql.DatabaseMetaData;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
public class H2 extends AbstractDialect {
public static final String ID = "h2";
public H2() {
super(ID, "org.h2.Driver", "true", "false", "SELECT 1");
}
@Override
public boolean matchesJdbcUrl(String jdbcConnectionURL) {
return StringUtils.startsWithIgnoreCase(jdbcConnectionURL, "jdbc:h2:");
}
@Override
public boolean supportsMigration() {
return false;
}
@Override
public void init(DatabaseMetaData metaData) {
LoggerFactory.getLogger(getClass()).warn("H2 database should be used for evaluation purpose only.");
}
}
| 1,549 | 30.632653 | 104 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/dialect/MsSql.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.dialect;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.utils.Version;
public class MsSql extends AbstractDialect {
public static final String ID = "mssql";
// SqlServer 2014 is 12.x
// https://support.microsoft.com/en-us/kb/321185
private static final Version MIN_SUPPORTED_VERSION = Version.create(12, 0, 0);
public MsSql() {
super(ID, "com.microsoft.sqlserver.jdbc.SQLServerDriver", "1", "0", "SELECT 1");
}
@Override
public boolean matchesJdbcUrl(String jdbcConnectionURL) {
return StringUtils.startsWithIgnoreCase(jdbcConnectionURL, "jdbc:sqlserver:");
}
@Override
public boolean supportsMigration() {
return true;
}
@Override
public void init(DatabaseMetaData metaData) throws SQLException {
checkDbVersion(metaData, MIN_SUPPORTED_VERSION);
}
}
| 1,751 | 31.444444 | 84 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/dialect/Oracle.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.dialect;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.Version;
public class Oracle extends AbstractDialect {
public static final String ID = "oracle";
private static final List<String> INIT_STATEMENTS = List.of("ALTER SESSION SET NLS_SORT='BINARY'");
private static final Version MIN_SUPPORTED_VERSION = Version.create(11, 0, 0);
public Oracle() {
super(ID, "oracle.jdbc.OracleDriver", "1", "0", "SELECT 1 FROM DUAL");
}
@Override
public boolean matchesJdbcUrl(String jdbcConnectionURL) {
return StringUtils.startsWithIgnoreCase(jdbcConnectionURL, "jdbc:oracle:");
}
@Override
public boolean supportsMigration() {
return true;
}
@Override
public List<String> getConnectionInitStatements() {
return INIT_STATEMENTS;
}
@Override
public String getSqlFromDual() {
return "from dual";
}
@Override
public void init(DatabaseMetaData metaData) throws SQLException {
checkDbVersion(metaData, MIN_SUPPORTED_VERSION);
checkDriverVersion(metaData);
}
private static void checkDriverVersion(DatabaseMetaData metaData) throws SQLException {
String driverVersion = metaData.getDriverVersion();
String[] parts = StringUtils.split(driverVersion, ".");
int intVersion = Integer.parseInt(parts[0]) * 100 + Integer.parseInt(parts[1]);
if (intVersion < 1200) {
throw MessageException.of(String.format(
"Unsupported Oracle driver version: %s. Minimal supported version is 12.1.", driverVersion));
}
}
}
| 2,518 | 33.040541 | 101 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/dialect/PostgreSql.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.dialect;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.utils.Version;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkState;
public class PostgreSql extends AbstractDialect {
public static final String ID = "postgresql";
static final List<String> INIT_STATEMENTS = List.of("SET standard_conforming_strings=on", "SET backslash_quote=off");
private static final Version MIN_SUPPORTED_VERSION = Version.create(9, 3, 0);
private static final Version MIN_UPSERT_VERSION = Version.create(9, 5, 0);
private boolean initialized = false;
private boolean supportsUpsert = false;
public PostgreSql() {
super(ID, "org.postgresql.Driver", "true", "false", "SELECT 1");
}
@Override
public boolean matchesJdbcUrl(String jdbcConnectionURL) {
return StringUtils.startsWithIgnoreCase(jdbcConnectionURL, "jdbc:postgresql:");
}
@Override
public List<String> getConnectionInitStatements() {
return INIT_STATEMENTS;
}
@Override
public boolean supportsMigration() {
return true;
}
@Override
public boolean supportsUpsert() {
checkState(initialized, "onInit() must be called before calling supportsUpsert()");
return supportsUpsert;
}
@Override
public void init(DatabaseMetaData metaData) throws SQLException {
checkState(!initialized, "onInit() must be called once");
Version version = checkDbVersion(metaData, MIN_SUPPORTED_VERSION);
supportsUpsert = version.compareTo(MIN_UPSERT_VERSION) >= 0;
if (!supportsUpsert) {
LoggerFactory.getLogger(getClass()).warn("Upgrading PostgreSQL to {} or greater is recommended for better performances", MIN_UPSERT_VERSION);
}
initialized = true;
}
}
| 2,687 | 33.025316 | 147 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/dialect/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.db.dialect;
import javax.annotation.ParametersAreNonnullByDefault;
| 961 | 37.48 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/profiling/ConnectionInterceptor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.profiling;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
public interface ConnectionInterceptor {
Connection getConnection(DataSource dataSource) throws SQLException;
Connection getConnection(DataSource dataSource, String login, String password) throws SQLException;
}
| 1,183 | 34.878788 | 101 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/profiling/InvocationUtils.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.profiling;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class InvocationUtils {
private InvocationUtils() {
// Only private stuff
}
static Object invokeQuietly(Object target, Method method, Object[] params) throws Throwable {
Object result = null;
try {
result = method.invoke(target, params);
} catch (InvocationTargetException invocationException) {
for (Class<?> exceptionClass : method.getExceptionTypes()) {
if (exceptionClass.isInstance(invocationException.getCause())) {
throw invocationException.getCause();
}
throw new IllegalStateException(invocationException.getCause());
}
}
return result;
}
}
| 1,598 | 33.76087 | 95 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/profiling/NullConnectionInterceptor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.profiling;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
public enum NullConnectionInterceptor implements ConnectionInterceptor {
INSTANCE;
@Override
public Connection getConnection(DataSource dataSource) throws SQLException {
return dataSource.getConnection();
}
@Override
public Connection getConnection(DataSource dataSource, String user, String password) throws SQLException {
return dataSource.getConnection(user, password);
}
}
| 1,365 | 34.025641 | 108 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/profiling/ProfiledConnectionInterceptor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.profiling;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
public enum ProfiledConnectionInterceptor implements ConnectionInterceptor {
INSTANCE;
@Override
public Connection getConnection(DataSource dataSource) throws SQLException {
return buildConnectionProxy(new ProfilingConnectionHandler(dataSource.getConnection()));
}
@Override
public Connection getConnection(DataSource dataSource, String login, String password) throws SQLException {
return buildConnectionProxy(new ProfilingConnectionHandler(dataSource.getConnection(login, password)));
}
private static Connection buildConnectionProxy(ProfilingConnectionHandler connectionHandler) {
ClassLoader classloader = ProfiledConnectionInterceptor.class.getClassLoader();
return (Connection) Proxy.newProxyInstance(classloader, new Class[] {Connection.class}, connectionHandler);
}
}
| 1,810 | 38.369565 | 111 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/profiling/ProfiledDataSource.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.profiling;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariConfigMXBean;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.HikariPoolMXBean;
import com.zaxxer.hikari.metrics.MetricsTrackerFactory;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ConnectionBuilder;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.ShardingKeyBuilder;
import java.util.Properties;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import javax.sql.DataSource;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
public class ProfiledDataSource extends HikariDataSource {
static final Logger SQL_LOGGER = Loggers.get("sql");
private final HikariDataSource delegate;
private ConnectionInterceptor connectionInterceptor;
public ProfiledDataSource(HikariDataSource delegate, ConnectionInterceptor connectionInterceptor) {
this.delegate = delegate;
this.connectionInterceptor = connectionInterceptor;
}
public HikariDataSource getDelegate() {
return delegate;
}
public synchronized void setConnectionInterceptor(ConnectionInterceptor ci) {
this.connectionInterceptor = ci;
}
@Override
public boolean isAutoCommit() {
return delegate.isAutoCommit();
}
@Override
public boolean isReadOnly() {
return delegate.isReadOnly();
}
@Override
public String getTransactionIsolation() {
return delegate.getTransactionIsolation();
}
@Override
public void setTransactionIsolation(String defaultTransactionIsolation) {
delegate.setTransactionIsolation(defaultTransactionIsolation);
}
@Override
public String getCatalog() {
return delegate.getCatalog();
}
@Override
public void setCatalog(String defaultCatalog) {
delegate.setCatalog(defaultCatalog);
}
@Override
public synchronized String getDriverClassName() {
return delegate.getDriverClassName();
}
@Override
public synchronized void setDriverClassName(String driverClassName) {
delegate.setDriverClassName(driverClassName);
}
@Override
public int getMaximumPoolSize() {
return delegate.getMaximumPoolSize();
}
@Override
public void setMaximumPoolSize(int maxActive) {
delegate.setMaximumPoolSize(maxActive);
}
@Override
public Connection getConnection() throws SQLException {
return connectionInterceptor.getConnection(delegate);
}
@Override
public Connection getConnection(String login, String password) throws SQLException {
return connectionInterceptor.getConnection(this, login, password);
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return delegate.getLogWriter();
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
delegate.setLogWriter(out);
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
delegate.setLoginTimeout(seconds);
}
@Override
public int getLoginTimeout() throws SQLException {
return delegate.getLoginTimeout();
}
@Override
public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
return delegate.getParentLogger();
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return delegate.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return delegate.isWrapperFor(iface);
}
@Override
public void setMetricRegistry(Object metricRegistry) {
delegate.setMetricRegistry(metricRegistry);
}
@Override
public void setMetricsTrackerFactory(MetricsTrackerFactory metricsTrackerFactory) {
delegate.setMetricsTrackerFactory(metricsTrackerFactory);
}
@Override
public void setHealthCheckRegistry(Object healthCheckRegistry) {
delegate.setHealthCheckRegistry(healthCheckRegistry);
}
@Override
public boolean isRunning() {
return delegate.isRunning();
}
@Override
public HikariPoolMXBean getHikariPoolMXBean() {
return delegate.getHikariPoolMXBean();
}
@Override
public HikariConfigMXBean getHikariConfigMXBean() {
return delegate.getHikariConfigMXBean();
}
@Override
public void evictConnection(Connection connection) {
delegate.evictConnection(connection);
}
@Override
public void close() {
delegate.close();
}
@Override
public boolean isClosed() {
return delegate.isClosed();
}
@Override
public String toString() {
return delegate.toString();
}
@Override
public long getConnectionTimeout() {
return delegate.getConnectionTimeout();
}
@Override
public void setConnectionTimeout(long connectionTimeoutMs) {
delegate.setConnectionTimeout(connectionTimeoutMs);
}
@Override
public long getIdleTimeout() {
return delegate.getIdleTimeout();
}
@Override
public void setIdleTimeout(long idleTimeoutMs) {
delegate.setIdleTimeout(idleTimeoutMs);
}
@Override
public long getLeakDetectionThreshold() {
return delegate.getLeakDetectionThreshold();
}
@Override
public void setLeakDetectionThreshold(long leakDetectionThresholdMs) {
delegate.setLeakDetectionThreshold(leakDetectionThresholdMs);
}
@Override
public long getMaxLifetime() {
return delegate.getMaxLifetime();
}
@Override
public void setMaxLifetime(long maxLifetimeMs) {
delegate.setMaxLifetime(maxLifetimeMs);
}
@Override
public int getMinimumIdle() {
return delegate.getMinimumIdle();
}
@Override
public void setMinimumIdle(int minIdle) {
delegate.setMinimumIdle(minIdle);
}
@Override
public String getPassword() {
return delegate.getPassword();
}
@Override
public void setPassword(String password) {
delegate.setPassword(password);
}
@Override
public String getUsername() {
return delegate.getUsername();
}
@Override
public void setUsername(String username) {
delegate.setUsername(username);
}
@Override
public long getValidationTimeout() {
return delegate.getValidationTimeout();
}
@Override
public void setValidationTimeout(long validationTimeoutMs) {
delegate.setValidationTimeout(validationTimeoutMs);
}
@Override
public String getConnectionTestQuery() {
return delegate.getConnectionTestQuery();
}
@Override
public void setConnectionTestQuery(String connectionTestQuery) {
delegate.setConnectionTestQuery(connectionTestQuery);
}
@Override
public String getConnectionInitSql() {
return delegate.getConnectionInitSql();
}
@Override
public void setConnectionInitSql(String connectionInitSql) {
delegate.setConnectionInitSql(connectionInitSql);
}
@Override
public DataSource getDataSource() {
return delegate.getDataSource();
}
@Override
public void setDataSource(DataSource dataSource) {
delegate.setDataSource(dataSource);
}
@Override
public String getDataSourceClassName() {
return delegate.getDataSourceClassName();
}
@Override
public void setDataSourceClassName(String className) {
delegate.setDataSourceClassName(className);
}
@Override
public void addDataSourceProperty(String propertyName, Object value) {
delegate.addDataSourceProperty(propertyName, value);
}
@Override
public String getDataSourceJNDI() {
return delegate.getDataSourceJNDI();
}
@Override
public void setDataSourceJNDI(String jndiDataSource) {
delegate.setDataSourceJNDI(jndiDataSource);
}
@Override
public Properties getDataSourceProperties() {
return delegate.getDataSourceProperties();
}
@Override
public void setDataSourceProperties(Properties dsProperties) {
delegate.setDataSourceProperties(dsProperties);
}
@Override
public String getJdbcUrl() {
return delegate.getJdbcUrl();
}
@Override
public void setJdbcUrl(String jdbcUrl) {
delegate.setJdbcUrl(jdbcUrl);
}
@Override
public void setAutoCommit(boolean isAutoCommit) {
delegate.setAutoCommit(isAutoCommit);
}
@Override
public boolean isAllowPoolSuspension() {
return delegate.isAllowPoolSuspension();
}
@Override
public void setAllowPoolSuspension(boolean isAllowPoolSuspension) {
delegate.setAllowPoolSuspension(isAllowPoolSuspension);
}
@Override
public long getInitializationFailTimeout() {
return delegate.getInitializationFailTimeout();
}
@Override
public void setInitializationFailTimeout(long initializationFailTimeout) {
delegate.setInitializationFailTimeout(initializationFailTimeout);
}
@Override
public boolean isIsolateInternalQueries() {
return delegate.isIsolateInternalQueries();
}
@Override
public void setIsolateInternalQueries(boolean isolate) {
delegate.setIsolateInternalQueries(isolate);
}
@Override
public MetricsTrackerFactory getMetricsTrackerFactory() {
return delegate.getMetricsTrackerFactory();
}
@Override
public Object getMetricRegistry() {
return delegate.getMetricRegistry();
}
@Override
public Object getHealthCheckRegistry() {
return delegate.getHealthCheckRegistry();
}
@Override
public Properties getHealthCheckProperties() {
return delegate.getHealthCheckProperties();
}
@Override
public void setHealthCheckProperties(Properties healthCheckProperties) {
delegate.setHealthCheckProperties(healthCheckProperties);
}
@Override
public void addHealthCheckProperty(String key, String value) {
delegate.addHealthCheckProperty(key, value);
}
@Override
public long getKeepaliveTime() {
return delegate.getKeepaliveTime();
}
@Override
public void setKeepaliveTime(long keepaliveTimeMs) {
delegate.setKeepaliveTime(keepaliveTimeMs);
}
@Override
public void setReadOnly(boolean readOnly) {
delegate.setReadOnly(readOnly);
}
@Override
public boolean isRegisterMbeans() {
return delegate.isRegisterMbeans();
}
@Override
public void setRegisterMbeans(boolean register) {
delegate.setRegisterMbeans(register);
}
@Override
public String getPoolName() {
return delegate.getPoolName();
}
@Override
public void setPoolName(String poolName) {
delegate.setPoolName(poolName);
}
@Override
public ScheduledExecutorService getScheduledExecutor() {
return delegate.getScheduledExecutor();
}
@Override
public void setScheduledExecutor(ScheduledExecutorService executor) {
delegate.setScheduledExecutor(executor);
}
@Override
public String getSchema() {
return delegate.getSchema();
}
@Override
public void setSchema(String schema) {
delegate.setSchema(schema);
}
@Override
public String getExceptionOverrideClassName() {
return delegate.getExceptionOverrideClassName();
}
@Override
public void setExceptionOverrideClassName(String exceptionOverrideClassName) {
delegate.setExceptionOverrideClassName(exceptionOverrideClassName);
}
@Override
public ThreadFactory getThreadFactory() {
return delegate.getThreadFactory();
}
@Override
public void setThreadFactory(ThreadFactory threadFactory) {
delegate.setThreadFactory(threadFactory);
}
@Override
public void copyStateTo(HikariConfig other) {
delegate.copyStateTo(other);
}
@Override
public void validate() {
delegate.validate();
}
@Override
public ConnectionBuilder createConnectionBuilder() throws SQLException {
return delegate.createConnectionBuilder();
}
@Override
public ShardingKeyBuilder createShardingKeyBuilder() throws SQLException {
return delegate.createShardingKeyBuilder();
}
}
| 12,530 | 23.005747 | 101 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/profiling/ProfilingConnectionHandler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.profiling;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
class ProfilingConnectionHandler implements InvocationHandler {
private final Connection connection;
ProfilingConnectionHandler(Connection connection) {
this.connection = connection;
}
@Override
public Object invoke(Object target, Method method, Object[] args) throws Throwable {
Object result = InvocationUtils.invokeQuietly(connection, method, args);
if ("prepareStatement".equals(method.getName())) {
PreparedStatement statement = (PreparedStatement) result;
String sql = (String) args[0];
return buildStatementProxy(PreparedStatement.class, new ProfilingPreparedStatementHandler(statement, sql));
}
if ("createStatement".equals(method.getName())) {
Statement statement = (Statement) result;
return buildStatementProxy(Statement.class, new ProfilingStatementHandler(statement));
}
return result;
}
private static Object buildStatementProxy(Class<? extends Statement> stmtClass, InvocationHandler handler) {
return Proxy.newProxyInstance(ProfilingConnectionHandler.class.getClassLoader(), new Class[] {stmtClass}, handler);
}
}
| 2,189 | 37.421053 | 119 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/profiling/ProfilingPreparedStatementHandler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.profiling;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import org.sonar.api.utils.log.Profiler;
class ProfilingPreparedStatementHandler implements InvocationHandler {
private final PreparedStatement statement;
private final String sql;
private final Object[] sqlParams;
ProfilingPreparedStatementHandler(PreparedStatement statement, String sql) {
this.statement = statement;
this.sql = sql;
sqlParams = new Object[SqlLogFormatter.countArguments(sql)];
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().startsWith("execute")) {
Profiler profiler = Profiler.create(ProfiledDataSource.SQL_LOGGER).start();
Object result;
try {
result = InvocationUtils.invokeQuietly(statement, method, args);
} finally {
profiler.addContext("sql", SqlLogFormatter.reformatSql(sql));
if (sqlParams.length > 0) {
profiler.addContext("params", SqlLogFormatter.reformatParams(sqlParams));
}
profiler.stopTrace("");
}
return result;
} else if (method.getName().startsWith("set") && args.length > 1) {
sqlParams[(int) args[0] - 1] = args[1];
return InvocationUtils.invokeQuietly(statement, method, args);
} else {
return InvocationUtils.invokeQuietly(statement, method, args);
}
}
}
| 2,310 | 35.68254 | 85 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/profiling/ProfilingStatementHandler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.profiling;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Statement;
import org.sonar.api.utils.log.Profiler;
class ProfilingStatementHandler implements InvocationHandler {
private final Statement statement;
ProfilingStatementHandler(Statement statement) {
this.statement = statement;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().startsWith("execute")) {
Profiler profiler = Profiler.create(ProfiledDataSource.SQL_LOGGER).start();
Object result;
try {
result = InvocationUtils.invokeQuietly(statement, method, args);
} finally {
String sql = (String) args[0];
profiler.addContext("sql", SqlLogFormatter.reformatSql(sql));
profiler.stopTrace("");
}
return result;
} else {
return InvocationUtils.invokeQuietly(statement, method, args);
}
}
}
| 1,830 | 33.54717 | 85 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/profiling/SqlLogFormatter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.profiling;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import static org.apache.commons.lang.StringUtils.abbreviate;
public class SqlLogFormatter {
public static final int PARAM_MAX_WIDTH = 500;
private static final String PARAM_NULL = "[null]";
private static final Pattern NEWLINE_PATTERN = Pattern.compile("\\n");
private SqlLogFormatter() {
// only statics
}
public static String reformatSql(String sql) {
char[] chars = sql.toCharArray();
StringBuilder result = new StringBuilder(chars.length);
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c == '\n' || c == '\t') {
c = ' ';
}
if (Character.isWhitespace(c) && i > 0 && Character.isWhitespace(chars[i - 1])) {
continue;
}
result.append(c);
}
return result.toString();
}
public static String reformatParam(@Nullable Object param) {
if (param == null) {
return PARAM_NULL;
}
String abbreviated = abbreviate(param.toString(), PARAM_MAX_WIDTH);
return NEWLINE_PATTERN.matcher(abbreviated).replaceAll("\\\\n");
}
public static String reformatParams(Object[] params) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < params.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(reformatParam(params[i]));
}
return sb.toString();
}
public static int countArguments(String sql) {
int argCount = 0;
for (int i = 0; i < sql.length(); i++) {
if (sql.charAt(i) == '?') {
argCount++;
}
}
return argCount;
}
}
| 2,482 | 28.915663 | 87 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/profiling/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.db.profiling;
import javax.annotation.ParametersAreNonnullByDefault;
| 963 | 37.56 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/version/SqTables.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.version;
import java.util.Set;
public final class SqTables {
/**
* List of all the tables.
* This list is hardcoded because we didn't succeed in using java.sql.DatabaseMetaData#getTables() in the same way
* for all the supported databases, particularly due to Oracle results.
*/
public static final Set<String> TABLES = Set.of(
"active_rules",
"active_rule_parameters",
"alm_settings",
"alm_pats",
"analysis_properties",
"app_branch_project_branch",
"app_projects",
"audits",
"ce_activity",
"ce_queue",
"ce_task_characteristics",
"ce_task_input",
"ce_task_message",
"ce_scanner_context",
"components",
"default_qprofiles",
"deprecated_rule_keys",
"duplications_index",
"es_queue",
"events",
"event_component_changes",
"external_groups",
"file_sources",
"groups",
"groups_users",
"group_roles",
"internal_component_props",
"internal_properties",
"issues",
"issue_changes",
"live_measures",
"metrics",
"new_code_periods",
"new_code_reference_issues",
"notifications",
"org_qprofiles",
"permission_templates",
"perm_templates_users",
"perm_templates_groups",
"perm_tpl_characteristics",
"plugins",
"portfolios",
"portfolio_projects",
"portfolio_proj_branches",
"portfolio_references",
"projects",
"project_alm_settings",
"project_badge_token",
"project_branches",
"project_links",
"project_measures",
"project_qprofiles",
"project_qgates",
"properties",
"push_events",
"qprofile_changes",
"qprofile_edit_groups",
"qprofile_edit_users",
"quality_gates",
"qgate_user_permissions",
"qgate_group_permissions",
"quality_gate_conditions",
"saml_message_ids",
"report_schedules",
"report_subscriptions",
"rules",
"rule_desc_sections",
"rules_parameters",
"rules_profiles",
"rule_repositories",
"scanner_analysis_cache",
"schema_migrations",
"scim_groups",
"scim_users",
"scm_accounts",
"session_tokens",
"snapshots",
"users",
"user_dismissed_messages",
"user_roles",
"user_tokens",
"webhooks",
"webhook_deliveries");
private SqTables() {
// prevents instantiation
}
}
| 3,182 | 25.525 | 116 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/main/java/org/sonar/db/version/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.db.version;
import javax.annotation.ParametersAreNonnullByDefault;
| 961 | 37.48 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/test/java/org/sonar/db/DefaultDatabaseTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import com.zaxxer.hikari.HikariDataSource;
import java.util.Properties;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.process.logging.LogbackHelper;
import static org.apache.commons.lang.StringUtils.removeStart;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
@RunWith(DataProviderRunner.class)
public class DefaultDatabaseTest {
private final LogbackHelper logbackHelper = mock(LogbackHelper.class);
private static final String SONAR_JDBC = "sonar.jdbc.";
@Rule
public final LogTester logTester = new LogTester();
@Test
public void shouldLoadDefaultValues() {
DefaultDatabase db = new DefaultDatabase(logbackHelper, new MapSettings());
db.initSettings();
Properties props = db.getProperties();
assertThat(props.getProperty("sonar.jdbc.url")).isEqualTo("jdbc:h2:tcp://localhost/sonar;NON_KEYWORDS=VALUE");
assertThat(props.getProperty("sonar.jdbc.driverClassName")).isEqualTo("org.h2.Driver");
assertThat(db).hasToString("Database[jdbc:h2:tcp://localhost/sonar;NON_KEYWORDS=VALUE]");
}
@Test
public void shouldExtractHikariProperties() {
Properties props = new Properties();
props.setProperty("sonar.jdbc.driverClassName", "my.Driver");
props.setProperty("sonar.jdbc.username", "me");
props.setProperty("sonar.jdbc.dataSource.password", "my_password");
props.setProperty("sonar.jdbc.dataSource.portNumber", "9999");
props.setProperty("sonar.jdbc.connectionTimeout", "8000");
props.setProperty("sonar.jdbc.maximumPoolSize", "80");
props.setProperty("sonar.jdbc.minimumIdle", "10");
props.setProperty("sonar.jdbc.schema", "db-schema");
props.setProperty("sonar.jdbc.validationTimeout", "5000");
props.setProperty("sonar.jdbc.catalog", "db-catalog");
props.setProperty("sonar.jdbc.initializationFailTimeout", "5000");
props.setProperty("sonar.jdbc.maxLifetime", "1800000");
props.setProperty("sonar.jdbc.leakDetectionThreshold", "0");
props.setProperty("sonar.jdbc.keepaliveTime", "30000");
props.setProperty("sonar.jdbc.idleTimeout", "600000");
Properties hikariProps = DefaultDatabase.extractCommonsHikariProperties(props);
assertThat(hikariProps).hasSize(15);
assertThat(hikariProps.getProperty("driverClassName")).isEqualTo("my.Driver");
assertThat(hikariProps.getProperty("dataSource.user")).isEqualTo("me");
assertThat(hikariProps.getProperty("dataSource.password")).isEqualTo("my_password");
assertThat(hikariProps.getProperty("dataSource.portNumber")).isEqualTo("9999");
assertThat(hikariProps.getProperty("connectionTimeout")).isEqualTo("8000");
assertThat(hikariProps.getProperty("maximumPoolSize")).isEqualTo("80");
assertThat(hikariProps.getProperty("minimumIdle")).isEqualTo("10");
assertThat(hikariProps.getProperty("schema")).isEqualTo("db-schema");
assertThat(hikariProps.getProperty("validationTimeout")).isEqualTo("5000");
assertThat(hikariProps.getProperty("catalog")).isEqualTo("db-catalog");
assertThat(hikariProps.getProperty("initializationFailTimeout")).isEqualTo("5000");
assertThat(hikariProps.getProperty("maxLifetime")).isEqualTo("1800000");
assertThat(hikariProps.getProperty("leakDetectionThreshold")).isEqualTo("0");
assertThat(hikariProps.getProperty("keepaliveTime")).isEqualTo("30000");
assertThat(hikariProps.getProperty("idleTimeout")).isEqualTo("600000");
}
@Test
public void logWarningIfDeprecatedPropertyUsed() {
Properties props = new Properties();
props.setProperty("sonar.jdbc.maxIdle", "5");
props.setProperty("sonar.jdbc.minEvictableIdleTimeMillis", "300000");
props.setProperty("sonar.jdbc.timeBetweenEvictionRunsMillis", "1000");
props.setProperty("sonar.jdbc.connectionTimeout", "8000");
DefaultDatabase.extractCommonsHikariProperties(props);
assertThat(logTester.logs())
.contains("Property [sonar.jdbc.maxIdle] has no effect as pool connection implementation changed, check 9.7 upgrade notes.")
.contains("Property [sonar.jdbc.minEvictableIdleTimeMillis] has no effect as pool connection implementation changed, check 9.7 upgrade notes.")
.contains("Property [sonar.jdbc.timeBetweenEvictionRunsMillis] has no effect as pool connection implementation changed, check 9.7 upgrade notes.");
}
@Test
@UseDataProvider("sonarJdbcAndHikariProperties")
public void shouldExtractCommonsDbcpPropertiesIfDuplicatedPropertiesWithSameValue(String jdbcProperty, String dbcpProperty) {
Properties props = new Properties();
props.setProperty(jdbcProperty, "100");
props.setProperty(dbcpProperty, "100");
Properties commonsDbcpProps = DefaultDatabase.extractCommonsHikariProperties(props);
assertThat(commonsDbcpProps.getProperty(removeStart(dbcpProperty, SONAR_JDBC))).isEqualTo("100");
}
@Test
@UseDataProvider("sonarJdbcAndHikariProperties")
public void shouldThrowISEIfDuplicatedResolvedPropertiesWithDifferentValue(String jdbcProperty, String hikariProperty) {
Properties props = new Properties();
props.setProperty(jdbcProperty, "100");
props.setProperty(hikariProperty, "200");
assertThatThrownBy(() -> DefaultDatabase.extractCommonsHikariProperties(props))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining(String.format("Duplicate property declaration for resolved jdbc key '%s': conflicting values are", removeStart(hikariProperty, SONAR_JDBC)));
}
@Test
public void shouldCompleteProperties() {
MapSettings settings = new MapSettings();
DefaultDatabase db = new DefaultDatabase(logbackHelper, settings) {
@Override
protected void doCompleteProperties(Properties properties) {
properties.setProperty("sonar.jdbc.maxActive", "2");
}
};
db.initSettings();
Properties props = db.getProperties();
assertThat(props.getProperty("sonar.jdbc.maxActive")).isEqualTo("2");
}
@Test
public void shouldStart() {
MapSettings settings = new MapSettings();
settings.setProperty("sonar.jdbc.url", "jdbc:h2:mem:sonar;NON_KEYWORDS=VALUE");
settings.setProperty("sonar.jdbc.driverClassName", "org.h2.Driver");
settings.setProperty("sonar.jdbc.username", "sonar");
settings.setProperty("sonar.jdbc.password", "sonar");
settings.setProperty("sonar.jdbc.maximumPoolSize", "1");
DefaultDatabase db = new DefaultDatabase(logbackHelper, settings);
db.start();
db.stop();
assertThat(db.getDialect().getId()).isEqualTo("h2");
assertThat(((HikariDataSource) db.getDataSource()).getMaximumPoolSize()).isOne();
}
@Test
public void shouldGuessDialectFromUrl() {
MapSettings settings = new MapSettings();
settings.setProperty("sonar.jdbc.url", "jdbc:postgresql://localhost/sonar");
DefaultDatabase database = new DefaultDatabase(logbackHelper, settings);
database.initSettings();
assertThat(database.getDialect().getId()).isEqualTo(PostgreSql.ID);
}
@Test
public void shouldGuessDefaultDriver() {
MapSettings settings = new MapSettings();
settings.setProperty("sonar.jdbc.url", "jdbc:postgresql://localhost/sonar");
DefaultDatabase database = new DefaultDatabase(logbackHelper, settings);
database.initSettings();
assertThat(database.getProperties().getProperty("sonar.jdbc.driverClassName")).isEqualTo("org.postgresql.Driver");
}
@DataProvider
public static Object[][] sonarJdbcAndHikariProperties() {
return new Object[][] {
{"sonar.jdbc.maxWait", "sonar.jdbc.connectionTimeout"},
{"sonar.jdbc.maxActive", "sonar.jdbc.maximumPoolSize"}
};
}
}
| 8,925 | 42.541463 | 169 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/test/java/org/sonar/db/dialect/DialectUtilsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.dialect;
import org.junit.Test;
import org.sonar.api.utils.MessageException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class DialectUtilsTest {
@Test
public void testFindById() {
Dialect d = DialectUtils.find("postgresql", null);
assertThat(d).isInstanceOf(PostgreSql.class);
}
@Test
public void testFindByJdbcUrl() {
Dialect d = DialectUtils.find(null, "jdbc:postgresql:foo:bar");
assertThat(d).isInstanceOf(PostgreSql.class);
}
@Test
public void testFindNoMatch() {
assertThatThrownBy(() -> DialectUtils.find("foo", "bar"))
.isInstanceOf(MessageException.class);
}
}
| 1,572 | 31.770833 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/test/java/org/sonar/db/dialect/H2Test.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.dialect;
import java.sql.DatabaseMetaData;
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.mockito.Mockito.mock;
public class H2Test {
@Rule
public LogTester logs = new LogTester();
private H2 underTest = new H2();
@Test
public void matchesJdbcURL() {
assertThat(underTest.matchesJdbcUrl("jdbc:h2:foo")).isTrue();
assertThat(underTest.matchesJdbcUrl("jdbc:hsql:foo")).isFalse();
}
@Test
public void testBooleanSqlValues() {
assertThat(underTest.getTrueSqlValue()).isEqualTo("true");
assertThat(underTest.getFalseSqlValue()).isEqualTo("false");
}
@Test
public void should_configure() {
assertThat(underTest.getId()).isEqualTo("h2");
assertThat(underTest.getDefaultDriverClassName()).isEqualTo("org.h2.Driver");
assertThat(underTest.getValidationQuery()).isEqualTo("SELECT 1");
}
@Test
public void testFetchSizeForScrolling() {
assertThat(underTest.getScrollDefaultFetchSize()).isEqualTo(200);
}
@Test
public void h2_does_not_supportMigration() {
assertThat(underTest.supportsMigration()).isFalse();
}
@Test
public void getSqlFromDual() {
assertThat(underTest.getSqlFromDual()).isEmpty();
}
@Test
public void init_logs_warning() {
underTest.init(mock(DatabaseMetaData.class));
assertThat(logs.logs(Level.WARN)).contains("H2 database should be used for evaluation purpose only.");
}
@Test
public void supportsUpsert_returns_false() {
assertThat(underTest.supportsUpsert()).isFalse();
}
}
| 2,522 | 29.035714 | 106 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/test/java/org/sonar/db/dialect/MsSqlTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.dialect;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.api.utils.MessageException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MsSqlTest {
private MsSql underTest = new MsSql();
@Test
public void matchesJdbcURL() {
assertThat(underTest.matchesJdbcUrl("jdbc:sqlserver://localhost:1433;databasename=sonar")).isTrue();
assertThat(underTest.matchesJdbcUrl("jdbc:hsql:foo")).isFalse();
}
@Test
public void testBooleanSqlValues() {
assertThat(underTest.getTrueSqlValue()).isEqualTo("1");
assertThat(underTest.getFalseSqlValue()).isEqualTo("0");
}
@Test
public void should_configure() {
assertThat(underTest.getId()).isEqualTo("mssql");
assertThat(underTest.getDefaultDriverClassName()).isEqualTo("com.microsoft.sqlserver.jdbc.SQLServerDriver");
assertThat(underTest.getValidationQuery()).isEqualTo("SELECT 1");
}
@Test
public void do_not_support_jtds_since_5_2() {
assertThat(underTest.matchesJdbcUrl("jdbc:jtds:sqlserver://localhost;databaseName=SONAR;SelectMethod=Cursor")).isFalse();
}
@Test
public void msSql_does_supportMigration() {
assertThat(underTest.supportsMigration()).isTrue();
}
@Test
public void getSqlFromDual() {
assertThat(underTest.getSqlFromDual()).isEmpty();
}
@Test
public void init_throws_MessageException_if_mssql_2012() throws Exception {
assertThatThrownBy(() -> {
DatabaseMetaData metadata = newMetadata( 11, 0);
underTest.init(metadata);
})
.isInstanceOf(MessageException.class)
.hasMessage("Unsupported mssql version: 11.0. Minimal supported version is 12.0.");
}
@Test
public void init_does_not_fail_if_mssql_2014() throws Exception {
DatabaseMetaData metadata = newMetadata( 12, 0);
underTest.init(metadata);
}
@Test
public void supportsUpsert_returns_false() {
assertThat(underTest.supportsUpsert()).isFalse();
}
private DatabaseMetaData newMetadata(int dbMajorVersion, int dbMinorVersion) throws SQLException {
DatabaseMetaData metadata = mock(DatabaseMetaData.class, Mockito.RETURNS_DEEP_STUBS);
when(metadata.getDatabaseMajorVersion()).thenReturn(dbMajorVersion);
when(metadata.getDatabaseMinorVersion()).thenReturn(dbMinorVersion);
return metadata;
}
}
| 3,383 | 32.176471 | 125 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/test/java/org/sonar/db/dialect/OracleTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.dialect;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.api.utils.MessageException;
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 OracleTest {
private Oracle underTest = new Oracle();
@Test
public void matchesJdbcURL() {
assertThat(underTest.matchesJdbcUrl("jdbc:oracle:thin:@localhost/XE")).isTrue();
assertThat(underTest.matchesJdbcUrl("jdbc:hsql:foo")).isFalse();
}
@Test
public void testBooleanSqlValues() {
assertThat(underTest.getTrueSqlValue()).isEqualTo("1");
assertThat(underTest.getFalseSqlValue()).isEqualTo("0");
}
@Test
public void should_configure() {
assertThat(underTest.getId()).isEqualTo("oracle");
assertThat(underTest.getDefaultDriverClassName()).isEqualTo("oracle.jdbc.OracleDriver");
assertThat(underTest.getValidationQuery()).isEqualTo("SELECT 1 FROM DUAL");
}
@Test
public void testFetchSizeForScrolling() {
assertThat(underTest.getScrollDefaultFetchSize()).isEqualTo(200);
}
@Test
public void oracle_does_supportMigration() {
assertThat(underTest.supportsMigration()).isTrue();
}
@Test
public void getSqlFromDual() {
assertThat(underTest.getSqlFromDual()).isEqualTo("from dual");
}
@Test
public void test_db_versions() throws Exception {
// oracle 11.0 is ok
DatabaseMetaData metadata = newMetadata( 11, 0, "12.1.0.1.0");
underTest.init(metadata);
// oracle 11.1 is noit
metadata = newMetadata(11, 1, "12.1.0.1.0");
underTest.init(metadata);
// oracle 11.2 is ok
metadata = newMetadata(11, 2, "12.1.0.1.0");
underTest.init(metadata);
// oracle 12 is ok
metadata = newMetadata(12, 0, "12.1.0.1.0");
underTest.init(metadata);
// oracle 18 is ok
metadata = newMetadata(18, 0, "18.3.0.0.0");
underTest.init(metadata);
// oracle 10 is not supported
metadata = newMetadata(10, 2, "12.1.0.1.0");
try {
underTest.init(metadata);
fail();
} catch (MessageException e) {
assertThat(e).hasMessage("Unsupported oracle version: 10.2. Minimal supported version is 11.0.");
}
}
@Test
public void test_driver_versions() throws Exception {
DatabaseMetaData metadata = newMetadata( 11, 2, "18.3.0.0.0");
underTest.init(metadata);
metadata = newMetadata(11, 2, "12.2.0.1.0");
underTest.init(metadata);
// no error
metadata = newMetadata(11, 2, "12.1.0.2.0");
underTest.init(metadata);
// no error
metadata = newMetadata(11, 2, "12.1.0.1.0");
underTest.init(metadata);
// no error
metadata = newMetadata(11, 2, "12.0.2");
underTest.init(metadata);
// no error
metadata = newMetadata(11, 2, "11.1.0.2");
try {
underTest.init(metadata);
fail();
} catch (MessageException e) {
assertThat(e).hasMessage("Unsupported Oracle driver version: 11.1.0.2. Minimal supported version is 12.1.");
}
}
@Test
public void supportsUpsert_returns_false() {
assertThat(underTest.supportsUpsert()).isFalse();
}
private DatabaseMetaData newMetadata(int dbMajorVersion, int dbMinorVersion, String driverVersion) throws SQLException {
DatabaseMetaData metadata = mock(DatabaseMetaData.class, Mockito.RETURNS_DEEP_STUBS);
when(metadata.getDatabaseMajorVersion()).thenReturn(dbMajorVersion);
when(metadata.getDatabaseMinorVersion()).thenReturn(dbMinorVersion);
when(metadata.getDriverVersion()).thenReturn(driverVersion);
return metadata;
}
}
| 4,550 | 30.171233 | 122 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/test/java/org/sonar/db/dialect/PostgreSqlTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.dialect;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.MessageException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class PostgreSqlTest {
@Rule
public LogTester logs = new LogTester();
private PostgreSql underTest = new PostgreSql();
@Test
public void matchesJdbcURL() {
assertThat(underTest.matchesJdbcUrl("jdbc:postgresql://localhost/sonar")).isTrue();
assertThat(underTest.matchesJdbcUrl("jdbc:hsql:foo")).isFalse();
}
@Test
public void should_set_connection_properties() {
assertThat(underTest.getConnectionInitStatements()).isEqualTo(PostgreSql.INIT_STATEMENTS);
}
@Test
public void testBooleanSqlValues() {
assertThat(underTest.getTrueSqlValue()).isEqualTo("true");
assertThat(underTest.getFalseSqlValue()).isEqualTo("false");
}
@Test
public void should_configure() {
assertThat(underTest.getId()).isEqualTo("postgresql");
assertThat(underTest.getDefaultDriverClassName()).isEqualTo("org.postgresql.Driver");
assertThat(underTest.getValidationQuery()).isEqualTo("SELECT 1");
}
@Test
public void testFetchSizeForScrolling() {
assertThat(underTest.getScrollDefaultFetchSize()).isEqualTo(200);
}
@Test
public void postgres_does_supportMigration() {
assertThat(underTest.supportsMigration()).isTrue();
}
@Test
public void getSqlFromDual() {
assertThat(underTest.getSqlFromDual()).isEmpty();
}
@Test
public void postgresql_9_2_is_not_supported() throws Exception {
assertThatThrownBy(() -> {
DatabaseMetaData metadata = newMetadata( 9, 2);
underTest.init(metadata);
})
.isInstanceOf(MessageException.class)
.hasMessage("Unsupported postgresql version: 9.2. Minimal supported version is 9.3.");
}
@Test
public void postgresql_9_3_is_supported_without_upsert() throws Exception {
DatabaseMetaData metadata = newMetadata( 9, 3);
underTest.init(metadata);
assertThat(underTest.supportsUpsert()).isFalse();
assertThat(logs.logs(Level.WARN)).contains("Upgrading PostgreSQL to 9.5 or greater is recommended for better performances");
}
@Test
public void postgresql_9_5_is_supported_with_upsert() throws Exception {
DatabaseMetaData metadata = newMetadata( 9, 5);
underTest.init(metadata);
assertThat(underTest.supportsUpsert()).isTrue();
assertThat(logs.logs(Level.WARN)).isEmpty();
}
@Test
public void init_throws_ISE_if_called_twice() throws Exception {
DatabaseMetaData metaData = newMetadata(9, 5);
underTest.init(metaData);
assertThatThrownBy(() -> underTest.init(metaData))
.isInstanceOf(IllegalStateException.class)
.hasMessage("onInit() must be called once");
}
@Test
public void supportsUpsert_throws_ISE_if_not_initialized() {
assertThatThrownBy(() -> underTest.supportsUpsert())
.isInstanceOf(IllegalStateException.class)
.hasMessage("onInit() must be called before calling supportsUpsert()");
}
private DatabaseMetaData newMetadata(int dbMajorVersion, int dbMinorVersion) throws SQLException {
DatabaseMetaData metadata = mock(DatabaseMetaData.class, Mockito.RETURNS_DEEP_STUBS);
when(metadata.getDatabaseMajorVersion()).thenReturn(dbMajorVersion);
when(metadata.getDatabaseMinorVersion()).thenReturn(dbMinorVersion);
return metadata;
}
}
| 4,544 | 32.666667 | 128 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/test/java/org/sonar/db/profiling/InvocationUtilsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.profiling;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import org.junit.Assert;
import org.junit.Test;
import org.sonar.test.TestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class InvocationUtilsTest {
@Test
public void should_return_result() throws Throwable {
String toString = "toString";
Object target = mock(Object.class);
when(target.toString()).thenReturn(toString);
assertThat(InvocationUtils.invokeQuietly(target, Object.class.getMethod("toString"), new Object[0])).isEqualTo(toString);
}
@Test
public void should_throw_declared_exception() throws Throwable {
Connection target = mock(Connection.class);
String failSql = "any sql";
when(target.prepareStatement(failSql)).thenThrow(new SQLException("Expected"));
Method prepareStatement = Connection.class.getMethod("prepareStatement", String.class);
Assert.assertThrows(SQLException.class, () -> InvocationUtils.invokeQuietly(target, prepareStatement, new Object[] {failSql}));
}
@Test
public void only_static_methods() {
assertThat(TestUtils.hasOnlyPrivateConstructors(InvocationUtils.class)).isTrue();
}
}
| 2,152 | 34.883333 | 131 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/test/java/org/sonar/db/profiling/ProfiledDataSourceTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.profiling;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.io.ByteArrayInputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Properties;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import static java.nio.charset.StandardCharsets.UTF_8;
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.when;
public class ProfiledDataSourceTest {
@Rule
public LogTester logTester = new LogTester();
HikariDataSource originDataSource = mock(HikariDataSource.class);
@Test
public void execute_and_log_statement() throws Exception {
logTester.setLevel(LoggerLevel.TRACE);
Connection connection = mock(Connection.class);
when(originDataSource.getConnection()).thenReturn(connection);
String sql = "select from dual";
Statement stmt = mock(Statement.class);
when(connection.createStatement()).thenReturn(stmt);
when(stmt.execute(sql)).thenReturn(true);
ProfiledDataSource underTest = new ProfiledDataSource(originDataSource, ProfiledConnectionInterceptor.INSTANCE);
assertThat(underTest.getJdbcUrl()).isNull();
assertThat(underTest.getConnection().getClientInfo()).isNull();
final Statement statementProxy = underTest.getConnection().createStatement();
assertThat(statementProxy.getConnection()).isNull();
assertThat(statementProxy.execute(sql)).isTrue();
assertThat(logTester.logs(Level.TRACE)).hasSize(1);
assertThat(logTester.logs(Level.TRACE).get(0))
.contains("sql=select from dual");
}
@Test
public void execute_and_log_prepared_statement_with_parameters() throws Exception {
logTester.setLevel(LoggerLevel.TRACE);
Connection connection = mock(Connection.class);
when(originDataSource.getConnection()).thenReturn(connection);
String sqlWithParams = "insert into polop (col1, col2, col3, col4) values (?, ?, ?, ?, ?)";
int param1 = 42;
String param2 = "plouf";
Date param3 = new Date(System.currentTimeMillis());
Timestamp param4 = new Timestamp(System.currentTimeMillis());
byte[] param5 = "blob".getBytes(UTF_8);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
when(connection.prepareStatement(sqlWithParams)).thenReturn(preparedStatement);
when(preparedStatement.execute()).thenReturn(true);
ProfiledDataSource ds = new ProfiledDataSource(originDataSource, ProfiledConnectionInterceptor.INSTANCE);
assertThat(ds.getJdbcUrl()).isNull();
assertThat(ds.getConnection().getClientInfo()).isNull();
PreparedStatement preparedStatementProxy = ds.getConnection().prepareStatement(sqlWithParams);
preparedStatementProxy.setInt(1, param1);
preparedStatementProxy.setString(2, param2);
preparedStatementProxy.setDate(3, param3);
preparedStatementProxy.setTimestamp(4, param4);
preparedStatementProxy.setBlob(5, new ByteArrayInputStream(param5));
assertThat(preparedStatementProxy.getConnection()).isNull();
assertThat(preparedStatementProxy.execute()).isTrue();
assertThat(logTester.logs(Level.TRACE)).hasSize(1);
assertThat(logTester.logs(Level.TRACE).get(0))
.contains("sql=insert into polop (col1, col2, col3, col4) values (?, ?, ?, ?, ?)")
.contains("params=42, plouf");
}
@Test
public void execute_and_log_prepared_statement_without_parameters() throws Exception {
logTester.setLevel(LoggerLevel.TRACE);
Connection connection = mock(Connection.class);
when(originDataSource.getConnection()).thenReturn(connection);
String sqlWithParams = "select from dual";
PreparedStatement preparedStatement = mock(PreparedStatement.class);
when(connection.prepareStatement(sqlWithParams)).thenReturn(preparedStatement);
when(preparedStatement.execute()).thenReturn(true);
ProfiledDataSource ds = new ProfiledDataSource(originDataSource, ProfiledConnectionInterceptor.INSTANCE);
assertThat(ds.getJdbcUrl()).isNull();
assertThat(ds.getConnection().getClientInfo()).isNull();
PreparedStatement preparedStatementProxy = ds.getConnection().prepareStatement(sqlWithParams);
assertThat(preparedStatementProxy.getConnection()).isNull();
assertThat(preparedStatementProxy.execute()).isTrue();
assertThat(logTester.logs(Level.TRACE)).hasSize(1);
assertThat(logTester.logs(Level.TRACE).get(0))
.contains("sql=select from dual")
.doesNotContain("params=");
}
@Test
public void delegate_to_underlying_data_source() throws Exception {
ProfiledDataSource proxy = new ProfiledDataSource(originDataSource, ProfiledConnectionInterceptor.INSTANCE);
// painful to call all methods
// so using reflection to check that calls does not fail
// Limitation: methods with parameters are not tested and calls to
// underlying datasource are not verified
for (Method method : ProfiledDataSource.class.getDeclaredMethods()) {
if (method.getParameterTypes().length == 0 && Modifier.isPublic(method.getModifiers())) {
method.invoke(proxy);
} else if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(String.class) && Modifier.isPublic(method.getModifiers())) {
method.invoke(proxy, "test");
} else if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(Boolean.TYPE) && Modifier.isPublic(method.getModifiers())) {
method.invoke(proxy, true);
} else if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(Long.TYPE) && Modifier.isPublic(method.getModifiers())) {
method.invoke(proxy, 1L);
} else if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(Integer.TYPE) && Modifier.isPublic(method.getModifiers())) {
method.invoke(proxy, 1);
}
}
proxy.addHealthCheckProperty("test", "test");
verify(originDataSource).addHealthCheckProperty("test", "test");
var schedulerMock = mock(ScheduledExecutorService.class);
proxy.setScheduledExecutor(schedulerMock);
verify(originDataSource).setScheduledExecutor(schedulerMock);
var hikariConfigMock = mock(HikariConfig.class);
proxy.copyStateTo(hikariConfigMock);
verify(originDataSource).copyStateTo(hikariConfigMock);
var threadFactoryMock = mock(ThreadFactory.class);
proxy.setThreadFactory(threadFactoryMock);
verify(originDataSource).setThreadFactory(threadFactoryMock);
var properties = new Properties();
proxy.setHealthCheckProperties(properties);
verify(originDataSource).setHealthCheckProperties(properties);
proxy.setDataSourceProperties(properties);
verify(originDataSource).setDataSourceProperties(properties);
}
}
| 8,054 | 41.845745 | 156 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/test/java/org/sonar/db/profiling/SqlLogFormatterTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.profiling;
import org.junit.Test;
import static org.apache.commons.lang.StringUtils.repeat;
import static org.assertj.core.api.Assertions.assertThat;
public class SqlLogFormatterTest {
@Test
public void reformatSql() {
assertThat(SqlLogFormatter.reformatSql("")).isEmpty();
assertThat(SqlLogFormatter.reformatSql("select *")).isEqualTo("select *");
assertThat(SqlLogFormatter.reformatSql("select *\nfrom issues")).isEqualTo("select * from issues");
assertThat(SqlLogFormatter.reformatSql("select *\n from issues")).isEqualTo("select * from issues");
assertThat(SqlLogFormatter.reformatSql("select *\n from issues")).isEqualTo("select * from issues");
assertThat(SqlLogFormatter.reformatSql("select *\n from issues")).isEqualTo("select * from issues");
assertThat(SqlLogFormatter.reformatSql("select *\n\t\t from \tissues")).isEqualTo("select * from issues");
}
@Test
public void reformatParam() {
assertThat(SqlLogFormatter.reformatParam(null)).isEqualTo("[null]");
assertThat(SqlLogFormatter.reformatParam("")).isEmpty();
assertThat(SqlLogFormatter.reformatParam("foo")).isEqualTo("foo");
assertThat(SqlLogFormatter.reformatParam("foo bar ")).isEqualTo("foo bar ");
}
@Test
public void reformatParam_escapes_newlines() {
assertThat(SqlLogFormatter.reformatParam("foo\n bar\nbaz")).isEqualTo("foo\\n bar\\nbaz");
}
@Test
public void reformatParam_truncates_if_too_long() {
String param = repeat("a", SqlLogFormatter.PARAM_MAX_WIDTH + 10);
String formattedParam = SqlLogFormatter.reformatParam(param);
assertThat(formattedParam)
.hasSize(SqlLogFormatter.PARAM_MAX_WIDTH)
.endsWith("...")
.startsWith(repeat("a", SqlLogFormatter.PARAM_MAX_WIDTH - 3));
}
@Test
public void reformatParams() {
String formattedParams = SqlLogFormatter.reformatParams(new Object[] {"foo", 42, null, true});
assertThat(formattedParams).isEqualTo("foo, 42, [null], true");
}
@Test
public void reformatParams_returns_blank_if_zero_params() {
String formattedParams = SqlLogFormatter.reformatParams(new Object[0]);
assertThat(formattedParams).isEmpty();
}
@Test
public void countArguments() {
assertThat(SqlLogFormatter.countArguments("select * from issues")).isZero();
assertThat(SqlLogFormatter.countArguments("select * from issues where id=?")).isOne();
assertThat(SqlLogFormatter.countArguments("select * from issues where id=? and kee=?")).isEqualTo(2);
}
}
| 3,377 | 40.195122 | 115 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/testFixtures/java/org/sonar/db/AbstractDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import java.math.BigDecimal;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.rules.ExternalResource;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Lists.asList;
import static java.sql.ResultSetMetaData.columnNoNulls;
import static java.sql.ResultSetMetaData.columnNullable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public class AbstractDbTester<T extends TestDb> extends ExternalResource {
private static final Joiner COMMA_JOINER = Joiner.on(", ");
protected final T db;
public AbstractDbTester(T db) {
this.db = db;
}
public T getDb() {
return db;
}
public void executeUpdateSql(String sql, Object... params) {
try (Connection connection = getConnection()) {
new QueryRunner().update(connection, sql, params);
if (!connection.getAutoCommit()) {
connection.commit();
}
} catch (SQLException e) {
SQLException nextException = e.getNextException();
if (nextException != null) {
throw new IllegalStateException("Fail to execute sql: " + sql,
new SQLException(e.getMessage(), nextException.getSQLState(), nextException.getErrorCode(), nextException));
}
throw new IllegalStateException("Fail to execute sql: " + sql, e);
} catch (Exception e) {
throw new IllegalStateException("Fail to execute sql: " + sql, e);
}
}
public void executeDdl(String ddl) {
try (Connection connection = getConnection();
Statement stmt = connection.createStatement()) {
stmt.execute(ddl);
} catch (SQLException e) {
throw new IllegalStateException("Failed to execute DDL: " + ddl, e);
}
}
/**
* Very simple helper method to insert some data into a table.
* It's the responsibility of the caller to convert column values to string.
*/
public void executeInsert(String table, String firstColumn, Object... others) {
executeInsert(table, mapOf(firstColumn, others));
}
private static Map<String, Object> mapOf(String firstColumn, Object... values) {
ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
List<Object> args = asList(firstColumn, values);
for (int i = 0; i < args.size(); i++) {
String key = args.get(i).toString();
Object value = args.get(i + 1);
if (value != null) {
builder.put(key, value);
}
i++;
}
return builder.build();
}
/**
* Very simple helper method to insert some data into a table.
* It's the responsibility of the caller to convert column values to string.
*/
public void executeInsert(String table, Map<String, Object> valuesByColumn) {
if (valuesByColumn.isEmpty()) {
throw new IllegalArgumentException("Values cannot be empty");
}
String sql = "insert into " + table.toLowerCase(Locale.ENGLISH) + " (" +
COMMA_JOINER.join(valuesByColumn.keySet().stream().map(t -> t.toLowerCase(Locale.ENGLISH)).toArray(String[]::new)) +
") values (" +
COMMA_JOINER.join(Collections.nCopies(valuesByColumn.size(), '?')) +
")";
executeUpdateSql(sql, valuesByColumn.values().toArray(new Object[valuesByColumn.size()]));
}
/**
* Returns the number of rows in the table. Example:
* <pre>int issues = countRowsOfTable("issues")</pre>
*/
public int countRowsOfTable(String tableName) {
return countRowsOfTable(tableName, new NewConnectionSupplier());
}
protected int countRowsOfTable(String tableName, ConnectionSupplier connectionSupplier) {
checkArgument(StringUtils.containsNone(tableName, " "), "Parameter must be the name of a table. Got " + tableName);
return countSql("select count(1) from " + tableName.toLowerCase(Locale.ENGLISH), connectionSupplier);
}
/**
* Executes a SQL request starting with "SELECT COUNT(something) FROM", for example:
* <pre>int OpenIssues = countSql("select count('id') from issues where status is not null")</pre>
*/
public int countSql(String sql) {
return countSql(sql, new NewConnectionSupplier());
}
protected int countSql(String sql, ConnectionSupplier connectionSupplier) {
checkArgument(StringUtils.contains(sql, "count("),
"Parameter must be a SQL request containing 'count(x)' function. Got " + sql);
try (
ConnectionSupplier supplier = connectionSupplier;
PreparedStatement stmt = supplier.get().prepareStatement(sql);
ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return rs.getInt(1);
}
throw new IllegalStateException("No results for " + sql);
} catch (Exception e) {
throw new IllegalStateException("Fail to execute sql: " + sql, e);
}
}
public List<Map<String, Object>> select(String selectSql) {
return select(selectSql, new NewConnectionSupplier());
}
protected List<Map<String, Object>> select(String selectSql, ConnectionSupplier connectionSupplier) {
try (
ConnectionSupplier supplier = connectionSupplier;
PreparedStatement stmt = supplier.get().prepareStatement(selectSql);
ResultSet rs = stmt.executeQuery()) {
return getHashMap(rs);
} catch (Exception e) {
throw new IllegalStateException("Fail to execute sql: " + selectSql, e);
}
}
public Map<String, Object> selectFirst(String selectSql) {
return selectFirst(selectSql, new NewConnectionSupplier());
}
protected Map<String, Object> selectFirst(String selectSql, ConnectionSupplier connectionSupplier) {
List<Map<String, Object>> rows = select(selectSql, connectionSupplier);
if (rows.isEmpty()) {
throw new IllegalStateException("No results for " + selectSql);
} else if (rows.size() > 1) {
throw new IllegalStateException("Too many results for " + selectSql);
}
return rows.get(0);
}
private static List<Map<String, Object>> getHashMap(ResultSet resultSet) throws Exception {
ResultSetMetaData metaData = resultSet.getMetaData();
int colCount = metaData.getColumnCount();
List<Map<String, Object>> rows = new ArrayList<>();
while (resultSet.next()) {
Map<String, Object> columns = new HashMap<>();
for (int i = 1; i <= colCount; i++) {
Object value = resultSet.getObject(i);
if (value instanceof Clob) {
Clob clob = (Clob) value;
value = IOUtils.toString((clob.getAsciiStream()));
doClobFree(clob);
} else if (value instanceof BigDecimal) {
// In Oracle, INTEGER types are mapped as BigDecimal
BigDecimal bgValue = ((BigDecimal) value);
if (bgValue.scale() == 0) {
value = bgValue.longValue();
} else {
value = bgValue.doubleValue();
}
} else if (value instanceof Integer) {
// To be consistent, all INTEGER types are mapped as Long
value = ((Integer) value).longValue();
} else if (value instanceof Byte) {
Byte byteValue = (Byte) value;
value = byteValue.intValue();
} else if (value instanceof Timestamp) {
value = new Date(((Timestamp) value).getTime());
}
columns.put(metaData.getColumnLabel(i), value);
}
rows.add(columns);
}
return rows;
}
public void assertColumnDefinition(String table, String column, int expectedType, @Nullable Integer expectedSize, @Nullable Boolean isNullable) {
try (Connection connection = getConnection();
PreparedStatement stmt = connection.prepareStatement("select * from " + table);
ResultSet res = stmt.executeQuery()) {
Integer columnIndex = getColumnIndex(res, column);
if (columnIndex == null) {
fail("The column '" + column + "' does not exist");
}
assertThat(res.getMetaData().getColumnType(columnIndex)).isEqualTo(expectedType);
if (expectedSize != null) {
assertThat(res.getMetaData().getColumnDisplaySize(columnIndex)).isEqualTo(expectedSize);
}
if (isNullable != null) {
assertThat(res.getMetaData().isNullable(columnIndex)).isEqualTo(isNullable ? columnNullable : columnNoNulls);
}
} catch (Exception e) {
throw new IllegalStateException("Fail to check column", e);
}
}
public void assertColumnDoesNotExist(String table, String column) throws SQLException {
try (Connection connection = getConnection();
PreparedStatement stmt = connection.prepareStatement("select * from " + table);
ResultSet res = stmt.executeQuery()) {
assertThat(getColumnNames(res)).doesNotContain(column);
}
}
public void assertTableDoesNotExist(String table) {
assertTableExists(table, false);
}
public void assertTableExists(String table) {
assertTableExists(table, true);
}
private void assertTableExists(String table, boolean expected) {
try (Connection connection = getConnection()) {
boolean tableExists = DatabaseUtils.tableExists(table, connection);
assertThat(tableExists).isEqualTo(expected);
} catch (Exception e) {
throw new IllegalStateException("Fail to check if table exists", e);
}
}
/**
* Verify that non-unique index exists on columns
*/
public void assertIndex(String tableName, String indexName, String expectedColumn, String... expectedSecondaryColumns) {
assertIndexImpl(tableName, indexName, false, expectedColumn, expectedSecondaryColumns);
}
/**
* Verify that unique index exists on columns
*/
public void assertUniqueIndex(String tableName, String indexName, String expectedColumn, String... expectedSecondaryColumns) {
assertIndexImpl(tableName, indexName, true, expectedColumn, expectedSecondaryColumns);
}
private void assertIndexImpl(String tableName, String indexName, boolean expectedUnique, String expectedColumn, String... expectedSecondaryColumns) {
try (Connection connection = getConnection();
ResultSet rs = connection.getMetaData().getIndexInfo(null, null, tableName.toUpperCase(Locale.ENGLISH), false, false)) {
List<String> onColumns = new ArrayList<>();
while (rs.next()) {
if (indexName.equalsIgnoreCase(rs.getString("INDEX_NAME"))) {
assertThat(rs.getBoolean("NON_UNIQUE")).isEqualTo(!expectedUnique);
int position = rs.getInt("ORDINAL_POSITION");
onColumns.add(position - 1, rs.getString("COLUMN_NAME").toLowerCase(Locale.ENGLISH));
}
}
assertThat(onColumns).containsExactlyInAnyOrderElementsOf(asList(expectedColumn, expectedSecondaryColumns));
} catch (SQLException e) {
throw new IllegalStateException("Fail to check index", e);
}
}
/**
* Verify that index with name {@code indexName} does not exist on the table {@code tableName}
*/
public void assertIndexDoesNotExist(String tableName, String indexName) {
try (Connection connection = getConnection();
ResultSet rs = connection.getMetaData().getIndexInfo(null, null, tableName.toUpperCase(Locale.ENGLISH), false, false)) {
List<String> indices = new ArrayList<>();
while (rs.next()) {
indices.add(rs.getString("INDEX_NAME").toLowerCase(Locale.ENGLISH));
}
assertThat(indices).doesNotContain(indexName);
} catch (SQLException e) {
throw new IllegalStateException("Fail to check existence of index", e);
}
}
public void assertPrimaryKey(String tableName, @Nullable String expectedPkName, String columnName, String... otherColumnNames) {
try (Connection connection = getConnection()) {
PK pk = pkOf(connection, tableName.toUpperCase(Locale.ENGLISH));
if (pk == null) {
pkOf(connection, tableName.toLowerCase(Locale.ENGLISH));
}
assertThat(pk).as("No primary key is defined on table %s", tableName).isNotNull();
if (expectedPkName != null) {
assertThat(pk.getName()).isEqualToIgnoringCase(expectedPkName);
}
List<String> expectedColumns = ImmutableList.copyOf(Iterables.concat(Collections.singletonList(columnName), Arrays.asList(otherColumnNames)));
assertThat(pk.getColumns()).as("Primary key does not have the '%s' expected columns", expectedColumns.size()).hasSize(expectedColumns.size());
Iterator<String> expectedColumnsIt = expectedColumns.iterator();
Iterator<String> actualColumnsIt = pk.getColumns().iterator();
while (expectedColumnsIt.hasNext() && actualColumnsIt.hasNext()) {
assertThat(actualColumnsIt.next()).isEqualToIgnoringCase(expectedColumnsIt.next());
}
} catch (SQLException e) {
throw new IllegalStateException("Fail to check primary key", e);
}
}
public void assertNoPrimaryKey(String tableName) {
try (Connection connection = getConnection()) {
PK pk = pkOf(connection, tableName.toUpperCase(Locale.ENGLISH));
if (pk == null) {
pkOf(connection, tableName.toLowerCase(Locale.ENGLISH));
}
assertThat(pk).as("Primary key is still defined on table %s", tableName).isNull();
} catch (SQLException e) {
throw new IllegalStateException("Fail to check primary key", e);
}
}
@CheckForNull
private PK pkOf(Connection connection, String tableName) throws SQLException {
try (ResultSet resultSet = connection.getMetaData().getPrimaryKeys(null, null, tableName)) {
String pkName = null;
List<PkColumn> columnNames = null;
while (resultSet.next()) {
if (columnNames == null) {
pkName = resultSet.getString("PK_NAME");
columnNames = new ArrayList<>(1);
} else {
assertThat(pkName).as("Multiple primary keys found").isEqualTo(resultSet.getString("PK_NAME"));
}
columnNames.add(new PkColumn(resultSet.getInt("KEY_SEQ") - 1, resultSet.getString("COLUMN_NAME")));
}
if (columnNames == null) {
return null;
}
return new PK(
pkName,
columnNames.stream()
.sorted(PkColumn.ORDERING_BY_INDEX)
.map(PkColumn::getName)
.toList());
}
}
private static final class PkColumn {
private static final Ordering<PkColumn> ORDERING_BY_INDEX = Ordering.natural().onResultOf(PkColumn::getIndex);
/**
* 0-based
*/
private final int index;
private final String name;
private PkColumn(int index, String name) {
this.index = index;
this.name = name;
}
public int getIndex() {
return index;
}
public String getName() {
return name;
}
}
@CheckForNull
private Integer getColumnIndex(ResultSet res, String column) {
try {
ResultSetMetaData meta = res.getMetaData();
int numCol = meta.getColumnCount();
for (int i = 1; i < numCol + 1; i++) {
if (meta.getColumnLabel(i).equalsIgnoreCase(column)) {
return i;
}
}
return null;
} catch (Exception e) {
throw new IllegalStateException("Fail to get column index");
}
}
private Set<String> getColumnNames(ResultSet res) {
try {
Set<String> columnNames = new HashSet<>();
ResultSetMetaData meta = res.getMetaData();
int numCol = meta.getColumnCount();
for (int i = 1; i < numCol + 1; i++) {
columnNames.add(meta.getColumnLabel(i).toLowerCase());
}
return columnNames;
} catch (Exception e) {
throw new IllegalStateException("Fail to get column names");
}
}
private static void doClobFree(Clob clob) throws SQLException {
try {
clob.free();
} catch (AbstractMethodError e) {
// JTS driver do not implement free() as it's using JDBC 3.0
}
}
public Connection openConnection() throws SQLException {
return getConnection();
}
private Connection getConnection() throws SQLException {
return db.getDatabase().getDataSource().getConnection();
}
public Database database() {
return db.getDatabase();
}
/**
* An {@link AutoCloseable} supplier of {@link Connection}.
*/
protected interface ConnectionSupplier extends AutoCloseable {
Connection get() throws SQLException;
@Override
void close();
}
private static class PK {
@CheckForNull
private final String name;
private final List<String> columns;
private PK(@Nullable String name, List<String> columns) {
this.name = name;
this.columns = List.copyOf(columns);
}
@CheckForNull
public String getName() {
return name;
}
public List<String> getColumns() {
return columns;
}
}
private class NewConnectionSupplier implements ConnectionSupplier {
private Connection connection;
@Override
public Connection get() throws SQLException {
if (this.connection == null) {
this.connection = getConnection();
}
return this.connection;
}
@Override
public void close() {
if (this.connection != null) {
try {
this.connection.close();
} catch (SQLException e) {
LoggerFactory.getLogger(CoreDbTester.class).warn("Fail to close connection", e);
// do not re-throw the exception
}
}
}
}
}
| 18,953 | 35.102857 | 151 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/testFixtures/java/org/sonar/db/CoreDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import org.apache.commons.lang.StringUtils;
/**
* This class should be called using @Rule.
* Data is truncated between each tests. The schema is created between each test.
*/
public class CoreDbTester extends AbstractDbTester<CoreTestDb> {
private CoreDbTester(CoreTestDb testDb) {
super(testDb);
}
public static CoreDbTester createForSchema(Class testClass, String filename) {
return createForSchema(testClass, filename, true);
}
public static CoreDbTester createForSchema(Class testClass, String filename, boolean databaseToUpper) {
String path = StringUtils.replaceChars(testClass.getCanonicalName(), '.', '/');
String schemaPath = path + "/" + filename;
return new CoreDbTester(CoreTestDb.create(schemaPath, databaseToUpper));
}
public static CoreDbTester createEmpty() {
return new CoreDbTester(CoreTestDb.createEmpty());
}
@Override
protected void before() {
db.start();
db.truncateTables();
}
@Override
protected void after() {
db.stop();
}
}
| 1,890 | 31.050847 | 105 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/testFixtures/java/org/sonar/db/CoreH2Database.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import com.zaxxer.hikari.HikariDataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.io.output.NullWriter;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import static java.lang.String.format;
/**
* H2 in-memory database, used for unit tests only against an empty DB or a provided H2 SQL script.
*/
public class CoreH2Database implements Database {
private static final String IGNORED_KEYWORDS_OPTION = ";NON_KEYWORDS=VALUE";
private final String name;
private HikariDataSource datasource;
/**
* IMPORTANT: change DB name in order to not conflict with {@link DefaultDatabaseTest}
*/
public CoreH2Database(String name) {
this.name = name + IGNORED_KEYWORDS_OPTION;
}
@Override
public void start() {
startDatabase();
}
private void startDatabase() {
try {
datasource = new HikariDataSource();
datasource.setDriverClassName("org.h2.Driver");
datasource.setUsername("sonar");
datasource.setPassword("sonar");
datasource.setJdbcUrl("jdbc:h2:mem:" + name);
} catch (Exception e) {
throw new IllegalStateException("Fail to start H2", e);
}
}
public void executeScript(String classloaderPath) {
try (Connection connection = datasource.getConnection()) {
executeScript(connection, classloaderPath);
} catch (SQLException e) {
throw new IllegalStateException("Fail to execute script: " + classloaderPath, e);
}
}
private static void executeScript(Connection connection, String path) {
ScriptRunner scriptRunner = newScriptRunner(connection);
try {
scriptRunner.runScript(Resources.getResourceAsReader(path));
connection.commit();
} catch (Exception e) {
throw new IllegalStateException("Fail to restore: " + path, e);
}
}
private static ScriptRunner newScriptRunner(Connection connection) {
ScriptRunner scriptRunner = new ScriptRunner(connection);
scriptRunner.setDelimiter(";");
scriptRunner.setStopOnError(true);
scriptRunner.setLogWriter(new PrintWriter(new NullWriter()));
return scriptRunner;
}
@Override
public void stop() {
datasource.close();
}
public DataSource getDataSource() {
return datasource;
}
public Dialect getDialect() {
return new H2();
}
@Override
public void enableSqlLogging(boolean enable) {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return format("H2 Database[%s]", name);
}
}
| 3,539 | 29.25641 | 99 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/testFixtures/java/org/sonar/db/CoreTestDb.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.annotation.Nullable;
import javax.sql.DataSource;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.AssumptionViolatedException;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.config.internal.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.db.version.SqTables;
import static java.util.Objects.requireNonNull;
import static org.sonar.process.ProcessProperties.Property.JDBC_USERNAME;
/**
* This class should be call using @ClassRule in order to create the schema once (if @Rule is used
* the schema will be recreated before each test).
* <p>
* <strong>Tests which rely on this class can only be run on H2</strong> because:
* <ul>
* <li>resetting the schema for each test on non-H2 database is assumed to expensive and slow</li>
* <li>when a specific schema is provided, this schema can't provide a syntax supported by all SGBDs and therefor only
* H2 is targeted</li>
* </ul>
*/
class CoreTestDb implements TestDb {
private Database db;
protected CoreTestDb() {
// use static factory method
}
protected CoreTestDb(Database db) {
this.db = db;
}
static CoreTestDb create(String schemaPath) {
return create(schemaPath, true);
}
static CoreTestDb create(String schemaPath, boolean databaseToUpper) {
requireNonNull(schemaPath, "schemaPath can't be null");
return new CoreTestDb().init(schemaPath, databaseToUpper);
}
static CoreTestDb createEmpty() {
return new CoreTestDb().init(null, true);
}
private CoreTestDb init(@Nullable String schemaPath, boolean databaseToUpper) {
Consumer<Settings> noExtraSettingsLoaded = settings -> {
};
Function<Settings, Database> databaseCreator = settings -> {
String dialect = settings.getString("sonar.jdbc.dialect");
// test relying on CoreTestDb can only run on H2
if (dialect != null && !"h2".equals(dialect)) {
throw new AssumptionViolatedException("This test is intended to be run on H2 only");
}
String name = "h2Tests-" + (schemaPath == null ? "empty" : DigestUtils.md5Hex(schemaPath));
if (!databaseToUpper) {
name = name + ";DATABASE_TO_UPPER=FALSE";
}
name = name + ";NON_KEYWORDS=VALUE";
return new CoreH2Database(name);
};
Consumer<Database> databaseInitializer = database -> {
if (schemaPath == null) {
return;
}
((CoreH2Database) database).executeScript(schemaPath);
};
BiConsumer<Database, Boolean> noPostStartAction = (db, created) -> {
};
init(noExtraSettingsLoaded, databaseCreator, databaseInitializer, noPostStartAction);
return this;
}
protected void init(Consumer<Settings> settingsLoader,
Function<Settings, Database> databaseCreator,
Consumer<Database> databaseInitializer,
BiConsumer<Database, Boolean> extendedStart) {
if (db == null) {
Settings settings = new MapSettings().addProperties(System.getProperties());
settingsLoader.accept(settings);
logJdbcSettings(settings);
db = databaseCreator.apply(settings);
db.start();
databaseInitializer.accept(db);
LoggerFactory.getLogger(getClass()).debug("Test Database: " + db);
String login = settings.getString(JDBC_USERNAME.getKey());
extendedStart.accept(db, true);
} else {
extendedStart.accept(db, false);
}
}
public void truncateTables() {
try {
truncateDatabase(getDatabase().getDataSource());
} catch (SQLException e) {
throw new IllegalStateException("Fail to truncate db tables", e);
}
}
private void truncateDatabase(DataSource dataSource) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(false);
try (Statement statement = connection.createStatement()) {
for (String table : SqTables.TABLES) {
try {
if (shouldTruncate(connection, table)) {
statement.executeUpdate(truncateSql(table));
connection.commit();
}
} catch (Exception e) {
connection.rollback();
throw new IllegalStateException("Fail to truncate table " + table, e);
}
}
}
}
}
private static boolean shouldTruncate(Connection connection, String table) {
try (Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select count(1) from " + table)) {
if (rs.next()) {
return rs.getInt(1) > 0;
}
} catch (SQLException ignored) {
// probably because table does not exist. That's the case with H2 tests.
}
return false;
}
private static String truncateSql(String table) {
return "TRUNCATE TABLE " + table;
}
@Override
public Database getDatabase() {
return db;
}
@Override
public void start() {
// everything is done in init
}
@Override
public void stop() {
db.stop();
}
private void logJdbcSettings(Settings settings) {
Logger logger = LoggerFactory.getLogger(getClass());
for (String key : settings.getKeysStartingWith("sonar.jdbc")) {
logger.info(key + ": " + settings.getString(key));
}
}
}
| 6,343 | 30.72 | 120 | java |
sonarqube | sonarqube-master/server/sonar-db-core/src/testFixtures/java/org/sonar/db/TestDb.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
public interface TestDb {
void start();
void stop();
Database getDatabase();
}
| 954 | 30.833333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/DatabaseMBeanIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo.Section;
import static org.assertj.core.api.Assertions.assertThat;
public class DatabaseMBeanIT {
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private final FakeDatabaseMBean underTest = new FakeDatabaseMBean(dbTester.getDbClient());
@Test
public void verify_mBean() {
assertThat(underTest.getPoolActiveConnections()).isNotNegative();
assertThat(underTest.getPoolIdleConnections()).isNotNegative();
assertThat(underTest.getPoolMaxConnections()).isNotNegative();
assertThat(underTest.getPoolMaxLifeTimeMillis()).isNotNegative();
assertThat(underTest.getPoolMinIdleConnections()).isNotNegative();
assertThat(underTest.getPoolTotalConnections()).isNotNegative();
assertThat(underTest.getPoolMaxWaitMillis()).isNotNegative();
assertThat(underTest.name()).isEqualTo("FakeMBean");
}
private static class FakeDatabaseMBean extends DatabaseMBean {
protected FakeDatabaseMBean(DbClient dbClient) {
super(dbClient);
}
@Override
protected String name() {
return "FakeMBean";
}
@Override
public Section toProtobuf() {
return Section.newBuilder().build();
}
}
}
| 2,192 | 32.227273 | 92 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/IsAliveMapperIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import static org.assertj.core.api.Assertions.assertThat;
public class IsAliveMapperIT {
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private DbSession session;
private IsAliveMapper underTest;
@Before
public void setUp() {
session = dbTester.getSession();
underTest = session.getMapper(IsAliveMapper.class);
}
@After
public void tearDown() {
session.close();
}
@Test
public void isAlive_works_for_current_vendors() {
assertThat(underTest.isAlive()).isEqualTo(IsAliveMapper.IS_ALIVE_RETURNED_VALUE);
}
}
| 1,572 | 28.679245 | 85 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/MyBatisIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import org.apache.ibatis.session.Configuration;
import org.hamcrest.core.Is;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.sonar.db.rule.RuleMapper;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
public class MyBatisIT {
private static SQDatabase database;
@BeforeClass
public static void start() {
database = SQDatabase.newH2Database("sonar2", true);
database.start();
}
@AfterClass
public static void stop() {
database.stop();
}
private MyBatis underTest = new MyBatis(database);
@Test
public void shouldConfigureMyBatis() {
underTest.start();
Configuration conf = underTest.getSessionFactory().getConfiguration();
assertThat(conf.isUseGeneratedKeys(), Is.is(true));
assertThat(conf.hasMapper(RuleMapper.class), Is.is(true));
assertThat(conf.isLazyLoadingEnabled(), Is.is(false));
}
@Test
public void shouldOpenBatchSession() {
underTest.start();
try (DbSession session = underTest.openSession(false)) {
assertThat(session.getConnection(), notNullValue());
assertThat(session.getMapper(RuleMapper.class), notNullValue());
}
}
}
| 2,086 | 29.691176 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/SQDatabaseForH2IT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class SQDatabaseForH2IT {
SQDatabase db = SQDatabase.newH2Database("sonar2", true);
@Before
public void startDb() {
db.start();
}
@After
public void stopDb() {
db.stop();
}
@Test
public void shouldExecuteDdlAtStartup() throws SQLException {
Connection connection = db.getDataSource().getConnection();
int tableCount = countTables(connection);
connection.close();
assertThat(tableCount).isGreaterThan(30);
}
private static int countTables(Connection connection) throws SQLException {
int count = 0;
ResultSet resultSet = connection.getMetaData().getTables("", null, null, new String[] {"TABLE"});
while (resultSet.next()) {
count++;
}
resultSet.close();
return count;
}
}
| 1,844 | 28.285714 | 101 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/alm/pat/AlmPatDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.alm.pat;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.alm.setting.AlmSettingDao;
import org.sonar.db.alm.setting.AlmSettingDto;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.user.UserDto;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto;
import static org.sonar.db.almsettings.AlmSettingsTesting.newGithubAlmSettingDto;
public class AlmPatDaoIT {
private static final long NOW = 1000000L;
private static final String A_UUID = "SOME_UUID";
private TestSystem2 system2 = new TestSystem2().setNow(NOW);
@Rule
public DbTester db = DbTester.create(system2);
private DbSession dbSession = db.getSession();
private UuidFactory uuidFactory = mock(UuidFactory.class);
private AlmSettingDao almSettingDao = new AlmSettingDao(system2, uuidFactory, new NoOpAuditPersister());
private AlmPatDao underTest = new AlmPatDao(system2, uuidFactory, new NoOpAuditPersister());
@Test
public void selectByUuid() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmPatDto almPatDto = newAlmPatDto();
underTest.insert(dbSession, almPatDto, null, null);
assertThat(underTest.selectByUuid(dbSession, A_UUID).get())
.extracting(AlmPatDto::getUuid, AlmPatDto::getPersonalAccessToken,
AlmPatDto::getUserUuid, AlmPatDto::getAlmSettingUuid,
AlmPatDto::getUpdatedAt, AlmPatDto::getCreatedAt)
.containsExactly(A_UUID, almPatDto.getPersonalAccessToken(),
almPatDto.getUserUuid(), almPatDto.getAlmSettingUuid(),
NOW, NOW);
assertThat(underTest.selectByUuid(dbSession, "foo")).isNotPresent();
}
@Test
public void selectByAlmSetting() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto almSetting = newGithubAlmSettingDto();
almSettingDao.insert(dbSession, almSetting);
AlmPatDto almPatDto = newAlmPatDto();
almPatDto.setAlmSettingUuid(almSetting.getUuid());
String userUuid = randomAlphanumeric(40);
almPatDto.setUserUuid(userUuid);
underTest.insert(dbSession, almPatDto, null, null);
assertThat(underTest.selectByUserAndAlmSetting(dbSession, userUuid, almSetting).get())
.extracting(AlmPatDto::getUuid, AlmPatDto::getPersonalAccessToken,
AlmPatDto::getUserUuid, AlmPatDto::getAlmSettingUuid,
AlmPatDto::getCreatedAt, AlmPatDto::getUpdatedAt)
.containsExactly(A_UUID, almPatDto.getPersonalAccessToken(),
userUuid, almSetting.getUuid(), NOW, NOW);
assertThat(underTest.selectByUserAndAlmSetting(dbSession, randomAlphanumeric(40), newGithubAlmSettingDto())).isNotPresent();
}
@Test
public void update() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmPatDto almPatDto = newAlmPatDto();
underTest.insert(dbSession, almPatDto, null, null);
String updated_pat = "updated pat";
almPatDto.setPersonalAccessToken(updated_pat);
system2.setNow(NOW + 1);
underTest.update(dbSession, almPatDto, null, null);
AlmPatDto result = underTest.selectByUuid(dbSession, A_UUID).get();
assertThat(result)
.extracting(AlmPatDto::getUuid, AlmPatDto::getPersonalAccessToken,
AlmPatDto::getUserUuid, AlmPatDto::getAlmSettingUuid,
AlmPatDto::getCreatedAt, AlmPatDto::getUpdatedAt)
.containsExactly(A_UUID, updated_pat, almPatDto.getUserUuid(),
almPatDto.getAlmSettingUuid(),
NOW, NOW + 1);
}
@Test
public void delete() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmPatDto almPat = newAlmPatDto();
underTest.insert(dbSession, almPat, null, null);
underTest.delete(dbSession, almPat, null, null);
assertThat(underTest.selectByUuid(dbSession, almPat.getUuid())).isNotPresent();
}
@Test
public void deleteByUser() {
when(uuidFactory.create()).thenReturn(A_UUID);
UserDto userDto = db.users().insertUser();
AlmPatDto almPat = newAlmPatDto();
almPat.setUserUuid(userDto.getUuid());
underTest.insert(dbSession, almPat, userDto.getLogin(), null);
underTest.deleteByUser(dbSession, userDto);
assertThat(underTest.selectByUuid(dbSession, almPat.getUuid())).isNotPresent();
}
@Test
public void deleteByAlmSetting() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto almSettingDto = db.almSettings().insertBitbucketAlmSetting();
AlmPatDto almPat = newAlmPatDto();
almPat.setAlmSettingUuid(almSettingDto.getUuid());
underTest.insert(dbSession, almPat, null, null);
underTest.deleteByAlmSetting(dbSession, almSettingDto);
assertThat(underTest.selectByUuid(dbSession, almPat.getUuid())).isNotPresent();
}
}
| 5,833 | 36.63871 | 128 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/alm/pat/AlmPatDaoWithPersisterIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.alm.pat;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.alm.setting.AlmSettingDto;
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.audit.model.PersonalAccessTokenNewValue;
import org.sonar.db.user.UserDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.clearInvocations;
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.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto;
public class AlmPatDaoWithPersisterIT {
private static final long NOW = 1000000L;
private static final String A_UUID = "SOME_UUID";
private final AuditPersister auditPersister = mock(AuditPersister.class);
private final ArgumentCaptor<PersonalAccessTokenNewValue> newValueCaptor = ArgumentCaptor.forClass(PersonalAccessTokenNewValue.class);
private final TestSystem2 system2 = new TestSystem2().setNow(NOW);
@Rule
public DbTester db = DbTester.create(system2, auditPersister);
private final DbSession dbSession = db.getSession();
private final UuidFactory uuidFactory = mock(UuidFactory.class);
private final AlmPatDao underTest = db.getDbClient().almPatDao();
@Test
public void insertAndUpdateArePersisted() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmPatDto almPatDto = newAlmPatDto();
underTest.insert(dbSession, almPatDto, "user-login", "alm-key");
verify(auditPersister).addPersonalAccessToken(eq(dbSession), newValueCaptor.capture());
PersonalAccessTokenNewValue newValue = newValueCaptor.getValue();
assertThat(newValue)
.extracting(PersonalAccessTokenNewValue::getPatUuid, PersonalAccessTokenNewValue::getUserUuid,
PersonalAccessTokenNewValue::getAlmSettingUuid, PersonalAccessTokenNewValue::getUserLogin,
PersonalAccessTokenNewValue::getAlmSettingKey)
.containsExactly(almPatDto.getUuid(), almPatDto.getUserUuid(), almPatDto.getAlmSettingUuid(),
"user-login", "alm-key");
assertThat(newValue.toString()).contains("userLogin");
String updated_pat = "updated pat";
almPatDto.setPersonalAccessToken(updated_pat);
system2.setNow(NOW + 1);
underTest.update(dbSession, almPatDto, null, null);
verify(auditPersister).updatePersonalAccessToken(eq(dbSession), newValueCaptor.capture());
}
@Test
public void deleteIsPersisted() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmPatDto almPat = newAlmPatDto();
underTest.insert(dbSession, almPat, null, null);
verify(auditPersister).addPersonalAccessToken(eq(dbSession), newValueCaptor.capture());
underTest.delete(dbSession, almPat, null, null);
verify(auditPersister).deletePersonalAccessToken(eq(dbSession), newValueCaptor.capture());
PersonalAccessTokenNewValue newValue = newValueCaptor.getValue();
assertThat(newValue)
.extracting(PersonalAccessTokenNewValue::getPatUuid, PersonalAccessTokenNewValue::getUserUuid,
PersonalAccessTokenNewValue::getAlmSettingUuid, PersonalAccessTokenNewValue::getUserLogin,
PersonalAccessTokenNewValue::getAlmSettingKey)
.containsExactly(almPat.getUuid(), almPat.getUserUuid(), almPat.getAlmSettingUuid(),
null, null);
assertThat(newValue.toString()).doesNotContain("userLogin");
}
@Test
public void deleteWithoutAffectedRowsIsNotPersisted() {
AlmPatDto almPat = newAlmPatDto();
underTest.delete(dbSession, almPat, null, null);
verifyNoInteractions(auditPersister);
}
@Test
public void deleteByUserIsPersisted() {
when(uuidFactory.create()).thenReturn(A_UUID);
UserDto userDto = db.users().insertUser();
AlmPatDto almPat = newAlmPatDto();
almPat.setUserUuid(userDto.getUuid());
underTest.insert(dbSession, almPat, userDto.getLogin(), null);
verify(auditPersister).addPersonalAccessToken(eq(dbSession), newValueCaptor.capture());
underTest.deleteByUser(dbSession, userDto);
verify(auditPersister).deletePersonalAccessToken(eq(dbSession), newValueCaptor.capture());
PersonalAccessTokenNewValue newValue = newValueCaptor.getValue();
assertThat(newValue)
.extracting(PersonalAccessTokenNewValue::getPatUuid, PersonalAccessTokenNewValue::getUserUuid,
PersonalAccessTokenNewValue::getUserLogin, PersonalAccessTokenNewValue::getAlmSettingKey)
.containsExactly(null, userDto.getUuid(), userDto.getLogin(), null);
assertThat(newValue.toString()).doesNotContain("patUuid");
}
@Test
public void deleteByUserWithoutAffectedRowsIsNotPersisted() {
UserDto userDto = db.users().insertUser();
underTest.deleteByUser(dbSession, userDto);
verify(auditPersister).addUser(any(), any());
verifyNoMoreInteractions(auditPersister);
}
@Test
public void deleteByAlmSettingIsPersisted() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto almSettingDto = db.almSettings().insertBitbucketAlmSetting();
AlmPatDto almPat = newAlmPatDto();
almPat.setAlmSettingUuid(almSettingDto.getUuid());
underTest.insert(dbSession, almPat, null, almSettingDto.getKey());
verify(auditPersister).addPersonalAccessToken(eq(dbSession), newValueCaptor.capture());
underTest.deleteByAlmSetting(dbSession, almSettingDto);
verify(auditPersister).deletePersonalAccessToken(eq(dbSession), newValueCaptor.capture());
PersonalAccessTokenNewValue newValue = newValueCaptor.getValue();
assertThat(newValue)
.extracting(PersonalAccessTokenNewValue::getPatUuid, PersonalAccessTokenNewValue::getAlmSettingUuid,
PersonalAccessTokenNewValue::getAlmSettingKey)
.containsExactly(null, almPat.getAlmSettingUuid(), almSettingDto.getKey());
assertThat(newValue.toString()).doesNotContain("userUuid");
}
@Test
public void deleteByAlmSettingWithoutAffectedRowsIsNotPersisted() {
AlmSettingDto almSettingDto = db.almSettings().insertBitbucketAlmSetting();
clearInvocations(auditPersister);
underTest.deleteByAlmSetting(dbSession, almSettingDto);
verifyNoInteractions(auditPersister);
}
}
| 7,348 | 40.755682 | 136 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/alm/setting/AlmSettingDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.alm.setting;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.audit.NoOpAuditPersister;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.db.alm.setting.ALM.GITHUB;
import static org.sonar.db.alm.setting.ALM.GITLAB;
import static org.sonar.db.almsettings.AlmSettingsTesting.newGithubAlmSettingDto;
public class AlmSettingDaoIT {
private static final long NOW = 1000000L;
private static final String A_UUID = "SOME_UUID";
private static final AlmSettingDto ALM_SETTING_WITH_WEBHOOK_SECRET = newGithubAlmSettingDto().setWebhookSecret("webhook_secret");
private final TestSystem2 system2 = new TestSystem2().setNow(NOW);
@Rule
public DbTester db = DbTester.create(system2);
private final DbSession dbSession = db.getSession();
private final UuidFactory uuidFactory = mock(UuidFactory.class);
private final AlmSettingDao underTest = new AlmSettingDao(system2, uuidFactory, new NoOpAuditPersister());
@Before
public void setUp() {
Iterator<Integer> values = Stream.iterate(0, i -> i + 1).iterator();
when(uuidFactory.create()).thenAnswer(answer -> A_UUID + "_" + values.next());
}
@Test
public void selectByUuid() {
AlmSettingDto expected = ALM_SETTING_WITH_WEBHOOK_SECRET;
underTest.insert(dbSession, expected);
AlmSettingDto result = underTest.selectByUuid(dbSession, expected.getUuid()).orElse(null);
assertThat(result).usingRecursiveComparison().isEqualTo(expected);
}
@Test
public void selectByUuid_shouldNotFindResult_whenUuidIsNotPresent() {
AlmSettingDto expected = ALM_SETTING_WITH_WEBHOOK_SECRET;
underTest.insert(dbSession, expected);
assertThat(underTest.selectByUuid(dbSession, "foo")).isNotPresent();
}
@Test
public void selectByKey() {
AlmSettingDto expected = ALM_SETTING_WITH_WEBHOOK_SECRET;
underTest.insert(dbSession, expected);
AlmSettingDto result = underTest.selectByKey(dbSession, expected.getKey()).orElse(null);
assertThat(result).usingRecursiveComparison().isEqualTo(expected);
}
@Test
public void selectByKey_shouldNotFindResult_whenKeyIsNotPresent() {
AlmSettingDto expected = ALM_SETTING_WITH_WEBHOOK_SECRET;
underTest.insert(dbSession, expected);
assertThat(underTest.selectByKey(dbSession, "foo")).isNotPresent();
}
@Test
public void selectByKey_withEmptySecrets() {
AlmSettingDto expected = newGithubAlmSettingDto().setWebhookSecret(null);
underTest.insert(dbSession, expected);
AlmSettingDto result = underTest.selectByKey(dbSession, expected.getKey()).orElse(null);
assertThat(result).usingRecursiveComparison().isEqualTo(expected);
}
@Test
public void selectByAlm() {
AlmSettingDto gitHubAlmSetting1 = db.almSettings().insertGitHubAlmSetting();
AlmSettingDto gitHubAlmSetting2 = db.almSettings().insertGitHubAlmSetting();
db.almSettings().insertAzureAlmSetting();
List<AlmSettingDto> almSettings = underTest.selectByAlm(dbSession, GITHUB);
assertThat(almSettings)
.extracting(AlmSettingDto::getUuid)
.containsExactlyInAnyOrder(gitHubAlmSetting1.getUuid(), gitHubAlmSetting2.getUuid());
}
@Test
public void selectAll() {
underTest.insert(dbSession, newGithubAlmSettingDto());
when(uuidFactory.create()).thenReturn(A_UUID + "bis");
underTest.insert(dbSession, newGithubAlmSettingDto());
List<AlmSettingDto> almSettings = underTest.selectAll(dbSession);
assertThat(almSettings).size().isEqualTo(2);
}
@Test
public void update() {
//GIVEN
AlmSettingDto expected = newGithubAlmSettingDto();
underTest.insert(dbSession, expected);
expected.setPrivateKey("updated private key");
expected.setAppId("updated app id");
expected.setUrl("updated url");
expected.setPersonalAccessToken("updated pat");
expected.setKey("updated key");
expected.setWebhookSecret("updated webhook secret");
system2.setNow(NOW + 1);
//WHEN
underTest.update(dbSession, expected, false);
//THEN
AlmSettingDto result = underTest.selectByUuid(dbSession, expected.getUuid()).orElse(null);
assertThat(result).usingRecursiveComparison().isEqualTo(expected);
}
@Test
public void delete() {
AlmSettingDto almSettingDto = newGithubAlmSettingDto();
underTest.insert(dbSession, almSettingDto);
underTest.delete(dbSession, almSettingDto);
assertThat(underTest.selectByKey(dbSession, almSettingDto.getKey())).isNotPresent();
}
@Test
public void selectByAlmAndAppId_whenSingleMatch_returnsCorrectObject() {
String appId = "APP_ID";
AlmSettingDto expectedAlmSettingDto = db.almSettings().insertGitHubAlmSetting(almSettingDto -> almSettingDto.setAppId(appId));
db.almSettings().insertGitHubAlmSetting(almSettingDto -> almSettingDto.setAppId(null));
Optional<AlmSettingDto> result = underTest.selectByAlmAndAppId(dbSession, GITHUB, appId);
assertThat(result).isPresent();
assertThat(result.get()).usingRecursiveComparison().isEqualTo(expectedAlmSettingDto);
}
@Test
public void selectByAlmAndAppId_whenAppIdSharedWithAnotherAlm_returnsCorrectOne() {
String appId = "APP_ID";
db.almSettings().insertGitHubAlmSetting(almSettingDto -> almSettingDto.setAppId(appId));
AlmSettingDto gitLabAlmSettingDto = db.almSettings().insertGitlabAlmSetting(almSettingDto -> almSettingDto.setAppId(appId));
Optional<AlmSettingDto> result = underTest.selectByAlmAndAppId(dbSession, GITLAB, appId);
assertThat(result).isPresent();
assertThat(result.get()).usingRecursiveComparison().isEqualTo(gitLabAlmSettingDto);
}
@Test
public void selectByAlmAndAppId_withMultipleConfigurationWithSameAppId_returnsAnyAndDoesNotFail() {
String appId = "APP_ID";
IntStream.of(1, 10).forEach(i -> db.almSettings().insertGitHubAlmSetting(almSettingDto -> almSettingDto.setAppId(appId)));
IntStream.of(1, 5).forEach(i -> db.almSettings().insertGitHubAlmSetting(almSettingDto -> almSettingDto.setAppId(null)));
Optional<AlmSettingDto> result = underTest.selectByAlmAndAppId(dbSession, GITHUB, appId);
assertThat(result).isPresent();
assertThat(result.get().getAppId()).isEqualTo(appId);
}
}
| 7,457 | 35.920792 | 131 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/alm/setting/AlmSettingDaoWithPersisterIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.alm.setting;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.audit.model.DevOpsPlatformSettingNewValue;
import org.sonar.db.audit.model.SecretNewValue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.db.almsettings.AlmSettingsTesting.newGithubAlmSettingDto;
public class AlmSettingDaoWithPersisterIT {
private static final long NOW = 1000000L;
private static final String A_UUID = "SOME_UUID";
private final ArgumentCaptor<DevOpsPlatformSettingNewValue> newValueCaptor = ArgumentCaptor.forClass(DevOpsPlatformSettingNewValue.class);
private final AuditPersister auditPersister = mock(AuditPersister.class);
private final TestSystem2 system2 = new TestSystem2().setNow(NOW);
@Rule
public final DbTester db = DbTester.create(system2, auditPersister);
private final DbSession dbSession = db.getSession();
private final UuidFactory uuidFactory = mock(UuidFactory.class);
private final AlmSettingDao underTest = db.getDbClient().almSettingDao();
@Test
public void insertAndUpdateArePersisted() {
ArgumentCaptor<SecretNewValue> secretNewValueCaptor = ArgumentCaptor.forClass(SecretNewValue.class);
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto almSettingDto = newGithubAlmSettingDto()
.setKey("key")
.setAppId("id1")
.setClientId("cid1")
.setUrl("url");
underTest.insert(dbSession, almSettingDto);
verify(auditPersister).addDevOpsPlatformSetting(eq(dbSession), newValueCaptor.capture());
DevOpsPlatformSettingNewValue newValue = newValueCaptor.getValue();
assertThat(newValue)
.extracting("devOpsPlatformSettingUuid", "key")
.containsExactly(almSettingDto.getUuid(), almSettingDto.getKey());
assertThat(newValue)
.hasToString("{\"devOpsPlatformSettingUuid\": \"1\", \"key\": \"key\", \"devOpsPlatformName\": \"id1\", \"url\": \"url\", \"appId\": \"id1\", \"clientId\": \"cid1\" }");
almSettingDto.setPrivateKey("updated private key");
almSettingDto.setAppId("updated app id");
almSettingDto.setUrl("updated url");
almSettingDto.setPersonalAccessToken("updated pat");
almSettingDto.setKey("updated key");
underTest.update(dbSession, almSettingDto, true);
verify(auditPersister).updateDevOpsPlatformSecret(eq(dbSession), secretNewValueCaptor.capture());
SecretNewValue secretNewValue = secretNewValueCaptor.getValue();
assertThat(secretNewValue).hasToString(String.format("{\"DevOpsPlatform\":\"%s\"}", almSettingDto.getRawAlm()));
verify(auditPersister).updateDevOpsPlatformSetting(eq(dbSession), newValueCaptor.capture());
newValue = newValueCaptor.getValue();
assertThat(newValue)
.extracting("devOpsPlatformSettingUuid", "key", "appId", "devOpsPlatformName", "url", "clientId")
.containsExactly(almSettingDto.getUuid(), almSettingDto.getKey(), almSettingDto.getAppId(), almSettingDto.getAppId(), almSettingDto.getUrl(), almSettingDto.getClientId());
assertThat(newValue).hasToString("{\"devOpsPlatformSettingUuid\": \"1\", \"key\": \"updated key\", \"devOpsPlatformName\": \"updated app id\", "
+ "\"url\": \"updated url\", \"appId\": \"updated app id\", \"clientId\": \"cid1\" }");
}
@Test
public void deleteIsPersisted() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto almSettingDto = newGithubAlmSettingDto();
underTest.insert(dbSession, almSettingDto);
underTest.delete(dbSession, almSettingDto);
verify(auditPersister).deleteDevOpsPlatformSetting(eq(dbSession), newValueCaptor.capture());
DevOpsPlatformSettingNewValue newValue = newValueCaptor.getValue();
assertThat(newValue)
.extracting("devOpsPlatformSettingUuid", "key")
.containsExactly(almSettingDto.getUuid(), almSettingDto.getKey());
assertThat(newValue.getUrl()).isNullOrEmpty();
}
}
| 5,120 | 44.318584 | 177 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/alm/setting/ProjectAlmSettingDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.alm.setting;
import java.util.HashSet;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.project.ProjectDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.db.almsettings.AlmSettingsTesting.newBitbucketProjectAlmSettingDto;
import static org.sonar.db.almsettings.AlmSettingsTesting.newGithubProjectAlmSettingDto;
public class ProjectAlmSettingDaoIT {
private static final long A_DATE = 1_000_000_000_000L;
private static final long A_DATE_LATER = 1_700_000_000_000L;
private static final String A_UUID = "SOME_UUID";
private TestSystem2 system2 = new TestSystem2().setNow(A_DATE);
@Rule
public DbTester db = DbTester.create(system2);
private DbSession dbSession = db.getSession();
private UuidFactory uuidFactory = mock(UuidFactory.class);
private ProjectAlmSettingDao underTest = new ProjectAlmSettingDao(system2, uuidFactory, new NoOpAuditPersister());
@Test
public void select_by_project() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto githubAlmSettingDto = db.almSettings().insertGitHubAlmSetting();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
ProjectDto anotherProject = db.components().insertPrivateProject().getProjectDto();
ProjectAlmSettingDto githubProjectAlmSettingDto = newGithubProjectAlmSettingDto(githubAlmSettingDto, project);
underTest.insertOrUpdate(dbSession, githubProjectAlmSettingDto, githubAlmSettingDto.getKey(), anotherProject.getName(),
anotherProject.getKey());
assertThat(underTest.selectByProject(dbSession, project).get())
.extracting(ProjectAlmSettingDto::getUuid, ProjectAlmSettingDto::getAlmSettingUuid, ProjectAlmSettingDto::getProjectUuid,
ProjectAlmSettingDto::getAlmRepo, ProjectAlmSettingDto::getAlmSlug,
ProjectAlmSettingDto::getCreatedAt, ProjectAlmSettingDto::getUpdatedAt,
ProjectAlmSettingDto::getSummaryCommentEnabled, ProjectAlmSettingDto::getMonorepo)
.containsExactly(A_UUID, githubAlmSettingDto.getUuid(), project.getUuid(),
githubProjectAlmSettingDto.getAlmRepo(), githubProjectAlmSettingDto.getAlmSlug(),
A_DATE, A_DATE, githubProjectAlmSettingDto.getSummaryCommentEnabled(), false);
assertThat(underTest.selectByProject(dbSession, anotherProject)).isNotPresent();
}
@Test
public void select_by_alm_setting_and_slugs() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto almSettingsDto = db.almSettings().insertBitbucketAlmSetting();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
ProjectAlmSettingDto bitbucketProjectAlmSettingDto = newBitbucketProjectAlmSettingDto(almSettingsDto, project);
bitbucketProjectAlmSettingDto.setAlmSlug("slug1");
underTest.insertOrUpdate(dbSession, bitbucketProjectAlmSettingDto, almSettingsDto.getKey(), project.getName(), project.getKey());
ProjectAlmSettingDto bitbucketProjectAlmSettingDto2 = newBitbucketProjectAlmSettingDto(almSettingsDto, db.components().insertPrivateProject().getProjectDto());
bitbucketProjectAlmSettingDto2.setAlmSlug("slug2");
when(uuidFactory.create()).thenReturn(A_UUID + 1);
underTest.insertOrUpdate(dbSession, bitbucketProjectAlmSettingDto2, almSettingsDto.getKey(), project.getName(), project.getKey());
Set<String> slugs = new HashSet<>();
slugs.add("slug1");
assertThat(underTest.selectByAlmSettingAndSlugs(dbSession, almSettingsDto, slugs))
.extracting(ProjectAlmSettingDto::getProjectUuid, ProjectAlmSettingDto::getSummaryCommentEnabled)
.containsExactly(tuple(project.getUuid(), bitbucketProjectAlmSettingDto2.getSummaryCommentEnabled()));
}
@Test
public void select_with_no_slugs_return_empty() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto almSettingsDto = db.almSettings().insertBitbucketAlmSetting();
assertThat(underTest.selectByAlmSettingAndSlugs(dbSession, almSettingsDto, new HashSet<>())).isEmpty();
}
@Test
public void select_by_alm_setting_and_repos() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto almSettingsDto = db.almSettings().insertGitHubAlmSetting();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
ProjectAlmSettingDto githubProjectAlmSettingDto = newGithubProjectAlmSettingDto(almSettingsDto, project);
githubProjectAlmSettingDto.setAlmRepo("repo1");
underTest.insertOrUpdate(dbSession, githubProjectAlmSettingDto, almSettingsDto.getKey(), project.getName(), project.getKey());
ProjectAlmSettingDto githubProjectAlmSettingDto2 = newGithubProjectAlmSettingDto(almSettingsDto, db.components().insertPrivateProject().getProjectDto());
githubProjectAlmSettingDto2.setAlmRepo("repo2");
when(uuidFactory.create()).thenReturn(A_UUID + 1);
underTest.insertOrUpdate(dbSession, githubProjectAlmSettingDto2, almSettingsDto.getKey(), project.getName(), project.getKey());
Set<String> repos = new HashSet<>();
repos.add("repo1");
assertThat(underTest.selectByAlmSettingAndRepos(dbSession, almSettingsDto, repos))
.extracting(ProjectAlmSettingDto::getProjectUuid, ProjectAlmSettingDto::getSummaryCommentEnabled)
.containsExactly(tuple(project.getUuid(), githubProjectAlmSettingDto.getSummaryCommentEnabled()));
}
@Test
public void select_with_no_repos_return_empty() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto almSettingsDto = db.almSettings().insertGitHubAlmSetting();
assertThat(underTest.selectByAlmSettingAndRepos(dbSession, almSettingsDto, new HashSet<>())).isEmpty();
}
@Test
public void select_alm_type_and_url_by_project() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto almSettingsDto = db.almSettings().insertGitHubAlmSetting();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
ProjectAlmSettingDto githubProjectAlmSettingDto = newGithubProjectAlmSettingDto(almSettingsDto, project);
underTest.insertOrUpdate(dbSession, githubProjectAlmSettingDto, almSettingsDto.getKey(), project.getName(), project.getKey());
assertThat(underTest.selectAlmTypeAndUrlByProject(dbSession))
.extracting(ProjectAlmKeyAndProject::getProjectUuid, ProjectAlmKeyAndProject::getAlmId, ProjectAlmKeyAndProject::getUrl)
.containsExactly(tuple(project.getUuid(), almSettingsDto.getAlm().getId(), almSettingsDto.getUrl()));
}
@Test
public void update_existing_binding() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto githubAlmSetting = db.almSettings().insertGitHubAlmSetting();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
ProjectAlmSettingDto projectAlmSettingDto = db.almSettings().insertGitHubProjectAlmSetting(githubAlmSetting, project);
AlmSettingDto anotherGithubAlmSetting = db.almSettings().insertGitHubAlmSetting();
system2.setNow(A_DATE_LATER);
ProjectAlmSettingDto newProjectAlmSettingDto = newGithubProjectAlmSettingDto(anotherGithubAlmSetting, project)
.setSummaryCommentEnabled(false);
underTest.insertOrUpdate(dbSession, newProjectAlmSettingDto, githubAlmSetting.getKey(), project.getName(), project.getKey());
assertThat(underTest.selectByProject(dbSession, project).get())
.extracting(ProjectAlmSettingDto::getUuid, ProjectAlmSettingDto::getAlmSettingUuid, ProjectAlmSettingDto::getProjectUuid,
ProjectAlmSettingDto::getAlmRepo, ProjectAlmSettingDto::getAlmSlug,
ProjectAlmSettingDto::getCreatedAt, ProjectAlmSettingDto::getUpdatedAt,
ProjectAlmSettingDto::getSummaryCommentEnabled)
.containsExactly(projectAlmSettingDto.getUuid(), anotherGithubAlmSetting.getUuid(), project.getUuid(),
newProjectAlmSettingDto.getAlmRepo(), newProjectAlmSettingDto.getAlmSlug(),
A_DATE, A_DATE_LATER, newProjectAlmSettingDto.getSummaryCommentEnabled());
}
@Test
public void deleteByProject() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto githubAlmSetting = db.almSettings().insertGitHubAlmSetting();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
db.almSettings().insertGitHubProjectAlmSetting(githubAlmSetting, project);
ProjectDto anotherProject = db.components().insertPrivateProject().getProjectDto();
db.almSettings().insertGitHubProjectAlmSetting(githubAlmSetting, anotherProject);
underTest.deleteByProject(dbSession, project);
assertThat(underTest.selectByProject(dbSession, project)).isEmpty();
assertThat(underTest.selectByProject(dbSession, anotherProject)).isNotEmpty();
}
@Test
public void deleteByAlmSetting() {
when(uuidFactory.create()).thenReturn(A_UUID);
AlmSettingDto githubAlmSetting = db.almSettings().insertGitHubAlmSetting();
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
ProjectDto project2 = db.components().insertPrivateProject().getProjectDto();
db.almSettings().insertGitHubProjectAlmSetting(githubAlmSetting, project1);
db.almSettings().insertGitHubProjectAlmSetting(githubAlmSetting, project2);
AlmSettingDto githubAlmSetting1 = db.almSettings().insertGitHubAlmSetting();
ProjectDto anotherProject = db.components().insertPrivateProject().getProjectDto();
db.almSettings().insertGitHubProjectAlmSetting(githubAlmSetting1, anotherProject);
underTest.deleteByAlmSetting(dbSession, githubAlmSetting);
assertThat(underTest.countByAlmSetting(dbSession, githubAlmSetting)).isZero();
assertThat(underTest.countByAlmSetting(dbSession, githubAlmSetting1)).isOne();
}
}
| 10,861 | 52.772277 | 163 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/alm/setting/ProjectAlmSettingDaoWithPersisterIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.alm.setting;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.audit.model.DevOpsPlatformSettingNewValue;
import org.sonar.db.project.ProjectDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.sonar.db.almsettings.AlmSettingsTesting.newGithubAlmSettingDto;
import static org.sonar.db.almsettings.AlmSettingsTesting.newGithubProjectAlmSettingDto;
public class ProjectAlmSettingDaoWithPersisterIT {
private static final long A_DATE = 1_000_000_000_000L;
private static final long A_DATE_LATER = 1_700_000_000_000L;
private final ArgumentCaptor<DevOpsPlatformSettingNewValue> newValueCaptor = ArgumentCaptor.forClass(DevOpsPlatformSettingNewValue.class);
private final AuditPersister auditPersister = mock(AuditPersister.class);
private final TestSystem2 system2 = new TestSystem2().setNow(A_DATE);
@Rule
public final DbTester db = DbTester.create(system2, auditPersister);
private final DbSession dbSession = db.getSession();
private final UuidFactory uuidFactory = UuidFactoryFast.getInstance();
private final ProjectAlmSettingDao underTest = db.getDbClient().projectAlmSettingDao();
@Test
public void insertAndUpdateExistingBindingArePersisted() {
AlmSettingDto githubAlmSetting = newGithubAlmSettingDto().setUuid(uuidFactory.create());
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
ProjectAlmSettingDto projectAlmSettingDto = newGithubProjectAlmSettingDto(githubAlmSetting, project)
.setSummaryCommentEnabled(false);
underTest.insertOrUpdate(dbSession, projectAlmSettingDto, githubAlmSetting.getKey(), project.getName(), project.getKey());
verify(auditPersister).addDevOpsPlatformSetting(eq(dbSession), newValueCaptor.capture());
DevOpsPlatformSettingNewValue newValue = newValueCaptor.getValue();
assertThat(newValue)
.extracting(DevOpsPlatformSettingNewValue::getDevOpsPlatformSettingUuid, DevOpsPlatformSettingNewValue::getKey,
DevOpsPlatformSettingNewValue::getProjectUuid, DevOpsPlatformSettingNewValue::getProjectKey,
DevOpsPlatformSettingNewValue::getProjectName)
.containsExactly(githubAlmSetting.getUuid(), githubAlmSetting.getKey(), project.getUuid(), project.getKey(), project.getName());
assertThat(newValue.toString()).doesNotContain("\"url\"");
AlmSettingDto anotherGithubAlmSetting = db.almSettings().insertGitHubAlmSetting();
system2.setNow(A_DATE_LATER);
ProjectAlmSettingDto newProjectAlmSettingDto = newGithubProjectAlmSettingDto(anotherGithubAlmSetting, project)
.setSummaryCommentEnabled(false);
underTest.insertOrUpdate(dbSession, newProjectAlmSettingDto, anotherGithubAlmSetting.getKey(), project.getName(), project.getKey());
verify(auditPersister).updateDevOpsPlatformSetting(eq(dbSession), newValueCaptor.capture());
newValue = newValueCaptor.getValue();
assertThat(newValue)
.extracting(DevOpsPlatformSettingNewValue::getDevOpsPlatformSettingUuid, DevOpsPlatformSettingNewValue::getKey,
DevOpsPlatformSettingNewValue::getProjectUuid, DevOpsPlatformSettingNewValue::getProjectName,
DevOpsPlatformSettingNewValue::getAlmRepo, DevOpsPlatformSettingNewValue::getAlmSlug,
DevOpsPlatformSettingNewValue::isSummaryCommentEnabled, DevOpsPlatformSettingNewValue::isMonorepo)
.containsExactly(anotherGithubAlmSetting.getUuid(), anotherGithubAlmSetting.getKey(), project.getUuid(), project.getName(),
newProjectAlmSettingDto.getAlmRepo(), newProjectAlmSettingDto.getAlmSlug(),
newProjectAlmSettingDto.getSummaryCommentEnabled(), newProjectAlmSettingDto.getMonorepo());
assertThat(newValue.toString()).doesNotContain("\"url\"");
}
@Test
public void deleteByProjectIsPersisted() {
AlmSettingDto githubAlmSetting = newGithubAlmSettingDto().setUuid(uuidFactory.create());
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
ProjectAlmSettingDto projectAlmSettingDto = newGithubProjectAlmSettingDto(githubAlmSetting, project)
.setSummaryCommentEnabled(false);
underTest.insertOrUpdate(dbSession, projectAlmSettingDto, githubAlmSetting.getKey(), project.getName(), project.getKey());
underTest.deleteByProject(dbSession, project);
verify(auditPersister).deleteDevOpsPlatformSetting(eq(dbSession), newValueCaptor.capture());
DevOpsPlatformSettingNewValue newValue = newValueCaptor.getValue();
assertThat(newValue)
.extracting(DevOpsPlatformSettingNewValue::getProjectUuid, DevOpsPlatformSettingNewValue::getProjectKey,
DevOpsPlatformSettingNewValue::getProjectName)
.containsExactly(project.getUuid(), project.getKey(), project.getName());
assertThat(newValue.toString()).doesNotContain("devOpsPlatformSettingUuid");
}
@Test
public void deleteByWithoutAffectedRowsProjectIsNotPersisted() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
underTest.deleteByProject(dbSession, project);
verify(auditPersister).addComponent(any(), any());
verifyNoMoreInteractions(auditPersister);
}
}
| 6,477 | 52.098361 | 140 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/audit/AuditDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.audit;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.core.util.UuidFactoryImpl;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.audit.AuditDao.EXCEEDED_LENGTH;
public class AuditDaoIT {
private static final long NOW = 1000000L;
private final TestSystem2 system2 = new TestSystem2().setNow(NOW);
@Rule
public final DbTester db = DbTester.create(system2);
private final DbSession dbSession = db.getSession();
private final AuditDao testAuditDao = new AuditDao(system2, UuidFactoryImpl.INSTANCE);
@Test
public void selectByPeriodPaginated_10001EntriesInserted_defaultPageSizeEntriesReturned() {
prepareRowsWithDeterministicCreatedAt(10001);
List<AuditDto> auditDtos = testAuditDao.selectByPeriodPaginated(dbSession, 1, 20000, 1);
assertThat(auditDtos).hasSize(10_000);
}
@Test
public void selectByPeriodPaginated_10001EntriesInserted_querySecondPageReturns1Item() {
prepareRowsWithDeterministicCreatedAt(10001);
List<AuditDto> auditDtos = testAuditDao.selectByPeriodPaginated(dbSession, 1, 20000, 2);
assertThat(auditDtos.size()).isOne();
}
@Test
public void purge_has_limit() {
prepareRowsWithDeterministicCreatedAt(100_001);
long purged = testAuditDao.deleteBefore(dbSession, 200_000);
assertThat(purged).isEqualTo(100_000);
assertThat(db.countRowsOfTable(dbSession, "audits")).isOne();
assertThat(testAuditDao.selectOlderThan(dbSession, 100_002))
.extracting(AuditDto::getCreatedAt)
.containsOnly(100_001L);
}
@Test
public void purge_with_threshold() {
prepareRowsWithDeterministicCreatedAt(100_000);
long purged = testAuditDao.deleteBefore(dbSession, 50_000);
assertThat(purged).isEqualTo(49_999);
assertThat(db.countRowsOfTable(dbSession, "audits")).isEqualTo(50_001);
assertThat(testAuditDao.selectOlderThan(dbSession, 100_000))
.hasSize(50_000)
.allMatch(a -> a.getCreatedAt() >= 50_000);
}
@Test
public void selectByPeriodPaginated_100EntriesInserted_100EntriesReturned() {
prepareRowsWithDeterministicCreatedAt(100);
List<AuditDto> auditDtos = testAuditDao.selectByPeriodPaginated(dbSession, 1, 101, 1);
assertThat(auditDtos).hasSize(100);
}
@Test
public void insert_doNotSetACreatedAtIfAlreadySet() {
AuditDto auditDto = AuditTesting.newAuditDto();
auditDto.setCreatedAt(1041375600000L);
testAuditDao.insert(dbSession, auditDto);
List<AuditDto> auditDtos = testAuditDao.selectByPeriodPaginated(dbSession, 1041375500000L, 1041375700000L, 1);
AuditDto storedAuditDto = auditDtos.get(0);
assertThat(storedAuditDto.getCreatedAt()).isEqualTo(auditDto.getCreatedAt());
}
@Test
public void insert_setACreatedAtIfAlreadySet() {
AuditDto auditDto = AuditTesting.newAuditDto();
auditDto.setCreatedAt(0);
testAuditDao.insert(dbSession, auditDto);
assertThat(auditDto.getCreatedAt()).isNotZero();
}
@Test
public void insert_doNotSetAUUIDIfAlreadySet() {
AuditDto auditDto = AuditTesting.newAuditDto();
auditDto.setUuid("myuuid");
auditDto.setCreatedAt(1041375600000L);
testAuditDao.insert(dbSession, auditDto);
List<AuditDto> auditDtos = testAuditDao.selectByPeriodPaginated(dbSession, 1041375500000L, 1041375700000L, 1);
AuditDto storedAuditDto = auditDtos.get(0);
assertThat(storedAuditDto.getUuid()).isEqualTo(auditDto.getUuid());
}
@Test
public void insert_truncateVeryLongNewValue() {
AuditDto auditDto = AuditTesting.newAuditDto();
String veryLongString = randomAlphanumeric(5000);
auditDto.setNewValue(veryLongString);
testAuditDao.insert(dbSession, auditDto);
assertThat(auditDto.getNewValue()).isEqualTo(EXCEEDED_LENGTH);
}
private void prepareRowsWithDeterministicCreatedAt(int size) {
for (int i = 1; i <= size; i++) {
AuditDto auditDto = AuditTesting.newAuditDto(i);
testAuditDao.insert(dbSession, auditDto);
}
}
}
| 5,052 | 33.609589 | 114 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/ce/CeActivityDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.ce;
import com.google.common.base.Function;
import com.google.common.base.Strings;
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.Optional;
import java.util.Random;
import java.util.stream.IntStream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.assertj.core.api.AbstractListAssert;
import org.assertj.core.api.ObjectAssert;
import org.assertj.core.groups.Tuple;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.core.util.CloseableIterator;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.Pagination;
import org.sonar.db.component.BranchDto;
import org.sonar.db.project.ProjectDto;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
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.tuple;
import static org.sonar.db.Pagination.forPage;
import static org.sonar.db.ce.CeActivityDto.Status.CANCELED;
import static org.sonar.db.ce.CeActivityDto.Status.FAILED;
import static org.sonar.db.ce.CeActivityDto.Status.SUCCESS;
import static org.sonar.db.ce.CeQueueDto.Status.PENDING;
import static org.sonar.db.ce.CeQueueTesting.makeInProgress;
import static org.sonar.db.ce.CeTaskTypes.REPORT;
@RunWith(DataProviderRunner.class)
public class CeActivityDaoIT {
private static final String ENTITY_1 = randomAlphabetic(12);
private static final String MAINCOMPONENT_2 = randomAlphabetic(13);
private static final String COMPONENT_1 = randomAlphabetic(14);
private static final long INITIAL_TIME = 1_450_000_000_000L;
private static final String NODE_NAME = "node1";
private final TestSystem2 system2 = new TestSystem2().setNow(INITIAL_TIME);
@Rule
public DbTester db = DbTester.create(system2);
private final DbSession dbSession = db.getSession();
private final CeActivityDao underTest = new CeActivityDao(system2);
@Before
public void setup() {
system2.setNow(INITIAL_TIME);
}
@Test
public void test_insert() {
CeActivityDto inserted = insert("TASK_1", REPORT, COMPONENT_1, ENTITY_1, SUCCESS);
Optional<CeActivityDto> saved = underTest.selectByUuid(db.getSession(), "TASK_1");
assertThat(saved).isPresent();
CeActivityDto dto = saved.get();
assertThat(dto.getUuid()).isEqualTo("TASK_1");
assertThat(dto.getNodeName()).isEqualTo(NODE_NAME);
assertThat(dto.getEntityUuid()).isEqualTo(ENTITY_1);
assertThat(dto.getComponentUuid()).isEqualTo(COMPONENT_1);
assertThat(dto.getStatus()).isEqualTo(SUCCESS);
assertThat(dto.getSubmitterUuid()).isEqualTo("submitter uuid");
assertThat(dto.getSubmittedAt()).isEqualTo(1_450_000_000_000L);
assertThat(dto.getWorkerUuid()).isEqualTo("worker uuid");
assertThat(dto.getIsLast()).isTrue();
assertThat(dto.getMainIsLast()).isTrue();
assertThat(dto.getIsLastKey()).isEqualTo("REPORT" + COMPONENT_1);
assertThat(dto.getMainIsLastKey()).isEqualTo("REPORT" + ENTITY_1);
assertThat(dto.getCreatedAt()).isEqualTo(INITIAL_TIME + 1);
assertThat(dto.getStartedAt()).isEqualTo(1_500_000_000_000L);
assertThat(dto.getExecutedAt()).isEqualTo(1_500_000_000_500L);
assertThat(dto.getExecutionTimeMs()).isEqualTo(500L);
assertThat(dto.getAnalysisUuid()).isEqualTo(inserted.getAnalysisUuid());
assertThat(dto.toString()).isNotEmpty();
assertThat(dto.getErrorMessage()).isNull();
assertThat(dto.getErrorStacktrace()).isNull();
assertThat(dto.getErrorType()).isNull();
assertThat(dto.isHasScannerContext()).isFalse();
assertThat(dto.getCeTaskMessageDtos()).isEmpty();
}
@Test
public void selectByUuid_populates_messages() {
CeActivityDto[] tasks = {
insert("TASK_1", REPORT, "PROJECT_1", SUCCESS),
insert("TASK_2", REPORT, "PROJECT_1", SUCCESS),
insert("TASK_3", REPORT, "PROJECT_1", SUCCESS)
};
List<CeTaskMessageDto> task1messages = insertCeTaskMessage(tasks[0], 4);
List<CeTaskMessageDto> task2messages = insertCeTaskMessage(tasks[1], 0);
List<CeTaskMessageDto> task3messages = insertCeTaskMessage(tasks[2], 1);
getCeActivityAndAssertMessages(tasks[0].getUuid(), task1messages);
getCeActivityAndAssertMessages(tasks[1].getUuid(), task2messages);
getCeActivityAndAssertMessages(tasks[2].getUuid(), task3messages);
}
private void getCeActivityAndAssertMessages(String taskUuid, List<CeTaskMessageDto> taskMessages) {
CeActivityDto ceActivityDto = underTest.selectByUuid(dbSession, taskUuid).orElseThrow();
assertThat(ceActivityDto.getCeTaskMessageDtos()).usingRecursiveFieldByFieldElementComparator().hasSameElementsAs(taskMessages);
}
private List<CeTaskMessageDto> insertCeTaskMessage(CeActivityDto task, int messagesCount) {
List<CeTaskMessageDto> ceTaskMessageDtos = IntStream.range(0, messagesCount)
.mapToObj(i -> createMessage(task, i))
.toList();
ceTaskMessageDtos.forEach(ceTaskMessageDto -> db.getDbClient().ceTaskMessageDao().insert(dbSession, ceTaskMessageDto));
db.commit();
return ceTaskMessageDtos;
}
private static CeTaskMessageDto createMessage(CeActivityDto task, int i) {
return new CeTaskMessageDto()
.setUuid(UuidFactoryFast.getInstance().create())
.setTaskUuid(task.getUuid())
.setMessage("message_" + task.getUuid() + "_" + i)
.setType(CeTaskMessageType.GENERIC)
.setCreatedAt(task.getUuid().hashCode() + i);
}
@Test
@UseDataProvider("notCanceledStatus")
public void insert_resets_is_last_and_main_is_last_fields_based_on_component_and_main_component(CeActivityDto.Status status) {
String project1 = randomAlphabetic(5);
String branch11 = randomAlphabetic(6);
String project2 = randomAlphabetic(8);
String branch21 = randomAlphabetic(9);
String type = randomAlphabetic(10);
String task1Project1 = insertAndCommit(newUuid(), type, project1, project1, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(true, true));
String task2Project1 = insertAndCommit(newUuid(), type, project1, project1, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Project1).containsOnly(tuple(true, true));
String task1Branch11 = insertAndCommit(newUuid(), type, branch11, project1, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Project1).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(task1Branch11).containsOnly(tuple(true, true));
String task2Branch11 = insertAndCommit(newUuid(), type, branch11, project1, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Project1).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(task1Branch11).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Branch11).containsOnly(tuple(true, true));
String task1Project2 = insertAndCommit(newUuid(), type, project2, project2, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Project1).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(task1Branch11).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Branch11).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(task1Project2).containsOnly(tuple(true, true));
String task2Project2 = insertAndCommit(newUuid(), type, project2, project2, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Project1).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(task1Branch11).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Branch11).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(task1Project2).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Project2).containsOnly(tuple(true, true));
String task1Branch21 = insertAndCommit(newUuid(), type, branch21, project2, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Project1).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(task1Branch11).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Branch11).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(task1Project2).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Project2).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(task1Branch21).containsOnly(tuple(true, true));
String task3project1 = insertAndCommit(newUuid(), type, project1, project1, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task1Branch11).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Branch11).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(task1Project2).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task2Project2).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(task1Branch21).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(task3project1).containsOnly(tuple(true, true));
}
@Test
@UseDataProvider("notCanceledStatus")
public void insert_resets_is_last_and_main_is_last_fields_based_on_type(CeActivityDto.Status status) {
String type1 = randomAlphabetic(10);
String type2 = randomAlphabetic(11);
String project = randomAlphabetic(5);
String branch = randomAlphabetic(6);
String type1Project1 = insertAndCommit(newUuid(), type1, project, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, true));
String type2Project1 = insertAndCommit(newUuid(), type2, project, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(type2Project1).containsOnly(tuple(true, true));
String type2Project2 = insertAndCommit(newUuid(), type2, project, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(type2Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(type2Project2).containsOnly(tuple(true, true));
String type1Branch1 = insertAndCommit(newUuid(), type1, branch, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(type2Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(type2Project2).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(type1Branch1).containsOnly(tuple(true, true));
String type2Branch1 = insertAndCommit(newUuid(), type2, branch, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(type2Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(type2Project2).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(type1Branch1).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(type2Branch1).containsOnly(tuple(true, true));
String type2Branch2 = insertAndCommit(newUuid(), type2, branch, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(type2Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(type2Project2).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(type1Branch1).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(type2Branch1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(type2Branch2).containsOnly(tuple(true, true));
}
@Test
@UseDataProvider("notCanceledStatus")
public void insert_resets_is_last_and_main_is_last_fields_based_on_component_or_not(CeActivityDto.Status status) {
String project = randomAlphabetic(5);
String type1 = randomAlphabetic(11);
String type2 = randomAlphabetic(11);
String type1Project1 = insertAndCommit(newUuid(), type1, project, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, true));
String type1NoProject1 = insertAndCommit(newUuid(), type1, null, null, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(type1NoProject1).containsOnly(tuple(true, true));
String type1NoProject2 = insertAndCommit(newUuid(), type1, null, null, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(type1NoProject1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(type1NoProject2).containsOnly(tuple(true, true));
String type2NoProject1 = insertAndCommit(newUuid(), type2, null, null, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(type1NoProject1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(type1NoProject2).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(type2NoProject1).containsOnly(tuple(true, true));
String type2NoProject2 = insertAndCommit(newUuid(), type2, null, null, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(type1NoProject1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(type1NoProject2).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(type2NoProject1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(type2NoProject2).containsOnly(tuple(true, true));
String type1Project2 = insertAndCommit(newUuid(), type1, project, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(type1NoProject1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(type1NoProject2).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(type2NoProject1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(type2NoProject2).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(type1Project2).containsOnly(tuple(true, true));
}
@Test
@UseDataProvider("notCanceledStatus")
public void insert_does_not_resets_is_last_and_main_is_last_fields_if_status_is_CANCELED(CeActivityDto.Status status) {
String project = randomAlphabetic(5);
String branch = randomAlphabetic(6);
String type = randomAlphabetic(10);
String task1Project1 = insertAndCommit(newUuid(), type, project, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(true, true));
String task1Project2 = insertAndCommit(newUuid(), type, project, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task1Project2).containsOnly(tuple(true, true));
String task1Project3 = insertAndCommit(newUuid(), type, project, project, CANCELED).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task1Project2).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(task1Project3).containsOnly(tuple(false, false));
String task1Branch1 = insertAndCommit(newUuid(), type, branch, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task1Project2).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(task1Project3).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task1Branch1).containsOnly(tuple(true, true));
String task1Branch2 = insertAndCommit(newUuid(), type, branch, project, CANCELED).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task1Project2).containsOnly(tuple(true, false));
assertIsLastAndMainIsLastFieldsOf(task1Project3).containsOnly(tuple(false, false));
assertIsLastAndMainIsLastFieldsOf(task1Branch1).containsOnly(tuple(true, true));
assertIsLastAndMainIsLastFieldsOf(task1Branch2).containsOnly(tuple(false, false));
}
@DataProvider
public static Object[][] notCanceledStatus() {
return Arrays.stream(CeActivityDto.Status.values())
.filter(t -> t != CANCELED)
.map(t -> new Object[] {t})
.toArray(Object[][]::new);
}
private AbstractListAssert<?, List<? extends Tuple>, Tuple, ObjectAssert<Tuple>> assertIsLastAndMainIsLastFieldsOf(String taskUuid) {
return assertThat(db.select("select is_last as \"IS_LAST\", main_is_last as \"MAIN_IS_LAST\" from ce_activity where uuid='" + taskUuid + "'"))
.extracting(t -> toBoolean(t.get("IS_LAST")), t -> toBoolean(t.get("MAIN_IS_LAST")));
}
private static boolean toBoolean(Object o) {
if (o instanceof Boolean) {
return (Boolean) o;
}
if (o instanceof Long) {
Long longBoolean = (Long) o;
return longBoolean.equals(1L);
}
throw new IllegalArgumentException("Unsupported object type returned for boolean: " + o.getClass());
}
@Test
public void test_insert_of_errorMessage_of_1_000_chars() {
CeActivityDto dto = createActivityDto("TASK_1", REPORT, COMPONENT_1, ENTITY_1, FAILED)
.setErrorMessage(Strings.repeat("x", 1_000));
underTest.insert(db.getSession(), dto);
Optional<CeActivityDto> saved = underTest.selectByUuid(db.getSession(), "TASK_1");
assertThat(saved.get().getErrorMessage()).isEqualTo(dto.getErrorMessage());
}
@Test
public void test_insert_of_errorMessage_of_1_001_chars_is_truncated_to_1000() {
String expected = Strings.repeat("x", 1_000);
CeActivityDto dto = createActivityDto("TASK_1", REPORT, COMPONENT_1, ENTITY_1, FAILED)
.setErrorMessage(expected + "y");
underTest.insert(db.getSession(), dto);
Optional<CeActivityDto> saved = underTest.selectByUuid(db.getSession(), "TASK_1");
assertThat(saved.get().getErrorMessage()).isEqualTo(expected);
}
@Test
public void test_insert_error_message_and_stacktrace() {
CeActivityDto dto = createActivityDto("TASK_1", REPORT, COMPONENT_1, ENTITY_1, FAILED)
.setErrorStacktrace("error stack");
underTest.insert(db.getSession(), dto);
Optional<CeActivityDto> saved = underTest.selectByUuid(db.getSession(), "TASK_1");
CeActivityDto read = saved.get();
assertThat(read.getErrorMessage()).isEqualTo(dto.getErrorMessage());
assertThat(read.getErrorStacktrace()).isEqualTo(dto.getErrorStacktrace());
assertThat(read.getErrorType()).isNotNull().isEqualTo(dto.getErrorType());
}
@Test
public void test_insert_error_message_only() {
CeActivityDto dto = createActivityDto("TASK_1", REPORT, COMPONENT_1, ENTITY_1, FAILED);
underTest.insert(db.getSession(), dto);
Optional<CeActivityDto> saved = underTest.selectByUuid(db.getSession(), "TASK_1");
CeActivityDto read = saved.get();
assertThat(read.getErrorMessage()).isEqualTo(read.getErrorMessage());
assertThat(read.getErrorStacktrace()).isNull();
}
@Test
public void insert_must_set_relevant_is_last_field() {
// only a single task on MAINCOMPONENT_1 -> is_last=true
insert("TASK_1", REPORT, ENTITY_1, SUCCESS);
assertThat(underTest.selectByUuid(db.getSession(), "TASK_1").get().getIsLast()).isTrue();
// only a single task on MAINCOMPONENT_2 -> is_last=true
insert("TASK_2", REPORT, MAINCOMPONENT_2, SUCCESS);
assertThat(underTest.selectByUuid(db.getSession(), "TASK_2").get().getIsLast()).isTrue();
// two tasks on MAINCOMPONENT_1, the most recent one is TASK_3
insert("TASK_3", REPORT, ENTITY_1, FAILED);
assertThat(underTest.selectByUuid(db.getSession(), "TASK_1").get().getIsLast()).isFalse();
assertThat(underTest.selectByUuid(db.getSession(), "TASK_2").get().getIsLast()).isTrue();
assertThat(underTest.selectByUuid(db.getSession(), "TASK_3").get().getIsLast()).isTrue();
// inserting a cancelled task does not change the last task
insert("TASK_4", REPORT, ENTITY_1, CANCELED);
assertThat(underTest.selectByUuid(db.getSession(), "TASK_1").get().getIsLast()).isFalse();
assertThat(underTest.selectByUuid(db.getSession(), "TASK_2").get().getIsLast()).isTrue();
assertThat(underTest.selectByUuid(db.getSession(), "TASK_3").get().getIsLast()).isTrue();
assertThat(underTest.selectByUuid(db.getSession(), "TASK_4").get().getIsLast()).isFalse();
}
@Test
public void test_selectByQuery() {
insert("TASK_1", REPORT, ENTITY_1, SUCCESS);
insert("TASK_2", REPORT, ENTITY_1, FAILED);
insert("TASK_3", REPORT, MAINCOMPONENT_2, SUCCESS);
insert("TASK_4", "views", null, SUCCESS);
// no filters
CeTaskQuery query = new CeTaskQuery().setStatuses(Collections.emptyList());
List<CeActivityDto> dtos = underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(10));
assertThat(dtos).extracting("uuid").containsExactly("TASK_4", "TASK_3", "TASK_2", "TASK_1");
// select by component uuid
query = new CeTaskQuery().setEntityUuid(ENTITY_1);
dtos = underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100));
assertThat(dtos).extracting("uuid").containsExactly("TASK_2", "TASK_1");
// select by status
query = new CeTaskQuery().setStatuses(singletonList(SUCCESS.name()));
dtos = underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100));
assertThat(dtos).extracting("uuid").containsExactly("TASK_4", "TASK_3", "TASK_1");
// select by type
query = new CeTaskQuery().setType(REPORT);
dtos = underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100));
assertThat(dtos).extracting("uuid").containsExactly("TASK_3", "TASK_2", "TASK_1");
query = new CeTaskQuery().setType("views");
dtos = underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100));
assertThat(dtos).extracting("uuid").containsExactly("TASK_4");
// select by multiple conditions
query = new CeTaskQuery().setType(REPORT).setOnlyCurrents(true).setEntityUuid(ENTITY_1);
dtos = underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100));
assertThat(dtos).extracting("uuid").containsExactly("TASK_2");
}
@Test
public void test_selectByQuery_verify_order_if_same_date() {
system2.setNow(INITIAL_TIME);
insert("TASK_1", REPORT, ENTITY_1, SUCCESS);
system2.setNow(INITIAL_TIME);
insert("TASK_2", REPORT, ENTITY_1, FAILED);
system2.setNow(INITIAL_TIME);
insert("TASK_3", REPORT, MAINCOMPONENT_2, SUCCESS);
system2.setNow(INITIAL_TIME);
insert("TASK_4", "views", null, SUCCESS);
// no filters
CeTaskQuery query = new CeTaskQuery().setStatuses(Collections.emptyList());
List<CeActivityDto> dtos = underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(10));
assertThat(dtos).extracting("uuid").containsExactly("TASK_4", "TASK_3", "TASK_2", "TASK_1");
// select by component uuid
query = new CeTaskQuery().setEntityUuid(ENTITY_1);
dtos = underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100));
assertThat(dtos).extracting("uuid").containsExactly("TASK_2", "TASK_1");
// select by status
query = new CeTaskQuery().setStatuses(singletonList(SUCCESS.name()));
dtos = underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100));
assertThat(dtos).extracting("uuid").containsExactly("TASK_4", "TASK_3", "TASK_1");
// select by type
query = new CeTaskQuery().setType(REPORT);
dtos = underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100));
assertThat(dtos).extracting("uuid").containsExactly("TASK_3", "TASK_2", "TASK_1");
query = new CeTaskQuery().setType("views");
dtos = underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100));
assertThat(dtos).extracting("uuid").containsExactly("TASK_4");
// select by multiple conditions
query = new CeTaskQuery().setType(REPORT).setOnlyCurrents(true).setEntityUuid(ENTITY_1);
dtos = underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100));
assertThat(dtos).extracting("uuid").containsExactly("TASK_2");
}
@Test
public void selectByQuery_does_not_populate_errorStacktrace_field() {
insert("TASK_1", REPORT, ENTITY_1, FAILED);
underTest.insert(db.getSession(), createActivityDto("TASK_2", REPORT, COMPONENT_1, ENTITY_1, FAILED).setErrorStacktrace("some stack"));
List<CeActivityDto> dtos = underTest.selectByQuery(db.getSession(), new CeTaskQuery().setEntityUuid(ENTITY_1), forPage(1).andSize(100));
assertThat(dtos)
.hasSize(2)
.extracting("errorStacktrace").containsOnly((String) null);
}
@Test
public void selectByQuery_populates_hasScannerContext_flag() {
insert("TASK_1", REPORT, ENTITY_1, SUCCESS);
CeActivityDto dto2 = insert("TASK_2", REPORT, MAINCOMPONENT_2, SUCCESS);
insertScannerContext(dto2.getUuid());
CeActivityDto dto = underTest.selectByQuery(db.getSession(), new CeTaskQuery().setEntityUuid(ENTITY_1), forPage(1).andSize(100)).iterator().next();
assertThat(dto.isHasScannerContext()).isFalse();
dto = underTest.selectByQuery(db.getSession(), new CeTaskQuery().setEntityUuid(MAINCOMPONENT_2), forPage(1).andSize(100)).iterator().next();
assertThat(dto.isHasScannerContext()).isTrue();
}
@Test
public void selectByQuery_populates_messages() {
CeActivityDto[] tasks = {
insert("TASK_1", REPORT, "PROJECT_1", SUCCESS),
insert("TASK_2", REPORT, "PROJECT_1", FAILED),
insert("TASK_3", REPORT, "PROJECT_2", SUCCESS),
insert("TASK_4", "views", null, SUCCESS)
};
int moreThan1 = 2 + new Random().nextInt(5);
insertCeTaskMessage(tasks[0], moreThan1);
insertCeTaskMessage(tasks[1], 30);
insertCeTaskMessage(tasks[2], 10);
insertCeTaskMessage(tasks[3], 60);
// no filters
CeTaskQuery query = new CeTaskQuery();
assertThat(underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(10)))
.extracting(CeActivityDto::getUuid, ceActivityDto -> ceActivityDto.getCeTaskMessageDtos().size())
.containsExactly(tuple("TASK_4", 60), tuple("TASK_3", 10), tuple("TASK_2", 30), tuple("TASK_1", moreThan1));
// select by component uuid
query = new CeTaskQuery().setEntityUuid("PROJECT_1");
assertThat(underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100)))
.extracting(CeActivityDto::getUuid, ceActivityDto -> ceActivityDto.getCeTaskMessageDtos().size())
.containsExactly(tuple("TASK_2", 30), tuple("TASK_1", moreThan1));
// select by status
query = new CeTaskQuery().setStatuses(singletonList(SUCCESS.name()));
assertThat(underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100)))
.extracting(CeActivityDto::getUuid, ceActivityDto -> ceActivityDto.getCeTaskMessageDtos().size())
.containsExactly(tuple("TASK_4", 60), tuple("TASK_3", 10), tuple("TASK_1", moreThan1));
// select by type
query = new CeTaskQuery().setType(REPORT);
assertThat(underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100)))
.extracting(CeActivityDto::getUuid, ceActivityDto -> ceActivityDto.getCeTaskMessageDtos().size())
.containsExactly(tuple("TASK_3", 10), tuple("TASK_2", 30), tuple("TASK_1", moreThan1));
query = new CeTaskQuery().setType("views");
assertThat(underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100)))
.extracting(CeActivityDto::getUuid, ceActivityDto -> ceActivityDto.getCeTaskMessageDtos().size())
.containsExactly(tuple("TASK_4", 60));
// select by multiple conditions
query = new CeTaskQuery().setType(REPORT).setOnlyCurrents(true).setEntityUuid("PROJECT_1");
assertThat(underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(100)))
.extracting(CeActivityDto::getUuid, ceActivityDto -> ceActivityDto.getCeTaskMessageDtos().size())
.containsExactly(tuple("TASK_2", 30));
}
@Test
public void selectByQuery_whenNoMessage_returnsEmptyList() {
insert("TASK_1", REPORT, "PROJECT_1", SUCCESS);
List<CeActivityDto> results = underTest.selectByQuery(db.getSession(), new CeTaskQuery(), Pagination.all());
assertThat(results)
.hasSize(1)
.extracting(CeActivityDto::getCeTaskMessageDtos)
.containsExactly(emptyList());
}
@Test
public void selectByQuery_is_paginated_and_return_results_sorted_from_last_to_first() {
insert("TASK_1", REPORT, ENTITY_1, SUCCESS);
insert("TASK_2", REPORT, ENTITY_1, FAILED);
insert("TASK_3", REPORT, MAINCOMPONENT_2, SUCCESS);
insert("TASK_4", "views", null, SUCCESS);
assertThat(selectPageOfUuids(forPage(1).andSize(1))).containsExactly("TASK_4");
assertThat(selectPageOfUuids(forPage(2).andSize(1))).containsExactly("TASK_3");
assertThat(selectPageOfUuids(forPage(1).andSize(3))).containsExactly("TASK_4", "TASK_3", "TASK_2");
assertThat(selectPageOfUuids(forPage(1).andSize(4))).containsExactly("TASK_4", "TASK_3", "TASK_2", "TASK_1");
assertThat(selectPageOfUuids(forPage(2).andSize(3))).containsExactly("TASK_1");
assertThat(selectPageOfUuids(forPage(1).andSize(100))).containsExactly("TASK_4", "TASK_3", "TASK_2", "TASK_1");
assertThat(selectPageOfUuids(forPage(5).andSize(2))).isEmpty();
}
@Test
public void selectByQuery_no_results_if_shortcircuited_by_component_uuids() {
insert("TASK_1", REPORT, ENTITY_1, SUCCESS);
CeTaskQuery query = new CeTaskQuery();
query.setEntityUuids(Collections.emptyList());
assertThat(underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(1))).isEmpty();
}
@Test
public void select_and_count_by_date() {
insertWithDates("UUID1", 1_450_000_000_000L, 1_470_000_000_000L);
insertWithDates("UUID2", 1_460_000_000_000L, 1_480_000_000_000L);
// search by min submitted date
CeTaskQuery query = new CeTaskQuery().setMinSubmittedAt(1_455_000_000_000L);
assertThat(underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(5))).extracting("uuid").containsOnly("UUID2");
// search by max executed date
query = new CeTaskQuery().setMaxExecutedAt(1_475_000_000_000L);
assertThat(underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(5))).extracting("uuid").containsOnly("UUID1");
// search by both dates
query = new CeTaskQuery()
.setMinSubmittedAt(1_400_000_000_000L)
.setMaxExecutedAt(1_475_000_000_000L);
assertThat(underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(5))).extracting("uuid").containsOnly("UUID1");
}
@Test
public void select_by_minExecutedAt() {
insertWithDates("UUID1", 1_450_000_000_000L, 1_470_000_000_000L);
insertWithDates("UUID2", 1_460_000_000_000L, 1_480_000_000_000L);
CeTaskQuery query = new CeTaskQuery().setMinExecutedAt(1_460_000_000_000L);
assertThat(underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(5))).extracting("uuid").containsExactlyInAnyOrder("UUID1", "UUID2");
query = new CeTaskQuery().setMinExecutedAt(1_475_000_000_000L);
assertThat(underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(5))).extracting("uuid").containsExactlyInAnyOrder("UUID2");
query = new CeTaskQuery().setMinExecutedAt(1_485_000_000_000L);
assertThat(underTest.selectByQuery(db.getSession(), query, forPage(1).andSize(5))).isEmpty();
}
private void insertWithDates(String uuid, long submittedAt, long executedAt) {
CeQueueDto queueDto = new CeQueueDto();
queueDto.setUuid(uuid);
queueDto.setTaskType("fake");
CeActivityDto dto = new CeActivityDto(queueDto);
dto.setStatus(SUCCESS);
dto.setSubmittedAt(submittedAt);
dto.setExecutedAt(executedAt);
underTest.insert(db.getSession(), dto);
}
@Test
public void selectOlderThan() {
insertWithCreationDate("TASK_1", 1_450_000_000_000L);
insertWithCreationDate("TASK_2", 1_460_000_000_000L);
insertWithCreationDate("TASK_3", 1_470_000_000_000L);
List<CeActivityDto> dtos = underTest.selectOlderThan(db.getSession(), 1_465_000_000_000L);
assertThat(dtos).extracting("uuid").containsOnly("TASK_1", "TASK_2");
}
@Test
public void selectNewerThan() {
insertWithCreationDate("TASK_1", 1_450_000_000_000L);
insertWithCreationDate("TASK_2", 1_460_000_000_000L);
insertWithCreationDate("TASK_3", 1_470_000_000_000L);
List<CeActivityDto> dtos = underTest.selectNewerThan(db.getSession(), 1_455_000_000_000L);
assertThat(dtos).extracting("uuid").containsOnly("TASK_2", "TASK_3");
}
@Test
public void selectOlder_populates_hasScannerContext_flag() {
insertWithCreationDate("TASK_1", 1_450_000_000_000L);
CeActivityDto dto2 = insertWithCreationDate("TASK_2", 1_450_000_000_000L);
insertScannerContext(dto2.getUuid());
List<CeActivityDto> dtos = underTest.selectOlderThan(db.getSession(), 1_465_000_000_000L);
assertThat(dtos).hasSize(2);
dtos.forEach((dto) -> assertThat(dto.isHasScannerContext()).isEqualTo(dto.getUuid().equals("TASK_2")));
}
@Test
public void selectOlderThan_does_not_populate_errorStacktrace() {
insert("TASK_1", REPORT, ENTITY_1, FAILED);
underTest.insert(db.getSession(), createActivityDto("TASK_2", REPORT, COMPONENT_1, ENTITY_1, FAILED).setErrorStacktrace("some stack"));
List<CeActivityDto> dtos = underTest.selectOlderThan(db.getSession(), system2.now() + 1_000_000L);
assertThat(dtos)
.hasSize(2)
.extracting("errorStacktrace").containsOnly((String) null);
}
@Test
public void selectOlderThan_populatesCorrectly() {
CeActivityDto activity1 = insert("TASK_1", REPORT, "PROJECT_1", FAILED);
insertCeTaskMessage(activity1, 10);
CeActivityDto activity2 = insert("TASK_2", REPORT, "PROJECT_1", SUCCESS);
insertCeTaskMessage(activity2, 1);
List<CeActivityDto> dtos = underTest.selectOlderThan(db.getSession(), system2.now() + 1_000_000L);
assertThat(dtos)
.hasSize(2)
.extracting(ceActivityDto -> ceActivityDto.getCeTaskMessageDtos().size())
.containsOnly(10, 1);
}
@Test
public void deleteByUuids() {
insert("TASK_1", "REPORT", ENTITY_1, SUCCESS);
insert("TASK_2", "REPORT", ENTITY_1, SUCCESS);
insert("TASK_3", "REPORT", ENTITY_1, SUCCESS);
underTest.deleteByUuids(db.getSession(), ImmutableSet.of("TASK_1", "TASK_3"));
assertThat(underTest.selectByUuid(db.getSession(), "TASK_1")).isEmpty();
assertThat(underTest.selectByUuid(db.getSession(), "TASK_2")).isPresent();
assertThat(underTest.selectByUuid(db.getSession(), "TASK_3")).isEmpty();
}
@Test
public void deleteByUuids_does_nothing_if_uuid_does_not_exist() {
insert("TASK_1", "REPORT", ENTITY_1, SUCCESS);
// must not fail
underTest.deleteByUuids(db.getSession(), singleton("TASK_2"));
assertThat(underTest.selectByUuid(db.getSession(), "TASK_1")).isPresent();
}
@Test
public void count_last_by_status_and_entity_uuid() {
insert("TASK_1", CeTaskTypes.REPORT, ENTITY_1, SUCCESS);
// component 2
insert("TASK_2", CeTaskTypes.REPORT, MAINCOMPONENT_2, SUCCESS);
// status failed
insert("TASK_3", CeTaskTypes.REPORT, ENTITY_1, FAILED);
// status canceled
insert("TASK_4", CeTaskTypes.REPORT, ENTITY_1, CANCELED);
insert("TASK_5", CeTaskTypes.REPORT, ENTITY_1, SUCCESS);
db.commit();
assertThat(underTest.countLastByStatusAndEntityUuid(dbSession, SUCCESS, ENTITY_1)).isOne();
assertThat(underTest.countLastByStatusAndEntityUuid(dbSession, SUCCESS, null)).isEqualTo(2);
}
@Test
public void selectLastByComponentUuidAndTaskType_returns_task_of_given_type() {
insert("TASK_1", "VIEW_REFRESH", ENTITY_1, ENTITY_1, SUCCESS);
insert("TASK_2", CeTaskTypes.REPORT, ENTITY_1, ENTITY_1, SUCCESS);
insert("TASK_3", "PROJECT_EXPORT", ENTITY_1, ENTITY_1, SUCCESS);
insert("TASK_4", "PROJECT_IMPORT", ENTITY_1, ENTITY_1, SUCCESS);
db.commit();
Optional<CeActivityDto> result = underTest.selectLastByComponentUuidAndTaskType(db.getSession(), ENTITY_1, "PROJECT_EXPORT");
assertThat(result).hasValueSatisfying(value -> assertThat(value.getUuid()).isEqualTo("TASK_3"));
}
@Test
public void selectLastByComponentUuidAndTaskType_returns_empty_if_task_of_given_type_does_not_exist() {
insert("TASK_1", CeTaskTypes.REPORT, ENTITY_1, SUCCESS);
db.commit();
Optional<CeActivityDto> result = underTest.selectLastByComponentUuidAndTaskType(db.getSession(), ENTITY_1, "PROJECT_EXPORT");
assertThat(result).isEmpty();
}
@Test
public void selectByTaskType() {
insert("TASK_1", CeTaskTypes.REPORT, ENTITY_1, SUCCESS);
insert("TASK_2", CeTaskTypes.BRANCH_ISSUE_SYNC, ENTITY_1, SUCCESS);
db.commit();
assertThat(underTest.selectByTaskType(db.getSession(), CeTaskTypes.REPORT))
.extracting("uuid")
.containsExactly("TASK_1");
assertThat(underTest.selectByTaskType(db.getSession(), CeTaskTypes.BRANCH_ISSUE_SYNC))
.extracting("uuid")
.containsExactly("TASK_2");
assertThat(underTest.selectByTaskType(db.getSession(), "unknown-type")).isEmpty();
}
@Test
public void hasAnyFailedOrCancelledIssueSyncTask() {
assertThat(underTest.hasAnyFailedOrCancelledIssueSyncTask(db.getSession())).isFalse();
insert("TASK_1", REPORT, ENTITY_1, SUCCESS);
insert("TASK_2", REPORT, ENTITY_1, FAILED);
ProjectDto projectDto1 = db.components().insertPrivateProject(
branchDto -> branchDto.setNeedIssueSync(false), c -> {
}, p -> {
}).getProjectDto();
insert("TASK_3", CeTaskTypes.BRANCH_ISSUE_SYNC, projectDto1.getUuid(), projectDto1.getUuid(), SUCCESS);
ProjectDto projectDto2 = db.components().insertPrivateProject(branchDto -> branchDto.setNeedIssueSync(false), c -> {
}, p -> {
}).getProjectDto();
insert("TASK_4", CeTaskTypes.BRANCH_ISSUE_SYNC, projectDto2.getUuid(), projectDto2.getUuid(), SUCCESS);
assertThat(underTest.hasAnyFailedOrCancelledIssueSyncTask(db.getSession())).isFalse();
ProjectDto projectDto3 = db.components().insertPrivateProject(branchDto -> branchDto.setNeedIssueSync(false), c -> {
}, p -> {
}).getProjectDto();
insert("TASK_5", CeTaskTypes.BRANCH_ISSUE_SYNC, projectDto3.getUuid(), projectDto3.getUuid(), SUCCESS);
BranchDto projectBranch1 = db.components()
.insertProjectBranch(projectDto3, branchDto -> branchDto.setNeedIssueSync(true));
insert("TASK_6", CeTaskTypes.BRANCH_ISSUE_SYNC, projectBranch1.getUuid(), projectDto3.getUuid(), FAILED);
BranchDto projectBranch2 = db.components()
.insertProjectBranch(projectDto3, branchDto -> branchDto.setNeedIssueSync(true));
insert("TASK_7", CeTaskTypes.BRANCH_ISSUE_SYNC, projectBranch2.getUuid(), projectDto3.getUuid(), CANCELED);
// failed task and project branch still exists and need sync
assertThat(underTest.hasAnyFailedOrCancelledIssueSyncTask(db.getSession())).isTrue();
// assume branch has been re-analysed
db.getDbClient().branchDao().updateNeedIssueSync(db.getSession(), projectBranch1.getUuid(), false);
// assume branch has been re-analysed
db.getDbClient().branchDao().updateNeedIssueSync(db.getSession(), projectBranch2.getUuid(), false);
assertThat(underTest.hasAnyFailedOrCancelledIssueSyncTask(db.getSession())).isFalse();
// assume branch has been deleted
db.getDbClient().purgeDao().deleteBranch(db.getSession(), projectBranch1.getUuid());
db.getDbClient().purgeDao().deleteBranch(db.getSession(), projectBranch2.getUuid());
// associated branch does not exist, so there is no failures - either it has been deleted or purged or reanalysed
assertThat(underTest.hasAnyFailedOrCancelledIssueSyncTask(db.getSession())).isFalse();
}
private CeActivityDto insert(String uuid, String type, @Nullable String mainComponentUuid, CeActivityDto.Status status) {
return insert(uuid, type, mainComponentUuid, mainComponentUuid, status);
}
private CeActivityDto insertAndCommit(String uuid, String type, @Nullable String componentUuid, @Nullable String entityUuid, CeActivityDto.Status status) {
CeActivityDto res = insert(uuid, type, componentUuid, entityUuid, status);
db.commit();
return res;
}
private CeActivityDto insert(String uuid, String type, @Nullable String componentUuid, @Nullable String entityUuid, CeActivityDto.Status status) {
CeActivityDto dto = createActivityDto(uuid, type, componentUuid, entityUuid, status);
system2.tick();
underTest.insert(db.getSession(), dto);
return dto;
}
private CeActivityDto createActivityDto(String uuid, String type, @Nullable String componentUuid, @Nullable String entityUuid, CeActivityDto.Status status) {
CeQueueDto creating = new CeQueueDto();
creating.setUuid(uuid);
creating.setStatus(PENDING);
creating.setTaskType(type);
creating.setComponentUuid(componentUuid);
creating.setEntityUuid(entityUuid);
creating.setSubmitterUuid("submitter uuid");
creating.setCreatedAt(system2.now());
db.getDbClient().ceQueueDao().insert(dbSession, creating);
makeInProgress(dbSession, "worker uuid", 1_400_000_000_000L, creating);
CeQueueDto ceQueueDto = db.getDbClient().ceQueueDao().selectByUuid(dbSession, uuid).get();
CeActivityDto dto = new CeActivityDto(ceQueueDto);
dto.setNodeName(NODE_NAME);
dto.setStatus(status);
dto.setStartedAt(1_500_000_000_000L);
dto.setExecutedAt(1_500_000_000_500L);
dto.setExecutionTimeMs(500L);
dto.setAnalysisUuid(uuid + "_2");
if (status == FAILED) {
dto.setErrorMessage("error msg for " + uuid);
dto.setErrorType("anErrorType");
}
return dto;
}
private CeActivityDto insertWithCreationDate(String uuid, long date) {
CeQueueDto queueDto = new CeQueueDto();
queueDto.setUuid(uuid);
queueDto.setTaskType("fake");
CeActivityDto dto = new CeActivityDto(queueDto);
dto.setStatus(SUCCESS);
dto.setAnalysisUuid(uuid + "_AA");
system2.setNow(date);
underTest.insert(db.getSession(), dto);
return dto;
}
private void insertScannerContext(String taskUuid) {
db.getDbClient().ceScannerContextDao().insert(dbSession, taskUuid, CloseableIterator.from(singletonList("scanner context of " + taskUuid).iterator()));
dbSession.commit();
}
private List<String> selectPageOfUuids(Pagination pagination) {
return underTest.selectByQuery(db.getSession(), new CeTaskQuery(), pagination).stream()
.map(CeActivityToUuid.INSTANCE::apply)
.toList();
}
private enum CeActivityToUuid implements Function<CeActivityDto, String> {
INSTANCE;
@Override
public String apply(@Nonnull CeActivityDto input) {
return input.getUuid();
}
}
private static String newUuid() {
return UuidFactoryFast.getInstance().create();
}
}
| 45,406 | 47.511752 | 159 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/ce/CeQueueDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.ce;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.function.Consumer;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import static com.google.common.collect.Lists.newArrayList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.db.ce.CeQueueDto.Status.IN_PROGRESS;
import static org.sonar.db.ce.CeQueueDto.Status.PENDING;
import static org.sonar.db.ce.CeQueueTesting.newCeQueueDto;
import static org.sonar.db.ce.CeQueueTesting.reset;
import static org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_KEY;
import static org.sonar.db.ce.CeTaskCharacteristicDto.PULL_REQUEST;
public class CeQueueDaoIT {
private static final long INIT_TIME = 1_450_000_000_000L;
private static final String TASK_UUID_1 = "TASK_1";
private static final String TASK_UUID_2 = "TASK_2";
private static final String ENTITY_UUID_1 = "PROJECT_1";
private static final String ENTITY_UUID_2 = "PROJECT_2";
private static final String COMPONENT_UUID_1 = "BRANCH_1";
private static final String TASK_UUID_3 = "TASK_3";
private static final String SELECT_QUEUE_UUID_AND_STATUS_QUERY = "select uuid,status from ce_queue";
private static final String SUBMITTER_LOGIN = "submitter uuid";
private static final String WORKER_UUID_1 = "worker uuid 1";
private static final String WORKER_UUID_2 = "worker uuid 2";
private final TestSystem2 system2 = new TestSystem2().setNow(INIT_TIME);
@Rule
public DbTester db = DbTester.create(system2);
private final System2 mockedSystem2 = mock(System2.class);
private final System2 alwaysIncreasingSystem2 = new AlwaysIncreasingSystem2();
private final CeQueueDao underTest = new CeQueueDao(system2);
private final CeQueueDao underTestWithSystem2Mock = new CeQueueDao(mockedSystem2);
private final CeQueueDao underTestAlwaysIncreasingSystem2 = new CeQueueDao(alwaysIncreasingSystem2);
@Test
public void insert_populates_createdAt_and_updateAt_from_System2_with_same_value_if_any_is_not_set() {
long now = 1_334_333L;
CeQueueDto dto = new CeQueueDto()
.setTaskType(CeTaskTypes.REPORT)
.setComponentUuid(ENTITY_UUID_1)
.setStatus(PENDING)
.setSubmitterUuid(SUBMITTER_LOGIN);
mockSystem2ForSingleCall(now);
underTestWithSystem2Mock.insert(db.getSession(), dto.setUuid(TASK_UUID_1));
mockSystem2ForSingleCall(now);
underTestWithSystem2Mock.insert(db.getSession(), dto.setUuid(TASK_UUID_2).setCreatedAt(8_000_999L).setUpdatedAt(0));
mockSystem2ForSingleCall(now);
underTestWithSystem2Mock.insert(db.getSession(), dto.setUuid(TASK_UUID_3).setCreatedAt(0).setUpdatedAt(8_000_999L));
mockSystem2ForSingleCall(now);
String uuid4 = "uuid 4";
underTestWithSystem2Mock.insert(db.getSession(), dto.setUuid(uuid4).setCreatedAt(6_888_777L).setUpdatedAt(8_000_999L));
db.getSession().commit();
Stream.of(TASK_UUID_1, TASK_UUID_2, TASK_UUID_3)
.forEach(uuid -> {
CeQueueDto saved = underTest.selectByUuid(db.getSession(), uuid).get();
assertThat(saved.getUuid()).isEqualTo(uuid);
assertThat(saved.getTaskType()).isEqualTo(CeTaskTypes.REPORT);
assertThat(saved.getComponentUuid()).isEqualTo(ENTITY_UUID_1);
assertThat(saved.getStatus()).isEqualTo(PENDING);
assertThat(saved.getSubmitterUuid()).isEqualTo(SUBMITTER_LOGIN);
assertThat(saved.getWorkerUuid()).isNull();
assertThat(saved.getCreatedAt()).isEqualTo(now);
assertThat(saved.getUpdatedAt()).isEqualTo(now);
assertThat(saved.getStartedAt()).isNull();
});
CeQueueDto saved = underTest.selectByUuid(db.getSession(), uuid4).get();
assertThat(saved.getUuid()).isEqualTo(uuid4);
assertThat(saved.getTaskType()).isEqualTo(CeTaskTypes.REPORT);
assertThat(saved.getComponentUuid()).isEqualTo(ENTITY_UUID_1);
assertThat(saved.getStatus()).isEqualTo(PENDING);
assertThat(saved.getSubmitterUuid()).isEqualTo(SUBMITTER_LOGIN);
assertThat(saved.getWorkerUuid()).isNull();
assertThat(saved.getCreatedAt()).isEqualTo(6_888_777L);
assertThat(saved.getUpdatedAt()).isEqualTo(8_000_999L);
assertThat(saved.getStartedAt()).isNull();
}
@Test
public void test_selectByUuid() {
CeQueueDto ceQueueDto = insertPending(TASK_UUID_1, ENTITY_UUID_1);
assertThat(underTest.selectByUuid(db.getSession(), "TASK_UNKNOWN")).isEmpty();
CeQueueDto saved = underTest.selectByUuid(db.getSession(), TASK_UUID_1).get();
assertThat(saved.getUuid()).isEqualTo(TASK_UUID_1);
assertThat(saved.getTaskType()).isEqualTo(CeTaskTypes.REPORT);
assertThat(saved.getEntityUuid()).isEqualTo(ENTITY_UUID_1);
assertThat(saved.getComponentUuid()).isEqualTo(ceQueueDto.getComponentUuid());
assertThat(saved.getStatus()).isEqualTo(PENDING);
assertThat(saved.getSubmitterUuid()).isEqualTo("henri");
assertThat(saved.getWorkerUuid()).isNull();
assertThat(saved.getCreatedAt()).isEqualTo(INIT_TIME);
assertThat(saved.getUpdatedAt()).isEqualTo(INIT_TIME);
assertThat(saved.getStartedAt()).isNull();
}
@Test
public void test_selectByMainComponentUuid() {
insertPending(TASK_UUID_1, ENTITY_UUID_1);
insertPending(TASK_UUID_2, ENTITY_UUID_1);
insertPending(TASK_UUID_3, "PROJECT_2");
assertThat(underTest.selectByEntityUuid(db.getSession(), "UNKNOWN")).isEmpty();
assertThat(underTest.selectByEntityUuid(db.getSession(), ENTITY_UUID_1)).extracting("uuid").containsOnly(TASK_UUID_1, TASK_UUID_2);
assertThat(underTest.selectByEntityUuid(db.getSession(), "PROJECT_2")).extracting("uuid").containsOnly(TASK_UUID_3);
}
@Test
public void test_selectAllInAscOrder() {
insertPending(TASK_UUID_1, ENTITY_UUID_1);
insertPending(TASK_UUID_2, ENTITY_UUID_1);
insertPending(TASK_UUID_3, "PROJECT_2");
assertThat(underTest.selectAllInAscOrder(db.getSession())).extracting("uuid").containsOnly(TASK_UUID_1, TASK_UUID_2, TASK_UUID_3);
}
@Test
public void selectPending_returns_pending_tasks() {
insertPending("p1");
insertPending("p2");
insertPending("p3");
makeInProgress("w1", alwaysIncreasingSystem2.now(), insertPending("i1"));
makeInProgress("w1", alwaysIncreasingSystem2.now(), insertPending("i2"));
makeInProgress("w1", alwaysIncreasingSystem2.now(), insertPending("i3"));
assertThat(underTest.selectPending(db.getSession()))
.extracting(CeQueueDto::getUuid)
.containsOnly("p1", "p2", "p3");
}
@Test
public void selectCreationDateOfOldestPendingByMainComponentUuid_on_any_component_returns_date() {
long time = alwaysIncreasingSystem2.now() + 10_000;
insertPending("p1", dto -> {
dto.setCreatedAt(time);
dto.setUpdatedAt(time + 500);
dto.setEntityUuid("c1");
});
insertPending("p2", dto -> {
dto.setCreatedAt(time + 1000);
dto.setUpdatedAt(time + 2000);
dto.setEntityUuid("c2");
});
makeInProgress("w1", alwaysIncreasingSystem2.now(), insertPending("i1", dto -> dto.setEntityUuid("c3")));
assertThat(underTest.selectCreationDateOfOldestPendingByEntityUuid(db.getSession(), null))
.isEqualTo(Optional.of(time));
}
@Test
public void selectCreationDateOfOldestPendingByMainComponentUuid_on_specific_component_returns_date() {
long time = alwaysIncreasingSystem2.now() + 10_000;
insertPending("p1", dto -> {
dto.setCreatedAt(time);
dto.setUpdatedAt(time + 500);
dto.setEntityUuid("c2");
});
insertPending("p2", dto -> {
dto.setCreatedAt(time + 2000);
dto.setUpdatedAt(time + 3000);
dto.setEntityUuid("c1");
});
insertPending("p3", dto -> {
dto.setCreatedAt(time + 4000);
dto.setUpdatedAt(time + 5000);
dto.setEntityUuid("c1");
});
makeInProgress("w1", alwaysIncreasingSystem2.now(), insertPending("i1", dto -> dto.setEntityUuid("c1")));
assertThat(underTest.selectCreationDateOfOldestPendingByEntityUuid(db.getSession(), "c1"))
.isEqualTo(Optional.of(time + 2000));
}
@Test
public void selectCreationDateOfOldestPendingByMainComponentUuid_returns_empty_when_no_pending_tasks() {
makeInProgress("w1", alwaysIncreasingSystem2.now(), insertPending("i1"));
assertThat(underTest.selectCreationDateOfOldestPendingByEntityUuid(db.getSession(), null))
.isEmpty();
}
@Test
public void selectWornout_returns_task_pending_with_a_non_null_startedAt() {
insertPending("p1");
makeInProgress("w1", alwaysIncreasingSystem2.now(), insertPending("i1"));
CeQueueDto resetDto = makeInProgress("w1", alwaysIncreasingSystem2.now(), insertPending("i2"));
makeInProgress("w1", alwaysIncreasingSystem2.now(), insertPending("i3"));
reset(db.getSession(), alwaysIncreasingSystem2.now(), resetDto);
List<CeQueueDto> ceQueueDtos = underTest.selectWornout(db.getSession());
assertThat(ceQueueDtos)
.extracting(CeQueueDto::getStatus, CeQueueDto::getUuid)
.containsOnly(tuple(PENDING, resetDto.getUuid()));
}
@Test
public void test_delete() {
insertPending(TASK_UUID_1, ENTITY_UUID_1);
insertPending(TASK_UUID_2, ENTITY_UUID_1);
int deletedCount = underTest.deleteByUuid(db.getSession(), "UNKNOWN");
assertThat(deletedCount).isZero();
assertThat(underTest.selectByUuid(db.getSession(), TASK_UUID_1)).isPresent();
deletedCount = underTest.deleteByUuid(db.getSession(), TASK_UUID_1);
assertThat(deletedCount).isOne();
assertThat(underTest.selectByUuid(db.getSession(), TASK_UUID_1)).isEmpty();
deletedCount = underTest.deleteByUuid(db.getSession(), TASK_UUID_2, null);
assertThat(deletedCount).isOne();
assertThat(underTest.selectByUuid(db.getSession(), TASK_UUID_2)).isEmpty();
}
@Test
public void test_delete_with_expected_status() {
insertPending(TASK_UUID_1, ENTITY_UUID_1);
insertInProgress(TASK_UUID_2, "workerUuid", System2.INSTANCE.now());
int deletedCount = underTest.deleteByUuid(db.getSession(), "UNKNOWN", null);
assertThat(deletedCount).isZero();
assertThat(underTest.selectByUuid(db.getSession(), TASK_UUID_1)).isPresent();
deletedCount = underTest.deleteByUuid(db.getSession(), TASK_UUID_1, new DeleteIf(IN_PROGRESS));
assertThat(deletedCount).isZero();
assertThat(underTest.selectByUuid(db.getSession(), TASK_UUID_1)).isPresent();
deletedCount = underTest.deleteByUuid(db.getSession(), TASK_UUID_2, new DeleteIf(PENDING));
assertThat(deletedCount).isZero();
assertThat(underTest.selectByUuid(db.getSession(), TASK_UUID_2)).isPresent();
deletedCount = underTest.deleteByUuid(db.getSession(), TASK_UUID_1, new DeleteIf(PENDING));
assertThat(deletedCount).isOne();
assertThat(underTest.selectByUuid(db.getSession(), TASK_UUID_1)).isEmpty();
deletedCount = underTest.deleteByUuid(db.getSession(), TASK_UUID_2, new DeleteIf(IN_PROGRESS));
assertThat(deletedCount).isOne();
assertThat(underTest.selectByUuid(db.getSession(), TASK_UUID_2)).isEmpty();
}
@Test
public void selectNotPendingForWorker_return_non_pending_tasks_for_specified_workerUuid() {
long startedAt = alwaysIncreasingSystem2.now();
insertPending("u1");
CeQueueDto inProgressTaskWorker1 = insertInProgress("u2", WORKER_UUID_1, startedAt);
insertInProgress("o2", WORKER_UUID_2, startedAt);
List<CeQueueDto> notPendingForWorker = underTestAlwaysIncreasingSystem2.selectNotPendingForWorker(db.getSession(), WORKER_UUID_1);
assertThat(notPendingForWorker).extracting(CeQueueDto::getUuid)
.contains(inProgressTaskWorker1.getUuid());
}
@Test
public void resetToPendingByUuid_resets_status_of_specific_task() {
long task1startedAt = alwaysIncreasingSystem2.now();
CeQueueDto task1 = insertInProgress("uuid-1", "workerUuid", task1startedAt);
CeQueueDto task2 = insertInProgress("uuid-2", "workerUuid", alwaysIncreasingSystem2.now());
underTestAlwaysIncreasingSystem2.resetToPendingByUuid(db.getSession(), task1.getUuid());
verifyResetToPendingForWorker(task1, task1.getWorkerUuid(), task1startedAt);
verifyUnchangedByResetToPendingForWorker(task2);
}
@Test
public void resetToPendingForWorker_resets_status_of_non_pending_tasks_only_for_specified_workerUuid() {
CeQueueDto[] worker1 = {insertPending("u1"), insertPending("u2"), insertPending("u3"), insertPending("u4")};
CeQueueDto[] worker2 = {insertPending("o1"), insertPending("o2"), insertPending("o3"), insertPending("o4")};
long startedAt = alwaysIncreasingSystem2.now();
makeInProgress(WORKER_UUID_1, startedAt, worker1[0]);
makeInProgress(WORKER_UUID_1, startedAt, worker1[3]);
makeInProgress(WORKER_UUID_2, startedAt, worker2[0]);
makeInProgress(WORKER_UUID_2, startedAt, worker2[3]);
List<CeQueueDto> notPendingForWorker = underTestAlwaysIncreasingSystem2.selectNotPendingForWorker(db.getSession(), WORKER_UUID_1);
for (CeQueueDto ceQueueDto : notPendingForWorker) {
underTestAlwaysIncreasingSystem2.resetToPendingByUuid(db.getSession(), ceQueueDto.getUuid());
}
verifyResetToPendingForWorker(worker1[0], WORKER_UUID_1, startedAt);
verifyUnchangedByResetToPendingForWorker(worker1[1]);
verifyUnchangedByResetToPendingForWorker(worker1[2]);
verifyResetToPendingForWorker(worker1[3], WORKER_UUID_1, startedAt);
verifyInProgressUnchangedByResetToPendingForWorker(worker2[0], WORKER_UUID_2, startedAt);
verifyUnchangedByResetToPendingForWorker(worker2[1]);
verifyUnchangedByResetToPendingForWorker(worker2[2]);
verifyInProgressUnchangedByResetToPendingForWorker(worker2[3], WORKER_UUID_2, startedAt);
}
@Test
public void resetTasksWithUnknownWorkerUUIDs_with_empty_set_resets_status_of_all_pending_tasks() {
CeQueueDto[] worker1 = {insertPending("u1"), insertPending("u2"), insertPending("u3"), insertPending("u4")};
CeQueueDto[] worker2 = {insertPending("o1"), insertPending("o2"), insertPending("o3"), insertPending("o4")};
long startedAt = alwaysIncreasingSystem2.now();
makeInProgress(WORKER_UUID_1, startedAt, worker1[0]);
makeInProgress(WORKER_UUID_1, startedAt, worker1[3]);
makeInProgress(WORKER_UUID_2, startedAt, worker2[0]);
makeInProgress(WORKER_UUID_2, startedAt, worker2[3]);
underTestAlwaysIncreasingSystem2.resetTasksWithUnknownWorkerUUIDs(db.getSession(), ImmutableSet.of());
verifyResetByResetTasks(worker1[0], startedAt);
verifyUnchangedByResetToPendingForWorker(worker1[1]);
verifyUnchangedByResetToPendingForWorker(worker1[2]);
verifyResetByResetTasks(worker1[3], startedAt);
verifyResetByResetTasks(worker2[0], startedAt);
verifyUnchangedByResetToPendingForWorker(worker2[1]);
verifyUnchangedByResetToPendingForWorker(worker2[2]);
verifyResetByResetTasks(worker2[3], startedAt);
}
@Test
public void resetTasksWithUnknownWorkerUUIDs_set_resets_status_of_all_pending_tasks_with_unknown_workers() {
CeQueueDto[] worker1 = {insertPending("u1"), insertPending("u2"), insertPending("u3"), insertPending("u4")};
CeQueueDto[] worker2 = {insertPending("o1"), insertPending("o2"), insertPending("o3"), insertPending("o4")};
long startedAt = alwaysIncreasingSystem2.now();
makeInProgress(WORKER_UUID_1, startedAt, worker1[0]);
makeInProgress(WORKER_UUID_1, startedAt, worker1[3]);
makeInProgress(WORKER_UUID_2, startedAt, worker2[0]);
makeInProgress(WORKER_UUID_2, startedAt, worker2[3]);
underTestAlwaysIncreasingSystem2.resetTasksWithUnknownWorkerUUIDs(db.getSession(), ImmutableSet.of(WORKER_UUID_1, "unknown"));
verifyInProgressUnchangedByResetToPendingForWorker(worker1[0], WORKER_UUID_1, startedAt);
verifyUnchangedByResetToPendingForWorker(worker1[1]);
verifyUnchangedByResetToPendingForWorker(worker1[2]);
verifyInProgressUnchangedByResetToPendingForWorker(worker1[3], WORKER_UUID_1, startedAt);
verifyResetByResetTasks(worker2[0], startedAt);
verifyUnchangedByResetToPendingForWorker(worker2[1]);
verifyUnchangedByResetToPendingForWorker(worker2[2]);
verifyResetByResetTasks(worker2[3], startedAt);
}
private CeQueueDto makeInProgress(String workerUuid, long startedAt, CeQueueDto ceQueueDto) {
CeQueueTesting.makeInProgress(db.getSession(), workerUuid, startedAt, ceQueueDto);
return underTestAlwaysIncreasingSystem2.selectByUuid(db.getSession(), ceQueueDto.getUuid()).get();
}
private void verifyResetByResetTasks(CeQueueDto original, long startedAt) {
CeQueueDto dto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), original.getUuid()).get();
assertThat(dto.getStatus()).isEqualTo(PENDING);
assertThat(dto.getStartedAt()).isEqualTo(startedAt);
assertThat(dto.getCreatedAt()).isEqualTo(original.getCreatedAt());
assertThat(dto.getUpdatedAt()).isGreaterThan(startedAt);
assertThat(dto.getWorkerUuid()).isNull();
}
private void verifyResetToPendingForWorker(CeQueueDto original, String workerUuid, long startedAt) {
CeQueueDto dto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), original.getUuid()).get();
assertThat(dto.getStatus()).isEqualTo(PENDING);
assertThat(dto.getStartedAt()).isEqualTo(startedAt);
assertThat(dto.getCreatedAt()).isEqualTo(original.getCreatedAt());
assertThat(dto.getUpdatedAt()).isGreaterThan(startedAt);
assertThat(dto.getWorkerUuid()).isEqualTo(workerUuid);
}
private void verifyUnchangedByResetToPendingForWorker(CeQueueDto original) {
CeQueueDto dto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), original.getUuid()).get();
assertThat(dto.getStatus()).isEqualTo(original.getStatus());
assertThat(dto.getStartedAt()).isEqualTo(original.getStartedAt());
assertThat(dto.getCreatedAt()).isEqualTo(original.getCreatedAt());
assertThat(dto.getUpdatedAt()).isEqualTo(original.getUpdatedAt());
assertThat(dto.getWorkerUuid()).isEqualTo(original.getWorkerUuid());
}
private void verifyInProgressUnchangedByResetToPendingForWorker(CeQueueDto original, String workerUuid, long startedAt) {
CeQueueDto dto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), original.getUuid()).get();
assertThat(dto.getStatus()).isEqualTo(IN_PROGRESS);
assertThat(dto.getStartedAt()).isEqualTo(startedAt);
assertThat(dto.getCreatedAt()).isEqualTo(original.getCreatedAt());
assertThat(dto.getUpdatedAt()).isEqualTo(startedAt);
assertThat(dto.getWorkerUuid()).isEqualTo(workerUuid);
}
@Test
public void select_by_query() {
// task status not in query
insertPending(newCeQueueDto(TASK_UUID_1)
.setEntityUuid(ENTITY_UUID_1)
.setStatus(IN_PROGRESS)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(100_000L));
// too early
insertPending(newCeQueueDto(TASK_UUID_3)
.setEntityUuid(ENTITY_UUID_1)
.setStatus(PENDING)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(90_000L));
// task type not in query
insertPending(newCeQueueDto("TASK_4")
.setEntityUuid("PROJECT_2")
.setStatus(PENDING)
.setTaskType("ANOTHER_TYPE")
.setCreatedAt(100_000L));
// correct
insertPending(newCeQueueDto(TASK_UUID_2)
.setEntityUuid(ENTITY_UUID_1)
.setStatus(PENDING)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(100_000L));
// correct submitted later
insertPending(newCeQueueDto("TASK_5")
.setEntityUuid(ENTITY_UUID_1)
.setStatus(PENDING)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(120_000L));
// select by component uuid, status, task type and minimum submitted at
CeTaskQuery query = new CeTaskQuery()
.setEntityUuids(newArrayList(ENTITY_UUID_1, "PROJECT_2"))
.setStatuses(singletonList(PENDING.name()))
.setType(CeTaskTypes.REPORT)
.setMinSubmittedAt(100_000L);
List<CeQueueDto> result = underTest.selectByQueryInDescOrder(db.getSession(), query, 1_000);
int total = underTest.countByQuery(db.getSession(), query);
assertThat(result).extracting("uuid").containsExactly("TASK_5", TASK_UUID_2);
assertThat(total).isEqualTo(2);
}
@Test
public void select_by_query_returns_empty_list_when_only_current() {
insertPending(newCeQueueDto(TASK_UUID_1)
.setComponentUuid(ENTITY_UUID_1)
.setStatus(IN_PROGRESS)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(100_000L));
CeTaskQuery query = new CeTaskQuery().setOnlyCurrents(true);
List<CeQueueDto> result = underTest.selectByQueryInDescOrder(db.getSession(), query, 1_000);
int total = underTest.countByQuery(db.getSession(), query);
assertThat(result).isEmpty();
assertThat(total).isZero();
}
@Test
public void select_by_query_returns_empty_list_when_max_submitted_at() {
insertPending(newCeQueueDto(TASK_UUID_1)
.setComponentUuid(ENTITY_UUID_1)
.setStatus(IN_PROGRESS)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(100_000L));
CeTaskQuery query = new CeTaskQuery().setMaxExecutedAt(1_000_000_000_000L);
List<CeQueueDto> result = underTest.selectByQueryInDescOrder(db.getSession(), query, 1_000);
int total = underTest.countByQuery(db.getSession(), query);
assertThat(result).isEmpty();
assertThat(total).isZero();
}
@Test
public void select_by_query_returns_empty_list_when_empty_list_of_entity_uuid() {
insertPending(newCeQueueDto(TASK_UUID_1)
.setComponentUuid(ENTITY_UUID_1)
.setStatus(IN_PROGRESS)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(100_000L));
CeTaskQuery query = new CeTaskQuery().setEntityUuids(Collections.emptyList());
List<CeQueueDto> result = underTest.selectByQueryInDescOrder(db.getSession(), query, 1_000);
int total = underTest.countByQuery(db.getSession(), query);
assertThat(result).isEmpty();
assertThat(total).isZero();
}
@Test
public void count_by_status_and_entity_uuid() {
// task retrieved in the queue
insertPending(newCeQueueDto(TASK_UUID_1)
.setEntityUuid(ENTITY_UUID_1)
.setStatus(IN_PROGRESS)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(100_000L));
// on component uuid 2, not returned
insertPending(newCeQueueDto(TASK_UUID_2)
.setEntityUuid(ENTITY_UUID_2)
.setStatus(IN_PROGRESS)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(100_000L));
// pending status, not returned
insertPending(newCeQueueDto(TASK_UUID_3)
.setEntityUuid(ENTITY_UUID_1)
.setStatus(PENDING)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(100_000L));
assertThat(underTest.countByStatusAndEntityUuid(db.getSession(), IN_PROGRESS, ENTITY_UUID_1)).isOne();
assertThat(underTest.countByStatus(db.getSession(), IN_PROGRESS)).isEqualTo(2);
}
@Test
public void count_by_status_and_entity_uuids() {
// task retrieved in the queue
insertPending(newCeQueueDto(TASK_UUID_1)
.setEntityUuid(ENTITY_UUID_1)
.setStatus(IN_PROGRESS)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(100_000L));
// on component uuid 2, not returned
insertPending(newCeQueueDto(TASK_UUID_2)
.setEntityUuid(ENTITY_UUID_2)
.setStatus(IN_PROGRESS)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(100_000L));
// pending status, not returned
insertPending(newCeQueueDto(TASK_UUID_3)
.setEntityUuid(ENTITY_UUID_1)
.setStatus(PENDING)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(100_000L));
assertThat(underTest.countByStatusAndEntityUuids(db.getSession(), IN_PROGRESS, ImmutableSet.of())).isEmpty();
assertThat(underTest.countByStatusAndEntityUuids(db.getSession(), IN_PROGRESS, ImmutableSet.of("non existing component uuid"))).isEmpty();
assertThat(underTest.countByStatusAndEntityUuids(db.getSession(), IN_PROGRESS, ImmutableSet.of(ENTITY_UUID_1, ENTITY_UUID_2)))
.containsOnly(entry(ENTITY_UUID_1, 1), entry(ENTITY_UUID_2, 1));
assertThat(underTest.countByStatusAndEntityUuids(db.getSession(), PENDING, ImmutableSet.of(ENTITY_UUID_1, ENTITY_UUID_2)))
.containsOnly(entry(ENTITY_UUID_1, 1));
assertThat(underTest.countByStatus(db.getSession(), IN_PROGRESS)).isEqualTo(2);
}
@Test
public void selectInProgressStartedBefore() {
// pending task is ignored
insertPending(newCeQueueDto(TASK_UUID_1)
.setStatus(PENDING)
.setStartedAt(1_000L));
// in-progress tasks
insertPending(newCeQueueDto(TASK_UUID_2)
.setStatus(IN_PROGRESS)
.setStartedAt(1_000L));
insertPending(newCeQueueDto(TASK_UUID_3)
.setStatus(IN_PROGRESS)
.setStartedAt(2_000L));
assertThat(underTest.selectInProgressStartedBefore(db.getSession(), 500L)).isEmpty();
assertThat(underTest.selectInProgressStartedBefore(db.getSession(), 1_000L)).isEmpty();
assertThat(underTest.selectInProgressStartedBefore(db.getSession(), 1_500L)).extracting(CeQueueDto::getUuid).containsExactly(TASK_UUID_2);
assertThat(underTest.selectInProgressStartedBefore(db.getSession(), 3_000L)).extracting(CeQueueDto::getUuid).containsExactlyInAnyOrder(TASK_UUID_2, TASK_UUID_3);
}
@Test
public void hasAnyIssueSyncTaskPendingOrInProgress_PENDING() {
assertThat(underTest.hasAnyIssueSyncTaskPendingOrInProgress(db.getSession())).isFalse();
insertPending(newCeQueueDto(TASK_UUID_1)
.setComponentUuid(ENTITY_UUID_1)
.setStatus(PENDING)
.setTaskType(CeTaskTypes.BRANCH_ISSUE_SYNC)
.setCreatedAt(100_000L));
assertThat(underTest.hasAnyIssueSyncTaskPendingOrInProgress(db.getSession())).isTrue();
}
@Test
public void hasAnyIssueSyncTaskPendingOrInProgress_IN_PROGRESS() {
assertThat(underTest.hasAnyIssueSyncTaskPendingOrInProgress(db.getSession())).isFalse();
insertPending(newCeQueueDto(TASK_UUID_1)
.setComponentUuid(ENTITY_UUID_1)
.setStatus(IN_PROGRESS)
.setTaskType(CeTaskTypes.BRANCH_ISSUE_SYNC)
.setCreatedAt(100_000L));
assertThat(underTest.hasAnyIssueSyncTaskPendingOrInProgress(db.getSession())).isTrue();
}
@Test
public void selectOldestPendingPrOrBranch_returns_oldest_100_pr_or_branch_tasks() {
for (int i = 1; i < 110; i++) {
insertPending(newCeQueueDto("task" + i)
.setComponentUuid(ENTITY_UUID_1).setStatus(PENDING).setTaskType(CeTaskTypes.REPORT).setCreatedAt(i));
}
for (int i = 1; i < 10; i++) {
insertPending(newCeQueueDto("progress" + i)
.setComponentUuid(ENTITY_UUID_1).setStatus(IN_PROGRESS).setTaskType(CeTaskTypes.REPORT).setCreatedAt(i));
insertPending(newCeQueueDto("sync" + i)
.setComponentUuid(ENTITY_UUID_1).setStatus(PENDING).setTaskType(CeTaskTypes.BRANCH_ISSUE_SYNC).setCreatedAt(i));
}
List<PrOrBranchTask> prOrBranchTasks = underTest.selectOldestPendingPrOrBranch(db.getSession());
assertThat(prOrBranchTasks).hasSize(100)
.allMatch(t -> t.getCeTaskUuid().startsWith("task"), "uuid starts with task")
.allMatch(t -> t.getCreatedAt() <= 100, "creation date older or equal than 100");
}
@Test
public void selectOldestPendingPrOrBranch_returns_branch_branch_type_if_no_characteristics() {
insertPending(newCeQueueDto(TASK_UUID_1)
.setComponentUuid(COMPONENT_UUID_1)
.setEntityUuid(ENTITY_UUID_1)
.setStatus(PENDING)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(123L));
List<PrOrBranchTask> prOrBranchTasks = underTest.selectOldestPendingPrOrBranch(db.getSession());
assertThat(prOrBranchTasks).hasSize(1);
assertThat(prOrBranchTasks.get(0))
.extracting(PrOrBranchTask::getBranchType, PrOrBranchTask::getComponentUuid, PrOrBranchTask::getEntityUuid, PrOrBranchTask::getTaskType)
.containsExactly(BRANCH_KEY, COMPONENT_UUID_1, ENTITY_UUID_1, CeTaskTypes.REPORT);
}
@Test
public void selectOldestPendingPrOrBranch_returns_branch_branch_type_if_unrelated_characteristics() {
insertPending(newCeQueueDto(TASK_UUID_1)
.setComponentUuid(COMPONENT_UUID_1)
.setEntityUuid(ENTITY_UUID_1)
.setStatus(PENDING)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(123L));
List<PrOrBranchTask> prOrBranchTasks = underTest.selectOldestPendingPrOrBranch(db.getSession());
insertCharacteristic(BRANCH_KEY, "123", "c1", TASK_UUID_1);
assertThat(prOrBranchTasks).hasSize(1);
assertThat(prOrBranchTasks.get(0))
.extracting(PrOrBranchTask::getBranchType, PrOrBranchTask::getComponentUuid, PrOrBranchTask::getEntityUuid, PrOrBranchTask::getTaskType)
.containsExactly(BRANCH_KEY, COMPONENT_UUID_1, ENTITY_UUID_1, CeTaskTypes.REPORT);
}
@Test
public void selectOldestPendingPrOrBranch_returns_all_fields() {
insertPending(newCeQueueDto(TASK_UUID_1)
.setComponentUuid(COMPONENT_UUID_1)
.setEntityUuid(ENTITY_UUID_1)
.setStatus(PENDING)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(123L));
insertCharacteristic(PULL_REQUEST, "1", "c1", TASK_UUID_1);
List<PrOrBranchTask> prOrBranchTasks = underTest.selectOldestPendingPrOrBranch(db.getSession());
assertThat(prOrBranchTasks).hasSize(1);
assertThat(prOrBranchTasks.get(0))
.extracting(PrOrBranchTask::getBranchType, PrOrBranchTask::getComponentUuid, PrOrBranchTask::getEntityUuid, PrOrBranchTask::getTaskType)
.containsExactly(PULL_REQUEST, COMPONENT_UUID_1, ENTITY_UUID_1, CeTaskTypes.REPORT);
}
@Test
public void selectInProgressWithCharacteristics_returns_all_fields() {
insertPending(newCeQueueDto(TASK_UUID_1)
.setComponentUuid(COMPONENT_UUID_1)
.setEntityUuid(ENTITY_UUID_1)
.setStatus(IN_PROGRESS)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(123L));
insertCharacteristic(PULL_REQUEST, "1", "c1", TASK_UUID_1);
List<PrOrBranchTask> prOrBranchTasks = underTest.selectInProgressWithCharacteristics(db.getSession());
assertThat(prOrBranchTasks).hasSize(1);
assertThat(prOrBranchTasks.get(0))
.extracting(PrOrBranchTask::getBranchType, PrOrBranchTask::getComponentUuid, PrOrBranchTask::getEntityUuid, PrOrBranchTask::getTaskType)
.containsExactly(PULL_REQUEST, COMPONENT_UUID_1, ENTITY_UUID_1, CeTaskTypes.REPORT);
}
@Test
public void selectInProgressWithCharacteristics_returns_branch_branch_type_if_no_characteristics() {
insertPending(newCeQueueDto(TASK_UUID_1)
.setComponentUuid(COMPONENT_UUID_1)
.setEntityUuid(ENTITY_UUID_1)
.setStatus(IN_PROGRESS)
.setTaskType(CeTaskTypes.REPORT)
.setCreatedAt(123L));
List<PrOrBranchTask> prOrBranchTasks = underTest.selectInProgressWithCharacteristics(db.getSession());
assertThat(prOrBranchTasks).hasSize(1);
assertThat(prOrBranchTasks.get(0))
.extracting(PrOrBranchTask::getBranchType, PrOrBranchTask::getComponentUuid, PrOrBranchTask::getEntityUuid, PrOrBranchTask::getTaskType)
.containsExactly(BRANCH_KEY, COMPONENT_UUID_1, ENTITY_UUID_1, CeTaskTypes.REPORT);
}
private void insertPending(CeQueueDto dto) {
underTest.insert(db.getSession(), dto);
db.commit();
}
private CeQueueDto insertPending(String uuid) {
return insertPending(uuid, (Consumer<CeQueueDto>) null);
}
private CeQueueDto insertPending(String uuid, @Nullable Consumer<CeQueueDto> dtoConsumer) {
CeQueueDto dto = new CeQueueDto();
dto.setUuid(uuid);
dto.setTaskType(CeTaskTypes.REPORT);
dto.setStatus(PENDING);
dto.setSubmitterUuid("henri");
if (dtoConsumer != null) {
dtoConsumer.accept(dto);
}
underTestAlwaysIncreasingSystem2.insert(db.getSession(), dto);
db.getSession().commit();
return dto;
}
private int pendingComponentUuidGenerator = new Random().nextInt(200);
private CeQueueDto insertPending(String uuid, String mainComponentUuid) {
CeQueueDto dto = new CeQueueDto();
dto.setUuid(uuid);
dto.setTaskType(CeTaskTypes.REPORT);
dto.setEntityUuid(mainComponentUuid);
dto.setComponentUuid("uuid_" + pendingComponentUuidGenerator++);
dto.setStatus(PENDING);
dto.setSubmitterUuid("henri");
underTest.insert(db.getSession(), dto);
db.getSession().commit();
return dto;
}
private CeQueueDto insertInProgress(String taskUuid, String workerUuid, long now) {
CeQueueDto ceQueueDto = insertPending(taskUuid);
CeQueueTesting.makeInProgress(db.getSession(), workerUuid, now, ceQueueDto);
return underTest.selectByUuid(db.getSession(), taskUuid).get();
}
private void insertCharacteristic(String key, String value, String uuid, String taskUuid) {
CeTaskCharacteristicDto dto1 = new CeTaskCharacteristicDto()
.setKey(key)
.setValue(value)
.setUuid(uuid)
.setTaskUuid(taskUuid);
db.getDbClient().ceTaskCharacteristicsDao().insert(db.getSession(), dto1);
}
private static Iterable<Map<String, Object>> upperizeKeys(List<Map<String, Object>> select) {
return select.stream().map(new Function<Map<String, Object>, Map<String, Object>>() {
@Nullable
@Override
public Map<String, Object> apply(Map<String, Object> input) {
Map<String, Object> res = new HashMap<>(input.size());
for (Map.Entry<String, Object> entry : input.entrySet()) {
res.put(entry.getKey().toUpperCase(), entry.getValue());
}
return res;
}
}).toList();
}
private void verifyCeQueueStatuses(String[] taskUuids, CeQueueDto.Status[] statuses) {
Map<String, Object>[] rows = new Map[taskUuids.length];
for (int i = 0; i < taskUuids.length; i++) {
rows[i] = rowMap(taskUuids[i], statuses[i]);
}
assertThat(upperizeKeys(db.select(SELECT_QUEUE_UUID_AND_STATUS_QUERY))).containsOnly(rows);
}
private static Map<String, Object> rowMap(String uuid, CeQueueDto.Status status) {
return ImmutableMap.of("UUID", uuid, "STATUS", status.name());
}
private void mockSystem2ForSingleCall(long now) {
Mockito.reset(mockedSystem2);
when(mockedSystem2.now())
.thenReturn(now)
.thenThrow(new IllegalStateException("now should be called only once"));
}
}
| 35,563 | 42.529988 | 165 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/ce/CeScannerContextDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.ce;
import com.google.common.collect.ImmutableSet;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.core.util.CloseableIterator;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import static java.lang.System.lineSeparator;
import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
public class CeScannerContextDaoIT {
private static final String TABLE_NAME = "ce_scanner_context";
private static final String SOME_UUID = "some UUID";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private System2 system = mock(System2.class);
private DbSession dbSession = dbTester.getSession();
private CeScannerContextDao underTest = new CeScannerContextDao(system);
@Test
public void selectScannerContext_returns_empty_on_empty_table() {
assertThat(underTest.selectScannerContext(dbSession, SOME_UUID)).isEmpty();
}
@Test
public void selectScannerContext_returns_empty_when_no_row_exist_for_taskUuid() {
String data = "some data";
underTest.insert(dbSession, SOME_UUID, scannerContextInputStreamOf(data));
dbSession.commit();
assertThat(underTest.selectScannerContext(dbSession, "OTHER_uuid")).isEmpty();
assertThat(underTest.selectScannerContext(dbSession, SOME_UUID)).contains(data);
}
@Test
public void insert_fails_with_IAE_if_data_is_empty() {
assertThatThrownBy(() -> underTest.insert(dbSession, SOME_UUID, CloseableIterator.emptyCloseableIterator()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Scanner context can not be empty");
}
@Test
public void insert_fails_with_IAE_if_data_is_fully_read() {
CloseableIterator<String> iterator = scannerContextInputStreamOf("aa");
iterator.next();
assertThatThrownBy(() -> underTest.insert(dbSession, SOME_UUID, iterator))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Scanner context can not be empty");
}
@Test
public void insert_fails_if_row_already_exists_for_taskUuid() {
underTest.insert(dbSession, SOME_UUID, scannerContextInputStreamOf("bla"));
dbSession.commit();
assertThat(dbTester.countRowsOfTable(dbSession, TABLE_NAME)).isOne();
assertThatThrownBy(() -> underTest.insert(dbSession, SOME_UUID, scannerContextInputStreamOf("blo")))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Fail to insert scanner context for task " + SOME_UUID);
}
@Test
public void insert_and_select_line_reader() {
String scannerContext = "line 1" + lineSeparator() + "line 2" + lineSeparator() + "line 3";
underTest.insert(dbSession, SOME_UUID, scannerContextInputStreamOf(scannerContext));
dbSession.commit();
assertThat(underTest.selectScannerContext(dbSession, SOME_UUID)).contains(scannerContext);
}
@Test
public void deleteByUuids_does_not_fail_on_empty_table() {
underTest.deleteByUuids(dbSession, singleton("some uuid"));
}
@Test
public void deleteByUuids_deletes_specified_existing_uuids() {
insertScannerContext(SOME_UUID);
String data2 = insertScannerContext("UUID_2");
insertScannerContext("UUID_3");
underTest.deleteByUuids(dbSession, ImmutableSet.of(SOME_UUID, "UUID_3", "UUID_4"));
assertThat(underTest.selectScannerContext(dbSession, SOME_UUID)).isEmpty();
assertThat(underTest.selectScannerContext(dbSession, "UUID_2")).contains(data2);
assertThat(underTest.selectScannerContext(dbSession, "UUID_3")).isEmpty();
}
@Test
public void selectOlderThan() {
insertWithCreationDate("TASK_1", 1_450_000_000_000L);
insertWithCreationDate("TASK_2", 1_460_000_000_000L);
insertWithCreationDate("TASK_3", 1_470_000_000_000L);
assertThat(underTest.selectOlderThan(dbSession, 1_465_000_000_000L))
.containsOnly("TASK_1", "TASK_2");
assertThat(underTest.selectOlderThan(dbSession, 1_450_000_000_000L))
.isEmpty();
}
private void insertWithCreationDate(String uuid, long createdAt) {
dbTester.executeInsert(
"CE_SCANNER_CONTEXT",
"task_uuid", uuid,
"created_at", createdAt,
"updated_at", 1,
"context_data", "YoloContent".getBytes());
dbSession.commit();
}
private String insertScannerContext(String uuid) {
String data = "data of " + uuid;
underTest.insert(dbSession, uuid, scannerContextInputStreamOf(data));
dbSession.commit();
return data;
}
private static CloseableIterator<String> scannerContextInputStreamOf(String data) {
return CloseableIterator.from(singleton(data).iterator());
}
}
| 5,589 | 35.298701 | 112 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/ce/CeTaskCharacteristicDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.ce;
import com.google.common.collect.ImmutableSet;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import static java.util.Arrays.asList;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
public class CeTaskCharacteristicDaoIT {
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private CeTaskCharacteristicDao underTest = new CeTaskCharacteristicDao();
@Test
public void selectByTaskUuids() {
insert("key1", "value1", "uuid1", "task1");
insert("key2", "value2", "uuid2", "task2");
dbTester.getSession().commit();
assertThat(underTest.selectByTaskUuids(dbTester.getSession(), asList("task1", "task2")))
.extracting(CeTaskCharacteristicDto::getTaskUuid, CeTaskCharacteristicDto::getUuid, CeTaskCharacteristicDto::getKey, CeTaskCharacteristicDto::getValue)
.containsOnly(
tuple("task1", "uuid1", "key1", "value1"),
tuple("task2", "uuid2", "key2", "value2"));
assertThat(underTest.selectByTaskUuids(dbTester.getSession(), singletonList("unknown"))).isEmpty();
}
@Test
public void deleteByTaskUuids() {
insert("key1", "value1", "uuid1", "task1");
insert("key2", "value2", "uuid2", "task2");
insert("key3", "value3", "uuid3", "task3");
underTest.deleteByTaskUuids(dbTester.getSession(), ImmutableSet.of("task1", "task3"));
assertThat(underTest.selectByTaskUuids(dbTester.getSession(), singletonList("task1"))).isEmpty();
assertThat(underTest.selectByTaskUuids(dbTester.getSession(), singletonList("task2"))).hasSize(1);
assertThat(underTest.selectByTaskUuids(dbTester.getSession(), singletonList("task3"))).isEmpty();
}
@Test
public void deleteByTaskUuids_does_nothing_if_uuid_does_not_exist() {
insert("key1", "value1", "uuid1", "task1");
// must not fail
underTest.deleteByTaskUuids(dbTester.getSession(), singleton("task2"));
assertThat(underTest.selectByTaskUuids(dbTester.getSession(), singletonList("task1"))).hasSize(1);
}
private void insert(String key, String value, String uuid, String taskUuid) {
CeTaskCharacteristicDto dto1 = new CeTaskCharacteristicDto()
.setKey(key)
.setValue(value)
.setUuid(uuid)
.setTaskUuid(taskUuid);
underTest.insert(dbTester.getSession(), singleton(dto1));
}
}
| 3,364 | 38.588235 | 157 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/ce/CeTaskInputDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.ce;
import java.io.InputStream;
import java.util.Optional;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbInputStream;
import org.sonar.db.DbTester;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CeTaskInputDaoIT {
private static final String A_UUID = "U1";
private static final String SOME_DATA = "this_is_a_report";
private static final long NOW = 1_500_000_000_000L;
private static final String TABLE_NAME = "ce_task_input";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private System2 system = mock(System2.class);
private CeTaskInputDao underTest = new CeTaskInputDao(system);
@Test
public void insert_and_select_data_stream() throws Exception {
when(system.now()).thenReturn(NOW);
InputStream report = IOUtils.toInputStream(SOME_DATA);
underTest.insert(dbTester.getSession(), A_UUID, report);
Optional<DbInputStream> result = underTest.selectData(dbTester.getSession(), A_UUID);
assertThat(result).isPresent();
try (DbInputStream is = result.get()) {
assertThat(IOUtils.toString(is, UTF_8)).isEqualTo(SOME_DATA);
}
}
@Test
public void fail_to_insert_invalid_row() {
assertThatThrownBy(() -> underTest.insert(dbTester.getSession(), null, IOUtils.toInputStream(SOME_DATA)))
.hasMessage("Fail to insert data of CE task null");
}
@Test
public void selectData_returns_absent_if_uuid_not_found() {
Optional<DbInputStream> result = underTest.selectData(dbTester.getSession(), A_UUID);
assertThat(result).isNotPresent();
}
@Test
public void selectData_returns_absent_if_uuid_exists_but_data_is_null() {
insertData(A_UUID);
dbTester.commit();
Optional<DbInputStream> result = underTest.selectData(dbTester.getSession(), A_UUID);
assertThat(result).isNotPresent();
}
@Test
public void selectUuidsNotInQueue() {
insertData("U1");
insertData("U2");
assertThat(underTest.selectUuidsNotInQueue(dbTester.getSession())).containsOnly("U1", "U2");
CeQueueDto inQueue = new CeQueueDto().setUuid("U2").setTaskType(CeTaskTypes.REPORT).setStatus(CeQueueDto.Status.IN_PROGRESS);
new CeQueueDao(system).insert(dbTester.getSession(), inQueue);
assertThat(underTest.selectUuidsNotInQueue(dbTester.getSession())).containsOnly("U1");
}
@Test
public void deleteByUuids() {
insertData(A_UUID);
assertThat(dbTester.countRowsOfTable(TABLE_NAME)).isOne();
underTest.deleteByUuids(dbTester.getSession(), singleton(A_UUID));
dbTester.commit();
assertThat(dbTester.countRowsOfTable(TABLE_NAME)).isZero();
}
private void insertData(String uuid) {
dbTester.executeInsert(TABLE_NAME, "task_uuid", uuid, "created_at", NOW, "updated_at", NOW);
dbTester.commit();
}
}
| 3,979 | 34.855856 | 129 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/ce/CeTaskMessageDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.ce;
import java.util.List;
import java.util.Optional;
import org.assertj.core.groups.Tuple;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.user.UserDto;
import static org.assertj.core.api.Assertions.assertThat;
public class CeTaskMessageDaoIT {
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private final CeTaskMessageDao underTest = new CeTaskMessageDao();
@Test
public void insert() {
underTest.insert(dbTester.getSession(), new CeTaskMessageDto()
.setUuid("uuid_1")
.setTaskUuid("task_uuid_1")
.setMessage("message_1")
.setType(CeTaskMessageType.GENERIC)
.setCreatedAt(1_222_333L));
dbTester.getSession().commit();
assertThat(
dbTester.select("select uuid as \"UUID\", task_uuid as \"TASK_UUID\", message as \"MESSAGE\", message_type as \"TYPE\", " +
"created_at as \"CREATED_AT\" from ce_task_message"))
.hasSize(1)
.extracting(t -> t.get("UUID"), t -> t.get("TASK_UUID"), t -> t.get("MESSAGE"), t -> CeTaskMessageType.valueOf((String) t.get("TYPE")),
t -> t.get("CREATED_AT"))
.containsOnly(Tuple.tuple("uuid_1", "task_uuid_1", "message_1", CeTaskMessageType.GENERIC, 1_222_333L));
}
@Test
public void selectByUuid_returns_object_if_found() {
CeTaskMessageDto dto = insertMessage("526787a4-e8af-46c0-b340-8c48188646a5", 1, 1_222_333L);
Optional<CeTaskMessageDto> result = underTest.selectByUuid(dbTester.getSession(), dto.getUuid());
assertThat(result).isPresent();
assertThat(result.get().getUuid()).isEqualTo(dto.getUuid());
}
@Test
public void selectByUuid_returns_empty_if_no_record_found() {
Optional<CeTaskMessageDto> result = underTest.selectByUuid(dbTester.getSession(), "e2a71626-1f07-402a-aac7-dd4e0bbb4394");
assertThat(result).isNotPresent();
}
@Test
public void deleteByType_deletes_messages_of_given_type() {
String task1 = "task1";
CeTaskMessageDto[] messages = {
insertMessage(task1, 0, 1_222_333L, CeTaskMessageType.GENERIC),
insertMessage(task1, 1, 2_222_333L, CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE),
insertMessage(task1, 2, 1_111_333L, CeTaskMessageType.GENERIC),
insertMessage(task1, 3, 1_222_111L, CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE)
};
underTest.deleteByType(dbTester.getSession(), CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE);
assertThat(underTest.selectByUuid(dbTester.getSession(), messages[0].getUuid())).isPresent();
assertThat(underTest.selectByUuid(dbTester.getSession(), messages[1].getUuid())).isEmpty();
assertThat(underTest.selectByUuid(dbTester.getSession(), messages[2].getUuid())).isPresent();
assertThat(underTest.selectByUuid(dbTester.getSession(), messages[3].getUuid())).isEmpty();
}
@Test
public void selectNonDismissedByUserAndTask_returns_empty_on_empty_table() {
UserDto user = dbTester.users().insertUser();
String taskUuid = "17ae66e6-fe83-4c80-b704-4b04e9c5abe8";
List<CeTaskMessageDto> dto = underTest.selectNonDismissedByUserAndTask(dbTester.getSession(), taskUuid, user.getUuid());
assertThat(dto).isEmpty();
}
@Test
public void selectNonDismissedByUserAndTask_returns_non_dismissed_messages() {
UserDto user = dbTester.users().insertUser();
ProjectDto project = dbTester.components().insertPrivateProject().getProjectDto();
dbTester.users().insertUserDismissedMessage(user, project, CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE);
String taskUuid = "17ae66e6-fe83-4c80-b704-4b04e9c5abe8";
CeTaskMessageDto msg1 = insertMessage(taskUuid, 1, 1_222_333L);
insertMessage(taskUuid, 2, 1_222_334L, CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE);
CeTaskMessageDto msg3 = insertMessage(taskUuid, 3, 1_222_335L);
List<CeTaskMessageDto> messages = underTest.selectNonDismissedByUserAndTask(dbTester.getSession(), taskUuid, user.getUuid());
assertThat(messages).hasSize(2);
assertThat(messages).extracting(CeTaskMessageDto::getUuid).containsExactlyInAnyOrder(msg1.getUuid(), msg3.getUuid());
}
private CeTaskMessageDto insertMessage(String taskUuid, int i, long createdAt) {
return insertMessage(taskUuid, i, createdAt, CeTaskMessageType.GENERIC);
}
private CeTaskMessageDto insertMessage(String taskUuid, int i, long createdAt, CeTaskMessageType messageType) {
CeTaskMessageDto res = new CeTaskMessageDto()
.setUuid("message_" + i)
.setTaskUuid(taskUuid)
.setMessage("test_" + i)
.setType(messageType)
.setCreatedAt(createdAt);
DbSession dbSession = dbTester.getSession();
underTest.insert(dbSession, res);
dbSession.commit();
return res;
}
}
| 5,741 | 40.912409 | 145 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/component/AnalysisPropertiesDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.component;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForClassTypes.tuple;
public class AnalysisPropertiesDaoIT {
private static final long NOW = 1_000L;
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private final System2 system2 = new TestSystem2().setNow(NOW);
private final DbSession dbSession = dbTester.getSession();
private final AnalysisPropertiesDao underTest = new AnalysisPropertiesDao(system2);
private final Random random = new Random();
@Test
public void insert_with_null_uuid_throws_NPE() {
AnalysisPropertyDto analysisPropertyDto = new AnalysisPropertyDto()
.setAnalysisUuid(randomAlphanumeric(10))
.setKey(randomAlphanumeric(10))
.setValue(randomAlphanumeric(10));
assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto))
.isInstanceOf(NullPointerException.class)
.hasMessage("uuid cannot be null");
}
@Test
public void insert_with_null_key_throws_NPE() {
AnalysisPropertyDto analysisPropertyDto = new AnalysisPropertyDto()
.setAnalysisUuid(randomAlphanumeric(10))
.setUuid(randomAlphanumeric(10))
.setValue(randomAlphanumeric(10));
assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto))
.isInstanceOf(NullPointerException.class)
.hasMessage("key cannot be null");
}
@Test
public void insert_with_null_analysis_uuid_throws_NPE() {
AnalysisPropertyDto analysisPropertyDto = new AnalysisPropertyDto()
.setUuid(randomAlphanumeric(10))
.setKey(randomAlphanumeric(10))
.setValue(randomAlphanumeric(10));
assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto))
.isInstanceOf(NullPointerException.class)
.hasMessage("analysis uuid cannot be null");
}
@Test
public void insert_with_null_value_throws_NPE() {
AnalysisPropertyDto analysisPropertyDto = new AnalysisPropertyDto()
.setAnalysisUuid(randomAlphanumeric(10))
.setUuid(randomAlphanumeric(10))
.setKey(randomAlphanumeric(10));
assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto))
.isInstanceOf(NullPointerException.class)
.hasMessage("value cannot be null");
}
@Test
public void insert_as_empty() {
AnalysisPropertyDto analysisPropertyDto = insertAnalysisPropertyDto(0);
assertThat(dbTester.countRowsOfTable(dbSession, "ANALYSIS_PROPERTIES")).isOne();
compareFirstValueWith(analysisPropertyDto);
}
@Test
public void insert_as_text() {
AnalysisPropertyDto analysisPropertyDto = insertAnalysisPropertyDto(1 + random.nextInt(3999));
assertThat(dbTester.countRowsOfTable(dbSession, "ANALYSIS_PROPERTIES")).isOne();
compareFirstValueWith(analysisPropertyDto);
}
@Test
public void insert_as_clob() {
AnalysisPropertyDto analysisPropertyDto = insertAnalysisPropertyDto(4000 + random.nextInt(100));
assertThat(dbTester.countRowsOfTable(dbSession, "ANALYSIS_PROPERTIES")).isOne();
compareFirstValueWith(analysisPropertyDto);
}
@Test
public void insert_a_list() {
List<AnalysisPropertyDto> propertyDtos = Arrays.asList(
newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)));
underTest.insert(dbSession, propertyDtos);
assertThat(dbTester.countRowsOfTable(dbSession, "ANALYSIS_PROPERTIES")).isEqualTo(propertyDtos.size());
}
@Test
public void selectByAnalysisUuid_should_return_correct_values() {
String analysisUuid = randomAlphanumeric(40);
List<AnalysisPropertyDto> propertyDtos = Arrays.asList(
newAnalysisPropertyDto(random.nextInt(8000), analysisUuid),
newAnalysisPropertyDto(random.nextInt(8000), analysisUuid),
newAnalysisPropertyDto(random.nextInt(8000), analysisUuid),
newAnalysisPropertyDto(random.nextInt(8000), analysisUuid),
newAnalysisPropertyDto(random.nextInt(8000), analysisUuid),
newAnalysisPropertyDto(random.nextInt(8000), analysisUuid),
newAnalysisPropertyDto(random.nextInt(8000), analysisUuid),
newAnalysisPropertyDto(random.nextInt(8000), analysisUuid));
underTest.insert(dbSession, propertyDtos);
assertThat(dbTester.countRowsOfTable(dbSession, "ANALYSIS_PROPERTIES")).isEqualTo(propertyDtos.size());
List<AnalysisPropertyDto> result = underTest.selectByAnalysisUuid(dbSession, analysisUuid);
assertThat(result).containsExactlyInAnyOrder(propertyDtos.toArray(new AnalysisPropertyDto[0]));
}
@Test
public void selectByKeyAndAnalysisUuids_should_return_correct_values() {
String analysisUuid = randomAlphanumeric(40);
List<AnalysisPropertyDto> propertyDtos = Arrays.asList(
newAnalysisPropertyDto(random.nextInt(10), "key1", analysisUuid),
newAnalysisPropertyDto(random.nextInt(10), "key2", analysisUuid),
newAnalysisPropertyDto(random.nextInt(10), "key3", analysisUuid)
);
underTest.insert(dbSession, propertyDtos);
assertThat(dbTester.countRowsOfTable(dbSession, "ANALYSIS_PROPERTIES")).isEqualTo(propertyDtos.size());
List<AnalysisPropertyDto> result = underTest.selectByKeyAndAnalysisUuids(dbSession, "key1", Set.of(analysisUuid));
assertThat(result).contains(propertyDtos.get(0));
result = underTest.selectByKeyAndAnalysisUuids(dbSession, "key2", Set.of(analysisUuid));
assertThat(result).contains(propertyDtos.get(1));
result = underTest.selectByKeyAndAnalysisUuids(dbSession, "key3", Set.of(analysisUuid));
assertThat(result).contains(propertyDtos.get(2));
}
@Test
public void selectProjectCountPerAnalysisPropertyValueInLastAnalysis_should_return_correct_values() {
final String analysisPropertyKey = "key";
for (int i = 0; i < 7; i++) {
String uuid = "uuid" + i;
ProjectDto project = dbTester.components().insertPrivateProject(c -> {
}, p -> p.setUuid(uuid)).getProjectDto();
dbTester.components().insertSnapshot(project, s -> s.setLast(true).setUuid(uuid));
// branches shouldn't be taken into account
dbTester.components().insertProjectBranch(project);
}
underTest.insert(dbSession, new AnalysisPropertyDto().setKey(analysisPropertyKey).setValue("git").setAnalysisUuid("uuid0").setUuid("0"));
underTest.insert(dbSession, new AnalysisPropertyDto().setKey(analysisPropertyKey).setValue("svn").setAnalysisUuid("uuid1").setUuid("1"));
underTest.insert(dbSession, new AnalysisPropertyDto().setKey(analysisPropertyKey).setValue("undetected").setAnalysisUuid("uuid2").setUuid("2"));
underTest.insert(dbSession, new AnalysisPropertyDto().setKey(analysisPropertyKey).setValue("undetected").setAnalysisUuid("uuid3").setUuid("3"));
underTest.insert(dbSession, new AnalysisPropertyDto().setKey(analysisPropertyKey).setValue("git").setAnalysisUuid("uuid4").setUuid("4"));
underTest.insert(dbSession, new AnalysisPropertyDto().setKey(analysisPropertyKey).setValue("git").setAnalysisUuid("uuid5").setUuid("5"));
List<AnalysisPropertyValuePerProject> result = underTest.selectAnalysisPropertyValueInLastAnalysisPerProject(dbSession, analysisPropertyKey);
assertThat(result)
.extracting(AnalysisPropertyValuePerProject::getProjectUuid, AnalysisPropertyValuePerProject::getPropertyValue)
.containsExactlyInAnyOrder(
tuple("uuid0", "git"),
tuple("uuid1", "svn"),
tuple("uuid2", "undetected"),
tuple("uuid3", "undetected"),
tuple("uuid4", "git"),
tuple("uuid5", "git")
);
}
private AnalysisPropertyDto insertAnalysisPropertyDto(int valueLength) {
AnalysisPropertyDto analysisPropertyDto = newAnalysisPropertyDto(valueLength, randomAlphanumeric(40));
underTest.insert(dbSession, analysisPropertyDto);
return analysisPropertyDto;
}
private AnalysisPropertyDto newAnalysisPropertyDto(int valueLength, String key, String analysisUuid) {
return new AnalysisPropertyDto()
.setAnalysisUuid(analysisUuid)
.setKey(key)
.setUuid(randomAlphanumeric(40))
.setValue(randomAlphanumeric(valueLength))
.setCreatedAt(1_000L);
}
private AnalysisPropertyDto newAnalysisPropertyDto(int valueLength, String analysisUuid) {
return newAnalysisPropertyDto(valueLength, randomAlphanumeric(512), analysisUuid);
}
private void compareFirstValueWith(AnalysisPropertyDto analysisPropertyDto) {
AnalysisPropertyDto dtoFromDatabase = underTest.selectByAnalysisUuid(dbSession, analysisPropertyDto.getAnalysisUuid()).get(0);
assertThat(dtoFromDatabase).isEqualTo(analysisPropertyDto);
}
}
| 10,439 | 43.050633 | 148 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/component/ApplicationProjectsDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.component;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import static org.assertj.core.api.Assertions.assertThat;
public class ApplicationProjectsDaoIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private final UuidFactoryFast uuids = UuidFactoryFast.getInstance();
private final TestSystem2 system2 = new TestSystem2();
private final DbSession dbSession = db.getSession();
private final ApplicationProjectsDao underTest = new ApplicationProjectsDao(system2, uuids);
@Before
public void before() {
system2.setNow(1000L);
}
@Test
public void select_projects() {
insertApplicationProject("uuid2", "p1");
insertApplicationProject("uuid2", "p2");
assertThat(underTest.selectProjects(dbSession, "uuid")).isEmpty();
assertThat(underTest.selectProjects(dbSession, "uuid2")).extracting(ProjectDto::getUuid).containsOnly("p1", "p2");
}
@Test
public void select_projects_from_non_existing_app_is_empty() {
insertApplicationProject("uuid", "p1");
assertThat(underTest.selectProjects(dbSession, "does_not_exist")).isEmpty();
}
@Test
public void add_project() {
insertProject("p1");
underTest.addProject(dbSession, "uuid", "p1");
assertThat(underTest.selectProjects(dbSession, "uuid")).extracting(ProjectDto::getUuid).containsOnly("p1");
}
@Test
public void add_project_branch_to_application_branch() {
insertProject("p1");
insertBranch("p1", "b1");
insertApplication("app1");
insertBranch("app1", "app-b1");
underTest.addProjectBranchToAppBranch(dbSession, "app1", "app-b1", "p1", "b1");
assertThat(underTest.selectProjectBranchesFromAppBranchUuid(dbSession, "app-b1")).extracting(BranchDto::getUuid).containsOnly("b1");
}
@Test
public void select_project_branches_from_application_branch() {
ProjectDto project = db.components().insertPublicProject(p -> p.setKey("project")).getProjectDto();
BranchDto projectBranch = db.components().insertProjectBranch(project, b -> b.setKey("project-branch"));
ProjectDto app = db.components().insertPrivateApplication(a -> a.setKey("app1")).getProjectDto();
BranchDto appBranch = db.components().insertProjectBranch(app, b -> b.setKey("app-branch"));
db.components().addApplicationProject(app, project);
underTest.addProjectBranchToAppBranch(dbSession, app.getUuid(), appBranch.getUuid(), project.getUuid(), projectBranch.getUuid());
assertThat(underTest.selectProjectBranchesFromAppBranchUuid(dbSession, appBranch.getUuid())).extracting(BranchDto::getKey).containsOnly("project-branch");
assertThat(underTest.selectProjectBranchesFromAppBranchKey(dbSession, app.getUuid(), appBranch.getKey())).extracting(BranchDto::getKey).containsOnly("project-branch");
}
@Test
public void remove_project() {
insertApplicationProject("uuid", "p1");
insertApplicationProject("uuid", "p2");
assertThat(underTest.selectProjects(dbSession, "uuid")).extracting(ProjectDto::getUuid).contains("p1");
underTest.removeApplicationProjectsByApplicationAndProject(dbSession, "uuid", "p1");
assertThat(underTest.selectProjects(dbSession, "uuid")).extracting(ProjectDto::getUuid).containsOnly("p2");
}
@Test
public void remove_project_from_non_existing_app_is_no_op() {
insertApplicationProject("uuid", "p1");
underTest.removeApplicationProjectsByApplicationAndProject(dbSession, "non_existing", "p1");
assertThat(underTest.selectProjects(dbSession, "uuid")).extracting(ProjectDto::getUuid).containsOnly("p1");
}
@Test
public void remove_non_existing_project_from_app_is_no_op() {
insertApplicationProject("uuid", "p1");
underTest.removeApplicationProjectsByApplicationAndProject(dbSession, "uuid", "non_existing");
assertThat(underTest.selectProjects(dbSession, "uuid")).extracting(ProjectDto::getUuid).containsOnly("p1");
}
@Test
public void selectProjectsMainBranchesOfApplication_whenApplicationDoesNotExist_shouldReturnEmptyList() {
insertBranchesForProjectUuids(true, "1");
List<BranchDto> branchDtos = underTest.selectProjectsMainBranchesOfApplication(dbSession, "1");
assertThat(branchDtos).isEmpty();
}
@Test
public void selectProjectsMainBranchesOfApplication_whenApplicationExistWithTwoProjects_shouldReturnTwoBranches() {
String appUuid = "appUuid";
insertProject("1");
insertProject("2");
insertBranchesForProjectUuids(false, "1", "2");
insertApplicationProjectWithoutProject(appUuid, "1");
insertApplicationProjectWithoutProject(appUuid, "2");
List<BranchDto> branchDtos = underTest.selectProjectsMainBranchesOfApplication(dbSession, appUuid);
assertThat(branchDtos).hasSize(2);
assertThat(branchDtos).extracting(BranchDto::isMain).allMatch(s -> true);
}
private void insertApplicationProject(String applicationUuid, String projectUuid) {
String uuid = uuids.create();
db.executeInsert(
"app_projects",
"uuid", uuid,
"application_uuid", applicationUuid,
"project_uuid", projectUuid,
"created_at", 1000L);
insertProject(projectUuid);
}
private void insertApplicationProjectWithoutProject(String applicationUuid, String projectUuid) {
String uuid = uuids.create();
db.executeInsert(
"app_projects",
"uuid", uuid,
"application_uuid", applicationUuid,
"project_uuid", projectUuid,
"created_at", 1000L);
}
private void insertProject(String projectUuid) {
db.components().insertPrivateProject(c -> {}, p -> p.setUuid(projectUuid));
}
private void insertApplication(String appUuid) {
db.executeInsert("projects",
"uuid", appUuid,
"kee", appUuid,
"qualifier", "APP",
"private", true,
"updated_at", 1000L,
"created_at", 1000L);
}
private void insertBranch(String projectUuid, String branchKey) {
insertBranch(projectUuid, branchKey, false);
}
private void insertBranch(String projectUuid, String branchKey, boolean isMain) {
db.executeInsert("project_branches",
"uuid", branchKey,
"branch_type", "BRANCH",
"project_uuid", projectUuid,
"kee", branchKey,
"NEED_ISSUE_SYNC", true,
"updated_at", 1000L,
"created_at", 1000L,
"is_main", isMain);
}
private void insertBranchesForProjectUuids(boolean mainBranch, String... projectUuids) {
for (String uuid : projectUuids) {
insertBranch(uuid, "key" + uuid + mainBranch, mainBranch);
}
}
}
| 7,610 | 37.246231 | 171 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/component/BranchDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.component;
import com.google.common.collect.Sets;
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.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.protobuf.DbProjectBranches;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang.StringUtils.repeat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.api.Assertions.tuple;
import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY;
import static org.sonar.db.component.BranchType.BRANCH;
import static org.sonar.db.component.BranchType.PULL_REQUEST;
@RunWith(DataProviderRunner.class)
public class BranchDaoIT {
private static final long NOW = 1_000L;
private static final String SELECT_FROM = """
select project_uuid as "projectUuid", uuid as "uuid", branch_type as "branchType",
kee as "kee", merge_branch_uuid as "mergeBranchUuid", pull_request_binary as "pullRequestBinary", created_at as "createdAt", updated_at as "updatedAt", is_main as "isMain"
from project_branches""";
private System2 system2 = new TestSystem2().setNow(NOW);
@Rule
public DbTester db = DbTester.create(system2);
private DbSession dbSession = db.getSession();
private BranchDao underTest = new BranchDao(system2);
@Test
public void insert_branch_with_only_nonnull_fields() {
BranchDto dto = new BranchDto();
dto.setProjectUuid("U1");
dto.setUuid("U2");
dto.setBranchType(BranchType.BRANCH);
dto.setIsMain(true);
dto.setKey("feature/foo");
underTest.insert(dbSession, dto);
Map<String, Object> map = db.selectFirst(dbSession, SELECT_FROM + " where uuid='" + dto.getUuid() + "'");
assertThat(map).contains(
entry("projectUuid", "U1"),
entry("uuid", "U2"),
entry("branchType", "BRANCH"),
entry("kee", "feature/foo"),
entry("mergeBranchUuid", null),
entry("pullRequestBinary", null),
entry("createdAt", 1_000L),
entry("updatedAt", 1_000L));
assertThat(map.get("isMain")).isIn(true, 1L); // Oracle returns 1L instead of true
}
@Test
public void update_main_branch_name() {
BranchDto dto = new BranchDto();
dto.setProjectUuid("U1");
dto.setUuid("U1");
dto.setIsMain(true);
dto.setBranchType(BranchType.BRANCH);
dto.setKey("feature");
underTest.insert(dbSession, dto);
BranchDto dto2 = new BranchDto();
dto2.setProjectUuid("U2");
dto2.setUuid("U2");
dto2.setIsMain(true);
dto2.setBranchType(BranchType.BRANCH);
dto2.setKey("branch");
underTest.insert(dbSession, dto2);
underTest.updateBranchName(dbSession, "U1", "master");
BranchDto loaded = underTest.selectByBranchKey(dbSession, "U1", "master").get();
assertThat(loaded.getMergeBranchUuid()).isNull();
assertThat(loaded.getProjectUuid()).isEqualTo("U1");
assertThat(loaded.getBranchType()).isEqualTo(BranchType.BRANCH);
assertThat(loaded.isMain()).isTrue();
}
@Test
public void selectBranchMeasuresForTelemetry() {
BranchDto dto = new BranchDto();
dto.setProjectUuid("U1");
dto.setUuid("U1");
dto.setBranchType(BranchType.BRANCH);
dto.setKey("feature");
dto.setIsMain(true);
dto.setExcludeFromPurge(false);
underTest.insert(dbSession, dto);
MetricDto qg = db.measures().insertMetric(m -> m.setKey(ALERT_STATUS_KEY));
SnapshotDto analysis = db.components().insertSnapshot(dto);
db.measures().insertMeasure(dto, analysis, qg, pm -> pm.setData("OK"));
var branchMeasures = underTest.selectBranchMeasuresWithCaycMetric(dbSession);
assertThat(branchMeasures)
.hasSize(1)
.extracting(BranchMeasuresDto::getBranchUuid, BranchMeasuresDto::getBranchKey, BranchMeasuresDto::getProjectUuid,
BranchMeasuresDto::getAnalysisCount, BranchMeasuresDto::getGreenQualityGateCount, BranchMeasuresDto::getExcludeFromPurge)
.containsExactly(tuple("U1", "feature", "U1", 1, 1, false));
}
@Test
public void updateExcludeFromPurge() {
BranchDto dto = new BranchDto();
dto.setProjectUuid("U1");
dto.setUuid("U1");
dto.setBranchType(BranchType.BRANCH);
dto.setKey("feature");
dto.setIsMain(true);
dto.setExcludeFromPurge(false);
underTest.insert(dbSession, dto);
underTest.updateExcludeFromPurge(dbSession, "U1", true);
BranchDto loaded = underTest.selectByBranchKey(dbSession, "U1", "feature").get();
assertThat(loaded.isExcludeFromPurge()).isTrue();
}
@DataProvider
public static Object[][] nullOrEmpty() {
return new Object[][] {
{null},
{""}
};
}
@DataProvider
public static Object[][] oldAndNewValuesCombinations() {
String value1 = randomAlphabetic(10);
String value2 = randomAlphabetic(20);
return new Object[][] {
{null, value1},
{"", value1},
{value1, null},
{value1, ""},
{value1, value2},
{null, null},
{"", null},
{value1, value1}
};
}
@Test
public void insert_branch_with_all_fields_and_max_length_values() {
BranchDto dto = new BranchDto();
dto.setProjectUuid(repeat("a", 50));
dto.setUuid(repeat("b", 50));
dto.setIsMain(false);
dto.setBranchType(BranchType.BRANCH);
dto.setKey(repeat("c", 255));
dto.setMergeBranchUuid(repeat("d", 50));
underTest.insert(dbSession, dto);
Map<String, Object> map = db.selectFirst(dbSession, SELECT_FROM + " where uuid='" + dto.getUuid() + "'");
assertThat((String) map.get("projectUuid")).contains("a").isEqualTo(dto.getProjectUuid());
assertThat((String) map.get("uuid")).contains("b").isEqualTo(dto.getUuid());
assertThat((String) map.get("kee")).contains("c").isEqualTo(dto.getKey());
assertThat((String) map.get("mergeBranchUuid")).contains("d").isEqualTo(dto.getMergeBranchUuid());
}
@Test
public void insert_pull_request_branch_with_only_non_null_fields() {
String projectUuid = "U1";
String uuid = "U2";
BranchType branchType = BranchType.PULL_REQUEST;
String kee = "123";
BranchDto dto = new BranchDto();
dto.setProjectUuid(projectUuid);
dto.setUuid(uuid);
dto.setIsMain(false);
dto.setBranchType(branchType);
dto.setKey(kee);
underTest.insert(dbSession, dto);
BranchDto loaded = underTest.selectByUuid(dbSession, dto.getUuid()).get();
assertThat(loaded.getProjectUuid()).isEqualTo(projectUuid);
assertThat(loaded.getUuid()).isEqualTo(uuid);
assertThat(loaded.isMain()).isFalse();
assertThat(loaded.getBranchType()).isEqualTo(branchType);
assertThat(loaded.getKey()).isEqualTo(kee);
assertThat(loaded.getMergeBranchUuid()).isNull();
assertThat(loaded.getPullRequestData()).isNull();
}
@Test
public void insert_pull_request_branch_with_all_fields() {
String projectUuid = "U1";
String uuid = "U2";
BranchType branchType = BranchType.PULL_REQUEST;
String kee = "123";
String branch = "feature/pr1";
String title = "Dummy Feature Title";
String url = "http://example.com/pullRequests/pr1";
String tokenAttributeName = "token";
String tokenAttributeValue = "dummy token";
DbProjectBranches.PullRequestData pullRequestData = DbProjectBranches.PullRequestData.newBuilder()
.setBranch(branch)
.setTitle(title)
.setUrl(url)
.putAttributes(tokenAttributeName, tokenAttributeValue)
.build();
BranchDto dto = new BranchDto();
dto.setProjectUuid(projectUuid);
dto.setUuid(uuid);
dto.setIsMain(false);
dto.setBranchType(branchType);
dto.setKey(kee);
dto.setPullRequestData(pullRequestData);
underTest.insert(dbSession, dto);
BranchDto loaded = underTest.selectByUuid(dbSession, dto.getUuid()).get();
assertThat(loaded.getProjectUuid()).isEqualTo(projectUuid);
assertThat(loaded.getUuid()).isEqualTo(uuid);
assertThat(loaded.getBranchType()).isEqualTo(branchType);
assertThat(loaded.getKey()).isEqualTo(kee);
assertThat(loaded.getMergeBranchUuid()).isNull();
DbProjectBranches.PullRequestData loadedPullRequestData = loaded.getPullRequestData();
assertThat(loadedPullRequestData).isNotNull();
assertThat(loadedPullRequestData.getBranch()).isEqualTo(branch);
assertThat(loadedPullRequestData.getTitle()).isEqualTo(title);
assertThat(loadedPullRequestData.getUrl()).isEqualTo(url);
assertThat(loadedPullRequestData.getAttributesMap()).containsEntry(tokenAttributeName, tokenAttributeValue);
}
@Test
public void upsert_branch() {
BranchDto dto = new BranchDto();
dto.setProjectUuid("U1");
dto.setUuid("U2");
dto.setIsMain(false);
dto.setBranchType(BranchType.BRANCH);
dto.setKey("foo");
underTest.insert(dbSession, dto);
// the fields that can be updated
dto.setMergeBranchUuid("U3");
// the fields that can't be updated. New values are ignored.
dto.setProjectUuid("ignored");
dto.setBranchType(BranchType.BRANCH);
underTest.upsert(dbSession, dto);
BranchDto loaded = underTest.selectByBranchKey(dbSession, "U1", "foo").get();
assertThat(loaded.getMergeBranchUuid()).isEqualTo("U3");
assertThat(loaded.getProjectUuid()).isEqualTo("U1");
assertThat(loaded.getBranchType()).isEqualTo(BranchType.BRANCH);
}
@Test
public void upsert_pull_request() {
BranchDto dto = new BranchDto();
dto.setProjectUuid("U1");
dto.setUuid("U2");
dto.setBranchType(BranchType.PULL_REQUEST);
dto.setKey("foo");
dto.setIsMain(false);
underTest.insert(dbSession, dto);
// the fields that can be updated
dto.setMergeBranchUuid("U3");
String branch = "feature/pr1";
String title = "Dummy Feature Title";
String url = "http://example.com/pullRequests/pr1";
String tokenAttributeName = "token";
String tokenAttributeValue = "dummy token";
DbProjectBranches.PullRequestData pullRequestData = DbProjectBranches.PullRequestData.newBuilder()
.setBranch(branch)
.setTitle(title)
.setUrl(url)
.putAttributes(tokenAttributeName, tokenAttributeValue)
.build();
dto.setPullRequestData(pullRequestData);
// the fields that can't be updated. New values are ignored.
dto.setProjectUuid("ignored");
dto.setBranchType(BranchType.BRANCH);
underTest.upsert(dbSession, dto);
BranchDto loaded = underTest.selectByPullRequestKey(dbSession, "U1", "foo").get();
assertThat(loaded.getMergeBranchUuid()).isEqualTo("U3");
assertThat(loaded.getProjectUuid()).isEqualTo("U1");
assertThat(loaded.getBranchType()).isEqualTo(BranchType.PULL_REQUEST);
DbProjectBranches.PullRequestData loadedPullRequestData = loaded.getPullRequestData();
assertThat(loadedPullRequestData).isNotNull();
assertThat(loadedPullRequestData.getBranch()).isEqualTo(branch);
assertThat(loadedPullRequestData.getTitle()).isEqualTo(title);
assertThat(loadedPullRequestData.getUrl()).isEqualTo(url);
assertThat(loadedPullRequestData.getAttributesMap()).containsEntry(tokenAttributeName, tokenAttributeValue);
}
@Test
public void update_pull_request_data() {
BranchDto dto = new BranchDto();
dto.setProjectUuid("U1");
dto.setUuid("U2");
dto.setIsMain(false);
dto.setBranchType(BranchType.PULL_REQUEST);
dto.setKey("foo");
// the fields that can be updated
String mergeBranchUuid = "U3";
dto.setMergeBranchUuid(mergeBranchUuid + "-dummy-suffix");
String branch = "feature/pr1";
String title = "Dummy Feature Title";
String url = "http://example.com/pullRequests/pr1";
String tokenAttributeName = "token";
String tokenAttributeValue = "dummy token";
DbProjectBranches.PullRequestData pullRequestData = DbProjectBranches.PullRequestData.newBuilder()
.setBranch(branch + "-dummy-suffix")
.setTitle(title + "-dummy-suffix")
.setUrl(url + "-dummy-suffix")
.putAttributes(tokenAttributeName, tokenAttributeValue + "-dummy-suffix")
.build();
dto.setPullRequestData(pullRequestData);
underTest.insert(dbSession, dto);
// modify pull request data
dto.setMergeBranchUuid(mergeBranchUuid);
pullRequestData = DbProjectBranches.PullRequestData.newBuilder()
.setBranch(branch)
.setTitle(title)
.setUrl(url)
.putAttributes(tokenAttributeName, tokenAttributeValue)
.build();
dto.setPullRequestData(pullRequestData);
underTest.upsert(dbSession, dto);
BranchDto loaded = underTest.selectByPullRequestKey(dbSession, "U1", "foo").get();
assertThat(loaded.getMergeBranchUuid()).isEqualTo(mergeBranchUuid);
assertThat(loaded.getProjectUuid()).isEqualTo("U1");
assertThat(loaded.getBranchType()).isEqualTo(BranchType.PULL_REQUEST);
DbProjectBranches.PullRequestData loadedPullRequestData = loaded.getPullRequestData();
assertThat(loadedPullRequestData).isNotNull();
assertThat(loadedPullRequestData.getBranch()).isEqualTo(branch);
assertThat(loadedPullRequestData.getTitle()).isEqualTo(title);
assertThat(loadedPullRequestData.getUrl()).isEqualTo(url);
assertThat(loadedPullRequestData.getAttributesMap()).containsEntry(tokenAttributeName, tokenAttributeValue);
}
@Test
public void selectByBranchKey() {
BranchDto mainBranch = new BranchDto();
mainBranch.setProjectUuid("U1");
mainBranch.setUuid("U1");
mainBranch.setIsMain(true);
mainBranch.setBranchType(BranchType.BRANCH);
mainBranch.setKey("master");
underTest.insert(dbSession, mainBranch);
BranchDto featureBranch = new BranchDto();
featureBranch.setProjectUuid("U1");
featureBranch.setUuid("U2");
featureBranch.setIsMain(false);
featureBranch.setBranchType(BranchType.BRANCH);
featureBranch.setKey("feature/foo");
featureBranch.setMergeBranchUuid("U3");
underTest.insert(dbSession, featureBranch);
// select the feature branch
BranchDto loaded = underTest.selectByBranchKey(dbSession, "U1", "feature/foo").get();
assertThat(loaded.getUuid()).isEqualTo(featureBranch.getUuid());
assertThat(loaded.getKey()).isEqualTo(featureBranch.getKey());
assertThat(loaded.isMain()).isFalse();
assertThat(loaded.getProjectUuid()).isEqualTo(featureBranch.getProjectUuid());
assertThat(loaded.getBranchType()).isEqualTo(featureBranch.getBranchType());
assertThat(loaded.getMergeBranchUuid()).isEqualTo(featureBranch.getMergeBranchUuid());
// select a branch on another project with same branch name
assertThat(underTest.selectByBranchKey(dbSession, "U3", "feature/foo")).isEmpty();
}
@Test
public void selectByBranchKeys() {
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
ProjectDto project2 = db.components().insertPrivateProject().getProjectDto();
ProjectDto project3 = db.components().insertPrivateProject().getProjectDto();
BranchDto branch1 = db.components().insertProjectBranch(project1, b -> b.setKey("branch1"));
BranchDto branch2 = db.components().insertProjectBranch(project2, b -> b.setKey("branch2"));
BranchDto branch3 = db.components().insertProjectBranch(project3, b -> b.setKey("branch3"));
Map<String, String> branchKeysByProjectUuid = new HashMap<>();
branchKeysByProjectUuid.put(project1.getUuid(), "branch1");
branchKeysByProjectUuid.put(project2.getUuid(), "branch2");
branchKeysByProjectUuid.put(project3.getUuid(), "nonexisting");
List<BranchDto> branchDtos = underTest.selectByBranchKeys(dbSession, branchKeysByProjectUuid);
assertThat(branchDtos).hasSize(2);
assertThat(branchDtos).extracting(BranchDto::getUuid).containsExactlyInAnyOrder(branch1.getUuid(), branch2.getUuid());
}
@Test
public void selectByComponent() {
BranchDto mainBranch = new BranchDto();
mainBranch.setProjectUuid("U1");
mainBranch.setUuid("U1");
mainBranch.setIsMain(true);
mainBranch.setBranchType(BranchType.BRANCH);
mainBranch.setKey("master");
underTest.insert(dbSession, mainBranch);
BranchDto featureBranch = new BranchDto();
featureBranch.setProjectUuid("U1");
featureBranch.setUuid("U2");
featureBranch.setIsMain(false);
featureBranch.setBranchType(BranchType.BRANCH);
featureBranch.setKey("feature/foo");
featureBranch.setMergeBranchUuid("U3");
underTest.insert(dbSession, featureBranch);
ComponentDto component = new ComponentDto().setBranchUuid(mainBranch.getUuid());
// select the component
Collection<BranchDto> branches = underTest.selectByComponent(dbSession, component);
assertThat(branches).hasSize(2);
assertThat(branches).extracting(BranchDto::getUuid, BranchDto::getKey, BranchDto::isMain, BranchDto::getProjectUuid, BranchDto::getBranchType, BranchDto::getMergeBranchUuid)
.containsOnly(tuple(mainBranch.getUuid(), mainBranch.getKey(), mainBranch.isMain(), mainBranch.getProjectUuid(), mainBranch.getBranchType(), mainBranch.getMergeBranchUuid()),
tuple(featureBranch.getUuid(), featureBranch.getKey(), featureBranch.isMain(), featureBranch.getProjectUuid(), featureBranch.getBranchType(),
featureBranch.getMergeBranchUuid()));
}
@Test
public void
selectByPullRequestKey() {
BranchDto mainBranch = new BranchDto();
mainBranch.setProjectUuid("U1");
mainBranch.setUuid("U1");
mainBranch.setBranchType(BranchType.BRANCH);
mainBranch.setKey("master");
mainBranch.setIsMain(true);
underTest.insert(dbSession, mainBranch);
String pullRequestId = "123";
BranchDto pullRequest = new BranchDto();
pullRequest.setIsMain(false);
pullRequest.setProjectUuid("U1");
pullRequest.setUuid("U2");
pullRequest.setBranchType(BranchType.PULL_REQUEST);
pullRequest.setKey(pullRequestId);
pullRequest.setMergeBranchUuid("U3");
underTest.insert(dbSession, pullRequest);
// select the feature branch
BranchDto loaded = underTest.selectByPullRequestKey(dbSession, "U1", pullRequestId).get();
assertThat(loaded.getUuid()).isEqualTo(pullRequest.getUuid());
assertThat(loaded.getKey()).isEqualTo(pullRequest.getKey());
assertThat(loaded.getProjectUuid()).isEqualTo(pullRequest.getProjectUuid());
assertThat(loaded.getBranchType()).isEqualTo(pullRequest.getBranchType());
assertThat(loaded.getMergeBranchUuid()).isEqualTo(pullRequest.getMergeBranchUuid());
// select a branch on another project with same branch name
assertThat(underTest.selectByPullRequestKey(dbSession, "U3", pullRequestId)).isEmpty();
}
@Test
public void selectByKeys() {
BranchDto mainBranch = new BranchDto()
.setProjectUuid("U1")
.setUuid("U1")
.setIsMain(true)
.setBranchType(BranchType.BRANCH)
.setKey("master");
underTest.insert(dbSession, mainBranch);
BranchDto featureBranch = new BranchDto()
.setProjectUuid("U1")
.setUuid("U2")
.setIsMain(false)
.setBranchType(BranchType.BRANCH)
.setKey("feature1");
underTest.insert(dbSession, featureBranch);
String pullRequestId = "123";
BranchDto pullRequest = new BranchDto()
.setProjectUuid("U1")
.setUuid("U3")
.setIsMain(false)
.setBranchType(BranchType.PULL_REQUEST)
.setKey(pullRequestId)
.setMergeBranchUuid("U4");
underTest.insert(dbSession, pullRequest);
assertThat(underTest.selectByKeys(dbSession, "U1", Collections.emptySet()))
.isEmpty();
List<BranchDto> loaded = underTest.selectByKeys(dbSession, "U1", Set.of(mainBranch.getKey(), featureBranch.getKey()));
assertThat(loaded)
.extracting(BranchDto::getUuid)
.containsExactlyInAnyOrder(mainBranch.getUuid(), featureBranch.getUuid());
}
@Test
public void selectByUuids() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto branch1 = db.components().insertProjectBranch(project);
ComponentDto branch2 = db.components().insertProjectBranch(project);
ComponentDto branch3 = db.components().insertProjectBranch(project);
assertThat(underTest.selectByUuids(db.getSession(), asList(branch1.uuid(), branch2.uuid(), branch3.uuid())))
.extracting(BranchDto::getUuid)
.containsExactlyInAnyOrder(branch1.uuid(), branch2.uuid(), branch3.uuid());
assertThat(underTest.selectByUuids(db.getSession(), singletonList(branch1.uuid())))
.extracting(BranchDto::getUuid)
.containsExactlyInAnyOrder(branch1.uuid());
assertThat(underTest.selectByUuids(db.getSession(), singletonList("unknown"))).isEmpty();
}
@Test
public void selectByProjectUuid() {
ProjectData projectData1 = db.components().insertPrivateProject();
ComponentDto mainBranch1 = projectData1.getMainBranchComponent();
ProjectData projectData2 = db.components().insertPrivateProject();
ComponentDto mainBranch2 = projectData2.getMainBranchComponent();
ComponentDto branch1 = db.components().insertProjectBranch(mainBranch1);
ComponentDto branch2 = db.components().insertProjectBranch(mainBranch1);
ComponentDto branch3 = db.components().insertProjectBranch(mainBranch2);
ComponentDto branch4 = db.components().insertProjectBranch(mainBranch2);
assertThat(underTest.selectByProject(dbSession, new ProjectDto().setUuid(projectData1.projectUuid())))
.extracting(BranchDto::getUuid)
.containsExactlyInAnyOrder(mainBranch1.uuid(), branch1.uuid(), branch2.uuid());
assertThat(underTest.selectByProject(dbSession, new ProjectDto().setUuid(projectData2.projectUuid())))
.extracting(BranchDto::getUuid)
.containsExactlyInAnyOrder(mainBranch2.uuid(), branch3.uuid(), branch4.uuid());
}
@Test
public void selectByUuid() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto branch1 = db.components().insertProjectBranch(project);
ComponentDto branch2 = db.components().insertProjectBranch(project);
assertThat(underTest.selectByUuid(db.getSession(), branch1.uuid()).get())
.extracting(BranchDto::getUuid)
.isEqualTo(branch1.uuid());
assertThat(underTest.selectByUuid(db.getSession(), project.uuid())).isPresent();
assertThat(underTest.selectByUuid(db.getSession(), "unknown")).isNotPresent();
}
@Test
public void countPrAndBranchByProjectUuid() {
ProjectData projectData1 = db.components().insertPrivateProject();
ComponentDto project1 = projectData1.getMainBranchComponent();
db.components().insertProjectBranch(project1, b -> b.setBranchType(BRANCH).setKey("p1-branch-1"));
db.components().insertProjectBranch(project1, b -> b.setBranchType(BRANCH).setKey("p1-branch-2"));
db.components().insertProjectBranch(project1, b -> b.setBranchType(PULL_REQUEST).setKey("p1-pr-1"));
db.components().insertProjectBranch(project1, b -> b.setBranchType(PULL_REQUEST).setKey("p1-pr-2"));
db.components().insertProjectBranch(project1, b -> b.setBranchType(PULL_REQUEST).setKey("p1-pr-3"));
ProjectData projectData2 = db.components().insertPrivateProject();
ComponentDto project2 = projectData2.getMainBranchComponent();
db.components().insertProjectBranch(project2, b -> b.setBranchType(PULL_REQUEST).setKey("p2-pr-1"));
ProjectData projectData3 = db.components().insertPrivateProject();
ComponentDto project3 = projectData3.getMainBranchComponent();
db.components().insertProjectBranch(project3, b -> b.setBranchType(BRANCH).setKey("p3-branch-1"));
MetricDto unanalyzedC = db.measures().insertMetric(m -> m.setKey("unanalyzed_c"));
MetricDto unanalyzedCpp = db.measures().insertMetric(m -> m.setKey("unanalyzed_cpp"));
db.measures().insertLiveMeasure(project1, unanalyzedC);
db.measures().insertLiveMeasure(project1, unanalyzedCpp);
db.measures().insertLiveMeasure(project2, unanalyzedCpp);
db.measures().insertLiveMeasure(project3, unanalyzedC);
assertThat(underTest.countPrBranchAnalyzedLanguageByProjectUuid(db.getSession()))
.extracting(PrBranchAnalyzedLanguageCountByProjectDto::getProjectUuid, PrBranchAnalyzedLanguageCountByProjectDto::getBranch,
PrBranchAnalyzedLanguageCountByProjectDto::getPullRequest)
.containsExactlyInAnyOrder(
tuple(projectData1.projectUuid(), 3L, 3L),
tuple(projectData2.projectUuid(), 1L, 1L),
tuple(projectData3.projectUuid(), 2L, 0L)
);
}
@Test
public void selectProjectUuidsWithIssuesNeedSync() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project3 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project4 = db.components().insertPrivateProject().getMainBranchComponent();
ProjectDto project1Dto = db.components().getProjectDtoByMainBranch(project1);
ProjectDto project2Dto = db.components().getProjectDtoByMainBranch(project2);
ProjectDto project3Dto = db.components().getProjectDtoByMainBranch(project3);
ProjectDto project4Dto = db.components().getProjectDtoByMainBranch(project4);
BranchDto branch1 = db.components().insertProjectBranch(project1Dto, branchDto -> branchDto.setNeedIssueSync(true));
BranchDto branch2 = db.components().insertProjectBranch(project1Dto, branchDto -> branchDto.setNeedIssueSync(false));
BranchDto branch3 = db.components().insertProjectBranch(project2Dto);
assertThat(underTest.selectProjectUuidsWithIssuesNeedSync(db.getSession(),
Sets.newHashSet(project1Dto.getUuid(), project2Dto.getUuid(), project3Dto.getUuid(), project4Dto.getUuid())))
.containsOnly(project1Dto.getUuid());
}
@Test
public void hasAnyBranchWhereNeedIssueSync() {
assertThat(underTest.hasAnyBranchWhereNeedIssueSync(dbSession, true)).isFalse();
assertThat(underTest.hasAnyBranchWhereNeedIssueSync(dbSession, false)).isFalse();
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setNeedIssueSync(false));
assertThat(underTest.hasAnyBranchWhereNeedIssueSync(dbSession, true)).isFalse();
assertThat(underTest.hasAnyBranchWhereNeedIssueSync(dbSession, false)).isTrue();
project = db.components().insertPrivateProject().getMainBranchComponent();
branch = db.components().insertProjectBranch(project, b -> b.setNeedIssueSync(true));
assertThat(underTest.hasAnyBranchWhereNeedIssueSync(dbSession, true)).isTrue();
}
@Test
public void countByTypeAndCreationDate() {
assertThat(underTest.countByTypeAndCreationDate(dbSession, BranchType.BRANCH, 0L)).isZero();
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto branch1 = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH));
ComponentDto branch2 = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH));
ComponentDto pr = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST));
assertThat(underTest.countByTypeAndCreationDate(dbSession, BranchType.BRANCH, 0L)).isEqualTo(3);
assertThat(underTest.countByTypeAndCreationDate(dbSession, BranchType.BRANCH, NOW)).isEqualTo(3);
assertThat(underTest.countByTypeAndCreationDate(dbSession, BranchType.BRANCH, NOW + 100)).isZero();
assertThat(underTest.countByTypeAndCreationDate(dbSession, BranchType.PULL_REQUEST, 0L)).isOne();
assertThat(underTest.countByTypeAndCreationDate(dbSession, BranchType.PULL_REQUEST, NOW)).isOne();
assertThat(underTest.countByTypeAndCreationDate(dbSession, BranchType.PULL_REQUEST, NOW + 100)).isZero();
}
@Test
public void countByNeedIssueSync() {
assertThat(underTest.countByNeedIssueSync(dbSession, true)).isZero();
assertThat(underTest.countByNeedIssueSync(dbSession, false)).isZero();
// master branch with flag set to false
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
// branches & PRs
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(true));
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(true));
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(false));
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(false));
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setNeedIssueSync(true));
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setNeedIssueSync(false));
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setNeedIssueSync(true));
assertThat(underTest.countByNeedIssueSync(dbSession, true)).isEqualTo(4);
assertThat(underTest.countByNeedIssueSync(dbSession, false)).isEqualTo(4);
}
@Test
public void countAll() {
assertThat(underTest.countAll(dbSession)).isZero();
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(true));
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(true));
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(false));
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(false));
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setNeedIssueSync(true));
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setNeedIssueSync(false));
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setNeedIssueSync(true));
assertThat(underTest.countAll(dbSession)).isEqualTo(8);
}
@Test
public void selectBranchNeedingIssueSync() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
String uuid = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(true)).uuid();
db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(false));
assertThat(underTest.selectBranchNeedingIssueSync(dbSession))
.extracting(BranchDto::getUuid)
.containsExactly(uuid);
}
@Test
public void selectBranchNeedingIssueSyncForProject() {
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
String uuid = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(true)).uuid();
db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(false));
assertThat(underTest.selectBranchNeedingIssueSyncForProject(dbSession, projectData.projectUuid()))
.extracting(BranchDto::getUuid)
.containsExactly(uuid);
}
@Test
public void updateAllNeedIssueSync() {
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
String uuid1 = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(true)).uuid();
String uuid2 = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(false)).uuid();
underTest.updateAllNeedIssueSync(dbSession);
Optional<BranchDto> project1 = underTest.selectByUuid(dbSession, uuid1);
assertThat(project1).isPresent();
assertThat(project1.get().isNeedIssueSync()).isTrue();
Optional<BranchDto> project2 = underTest.selectByUuid(dbSession, uuid2);
assertThat(project2).isPresent();
assertThat(project2.get().isNeedIssueSync()).isTrue();
}
@Test
public void updateAllNeedIssueSyncForProject() {
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
String uuid1 = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(true)).uuid();
String uuid2 = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(false)).uuid();
underTest.updateAllNeedIssueSyncForProject(dbSession, projectData.projectUuid());
Optional<BranchDto> project1 = underTest.selectByUuid(dbSession, uuid1);
assertThat(project1).isPresent();
assertThat(project1.get().isNeedIssueSync()).isTrue();
Optional<BranchDto> project2 = underTest.selectByUuid(dbSession, uuid2);
assertThat(project2).isPresent();
assertThat(project2.get().isNeedIssueSync()).isTrue();
}
@Test
public void updateNeedIssueSync() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
String uuid1 = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(false)).uuid();
String uuid2 = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(true)).uuid();
underTest.updateNeedIssueSync(dbSession, uuid1, true);
underTest.updateNeedIssueSync(dbSession, uuid2, false);
Optional<BranchDto> project1 = underTest.selectByUuid(dbSession, uuid1);
assertThat(project1).isPresent();
assertThat(project1.get().isNeedIssueSync()).isTrue();
Optional<BranchDto> project2 = underTest.selectByUuid(dbSession, uuid2);
assertThat(project2).isPresent();
assertThat(project2.get().isNeedIssueSync()).isFalse();
}
@Test
public void doAnyOfComponentsNeedIssueSync() {
assertThat(underTest.doAnyOfComponentsNeedIssueSync(dbSession, emptyList())).isFalse();
ProjectData projectData1 = db.components().insertPrivateProject();
ComponentDto project1 = projectData1.getMainBranchComponent();
ProjectData projectData2 = db.components().insertPrivateProject();
ComponentDto project2 = projectData2.getMainBranchComponent();
db.components().insertProjectBranch(projectData1.getProjectDto(), b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(true));
BranchDto projectBranch1 = db.components().insertProjectBranch(projectData1.getProjectDto(), b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(true));
BranchDto projectBranch2 = db.components().insertProjectBranch(projectData1.getProjectDto(), b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(false));
db.components().insertProjectBranch(projectData1.getProjectDto(), b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(false));
BranchDto pullRequest1 = db.components().insertProjectBranch(projectData1.getProjectDto(), b -> b.setBranchType(BranchType.PULL_REQUEST).setNeedIssueSync(true));
BranchDto pullRequest2 = db.components().insertProjectBranch(projectData1.getProjectDto(), b -> b.setBranchType(BranchType.PULL_REQUEST).setNeedIssueSync(false));
db.components().insertProjectBranch(projectData1.getProjectDto(), b -> b.setBranchType(BranchType.PULL_REQUEST).setNeedIssueSync(true));
assertThat(underTest.doAnyOfComponentsNeedIssueSync(dbSession, singletonList(projectData1.projectKey()))).isTrue();
assertThat(underTest.doAnyOfComponentsNeedIssueSync(dbSession, singletonList(projectData2.projectKey()))).isFalse();
}
@Test
public void doAnyOfComponentsNeedIssueSync_test_more_than_1000() {
List<String> componentKeys = IntStream.range(0, 1100).mapToObj(value -> db.components().insertPrivateProject().getMainBranchComponent())
.map(ComponentDto::getKey)
.collect(Collectors.toCollection(ArrayList::new));
assertThat(underTest.doAnyOfComponentsNeedIssueSync(dbSession, componentKeys)).isFalse();
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ProjectDto projectDto = db.components().getProjectDtoByMainBranch(project);
db.components().insertProjectBranch(projectDto, b -> b.setBranchType(BranchType.BRANCH).setNeedIssueSync(true));
componentKeys.add(project.getKey());
assertThat(underTest.doAnyOfComponentsNeedIssueSync(dbSession, componentKeys)).isTrue();
}
@DataProvider
public static Object[][] booleanValues() {
return new Object[][] {
{true},
{false}
};
}
@Test
@UseDataProvider("booleanValues")
public void isBranchNeedIssueSync_shouldReturnCorrectValue(boolean needIssueSync) {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
String branchUuid = db.components().insertProjectBranch(project, branch -> branch.setBranchType(BranchType.BRANCH).setNeedIssueSync(needIssueSync)).uuid();
assertThat(underTest.isBranchNeedIssueSync(dbSession, branchUuid)).isEqualTo(needIssueSync);
}
@Test
public void isBranchNeedIssueSync_whenNoBranch_shouldReturnFalse() {
assertThat(underTest.isBranchNeedIssueSync(dbSession, "unknown")).isFalse();
}
@Test
public void selectMainBranchByProjectUuid_whenMainBranch_shouldReturnMainBranch() {
BranchDto dto = new BranchDto();
dto.setProjectUuid("U1");
dto.setUuid("U1");
dto.setIsMain(true);
dto.setBranchType(BranchType.BRANCH);
dto.setKey("feature");
underTest.insert(dbSession, dto);
assertThat(underTest.selectMainBranchByProjectUuid(dbSession, "U1")).get()
.extracting(e -> e.getUuid()).isEqualTo("U1");
}
@Test
public void selectMainBranchByProjectUuid_whenNonMainBranch_shouldReturnEmpty() {
BranchDto dto = new BranchDto();
dto.setProjectUuid("U1");
dto.setUuid("U2");
dto.setIsMain(false);
dto.setBranchType(BranchType.BRANCH);
dto.setKey("feature");
underTest.insert(dbSession, dto);
assertThat(underTest.selectMainBranchByProjectUuid(dbSession, "U1")).isEmpty();
}
@Test
public void selectMainBranchesByProjectUuids_whenNoUuidsPassed_shouldReturnEmpty() {
insertBranchesForProjectUuids(true, "1");
List<BranchDto> branchDtos = underTest.selectMainBranchesByProjectUuids(dbSession, Set.of());
assertThat(branchDtos).isEmpty();
}
@Test
public void selectMainBranchesByProjectUuids_whenOneUuidPassedAndTwoBranchesInDatabase_shouldReturnOneBranch() {
insertBranchesForProjectUuids(true, "1", "2");
List<BranchDto> branchDtos = underTest.selectMainBranchesByProjectUuids(dbSession, Set.of("1"));
assertThat(branchDtos).hasSize(1);
assertThat(branchDtos).extracting(BranchDto::getProjectUuid).allMatch(s -> s.equals("1"));
}
@Test
public void selectMainBranchesByProjectUuids_whenTenUuidsPassedAndTenBranchesInDatabase_shouldReturnAllBranches() {
String[] projectUuids = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
insertBranchesForProjectUuids(true, projectUuids);
insertBranchesForProjectUuids(false, projectUuids);
List<BranchDto> branchDtos = underTest.selectMainBranchesByProjectUuids(dbSession, Set.of(projectUuids));
assertThat(branchDtos).hasSize(10);
assertThat(branchDtos).extracting(BranchDto::isMain).allMatch(b -> true);
}
private void insertBranchesForProjectUuids(boolean mainBranch, String... uuids) {
for (String uuid : uuids) {
BranchDto dto = new BranchDto();
dto.setProjectUuid(uuid);
dto.setUuid(uuid + "-uuid" + mainBranch);
dto.setIsMain(mainBranch);
dto.setBranchType(BranchType.BRANCH);
dto.setKey("feature-" + uuid + mainBranch);
underTest.insert(dbSession, dto);
}
}
}
| 41,570 | 43.460963 | 180 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/component/ComponentDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.component;
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.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.RowNotFoundException;
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.audit.model.ComponentNewValue;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.source.FileSourceDto;
import static com.google.common.collect.ImmutableSet.of;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
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.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
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.resources.Qualifiers.APP;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.api.resources.Qualifiers.SUBVIEW;
import static org.sonar.api.resources.Qualifiers.VIEW;
import static org.sonar.api.utils.DateUtils.parseDate;
import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
import static org.sonar.db.component.BranchType.BRANCH;
import static org.sonar.db.component.BranchType.PULL_REQUEST;
import static org.sonar.db.component.ComponentTesting.newApplication;
import static org.sonar.db.component.ComponentTesting.newBranchComponent;
import static org.sonar.db.component.ComponentTesting.newBranchDto;
import static org.sonar.db.component.ComponentTesting.newDirectory;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.component.ComponentTesting.newPortfolio;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.db.component.ComponentTesting.newProjectCopy;
import static org.sonar.db.component.ComponentTesting.newSubPortfolio;
import static org.sonar.db.component.ComponentTreeQuery.Strategy.CHILDREN;
import static org.sonar.db.component.ComponentTreeQuery.Strategy.LEAVES;
@RunWith(DataProviderRunner.class)
public class ComponentDaoIT {
private static final String PROJECT_UUID = "project-uuid";
private static final String DIR_UUID = "dir-uuid";
private static final String FILE_1_UUID = "file-1-uuid";
private static final String FILE_2_UUID = "file-2-uuid";
private static final String FILE_3_UUID = "file-3-uuid";
private static final String A_VIEW_UUID = "view-uuid";
private static final ComponentQuery ALL_PROJECTS_COMPONENT_QUERY = ComponentQuery.builder().setQualifiers("TRK").build();
private final System2 system2 = new AlwaysIncreasingSystem2(1000L);
@Rule
public DbTester db = DbTester.create(system2);
private final AuditPersister auditPersister = mock(AuditPersister.class);
private final Random random = new Random();
private final DbSession dbSession = db.getSession();
private final ComponentDao underTest = new ComponentDao(new NoOpAuditPersister());
private final ComponentDao underTestWithAuditPersister = new ComponentDao(auditPersister);
private static ComponentTreeQuery.Builder newTreeQuery(String baseUuid) {
return ComponentTreeQuery.builder()
.setBaseUuid(baseUuid)
.setStrategy(CHILDREN);
}
@Test
public void get_by_uuid() {
ComponentDto project = db.components().insertPrivateProject(p -> p
.setKey("org.struts:struts")
.setName("Struts")
.setLongName("Apache Struts")).getMainBranchComponent();
ComponentDto anotherProject = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto result = underTest.selectByUuid(dbSession, project.uuid()).get();
assertThat(result).isNotNull();
assertThat(result.uuid()).isEqualTo(project.uuid());
assertThat(result.getUuidPath()).isEqualTo(".");
assertThat(result.branchUuid()).isEqualTo(project.uuid());
assertThat(result.getKey()).isEqualTo("org.struts:struts");
assertThat(result.path()).isNull();
assertThat(result.name()).isEqualTo("Struts");
assertThat(result.longName()).isEqualTo("Apache Struts");
assertThat(result.qualifier()).isEqualTo("TRK");
assertThat(result.scope()).isEqualTo("PRJ");
assertThat(result.language()).isNull();
assertThat(result.getCopyComponentUuid()).isNull();
assertThat(result.isPrivate()).isTrue();
assertThat(underTest.selectByUuid(dbSession, "UNKNOWN")).isEmpty();
}
@Test
public void get_by_uuid_on_technical_project_copy() {
ComponentDto view = db.components().insertPublicPortfolio();
ComponentDto project = db.components().insertPublicProject(p -> p
.setKey("org.struts:struts")
.setName("Struts")
.setLongName("Apache Struts")).getMainBranchComponent();
ComponentDto projectCopy = db.components().insertComponent(newProjectCopy(project, view));
ComponentDto anotherProject = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto anotherProjectCopy = db.components().insertComponent(newProjectCopy(anotherProject, view));
ComponentDto result = underTest.selectByUuid(dbSession, projectCopy.uuid()).get();
assertThat(result.uuid()).isEqualTo(projectCopy.uuid());
assertThat(result.branchUuid()).isEqualTo(view.uuid());
assertThat(result.getKey()).isEqualTo(view.getKey() + project.getKey());
assertThat(result.path()).isNull();
assertThat(result.name()).isEqualTo("Struts");
assertThat(result.longName()).isEqualTo("Apache Struts");
assertThat(result.qualifier()).isEqualTo("TRK");
assertThat(result.scope()).isEqualTo("FIL");
assertThat(result.language()).isNull();
assertThat(result.getCopyComponentUuid()).isEqualTo(project.uuid());
assertThat(result.isPrivate()).isFalse();
}
@Test
public void selectByUuid_on_disabled_component() {
ComponentDto enabledProject = db.components().insertPublicProject(p -> p.setEnabled(true)).getMainBranchComponent();
ComponentDto disabledProject = db.components().insertPublicProject(p -> p.setEnabled(false)).getMainBranchComponent();
ComponentDto result = underTest.selectByUuid(dbSession, disabledProject.uuid()).get();
assertThat(result).isNotNull();
assertThat(result.isEnabled()).isFalse();
}
@Test
public void selectOrFailByUuid_fails_when_component_not_found() {
db.components().insertPublicProject().getMainBranchComponent();
assertThatThrownBy(() -> underTest.selectOrFailByUuid(dbSession, "unknown"))
.isInstanceOf(RowNotFoundException.class);
}
@Test
public void select_by_key() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project);
ComponentDto directory = db.components().insertComponent(newDirectory(project, "src"));
ComponentDto file = db.components().insertComponent(newFileDto(project, directory)
.setKey("org.struts:struts-core:src/org/struts/RequestContext.java")
.setName("RequestContext.java")
.setLongName("org.struts.RequestContext")
.setLanguage("java")
.setPath("src/RequestContext.java"));
assertThat(underTest.selectByKey(dbSession, project.getKey())).isPresent();
Optional<ComponentDto> optional = underTest.selectByKey(dbSession, file.getKey());
ComponentDto result = optional.get();
assertThat(result.uuid()).isEqualTo(file.uuid());
assertThat(result.getKey()).isEqualTo("org.struts:struts-core:src/org/struts/RequestContext.java");
assertThat(result.path()).isEqualTo("src/RequestContext.java");
assertThat(result.name()).isEqualTo("RequestContext.java");
assertThat(result.longName()).isEqualTo("org.struts.RequestContext");
assertThat(result.qualifier()).isEqualTo("FIL");
assertThat(result.scope()).isEqualTo("FIL");
assertThat(result.language()).isEqualTo("java");
assertThat(result.branchUuid()).isEqualTo(project.uuid());
assertThat(underTest.selectByKey(dbSession, "unknown")).isEmpty();
}
@Test
public void select_by_key_and_branch() {
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch").setBranchType(BRANCH));
ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
assertThat(underTest.selectByKeyAndBranch(dbSession, project.getKey(), DEFAULT_MAIN_BRANCH_NAME).get().uuid()).isEqualTo(project.uuid());
assertThat(underTest.selectByKeyAndBranch(dbSession, branch.getKey(), "my_branch").get().uuid()).isEqualTo(branch.uuid());
assertThat(underTest.selectByKeyAndBranch(dbSession, file.getKey(), "my_branch").get().uuid()).isEqualTo(file.uuid());
assertThat(underTest.selectByKeyAndBranch(dbSession, "unknown", "my_branch")).isNotPresent();
assertThat(underTest.selectByKeyAndBranch(dbSession, file.getKey(), "unknown")).isNotPresent();
}
@Test
public void select_by_key_and_pull_request() {
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setKey("my_PR").setBranchType(PULL_REQUEST));
ComponentDto pullRequestNamedAsMainBranch = db.components().insertProjectBranch(project, b -> b.setKey("master").setBranchType(PULL_REQUEST));
ComponentDto pullRequestNamedAsBranch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch").setBranchType(PULL_REQUEST));
ComponentDto file = db.components().insertComponent(newFileDto(pullRequest));
assertThat(underTest.selectByKeyAndPullRequest(dbSession, project.getKey(), "my_PR").get().uuid()).isEqualTo(pullRequest.uuid());
assertThat(underTest.selectByKeyAndPullRequest(dbSession, project.getKey(), "master").get().uuid()).isEqualTo(pullRequestNamedAsMainBranch.uuid());
assertThat(underTest.selectByKeyAndPullRequest(dbSession, branch.getKey(), "my_branch").get().uuid()).isEqualTo(pullRequestNamedAsBranch.uuid());
assertThat(underTest.selectByKeyAndPullRequest(dbSession, file.getKey(), "my_PR").get().uuid()).isEqualTo(file.uuid());
assertThat(underTest.selectByKeyAndPullRequest(dbSession, "unknown", "my_branch")).isNotPresent();
assertThat(underTest.selectByKeyAndPullRequest(dbSession, file.getKey(), "unknown")).isNotPresent();
}
@Test
public void get_by_key_on_disabled_component() {
ComponentDto project = db.components().insertPrivateProject(p -> p.setEnabled(false)).getMainBranchComponent();
ComponentDto result = underTest.selectByKey(dbSession, project.getKey()).get();
assertThat(result.isEnabled()).isFalse();
}
@Test
public void get_by_key_on_a_root_project() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto result = underTest.selectByKey(dbSession, project.getKey()).get();
assertThat(result.getKey()).isEqualTo(project.getKey());
assertThat(result.uuid()).isEqualTo(project.uuid());
assertThat(result.getUuidPath()).isEqualTo(project.getUuidPath());
assertThat(result.branchUuid()).isEqualTo(project.uuid());
}
@Test
public void selectByKeys_whenPassingKeys_shouldReturnComponentsInMainBranch() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project1);
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
List<ComponentDto> results = underTest.selectByKeys(dbSession, asList(project1.getKey(), project2.getKey()));
assertThat(results)
.extracting(ComponentDto::uuid, ComponentDto::getKey)
.containsExactlyInAnyOrder(
tuple(project1.uuid(), project1.getKey()),
tuple(project2.uuid(), project2.getKey()));
assertThat(underTest.selectByKeys(dbSession, singletonList("unknown"), null, null)).isEmpty();
}
@Test
public void selectByKeys_whenAppWithMultipleBranches_shouldReturnMainBranch() {
ProjectDto proj = db.components().insertPrivateProject().getProjectDto();
BranchDto projBranch = db.components().insertProjectBranch(proj);
ProjectDto app = db.components().insertPrivateApplication().getProjectDto();
BranchDto appBranch = db.components().insertProjectBranch(app);
db.components().addApplicationProject(app, proj);
db.components().addProjectBranchToApplicationBranch(appBranch, projBranch);
ComponentDto projInApp = db.components().insertComponent(newProjectCopy(db.components().getComponentDto(proj), db.components().getComponentDto(app)));
db.components().insertComponent(ComponentTesting.newProjectCopy(db.components().getComponentDto(projBranch), db.components().getComponentDto(appBranch)));
List<ComponentDto> results = underTest.selectByKeys(dbSession, asList(projInApp.getKey()));
assertThat(results)
.extracting(ComponentDto::uuid, ComponentDto::getKey)
.containsOnly(tuple(projInApp.uuid(), projInApp.getKey()));
}
@Test
public void selectByKeys_whenBranchMissingDueToCorruption_shouldNotReturnComponents() {
// this will create an entry in the components table, but not in the project_branches table
ComponentDto project1 = db.components().insertComponent(ComponentTesting.newPublicProjectDto());
List<ComponentDto> results = underTest.selectByKeys(dbSession, asList(project1.getKey()));
assertThat(results)
.extracting(ComponentDto::uuid, ComponentDto::getKey)
.isEmpty();
}
@Test
public void selectByKeys_whenPortfolio_shouldReturnIt() {
ComponentDto portfolio = db.components().insertPrivatePortfolio();
List<ComponentDto> results = underTest.selectByKeys(dbSession, asList(portfolio.getKey()));
assertThat(results)
.extracting(ComponentDto::uuid, ComponentDto::getKey)
.containsExactlyInAnyOrder(tuple(portfolio.uuid(), portfolio.getKey()));
}
@Test
public void selectByKeys_whenSubPortfolio_shouldReturnIt() {
ComponentDto portfolio = db.components().insertPrivatePortfolio();
ComponentDto subPortfolio = db.components().insertSubView(portfolio);
List<ComponentDto> results = underTest.selectByKeys(dbSession, asList(subPortfolio.getKey()));
assertThat(results)
.extracting(ComponentDto::uuid, ComponentDto::getKey)
.containsExactlyInAnyOrder(tuple(subPortfolio.uuid(), subPortfolio.getKey()));
}
@Test
public void selectByKeys_whenBothBranchAndPrPassed_shouldThrowISE() {
DbSession session = db.getSession();
List<String> keys = List.of("key");
assertThatThrownBy(() -> underTest.selectByKeys(session, keys, "branch", "pr"))
.isInstanceOf(IllegalStateException.class);
}
@Test
public void selectByKeys_whenSpecifyingBranch_shouldReturnComponentsInIt() {
String branchKey = "my_branch";
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchKey));
ComponentDto file1 = db.components().insertComponent(newFileDto(branch, project.uuid()));
ComponentDto file2 = db.components().insertComponent(newFileDto(branch, project.uuid()));
ComponentDto anotherBranch = db.components().insertProjectBranch(project, b -> b.setKey("another_branch"));
ComponentDto fileOnAnotherBranch = db.components().insertComponent(newFileDto(anotherBranch));
assertThat(underTest.selectByKeys(dbSession, asList(branch.getKey(), file1.getKey(), file2.getKey()), branchKey, null)).extracting(ComponentDto::uuid)
.containsExactlyInAnyOrder(branch.uuid(), file1.uuid(), file2.uuid());
assertThat(underTest.selectByKeys(dbSession, asList(file1.getKey(), file2.getKey(), fileOnAnotherBranch.getKey()), branchKey, null)).extracting(ComponentDto::uuid)
.containsExactlyInAnyOrder(file1.uuid(), file2.uuid());
assertThat(underTest.selectByKeys(dbSession, singletonList(fileOnAnotherBranch.getKey()), branchKey, null)).isEmpty();
assertThat(underTest.selectByKeys(dbSession, singletonList(file1.getKey()), "unknown", null)).isEmpty();
assertThat(underTest.selectByKeys(dbSession, singletonList("unknown"), branchKey, null)).isEmpty();
assertThat(underTest.selectByKeys(dbSession, singletonList(branch.getKey()), branchKey, null)).extracting(ComponentDto::uuid).containsExactlyInAnyOrder(branch.uuid());
}
@Test
public void selectByKeys_whenSpecifyingPR_shouldReturnComponentsInIt() {
String prKey = "my_branch";
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto pr = db.components().insertProjectBranch(project, b -> b.setKey(prKey).setBranchType(PULL_REQUEST));
ComponentDto file1 = db.components().insertComponent(newFileDto(pr));
ComponentDto anotherBranch = db.components().insertProjectBranch(project, b -> b.setKey(prKey));
ComponentDto fileOnAnotherBranch = db.components().insertComponent(newFileDto(anotherBranch));
assertThat(underTest.selectByKeys(dbSession, asList(pr.getKey(), file1.getKey()), null, prKey)).extracting(ComponentDto::uuid)
.containsExactlyInAnyOrder(pr.uuid(), file1.uuid());
assertThat(underTest.selectByKeys(dbSession, asList(file1.getKey(), fileOnAnotherBranch.getKey()), null, prKey)).extracting(ComponentDto::uuid)
.containsExactlyInAnyOrder(file1.uuid());
assertThat(underTest.selectByKeys(dbSession, singletonList(fileOnAnotherBranch.getKey()), null, prKey)).isEmpty();
assertThat(underTest.selectByKeys(dbSession, singletonList(file1.getKey()), null, "unknown")).isEmpty();
assertThat(underTest.selectByKeys(dbSession, singletonList("unknown"), null, prKey)).isEmpty();
assertThat(underTest.selectByKeys(dbSession, singletonList(pr.getKey()), null, prKey)).extracting(ComponentDto::uuid).containsExactlyInAnyOrder(pr.uuid());
}
@Test
public void get_by_uuids() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
List<ComponentDto> results = underTest.selectByUuids(dbSession, asList(project1.uuid(), project2.uuid()));
assertThat(results)
.extracting(ComponentDto::uuid, ComponentDto::getKey)
.containsExactlyInAnyOrder(
tuple(project1.uuid(), project1.getKey()),
tuple(project2.uuid(), project2.getKey()));
assertThat(underTest.selectByUuids(dbSession, singletonList("unknown"))).isEmpty();
}
@Test
public void get_by_uuids_on_removed_components() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject(p -> p.setEnabled(false)).getMainBranchComponent();
List<ComponentDto> results = underTest.selectByUuids(dbSession, asList(project1.uuid(), project2.uuid()));
assertThat(results)
.extracting(ComponentDto::getKey, ComponentDto::isEnabled)
.containsExactlyInAnyOrder(
tuple(project1.getKey(), true),
tuple(project2.getKey(), false));
}
@Test
public void select_existing_uuids() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject(p -> p.setEnabled(false)).getMainBranchComponent();
assertThat(underTest.selectExistingUuids(dbSession, asList(project1.uuid(), project2.uuid()))).containsExactlyInAnyOrder(project1.uuid(), project2.uuid());
assertThat(underTest.selectExistingUuids(dbSession, asList(project1.uuid(), "unknown"))).containsExactlyInAnyOrder(project1.uuid());
assertThat(underTest.selectExistingUuids(dbSession, singletonList("unknown"))).isEmpty();
}
@Test
public void select_component_keys_by_qualifiers() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto directory = db.components().insertComponent(newDirectory(project, "src"));
ComponentDto file = db.components().insertComponent(newFileDto(directory));
assertThat(underTest.selectComponentsByQualifiers(dbSession, newHashSet("TRK"))).extracting(ComponentDto::getKey).containsExactlyInAnyOrder(project.getKey());
assertThat(underTest.selectComponentsByQualifiers(dbSession, newHashSet("DIR"))).extracting(ComponentDto::getKey).containsExactlyInAnyOrder(directory.getKey());
assertThat(underTest.selectComponentsByQualifiers(dbSession, newHashSet("FIL"))).extracting(ComponentDto::getKey).containsExactlyInAnyOrder(file.getKey());
assertThat(underTest.selectComponentsByQualifiers(dbSession, newHashSet("unknown"))).isEmpty();
}
@Test
public void fail_with_IAE_select_component_keys_by_qualifiers_on_empty_qualifier() {
Set<String> set = emptySet();
assertThatThrownBy(() -> underTest.selectComponentsByQualifiers(dbSession, set))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Qualifiers cannot be empty");
}
@Test
public void find_sub_projects_by_component_keys() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto removedProject = db.components().insertPrivateProject(p -> p.setEnabled(false)).getMainBranchComponent();
ComponentDto directory = db.components().insertComponent(newDirectory(project, "src"));
ComponentDto removedDirectory = db.components().insertComponent(newDirectory(project, "src2").setEnabled(false));
ComponentDto file = db.components().insertComponent(newFileDto(project, directory));
ComponentDto removedFile = db.components().insertComponent(newFileDto(project, directory).setEnabled(false));
// Sub project of a file
assertThat(underTest.selectSubProjectsByComponentUuids(dbSession, singletonList(file.uuid())))
.extracting(ComponentDto::getKey)
.containsExactlyInAnyOrder(project.getKey());
// Sub project of a directory
assertThat(underTest.selectSubProjectsByComponentUuids(dbSession, singletonList(directory.uuid())))
.extracting(ComponentDto::uuid)
.containsExactlyInAnyOrder(project.uuid());
// Sub project of a project
assertThat(underTest.selectSubProjectsByComponentUuids(dbSession, singletonList(project.uuid())))
.extracting(ComponentDto::uuid)
.containsExactlyInAnyOrder(project.uuid());
assertThat(underTest.selectSubProjectsByComponentUuids(dbSession, singletonList("unknown"))).isEmpty();
assertThat(underTest.selectSubProjectsByComponentUuids(dbSession, Collections.emptyList())).isEmpty();
}
@Test
public void select_enabled_files_from_project() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto directory = db.components().insertComponent(newDirectory(project, "src"));
ComponentDto file = db.components().insertComponent(newFileDto(project, directory));
FileSourceDto fileSource = db.fileSources().insertFileSource(file);
// From root project
assertThat(underTest.selectEnabledFilesFromProject(dbSession, project.uuid()))
.extracting(FilePathWithHashDto::getUuid, FilePathWithHashDto::getSrcHash, FilePathWithHashDto::getPath, FilePathWithHashDto::getRevision)
.containsExactlyInAnyOrder(
tuple(file.uuid(), fileSource.getSrcHash(), file.path(), fileSource.getRevision()));
// From directory
assertThat(underTest.selectEnabledFilesFromProject(dbSession, directory.uuid())).isEmpty();
assertThat(underTest.selectEnabledFilesFromProject(dbSession, "unknown")).isEmpty();
}
@Test
public void select_by_branch_uuid() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto removedProject = db.components().insertPrivateProject(p -> p.setEnabled(false)).getMainBranchComponent();
ComponentDto directory = db.components().insertComponent(newDirectory(project, "src"));
ComponentDto removedDirectory = db.components().insertComponent(newDirectory(project, "src2").setEnabled(false));
ComponentDto file = db.components().insertComponent(newFileDto(project, directory));
ComponentDto removedFile = db.components().insertComponent(newFileDto(project, directory).setEnabled(false));
// Removed components are included
assertThat(underTest.selectByBranchUuid(project.uuid(), dbSession))
.extracting(ComponentDto::getKey)
.containsExactlyInAnyOrder(project.getKey(), directory.getKey(), removedDirectory.getKey(), file.getKey(), removedFile.getKey());
assertThat(underTest.selectByBranchUuid("UNKNOWN", dbSession)).isEmpty();
}
@Test
public void select_uuids_by_key_from_project() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project);
ComponentDto removedProject = db.components().insertPrivateProject(p -> p.setEnabled(false)).getMainBranchComponent();
ComponentDto directory = db.components().insertComponent(newDirectory(project, "src"));
ComponentDto removedDirectory = db.components().insertComponent(newDirectory(project, "src2").setEnabled(false));
ComponentDto file = db.components().insertComponent(newFileDto(project, directory));
ComponentDto removedFile = db.components().insertComponent(newFileDto(project, directory).setEnabled(false));
Map<String, String> uuidsByKey = underTest.selectUuidsByKeyFromProjectKey(dbSession, project.getKey())
.stream().collect(Collectors.toMap(KeyWithUuidDto::key, KeyWithUuidDto::uuid));
assertThat(uuidsByKey).containsOnly(
entry(project.getKey(), project.uuid()),
entry(directory.getKey(), directory.uuid()),
entry(removedDirectory.getKey(), removedDirectory.uuid()),
entry(file.getKey(), file.uuid()),
entry(removedFile.getKey(), removedFile.uuid()));
}
@Test
public void select_uuids_by_key_from_project_and_branch() {
String branchKey = "branch1";
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchKey));
ComponentDto pr = db.components().insertProjectBranch(project, b -> b.setKey(branchKey).setBranchType(PULL_REQUEST));
ComponentDto directory = db.components().insertComponent(newDirectory(branch, "src"));
ComponentDto file = db.components().insertComponent(newFileDto(branch, directory));
ComponentDto projectFile = db.components().insertComponent(newFileDto(project, directory));
Map<String, String> uuidsByKey = underTest.selectUuidsByKeyFromProjectKeyAndBranch(dbSession, project.getKey(), branchKey)
.stream().collect(Collectors.toMap(KeyWithUuidDto::key, KeyWithUuidDto::uuid));
assertThat(uuidsByKey).containsOnly(
entry(branch.getKey(), branch.uuid()),
entry(directory.getKey(), directory.uuid()),
entry(file.getKey(), file.uuid()));
}
@Test
public void select_uuids_by_key_from_project_and_pr() {
String prKey = "pr1";
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(prKey).setBranchType(PULL_REQUEST));
ComponentDto pr = db.components().insertProjectBranch(project, b -> b.setKey(prKey).setBranchType(BRANCH));
ComponentDto directory = db.components().insertComponent(newDirectory(branch, "src"));
ComponentDto file = db.components().insertComponent(newFileDto(branch, directory));
ComponentDto projectFile = db.components().insertComponent(newFileDto(project, directory));
Map<String, String> uuidsByKey = underTest.selectUuidsByKeyFromProjectKeyAndPullRequest(dbSession, project.getKey(), prKey)
.stream().collect(Collectors.toMap(KeyWithUuidDto::key, KeyWithUuidDto::uuid));
assertThat(uuidsByKey).containsOnly(
entry(branch.getKey(), branch.uuid()),
entry(directory.getKey(), directory.uuid()),
entry(file.getKey(), file.uuid()));
}
@Test
public void select_views_and_sub_views_and_applications() {
db.components().insertPublicPortfolio("ABCD", p -> {
});
db.components().insertPublicPortfolio("IJKL", p -> {
});
ComponentDto view = db.components().insertPublicPortfolio("EFGH", p -> {
});
db.components().insertSubView(view, dto -> dto.setUuid("FGHI"));
ComponentDto application = db.components().insertPublicApplication().getMainBranchComponent();
assertThat(underTest.selectAllViewsAndSubViews(dbSession)).extracting(UuidWithBranchUuidDto::getUuid)
.containsExactlyInAnyOrder("ABCD", "EFGH", "FGHI", "IJKL", application.uuid());
assertThat(underTest.selectAllViewsAndSubViews(dbSession)).extracting(UuidWithBranchUuidDto::getBranchUuid)
.containsExactlyInAnyOrder("ABCD", "EFGH", "EFGH", "IJKL", application.branchUuid());
}
@Test
public void selectViewKeysWithEnabledCopyOfProject_returns_empty_when_set_is_empty() {
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, emptySet()))
.isEmpty();
}
@Test
@UseDataProvider("oneOrMoreProjects")
public void selectViewKeysWithEnabledCopyOfProject_returns_empty_when_there_is_no_view(int projectCount) {
Set<String> projectUuids = IntStream.range(0, projectCount)
.mapToObj(i -> randomAlphabetic(5))
.collect(toSet());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, projectUuids)).isEmpty();
}
@DataProvider
public static Object[][] oneOrMoreProjects() {
return new Object[][] {
{1},
{1 + new Random().nextInt(10)}
};
}
@Test
@UseDataProvider("portfolioOrApplicationRootViewQualifier")
public void selectViewKeysWithEnabledCopyOfProject_returns_root_view_with_direct_copy_of_project(String rootViewQualifier) {
ComponentDto project = insertProject();
ComponentDto view = insertView(rootViewQualifier);
insertProjectCopy(view, project);
Set<String> keys = underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project.uuid()));
assertThat(keys).containsOnly(view.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project.uuid())))
.isEqualTo(keys);
}
@Test
@UseDataProvider("portfolioOrApplicationRootViewQualifier")
public void selectViewKeysWithEnabledCopyOfProject_returns_root_views_with_direct_copy_of_projects(String rootViewQualifier) {
ComponentDto project1 = insertProject();
ComponentDto project2 = insertProject();
ComponentDto view = insertView(rootViewQualifier);
insertProjectCopy(view, project1);
insertProjectCopy(view, project2);
ComponentDto view2 = insertView(rootViewQualifier);
ComponentDto project3 = insertProject();
insertProjectCopy(view2, project3);
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project1.uuid())))
.containsOnly(view.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project1.uuid())))
.containsOnly(view.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project2.uuid())))
.containsOnly(view.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project2.uuid())))
.containsOnly(view.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project3.uuid())))
.containsOnly(view2.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project3.uuid())))
.containsOnly(view2.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, of(project2.uuid(), project1.uuid())))
.containsOnly(view.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project2.uuid(), project1.uuid())))
.containsOnly(view.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, of(project1.uuid(), project3.uuid())))
.containsOnly(view.getKey(), view2.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project1.uuid(), project3.uuid())))
.containsOnly(view.getKey(), view2.getKey());
}
@Test
@UseDataProvider("portfolioOrApplicationRootViewQualifier")
public void selectViewKeysWithEnabledCopyOfProject_does_not_return_root_view_with_direct_copy_of_other_project(String rootViewQualifier) {
ComponentDto project1 = insertProject();
ComponentDto project2 = insertProject();
ComponentDto view1 = insertView(rootViewQualifier);
insertProjectCopy(view1, project1);
ComponentDto view2 = insertView(rootViewQualifier);
insertProjectCopy(view2, project2);
Set<String> keys = underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project2.uuid()));
assertThat(keys).containsOnly(view2.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project2.uuid())))
.isEqualTo(keys);
}
@Test
@UseDataProvider("portfolioOrApplicationRootViewQualifier")
public void selectViewKeysWithEnabledCopyOfProject_does_not_return_root_view_with_disabled_direct_copy_of_project(String rootViewQualifier) {
ComponentDto project = insertProject();
ComponentDto view1 = insertView(rootViewQualifier);
insertProjectCopy(view1, project);
ComponentDto view2 = insertView(rootViewQualifier);
insertProjectCopy(view2, project, t -> t.setEnabled(false));
Set<String> keys = underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project.uuid()));
assertThat(keys).containsOnly(view1.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project.uuid())))
.isEqualTo(keys);
}
@Test
@UseDataProvider("portfolioOrApplicationRootViewQualifier")
public void selectViewKeysWithEnabledCopyOfProject_does_not_return_disabled_root_view_with_direct_copy_of_project(String rootViewQualifier) {
ComponentDto project = insertProject();
ComponentDto view1 = insertView(rootViewQualifier, t -> t.setEnabled(false));
insertProjectCopy(view1, project);
ComponentDto view2 = insertView(rootViewQualifier);
insertProjectCopy(view2, project);
Set<String> keys = underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project.uuid()));
assertThat(keys).containsOnly(view2.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project.uuid())))
.isEqualTo(keys);
}
@Test
@UseDataProvider("portfolioOrApplicationRootViewQualifier")
public void selectViewKeysWithEnabledCopyOfProject_returns_root_view_with_indirect_copy_of_project(String rootViewQualifier) {
ComponentDto project = insertProject();
ComponentDto view = insertView(rootViewQualifier);
ComponentDto lowestSubview = insertSubviews(view);
insertProjectCopy(lowestSubview, project);
Set<String> keys = underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project.uuid()));
assertThat(keys).containsOnly(view.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project.uuid())))
.isEqualTo(keys);
}
@Test
@UseDataProvider("portfolioOrApplicationRootViewQualifier")
public void selectViewKeysWithEnabledCopyOfProject_returns_root_views_with_indirect_copy_of_projects(String rootViewQualifier) {
ComponentDto project1 = insertProject();
ComponentDto project2 = insertProject();
ComponentDto view1 = insertView(rootViewQualifier);
ComponentDto lowestSubview1 = insertSubviews(view1);
insertProjectCopy(lowestSubview1, project1);
insertProjectCopy(lowestSubview1, project2);
ComponentDto view2 = insertView(rootViewQualifier);
ComponentDto lowestSubview2 = insertSubviews(view2);
ComponentDto project3 = insertProject();
insertProjectCopy(lowestSubview2, project3);
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project1.uuid())))
.containsOnly(view1.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project1.uuid())))
.containsOnly(view1.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project2.uuid())))
.containsOnly(view1.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project2.uuid())))
.containsOnly(view1.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project3.uuid())))
.containsOnly(view2.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project3.uuid())))
.containsOnly(view2.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, of(project2.uuid(), project1.uuid())))
.containsOnly(view1.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project2.uuid(), project1.uuid())))
.containsOnly(view1.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, of(project1.uuid(), project3.uuid())))
.containsOnly(view1.getKey(), view2.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project1.uuid(), project3.uuid())))
.containsOnly(view1.getKey(), view2.getKey());
}
@Test
@UseDataProvider("portfolioOrApplicationRootViewQualifier")
public void selectViewKeysWithEnabledCopyOfProject_does_not_return_root_view_with_indirect_copy_of_other_project(String rootViewQualifier) {
ComponentDto project1 = insertProject();
ComponentDto project2 = insertProject();
ComponentDto view1 = insertView(rootViewQualifier);
ComponentDto lowestSubview1 = insertSubviews(view1);
insertProjectCopy(lowestSubview1, project1);
ComponentDto view2 = insertView(rootViewQualifier);
ComponentDto lowestSubview2 = insertSubviews(view2);
insertProjectCopy(lowestSubview2, project2);
Set<String> keys = underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project2.uuid()));
assertThat(keys).containsOnly(view2.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project2.uuid())))
.isEqualTo(keys);
}
@Test
@UseDataProvider("portfolioOrApplicationRootViewQualifier")
public void selectViewKeysWithEnabledCopyOfProject_does_not_return_root_view_with_disabled_indirect_copy_of_project(String rootViewQualifier) {
ComponentDto project = insertProject();
ComponentDto view1 = insertView(rootViewQualifier);
ComponentDto lowestSubview1 = insertSubviews(view1);
insertProjectCopy(lowestSubview1, project);
ComponentDto view2 = insertView(rootViewQualifier);
ComponentDto lowestSubview2 = insertSubviews(view2);
insertProjectCopy(lowestSubview2, project, t -> t.setEnabled(false));
Set<String> keys = underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project.uuid()));
assertThat(keys).containsOnly(view1.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project.uuid())))
.isEqualTo(keys);
}
@Test
@UseDataProvider("portfolioOrApplicationRootViewQualifier")
public void selectViewKeysWithEnabledCopyOfProject_does_not_return_disabled_root_view_with_indirect_copy_of_project(String rootViewQualifier) {
ComponentDto project = insertProject();
ComponentDto view1 = insertView(rootViewQualifier, t -> t.setEnabled(false));
ComponentDto lowestSubview1 = insertSubviews(view1);
insertProjectCopy(lowestSubview1, project);
ComponentDto view2 = insertView(rootViewQualifier);
ComponentDto lowestSubview2 = insertSubviews(view2);
insertProjectCopy(lowestSubview2, project);
Set<String> keys = underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, singleton(project.uuid()));
assertThat(keys).containsOnly(view2.getKey());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, shuffleWithNonExistentUuids(project.uuid())))
.isEqualTo(keys);
}
@DataProvider
public static Object[][] portfolioOrApplicationRootViewQualifier() {
return new Object[][] {
{Qualifiers.VIEW},
{Qualifiers.APP},
};
}
private ComponentDto insertSubviews(ComponentDto view) {
ComponentDto lowestView = view;
int subviewsCount1 = 1 + random.nextInt(5);
for (int i = 0; i < subviewsCount1; i++) {
lowestView = db.components().insertSubView(lowestView);
}
return lowestView;
}
private ComponentDto insertView(String rootViewQualifier) {
return insertView(rootViewQualifier, defaults());
}
private ComponentDto insertView(String rootViewQualifier, Consumer<ComponentDto> dtoPopulators) {
ComponentDbTester tester = db.components();
if (rootViewQualifier.equals(Qualifiers.VIEW)) {
return random.nextBoolean() ? tester.insertPublicPortfolio(dtoPopulators) : tester.insertPrivatePortfolio(dtoPopulators);
}
return random.nextBoolean() ? tester.insertPublicApplication(dtoPopulators).getMainBranchComponent() : tester.insertPrivatePortfolio(dtoPopulators);
}
private ComponentDto insertProject() {
return random.nextBoolean() ? db.components().insertPrivateProject().getMainBranchComponent() : db.components().insertPublicProject().getMainBranchComponent();
}
@SafeVarargs
private final ComponentDto insertProjectCopy(ComponentDto view, ComponentDto project, Consumer<ComponentDto>... decorators) {
ComponentDto component = ComponentTesting.newProjectCopy(project, view);
Arrays.stream(decorators).forEach(decorator -> decorator.accept(component));
return db.components().insertComponent(component);
}
@Test
public void select_projects_from_view() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto view = db.components().insertPublicPortfolio();
db.components().insertComponent(newProjectCopy(project1, view));
ComponentDto viewWithSubView = db.components().insertPublicPortfolio();
db.components().insertComponent(newProjectCopy(project2, viewWithSubView));
ComponentDto subView = db.components().insertSubView(viewWithSubView);
db.components().insertComponent(newProjectCopy(project1, subView));
ComponentDto viewWithoutProject = db.components().insertPrivatePortfolio();
assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, view.uuid(), view.uuid())).containsExactlyInAnyOrder(project1.uuid());
assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, viewWithSubView.uuid(), viewWithSubView.uuid())).containsExactlyInAnyOrder(project1.uuid(), project2.uuid());
assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, subView.uuid(), viewWithSubView.uuid())).containsExactlyInAnyOrder(project1.uuid());
assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, viewWithoutProject.uuid(), viewWithoutProject.uuid())).isEmpty();
assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, "Unknown", "Unknown")).isEmpty();
}
@Test
public void select_enabled_views_from_root_view() {
ComponentDto rootPortfolio = db.components().insertPrivatePortfolio();
ComponentDto subPortfolio = db.components().insertSubView(rootPortfolio);
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
db.components().insertComponent(newProjectCopy(project, subPortfolio));
assertThat(underTest.selectEnabledViewsFromRootView(dbSession, rootPortfolio.uuid()))
.extracting(ComponentDto::uuid)
.containsOnly(rootPortfolio.uuid(), subPortfolio.uuid());
assertThat(underTest.selectEnabledViewsFromRootView(dbSession, project.uuid())).isEmpty();
}
@Test
public void select_projects_from_view_should_escape_like_sensitive_characters() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project3 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto view = db.components().insertPrivatePortfolio();
//subview with uuid containing special character ( '_' ) for 'like' SQL clause
ComponentDto subView1 = db.components().insertComponent(newSubPortfolio(view, "A_C", "A_C-key"));
db.components().insertComponent(newProjectCopy(project1, subView1));
db.components().insertComponent(newProjectCopy(project2, subView1));
ComponentDto subView2 = db.components().insertComponent(newSubPortfolio(view, "ABC", "ABC-key"));
db.components().insertComponent(newProjectCopy(project3, subView2));
assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, subView1.uuid(), view.uuid())).containsExactlyInAnyOrder(project1.uuid(), project2.uuid());
assertThat(underTest.selectProjectBranchUuidsFromView(dbSession, subView2.uuid(), view.uuid())).containsExactlyInAnyOrder(project3.uuid());
}
@Test
public void selectByQuery_provisioned() {
ComponentDto provisionedProject = db.components()
.insertPrivateProject(p -> p.setKey("provisioned.project").setName("Provisioned Project")).getMainBranchComponent();
ComponentDto provisionedPortfolio = db.components().insertPrivatePortfolio();
SnapshotDto analyzedProject = db.components().insertProjectAndSnapshot(newPrivateProjectDto());
SnapshotDto analyzedDisabledProject = db.components().insertProjectAndSnapshot(newPrivateProjectDto()
.setEnabled(false));
SnapshotDto analyzedPortfolio = db.components().insertProjectAndSnapshot(ComponentTesting.newPortfolio());
Supplier<ComponentQuery.Builder> query = () -> ComponentQuery.builder().setQualifiers(PROJECT).setOnProvisionedOnly(true);
assertThat(underTest.selectByQuery(dbSession, query.get().build(), 0, 10))
.extracting(ComponentDto::uuid)
.containsOnly(provisionedProject.uuid());
// pagination
assertThat(underTest.selectByQuery(dbSession, query.get().build(), 2, 10)).isEmpty();
// filter on qualifiers
assertThat(underTest.selectByQuery(dbSession, query.get().setQualifiers("XXX").build(), 0, 10)).isEmpty();
assertThat(underTest.selectByQuery(dbSession, query.get().setQualifiers(PROJECT, "XXX").build(), 0, 10))
.extracting(ComponentDto::uuid)
.containsOnly(provisionedProject.uuid());
assertThat(underTest.selectByQuery(dbSession, query.get().setQualifiers(PROJECT, Qualifiers.VIEW).build(), 0, 10))
.extracting(ComponentDto::uuid)
.containsOnly(provisionedProject.uuid(), provisionedPortfolio.uuid());
// match key
assertThat(underTest.selectByQuery(dbSession, query.get().setNameOrKeyQuery(provisionedProject.getKey()).build(), 0, 10))
.extracting(ComponentDto::uuid)
.containsExactly(provisionedProject.uuid());
assertThat(underTest.selectByQuery(dbSession, query.get().setNameOrKeyQuery("pROvisiONed.proJEcT").setPartialMatchOnKey(true).build(), 0, 10))
.extracting(ComponentDto::uuid)
.containsExactly(provisionedProject.uuid());
assertThat(underTest.selectByQuery(dbSession, query.get().setNameOrKeyQuery("missing").setPartialMatchOnKey(true).build(), 0, 10)).isEmpty();
assertThat(underTest.selectByQuery(dbSession, query.get().setNameOrKeyQuery("to be escaped '\"\\%").setPartialMatchOnKey(true).build(), 0, 10))
.isEmpty();
// match name
assertThat(underTest.selectByQuery(dbSession, query.get().setNameOrKeyQuery("ned proj").setPartialMatchOnKey(true).build(), 0, 10))
.extracting(ComponentDto::uuid)
.containsExactly(provisionedProject.uuid());
}
@Test
public void selectByQuery_onProvisionedOnly_filters_projects_with_analysis_on_branch() {
Supplier<ComponentQuery.Builder> query = () -> ComponentQuery.builder()
.setQualifiers(PROJECT)
.setOnProvisionedOnly(true);
// the project does not have any analysis
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
assertThat(underTest.selectByQuery(dbSession, query.get().build(), 0, 10))
.extracting(ComponentDto::uuid)
.containsOnly(project.uuid());
// the project does not have analysis of main branch but only
// analysis of non-main branches
ComponentDto branchWithoutAnalysis = db.components().insertProjectBranch(project);
ComponentDto branchWithAnalysis = db.components().insertProjectBranch(project);
db.components().insertSnapshot(branchWithAnalysis);
assertThat(underTest.selectByQuery(dbSession, query.get().build(), 0, 10))
.isEmpty();
}
@Test
public void selectByQuery_verify_order() {
Date firstDate = new Date(system2.now());
Date secondDate = new Date(system2.now());
Date thirdDate = new Date(system2.now());
ComponentDto project3 = db.components().insertPrivateProject(componentDto -> componentDto.setName("project3").setCreatedAt(thirdDate)).getMainBranchComponent();
ComponentDto project1 = db.components().insertPrivateProject(componentDto -> componentDto.setName("project1").setCreatedAt(firstDate)).getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject(componentDto -> componentDto.setName("project2").setCreatedAt(secondDate)).getMainBranchComponent();
Supplier<ComponentQuery.Builder> query = () -> ComponentQuery.builder()
.setQualifiers(PROJECT)
.setOnProvisionedOnly(true);
List<ComponentDto> results = underTest.selectByQuery(dbSession, query.get().build(), 0, 10);
assertThat(results)
.extracting(ComponentDto::uuid)
.containsExactly(
project1.uuid(),
project2.uuid(),
project3.uuid());
}
@Test
public void count_provisioned() {
db.components().insertPrivateProject().getMainBranchComponent();
db.components().insertProjectAndSnapshot(newPrivateProjectDto());
db.components().insertProjectAndSnapshot(ComponentTesting.newPortfolio());
Supplier<ComponentQuery.Builder> query = () -> ComponentQuery.builder().setOnProvisionedOnly(true);
assertThat(underTest.countByQuery(dbSession, query.get().setQualifiers(PROJECT).build())).isOne();
assertThat(underTest.countByQuery(dbSession, query.get().setQualifiers(Qualifiers.VIEW).build())).isZero();
assertThat(underTest.countByQuery(dbSession, query.get().setQualifiers(PROJECT, Qualifiers.VIEW).build())).isOne();
}
@Test
public void countByQuery_throws_IAE_if_too_many_component_keys() {
Set<String> keys = IntStream.range(0, 1_010).mapToObj(String::valueOf).collect(toSet());
ComponentQuery.Builder query = ComponentQuery.builder()
.setQualifiers(PROJECT)
.setComponentKeys(keys);
assertThatCountByQueryThrowsIAE(query, "Too many component keys in query");
}
@Test
public void countByQuery_throws_IAE_if_too_many_component_uuids() {
Set<String> uuids = IntStream.range(0, 1_010).mapToObj(String::valueOf).collect(toSet());
ComponentQuery.Builder query = ComponentQuery.builder()
.setQualifiers(PROJECT)
.setComponentUuids(uuids);
assertThatCountByQueryThrowsIAE(query, "Too many component UUIDs in query");
}
private void assertThatCountByQueryThrowsIAE(ComponentQuery.Builder query, String expectedMessage) {
ComponentQuery componentQuery = query.build();
assertThatThrownBy(() -> underTest.countByQuery(dbSession, componentQuery))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(expectedMessage);
}
@Test
public void selectByProjectUuid() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto removedProject = db.components().insertPrivateProject(p -> p.setEnabled(false)).getMainBranchComponent();
ComponentDto directory = db.components().insertComponent(newDirectory(project, "src"));
ComponentDto removedDirectory = db.components().insertComponent(newDirectory(project, "src2").setEnabled(false));
ComponentDto file = db.components().insertComponent(newFileDto(project, directory));
ComponentDto removedFile = db.components().insertComponent(newFileDto(project, directory).setEnabled(false));
assertThat(underTest.selectByBranchUuid(project.uuid(), dbSession))
.extracting(ComponentDto::uuid)
.containsExactlyInAnyOrder(project.uuid(), directory.uuid(), removedDirectory.uuid(),
file.uuid(),
removedFile.uuid());
}
@Test
public void update() {
ComponentDto mainBranch = db.components().insertPrivateProject("U1").getMainBranchComponent();
underTest.update(dbSession, new ComponentUpdateDto()
.setUuid(mainBranch.uuid())
.setBKey("key")
.setBCopyComponentUuid("copy")
.setBChanged(true)
.setBDescription("desc")
.setBEnabled(true)
.setBUuidPath("uuid_path")
.setBLanguage("lang")
.setBLongName("longName")
.setBName("name")
.setBPath("path")
.setBQualifier("qualifier"), "qualifier");
dbSession.commit();
Map<String, Object> row = selectBColumnsForUuid(mainBranch.uuid());
assertThat(row.get("bChanged")).isIn(true, /* for Oracle */1L, 1);
assertThat(row)
.containsEntry("bKey", "key")
.containsEntry("bCopyComponentUuid", "copy")
.containsEntry("bDescription", "desc");
assertThat(row.get("bEnabled")).isIn(true, /* for Oracle */1L, 1);
assertThat(row)
.containsEntry("bUuidPath", "uuid_path")
.containsEntry("bLanguage", "lang")
.containsEntry("bLongName", "longName")
.containsEntry("bName", "name")
.containsEntry("bPath", "path")
.containsEntry("bQualifier", "qualifier");
}
@Test
public void updateBEnabledToFalse() {
ComponentDto dto1 = newPrivateProjectDto("U1");
ComponentDto dto2 = newPrivateProjectDto("U2");
ComponentDto dto3 = newPrivateProjectDto("U3");
underTest.insert(dbSession, List.of(dto1, dto2, dto3), true);
underTest.updateBEnabledToFalse(dbSession, asList("U1", "U2"));
dbSession.commit();
Map<String, Object> row1 = selectBColumnsForUuid("U1");
assertThat(row1.get("bChanged")).isIn(true, /* for Oracle */1L, 1);
assertThat(row1)
.containsEntry("bKey", dto1.getKey())
.containsEntry("bCopyComponentUuid", dto1.getCopyComponentUuid())
.containsEntry("bDescription", dto1.description());
assertThat(row1.get("bEnabled")).isIn(false, /* for Oracle */0L, 0);
assertThat(row1)
.containsEntry("bUuidPath", dto1.getUuidPath())
.containsEntry("bLanguage", dto1.language())
.containsEntry("bLongName", dto1.longName())
.containsEntry("bName", dto1.name())
.containsEntry("bPath", dto1.path())
.containsEntry("bQualifier", dto1.qualifier());
Map<String, Object> row2 = selectBColumnsForUuid("U2");
assertThat(row2.get("bChanged")).isIn(true, /* for Oracle */1L, 1);
assertThat(row2)
.containsEntry("bKey", dto2.getKey())
.containsEntry("bCopyComponentUuid", dto2.getCopyComponentUuid())
.containsEntry("bDescription", dto2.description());
assertThat(row2.get("bEnabled")).isIn(false, /* for Oracle */0L, 0);
assertThat(row2)
.containsEntry("bUuidPath", dto2.getUuidPath())
.containsEntry("bLanguage", dto2.language())
.containsEntry("bLongName", dto2.longName())
.containsEntry("bName", dto2.name())
.containsEntry("bPath", dto2.path())
.containsEntry("bQualifier", dto2.qualifier());
Map<String, Object> row3 = selectBColumnsForUuid("U3");
assertThat(row3.get("bChanged")).isIn(false, /* for Oracle */0L, 0);
}
private Map<String, Object> selectBColumnsForUuid(String uuid) {
return db.selectFirst(
"select b_changed as \"bChanged\", deprecated_kee as \"bKey\", b_copy_component_uuid as \"bCopyComponentUuid\", b_description as \"bDescription\", " +
"b_enabled as \"bEnabled\", b_uuid_path as \"bUuidPath\", b_language as \"bLanguage\", b_long_name as \"bLongName\", b_name as \"bName\", " +
"b_path as \"bPath\", b_qualifier as \"bQualifier\" " +
"from components where uuid='" + uuid + "'");
}
@Test
public void selectByQuery_throws_IAE_if_too_many_component_keys() {
Set<String> keys = IntStream.range(0, 1_010).mapToObj(String::valueOf).collect(toSet());
ComponentQuery.Builder query = ComponentQuery.builder()
.setQualifiers(PROJECT)
.setComponentKeys(keys);
assertThatSelectByQueryThrowsIAE(query, "Too many component keys in query");
}
@Test
public void selectByQuery_throws_IAE_if_too_many_component_uuids() {
Set<String> uuids = IntStream.range(0, 1_010).mapToObj(String::valueOf).collect(toSet());
ComponentQuery.Builder query = ComponentQuery.builder()
.setQualifiers(PROJECT)
.setComponentUuids(uuids);
assertThatSelectByQueryThrowsIAE(query, "Too many component UUIDs in query");
}
private void assertThatSelectByQueryThrowsIAE(ComponentQuery.Builder query, String expectedMessage) {
ComponentQuery componentQuery = query.build();
assertThatThrownBy(() -> underTest.selectByQuery(dbSession, componentQuery, 0, Integer.MAX_VALUE))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(expectedMessage);
}
@Test
public void selectByQuery_with_paging_query_and_qualifiers() {
db.components().insertProjectAndSnapshot(newPrivateProjectDto().setName("aaaa-name"));
db.components().insertProjectAndSnapshot(newPortfolio());
for (int i = 9; i >= 1; i--) {
db.components().insertProjectAndSnapshot(newPrivateProjectDto().setName("project-" + i));
}
ComponentQuery query = ComponentQuery.builder().setNameOrKeyQuery("oJect").setQualifiers(PROJECT).build();
List<ComponentDto> result = underTest.selectByQuery(dbSession, query, 1, 3);
int count = underTest.countByQuery(dbSession, query);
assertThat(result).hasSize(3);
assertThat(count).isEqualTo(9);
assertThat(result).extracting(ComponentDto::name).containsExactly("project-2", "project-3", "project-4");
}
@Test
public void selectByQuery_should_not_return_branches() {
ComponentDto main = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(main);
assertThat(underTest.selectByQuery(dbSession, ALL_PROJECTS_COMPONENT_QUERY, 0, 2)).hasSize(1);
assertThat(underTest.selectByQuery(dbSession, ALL_PROJECTS_COMPONENT_QUERY, 0, 2).get(0).uuid()).isEqualTo(main.uuid());
}
@Test
public void countByQuery_should_not_include_branches() {
ComponentDto main = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(main);
assertThat(underTest.countByQuery(dbSession, ALL_PROJECTS_COMPONENT_QUERY)).isOne();
}
@Test
public void selectByQuery_name_with_special_characters() {
db.components().insertProjectAndSnapshot(newPrivateProjectDto().setName("project-\\_%/-name"));
ComponentQuery query = ComponentQuery.builder().setNameOrKeyQuery("-\\_%/-").setQualifiers(PROJECT).build();
List<ComponentDto> result = underTest.selectByQuery(dbSession, query, 0, 10);
assertThat(result).hasSize(1);
assertThat(result.get(0).name()).isEqualTo("project-\\_%/-name");
}
@Test
public void selectByQuery_key_with_special_characters() {
db.components().insertProjectAndSnapshot(newPrivateProjectDto().setKey("project-_%-key"));
db.components().insertProjectAndSnapshot(newPrivateProjectDto().setKey("project-key-that-does-not-match"));
ComponentQuery query = ComponentQuery.builder().setNameOrKeyQuery("project-_%-key").setQualifiers(PROJECT).build();
List<ComponentDto> result = underTest.selectByQuery(dbSession, query, 0, 10);
assertThat(result).hasSize(1);
assertThat(result.get(0).getKey()).isEqualTo("project-_%-key");
}
@Test
public void selectByQuery_on_key_partial_match_case_insensitive() {
db.components().insertProjectAndSnapshot(newPrivateProjectDto().setKey("project-key"));
ComponentQuery query = ComponentQuery.builder()
.setNameOrKeyQuery("JECT-K")
.setPartialMatchOnKey(true)
.setQualifiers(PROJECT).build();
List<ComponentDto> result = underTest.selectByQuery(dbSession, query, 0, 10);
assertThat(result).hasSize(1);
assertThat(result.get(0).getKey()).isEqualTo("project-key");
}
@Test
public void selectByQuery_filter_last_analysis_date() {
long aLongTimeAgo = 1_000_000_000L;
long recentTime = 3_000_000_000L;
ComponentDto oldProject = db.components().insertPrivateProject().getMainBranchComponent();
db.components().insertSnapshot(oldProject, s -> s.setCreatedAt(aLongTimeAgo));
ComponentDto recentProject = db.components().insertPrivateProject().getMainBranchComponent();
db.components().insertSnapshot(recentProject, s -> s.setCreatedAt(recentTime).setLast(true));
db.components().insertSnapshot(recentProject, s -> s.setCreatedAt(aLongTimeAgo).setLast(false));
// before date on main branch
assertThat(selectProjectUuidsByQuery(q -> q.setAnalyzedBefore(recentTime)))
.containsExactlyInAnyOrder(oldProject.uuid());
assertThat(selectProjectUuidsByQuery(q -> q.setAnalyzedBefore(aLongTimeAgo)))
.isEmpty();
assertThat(selectProjectUuidsByQuery(q -> q.setAnalyzedBefore(recentTime + 1_000L)))
.containsExactlyInAnyOrder(oldProject.uuid(), recentProject.uuid());
// before date on any branch
assertThat(selectProjectUuidsByQuery(q -> q.setAnyBranchAnalyzedBefore(recentTime)))
.containsExactlyInAnyOrder(oldProject.uuid());
assertThat(selectProjectUuidsByQuery(q -> q.setAnyBranchAnalyzedBefore(aLongTimeAgo)))
.isEmpty();
assertThat(selectProjectUuidsByQuery(q -> q.setAnyBranchAnalyzedBefore(recentTime + 1_000L)))
.containsExactlyInAnyOrder(oldProject.uuid(), recentProject.uuid());
// after date
assertThat(selectProjectUuidsByQuery(q -> q.setAnyBranchAnalyzedAfter(recentTime - 1_000L)))
.containsExactlyInAnyOrder(recentProject.uuid());
assertThat(selectProjectUuidsByQuery(q -> q.setAnyBranchAnalyzedAfter(recentTime + 1_000L)))
.isEmpty();
assertThat(selectProjectUuidsByQuery(q -> q.setAnyBranchAnalyzedAfter(aLongTimeAgo)))
.containsExactlyInAnyOrder(oldProject.uuid(), recentProject.uuid());
}
@Test
public void selectByQuery_filter_last_analysis_date_on_non_main_branches() {
long aLongTimeAgo = 1_000_000_000L;
long recentTime = 3_000_000_000L;
// project with only a non-main and old analyzed branch
ProjectData oldProjectData = db.components().insertPublicProject();
ComponentDto oldProject = oldProjectData.getMainBranchComponent();
ComponentDto oldProjectBranch = db.components().insertProjectBranch(oldProject, newBranchDto(oldProjectData.projectUuid(), BRANCH).setBranchType(BRANCH));
db.components().insertSnapshot(oldProjectBranch, s -> s.setLast(true).setCreatedAt(aLongTimeAgo));
// project with only a old main branch and a recent non-main branch
ProjectData recentProjectData = db.components().insertPublicProject();
ComponentDto recentProject = recentProjectData.getMainBranchComponent();
ComponentDto recentProjectBranch = db.components().insertProjectBranch(recentProject, newBranchDto(recentProjectData.projectUuid(), BRANCH).setBranchType(BRANCH));
db.components().insertSnapshot(recentProjectBranch, s -> s.setCreatedAt(recentTime).setLast(true));
db.components().insertSnapshot(recentProjectBranch, s -> s.setCreatedAt(aLongTimeAgo).setLast(false));
// before date on main branch only
assertThat(selectProjectUuidsByQuery(q -> q.setAnalyzedBefore(recentTime))).isEmpty();
assertThat(selectProjectUuidsByQuery(q -> q.setAnalyzedBefore(aLongTimeAgo))).isEmpty();
assertThat(selectProjectUuidsByQuery(q -> q.setAnalyzedBefore(recentTime + 1_000L))).isEmpty();
// before date on any branch
assertThat(selectProjectUuidsByQuery(q -> q.setAnyBranchAnalyzedBefore(recentTime)))
.containsExactlyInAnyOrder(oldProject.uuid());
assertThat(selectProjectUuidsByQuery(q -> q.setAnyBranchAnalyzedBefore(aLongTimeAgo)))
.isEmpty();
assertThat(selectProjectUuidsByQuery(q -> q.setAnyBranchAnalyzedBefore(recentTime + 1_000L)))
.containsExactlyInAnyOrder(oldProject.uuid(), recentProject.uuid());
// after date
assertThat(selectProjectUuidsByQuery(q -> q.setAnyBranchAnalyzedAfter(recentTime - 1_000L)))
.containsExactlyInAnyOrder(recentProject.uuid());
assertThat(selectProjectUuidsByQuery(q -> q.setAnyBranchAnalyzedAfter(recentTime + 1_000L)))
.isEmpty();
assertThat(selectProjectUuidsByQuery(q -> q.setAnyBranchAnalyzedAfter(aLongTimeAgo)))
.containsExactlyInAnyOrder(oldProject.uuid(), recentProject.uuid());
}
@Test
public void selectByQuery_filter_last_analysisof_all_branches_before() {
long aLongTimeAgo = 1_000_000_000L;
long recentTime = 3_000_000_000L;
// project with only a non-main and old analyzed branch
ProjectData oldProjectData = db.components().insertPublicProject();
ComponentDto oldProject = oldProjectData.getMainBranchComponent();
ComponentDto oldProjectBranch = db.components().insertProjectBranch(oldProject, newBranchDto(oldProjectData.projectUuid(), BRANCH).setBranchType(BRANCH));
db.components().insertSnapshot(oldProjectBranch, s -> s.setLast(true).setCreatedAt(aLongTimeAgo));
// project with only a old main branch and a recent non-main branch
ProjectData recentProjectData = db.components().insertPublicProject();
ComponentDto recentProject = recentProjectData.getMainBranchComponent();
ComponentDto recentProjectBranch = db.components().insertProjectBranch(recentProject, newBranchDto(recentProjectData.projectUuid(), BRANCH).setBranchType(BRANCH));
db.components().insertSnapshot(recentProjectBranch, s -> s.setCreatedAt(recentTime).setLast(true));
db.components().insertSnapshot(recentProjectBranch, s -> s.setCreatedAt(aLongTimeAgo).setLast(false));
assertThat(selectProjectUuidsByQuery(q -> q.setAllBranchesAnalyzedBefore(recentTime + 1_000L))).containsOnly(oldProject.uuid(), recentProject.uuid());
assertThat(selectProjectUuidsByQuery(q -> q.setAllBranchesAnalyzedBefore(aLongTimeAgo))).isEmpty();
assertThat(selectProjectUuidsByQuery(q -> q.setAllBranchesAnalyzedBefore(aLongTimeAgo + 1_000L))).containsOnly(oldProject.uuid());
}
@Test
public void selectByQuery_filter_last_analysisof_all_branches_before_for_portfolios() {
long aLongTimeAgo = 1_000_000_000L;
long recentTime = 3_000_000_000L;
// old portfolio
ComponentDto oldPortfolio = db.components().insertPublicPortfolio();
db.components().insertSnapshot(oldPortfolio, s -> s.setLast(true).setCreatedAt(aLongTimeAgo));
// recent portfolio
ComponentDto recentPortfolio = db.components().insertPublicPortfolio();
db.components().insertSnapshot(recentPortfolio, s -> s.setCreatedAt(recentTime).setLast(true));
assertThat(selectPortfolioUuidsByQuery(q -> q.setAllBranchesAnalyzedBefore(recentTime + 1_000_000L))).containsOnly(oldPortfolio.uuid(), recentPortfolio.uuid());
assertThat(selectPortfolioUuidsByQuery(q -> q.setAllBranchesAnalyzedBefore(aLongTimeAgo))).isEmpty();
assertThat(selectPortfolioUuidsByQuery(q -> q.setAllBranchesAnalyzedBefore(aLongTimeAgo + 1_000L))).containsOnly(oldPortfolio.uuid());
}
@Test
public void selectByQuery_filter_created_at() {
ComponentDto project1 = db.components().insertPrivateProject(p -> p.setCreatedAt(parseDate("2018-02-01"))).getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject(p -> p.setCreatedAt(parseDate("2018-06-01"))).getMainBranchComponent();
assertThat(selectProjectUuidsByQuery(q -> q.setCreatedAfter(parseDate("2017-12-01"))))
.containsExactlyInAnyOrder(project1.uuid(), project2.uuid());
assertThat(selectProjectUuidsByQuery(q -> q.setCreatedAfter(parseDate("2018-02-20"))))
.containsExactlyInAnyOrder(project2.uuid());
assertThat(selectProjectUuidsByQuery(q -> q.setCreatedAfter(parseDate("2019-01-01"))))
.isEmpty();
}
private List<String> selectProjectUuidsByQuery(Consumer<ComponentQuery.Builder> query) {
return selectUuidsByQuery(PROJECT, query);
}
private List<String> selectPortfolioUuidsByQuery(Consumer<ComponentQuery.Builder> query) {
return selectUuidsByQuery(VIEW, query);
}
private List<String> selectUuidsByQuery(String qualifier, Consumer<ComponentQuery.Builder> query) {
ComponentQuery.Builder builder = ComponentQuery.builder().setQualifiers(qualifier);
query.accept(builder);
return underTest.selectByQuery(dbSession, builder.build(), 0, 5)
.stream()
.map(ComponentDto::uuid)
.toList();
}
@Test
public void selectByQuery_filter_on_visibility() {
db.components().insertPrivateProject(p -> p.setKey("private-key")).getMainBranchComponent();
db.components().insertPublicProject(p -> p.setKey("public-key")).getMainBranchComponent();
ComponentQuery privateProjectsQuery = ComponentQuery.builder().setPrivate(true).setQualifiers(PROJECT).build();
ComponentQuery publicProjectsQuery = ComponentQuery.builder().setPrivate(false).setQualifiers(PROJECT).build();
ComponentQuery allProjectsQuery = ComponentQuery.builder().setPrivate(null).setQualifiers(PROJECT).build();
assertThat(underTest.selectByQuery(dbSession, privateProjectsQuery, 0, 10)).extracting(ComponentDto::getKey).containsExactly("private-key");
assertThat(underTest.selectByQuery(dbSession, publicProjectsQuery, 0, 10)).extracting(ComponentDto::getKey).containsExactly("public-key");
assertThat(underTest.selectByQuery(dbSession, allProjectsQuery, 0, 10)).extracting(ComponentDto::getKey).containsOnly("public-key", "private-key");
}
@Test
public void selectByQuery_on_empty_list_of_component_key() {
db.components().insertPrivateProject().getMainBranchComponent();
ComponentQuery dbQuery = ComponentQuery.builder().setQualifiers(PROJECT).setComponentKeys(emptySet()).build();
List<ComponentDto> result = underTest.selectByQuery(dbSession, dbQuery, 0, 10);
int count = underTest.countByQuery(dbSession, dbQuery);
assertThat(result).isEmpty();
assertThat(count).isZero();
}
@Test
public void selectByQuery_on_component_keys() {
ComponentDto sonarqube = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto jdk8 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto cLang = db.components().insertPrivateProject().getMainBranchComponent();
ComponentQuery query = ComponentQuery.builder().setQualifiers(PROJECT)
.setComponentKeys(newHashSet(sonarqube.getKey(), jdk8.getKey())).build();
List<ComponentDto> result = underTest.selectByQuery(dbSession, query, 0, 10);
assertThat(result).hasSize(2).extracting(ComponentDto::getKey)
.containsExactlyInAnyOrder(sonarqube.getKey(), jdk8.getKey())
.doesNotContain(cLang.getKey());
}
@Test
public void selectByQuery_on_empty_list_of_component_uuids() {
db.components().insertPrivateProject().getMainBranchComponent();
ComponentQuery dbQuery = ComponentQuery.builder().setQualifiers(PROJECT).setComponentUuids(emptySet()).build();
List<ComponentDto> result = underTest.selectByQuery(dbSession, dbQuery, 0, 10);
int count = underTest.countByQuery(dbSession, dbQuery);
assertThat(result).isEmpty();
assertThat(count).isZero();
}
@Test
public void selectByQuery_on_component_uuids() {
ComponentDto sonarqube = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto jdk8 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto cLang = db.components().insertPrivateProject().getMainBranchComponent();
ComponentQuery query = ComponentQuery.builder().setQualifiers(PROJECT)
.setComponentUuids(newHashSet(sonarqube.uuid(), jdk8.uuid())).build();
List<ComponentDto> result = underTest.selectByQuery(dbSession, query, 0, 10);
assertThat(result).hasSize(2).extracting(ComponentDto::uuid)
.containsOnlyOnce(sonarqube.uuid(), jdk8.uuid())
.doesNotContain(cLang.uuid());
}
@Test
public void selectAncestors() {
// project -> dir -> file
ComponentDto project = newPrivateProjectDto(PROJECT_UUID);
db.components().insertProjectAndSnapshot(project);
ComponentDto dir = newDirectory(project, DIR_UUID, "path");
db.components().insertComponent(dir);
ComponentDto file = newFileDto(dir, null, FILE_1_UUID);
db.components().insertComponent(file);
db.commit();
// ancestors of root
List<ComponentDto> ancestors = underTest.selectAncestors(dbSession, project);
assertThat(ancestors).isEmpty();
// ancestors of dir
ancestors = underTest.selectAncestors(dbSession, dir);
assertThat(ancestors).extracting("uuid").containsExactly(PROJECT_UUID);
// ancestors of file
ancestors = underTest.selectAncestors(dbSession, file);
assertThat(ancestors).extracting("uuid").containsExactly(PROJECT_UUID, DIR_UUID);
}
@Test
public void select_children() {
ComponentDto project = newPrivateProjectDto(PROJECT_UUID);
db.components().insertProjectAndSnapshot(project);
ComponentDto dir = newDirectory(project, DIR_UUID, "path");
db.components().insertComponent(dir);
ComponentDto fileInProject = newFileDto(project, null, FILE_1_UUID).setKey("file-key-1").setName("File One");
db.components().insertComponent(fileInProject);
ComponentDto file1InDir = newFileDto(dir, null, FILE_2_UUID).setKey("file-key-2").setName("File Two");
db.components().insertComponent(file1InDir);
ComponentDto file2InDir = newFileDto(dir, null, FILE_3_UUID).setKey("file-key-3").setName("File Three");
db.components().insertComponent(file2InDir);
db.commit();
// test children of root
assertThat(underTest.selectChildren(dbSession, project.uuid(), List.of(project))).extracting("uuid").containsOnly(FILE_1_UUID, DIR_UUID);
// test children of intermediate component (dir here)
assertThat(underTest.selectChildren(dbSession, project.uuid(), List.of(dir))).extracting("uuid").containsOnly(FILE_2_UUID, FILE_3_UUID);
// test children of leaf component (file here)
assertThat(underTest.selectChildren(dbSession, project.uuid(), List.of(fileInProject))).isEmpty();
// test children of 2 components
assertThat(underTest.selectChildren(dbSession, project.uuid(), List.of(project, dir))).extracting("uuid").containsOnly(FILE_1_UUID, DIR_UUID, FILE_2_UUID, FILE_3_UUID);
}
@Test
public void select_descendants_with_children_strategy() {
// project has 2 children: dir and file 1. Other files are part of dir.
ComponentDto project = newPrivateProjectDto(PROJECT_UUID);
db.components().insertProjectAndSnapshot(project);
ComponentDto dir = newDirectory(project, DIR_UUID, "dir");
db.components().insertComponent(dir);
ComponentDto fileInProject = newFileDto(project, null, FILE_1_UUID).setKey("file-key-1").setName("File One");
db.components().insertComponent(fileInProject);
ComponentDto file1InDir = newFileDto(project, dir, FILE_2_UUID).setKey("file-key-2").setName("File Two");
db.components().insertComponent(file1InDir);
ComponentDto file2InDir = newFileDto(project, dir, FILE_3_UUID).setKey("file-key-3").setName("File Three");
db.components().insertComponent(file2InDir);
db.commit();
// test children of root
ComponentTreeQuery query = newTreeQuery(PROJECT_UUID).build();
List<ComponentDto> children = underTest.selectDescendants(dbSession, query);
assertThat(children).extracting("uuid").containsOnly(FILE_1_UUID, DIR_UUID);
// test children of root, filtered by qualifier
query = newTreeQuery(PROJECT_UUID).setQualifiers(asList(Qualifiers.DIRECTORY)).build();
children = underTest.selectDescendants(dbSession, query);
assertThat(children).extracting("uuid").containsOnly(DIR_UUID);
// test children of intermediate component (dir here), default ordering by
query = newTreeQuery(DIR_UUID).build();
assertThat(underTest.selectDescendants(dbSession, query)).extracting("uuid").containsOnly(FILE_2_UUID, FILE_3_UUID);
// test children of leaf component (file here)
query = newTreeQuery(FILE_1_UUID).build();
assertThat(underTest.selectDescendants(dbSession, query)).isEmpty();
// test children of root, matching name
query = newTreeQuery(PROJECT_UUID).setNameOrKeyQuery("One").build();
assertThat(underTest.selectDescendants(dbSession, query)).extracting("uuid").containsOnly(FILE_1_UUID);
// test children of root, matching case-insensitive name
query = newTreeQuery(PROJECT_UUID).setNameOrKeyQuery("OnE").build();
assertThat(underTest.selectDescendants(dbSession, query)).extracting("uuid").containsOnly(FILE_1_UUID);
// test children of root, matching key
query = newTreeQuery(PROJECT_UUID).setNameOrKeyQuery("file-key-1").build();
assertThat(underTest.selectDescendants(dbSession, query)).extracting("uuid").containsOnly(FILE_1_UUID);
// test children of root, without matching name nor key
query = newTreeQuery(PROJECT_UUID).setNameOrKeyQuery("does-not-exist").build();
assertThat(underTest.selectDescendants(dbSession, query)).isEmpty();
// test children of intermediate component (dir here), matching name
query = newTreeQuery(DIR_UUID).setNameOrKeyQuery("Two").build();
assertThat(underTest.selectDescendants(dbSession, query)).extracting("uuid").containsOnly(FILE_2_UUID);
// test children of intermediate component (dir here), without matching name
query = newTreeQuery(DIR_UUID).setNameOrKeyQuery("does-not-exist").build();
assertThat(underTest.selectDescendants(dbSession, query)).isEmpty();
// test children of leaf component (file here)
query = newTreeQuery(FILE_1_UUID).build();
assertThat(underTest.selectDescendants(dbSession, query)).isEmpty();
// test children of leaf component (file here), matching name
query = newTreeQuery(FILE_1_UUID).setNameOrKeyQuery("Foo").build();
assertThat(underTest.selectDescendants(dbSession, query)).isEmpty();
// test filtering by scope
query = newTreeQuery(project.uuid()).setScopes(asList(Scopes.FILE)).build();
assertThat(underTest.selectDescendants(dbSession, query))
.extracting(ComponentDto::uuid)
.containsExactlyInAnyOrder(fileInProject.uuid());
query = newTreeQuery(project.uuid()).setScopes(asList(Scopes.DIRECTORY)).build();
assertThat(underTest.selectDescendants(dbSession, query))
.extracting(ComponentDto::uuid)
.containsExactlyInAnyOrder(dir.uuid());
}
@Test
public void select_descendants_with_leaves_strategy() {
ComponentDto project = newPrivateProjectDto(PROJECT_UUID);
db.components().insertProjectAndSnapshot(project);
db.components().insertComponent(newDirectory(project, "dir-1-uuid", "dir"));
db.components().insertComponent(newFileDto(project, null, "file-1-uuid"));
db.components().insertComponent(newFileDto(project, null, "file-2-uuid"));
db.commit();
ComponentTreeQuery query = newTreeQuery(PROJECT_UUID).setStrategy(LEAVES).build();
List<ComponentDto> result = underTest.selectDescendants(dbSession, query);
assertThat(result).extracting("uuid").containsOnly("file-1-uuid", "file-2-uuid", "dir-1-uuid");
}
@Test
public void select_descendants_returns_empty_list_if_base_component_does_not_exist() {
ComponentTreeQuery query = newTreeQuery(PROJECT_UUID).setStrategy(CHILDREN).build();
List<ComponentDto> result = underTest.selectDescendants(dbSession, query);
assertThat(result).isEmpty();
}
@Test
public void select_descendants_of_a_view_and_filter_by_name() {
ComponentDto view = ComponentTesting.newPortfolio(A_VIEW_UUID);
db.components().insertPortfolioAndSnapshot(view);
// one subview
ComponentDto subView = ComponentTesting.newSubPortfolio(view, "subview-uuid", "subview-key").setName("subview name");
db.components().insertComponent(subView);
// one project and its copy linked to the view
ComponentDto project = newPrivateProjectDto(PROJECT_UUID).setName("project name");
db.components().insertProjectAndSnapshot(project);
db.components().insertComponent(newProjectCopy("project-copy-uuid", project, view));
ComponentTreeQuery dbQuery = newTreeQuery(A_VIEW_UUID).setNameOrKeyQuery("name").setStrategy(CHILDREN).build();
List<ComponentDto> components = underTest.selectDescendants(dbSession, dbQuery);
assertThat(components).extracting("uuid").containsOnly("project-copy-uuid", "subview-uuid");
}
@Test
public void setPrivateForBranchUuid_updates_private_column_to_specified_value_for_all_rows_with_specified_projectUuid() {
String uuid1 = "uuid1";
String uuid2 = "uuid2";
String[] uuids = {
db.components().insertComponent(newPrivateProjectDto().setBranchUuid(uuid1).setPrivate(true)).uuid(),
db.components().insertComponent(newPrivateProjectDto().setBranchUuid(uuid1).setPrivate(false)).uuid(),
db.components().insertComponent(newPrivateProjectDto().setBranchUuid(uuid2).setPrivate(true)).uuid(),
db.components().insertComponent(newPrivateProjectDto().setBranchUuid(uuid2).setPrivate(false)).uuid(),
db.components().insertComponent(newPrivateProjectDto().setBranchUuid("foo").setPrivate(false)).uuid(),
};
underTest.setPrivateForBranchUuidWithoutAudit(db.getSession(), uuid1, true);
assertThat(privateFlagOfUuid(uuids[0])).isTrue();
assertThat(privateFlagOfUuid(uuids[1])).isTrue();
assertThat(privateFlagOfUuid(uuids[2])).isTrue();
assertThat(privateFlagOfUuid(uuids[3])).isFalse();
assertThat(privateFlagOfUuid(uuids[4])).isFalse();
underTest.setPrivateForBranchUuidWithoutAudit(db.getSession(), uuid1, false);
assertThat(privateFlagOfUuid(uuids[0])).isFalse();
assertThat(privateFlagOfUuid(uuids[1])).isFalse();
assertThat(privateFlagOfUuid(uuids[2])).isTrue();
assertThat(privateFlagOfUuid(uuids[3])).isFalse();
assertThat(privateFlagOfUuid(uuids[4])).isFalse();
underTest.setPrivateForBranchUuidWithoutAudit(db.getSession(), uuid2, false);
assertThat(privateFlagOfUuid(uuids[0])).isFalse();
assertThat(privateFlagOfUuid(uuids[1])).isFalse();
assertThat(privateFlagOfUuid(uuids[2])).isFalse();
assertThat(privateFlagOfUuid(uuids[3])).isFalse();
assertThat(privateFlagOfUuid(uuids[4])).isFalse();
underTest.setPrivateForBranchUuidWithoutAudit(db.getSession(), uuid2, true);
assertThat(privateFlagOfUuid(uuids[0])).isFalse();
assertThat(privateFlagOfUuid(uuids[1])).isFalse();
assertThat(privateFlagOfUuid(uuids[2])).isTrue();
assertThat(privateFlagOfUuid(uuids[3])).isTrue();
assertThat(privateFlagOfUuid(uuids[4])).isFalse();
}
@Test
public void existAnyOfComponentsWithQualifiers() {
ComponentDto projectDto = db.components().insertComponent(newPrivateProjectDto());
ComponentDto view = db.components().insertComponent(newPortfolio());
ComponentDto subview = db.components().insertComponent(newSubPortfolio(view));
ComponentDto app = db.components().insertComponent(newApplication());
assertThat(underTest.existAnyOfComponentsWithQualifiers(db.getSession(), emptyList(), newHashSet(APP, VIEW, SUBVIEW))).isFalse();
assertThat(underTest.existAnyOfComponentsWithQualifiers(db.getSession(), singletonList("not-existing-component"), newHashSet(APP, VIEW, SUBVIEW))).isFalse();
assertThat(underTest.existAnyOfComponentsWithQualifiers(db.getSession(), singletonList(projectDto.getKey()), newHashSet(APP, VIEW, SUBVIEW))).isFalse();
assertThat(underTest.existAnyOfComponentsWithQualifiers(db.getSession(), singletonList(projectDto.getKey()), newHashSet(PROJECT))).isTrue();
assertThat(underTest.existAnyOfComponentsWithQualifiers(db.getSession(), singletonList(view.getKey()), newHashSet(APP, VIEW, SUBVIEW))).isTrue();
assertThat(underTest.existAnyOfComponentsWithQualifiers(db.getSession(), singletonList(subview.getKey()), newHashSet(APP, VIEW, SUBVIEW))).isTrue();
assertThat(underTest.existAnyOfComponentsWithQualifiers(db.getSession(), singletonList(app.getKey()), newHashSet(APP, VIEW, SUBVIEW))).isTrue();
assertThat(underTest.existAnyOfComponentsWithQualifiers(db.getSession(), newHashSet(projectDto.getKey(), view.getKey()), newHashSet(APP, VIEW, SUBVIEW))).isTrue();
}
@Test
public void selectComponentsFromBranchesThatHaveOpenIssues() {
final ProjectDto project = db.components().insertPrivateProject(b -> b.setName("foo")).getProjectDto();
ComponentDto branch1 = db.components().insertProjectBranch(project, ComponentTesting.newBranchDto(project.getUuid(), BRANCH).setKey("branch1"));
ComponentDto fileBranch1 = db.components().insertComponent(ComponentTesting.newFileDto(branch1));
ComponentDto branch2 = db.components().insertProjectBranch(project, ComponentTesting.newBranchDto(project.getUuid(), BRANCH).setKey("branch2"));
ComponentDto fileBranch2 = db.components().insertComponent(ComponentTesting.newFileDto(branch2));
RuleDto rule = db.rules().insert();
db.issues().insert(new IssueDto().setKee("i1").setComponent(fileBranch1).setProject(branch1).setRule(rule).setStatus(STATUS_CONFIRMED));
db.issues().insert(new IssueDto().setKee("i2").setComponent(fileBranch2).setProject(branch2).setRule(rule).setStatus(STATUS_CLOSED));
db.issues().insert(new IssueDto().setKee("i3").setComponent(fileBranch2).setProject(branch2).setRule(rule).setStatus(STATUS_OPEN));
List<KeyWithUuidDto> result = underTest.selectComponentsFromBranchesThatHaveOpenIssues(db.getSession(), of(branch1.uuid(), branch2.uuid()));
assertThat(result).extracting(KeyWithUuidDto::uuid).contains(fileBranch2.uuid());
}
@Test
public void selectComponentsFromBranchesThatHaveOpenIssues_returns_nothing_if_no_open_issues_in_sibling_branches() {
final ProjectDto project = db.components().insertPrivateProject(b -> b.setName("foo")).getProjectDto();
ComponentDto branch1 = db.components().insertProjectBranch(project, ComponentTesting.newBranchDto(project.getUuid(), BRANCH).setKey("branch1"));
ComponentDto fileBranch1 = db.components().insertComponent(ComponentTesting.newFileDto(branch1));
RuleDto rule = db.rules().insert();
db.issues().insert(new IssueDto().setKee("i").setComponent(fileBranch1).setProject(branch1).setRule(rule).setStatus(STATUS_CLOSED));
List<KeyWithUuidDto> result = underTest.selectComponentsFromBranchesThatHaveOpenIssues(db.getSession(), singleton(branch1.uuid()));
assertThat(result).isEmpty();
}
@Test
public void setPrivateForBranchUuid_auditPersisterIsCalled() {
underTestWithAuditPersister.setPrivateForBranchUuid(dbSession, "anyUuid", false, "key", APP, "appName");
verify(auditPersister).updateComponentVisibility(any(DbSession.class), any(ComponentNewValue.class));
}
@Test
public void setPrivateForBranchUuidWithoutAudit_auditPersisterIsNotCalled() {
underTestWithAuditPersister.setPrivateForBranchUuidWithoutAudit(dbSession, "anyUuid", false);
verifyNoInteractions(auditPersister);
}
@Test
public void update_auditPersisterIsCalled() {
ComponentUpdateDto app = new ComponentUpdateDto().setUuid("uuid");
app.setBQualifier(APP);
underTestWithAuditPersister.update(dbSession, app, APP);
verify(auditPersister).updateComponent(any(DbSession.class), any(ComponentNewValue.class));
}
@Test
public void insert_auditPersisterIsCalled() {
ComponentDto app = ComponentTesting.newApplication();
underTestWithAuditPersister.insert(dbSession, app, true);
verify(auditPersister).addComponent(any(DbSession.class), any(ComponentNewValue.class));
}
@Test
public void insert_branch_auditPersisterIsNotCalled() {
ProjectData projectData = db.components().insertPublicProject();
ComponentDto project = projectData.getMainBranchComponent();
BranchDto branch = newBranchDto(projectData.projectUuid(), BRANCH);
ComponentDto branchComponent = newBranchComponent(project, branch);
underTestWithAuditPersister.insert(dbSession, branchComponent, false);
verifyNoInteractions(auditPersister);
}
@Test
public void selectByKeyCaseInsensitive_shouldFindProject_whenCaseIsDifferent() {
String projectKey = randomAlphabetic(5).toLowerCase();
db.components().insertPrivateProject(c -> c.setKey(projectKey)).getMainBranchComponent();
List<ComponentDto> result = underTest.selectByKeyCaseInsensitive(db.getSession(), projectKey.toUpperCase());
assertThat(result).isNotEmpty();
assertThat(result.get(0).getKey()).isEqualTo(projectKey);
}
@Test
public void selectByKeyCaseInsensitive_should_not_match_non_main_branch() {
String projectKey = randomAlphabetic(5).toLowerCase();
ProjectDto project = db.components().insertPrivateProject(c -> c.setKey(projectKey)).getProjectDto();
BranchDto projectBranch = db.components().insertProjectBranch(project);
ComponentDto file = db.components().insertFile(projectBranch);
List<ComponentDto> result = underTest.selectByKeyCaseInsensitive(db.getSession(), file.getKey());
assertThat(result).isEmpty();
}
@Test
public void selectByKeyCaseInsensitive_shouldNotFindProject_whenKeyIsDifferent() {
String projectKey = randomAlphabetic(5).toLowerCase();
db.components().insertPrivateProject(c -> c.setKey(projectKey)).getMainBranchComponent();
List<ComponentDto> result = underTest.selectByKeyCaseInsensitive(db.getSession(), projectKey + randomAlphabetic(1));
assertThat(result).isEmpty();
}
private boolean privateFlagOfUuid(String uuid) {
return underTest.selectByUuid(db.getSession(), uuid).get().isPrivate();
}
private static Set<String> shuffleWithNonExistentUuids(String... uuids) {
return Stream.concat(
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(i -> randomAlphabetic(9)),
Arrays.stream(uuids))
.collect(toSet());
}
private void insertMeasure(double value, ComponentDto componentDto, MetricDto metric) {
db.measures().insertLiveMeasure(componentDto, metric, m -> m.setValue(value));
}
private static <T> Consumer<T> defaults() {
return t -> {
};
}
}
| 93,746 | 50.255878 | 178 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/component/ComponentKeyUpdaterDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.component;
import com.google.common.base.Strings;
import java.util.List;
import org.assertj.core.groups.Tuple;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.audit.model.ComponentKeyNewValue;
import org.sonar.db.project.ProjectDto;
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.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.sonar.db.component.BranchType.PULL_REQUEST;
import static org.sonar.db.component.ComponentKeyUpdaterDao.computeNewKey;
import static org.sonar.db.component.ComponentTesting.newDirectory;
import static org.sonar.db.component.ComponentTesting.newFileDto;
public class ComponentKeyUpdaterDaoIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private final AuditPersister auditPersister = mock(AuditPersister.class);
private final DbClient dbClient = db.getDbClient();
private final DbSession dbSession = db.getSession();
private final ComponentKeyUpdaterDao underTest = db.getDbClient().componentKeyUpdaterDao();
private final ComponentKeyUpdaterDao underTestWithAuditPersister = new ComponentKeyUpdaterDao(auditPersister);
@Test
public void updateKey_changes_the_key_of_tree_of_components() {
ProjectData projectData = populateSomeData();
underTest.updateKey(dbSession, projectData.getProjectDto().getUuid(), "org.struts:struts", "struts:core");
dbSession.commit();
assertThat(db.select("select uuid as \"UUID\", kee as \"KEE\" from components"))
.extracting(t -> t.get("UUID"), t -> t.get("KEE"))
.containsOnly(
Tuple.tuple("A", "struts:core"),
Tuple.tuple("B", "struts:core:/src/org/struts"),
Tuple.tuple("C", "struts:core:/src/org/struts/RequestContext.java"),
Tuple.tuple("D", "foo:struts-core"));
}
@Test
public void updateKey_updates_disabled_components() {
ProjectData projectData = db.components().insertPrivateProject(p -> p.setKey("my_project"));
ComponentDto mainBranch = projectData.getMainBranchComponent();
ComponentDto directory = db.components().insertComponent(
newDirectory(mainBranch, "B")
.setKey("my_project:directory"));
db.components().insertComponent(newFileDto(mainBranch, directory).setKey("my_project:directory/file"));
ComponentDto inactiveDirectory = db.components().insertComponent(newDirectory(mainBranch, "/inactive_directory").setKey("my_project:inactive_directory").setEnabled(false));
db.components().insertComponent(newFileDto(mainBranch, inactiveDirectory).setKey("my_project:inactive_directory/file").setEnabled(false));
underTest.updateKey(dbSession, projectData.projectUuid(), "my_project", "your_project");
dbSession.commit();
List<ComponentDto> result = dbClient.componentDao().selectByBranchUuid(mainBranch.uuid(), dbSession);
assertThat(result)
.hasSize(5)
.extracting(ComponentDto::getKey)
.containsOnlyOnce("your_project", "your_project:directory", "your_project:directory/file", "your_project:inactive_directory", "your_project:inactive_directory/file");
}
@Test
public void updateKey_updates_branches_too() {
ProjectData projectData = db.components().insertPublicProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
String branchName = randomAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName));
db.components().insertComponent(newFileDto(branch, mainBranch.uuid()));
db.components().insertComponent(newFileDto(branch, mainBranch.uuid()));
int prComponentCount = 3;
String oldProjectKey = mainBranch.getKey();
assertThat(dbClient.componentDao().selectByBranchUuid(mainBranch.uuid(), dbSession)).hasSize(1);
assertThat(dbClient.componentDao().selectByBranchUuid(branch.uuid(), dbSession)).hasSize(prComponentCount);
String newProjectKey = "newKey";
underTest.updateKey(dbSession, projectData.projectUuid(), projectData.projectKey(), newProjectKey);
assertThat(dbClient.componentDao().selectByKey(dbSession, oldProjectKey)).isEmpty();
assertThat(dbClient.componentDao().selectByKey(dbSession, newProjectKey)).isPresent();
assertThat(dbClient.componentDao().selectByKeyAndBranch(dbSession, newProjectKey, branchName)).isPresent();
assertThat(dbClient.componentDao().selectByBranchUuid(mainBranch.uuid(), dbSession)).hasSize(1);
assertThat(dbClient.componentDao().selectByBranchUuid(branch.uuid(), dbSession)).hasSize(prComponentCount);
db.select(dbSession, "select kee from components")
.forEach(map -> map.values().forEach(k -> assertThat(k.toString()).startsWith(newProjectKey)));
}
@Test
public void updateKey_updates_pull_requests_too() {
ProjectData projectData = db.components().insertPublicProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
String pullRequestKey1 = randomAlphanumeric(100);
ComponentDto pullRequest = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey1));
db.components().insertComponent(newFileDto(pullRequest));
db.components().insertComponent(newFileDto(pullRequest));
int prComponentCount = 3;
String oldProjectKey = mainBranch.getKey();
assertThat(dbClient.componentDao().selectByBranchUuid(mainBranch.uuid(), dbSession)).hasSize(1);
assertThat(dbClient.componentDao().selectByBranchUuid(pullRequest.uuid(), dbSession)).hasSize(prComponentCount);
String newProjectKey = "newKey";
underTest.updateKey(dbSession, projectData.projectUuid(), projectData.projectKey(), newProjectKey);
assertThat(dbClient.componentDao().selectByKey(dbSession, oldProjectKey)).isEmpty();
assertThat(dbClient.componentDao().selectByKey(dbSession, newProjectKey)).isPresent();
assertThat(dbClient.componentDao().selectByKeyAndPullRequest(dbSession, newProjectKey, pullRequestKey1)).isPresent();
assertThat(dbClient.componentDao().selectByBranchUuid(mainBranch.uuid(), dbSession)).hasSize(1);
assertThat(dbClient.componentDao().selectByBranchUuid(pullRequest.uuid(), dbSession)).hasSize(prComponentCount);
db.select(dbSession, "select kee from components")
.forEach(map -> map.values().forEach(k -> assertThat(k.toString()).startsWith(newProjectKey)));
}
@Test
public void updateKey_throws_IAE_if_component_with_specified_key_does_not_exist() {
populateSomeData();
assertThatThrownBy(() -> underTest.updateKey(dbSession, "A", "org.struts:struts", "foo:struts-core"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Impossible to update key: a component with key \"foo:struts-core\" already exists.");
}
@Test
public void updateKey_throws_IAE_when_sub_component_key_is_too_long() {
ProjectData projectData = db.components().insertPrivateProject("project-uuid", p -> p.setKey("old-project-key"));
ProjectDto project = projectData.getProjectDto();
db.components().insertComponent(newFileDto(projectData.getMainBranchComponent()).setKey("old-project-key:file"));
String newLongProjectKey = Strings.repeat("a", 400);
String projectUuid = project.getUuid();
String projectKey = project.getKey();
assertThatThrownBy(() -> underTest.updateKey(dbSession, projectUuid, projectKey, newLongProjectKey))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Component key length (405) is longer than the maximum authorized (400). '" + newLongProjectKey + ":file' was provided.");
}
@Test
public void compute_new_key() {
assertThat(computeNewKey("my_project", "my_", "your_")).isEqualTo("your_project");
assertThat(computeNewKey("my_project", "my_", "$()_")).isEqualTo("$()_project");
}
@Test
public void updateKey_callsAuditPersister() {
db.components().insertPrivateProject("A", p -> p.setKey("my_project"));
underTestWithAuditPersister.updateKey(dbSession, "A", "my_project", "your_project");
verify(auditPersister, times(1)).componentKeyUpdate(any(DbSession.class), any(ComponentKeyNewValue.class), anyString());
}
private ProjectData populateSomeData() {
ProjectData projectData = db.components().insertPrivateProject(t -> t.setKey("org.struts:struts").setUuid("A").setBranchUuid("A"));
ComponentDto mainBranch1 = projectData.getMainBranchComponent();
ComponentDto directory1 = db.components().insertComponent(newDirectory(mainBranch1, "/src/org/struts").setUuid("B"));
db.components().insertComponent(ComponentTesting.newFileDto(mainBranch1, directory1).setKey("org.struts:struts:/src/org/struts/RequestContext.java").setUuid("C"));
ComponentDto project2 = db.components().insertPublicProject(t -> t.setKey("foo:struts-core").setUuid("D")).getMainBranchComponent();
return projectData;
}
}
| 10,137 | 50.72449 | 176 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/component/ProjectLinkDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.component;
import java.util.Collections;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
public class ProjectLinkDaoIT {
private final static long PAST = 5_000_000_000L;
private final static long NOW = 10_000_000_000L;
private System2 system2 = new TestSystem2().setNow(NOW);
@Rule
public DbTester db = DbTester.create(system2);
private ProjectLinkDao underTest = db.getDbClient().projectLinkDao();
@Test
public void select_by_id() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
ProjectLinkDto link = db.projectLinks().insertProvidedLink(project, c -> c
.setUuid("ABCD")
.setName("Home")
.setType("homepage")
.setHref("http://www.struts.org"));
ProjectLinkDto reloaded = underTest.selectByUuid(db.getSession(), link.getUuid());
assertThat(reloaded.getUuid()).isEqualTo("ABCD");
assertThat(reloaded.getProjectUuid()).isEqualTo(project.getUuid());
assertThat(reloaded.getType()).isEqualTo("homepage");
assertThat(reloaded.getName()).isEqualTo("Home");
assertThat(reloaded.getHref()).isEqualTo("http://www.struts.org");
assertThat(reloaded.getCreatedAt()).isEqualTo(NOW);
assertThat(reloaded.getUpdatedAt()).isEqualTo(NOW);
}
@Test
public void select_by_project_uuid() {
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
ProjectLinkDto link1 = db.projectLinks().insertProvidedLink(project1);
ProjectLinkDto link2 = db.projectLinks().insertProvidedLink(project1);
ProjectLinkDto link3 = db.projectLinks().insertProvidedLink(project1);
ProjectDto project2 = db.components().insertPrivateProject().getProjectDto();
ProjectLinkDto otherLink = db.projectLinks().insertProvidedLink(project2);
assertThat(underTest.selectByProjectUuid(db.getSession(), project1.getUuid()))
.extracting(ProjectLinkDto::getUuid)
.containsExactlyInAnyOrder(link1.getUuid(), link2.getUuid(), link3.getUuid());
assertThat(underTest.selectByProjectUuid(db.getSession(), project2.getUuid()))
.extracting(ProjectLinkDto::getUuid)
.containsExactlyInAnyOrder(otherLink.getUuid());
assertThat(underTest.selectByProjectUuid(db.getSession(), "UNKNOWN")).isEmpty();
}
@Test
public void select_by_project_uuids() {
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
ProjectLinkDto link1 = db.projectLinks().insertProvidedLink(project1);
ProjectLinkDto link2 = db.projectLinks().insertProvidedLink(project1);
ProjectDto project2 = db.components().insertPrivateProject().getProjectDto();
ProjectLinkDto link3 = db.projectLinks().insertProvidedLink(project2);
assertThat(underTest.selectByProjectUuids(db.getSession(), asList(project1.getUuid(), project2.getUuid())))
.extracting(ProjectLinkDto::getUuid)
.containsOnly(link1.getUuid(), link2.getUuid(), link3.getUuid());
assertThat(underTest.selectByProjectUuids(db.getSession(), singletonList(project1.getUuid())))
.extracting(ProjectLinkDto::getUuid)
.containsOnly(link1.getUuid(), link2.getUuid());
assertThat(underTest.selectByProjectUuids(db.getSession(), Collections.emptyList())).isEmpty();
}
@Test
public void insert() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
ProjectLinkDto link = ProjectLinkTesting.newProvidedLinkDto()
.setUuid("ABCD")
.setProjectUuid(project.getUuid())
.setName("Home")
.setType("homepage")
.setHref("http://www.struts.org")
// These fields will be set by the DAO
.setCreatedAt(0L)
.setUpdatedAt(0L);
underTest.insert(db.getSession(), link);
db.getSession().commit();
ProjectLinkDto reloaded = underTest.selectByUuid(db.getSession(), link.getUuid());
assertThat(reloaded.getUuid()).isEqualTo("ABCD");
assertThat(reloaded.getProjectUuid()).isEqualTo(project.getUuid());
assertThat(reloaded.getType()).isEqualTo("homepage");
assertThat(reloaded.getName()).isEqualTo("Home");
assertThat(reloaded.getHref()).isEqualTo("http://www.struts.org");
assertThat(reloaded.getCreatedAt()).isEqualTo(NOW);
assertThat(reloaded.getUpdatedAt()).isEqualTo(NOW);
}
@Test
public void update() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
ProjectLinkDto link = db.projectLinks().insertProvidedLink(project, c -> c
.setUuid("ABCD")
.setType("ci")
.setName("Gihub")
.setHref("http://www.github.org"));
// Force dates to be in the past
db.executeUpdateSql("UPDATE project_links SET created_at=" + PAST + " ,updated_at=" + PAST);
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
underTest.update(db.getSession(), link
.setProjectUuid(project2.uuid())
.setType("homepage")
.setName("Home")
.setHref("http://www.sonarqube.org"));
db.getSession().commit();
ProjectLinkDto reloaded = underTest.selectByUuid(db.getSession(), link.getUuid());
assertThat(reloaded.getUuid()).isEqualTo("ABCD");
assertThat(reloaded.getProjectUuid()).isEqualTo(project2.uuid());
assertThat(reloaded.getType()).isEqualTo("homepage");
assertThat(reloaded.getName()).isEqualTo("Home");
assertThat(reloaded.getHref()).isEqualTo("http://www.sonarqube.org");
assertThat(reloaded.getCreatedAt()).isEqualTo(PAST);
assertThat(reloaded.getUpdatedAt()).isEqualTo(NOW);
}
@Test
public void delete() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
ProjectLinkDto link = db.projectLinks().insertProvidedLink(project);
underTest.delete(db.getSession(), link.getUuid());
db.getSession().commit();
assertThat(db.countRowsOfTable("project_links")).isZero();
}
}
| 6,994 | 40.636905 | 111 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/component/ScrollForFileMoveComponentDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.component;
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.List;
import java.util.Random;
import java.util.stream.IntStream;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.source.FileSourceDto;
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.sonar.api.resources.Qualifiers.FILE;
import static org.sonar.api.resources.Qualifiers.UNIT_TEST_FILE;
@RunWith(DataProviderRunner.class)
public class ScrollForFileMoveComponentDaoIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private Random random = new Random();
private DbSession dbSession = db.getSession();
private ComponentDao underTest = new ComponentDao(new NoOpAuditPersister());
@Test
public void scrollAllFilesForFileMove_has_no_effect_if_project_does_not_exist() {
String nonExistingProjectUuid = randomAlphabetic(10);
underTest.scrollAllFilesForFileMove(dbSession, nonExistingProjectUuid, resultContext -> fail("handler should not be called"));
}
@Test
public void scrollAllFilesForFileMove_has_no_effect_if_project_has_no_file() {
ComponentDto project = random.nextBoolean() ? db.components().insertPrivateProject().getMainBranchComponent() : db.components().insertPublicProject().getMainBranchComponent();
underTest.scrollAllFilesForFileMove(dbSession, project.uuid(), resultContext -> fail("handler should not be called"));
}
@Test
public void scrollAllFilesForFileMove_ignores_files_with_null_path() {
ComponentDto project = random.nextBoolean() ? db.components().insertPrivateProject().getMainBranchComponent() : db.components().insertPublicProject().getMainBranchComponent();
ComponentAndSource file = insertFileAndSource(project, FILE);
ComponentAndSource ut = insertFileAndSource(project, UNIT_TEST_FILE);
ComponentDto fileNoPath = db.components().insertComponent(ComponentTesting.newFileDto(project).setPath(null).setQualifier(FILE));
db.fileSources().insertFileSource(fileNoPath);
ComponentDto utNoPath = db.components().insertComponent(ComponentTesting.newFileDto(project).setPath(null).setQualifier(UNIT_TEST_FILE));
db.fileSources().insertFileSource(utNoPath);
RecordingResultHandler resultHandler = new RecordingResultHandler();
underTest.scrollAllFilesForFileMove(dbSession, project.uuid(), resultHandler);
assertThat(resultHandler.dtos).hasSize(2);
verifyFileMoveRowDto(resultHandler, file);
verifyFileMoveRowDto(resultHandler, ut);
}
@Test
public void scrollAllFilesForFileMove_ignores_files_without_source() {
ComponentDto project = random.nextBoolean() ? db.components().insertPrivateProject().getMainBranchComponent() : db.components().insertPublicProject().getMainBranchComponent();
ComponentAndSource file = insertFileAndSource(project, FILE);
ComponentAndSource ut = insertFileAndSource(project, UNIT_TEST_FILE);
ComponentDto fileNoSource = db.components().insertComponent(ComponentTesting.newFileDto(project).setPath(null).setQualifier(FILE));
ComponentDto utNoSource = db.components().insertComponent(ComponentTesting.newFileDto(project).setPath(null).setQualifier(UNIT_TEST_FILE));
RecordingResultHandler resultHandler = new RecordingResultHandler();
underTest.scrollAllFilesForFileMove(dbSession, project.uuid(), resultHandler);
assertThat(resultHandler.dtos).hasSize(2);
verifyFileMoveRowDto(resultHandler, file);
verifyFileMoveRowDto(resultHandler, ut);
}
@Test
public void scrollAllFilesForFileMove_scrolls_files_of_project() {
ComponentDto project = random.nextBoolean() ? db.components().insertPrivateProject().getMainBranchComponent() : db.components().insertPublicProject().getMainBranchComponent();
ComponentDto dir1 = db.components().insertComponent(ComponentTesting.newDirectory(project, "path"));
ComponentDto dir2 = db.components().insertComponent(ComponentTesting.newDirectory(dir1, "path2"));
ComponentAndSource file1 = insertFileAndSource(project, FILE);
ComponentAndSource file2 = insertFileAndSource(dir1, FILE);
ComponentAndSource file3 = insertFileAndSource(dir2, FILE);
RecordingResultHandler resultHandler = new RecordingResultHandler();
underTest.scrollAllFilesForFileMove(dbSession, project.uuid(), resultHandler);
assertThat(resultHandler.dtos).hasSize(3);
verifyFileMoveRowDto(resultHandler, file1);
verifyFileMoveRowDto(resultHandler, file2);
verifyFileMoveRowDto(resultHandler, file3);
}
@Test
public void scrollAllFilesForFileMove_scrolls_large_number_of_files_and_uts() {
ComponentDto project = random.nextBoolean() ? db.components().insertPrivateProject().getMainBranchComponent() : db.components().insertPublicProject().getMainBranchComponent();
List<ComponentAndSource> files = IntStream.range(0, 300 + random.nextInt(500))
.mapToObj(i -> {
String qualifier = random.nextBoolean() ? FILE : UNIT_TEST_FILE;
ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project).setKey("f_" + i).setQualifier(qualifier));
FileSourceDto fileSource = db.fileSources().insertFileSource(file);
return new ComponentAndSource(file, fileSource);
})
.toList();
RecordingResultHandler resultHandler = new RecordingResultHandler();
underTest.scrollAllFilesForFileMove(dbSession, project.uuid(), resultHandler);
assertThat(resultHandler.dtos).hasSize(files.size());
files.forEach(f -> verifyFileMoveRowDto(resultHandler, f));
}
@Test
public void scrollAllFilesForFileMove_scrolls_unit_tests_of_project() {
ComponentDto project = random.nextBoolean() ? db.components().insertPrivateProject().getMainBranchComponent() : db.components().insertPublicProject().getMainBranchComponent();
ComponentAndSource ut = insertFileAndSource(project, UNIT_TEST_FILE);
RecordingResultHandler resultHandler = new RecordingResultHandler();
underTest.scrollAllFilesForFileMove(dbSession, project.uuid(), resultHandler);
assertThat(resultHandler.dtos).hasSize(1);
verifyFileMoveRowDto(resultHandler, ut);
}
@Test
@UseDataProvider("branchTypes")
public void scrollAllFilesForFileMove_scrolls_files_and_unit_tests_of_branch(BranchType branchType) {
ComponentDto project = random.nextBoolean() ? db.components().insertPrivateProject().getMainBranchComponent() : db.components().insertPublicProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project, t -> t.setBranchType(branchType));
ComponentAndSource file = insertFileAndSource(branch, FILE);
ComponentAndSource ut = insertFileAndSource(branch, UNIT_TEST_FILE);
RecordingResultHandler resultHandler = new RecordingResultHandler();
underTest.scrollAllFilesForFileMove(dbSession, branch.uuid(), resultHandler);
assertThat(resultHandler.dtos).hasSize(2);
verifyFileMoveRowDto(resultHandler, file);
verifyFileMoveRowDto(resultHandler, ut);
}
@DataProvider
public static Object[][] branchTypes() {
return new Object[][] {
{BranchType.BRANCH},
{BranchType.PULL_REQUEST}
};
}
@Test
public void scrollAllFilesForFileMove_ignores_non_file_and_non_ut_component_with_source() {
ComponentDto project = random.nextBoolean() ? db.components().insertPrivateProject().getMainBranchComponent() : db.components().insertPublicProject().getMainBranchComponent();
db.fileSources().insertFileSource(project);
ComponentDto dir = db.components().insertComponent(ComponentTesting.newDirectory(project, "foo"));
db.fileSources().insertFileSource(dir);
ComponentAndSource file = insertFileAndSource(project, FILE);
ComponentAndSource ut = insertFileAndSource(dir, UNIT_TEST_FILE);
ComponentDto portfolio = random.nextBoolean() ? db.components().insertPublicPortfolio() : db.components().insertPrivatePortfolio();
db.fileSources().insertFileSource(portfolio);
ComponentDto subView = db.components().insertSubView(portfolio);
db.fileSources().insertFileSource(subView);
ComponentDto application = random.nextBoolean() ? db.components().insertPrivateApplication().getMainBranchComponent() : db.components().insertPublicApplication().getMainBranchComponent();
db.fileSources().insertFileSource(application);
RecordingResultHandler resultHandler = new RecordingResultHandler();
underTest.scrollAllFilesForFileMove(dbSession, project.uuid(), resultHandler);
underTest.scrollAllFilesForFileMove(dbSession, portfolio.uuid(), resultHandler);
underTest.scrollAllFilesForFileMove(dbSession, application.uuid(), resultHandler);
assertThat(resultHandler.dtos).hasSize(2);
verifyFileMoveRowDto(resultHandler, file);
verifyFileMoveRowDto(resultHandler, ut);
}
private static final class RecordingResultHandler implements ResultHandler<FileMoveRowDto> {
List<FileMoveRowDto> dtos = new ArrayList<>();
@Override
public void handleResult(ResultContext<? extends FileMoveRowDto> resultContext) {
dtos.add(resultContext.getResultObject());
}
private java.util.Optional<FileMoveRowDto> getByUuid(String uuid) {
return dtos.stream().filter(t -> t.getUuid().equals(uuid)).findAny();
}
}
private ComponentAndSource insertFileAndSource(ComponentDto parent, String qualifier) {
ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(parent).setQualifier(qualifier));
FileSourceDto fileSource = db.fileSources().insertFileSource(file);
return new ComponentAndSource(file, fileSource);
}
private static final class ComponentAndSource {
private final ComponentDto component;
private final FileSourceDto source;
private ComponentAndSource(ComponentDto component, FileSourceDto source) {
this.component = component;
this.source = source;
}
}
private static void verifyFileMoveRowDto(RecordingResultHandler resultHander, ComponentAndSource componentAndSource) {
FileMoveRowDto dto = resultHander.getByUuid(componentAndSource.component.uuid()).get();
assertThat(dto.getKey()).isEqualTo(componentAndSource.component.getKey());
assertThat(dto.getUuid()).isEqualTo(componentAndSource.component.uuid());
assertThat(dto.getPath()).isEqualTo(componentAndSource.component.path());
assertThat(dto.getLineCount()).isEqualTo(componentAndSource.source.getLineCount());
}
}
| 11,813 | 48.225 | 191 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/component/SnapshotDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.component;
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.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.ce.CeActivityDto;
import org.sonar.db.ce.CeQueueDto;
import org.sonar.db.ce.CeTaskTypes;
import static com.google.common.collect.Lists.newArrayList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.math.RandomUtils.nextLong;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.sonar.db.ce.CeActivityDto.Status.CANCELED;
import static org.sonar.db.ce.CeActivityDto.Status.SUCCESS;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED;
import static org.sonar.db.component.SnapshotDto.STATUS_UNPROCESSED;
import static org.sonar.db.component.SnapshotQuery.SORT_FIELD.BY_DATE;
import static org.sonar.db.component.SnapshotQuery.SORT_ORDER.ASC;
import static org.sonar.db.component.SnapshotQuery.SORT_ORDER.DESC;
import static org.sonar.db.component.SnapshotTesting.newAnalysis;
@RunWith(DataProviderRunner.class)
public class SnapshotDaoIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private final DbClient dbClient = db.getDbClient();
private final DbSession dbSession = db.getSession();
private final SnapshotDao underTest = dbClient.snapshotDao();
@Test
public void selectByUuid() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
db.components().insertSnapshot(newAnalysis(project)
.setUuid("ABCD")
.setStatus("P")
.setLast(true)
.setPeriodMode("days")
.setPeriodParam("30")
.setPeriodDate(1500000000001L)
.setProjectVersion("2.1.0")
.setBuildString("2.1.0.2336")
.setBuildDate(1500000000006L)
.setCreatedAt(1403042400000L)
.setRevision("sha1"));
SnapshotDto result = underTest.selectByUuid(db.getSession(), "ABCD").get();
assertThat(result.getUuid()).isEqualTo("ABCD");
assertThat(result.getRootComponentUuid()).isEqualTo(project.uuid());
assertThat(result.getStatus()).isEqualTo("P");
assertThat(result.getLast()).isTrue();
assertThat(result.getProjectVersion()).isEqualTo("2.1.0");
assertThat(result.getBuildString()).isEqualTo("2.1.0.2336");
assertThat(result.getPeriodMode()).isEqualTo("days");
assertThat(result.getPeriodModeParameter()).isEqualTo("30");
assertThat(result.getPeriodDate()).isEqualTo(1500000000001L);
assertThat(result.getBuildDate()).isEqualTo(1500000000006L);
assertThat(result.getCreatedAt()).isEqualTo(1403042400000L);
assertThat(result.getRevision()).isEqualTo("sha1");
assertThat(underTest.selectByUuid(db.getSession(), "DOES_NOT_EXIST")).isNotPresent();
}
@Test
public void selectLastAnalysisByRootComponentUuid_returns_absent_when_no_last_snapshot() {
Optional<SnapshotDto> snapshot = underTest.selectLastAnalysisByRootComponentUuid(db.getSession(), "uuid_123");
assertThat(snapshot).isNotPresent();
}
@Test
public void selectLastAnalysisByRootComponentUuid_returns_snapshot_flagged_as_last() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
db.components().insertSnapshot(project1, t -> t.setLast(false));
SnapshotDto lastSnapshot1 = db.components().insertSnapshot(project1, t -> t.setLast(true));
db.components().insertSnapshot(project1, t -> t.setLast(false));
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
db.components().insertSnapshot(project2, t -> t.setLast(false));
SnapshotDto lastSnapshot2 = db.components().insertSnapshot(project2, t -> t.setLast(true));
db.components().insertSnapshot(project2, t -> t.setLast(false));
db.components().insertSnapshot(project2, t -> t.setLast(false));
assertThat(underTest.selectLastAnalysisByRootComponentUuid(db.getSession(), project1.uuid()).get().getUuid())
.isEqualTo(lastSnapshot1.getUuid());
assertThat(underTest.selectLastAnalysisByRootComponentUuid(db.getSession(), project2.uuid()).get().getUuid())
.isEqualTo(lastSnapshot2.getUuid());
assertThat(underTest.selectLastAnalysisByRootComponentUuid(db.getSession(), "does not exist"))
.isEmpty();
}
@Test
public void selectLastAnalysisByRootComponentUuid_returns_absent_if_only_unprocessed_snapshots() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
db.components().insertSnapshot(project1, t -> t.setLast(false));
db.components().insertSnapshot(project1, t -> t.setLast(false));
db.components().insertSnapshot(project1, t -> t.setLast(false));
assertThat(underTest.selectLastAnalysisByRootComponentUuid(db.getSession(), project1.uuid()))
.isNotPresent();
}
@Test
public void selectLastAnalysesByRootComponentUuids_returns_empty_list_if_empty_input() {
List<SnapshotDto> result = underTest.selectLastAnalysesByRootComponentUuids(dbSession, emptyList());
assertThat(result).isEmpty();
}
@Test
public void selectLastAnalysesByRootComponentUuids_returns_snapshots_flagged_as_last() {
ComponentDto firstProject = db.components().insertComponent(newPrivateProjectDto("PROJECT_UUID_1"));
dbClient.snapshotDao().insert(dbSession, newAnalysis(firstProject).setLast(false));
SnapshotDto lastSnapshotOfFirstProject = dbClient.snapshotDao().insert(dbSession, newAnalysis(firstProject).setLast(true));
ComponentDto secondProject = db.components().insertComponent(newPrivateProjectDto("PROJECT_UUID_2"));
SnapshotDto lastSnapshotOfSecondProject = dbClient.snapshotDao().insert(dbSession, newAnalysis(secondProject).setLast(true));
db.components().insertProjectAndSnapshot(newPrivateProjectDto());
List<SnapshotDto> result = underTest.selectLastAnalysesByRootComponentUuids(dbSession, newArrayList(firstProject.uuid(), secondProject.uuid()));
assertThat(result).extracting(SnapshotDto::getUuid).containsOnly(lastSnapshotOfFirstProject.getUuid(), lastSnapshotOfSecondProject.getUuid());
}
@Test
public void selectLastAnalysisDateByProjects_is_empty_if_no_project_passed() {
assertThat(underTest.selectLastAnalysisDateByProjectUuids(dbSession, emptyList())).isEmpty();
}
@Test
public void selectLastAnalysisDateByProjects_returns_all_existing_projects_with_a_snapshot() {
ProjectData project1 = db.components().insertPrivateProject();
ProjectData project2 = db.components().insertPrivateProject();
ComponentDto branch1 = db.components().insertProjectBranch(project2.getMainBranchComponent());
ComponentDto branch2 = db.components().insertProjectBranch(project2.getMainBranchComponent());
ProjectData project3 = db.components().insertPrivateProject();
dbClient.snapshotDao().insert(dbSession, newAnalysis(project1.getMainBranchComponent()).setLast(false).setCreatedAt(2L));
dbClient.snapshotDao().insert(dbSession, newAnalysis(project1.getMainBranchComponent()).setLast(true).setCreatedAt(1L));
dbClient.snapshotDao().insert(dbSession, newAnalysis(project2.getMainBranchComponent()).setLast(true).setCreatedAt(2L));
dbClient.snapshotDao().insert(dbSession, newAnalysis(branch2).setLast(false).setCreatedAt(5L));
dbClient.snapshotDao().insert(dbSession, newAnalysis(branch1).setLast(true).setCreatedAt(4L));
List<ProjectLastAnalysisDateDto> lastAnalysisByProject = underTest.selectLastAnalysisDateByProjectUuids(dbSession,
List.of(project1.projectUuid(), project2.projectUuid(), project3.projectUuid(), "non-existing"));
assertThat(lastAnalysisByProject).extracting(ProjectLastAnalysisDateDto::getProjectUuid, ProjectLastAnalysisDateDto::getDate)
.containsOnly(tuple(project1.projectUuid(), 1L), tuple(project2.projectUuid(), 4L));
}
@Test
public void selectLastAnalysisDateByProjects_returns_all_existing_projects_and_portfolios_with_a_snapshot() {
ProjectData project1 = db.components().insertPrivateProject();
ComponentDto branch1 = db.components().insertProjectBranch(project1.getMainBranchComponent());
ComponentDto portfolio = db.components().insertPrivatePortfolio();
dbClient.snapshotDao().insert(dbSession, newAnalysis(project1.getMainBranchComponent()).setLast(true).setCreatedAt(1L));
dbClient.snapshotDao().insert(dbSession, newAnalysis(portfolio).setLast(true).setCreatedAt(2L));
dbClient.snapshotDao().insert(dbSession, newAnalysis(branch1).setLast(true).setCreatedAt(3L));
List<ProjectLastAnalysisDateDto> lastAnalysisByProject = underTest.selectLastAnalysisDateByProjectUuids(dbSession,
List.of(project1.projectUuid(), portfolio.uuid()));
assertThat(lastAnalysisByProject).extracting(ProjectLastAnalysisDateDto::getProjectUuid, ProjectLastAnalysisDateDto::getDate)
.containsOnly(tuple(project1.projectUuid(), 3L), tuple(portfolio.uuid(), 2L));
}
@Test
public void selectAnalysesByQuery_all() {
Random random = new Random();
List<SnapshotDto> snapshots = IntStream.range(0, 1 + random.nextInt(5))
.mapToObj(i -> {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
return IntStream.range(0, 1 + random.nextInt(20))
.mapToObj(j -> db.components().insertSnapshot(project));
})
.flatMap(t -> t)
.toList();
assertThat(underTest.selectAnalysesByQuery(db.getSession(), new SnapshotQuery()))
.extracting(SnapshotDto::getUuid)
.containsOnly(snapshots.stream().map(SnapshotDto::getUuid).toArray(String[]::new));
}
@Test
public void selectAnalysesByQuery_by_component_uuid() {
Random random = new Random();
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
List<SnapshotDto> snapshots1 = IntStream.range(0, 1 + random.nextInt(20))
.mapToObj(j -> db.components().insertSnapshot(project1))
.toList();
List<SnapshotDto> snapshots2 = IntStream.range(0, 1 + random.nextInt(20))
.mapToObj(j -> db.components().insertSnapshot(project2))
.toList();
assertThat(underTest.selectAnalysesByQuery(db.getSession(), new SnapshotQuery().setRootComponentUuid(project1.uuid())))
.extracting(SnapshotDto::getUuid)
.containsOnly(snapshots1.stream().map(SnapshotDto::getUuid).toArray(String[]::new));
assertThat(underTest.selectAnalysesByQuery(db.getSession(), new SnapshotQuery().setRootComponentUuid(project2.uuid())))
.extracting(SnapshotDto::getUuid)
.containsOnly(snapshots2.stream().map(SnapshotDto::getUuid).toArray(String[]::new));
assertThat(underTest.selectAnalysesByQuery(db.getSession(), new SnapshotQuery().setRootComponentUuid("does not exist")))
.isEmpty();
}
@Test
public void selectAnalysesByQuery_sort_by_date() {
Random random = new Random();
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
List<SnapshotDto> snapshots = IntStream.range(0, 1 + random.nextInt(20))
.mapToObj(j -> SnapshotTesting.newAnalysis(project).setCreatedAt(1_000L + j))
.collect(toList());
Collections.shuffle(snapshots);
snapshots.forEach(db.components()::insertSnapshot);
assertThat(underTest.selectAnalysesByQuery(db.getSession(), new SnapshotQuery().setRootComponentUuid(project.uuid()).setSort(BY_DATE, ASC)))
.extracting(SnapshotDto::getUuid)
.containsExactly(snapshots.stream()
.sorted(Comparator.comparingLong(SnapshotDto::getCreatedAt))
.map(SnapshotDto::getUuid)
.toArray(String[]::new));
assertThat(underTest.selectAnalysesByQuery(db.getSession(), new SnapshotQuery().setRootComponentUuid(project.uuid()).setSort(BY_DATE, DESC)))
.extracting(SnapshotDto::getUuid)
.containsExactly(snapshots.stream()
.sorted(Comparator.comparingLong(SnapshotDto::getCreatedAt).reversed())
.map(SnapshotDto::getUuid)
.toArray(String[]::new));
}
@Test
public void selectAnalysesByQuery_get_last() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
db.components().insertSnapshot(project1, t -> t.setLast(false));
SnapshotDto lastSnapshot = db.components().insertSnapshot(project1, t -> t.setLast(true));
db.components().insertSnapshot(project1, t -> t.setLast(false));
assertThat(underTest.selectAnalysesByQuery(db.getSession(), new SnapshotQuery().setRootComponentUuid(project1.uuid()).setIsLast(true)))
.extracting(SnapshotDto::getUuid)
.containsOnly(lastSnapshot.getUuid());
assertThat(underTest.selectAnalysesByQuery(db.getSession(), new SnapshotQuery().setRootComponentUuid("unknown").setIsLast(true)))
.isEmpty();
}
@Test
public void selectAnalysesByQuery_get_last_supports_multiple_last_snapshots() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
db.components().insertSnapshot(project1, t -> t.setLast(false));
SnapshotDto lastSnapshot1 = db.components().insertSnapshot(project1, t -> t.setLast(true));
SnapshotDto lastSnapshot2 = db.components().insertSnapshot(project1, t -> t.setLast(true));
db.components().insertSnapshot(project1, t -> t.setLast(false));
assertThat(underTest.selectAnalysesByQuery(db.getSession(), new SnapshotQuery().setRootComponentUuid(project1.uuid()).setIsLast(true)))
.extracting(SnapshotDto::getUuid)
.containsOnly(lastSnapshot1.getUuid(), lastSnapshot2.getUuid());
}
@Test
public void selectOldestSnapshot() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
db.getDbClient().snapshotDao().insert(dbSession,
newAnalysis(project).setCreatedAt(5L),
newAnalysis(project).setCreatedAt(2L),
newAnalysis(project).setCreatedAt(1L));
dbSession.commit();
Optional<SnapshotDto> dto = underTest.selectOldestAnalysis(dbSession, project.uuid());
assertThat(dto).isNotEmpty();
assertThat(dto.get().getCreatedAt()).isOne();
assertThat(underTest.selectOldestAnalysis(dbSession, "blabla")).isEmpty();
}
@Test
public void selectFinishedByComponentUuidsAndFromDates() {
long from = 1_500_000_000_000L;
long otherFrom = 1_200_000_000_000L;
ProjectData firstProject = db.components().insertPublicProject();
ProjectData secondProject = db.components().insertPublicProject();
ProjectData thirdProject = db.components().insertPublicProject();
SnapshotDto finishedAnalysis = db.components().insertSnapshot(firstProject, s -> s.setStatus(STATUS_PROCESSED).setCreatedAt(from));
insertActivity(firstProject.getMainBranchComponent().uuid(), finishedAnalysis, SUCCESS);
SnapshotDto otherFinishedAnalysis = db.components().insertSnapshot(firstProject, s -> s.setStatus(STATUS_PROCESSED).setCreatedAt(from + 1_000_000L));
insertActivity(firstProject.getMainBranchComponent().uuid(), otherFinishedAnalysis, SUCCESS);
SnapshotDto oldAnalysis = db.components().insertSnapshot(firstProject, s -> s.setStatus(STATUS_PROCESSED).setCreatedAt(from - 1L));
insertActivity(firstProject.getMainBranchComponent().uuid(), oldAnalysis, SUCCESS);
SnapshotDto analysisOnSecondProject = db.components().insertSnapshot(secondProject, s -> s.setStatus(STATUS_PROCESSED).setCreatedAt(otherFrom));
insertActivity(secondProject.getMainBranchComponent().uuid(), analysisOnSecondProject, SUCCESS);
SnapshotDto oldAnalysisOnThirdProject = db.components().insertSnapshot(thirdProject, s -> s.setStatus(STATUS_PROCESSED).setCreatedAt(otherFrom - 1L));
insertActivity(thirdProject.getMainBranchComponent().uuid(), oldAnalysisOnThirdProject, SUCCESS);
List<SnapshotDto> result = underTest.selectFinishedByProjectUuidsAndFromDates(dbSession,
Arrays.asList(firstProject.projectUuid(), secondProject.projectUuid(), thirdProject.projectUuid()),
Arrays.asList(from, otherFrom, otherFrom));
assertThat(result).extracting(SnapshotDto::getUuid)
.containsExactlyInAnyOrder(finishedAnalysis.getUuid(), otherFinishedAnalysis.getUuid(), analysisOnSecondProject.getUuid());
}
@Test
public void selectFinishedByComponentUuidsAndFromDates_returns_processed_analysis_even_if_analysis_failed() {
long from = 1_500_000_000_000L;
ProjectData project = db.components().insertPublicProject();
SnapshotDto unprocessedAnalysis = db.components().insertSnapshot(project, s -> s.setStatus(STATUS_UNPROCESSED).setCreatedAt(from + 1_000_000L));
insertActivity(project.getMainBranchComponent().uuid(), unprocessedAnalysis, CANCELED);
SnapshotDto finishedAnalysis = db.components().insertSnapshot(project, s -> s.setStatus(STATUS_PROCESSED).setCreatedAt(from));
insertActivity(project.getMainBranchComponent().uuid(), finishedAnalysis, SUCCESS);
SnapshotDto canceledAnalysis = db.components().insertSnapshot(project, s -> s.setStatus(STATUS_PROCESSED).setCreatedAt(from));
insertActivity(project.getMainBranchComponent().uuid(), canceledAnalysis, CANCELED);
List<SnapshotDto> result = underTest.selectFinishedByProjectUuidsAndFromDates(dbSession,
singletonList(project.getProjectDto().getUuid()), singletonList(from));
assertThat(result).extracting(SnapshotDto::getUuid).containsExactlyInAnyOrder(finishedAnalysis.getUuid(), canceledAnalysis.getUuid());
}
@Test
public void selectFinishedByComponentUuidsAndFromDates_return_branches_analysis() {
long from = 1_500_000_000_000L;
ProjectData project = db.components().insertPublicProject();
ComponentDto firstBranch = db.components().insertProjectBranch(project.getMainBranchComponent());
ComponentDto secondBranch = db.components().insertProjectBranch(project.getMainBranchComponent());
SnapshotDto finishedAnalysis = db.components().insertSnapshot(firstBranch, s -> s.setStatus(STATUS_PROCESSED).setCreatedAt(from));
insertActivity(project.getProjectDto().getUuid(), finishedAnalysis, SUCCESS);
SnapshotDto otherFinishedAnalysis = db.components().insertSnapshot(firstBranch, s -> s.setStatus(STATUS_PROCESSED).setCreatedAt(from + 1_000_000L));
insertActivity(project.getProjectDto().getUuid(), otherFinishedAnalysis, SUCCESS);
SnapshotDto oldAnalysis = db.components().insertSnapshot(firstBranch, s -> s.setStatus(STATUS_PROCESSED).setCreatedAt(from - 1L));
insertActivity(project.getProjectDto().getUuid(), oldAnalysis, SUCCESS);
SnapshotDto analysisOnSecondBranch = db.components().insertSnapshot(secondBranch, s -> s.setStatus(STATUS_PROCESSED).setCreatedAt(from));
insertActivity(project.getProjectDto().getUuid(), analysisOnSecondBranch, SUCCESS);
List<SnapshotDto> result = underTest.selectFinishedByProjectUuidsAndFromDates(dbSession, singletonList(project.getProjectDto().getUuid()),
singletonList(from));
assertThat(result).extracting(SnapshotDto::getUuid)
.containsExactlyInAnyOrder(finishedAnalysis.getUuid(), otherFinishedAnalysis.getUuid(), analysisOnSecondBranch.getUuid());
}
@Test
public void selectSnapshotBefore() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
SnapshotDto analysis1 = newAnalysis(project).setCreatedAt(50L).setPeriodDate(20L);
SnapshotDto analysis2 = newAnalysis(project).setCreatedAt(20L).setPeriodDate(10L);
SnapshotDto analysis3 = newAnalysis(project).setCreatedAt(10L).setPeriodDate(null);
db.components().insertSnapshots(analysis1, analysis2, analysis3);
assertThat(underTest.selectSnapshotBefore(project.uuid(), 50L, dbSession))
.extracting(ViewsSnapshotDto::getUuid, ViewsSnapshotDto::getCreatedAt, ViewsSnapshotDto::getLeakDate)
.containsExactlyInAnyOrder(analysis2.getUuid(), analysis2.getCreatedAt(), analysis2.getPeriodDate());
assertThat(underTest.selectSnapshotBefore(project.uuid(), 20L, dbSession))
.extracting(ViewsSnapshotDto::getUuid, ViewsSnapshotDto::getLeakDate)
.containsExactlyInAnyOrder(analysis3.getUuid(), null);
assertThat(underTest.selectSnapshotBefore(project.uuid(), 5L, dbSession)).isNull();
}
@Test
public void insert() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
SnapshotDto dto = underTest.insert(db.getSession(), newAnalysis(project)
.setStatus("P")
.setLast(true)
.setPeriodMode("days")
.setPeriodParam("30")
.setPeriodDate(1500000000001L)
.setProjectVersion("2.1-SNAPSHOT")
.setBuildDate(1500000000006L)
.setCreatedAt(1403042400000L));
assertThat(dto.getUuid()).isNotNull();
assertThat(dto.getRootComponentUuid()).isEqualTo(project.uuid());
assertThat(dto.getStatus()).isEqualTo("P");
assertThat(dto.getLast()).isTrue();
assertThat(dto.getPeriodMode()).isEqualTo("days");
assertThat(dto.getPeriodModeParameter()).isEqualTo("30");
assertThat(dto.getPeriodDate()).isEqualTo(1500000000001L);
assertThat(dto.getBuildDate()).isEqualTo(1500000000006L);
assertThat(dto.getCreatedAt()).isEqualTo(1403042400000L);
assertThat(dto.getProjectVersion()).isEqualTo("2.1-SNAPSHOT");
}
@Test
@UseDataProvider("nullAndEmptyNonEmptyStrings")
public void insert_with_null_and_empty_and_non_empty_projectVersion(@Nullable String projectVersion) {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
SnapshotDto dto = underTest.insert(db.getSession(), newAnalysis(project).setProjectVersion(projectVersion));
assertThat(dto.getProjectVersion()).isEqualTo(projectVersion);
}
@Test
@UseDataProvider("nullAndEmptyNonEmptyStrings")
public void insert_with_null_and_empty_and_non_empty_buildString(@Nullable String buildString) {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
SnapshotDto dto = underTest.insert(db.getSession(), newAnalysis(project).setBuildString(buildString));
assertThat(dto.getBuildString()).isEqualTo(buildString);
}
@DataProvider
public static Object[][] nullAndEmptyNonEmptyStrings() {
return new Object[][] {
{null},
{""},
{randomAlphanumeric(7)},
};
}
@Test
public void insert_snapshots() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
underTest.insert(db.getSession(),
newAnalysis(project).setLast(false).setUuid("u5"),
newAnalysis(project).setLast(false).setUuid("u6"));
db.getSession().commit();
assertThat(db.countRowsOfTable("snapshots")).isEqualTo(2);
}
@Test
public void isLast_is_true_when_no_previous_snapshot() {
SnapshotDto snapshot = defaultSnapshot();
boolean isLast = SnapshotDao.isLast(snapshot, null);
assertThat(isLast).isTrue();
}
@Test
public void isLast_is_true_when_previous_snapshot_is_older() {
Date today = new Date();
Date yesterday = DateUtils.addDays(today, -1);
SnapshotDto snapshot = defaultSnapshot().setCreatedAt(today.getTime());
SnapshotDto previousLastSnapshot = defaultSnapshot().setCreatedAt(yesterday.getTime());
boolean isLast = SnapshotDao.isLast(snapshot, previousLastSnapshot);
assertThat(isLast).isTrue();
}
@Test
public void isLast_is_false_when_previous_snapshot_is_newer() {
Date today = new Date();
Date yesterday = DateUtils.addDays(today, -1);
SnapshotDto snapshot = defaultSnapshot().setCreatedAt(yesterday.getTime());
SnapshotDto previousLastSnapshot = defaultSnapshot().setCreatedAt(today.getTime());
boolean isLast = SnapshotDao.isLast(snapshot, previousLastSnapshot);
assertThat(isLast).isFalse();
}
@Test
public void switchIsLastFlagAndSetProcessedStatus() {
insertAnalysis("P1", "A1", SnapshotDto.STATUS_PROCESSED, true);
insertAnalysis("P1", "A2", SnapshotDto.STATUS_UNPROCESSED, false);
insertAnalysis("P2", "A3", SnapshotDto.STATUS_PROCESSED, true);
db.commit();
underTest.switchIsLastFlagAndSetProcessedStatus(db.getSession(), "P1", "A2");
verifyStatusAndIsLastFlag("A1", SnapshotDto.STATUS_PROCESSED, false);
verifyStatusAndIsLastFlag("A2", SnapshotDto.STATUS_PROCESSED, true);
// other project is untouched
verifyStatusAndIsLastFlag("A3", SnapshotDto.STATUS_PROCESSED, true);
}
@Test
public void update() {
SnapshotDto analysis = insertAnalysis("P1", "A1", STATUS_PROCESSED, false);
db.commit();
analysis
.setRootComponentUuid("P42")
.setProjectVersion("5.6.3")
.setStatus(STATUS_UNPROCESSED);
underTest.update(dbSession, analysis);
SnapshotDto result = underTest.selectByUuid(dbSession, "A1").get();
assertThat(result.getProjectVersion()).isEqualTo("5.6.3");
assertThat(result.getStatus()).isEqualTo(STATUS_UNPROCESSED);
assertThat(result.getRootComponentUuid()).isEqualTo("P1");
}
private SnapshotDto insertAnalysis(String projectUuid, String uuid, String status, boolean isLastFlag) {
SnapshotDto snapshot = newAnalysis(newPrivateProjectDto(projectUuid))
.setLast(isLastFlag)
.setStatus(status)
.setUuid(uuid);
underTest.insert(db.getSession(), snapshot);
return snapshot;
}
private void verifyStatusAndIsLastFlag(String uuid, String expectedStatus, boolean expectedLastFlag) {
Optional<SnapshotDto> analysis = underTest.selectByUuid(db.getSession(), uuid);
assertThat(analysis.get().getStatus()).isEqualTo(expectedStatus);
assertThat(analysis.get().getLast()).isEqualTo(expectedLastFlag);
}
private static SnapshotDto defaultSnapshot() {
return new SnapshotDto()
.setUuid("u1")
.setRootComponentUuid("uuid_3")
.setStatus("P")
.setLast(true)
.setProjectVersion("2.1-SNAPSHOT")
.setPeriodMode("days1")
.setPeriodParam("30")
.setPeriodDate(1_500_000_000_001L)
.setBuildDate(1_500_000_000_006L);
}
private CeActivityDto insertActivity(String projectUuid, SnapshotDto analysis, CeActivityDto.Status status) {
CeQueueDto queueDto = new CeQueueDto();
queueDto.setTaskType(CeTaskTypes.REPORT);
queueDto.setComponentUuid(projectUuid);
queueDto.setUuid(randomAlphanumeric(40));
queueDto.setCreatedAt(nextLong());
CeActivityDto activityDto = new CeActivityDto(queueDto);
activityDto.setStatus(status);
activityDto.setExecutionTimeMs(nextLong());
activityDto.setExecutedAt(nextLong());
activityDto.setAnalysisUuid(analysis.getUuid());
db.getDbClient().ceActivityDao().insert(db.getSession(), activityDto);
db.commit();
return activityDto;
}
}
| 28,316 | 47.822414 | 154 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/it/java/org/sonar/db/duplication/DuplicationDaoIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.duplication;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.assertj.core.api.AbstractListAssert;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.ObjectAssert;
import org.assertj.core.groups.Tuple;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.SnapshotDto;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.tuple;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
public class DuplicationDaoIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private final DbSession dbSession = db.getSession();
private final DuplicationDao dao = db.getDbClient().duplicationDao();
@Test
public void selectCandidates_returns_block_from_last_snapshot_only_of_component_with_language_and_if_not_specified_analysis() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto fooFile = db.components().insertComponent(ComponentTesting.newFileDto(project1).setLanguage("foo").setEnabled(true));
ComponentDto fooFile1 = db.components().insertComponent(ComponentTesting.newFileDto(project1).setLanguage("foo").setEnabled(true));
ComponentDto disabledFooFile = db.components().insertComponent(ComponentTesting.newFileDto(project1).setLanguage("foo").setEnabled(false));
ComponentDto barFile = db.components().insertComponent(ComponentTesting.newFileDto(project1).setLanguage("bar").setEnabled(true));
ComponentDto noLanguageFile = db.components().insertComponent(ComponentTesting.newFileDto(project1).setLanguage(null).setEnabled(true));
SnapshotDto newAnalysis = db.components().insertSnapshot(project1, t -> t.setLast(false));
SnapshotDto lastAnalysis = db.components().insertSnapshot(project1, t -> t.setLast(true));
SnapshotDto notLastAnalysis = db.components().insertSnapshot(project1, t -> t.setLast(false));
for (String hash : Arrays.asList("aa", "bb")) {
for (ComponentDto component : Arrays.asList(project1, fooFile, fooFile1, disabledFooFile, barFile, noLanguageFile)) {
insert(component, lastAnalysis, hash, 0, 1, 2);
insert(component, notLastAnalysis, hash, 0, 4, 5);
insert(component, newAnalysis, hash, 0, 6, 7);
}
}
for (String hash : Arrays.asList("aa", "bb")) {
assertThat(dao.selectCandidates(dbSession, newAnalysis.getUuid(), "foo", singletonList(hash)))
.containsOnly(
tuple(fooFile.uuid(), fooFile.getKey(), lastAnalysis.getUuid(), hash),
tuple(fooFile1.uuid(), fooFile1.getKey(), lastAnalysis.getUuid(), hash));
assertThat(dao.selectCandidates(dbSession, newAnalysis.getUuid(), "bar", singletonList(hash)))
.containsOnly(
tuple(barFile.uuid(), barFile.getKey(), lastAnalysis.getUuid(), hash));
assertThat(dao.selectCandidates(dbSession, newAnalysis.getUuid(), "donut", singletonList(hash)))
.isEmpty();
}
for (List<String> hashes : Arrays.asList(List.of("aa", "bb"), List.of("bb", "aa"), List.of("aa", "bb", "cc"))) {
assertThat(dao.selectCandidates(dbSession, newAnalysis.getUuid(), "foo", hashes))
.containsOnly(
tuple(fooFile.uuid(), fooFile.getKey(), lastAnalysis.getUuid(), "aa"),
tuple(fooFile.uuid(), fooFile.getKey(), lastAnalysis.getUuid(), "bb"),
tuple(fooFile1.uuid(), fooFile1.getKey(), lastAnalysis.getUuid(), "aa"),
tuple(fooFile1.uuid(), fooFile1.getKey(), lastAnalysis.getUuid(), "bb"));
assertThat(dao.selectCandidates(dbSession, newAnalysis.getUuid(), "bar", hashes))
.containsOnly(
tuple(barFile.uuid(), barFile.getKey(), lastAnalysis.getUuid(), "aa"),
tuple(barFile.uuid(), barFile.getKey(), lastAnalysis.getUuid(), "bb"));
assertThat(dao.selectCandidates(dbSession, newAnalysis.getUuid(), "donut", hashes))
.isEmpty();
}
assertThat(dao.selectCandidates(dbSession, lastAnalysis.getUuid(), "foo", singletonList("aa")))
.isEmpty();
assertThat(dao.selectCandidates(dbSession, lastAnalysis.getUuid(), "bar", singletonList("aa")))
.isEmpty();
assertThat(dao.selectCandidates(dbSession, lastAnalysis.getUuid(), "donut", singletonList("aa")))
.isEmpty();
}
private AbstractListAssert<?, List<? extends Tuple>, Tuple, ObjectAssert<Tuple>> assertThat(List<DuplicationUnitDto> blocks) {
return Assertions.assertThat(blocks)
.extracting(DuplicationUnitDto::getComponentUuid, DuplicationUnitDto::getComponentKey, DuplicationUnitDto::getAnalysisUuid, DuplicationUnitDto::getHash);
}
@Test
public void select_component() {
ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent();
SnapshotDto analysis1 = db.components().insertSnapshot(project1);
ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent();
SnapshotDto analysis2 = db.components().insertSnapshot(project2);
ComponentDto project3 = db.components().insertPrivateProject().getMainBranchComponent();
SnapshotDto analysis3 = db.components().insertSnapshot(project3);
ComponentDto project4 = db.components().insertPrivateProject().getMainBranchComponent();
insert(project1, analysis1, "bb", 0, 0, 0);
insert(project2, analysis2, "aa", 0, 1, 2);
insert(project3, analysis3, "bb", 0, 0, 0);
// irrealistic case but allow to test the SQL code
insert(project4, analysis3, "aa", 0, 0, 0);
List<DuplicationUnitDto> blocks = dao.selectComponent(dbSession, project3.uuid(), analysis3.getUuid());
assertThat(blocks).hasSize(1);
DuplicationUnitDto block = blocks.get(0);
Assertions.assertThat(block.getUuid()).isNotNull();
Assertions.assertThat(block.getComponentKey()).isNull();
Assertions.assertThat(block.getComponentUuid()).isEqualTo(project3.uuid());
Assertions.assertThat(block.getHash()).isEqualTo("bb");
Assertions.assertThat(block.getAnalysisUuid()).isEqualTo(analysis3.getUuid());
Assertions.assertThat(block.getIndexInFile()).isZero();
Assertions.assertThat(block.getStartLine()).isZero();
Assertions.assertThat(block.getEndLine()).isZero();
}
@Test
public void insert() {
ComponentDto project = newPrivateProjectDto();
SnapshotDto analysis = db.components().insertProjectAndSnapshot(project);
insert(project, analysis, "bb", 0, 1, 2);
List<Map<String, Object>> rows = db.select("select " +
"uuid as \"UUID\", analysis_uuid as \"ANALYSIS\", component_uuid as \"COMPONENT\", hash as \"HASH\", " +
"index_in_file as \"INDEX\", start_line as \"START\", end_line as \"END\"" +
" from duplications_index");
Assertions.assertThat(rows).hasSize(1);
Map<String, Object> row = rows.get(0);
Assertions.assertThat(row.get("UUID")).isNotNull();
Assertions.assertThat(row)
.containsEntry("ANALYSIS", analysis.getUuid())
.containsEntry("COMPONENT", project.uuid())
.containsEntry("HASH", "bb")
.containsEntry("INDEX", 0L)
.containsEntry("START", 1L)
.containsEntry("END", 2L);
}
public void insert(ComponentDto project, SnapshotDto analysis, String hash, int indexInFile, int startLine, int endLine) {
dao.insert(dbSession, new DuplicationUnitDto()
.setAnalysisUuid(analysis.getUuid())
.setComponentUuid(project.uuid())
.setHash(hash)
.setIndexInFile(indexInFile)
.setStartLine(startLine)
.setEndLine(endLine));
dbSession.commit();
}
}
| 8,601 | 48.722543 | 159 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.