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-db-dao/src/main/java/org/sonar/db/user/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.user;
import javax.annotation.ParametersAreNonnullByDefault;
| 958 | 37.36 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/webhook/WebhookDao.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.webhook;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.api.utils.System2;
import org.sonar.db.Dao;
import org.sonar.db.DbSession;
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.audit.model.SecretNewValue;
import org.sonar.db.audit.model.WebhookNewValue;
import org.sonar.db.project.ProjectDto;
public class WebhookDao implements Dao {
private final System2 system2;
private final AuditPersister auditPersister;
public WebhookDao(System2 system2, AuditPersister auditPersister) {
this.system2 = system2;
this.auditPersister = auditPersister;
}
public List<WebhookDto> selectGlobalWebhooks(DbSession dbSession) {
return mapper(dbSession).selectGlobalWebhooksOrderedByName();
}
public Optional<WebhookDto> selectByUuid(DbSession dbSession, String uuid) {
return Optional.ofNullable(mapper(dbSession).selectByUuid(uuid));
}
public List<WebhookDto> selectByProject(DbSession dbSession, ProjectDto projectDto) {
return mapper(dbSession).selectForProjectUuidOrderedByName(projectDto.getUuid());
}
public void insert(DbSession dbSession, WebhookDto dto, @Nullable String projectKey, @Nullable String projectName) {
mapper(dbSession).insert(dto.setCreatedAt(system2.now()).setUpdatedAt(system2.now()));
auditPersister.addWebhook(dbSession, new WebhookNewValue(dto, projectKey, projectName));
}
public void update(DbSession dbSession, WebhookDto dto, @Nullable String projectKey, @Nullable String projectName) {
mapper(dbSession).update(dto.setUpdatedAt(system2.now()));
if (dto.getSecret() != null) {
auditPersister.updateWebhookSecret(dbSession, new SecretNewValue("webhook_name", dto.getName()));
}
auditPersister.updateWebhook(dbSession, new WebhookNewValue(dto, projectKey, projectName));
}
public void delete(DbSession dbSession, String uuid, String webhookName) {
int deletedRows = mapper(dbSession).delete(uuid);
if (deletedRows > 0) {
auditPersister.deleteWebhook(dbSession, new WebhookNewValue(uuid, webhookName));
}
}
public void deleteByProject(DbSession dbSession, ProjectDto projectDto) {
int deletedRows = mapper(dbSession).deleteForProjectUuid(projectDto.getUuid());
if (deletedRows > 0) {
auditPersister.deleteWebhook(dbSession, new WebhookNewValue(projectDto));
}
}
private static WebhookMapper mapper(DbSession dbSession) {
return dbSession.getMapper(WebhookMapper.class);
}
}
| 3,365 | 36.820225 | 118 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/webhook/WebhookDeliveryDao.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.webhook;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.ibatis.session.RowBounds;
import org.sonar.db.Dao;
import org.sonar.db.DbSession;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
public class WebhookDeliveryDao implements Dao {
public Optional<WebhookDeliveryDto> selectByUuid(DbSession dbSession, String uuid) {
return Optional.ofNullable(mapper(dbSession).selectByUuid(uuid));
}
public int countDeliveriesByWebhookUuid(DbSession dbSession, String webhookUuid) {
return mapper(dbSession).countByWebhookUuid(webhookUuid);
}
/**
* All the deliveries for the specified webhook. Results are ordered by descending date.
*/
public List<WebhookDeliveryLiteDto> selectByWebhookUuid(DbSession dbSession, String webhookUuid, int offset, int limit) {
return mapper(dbSession).selectByWebhookUuid(webhookUuid, new RowBounds(offset, limit));
}
public int countDeliveriesByProjectUuid(DbSession dbSession, String projectUuid) {
return mapper(dbSession).countByProjectUuid(projectUuid);
}
/**
* All the deliveries for the specified project. Results are ordered by descending date.
*/
public List<WebhookDeliveryLiteDto> selectOrderedByProjectUuid(DbSession dbSession, String projectUuid, int offset, int limit) {
return mapper(dbSession).selectOrderedByProjectUuid(projectUuid, new RowBounds(offset, limit));
}
public int countDeliveriesByCeTaskUuid(DbSession dbSession, String ceTaskId) {
return mapper(dbSession).countByCeTaskUuid(ceTaskId);
}
/**
* All the deliveries for the specified CE task. Results are ordered by descending date.
*/
public List<WebhookDeliveryLiteDto> selectOrderedByCeTaskUuid(DbSession dbSession, String ceTaskUuid, int offset, int limit) {
return mapper(dbSession).selectOrderedByCeTaskUuid(ceTaskUuid, new RowBounds(offset, limit));
}
public void insert(DbSession dbSession, WebhookDeliveryDto dto) {
mapper(dbSession).insert(dto);
}
public void deleteProjectBeforeDate(DbSession dbSession, String projectUuid, long beforeDate) {
mapper(dbSession).deleteProjectBeforeDate(projectUuid, beforeDate);
}
public Map<String, WebhookDeliveryLiteDto> selectLatestDeliveries(DbSession dbSession, List<WebhookDto> webhooks) {
return webhooks.stream()
.flatMap(webhook -> selectByWebhookUuid(dbSession, webhook.getUuid(),0,1).stream())
.collect(toMap(WebhookDeliveryLiteDto::getWebhookUuid, identity()));
}
private static WebhookDeliveryMapper mapper(DbSession dbSession) {
return dbSession.getMapper(WebhookDeliveryMapper.class);
}
public void deleteByWebhook(DbSession dbSession, WebhookDto webhook) {
mapper(dbSession).deleteByWebhookUuid(webhook.getUuid());
}
}
| 3,684 | 38.623656 | 130 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/webhook/WebhookDeliveryDto.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.webhook;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.builder.ToStringBuilder;
public class WebhookDeliveryDto extends WebhookDeliveryLiteDto<WebhookDeliveryDto> {
/** Error message if HTTP request cannot be sent, else null */
private String errorStacktrace;
/** The payload that has been sent, cannot be null */
private String payload;
@CheckForNull
public String getErrorStacktrace() {
return errorStacktrace;
}
public WebhookDeliveryDto setErrorStacktrace(@Nullable String s) {
this.errorStacktrace = s;
return this;
}
public String getPayload() {
return payload;
}
public WebhookDeliveryDto setPayload(String s) {
this.payload = s;
return this;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("uuid", uuid)
.append("projectUuid", projectUuid)
.append("name", name)
.append("success", success)
.append("httpStatus", httpStatus)
.append("durationMs", durationMs)
.append("url", url)
.append("errorStacktrace", errorStacktrace)
.append("createdAt", createdAt)
.toString();
}
}
| 2,059 | 30.212121 | 84 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/webhook/WebhookDeliveryLiteDto.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.webhook;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.builder.ToStringBuilder;
public class WebhookDeliveryLiteDto<T extends WebhookDeliveryLiteDto> {
/** Technical unique identifier, can't be null */
protected String uuid;
/** Technical unique identifier, can be null for migration */
protected String webhookUuid;
/** Project UUID, can't be null */
protected String projectUuid;
/** Compute Engine task UUID, can be null */
protected String ceTaskUuid;
/** analysis UUID, can be null */
protected String analysisUuid;
/** Name, can't be null */
protected String name;
protected boolean success;
/** HTTP response status. Null if HTTP request cannot be sent */
protected Integer httpStatus;
/** Duration in ms. Null if HTTP request cannot be sent */
protected Integer durationMs;
/** URL, cannot be null */
protected String url;
/** Time of delivery */
protected long createdAt;
public String getUuid() {
return uuid;
}
public T setUuid(String s) {
this.uuid = s;
return (T) this;
}
public String getWebhookUuid() {
return webhookUuid;
}
public T setWebhookUuid(String webhookUuid) {
this.webhookUuid = webhookUuid;
return (T) this;
}
public String getProjectUuid() {
return projectUuid;
}
public T setProjectUuid(String s) {
this.projectUuid = s;
return (T) this;
}
@CheckForNull
public String getCeTaskUuid() {
return ceTaskUuid;
}
public T setCeTaskUuid(@Nullable String s) {
this.ceTaskUuid = s;
return (T) this;
}
@CheckForNull
public String getAnalysisUuid() {
return analysisUuid;
}
public T setAnalysisUuid(@Nullable String s) {
this.analysisUuid = s;
return (T) this;
}
public String getName() {
return name;
}
public T setName(String s) {
this.name = s;
return (T) this;
}
public boolean isSuccess() {
return success;
}
public T setSuccess(boolean b) {
this.success = b;
return (T) this;
}
@CheckForNull
public Integer getHttpStatus() {
return httpStatus;
}
public T setHttpStatus(@Nullable Integer i) {
this.httpStatus = i;
return (T) this;
}
@CheckForNull
public Integer getDurationMs() {
return durationMs;
}
public T setDurationMs(@Nullable Integer i) {
this.durationMs = i;
return (T) this;
}
public String getUrl() {
return url;
}
public T setUrl(String s) {
this.url = s;
return (T) this;
}
public long getCreatedAt() {
return createdAt;
}
public T setCreatedAt(long l) {
this.createdAt = l;
return (T) this;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("uuid", uuid)
.append("componentUuid", projectUuid)
.append("ceTaskUuid", ceTaskUuid)
.append("name", name)
.append("success", success)
.append("httpStatus", httpStatus)
.append("durationMs", durationMs)
.append("url", url)
.append("createdAt", createdAt)
.toString();
}
}
| 3,967 | 22.760479 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/webhook/WebhookDeliveryMapper.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.webhook;
import java.util.List;
import javax.annotation.CheckForNull;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
public interface WebhookDeliveryMapper {
@CheckForNull
WebhookDeliveryDto selectByUuid(@Param("uuid") String uuid);
int countByWebhookUuid(@Param("webhookUuid") String webhookUuid);
List<WebhookDeliveryLiteDto> selectByWebhookUuid(@Param("webhookUuid") String webhookUuid, RowBounds rowBounds);
int countByProjectUuid(@Param("projectUuid") String projectUuid);
List<WebhookDeliveryLiteDto> selectOrderedByProjectUuid(@Param("projectUuid") String projectUuid, RowBounds rowBounds);
int countByCeTaskUuid(@Param("ceTaskUuid") String ceTaskId);
List<WebhookDeliveryLiteDto> selectOrderedByCeTaskUuid(@Param("ceTaskUuid") String ceTaskUuid, RowBounds rowBounds);
void insert(WebhookDeliveryDto dto);
void deleteProjectBeforeDate(@Param("projectUuid") String projectUuid, @Param("beforeDate") long beforeDate);
void deleteByWebhookUuid(@Param("webhookUuid") String webhookUuid);
}
| 1,932 | 37.66 | 121 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/webhook/WebhookDto.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.webhook;
import javax.annotation.Nullable;
public class WebhookDto {
/** Technical unique identifier, can't be null */
private String uuid;
/** Name, can't be null */
private String name;
/** URL, can't be null */
private String url;
@Nullable
private String projectUuid;
/**
* The optional secret used to generate payload signature
*/
@Nullable
private String secret;
private long createdAt;
private long updatedAt;
public WebhookDto setUuid(String uuid) {
this.uuid = uuid;
return this;
}
public WebhookDto setName(String name) {
this.name = name;
return this;
}
public WebhookDto setUrl(String url) {
this.url = url;
return this;
}
public WebhookDto setProjectUuid(@Nullable String projectUuid) {
this.projectUuid = projectUuid;
return this;
}
public WebhookDto setSecret(@Nullable String s) {
this.secret = s;
return this;
}
WebhookDto setCreatedAt(long createdAt) {
this.createdAt = createdAt;
return this;
}
WebhookDto setUpdatedAt(long updatedAt) {
this.updatedAt = updatedAt;
return this;
}
public String getUuid() {
return uuid;
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
@Nullable
public String getProjectUuid() {
return projectUuid;
}
@Nullable
public String getSecret() {
return secret;
}
public long getCreatedAt() {
return createdAt;
}
@Nullable
public long getUpdatedAt() {
return updatedAt;
}
}
| 2,412 | 20.738739 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/webhook/WebhookMapper.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.webhook;
import java.util.List;
import javax.annotation.CheckForNull;
import org.apache.ibatis.annotations.Param;
public interface WebhookMapper {
@CheckForNull
WebhookDto selectByUuid(@Param("webhookUuid") String webhookUuid);
List<WebhookDto> selectGlobalWebhooksOrderedByName();
List<WebhookDto> selectForProjectUuidOrderedByName(@Param("projectUuid") String projectUuid);
void insert(WebhookDto dto);
void update(WebhookDto dto);
int delete(@Param("uuid") String uuid);
int deleteForProjectUuid(@Param("projectUuid") String projectUuid);
}
| 1,433 | 32.348837 | 95 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/webhook/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.db.webhook;
import javax.annotation.ParametersAreNonnullByDefault;
| 961 | 37.48 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/BatchSessionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.Test;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class BatchSessionTest {
@Test
public void shouldCommitWhenReachingBatchSize() {
DbSession mybatisSession = mock(DbSession.class);
BatchSession session = new BatchSession(mybatisSession, 10);
for (int i = 0; i < 9; i++) {
session.insert("id" + i);
verify(mybatisSession).insert("id" + i);
verify(mybatisSession, never()).commit();
verify(mybatisSession, never()).commit(anyBoolean());
}
session.insert("id9");
verify(mybatisSession).commit();
session.close();
}
@Test
public void shouldCommitWhenReachingBatchSizeWithoutCommits() {
DbSession mybatisSession = mock(DbSession.class);
BatchSession session = new BatchSession(mybatisSession, 10);
for (int i = 0; i < 9; i++) {
session.delete("delete something");
verify(mybatisSession, never()).commit();
verify(mybatisSession, never()).commit(anyBoolean());
}
session.delete("delete something");
verify(mybatisSession).commit();
session.close();
}
@Test
public void shouldResetCounterAfterCommit() {
DbSession mybatisSession = mock(DbSession.class);
BatchSession session = new BatchSession(mybatisSession, 10);
for (int i = 0; i < 35; i++) {
session.insert("id" + i);
}
verify(mybatisSession, times(3)).commit();
session.close();
}
}
| 2,449 | 32.108108 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/DBSessionsImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.junit.After;
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 static java.lang.Math.abs;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class DBSessionsImplTest {
@Rule
public LogTester logTester = new LogTester();
private final MyBatis myBatis = mock(MyBatis.class);
private final DbSession myBatisDbSession = mock(DbSession.class);
private final Random random = new Random();
private final DBSessionsImpl underTest = new DBSessionsImpl(myBatis);
@After
public void tearDown() {
underTest.disableCaching();
}
@Test
public void openSession_without_caching_always_returns_a_new_regular_session_when_parameter_is_false() {
DbSession[] expected = {mock(DbSession.class), mock(DbSession.class), mock(DbSession.class), mock(DbSession.class)};
when(myBatis.openSession(false))
.thenReturn(expected[0])
.thenReturn(expected[1])
.thenReturn(expected[2])
.thenReturn(expected[3])
.thenThrow(oneCallTooMuch());
assertThat(Arrays.stream(expected).map(ignored -> underTest.openSession(false)).toList())
.containsExactly(expected);
}
@Test
public void openSession_without_caching_always_returns_a_new_batch_session_when_parameter_is_true() {
DbSession[] expected = {mock(DbSession.class), mock(DbSession.class), mock(DbSession.class), mock(DbSession.class)};
when(myBatis.openSession(true))
.thenReturn(expected[0])
.thenReturn(expected[1])
.thenReturn(expected[2])
.thenReturn(expected[3])
.thenThrow(oneCallTooMuch());
assertThat(Arrays.stream(expected).map(ignored -> underTest.openSession(true)).toList())
.containsExactly(expected);
}
@Test
public void openSession_with_caching_always_returns_the_same_regular_session_when_parameter_is_false() {
DbSession expected = mock(DbSession.class);
when(myBatis.openSession(false))
.thenReturn(expected)
.thenThrow(oneCallTooMuch());
underTest.enableCaching();
int size = 1 + abs(random.nextInt(10));
Set<DbSession> dbSessions = IntStream.range(0, size).mapToObj(ignored -> underTest.openSession(false)).collect(Collectors.toSet());
assertThat(dbSessions).hasSize(size);
assertThat(getWrappedDbSessions(dbSessions))
.hasSize(1)
.containsOnly(expected);
}
@Test
public void openSession_with_caching_always_returns_the_same_batch_session_when_parameter_is_true() {
DbSession expected = mock(DbSession.class);
when(myBatis.openSession(true))
.thenReturn(expected)
.thenThrow(oneCallTooMuch());
underTest.enableCaching();
int size = 1 + abs(random.nextInt(10));
Set<DbSession> dbSessions = IntStream.range(0, size).mapToObj(ignored -> underTest.openSession(true)).collect(Collectors.toSet());
assertThat(dbSessions).hasSize(size);
assertThat(getWrappedDbSessions(dbSessions))
.hasSize(1)
.containsOnly(expected);
}
@Test
public void openSession_with_caching_returns_a_session_per_thread() {
boolean batchOrRegular = random.nextBoolean();
DbSession[] expected = {mock(DbSession.class), mock(DbSession.class), mock(DbSession.class), mock(DbSession.class)};
when(myBatis.openSession(batchOrRegular))
.thenReturn(expected[0])
.thenReturn(expected[1])
.thenReturn(expected[2])
.thenReturn(expected[3])
.thenThrow(oneCallTooMuch());
List<DbSession> collector = new ArrayList<>();
Runnable runnable = () -> {
underTest.enableCaching();
collector.add(underTest.openSession(batchOrRegular));
underTest.disableCaching();
};
Thread[] threads = {new Thread(runnable, "T1"), new Thread(runnable, "T2"), new Thread(runnable, "T3")};
executeThreadsAndCurrent(runnable, threads);
// verify each DbSession was closed and then reset mock for next verification
Arrays.stream(expected).forEach(s -> {
verify(s).close();
reset(s);
});
// verify whether each thread got the expected DbSession from MyBatis
// by verifying to which each returned DbSession delegates to
DbSession[] dbSessions = collector.toArray(new DbSession[0]);
for (int i = 0; i < expected.length; i++) {
dbSessions[i].rollback();
verify(expected[i]).rollback();
List<DbSession> sub = new ArrayList<>(Arrays.asList(expected));
sub.remove(expected[i]);
sub.forEach(Mockito::verifyNoMoreInteractions);
reset(expected);
}
}
private static void executeThreadsAndCurrent(Runnable runnable, Thread[] threads) {
Arrays.stream(threads).forEach(thread -> {
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
Throwables.propagate(e);
}
});
runnable.run();
}
@Test
public void openSession_with_caching_returns_wrapper_of_MyBatis_DbSession_which_delegates_all_methods_but_close() {
boolean batchOrRegular = random.nextBoolean();
underTest.enableCaching();
verifyFirstDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
dbSession.rollback();
verify(myBatisDbSession).rollback();
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
boolean flag = random.nextBoolean();
dbSession.rollback(flag);
verify(myBatisDbSession).rollback(flag);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
dbSession.commit();
verify(myBatisDbSession).commit();
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
boolean flag = random.nextBoolean();
dbSession.commit(flag);
verify(myBatisDbSession).commit(flag);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
dbSession.selectOne(str);
verify(myBatisDbSession).selectOne(str);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
Object object = new Object();
dbSession.selectOne(str, object);
verify(myBatisDbSession).selectOne(str, object);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
dbSession.selectList(str);
verify(myBatisDbSession).selectList(str);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
Object object = new Object();
dbSession.selectList(str, object);
verify(myBatisDbSession).selectList(str, object);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
Object parameter = new Object();
RowBounds rowBounds = new RowBounds();
dbSession.selectList(str, parameter, rowBounds);
verify(myBatisDbSession).selectList(str, parameter, rowBounds);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
String mapKey = randomAlphabetic(10);
dbSession.selectMap(str, mapKey);
verify(myBatisDbSession).selectMap(str, mapKey);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
Object parameter = new Object();
String mapKey = randomAlphabetic(10);
dbSession.selectMap(str, parameter, mapKey);
verify(myBatisDbSession).selectMap(str, parameter, mapKey);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
Object parameter = new Object();
String mapKey = randomAlphabetic(10);
RowBounds rowBounds = new RowBounds();
dbSession.selectMap(str, parameter, mapKey, rowBounds);
verify(myBatisDbSession).selectMap(str, parameter, mapKey, rowBounds);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
ResultHandler handler = mock(ResultHandler.class);
dbSession.select(str, handler);
verify(myBatisDbSession).select(str, handler);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
Object parameter = new Object();
ResultHandler handler = mock(ResultHandler.class);
dbSession.select(str, parameter, handler);
verify(myBatisDbSession).select(str, parameter, handler);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
Object parameter = new Object();
ResultHandler handler = mock(ResultHandler.class);
RowBounds rowBounds = new RowBounds();
dbSession.select(str, parameter, rowBounds, handler);
verify(myBatisDbSession).select(str, parameter, rowBounds, handler);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
dbSession.insert(str);
verify(myBatisDbSession).insert(str);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
Object object = new Object();
dbSession.insert(str, object);
verify(myBatisDbSession).insert(str, object);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
dbSession.update(str);
verify(myBatisDbSession).update(str);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
Object object = new Object();
dbSession.update(str, object);
verify(myBatisDbSession).update(str, object);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
dbSession.delete(str);
verify(myBatisDbSession).delete(str);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
String str = randomAlphabetic(10);
Object object = new Object();
dbSession.delete(str, object);
verify(myBatisDbSession).delete(str, object);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
dbSession.flushStatements();
verify(myBatisDbSession).flushStatements();
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
dbSession.clearCache();
verify(myBatisDbSession).clearCache();
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
Configuration expected = mock(Configuration.class);
when(myBatisDbSession.getConfiguration()).thenReturn(expected);
assertThat(dbSession.getConfiguration()).isSameAs(expected);
verify(myBatisDbSession).getConfiguration();
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
Class<Object> clazz = Object.class;
Object expected = new Object();
when(myBatisDbSession.getMapper(clazz)).thenReturn(expected);
assertThat(dbSession.getMapper(clazz)).isSameAs(expected);
verify(myBatisDbSession).getMapper(clazz);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
Connection connection = mock(Connection.class);
when(myBatisDbSession.getConnection()).thenReturn(connection);
assertThat(dbSession.getConnection()).isSameAs(connection);
verify(myBatisDbSession).getConnection();
});
}
@Test
public void openSession_with_caching_returns_DbSession_that_rolls_back_on_close_if_any_mutation_call_was_not_followed_by_commit_nor_rollback() throws SQLException {
DbSession dbSession = openSessionAndDoSeveralMutatingAndNeutralCalls();
dbSession.close();
verify(myBatisDbSession).rollback();
}
@Test
public void openSession_with_caching_returns_DbSession_that_does_not_roll_back_on_close_if_any_mutation_call_was_followed_by_commit() throws SQLException {
DbSession dbSession = openSessionAndDoSeveralMutatingAndNeutralCalls();
COMMIT_CALLS[random.nextBoolean() ? 0 : 1].consume(dbSession);
dbSession.close();
verify(myBatisDbSession, times(0)).rollback();
}
@Test
public void openSession_with_caching_returns_DbSession_that_does_not_roll_back_on_close_if_any_mutation_call_was_followed_by_rollback_without_parameters() throws SQLException {
DbSession dbSession = openSessionAndDoSeveralMutatingAndNeutralCalls();
dbSession.rollback();
dbSession.close();
verify(myBatisDbSession, times(1)).rollback();
}
@Test
public void openSession_with_caching_returns_DbSession_that_does_not_roll_back_on_close_if_any_mutation_call_was_followed_by_rollback_with_parameters() throws SQLException {
boolean force = random.nextBoolean();
DbSession dbSession = openSessionAndDoSeveralMutatingAndNeutralCalls();
dbSession.rollback(force);
dbSession.close();
verify(myBatisDbSession, times(1)).rollback(force);
verify(myBatisDbSession, times(0)).rollback();
}
private DbSession openSessionAndDoSeveralMutatingAndNeutralCalls() throws SQLException {
boolean batchOrRegular = random.nextBoolean();
when(myBatis.openSession(batchOrRegular))
.thenReturn(myBatisDbSession)
.thenThrow(oneCallTooMuch());
underTest.enableCaching();
DbSession dbSession = underTest.openSession(batchOrRegular);
int dirtyingCallsCount = 1 + abs(random.nextInt(5));
int neutralCallsCount = abs(random.nextInt(5));
int[] dirtyCallIndices = IntStream.range(0, dirtyingCallsCount).map(ignored -> abs(random.nextInt(DIRTYING_CALLS.length))).toArray();
int[] neutralCallsIndices = IntStream.range(0, neutralCallsCount).map(ignored -> abs(random.nextInt(NEUTRAL_CALLS.length))).toArray();
for (int index : dirtyCallIndices) {
DIRTYING_CALLS[index].consume(dbSession);
}
for (int index : neutralCallsIndices) {
NEUTRAL_CALLS[index].consume(dbSession);
}
return dbSession;
}
private static DbSessionCaller[] DIRTYING_CALLS = {
session -> session.insert(randomAlphabetic(3)),
session -> session.insert(randomAlphabetic(2), new Object()),
session -> session.update(randomAlphabetic(3)),
session -> session.update(randomAlphabetic(3), new Object()),
session -> session.delete(randomAlphabetic(3)),
session -> session.delete(randomAlphabetic(3), new Object()),
};
private static DbSessionCaller[] COMMIT_CALLS = {
session -> session.commit(),
session -> session.commit(new Random().nextBoolean()),
};
private static DbSessionCaller[] ROLLBACK_CALLS = {
session -> session.rollback(),
session -> session.rollback(new Random().nextBoolean()),
};
private static DbSessionCaller[] NEUTRAL_CALLS = {
session -> session.selectOne(randomAlphabetic(3)),
session -> session.selectOne(randomAlphabetic(3), new Object()),
session -> session.select(randomAlphabetic(3), mock(ResultHandler.class)),
session -> session.select(randomAlphabetic(3), new Object(), mock(ResultHandler.class)),
session -> session.select(randomAlphabetic(3), new Object(), new RowBounds(), mock(ResultHandler.class)),
session -> session.selectList(randomAlphabetic(3)),
session -> session.selectList(randomAlphabetic(3), new Object()),
session -> session.selectList(randomAlphabetic(3), new Object(), new RowBounds()),
session -> session.selectMap(randomAlphabetic(3), randomAlphabetic(3)),
session -> session.selectMap(randomAlphabetic(3), new Object(), randomAlphabetic(3)),
session -> session.selectMap(randomAlphabetic(3), new Object(), randomAlphabetic(3), new RowBounds()),
session -> session.getMapper(Object.class),
session -> session.getConfiguration(),
session -> session.getConnection(),
session -> session.clearCache(),
session -> session.flushStatements()
};
private interface DbSessionCaller {
void consume(DbSession t) throws SQLException;
}
@Test
public void disableCaching_does_not_open_DB_connection_if_openSession_was_never_called() {
when(myBatis.openSession(anyBoolean()))
.thenThrow(oneCallTooMuch());
underTest.enableCaching();
underTest.disableCaching();
verifyNoMoreInteractions(myBatis);
}
@Test
public void disableCaching_has_no_effect_if_enabledCaching_has_not_been_called() {
underTest.disableCaching();
verifyNoMoreInteractions(myBatis);
}
@Test
public void disableCaching_does_not_fail_but_logs_if_closing_MyBatis_session_close_throws_an_exception() {
boolean batchOrRegular = random.nextBoolean();
IllegalStateException toBeThrown = new IllegalStateException("Faking MyBatisSession#close failing");
when(myBatis.openSession(batchOrRegular))
.thenReturn(myBatisDbSession)
.thenThrow(oneCallTooMuch());
Mockito.doThrow(toBeThrown)
.when(myBatisDbSession).close();
underTest.enableCaching();
underTest.openSession(batchOrRegular);
underTest.disableCaching();
List<String> errorLogs = logTester.logs(Level.ERROR);
assertThat(errorLogs)
.hasSize(1)
.containsOnly("Failed to close " + (batchOrRegular ? "batch" : "regular") + " connection in " + Thread.currentThread());
}
private void verifyFirstDelegation(boolean batchOrRegular, BiConsumer<DbSession, DbSession> r) {
verifyDelegation(batchOrRegular, true, r);
}
private void verifyDelegation(boolean batchOrRegular, BiConsumer<DbSession, DbSession> r) {
verifyDelegation(batchOrRegular, false, r);
}
private void verifyDelegation(boolean batchOrRegular, boolean firstCall, BiConsumer<DbSession, DbSession> r) {
when(myBatis.openSession(batchOrRegular))
.thenReturn(myBatisDbSession)
.thenThrow(oneCallTooMuch());
r.accept(myBatisDbSession, underTest.openSession(batchOrRegular));
verify(myBatisDbSession, times(firstCall ? 1 : 0)).getSqlSession();
verifyNoMoreInteractions(myBatisDbSession);
reset(myBatis, myBatisDbSession);
}
private static IllegalStateException oneCallTooMuch() {
return new IllegalStateException("one call too much");
}
private Set<DbSession> getWrappedDbSessions(Set<DbSession> dbSessions) {
return dbSessions.stream()
.filter(NonClosingDbSession.class::isInstance)
.map(NonClosingDbSession.class::cast)
.map(NonClosingDbSession::getDelegate)
.collect(Collectors.toSet());
}
}
| 20,293 | 37.877395 | 178 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/DaoModuleTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class DaoModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new DaoModule().configure(container);
assertThat(container.getAddedObjects()).hasSizeGreaterThan(1);
}
}
| 1,249 | 34.714286 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/DaoUtilsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.DaoUtils.buildLikeValue;
import static org.sonar.db.WildcardPosition.AFTER;
import static org.sonar.db.WildcardPosition.BEFORE;
import static org.sonar.db.WildcardPosition.BEFORE_AND_AFTER;
public class DaoUtilsTest {
@Test
public void buildLikeValue_with_special_characters() {
String escapedValue = "like-\\/_/%//-value";
String wildcard = "%";
assertThat(buildLikeValue("like-\\_%/-value", BEFORE)).isEqualTo(wildcard + escapedValue);
assertThat(buildLikeValue("like-\\_%/-value", AFTER)).isEqualTo(escapedValue + wildcard);
assertThat(buildLikeValue("like-\\_%/-value", BEFORE_AND_AFTER)).isEqualTo(wildcard + escapedValue + wildcard);
}
}
| 1,648 | 38.261905 | 115 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/DbSessionImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.executor.BatchResult;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class DbSessionImplTest {
private SqlSession sqlSessionMock = mock(SqlSession.class);
private DbSessionImpl underTest = new DbSessionImpl(sqlSessionMock);
@Test
public void all_methods_to_wrapped_SqlSession() {
Random random = new Random();
boolean randomBoolean = random.nextBoolean();
int randomInt = random.nextInt(200);
String randomStatement = randomAlphabetic(10);
Object randomParameter = new Object();
Cursor<Object> mockCursor = mock(Cursor.class);
RowBounds rowBounds = new RowBounds();
Object randomObject = new Object();
List<Object> randomList = new ArrayList<>();
Map<Object, Object> randomMap = new HashMap<>();
String randomMapKey = randomAlphabetic(10);
ResultHandler randomResultHandler = resultContext -> {
// don't care
};
List<BatchResult> randomBatchResults = new ArrayList<>();
Configuration randomConfiguration = new Configuration();
verifyDelegation(DbSessionImpl::commit, s -> verify(s).commit());
verifyDelegation(t -> t.commit(randomBoolean), s -> verify(s).commit(randomBoolean));
verifyDelegation(
sqlSession -> when(sqlSession.selectCursor(randomStatement)).thenReturn(mockCursor),
dbSession -> dbSession.selectCursor(randomStatement),
sqlSession -> {
verify(sqlSession).selectCursor(randomStatement);
return mockCursor;
});
verifyDelegation(
sqlSession -> when(sqlSession.selectCursor(randomStatement, randomParameter)).thenReturn(mockCursor),
dbSession -> dbSession.selectCursor(randomStatement, randomParameter),
sqlSession -> {
verify(sqlSessionMock).selectCursor(randomStatement, randomParameter);
return mockCursor;
});
verifyDelegation(
sqlSession -> when(sqlSession.selectCursor(randomStatement, randomParameter, rowBounds)).thenReturn(mockCursor),
dbSession -> dbSession.selectCursor(randomStatement, randomParameter, rowBounds),
sqlSession -> {
verify(sqlSessionMock).selectCursor(randomStatement, randomParameter, rowBounds);
return mockCursor;
});
verifyDelegation(
sqlSession -> when(sqlSession.selectOne(randomStatement)).thenReturn(randomObject),
dbSession -> dbSession.selectOne(randomStatement),
sqlSession -> {
verify(sqlSession).selectOne(randomStatement);
return randomObject;
});
verifyDelegation(
sqlSession -> when(sqlSession.selectOne(randomStatement, randomParameter)).thenReturn(randomObject),
dbSession -> dbSession.selectOne(randomStatement, randomParameter),
sqlSession -> {
verify(sqlSessionMock).selectOne(randomStatement, randomParameter);
return randomObject;
});
verifyDelegation(
sqlSession -> when(sqlSession.selectList(randomStatement)).thenReturn(randomList),
dbSession -> dbSession.selectList(randomStatement),
sqlSession -> {
verify(sqlSession).selectList(randomStatement);
return randomList;
});
verifyDelegation(
sqlSession -> when(sqlSession.selectList(randomStatement, randomParameter)).thenReturn(randomList),
dbSession -> dbSession.selectList(randomStatement, randomParameter),
sqlSession -> {
verify(sqlSessionMock).selectList(randomStatement, randomParameter);
return randomList;
});
verifyDelegation(
sqlSession -> when(sqlSession.selectList(randomStatement, randomParameter, rowBounds)).thenReturn(randomList),
dbSession -> dbSession.selectList(randomStatement, randomParameter, rowBounds),
sqlSession -> {
verify(sqlSessionMock).selectList(randomStatement, randomParameter, rowBounds);
return randomList;
});
verifyDelegation(
sqlSession -> when(sqlSession.selectMap(randomStatement, randomMapKey)).thenReturn(randomMap),
dbSession -> dbSession.selectMap(randomStatement, randomMapKey),
sqlSession -> {
verify(sqlSession).selectMap(randomStatement, randomMapKey);
return randomMap;
});
verifyDelegation(
sqlSession -> when(sqlSession.selectMap(randomStatement, randomParameter, randomMapKey)).thenReturn(randomMap),
dbSession -> dbSession.selectMap(randomStatement, randomParameter, randomMapKey),
sqlSession -> {
verify(sqlSessionMock).selectMap(randomStatement, randomParameter, randomMapKey);
return randomMap;
});
verifyDelegation(
sqlSession -> when(sqlSession.selectMap(randomStatement, randomParameter, randomMapKey, rowBounds)).thenReturn(randomMap),
dbSession -> dbSession.selectMap(randomStatement, randomParameter, randomMapKey, rowBounds),
sqlSession -> {
verify(sqlSessionMock).selectMap(randomStatement, randomParameter, randomMapKey, rowBounds);
return randomMap;
});
verifyDelegation(
dbSession -> dbSession.select(randomStatement, randomResultHandler),
sqlSession -> verify(sqlSessionMock).select(randomStatement, randomResultHandler));
verifyDelegation(
dbSession -> dbSession.select(randomStatement, randomParameter, randomResultHandler),
sqlSession -> verify(sqlSession).select(randomStatement, randomParameter, randomResultHandler));
verifyDelegation(
dbSession -> dbSession.select(randomStatement, randomParameter, rowBounds, randomResultHandler),
sqlSession -> verify(sqlSessionMock).select(randomStatement, randomParameter, rowBounds, randomResultHandler));
verifyDelegation(
sqlSession -> when(sqlSession.insert(randomStatement)).thenReturn(randomInt),
dbSession -> dbSession.insert(randomStatement),
sqlSession -> {
verify(sqlSession).insert(randomStatement);
return randomInt;
});
verifyDelegation(
sqlSession -> when(sqlSession.insert(randomStatement, randomParameter)).thenReturn(randomInt),
dbSession -> dbSession.insert(randomStatement, randomParameter),
sqlSession -> {
verify(sqlSessionMock).insert(randomStatement, randomParameter);
return randomInt;
});
verifyDelegation(
sqlSession -> when(sqlSession.update(randomStatement)).thenReturn(randomInt),
dbSession -> dbSession.update(randomStatement),
sqlSession -> {
verify(sqlSession).update(randomStatement);
return randomInt;
});
verifyDelegation(
sqlSession -> when(sqlSession.update(randomStatement, randomParameter)).thenReturn(randomInt),
dbSession -> dbSession.update(randomStatement, randomParameter),
sqlSession -> {
verify(sqlSessionMock).update(randomStatement, randomParameter);
return randomInt;
});
verifyDelegation(
sqlSession -> when(sqlSession.delete(randomStatement)).thenReturn(randomInt),
dbSession -> dbSession.delete(randomStatement),
sqlSession -> {
verify(sqlSession).delete(randomStatement);
return randomInt;
});
verifyDelegation(
sqlSession -> when(sqlSession.delete(randomStatement, randomParameter)).thenReturn(randomInt),
dbSession -> dbSession.delete(randomStatement, randomParameter),
sqlSession -> {
verify(sqlSessionMock).delete(randomStatement, randomParameter);
return randomInt;
});
verifyDelegation(DbSessionImpl::rollback, s -> verify(s).rollback());
verifyDelegation(t -> t.rollback(randomBoolean), s -> verify(s).rollback(randomBoolean));
verifyDelegation(
sqlSession -> when(sqlSession.flushStatements()).thenReturn(randomBatchResults),
DbSessionImpl::flushStatements,
sqlSession -> {
verify(sqlSession).flushStatements();
return randomBatchResults;
});
verifyDelegation(DbSessionImpl::close, s -> verify(s).close());
verifyDelegation(DbSessionImpl::clearCache, s -> verify(s).clearCache());
verifyDelegation(
sqlSession -> when(sqlSession.getConfiguration()).thenReturn(randomConfiguration),
DbSessionImpl::getConfiguration,
sqlSession -> {
verify(sqlSession).getConfiguration();
return randomConfiguration;
});
verifyDelegation(
sqlSession -> when(sqlSession.getMapper(DbSessionImplTest.class)).thenReturn(DbSessionImplTest.this),
dbSession -> dbSession.getMapper(DbSessionImplTest.class),
sqlSession -> {
verify(sqlSession).getMapper(DbSessionImplTest.class);
return DbSessionImplTest.this;
});
verifyDelegation(DbSessionImpl::getConnection, s -> verify(s).getConnection());
}
@Test
public void getSqlSession_returns_wrapped_SqlSession_object() {
assertThat(underTest.getSqlSession()).isSameAs(sqlSessionMock);
}
private void verifyDelegation(Consumer<DbSessionImpl> t, Consumer<SqlSession> s) {
reset(sqlSessionMock);
t.accept(underTest);
s.accept(sqlSessionMock);
verifyNoMoreInteractions(sqlSessionMock);
}
private <T> void verifyDelegation(Consumer<SqlSession> prepare, Function<DbSessionImpl, T> t, Function<SqlSession, T> s) {
reset(sqlSessionMock);
prepare.accept(sqlSessionMock);
T value = t.apply(underTest);
T expected = s.apply(sqlSessionMock);
verifyNoMoreInteractions(sqlSessionMock);
if (expected instanceof Number) {
assertThat(value).isEqualTo(expected);
} else {
assertThat(value).isSameAs(expected);
}
}
}
| 11,086 | 40.524345 | 128 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/PaginationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.util.Random;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.Pagination.forPage;
public class PaginationTest {
@Test
public void all_is_page_1_with_MAX_INTEGER_page_size() {
Pagination pagination = Pagination.all();
assertThat(pagination.getPage()).isOne();
assertThat(pagination.getPageSize()).isEqualTo(Integer.MAX_VALUE);
}
@Test
public void all_returns_a_constant() {
assertThat(Pagination.all()).isSameAs(Pagination.all());
}
@Test
public void forPage_fails_with_IAE_if_page_is_0() {
assertThatThrownBy(() -> forPage(0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("page index must be >= 1");
}
@Test
public void forPage_fails_with_IAE_if_page_is_less_than_0() {
assertThatThrownBy(() -> forPage(-Math.abs(new Random().nextInt()) - 1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("page index must be >= 1");
}
@Test
public void andSize_fails_with_IAE_if_size_is_0() {
Pagination.Builder builder = forPage(1);
assertThatThrownBy(() -> builder.andSize(0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("page size must be >= 1");
}
@Test
public void andSize_fails_with_IAE_if_size_is_less_than_0() {
Pagination.Builder builder = forPage(1);
assertThatThrownBy(() -> builder.andSize(-Math.abs(new Random().nextInt()) - 1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("page size must be >= 1");
}
@Test
public void offset_is_computed_from_page_and_size() {
assertThat(forPage(2).andSize(3).getOffset()).isEqualTo(3);
assertThat(forPage(5).andSize(3).getOffset()).isEqualTo(12);
assertThat(forPage(5).andSize(1).getOffset()).isEqualTo(4);
}
@Test
public void startRowNumber_is_computed_from_page_and_size() {
assertThat(forPage(2).andSize(3).getStartRowNumber()).isEqualTo(4);
assertThat(forPage(5).andSize(3).getStartRowNumber()).isEqualTo(13);
assertThat(forPage(5).andSize(1).getStartRowNumber()).isEqualTo(5);
}
@Test
public void endRowNumber_is_computed_from_page_and_size() {
assertThat(forPage(2).andSize(3).getEndRowNumber()).isEqualTo(6);
assertThat(forPage(5).andSize(3).getEndRowNumber()).isEqualTo(15);
assertThat(forPage(5).andSize(1).getEndRowNumber()).isEqualTo(5);
}
}
| 3,334 | 33.381443 | 84 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/StartMyBatisTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
public class StartMyBatisTest {
@Test
public void should_start_mybatis_instance(){
var myBatis = mock(MyBatis.class);
var startMyBatis = new StartMyBatis(myBatis);
startMyBatis.start();
verify(myBatis).start();
verifyNoMoreInteractions(myBatis);
}
}
| 1,312 | 31.02439 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/audit/model/ComponentKeyNewValueTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.model;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ComponentKeyNewValueTest {
@Test
public void toString_generatesValidJson() throws ParseException {
ComponentKeyNewValue newValue = new ComponentKeyNewValue("uuid", "a", "b");
JSONObject jsonObject = (JSONObject) new JSONParser().parse(newValue.toString());
assertThat(jsonObject).hasSize(3);
}
}
| 1,414 | 34.375 | 85 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/audit/model/ComponentNewValueTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.model;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ComponentNewValueTest {
@Test
public void toString_generatesValidJson() throws ParseException {
ComponentNewValue newValue = new ComponentNewValue("uuid", "name", "key", true, "path", "qualifier");
JSONObject jsonObject = (JSONObject) new JSONParser().parse(newValue.toString());
assertThat(jsonObject).hasSize(5);
}
@Test
public void toString_addsPortfolioQualifier() {
ComponentNewValue newValue = new ComponentNewValue("uuid", "name", "key", true, "path", "VW");
assertThat(newValue.toString())
.contains("componentUuid")
.contains("\"qualifier\": \"portfolio\"");
}
@Test
public void toString_project_uuid_and_name_and_isPrivate_withEscapedQuotes() {
ComponentNewValue newValue = new ComponentNewValue("uuid", "the \"best\" name", "key", true,"TRK");
assertThat(newValue.toString())
.contains("\"componentUuid\": \"uuid\"")
.contains("\"componentKey\": \"key\"")
.contains("\"componentName\": \"the \\\"best\\\" name\"")
.contains("\"qualifier\": \"project\"")
.contains("\"isPrivate\": true");
}
@Test
public void toString_project_uuid_and_name_and_key() {
ComponentNewValue newValue = new ComponentNewValue("uuid", "name", "key", "TRK");
assertThat(newValue.toString())
.contains("\"componentUuid\": \"uuid\"")
.contains("\"componentName\": \"name\"")
.contains("\"qualifier\": \"project\"")
.contains("\"componentKey\": \"key\"");
}
@Test
public void toString_project_uuid_and_name_and_key_and_isPrivate_and_description() {
ComponentNewValue newValue = new ComponentNewValue("uuid", true, "name", "key", "description", "TRK");
assertThat(newValue.toString())
.contains("\"componentUuid\": \"uuid\"")
.contains("\"componentName\": \"name\"")
.contains("\"qualifier\": \"project\"")
.contains("\"isPrivate\": true")
.contains("\"componentKey\": \"key\"")
.contains("\"description\": \"description\"");
}
@Test
public void toString_addsProjectQualifier() {
ComponentNewValue newValue = new ComponentNewValue("uuid", "name", "key", true, "path", "TRK");
assertThat(newValue.toString())
.contains("componentUuid")
.contains("\"qualifier\": \"project\"");
}
@Test
public void toString_addsApplicationQualifier() {
ComponentNewValue newValue = new ComponentNewValue("uuid", "name", "key", true, "path", "APP");
assertThat(newValue.toString())
.contains("componentUuid")
.contains("\"qualifier\": \"application\"");
}
}
| 3,660 | 34.201923 | 106 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/audit/model/LicenseNewValueTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.model;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class LicenseNewValueTest {
@Test
public void toStringIsEmptyForNullEdition(){
LicenseNewValue newValue = new LicenseNewValue(null);
assertThat(newValue).hasToString("{}");
}
@Test
public void toStringHasEdition(){
LicenseNewValue newValue = new LicenseNewValue("Developer");
assertThat(newValue.toString()).contains("edition");
}
}
| 1,331 | 32.3 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/audit/model/UserNewValueTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.model;
import java.util.List;
import org.json.simple.parser.JSONParser;
import org.junit.Test;
import org.sonar.db.user.UserDto;
import static java.util.Collections.emptyList;
import static org.junit.Assert.fail;
public class UserNewValueTest {
private static final JSONParser jsonParser = new JSONParser();
@Test
public void toString_givenAllFieldsWithValue_returnValidJSON() {
UserDto userDto = createUserDto();
UserNewValue userNewValue = new UserNewValue(userDto);
String jsonString = userNewValue.toString();
assertValidJSON(jsonString);
}
@Test
public void toString_givenEmptyScmAccount_returnValidJSON() {
UserDto userDto = createUserDto();
userDto.setScmAccounts(emptyList());
UserNewValue userNewValue = new UserNewValue(userDto);
String jsonString = userNewValue.toString();
assertValidJSON(jsonString);
}
@Test
public void toString_givenUserUuidAndUserLogin_returnValidJSON() {
UserNewValue userNewValue = new UserNewValue("userUuid", "userLogin");
String jsonString = userNewValue.toString();
assertValidJSON(jsonString);
}
private static UserDto createUserDto() {
UserDto userDto = new UserDto();
userDto.setName("name");
userDto.setEmail("name@email.com");
userDto.setActive(true);
userDto.setScmAccounts(List.of("github-account", "gitlab-account"));
userDto.setExternalId("name");
userDto.setExternalLogin("name");
userDto.setExternalIdentityProvider("github");
userDto.setLocal(false);
userDto.setLastConnectionDate(System.currentTimeMillis());
return userDto;
}
private void assertValidJSON(String jsonString) {
try {
jsonParser.parse(jsonString);
} catch (Exception e) {
//if the json is invalid the test will fail
fail("UserNewValue.toString() generated invalid JSON. More details: " + e.getMessage());
}
}
}
| 2,763 | 30.770115 | 94 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/audit/model/WebhookNewValueTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.model;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class WebhookNewValueTest {
@Test
public void sanitize_url_replace_url() {
var webhookNewValue = new WebhookNewValue("uuid", "name", "projectUuid", "projectKey", "projectName", "http://admin:admin@localhost.com");
webhookNewValue.sanitizeUrl(s -> s.replace("admin", "*****"));
assertThat(webhookNewValue).hasToString("{"
+ "\"webhookUuid\": \"uuid\","
+ " \"name\": \"name\","
+ " \"url\": \"http://*****:*****@localhost.com\","
+ " \"projectUuid\": \"projectUuid\","
+ " \"projectKey\": \"projectKey\","
+ " \"projectName\": \"projectName\" }");
}
@Test
public void sanitize_url_do_nothing_when_url_is_null() {
var webhookNewValue = new WebhookNewValue("uuid", "name", "projectUuid", "projectKey", "projectName", null);
webhookNewValue.sanitizeUrl(s -> s.replace("admin", "*****"));
assertThat(webhookNewValue).hasToString("{"
+ "\"webhookUuid\": \"uuid\","
+ " \"name\": \"name\","
+ " \"projectUuid\": \"projectUuid\","
+ " \"projectKey\": \"projectKey\","
+ " \"projectName\": \"projectName\" }");
}
}
| 2,079 | 37.518519 | 142 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeActivityDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Random;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(DataProviderRunner.class)
public class CeActivityDtoTest {
private static final String STR_40_CHARS = "0123456789012345678901234567890123456789";
private static final String STR_100_CHARS = randomAlphabetic(100);
private CeActivityDto underTest = new CeActivityDto();
@Test
public void constructor_from_CeQueueDto_populates_fields() {
long now = new Random().nextLong();
CeQueueDto ceQueueDto = new CeQueueDto()
.setUuid(randomAlphanumeric(10))
.setTaskType(randomAlphanumeric(11))
.setComponentUuid(randomAlphanumeric(12))
.setEntityUuid(randomAlphanumeric(13))
.setSubmitterUuid(randomAlphanumeric(14))
.setWorkerUuid(randomAlphanumeric(15))
.setCreatedAt(now + 9_999)
.setStartedAt(now + 865);
CeActivityDto underTest = new CeActivityDto(ceQueueDto);
assertThat(underTest.getUuid()).isEqualTo(ceQueueDto.getUuid());
assertThat(underTest.getTaskType()).isEqualTo(ceQueueDto.getTaskType());
assertThat(underTest.getComponentUuid()).isEqualTo(ceQueueDto.getComponentUuid());
assertThat(underTest.getEntityUuid()).isEqualTo(ceQueueDto.getEntityUuid());
assertThat(underTest.getIsLastKey()).isEqualTo(ceQueueDto.getTaskType() + ceQueueDto.getComponentUuid());
assertThat(underTest.getIsLast()).isFalse();
assertThat(underTest.getMainIsLastKey()).isEqualTo(ceQueueDto.getTaskType() + ceQueueDto.getEntityUuid());
assertThat(underTest.getMainIsLast()).isFalse();
assertThat(underTest.getSubmitterUuid()).isEqualTo(ceQueueDto.getSubmitterUuid());
assertThat(underTest.getWorkerUuid()).isEqualTo(ceQueueDto.getWorkerUuid());
assertThat(underTest.getSubmittedAt()).isEqualTo(ceQueueDto.getCreatedAt());
assertThat(underTest.getStartedAt()).isEqualTo(ceQueueDto.getStartedAt());
assertThat(underTest.getStatus()).isNull();
}
@Test
public void setComponentUuid_accepts_null_empty_and_string_40_chars_or_less() {
underTest.setComponentUuid(null);
underTest.setComponentUuid("");
underTest.setComponentUuid("bar");
underTest.setComponentUuid(STR_40_CHARS);
}
@Test
public void setComponentUuid_throws_IAE_if_value_is_41_chars() {
String str_41_chars = STR_40_CHARS + "a";
assertThatThrownBy(() -> underTest.setComponentUuid(str_41_chars))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value is too long for column CE_ACTIVITY.COMPONENT_UUID: " + str_41_chars);
}
@Test
public void setMainComponentUuid_accepts_null_empty_and_string_40_chars_or_less() {
underTest.setEntityUuid(null);
underTest.setEntityUuid("");
underTest.setEntityUuid("bar");
underTest.setEntityUuid(STR_40_CHARS);
}
@Test
public void seEntityUuid_throws_IAE_if_value_is_41_chars() {
String str_41_chars = STR_40_CHARS + "a";
assertThatThrownBy(() -> underTest.setEntityUuid(str_41_chars))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value is too long for column CE_ACTIVITY.ENTITY_UUID: " + str_41_chars);
}
@Test
public void setNodeName_accepts_null_empty_and_string_100_chars_or_less() {
underTest.setNodeName(null);
underTest.setNodeName("");
underTest.setNodeName("bar");
underTest.setNodeName(STR_100_CHARS);
assertThat(underTest.getNodeName()).isEqualTo(STR_100_CHARS);
}
@Test
public void setNodeName_ifMoreThan100chars_truncates() {
underTest.setNodeName(STR_100_CHARS + "This should be truncated");
assertThat(underTest.getNodeName()).isEqualTo(STR_100_CHARS);
}
@Test
@UseDataProvider("stringsWithChar0")
public void setStacktrace_filters_out_char_zero(String withChar0, String expected) {
underTest.setErrorStacktrace(withChar0);
assertThat(underTest.getErrorStacktrace()).isEqualTo(expected);
}
@Test
@UseDataProvider("stringsWithChar0")
public void setErrorMessage_filters_out_char_zero(String withChar0, String expected) {
underTest.setErrorMessage(withChar0);
assertThat(underTest.getErrorMessage()).isEqualTo(expected);
}
@Test
public void setErrorMessage_truncates_to_1000_after_removing_char_zero() {
String before = randomAlphanumeric(50);
String after = randomAlphanumeric(950);
String truncated = randomAlphanumeric(1 + new Random().nextInt(50));
underTest.setErrorMessage(before + "\u0000" + after + truncated);
assertThat(underTest.getErrorMessage()).isEqualTo(before + after);
}
@DataProvider
public static Object[][] stringsWithChar0() {
return new Object[][] {
{"\u0000", ""},
{"\u0000\u0000\u0000\u0000", ""},
{"\u0000 \u0000a\u0000b\u0000 ", " ab "},
{"a \u0000 0message", "a 0message"}
};
}
}
| 6,103 | 38.380645 | 110 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeQueueDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class CeQueueDtoTest {
private static final String STR_15_CHARS = "012345678901234";
private static final String STR_40_CHARS = "0123456789012345678901234567890123456789";
private static final String STR_255_CHARS = STR_40_CHARS + STR_40_CHARS + STR_40_CHARS + STR_40_CHARS
+ STR_40_CHARS + STR_40_CHARS + STR_15_CHARS;
private CeQueueDto underTest = new CeQueueDto();
@Test
public void setComponentUuid_accepts_null_empty_and_string_40_chars_or_less() {
underTest.setComponentUuid(null);
underTest.setComponentUuid("");
underTest.setComponentUuid("bar");
underTest.setComponentUuid(STR_40_CHARS);
}
@Test
public void setComponentUuid_throws_IAE_if_value_is_41_chars() {
String str_41_chars = STR_40_CHARS + "a";
assertThatThrownBy(() -> underTest.setComponentUuid(str_41_chars))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value is too long for column CE_QUEUE.COMPONENT_UUID: " + str_41_chars);
}
@Test
public void setEntityUuid_accepts_null_empty_and_string_40_chars_or_less() {
underTest.setEntityUuid(null);
underTest.setEntityUuid("");
underTest.setEntityUuid("bar");
underTest.setEntityUuid(STR_40_CHARS);
}
@Test
public void setEntityUuid_throws_IAE_if_value_is_41_chars() {
String str_41_chars = STR_40_CHARS + "a";
assertThatThrownBy(() -> underTest.setEntityUuid(str_41_chars))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value is too long for column CE_QUEUE.ENTITY_UUID: " + str_41_chars);
}
@Test
public void setTaskType_throws_NPE_if_argument_is_null() {
assertThatThrownBy(() -> underTest.setTaskType(null))
.isInstanceOf(NullPointerException.class);
}
@Test
public void setTaskType_accepts_empty_and_string_15_chars_or_less() {
underTest.setTaskType("");
underTest.setTaskType("bar");
underTest.setTaskType(STR_15_CHARS);
}
@Test
public void setTaskType_throws_IAE_if_value_is_41_chars() {
String str_41_chars = STR_40_CHARS + "a";
assertThatThrownBy(() -> underTest.setTaskType(str_41_chars))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value of task type is too long: " + str_41_chars);
}
@Test
public void setSubmitterLogin_accepts_null_empty_and_string_255_chars_or_less() {
underTest.setSubmitterUuid(null);
underTest.setSubmitterUuid("");
underTest.setSubmitterUuid("bar");
underTest.setSubmitterUuid(STR_255_CHARS);
}
@Test
public void setSubmitterLogin_throws_IAE_if_value_is_41_chars() {
String str_256_chars = STR_255_CHARS + "a";
assertThatThrownBy(() -> underTest.setSubmitterUuid(str_256_chars))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value of submitter uuid is too long: " + str_256_chars);
}
}
| 3,789 | 34.754717 | 103 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskCharacteristicDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class CeTaskCharacteristicDtoTest {
@Test
public void test_set_get() {
CeTaskCharacteristicDto dto = new CeTaskCharacteristicDto();
dto.setKey("key");
dto.setValue("value");
dto.setTaskUuid("task");
dto.setUuid("uuid");
assertThat(dto.getKey()).isEqualTo("key");
assertThat(dto.getValue()).isEqualTo("value");
assertThat(dto.getTaskUuid()).isEqualTo("task");
assertThat(dto.getUuid()).isEqualTo("uuid");
}
}
| 1,411 | 32.619048 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskDtoLightTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class CeTaskDtoLightTest {
private final CeTaskDtoLight task1 = new CeTaskDtoLight();
private final CeTaskDtoLight task2 = new CeTaskDtoLight();
private final CeTaskDtoLight task3 = new CeTaskDtoLight();
private final CeTaskDtoLight task4 = new CeTaskDtoLight();
@Before
public void setUp() {
task1.setCeTaskUuid("id1");
task1.setCreatedAt(1);
task2.setCeTaskUuid("id1");
task2.setCreatedAt(1);
task3.setCeTaskUuid("id2");
task3.setCreatedAt(1);
task4.setCeTaskUuid("id1");
task4.setCreatedAt(2);
}
@Test
public void equals_is_based_on_created_date_and_uuid() {
assertThat(task1)
.isEqualTo(task2)
.isNotEqualTo(task3)
.isNotEqualTo(task4);
}
@Test
public void hashCode_is_based_on_created_date_and_uuid() {
assertThat(task1).hasSameHashCodeAs(task2);
}
@Test
public void compareTo_is_based_on_created_date_and_uuid() {
assertThat(task1)
.isEqualByComparingTo(task2)
.isLessThan(task3)
.isLessThan(task4);
}
}
| 2,010 | 29.469697 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskMessageDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 org.junit.Test;
import static org.apache.commons.lang.StringUtils.repeat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.ce.CeTaskMessageDto.MAX_MESSAGE_SIZE;
public class CeTaskMessageDtoTest {
private CeTaskMessageDto underTest = new CeTaskMessageDto();
@Test
public void setMessage_fails_with_IAE_if_argument_is_null() {
assertThatThrownBy(() -> underTest.setMessage(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("message can't be null nor empty");
}
@Test
public void setMessage_fails_with_IAE_if_argument_is_empty() {
assertThatThrownBy(() -> underTest.setMessage(""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("message can't be null nor empty");
}
@Test
public void setMessage_accept_argument_of_size_4000() {
String str = repeat("a", MAX_MESSAGE_SIZE);
underTest.setMessage(str);
assertThat(underTest.getMessage()).isEqualTo(str);
}
@Test
public void setMessage_truncates_the_message_if_argument_has_size_bigger_then_4000() {
String str = repeat("a", MAX_MESSAGE_SIZE) + "extra long tail!!!";
underTest.setMessage(str);
assertThat(underTest.getMessage()).isEqualTo(repeat("a", MAX_MESSAGE_SIZE - 3) + "...");
}
}
| 2,227 | 33.8125 | 92 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskQueryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
public class CeTaskQueryTest {
CeTaskQuery underTest = new CeTaskQuery();
@Test
public void no_filter_on_entity_uuids_by_default() {
assertThat(underTest.getEntityUuids()).isNull();
assertThat(underTest.isShortCircuitedByEntityUuids()).isFalse();
}
@Test
public void filter_on_entity_uuid() {
underTest.setEntityUuid("UUID1");
assertThat(underTest.getEntityUuids()).containsOnly("UUID1");
assertThat(underTest.isShortCircuitedByEntityUuids()).isFalse();
}
@Test
public void filter_on_multiple_entity_uuids() {
underTest.setEntityUuids(asList("UUID1", "UUID2"));
assertThat(underTest.getEntityUuids()).containsOnly("UUID1", "UUID2");
assertThat(underTest.isShortCircuitedByEntityUuids()).isFalse();
}
/**
* entityUuid is not null but is set to empty
* --> no results
*/
@Test
public void short_circuited_if_empty_entity_uuid_filter() {
underTest.setEntityUuids(Collections.emptyList());
assertThat(underTest.getEntityUuids()).isEmpty();
assertThat(underTest.isShortCircuitedByEntityUuids()).isTrue();
}
/**
* too many entityUuids for SQL request. Waiting for ES to improve this use-case
* --> no results
*/
@Test
public void short_circuited_if_too_many_entity_uuid_filters() {
List<String> uuids = new ArrayList<>();
for (int i = 0; i < CeTaskQuery.MAX_COMPONENT_UUIDS + 2; i++) {
uuids.add(String.valueOf(i));
}
underTest.setEntityUuids(uuids);
assertThat(underTest.getEntityUuids()).hasSize(CeTaskQuery.MAX_COMPONENT_UUIDS + 2);
assertThat(underTest.isShortCircuitedByEntityUuids()).isTrue();
}
@Test
public void test_errorTypes() {
assertThat(underTest.getErrorTypes()).isNull();
underTest.setErrorTypes(asList("foo", "bar"));
assertThat(underTest.getErrorTypes()).containsExactlyInAnyOrder("foo", "bar");
}
@Test
public void test_minExecutedAt() {
assertThat(underTest.getMinExecutedAt()).isNull();
underTest.setMinExecutedAt(1_000L);
assertThat(underTest.getMinExecutedAt()).isEqualTo(1_000L);
}
}
| 3,148 | 31.802083 | 88 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/ce/LogsIteratorInputStreamTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.IOException;
import java.util.Arrays;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.sonar.core.util.CloseableIterator;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class LogsIteratorInputStreamTest {
@Test
public void read_from_ClosableIterator_with_several_lines() throws IOException {
assertThat(read(create("line1", "line2", "line3"))).isEqualTo("line1" + '\n' + "line2" + '\n' + "line3");
}
@Test
public void read_from_ClosableIterator_with_single_line() throws IOException {
assertThat(read(create("line1"))).isEqualTo("line1");
}
@Test
public void read_from_ClosableIterator_with_single_empty_line() throws IOException {
assertThat(read(create(""))).isEmpty();
}
@Test
public void read_from_ClosableIterator_with_several_empty_lines() throws IOException {
assertThat(read(create("", "line2", "", "line4", "", "", "", "line8", "")))
.isEqualTo('\n' + "line2" + '\n' + '\n' + "line4" + '\n' + '\n' + '\n' + '\n' + "line8" + '\n');
}
@Test
public void constructor_throws_IAE_when_ClosableIterator_is_empty() {
assertThatThrownBy(LogsIteratorInputStreamTest::create)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("LogsIterator can't be empty or already read");
}
@Test
public void constructor_throws_IAE_when_ClosableIterator_has_already_been_read() {
CloseableIterator<String> iterator = CloseableIterator.from(Arrays.asList("line1").iterator());
// read iterator to the end
iterator.next();
assertThatThrownBy(() -> new LogsIteratorInputStream(iterator, UTF_8))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("LogsIterator can't be empty or already read");
}
private static LogsIteratorInputStream create(String... lines) {
return new LogsIteratorInputStream(CloseableIterator.from(Arrays.asList(lines).iterator()), UTF_8);
}
private static String read(LogsIteratorInputStream logsIteratorInputStream) throws IOException {
return IOUtils.toString(logsIteratorInputStream, UTF_8);
}
}
| 3,092 | 36.719512 | 109 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/ce/UpdateIfTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Random;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(DataProviderRunner.class)
public class UpdateIfTest {
private static final String STR_40_CHARS = "0123456789012345678901234567890123456789";
@Test
public void newProperties_constructor_accepts_null_workerUuid() {
UpdateIf.NewProperties newProperties = new UpdateIf.NewProperties(CeQueueDto.Status.PENDING, null, 123, 456);
assertThat(newProperties.getWorkerUuid()).isNull();
}
@Test
public void newProperties_constructor_fails_with_NPE_if_status_is_null() {
assertThatThrownBy(() -> new UpdateIf.NewProperties(null, "foo", 123, 456))
.isInstanceOf(NullPointerException.class)
.hasMessage("status can't be null");
}
@Test
public void newProperties_constructor_fails_with_IAE_if_workerUuid_is_41_or_more() {
String workerUuid = RandomStringUtils.randomAlphanumeric(41 + new Random().nextInt(5));
assertThatThrownBy(() -> new UpdateIf.NewProperties(CeQueueDto.Status.PENDING, workerUuid, 123, 456))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("worker uuid is too long: " + workerUuid);
}
@Test
@UseDataProvider("workerUuidValidValues")
public void newProperties_constructor_accepts_null_empty_and_string_40_chars_or_less(String workerUuid) {
new UpdateIf.NewProperties(CeQueueDto.Status.PENDING, workerUuid, 123, 345);
}
@DataProvider
public static Object[][] workerUuidValidValues() {
return new Object[][] {
{null},
{""},
{"bar"},
{STR_40_CHARS}
};
}
@Test
public void newProperties_constructor_IAE_if_workerUuid_is_41_chars() {
String str_41_chars = STR_40_CHARS + "a";
assertThatThrownBy(() -> new UpdateIf.NewProperties(CeQueueDto.Status.PENDING, str_41_chars, 123, 345))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("worker uuid is too long: " + str_41_chars);
}
}
| 3,159 | 36.619048 | 113 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/component/AnalysisPropertyDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 org.junit.Test;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class AnalysisPropertyDtoTest {
private AnalysisPropertyDto underTest;
@Test
public void null_key_should_throw_NPE() {
underTest = new AnalysisPropertyDto();
assertThatThrownBy(() -> underTest.setKey(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("key cannot be null");
}
@Test
public void null_value_should_throw_NPE() {
underTest = new AnalysisPropertyDto();
assertThatThrownBy(() -> underTest.setValue(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("value cannot be null");
}
@Test
public void null_uuid_should_throw_NPE() {
underTest = new AnalysisPropertyDto();
assertThatThrownBy(() -> underTest.setUuid(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("uuid cannot be null");
}
@Test
public void null_analysis_uuid_should_throw_NPE() {
underTest = new AnalysisPropertyDto();
assertThatThrownBy(() -> underTest.setAnalysisUuid(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("analysisUuid cannot be null");
}
@Test
public void test_equality() {
underTest = new AnalysisPropertyDto()
.setUuid(randomAlphanumeric(40))
.setAnalysisUuid(randomAlphanumeric(40))
.setKey(randomAlphanumeric(512))
.setValue(randomAlphanumeric(10000));
assertThat(underTest)
.isEqualTo(
new AnalysisPropertyDto()
.setUuid(underTest.getUuid())
.setAnalysisUuid(underTest.getAnalysisUuid())
.setKey(underTest.getKey())
.setValue(underTest.getValue()))
.isNotEqualTo(
new AnalysisPropertyDto()
.setUuid("1" + underTest.getUuid())
.setAnalysisUuid(underTest.getAnalysisUuid())
.setKey(underTest.getKey())
.setValue(underTest.getValue()))
.isNotEqualTo(
new AnalysisPropertyDto()
.setUuid(underTest.getUuid())
.setAnalysisUuid("1" + underTest.getAnalysisUuid())
.setKey(underTest.getKey())
.setValue(underTest.getValue()))
.isNotEqualTo(
new AnalysisPropertyDto()
.setUuid(underTest.getUuid())
.setAnalysisUuid(underTest.getAnalysisUuid())
.setKey("1" + underTest.getKey())
.setValue(underTest.getValue()))
.isNotEqualTo(
new AnalysisPropertyDto()
.setUuid(underTest.getUuid())
.setAnalysisUuid(underTest.getAnalysisUuid())
.setKey(underTest.getKey())
.setValue("1" + underTest.getValue()));
}
@Test
public void test_hashcode() {
underTest = new AnalysisPropertyDto()
.setUuid(randomAlphanumeric(40))
.setAnalysisUuid(randomAlphanumeric(40))
.setKey(randomAlphanumeric(512))
.setValue(randomAlphanumeric(10000));
assertThat(underTest.hashCode()).isEqualTo(
new AnalysisPropertyDto()
.setUuid(underTest.getUuid())
.setAnalysisUuid(underTest.getAnalysisUuid())
.setKey(underTest.getKey())
.setValue(underTest.getValue())
.hashCode());
assertThat(underTest.hashCode()).isNotEqualTo(
new AnalysisPropertyDto()
.setUuid("1" + underTest.getUuid())
.setAnalysisUuid(underTest.getAnalysisUuid())
.setKey(underTest.getKey())
.setValue(underTest.getValue())
.hashCode());
assertThat(underTest.hashCode()).isNotEqualTo(
new AnalysisPropertyDto()
.setUuid(underTest.getUuid())
.setAnalysisUuid("1" + underTest.getAnalysisUuid())
.setKey(underTest.getKey())
.setValue(underTest.getValue())
.hashCode());
assertThat(underTest.hashCode()).isNotEqualTo(
new AnalysisPropertyDto()
.setUuid(underTest.getUuid())
.setAnalysisUuid(underTest.getAnalysisUuid())
.setKey("1" + underTest.getKey())
.setValue(underTest.getValue())
.hashCode());
assertThat(underTest.hashCode()).isNotEqualTo(
new AnalysisPropertyDto()
.setUuid(underTest.getUuid())
.setAnalysisUuid(underTest.getAnalysisUuid())
.setKey(underTest.getKey())
.setValue("1" + underTest.getValue())
.hashCode());
}
}
| 5,305 | 32.582278 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/component/BranchDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 org.junit.Test;
import org.sonar.db.protobuf.DbProjectBranches;
import static org.assertj.core.api.Assertions.assertThat;
public class BranchDtoTest {
private final BranchDto underTest = new BranchDto();
@Test
public void verify_toString() {
underTest.setUuid("U1");
underTest.setProjectUuid("U2");
underTest.setIsMain(false);
underTest.setKey("K1");
underTest.setBranchType(BranchType.BRANCH);
underTest.setMergeBranchUuid("U3");
underTest.setExcludeFromPurge(true);
assertThat(underTest).hasToString("BranchDto{uuid='U1', " +
"projectUuid='U2', isMain='false', kee='K1', branchType=BRANCH, mergeBranchUuid='U3', excludeFromPurge=true, needIssueSync=false}");
}
@Test
public void verify_equals() {
underTest.setUuid("U1");
underTest.setProjectUuid("U2");
underTest.setIsMain(true);
underTest.setKey("K1");
underTest.setBranchType(BranchType.BRANCH);
underTest.setMergeBranchUuid("U3");
BranchDto toCompare = new BranchDto();
toCompare.setUuid("U1");
toCompare.setProjectUuid("U2");
toCompare.setIsMain(true);
toCompare.setKey("K1");
toCompare.setBranchType(BranchType.BRANCH);
toCompare.setMergeBranchUuid("U3");
assertThat(underTest).isEqualTo(toCompare);
}
@Test
public void encode_and_decode_pull_request_data() {
String branch = "feature/pr1";
String title = "Dummy Feature Title";
String url = "http://example.com/pullRequests/pr1";
DbProjectBranches.PullRequestData pullRequestData = DbProjectBranches.PullRequestData.newBuilder()
.setBranch(branch)
.setTitle(title)
.setUrl(url)
.build();
underTest.setPullRequestData(pullRequestData);
DbProjectBranches.PullRequestData decoded = underTest.getPullRequestData();
assertThat(decoded).isNotNull();
assertThat(decoded.getBranch()).isEqualTo(branch);
assertThat(decoded.getTitle()).isEqualTo(title);
assertThat(decoded.getUrl()).isEqualTo(url);
}
@Test
public void getPullRequestData_returns_null_when_data_is_null() {
assertThat(underTest.getPullRequestData()).isNull();
}
}
| 3,014 | 31.771739 | 138 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 org.junit.Test;
import org.sonar.api.resources.Scopes;
import static org.assertj.core.api.Assertions.assertThat;
public class ComponentDtoTest {
@Test
public void setters_and_getters() {
ComponentDto componentDto = new ComponentDto()
.setKey("org.struts:struts-core:src/org/struts/RequestContext.java")
.setName("RequestContext.java")
.setLongName("org.struts.RequestContext")
.setQualifier("FIL")
.setScope("FIL")
.setLanguage("java")
.setDescription("desc")
.setPath("src/org/struts/RequestContext.java")
.setCopyComponentUuid("uuid_5");
assertThat(componentDto.getKey()).isEqualTo("org.struts:struts-core:src/org/struts/RequestContext.java");
assertThat(componentDto.name()).isEqualTo("RequestContext.java");
assertThat(componentDto.longName()).isEqualTo("org.struts.RequestContext");
assertThat(componentDto.qualifier()).isEqualTo("FIL");
assertThat(componentDto.scope()).isEqualTo("FIL");
assertThat(componentDto.path()).isEqualTo("src/org/struts/RequestContext.java");
assertThat(componentDto.language()).isEqualTo("java");
assertThat(componentDto.description()).isEqualTo("desc");
assertThat(componentDto.getCopyComponentUuid()).isEqualTo("uuid_5");
assertThat(componentDto.isPrivate()).isFalse();
}
@Test
public void equals_and_hashcode() {
ComponentDto dto = new ComponentDto().setUuid("u1");
ComponentDto dtoWithSameUuid = new ComponentDto().setUuid("u1");
ComponentDto dtoWithDifferentUuid = new ComponentDto().setUuid("u2");
assertThat(dto)
.isEqualTo(dto)
.isEqualTo(dtoWithSameUuid)
.isNotEqualTo(dtoWithDifferentUuid)
.hasSameHashCodeAs(dto)
.hasSameHashCodeAs(dtoWithSameUuid);
assertThat(dto.hashCode()).isNotEqualTo(dtoWithDifferentUuid.hashCode());
}
@Test
public void toString_does_not_fail_if_empty() {
ComponentDto dto = new ComponentDto();
assertThat(dto.toString()).isNotEmpty();
}
@Test
public void is_root_project() {
assertThat(new ComponentDto().setUuid("uuid").setBranchUuid("branch").isRootProject()).isFalse();
assertThat(new ComponentDto().setScope(Scopes.DIRECTORY).setUuid("uuid").setBranchUuid("uuid").isRootProject()).isFalse();
assertThat(new ComponentDto().setScope(Scopes.PROJECT).setUuid("uuid").setBranchUuid("uuid").isRootProject()).isTrue();
}
@Test
public void formatUuidPathFromParent() {
ComponentDto parent = ComponentTesting.newPrivateProjectDto("123").setUuidPath(ComponentDto.UUID_PATH_OF_ROOT);
assertThat(ComponentDto.formatUuidPathFromParent(parent)).isEqualTo(".123.");
}
@Test
public void getUuidPathLikeIncludingSelf() {
ComponentDto project = ComponentTesting.newPrivateProjectDto().setUuidPath(ComponentDto.UUID_PATH_OF_ROOT);
assertThat(project.getUuidPathLikeIncludingSelf()).isEqualTo("." + project.uuid() + ".%");
ComponentDto dir = ComponentTesting.newDirectory(project, "path");
assertThat(dir.getUuidPathLikeIncludingSelf()).isEqualTo("." + project.uuid() + "." + dir.uuid() + ".%");
ComponentDto file = ComponentTesting.newFileDto(project, dir);
assertThat(file.getUuidPathLikeIncludingSelf()).isEqualTo("." + project.uuid() + "." + dir.uuid() + "." + file.uuid() + ".%");
}
@Test
public void getUuidPathAsList() {
ComponentDto root = new ComponentDto().setUuidPath(ComponentDto.UUID_PATH_OF_ROOT);
assertThat(root.getUuidPathAsList()).isEmpty();
ComponentDto nonRoot = new ComponentDto().setUuidPath(".12.34.56.");
assertThat(nonRoot.getUuidPathAsList()).containsExactly("12", "34", "56");
}
}
| 4,516 | 40.440367 | 130 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentQueryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.Date;
import java.util.function.Supplier;
import org.junit.Test;
import static java.util.Collections.emptySet;
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.sonar.api.resources.Qualifiers.PROJECT;
public class ComponentQueryTest {
@Test
public void build_query() {
ComponentQuery underTest = ComponentQuery.builder()
.setNameOrKeyQuery("key")
.setAnyBranchAnalyzedBefore(100L)
.setAnyBranchAnalyzedAfter(200L)
.setCreatedAfter(new Date(300L))
.setQualifiers(PROJECT)
.build();
assertThat(underTest.getNameOrKeyQuery()).isEqualTo("key");
assertThat(underTest.getQualifiers()).containsOnly(PROJECT);
assertThat(underTest.getAnyBranchAnalyzedBefore()).isEqualTo(100L);
assertThat(underTest.getAnyBranchAnalyzedAfter()).isEqualTo(200L);
assertThat(underTest.getCreatedAfter().getTime()).isEqualTo(300L);
assertThat(underTest.isOnProvisionedOnly()).isFalse();
assertThat(underTest.isPartialMatchOnKey()).isFalse();
assertThat(underTest.hasEmptySetOfComponents()).isFalse();
}
@Test
public void build_query_minimal_properties() {
ComponentQuery underTest = ComponentQuery.builder()
.setQualifiers(PROJECT)
.build();
assertThat(underTest.getNameOrKeyQuery()).isNull();
assertThat(underTest.getQualifiers()).containsOnly(PROJECT);
}
@Test
public void test_getNameOrKeyUpperLikeQuery() {
ComponentQuery underTest = ComponentQuery.builder()
.setNameOrKeyQuery("NAME/key")
.setQualifiers(PROJECT)
.build();
assertThat(underTest.getNameOrKeyUpperLikeQuery()).isEqualTo("%NAME//KEY%");
}
@Test
public void empty_list_of_components() {
Supplier<ComponentQuery.Builder> query = () -> ComponentQuery.builder().setQualifiers(PROJECT);
assertThat(query.get().setComponentKeys(emptySet()).build().hasEmptySetOfComponents()).isTrue();
assertThat(query.get().setComponentUuids(emptySet()).build().hasEmptySetOfComponents()).isTrue();
assertThat(query.get().setComponentKeys(singleton("P1")).build().hasEmptySetOfComponents()).isFalse();
assertThat(query.get().setComponentUuids(singleton("U1")).build().hasEmptySetOfComponents()).isFalse();
}
@Test
public void fail_if_no_qualifier_provided() {
assertThatThrownBy(() -> ComponentQuery.builder().build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("At least one qualifier must be provided");
}
@Test
public void fail_if_partial_match_on_key_without_a_query() {
assertThatThrownBy(() -> ComponentQuery.builder().setQualifiers(PROJECT).setPartialMatchOnKey(false).build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("A query must be provided if a partial match on key is specified.");
}
}
| 3,804 | 37.434343 | 113 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentTreeQueryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.db.component.ComponentTreeQuery.Strategy.CHILDREN;
import static org.sonar.db.component.ComponentTreeQuery.Strategy.LEAVES;
public class ComponentTreeQueryTest {
private static final String BASE_UUID = "ABCD";
@Test
public void create_query() {
ComponentTreeQuery query = ComponentTreeQuery.builder()
.setBaseUuid(BASE_UUID)
.setStrategy(CHILDREN)
.setQualifiers(asList("FIL", "DIR"))
.setNameOrKeyQuery("teSt")
.build();
assertThat(query.getBaseUuid()).isEqualTo(BASE_UUID);
assertThat(query.getStrategy()).isEqualTo(CHILDREN);
assertThat(query.getQualifiers()).containsOnly("FIL", "DIR");
assertThat(query.getNameOrKeyQuery()).isEqualTo("teSt");
assertThat(query.getNameOrKeyUpperLikeQuery()).isEqualTo("%TEST%");
}
@Test
public void create_minimal_query() {
ComponentTreeQuery query = ComponentTreeQuery.builder()
.setBaseUuid(BASE_UUID)
.setStrategy(CHILDREN)
.build();
assertThat(query.getBaseUuid()).isEqualTo(BASE_UUID);
assertThat(query.getStrategy()).isEqualTo(CHILDREN);
assertThat(query.getQualifiers()).isNull();
assertThat(query.getNameOrKeyQuery()).isNull();
assertThat(query.getNameOrKeyUpperLikeQuery()).isNull();
}
@Test
public void test_getUuidPath() {
assertThat(ComponentTreeQuery.builder().setBaseUuid(BASE_UUID).setStrategy(CHILDREN)
.build().getUuidPath(newPrivateProjectDto("PROJECT_UUID"))).isEqualTo(".PROJECT_UUID.");
assertThat(ComponentTreeQuery.builder().setBaseUuid(BASE_UUID).setStrategy(LEAVES)
.build().getUuidPath(newPrivateProjectDto("PROJECT_UUID"))).isEqualTo(".PROJECT/_UUID.%");
}
@Test
public void fail_when_no_base_uuid() {
assertThatThrownBy(() -> {
ComponentTreeQuery.builder()
.setStrategy(CHILDREN)
.build();
})
.isInstanceOf(NullPointerException.class);
}
@Test
public void fail_when_no_strategy() {
assertThatThrownBy(() -> {
ComponentTreeQuery.builder()
.setBaseUuid(BASE_UUID)
.build();
})
.isInstanceOf(NullPointerException.class);
}
}
| 3,281 | 33.547368 | 96 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentValidatorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 org.junit.Test;
import static com.google.common.base.Strings.repeat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.test.TestUtils.hasOnlyPrivateConstructors;
public class ComponentValidatorTest {
@Test
public void check_name() {
String name = repeat("a", 500);
assertThat(ComponentValidator.checkComponentName(name)).isEqualTo(name);
}
@Test
public void fail_when_name_longer_than_500_characters() {
assertThatThrownBy(() -> ComponentValidator.checkComponentName(repeat("a", 500 + 1)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Component name length");
}
@Test
public void check_key() {
String key = repeat("a", 400);
assertThat(ComponentValidator.checkComponentKey(key)).isEqualTo(key);
}
@Test
public void fail_when_key_longer_than_400_characters() {
assertThatThrownBy(() -> {
String key = repeat("a", 400 + 1);
ComponentValidator.checkComponentKey(key);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Component key length");
}
@Test
public void check_qualifier() {
String qualifier = repeat("a", 10);
assertThat(ComponentValidator.checkComponentQualifier(qualifier)).isEqualTo(qualifier);
}
@Test
public void fail_when_qualifier_is_longer_than_10_characters() {
assertThatThrownBy(() -> ComponentValidator.checkComponentQualifier(repeat("a", 10 + 1)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Component qualifier length");
}
@Test
public void private_constructor() {
assertThat(hasOnlyPrivateConstructors(ComponentValidator.class)).isTrue();
}
}
| 2,661 | 31.864198 | 93 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/component/ProjectLinkDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ProjectLinkDtoTest {
@Test
public void test_getters_and_setters() {
ProjectLinkDto dto = new ProjectLinkDto()
.setUuid("ABCD")
.setProjectUuid("EFGH")
.setType("homepage")
.setName("Home")
.setHref("http://www.sonarqube.org")
.setCreatedAt(1_000_000_000L)
.setUpdatedAt(5_000_000_000L);
assertThat(dto.getUuid()).isEqualTo("ABCD");
assertThat(dto.getProjectUuid()).isEqualTo("EFGH");
assertThat(dto.getType()).isEqualTo("homepage");
assertThat(dto.getName()).isEqualTo("Home");
assertThat(dto.getHref()).isEqualTo("http://www.sonarqube.org");
assertThat(dto.getCreatedAt()).isEqualTo(1_000_000_000L);
assertThat(dto.getUpdatedAt()).isEqualTo(5_000_000_000L);
}
@Test
public void test_provided_types() {
assertThat(ProjectLinkDto.PROVIDED_TYPES).hasSize(5);
}
}
| 1,826 | 33.471698 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/component/ScrapAnalysisPropertyDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.Random;
import org.junit.Test;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
public class ScrapAnalysisPropertyDtoTest {
private Random random = new Random();
@Test
public void test_empty_value() {
ScrapAnalysisPropertyDto underTest = new ScrapAnalysisPropertyDto();
underTest.setEmpty(true);
assertThat(underTest.getValue()).isEmpty();
}
@Test
public void test_text_set() {
ScrapAnalysisPropertyDto underTest = new ScrapAnalysisPropertyDto();
String value = randomAlphanumeric(random.nextInt(4000));
underTest.setTextValue(value);
assertThat(underTest.getValue()).isEqualTo(value);
}
@Test
public void test_clob_set() {
ScrapAnalysisPropertyDto underTest = new ScrapAnalysisPropertyDto();
String value = randomAlphanumeric(4000 + random.nextInt(4000));
underTest.setClobValue(value);
assertThat(underTest.getValue()).isEqualTo(value);
}
}
| 1,894 | 31.672414 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/component/SnapshotDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 org.junit.Test;
import static org.apache.commons.lang.StringUtils.repeat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.utils.DateUtils.parseDate;
public class SnapshotDtoTest {
@Test
public void test_getter_and_setter() {
SnapshotDto snapshotDto = new SnapshotDto()
.setBuildDate(parseDate("2014-07-02").getTime())
.setRootComponentUuid("uuid_21")
.setLast(true)
.setProjectVersion("1.0")
.setBuildString("1.0.1.123")
.setPeriodMode("mode1")
.setPeriodParam("param1")
.setPeriodDate(parseDate("2014-06-01").getTime());
assertThat(snapshotDto.getBuildDate()).isEqualTo(parseDate("2014-07-02").getTime());
assertThat(snapshotDto.getRootComponentUuid()).isEqualTo("uuid_21");
assertThat(snapshotDto.getLast()).isTrue();
assertThat(snapshotDto.getProjectVersion()).isEqualTo("1.0");
assertThat(snapshotDto.getBuildString()).isEqualTo("1.0.1.123");
assertThat(snapshotDto.getPeriodMode()).isEqualTo("mode1");
assertThat(snapshotDto.getPeriodModeParameter()).isEqualTo("param1");
assertThat(snapshotDto.getPeriodDate()).isEqualTo(parseDate("2014-06-01").getTime());
}
@Test
public void fail_if_projectVersion_is_longer_then_100_characters() {
SnapshotDto snapshotDto = new SnapshotDto();
snapshotDto.setProjectVersion(null);
snapshotDto.setProjectVersion("1.0");
snapshotDto.setProjectVersion(repeat("a", 100));
assertThatThrownBy(() -> snapshotDto.setProjectVersion(repeat("a", 101)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("projectVersion" +
" length (101) is longer than the maximum authorized (100). " +
"'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided.");
}
@Test
public void fail_if_buildString_is_longer_then_100_characters() {
SnapshotDto snapshotDto = new SnapshotDto();
snapshotDto.setBuildString(null);
snapshotDto.setBuildString("1.0");
snapshotDto.setBuildString(repeat("a", 100));
assertThatThrownBy(() -> snapshotDto.setBuildString(repeat("a", 101)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("buildString" +
" length (101) is longer than the maximum authorized (100). " +
"'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided.");
}
}
| 3,410 | 40.597561 | 129 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/component/SnapshotQueryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.component.SnapshotQuery.SORT_FIELD.BY_DATE;
import static org.sonar.db.component.SnapshotQuery.SORT_ORDER.ASC;
public class SnapshotQueryTest {
@Test
public void test_setters_and_getters() {
SnapshotQuery query = new SnapshotQuery()
.setRootComponentUuid("abcd")
.setIsLast(true)
.setStatus("P")
.setProjectVersion("1.0")
.setCreatedAfter(10L)
.setCreatedBefore(20L)
.setSort(BY_DATE, ASC);
assertThat(query.getRootComponentUuid()).isEqualTo("abcd");
assertThat(query.getIsLast()).isTrue();
assertThat(query.getStatus()).isEqualTo(List.of("P"));
assertThat(query.getProjectVersion()).isEqualTo("1.0");
assertThat(query.getCreatedAfter()).isEqualTo(10L);
assertThat(query.getCreatedBefore()).isEqualTo(20L);
assertThat(query.getSortField()).isEqualTo("created_at");
assertThat(query.getSortOrder()).isEqualTo("asc");
query.setStatuses(List.of("P", "L"));
assertThat(query.getStatus()).isEqualTo(List.of("P", "L"));
}
}
| 2,023 | 35.142857 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/createdb/CreateDb.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.createdb;
import com.sonar.orchestrator.config.Configuration;
import com.sonar.orchestrator.db.DatabaseClient;
import com.sonar.orchestrator.db.DatabaseFactory;
import com.sonar.orchestrator.db.DefaultDatabase;
import java.util.function.Consumer;
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.SQDatabase;
public class CreateDb {
public static void main(String[] args) {
createDb(configuration -> {
Settings settings = new MapSettings();
configuration.asMap().forEach(settings::setProperty);
logJdbcSettings(settings);
SQDatabase.newDatabase(settings, true).start();
});
}
private static void createDb(Consumer<Configuration> execute) {
Configuration configuration = Configuration.builder()
.addSystemProperties()
.setProperty("orchestrator.keepDatabase", "false")
.build();
DatabaseClient databaseClient = DatabaseFactory.create(configuration, configuration.locators());
DefaultDatabase defaultDatabase = new DefaultDatabase(databaseClient);
defaultDatabase.killOtherConnections();
try {
defaultDatabase.start();
execute.accept(configuration);
} finally {
defaultDatabase.stop();
}
}
private static void logJdbcSettings(Settings settings) {
Logger logger = LoggerFactory.getLogger(CreateDb.class);
for (String key : settings.getKeysStartingWith("sonar.jdbc")) {
logger.info(key + ": " + settings.getString(key));
}
}
}
| 2,444 | 34.434783 | 100 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/dump/DumpSQSchema.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.dump;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.sql.SQLException;
import org.apache.commons.io.FileUtils;
import static java.nio.charset.StandardCharsets.UTF_8;
public class DumpSQSchema {
public static void main(String[] args) {
SQSchemaDumper dumper = new SQSchemaDumper();
try {
File targetFile = new File("src/schema/schema-sq.ddl");
if (!targetFile.exists()) {
System.out.println("Can not find schema dump file: '" + targetFile + "'");
System.exit(1);
}
Charset charset = UTF_8;
String oldContent = FileUtils.readFileToString(targetFile, charset);
String newContent = dumper.dumpToText();
boolean upToDate = newContent.equals(oldContent);
FileUtils.write(targetFile, newContent, charset);
if (!upToDate) {
System.err.println("SQL Schema dump file has changed. Please review and commit " + targetFile.getAbsolutePath());
System.exit(137);
}
} catch (SQLException | IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
| 1,975 | 33.666667 | 121 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/dump/SQSchemaDumper.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.dump;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import org.sonar.db.SQDatabase;
import static com.google.common.base.Preconditions.checkState;
class SQSchemaDumper {
private static final String LINE_SEPARATOR = System.lineSeparator();
private static final String HEADER = "" +
"###############################################################" + LINE_SEPARATOR +
"#### Description of SonarQube's schema in H2 SQL syntax ####" + LINE_SEPARATOR +
"#### ####" + LINE_SEPARATOR +
"#### This file is autogenerated and stored in SCM to ####" + LINE_SEPARATOR +
"#### conveniently read the SonarQube's schema at any ####" + LINE_SEPARATOR +
"#### point in time. ####" + LINE_SEPARATOR +
"#### ####" + LINE_SEPARATOR +
"#### DO NOT MODIFY THIS FILE DIRECTLY ####" + LINE_SEPARATOR +
"#### use gradle task :server:sonar-db-dao:dumpSchema ####" + LINE_SEPARATOR +
"###############################################################" + LINE_SEPARATOR;
private static final String TABLE_SCHEMA_MIGRATIONS = "SCHEMA_MIGRATIONS";
private static final Comparator<String> SCHEMA_MIGRATIONS_THEN_NATURAL_ORDER = ((Comparator<String>) (o1, o2) -> {
if (o1.equals(TABLE_SCHEMA_MIGRATIONS)) {
return -1;
}
if (o2.equals(TABLE_SCHEMA_MIGRATIONS)) {
return 1;
}
return 0;
}).thenComparing(String.CASE_INSENSITIVE_ORDER);
String dumpToText() throws SQLException {
SQDatabase database = SQDatabase.newH2Database("SQSchemaDumper", true);
database.start();
try (Connection connection = database.getDataSource().getConnection();
Statement statement = connection.createStatement()) {
List<String> tableNames = getSortedTableNames(statement);
StringBuilder res = new StringBuilder(HEADER);
for (String tableName : tableNames) {
res.append(LINE_SEPARATOR);
dumpTable(statement, res, tableName);
}
return res.toString();
}
}
/**
* List of all tables in database sorted in natural order except that table {@link #TABLE_SCHEMA_MIGRATIONS SCHEMA_MIGRATIONS}
* will always be first.
*/
private List<String> getSortedTableNames(Statement statement) throws SQLException {
checkState(statement.execute("SHOW TABLES"), "can't list tables");
List<String> tableNames = new ArrayList<>();
try (ResultSet rSet = statement.getResultSet()) {
while (rSet.next()) {
tableNames.add(rSet.getString(1));
}
}
tableNames.sort(SCHEMA_MIGRATIONS_THEN_NATURAL_ORDER);
return tableNames;
}
private void dumpTable(Statement statement, StringBuilder res, String tableName) throws SQLException {
checkState(statement.execute("SCRIPT NODATA NOSETTINGS TABLE " + tableName), "Can't get schema dump of table %s", tableName);
try (ResultSet resultSet = statement.getResultSet()) {
while (resultSet.next()) {
String sql = resultSet.getString(1);
if (isIgnoredStatement(sql)) {
continue;
}
String cleanedSql = sql
.replaceAll(" \"PUBLIC\"\\.", " ")
.replaceAll(" MEMORY TABLE ", " TABLE ");
if (cleanedSql.startsWith("CREATE TABLE")) {
cleanedSql = fixAutoIncrementIdColumn(cleanedSql);
}
res.append(cleanedSql).append(LINE_SEPARATOR);
}
}
}
private static boolean isIgnoredStatement(String sql) {
return sql.startsWith("CREATE SEQUENCE") || sql.startsWith("CREATE USER") || sql.startsWith("--");
}
/**
* Hacky hacky hack: H2 generates DDL for auto increment column which varies from one run to another and is hardly
* readable for user.
* It's currently reasonable to assume:
* <ul>
* <li>all existing auto increment columns are called ID</li>
* <li>it's not a practice to create auto increment anymore => no new will be added which could have a different name</li>
* </ul>
*/
private String fixAutoIncrementIdColumn(String cleanedSql) {
String res = fixAutoIncrementIdColumn(cleanedSql, "\"ID\" INTEGER DEFAULT (NEXT VALUE FOR ", "\"ID\" INTEGER NOT NULL AUTO_INCREMENT (1,1)");
res = fixAutoIncrementIdColumn(res, "\"ID\" BIGINT DEFAULT (NEXT VALUE FOR ", "\"ID\" BIGINT NOT NULL AUTO_INCREMENT (1,1)");
return res;
}
private static String fixAutoIncrementIdColumn(String sql, String src, String tgt) {
int idAutoGenColumn = sql.indexOf(src);
if (idAutoGenColumn < 0) {
return sql;
}
int comma = sql.indexOf(",", idAutoGenColumn + 1);
checkState(comma > -1, "can't find end of ID column declaration??");
StringBuilder bar = new StringBuilder(sql);
bar.replace(idAutoGenColumn, comma, tgt);
return bar.toString();
}
}
| 5,903 | 40.577465 | 145 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/entity/EntityDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.entity;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import org.sonar.db.portfolio.PortfolioDto;
import org.sonar.db.project.ProjectDto;
import static org.assertj.core.api.Assertions.assertThat;
public class EntityDtoTest {
@Test
public void equals_whenEmptyObjects_shouldReturnTrue() {
PortfolioDto p1 = new PortfolioDto();
PortfolioDto p2 = new PortfolioDto();
boolean equals = p1.equals(p2);
assertThat(equals).isTrue();
}
@Test
public void equals_whenSameUuid_shouldReturnTrue() {
PortfolioDto e1 = new PortfolioDto().setUuid("uuid1");
PortfolioDto e2 = new PortfolioDto().setUuid("uuid1");
assertThat(e1).isEqualTo(e2);
}
@Test
public void equals_whenDifferentUuid_shouldReturnFalse() {
PortfolioDto e1 = new PortfolioDto().setUuid("uuid1");
PortfolioDto e2 = new PortfolioDto().setUuid("uuid2");
assertThat(e1).isNotEqualTo(e2);
}
@Test
public void equals_whenSameObject_shouldReturnFalse() {
PortfolioDto e1 = new PortfolioDto().setUuid("uuid1");
assertThat(e1).isEqualTo(e1);
}
@Test
public void equals_whenDifferentType_shouldReturnFalse() {
PortfolioDto e1 = new PortfolioDto().setUuid("uuid1");
assertThat(e1).isNotEqualTo(new Object());
}
@Test
public void hashCode_whenEmptyObjects_shouldBeTheSame() {
PortfolioDto p1 = new PortfolioDto();
PortfolioDto p2 = new PortfolioDto();
int hash1 = p1.hashCode();
int hash2 = p2.hashCode();
assertThat(hash1).isEqualTo(hash2);
}
@Test
public void getAuthUuid_whenEntityIsSubportfolio_shouldReturnAuthUuid() {
PortfolioDto portfolioDto = new PortfolioDto();
portfolioDto.qualifier = Qualifiers.SUBVIEW;
portfolioDto.authUuid = "authUuid";
portfolioDto.setUuid("uuid");
String authUuid = portfolioDto.getAuthUuid();
assertThat(authUuid).isEqualTo("authUuid");
}
@Test
public void isProjectOrApp_whenQualifierIsProject_shouldReturnTrue() {
ProjectDto projectDto = new ProjectDto();
projectDto.setQualifier(Qualifiers.PROJECT);
boolean projectOrApp = projectDto.isProjectOrApp();
assertThat(projectOrApp).isTrue();
}
@Test
public void isProjectOrApp_whenQualifierIsPortfolio_shouldReturnFalse() {
ProjectDto projectDto = new ProjectDto();
projectDto.setQualifier(Qualifiers.VIEW);
boolean projectOrApp = projectDto.isProjectOrApp();
assertThat(projectOrApp).isFalse();
}
@Test
public void isPortfolio_whenQualifierIsPortfolio_shouldReturnTrue() {
ProjectDto projectDto = new ProjectDto();
projectDto.setQualifier(Qualifiers.VIEW);
boolean projectOrApp = projectDto.isPortfolio();
assertThat(projectOrApp).isTrue();
}
@Test
public void isPortfolio_whenQualifierIsProject_shouldReturnFalse() {
ProjectDto projectDto = new ProjectDto();
projectDto.setQualifier(Qualifiers.PROJECT);
boolean projectOrApp = projectDto.isPortfolio();
assertThat(projectOrApp).isFalse();
}
} | 3,860 | 28.930233 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.event;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class EventDtoTest {
@Test
public void test_getters_and_setters() {
EventDto dto = new EventDto()
.setAnalysisUuid("uuid_1")
.setComponentUuid("ABCD")
.setName("1.0")
.setCategory("Version")
.setDescription("Version 1.0")
.setData("some data")
.setDate(1413407091086L)
.setCreatedAt(1225630680000L);
assertThat(dto.getAnalysisUuid()).isEqualTo("uuid_1");
assertThat(dto.getComponentUuid()).isEqualTo("ABCD");
assertThat(dto.getName()).isEqualTo("1.0");
assertThat(dto.getCategory()).isEqualTo("Version");
assertThat(dto.getDescription()).isEqualTo("Version 1.0");
assertThat(dto.getData()).isEqualTo("some data");
assertThat(dto.getCreatedAt()).isEqualTo(1225630680000L);
}
}
| 1,727 | 33.56 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventValidatorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.event;
import org.junit.Test;
import static com.google.common.base.Strings.repeat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class EventValidatorTest {
@Test
public void valid_cases() {
EventValidator.checkEventName(repeat("a", 400));
EventValidator.checkEventName(null);
EventValidator.checkEventCategory(repeat("a", 50));
EventValidator.checkEventCategory(null);
EventValidator.checkEventDescription(repeat("a", 4000));
EventValidator.checkEventDescription(null);
}
@Test
public void fail_if_name_longer_than_400() {
assertThatThrownBy(() -> EventValidator.checkEventName(repeat("a", 400 + 1)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Event name length (401) is longer than the maximum authorized (400).");
}
@Test
public void fail_if_category_longer_than_50() {
assertThatThrownBy(() -> EventValidator.checkEventCategory(repeat("a", 50 + 1)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Event category length (51) is longer than the maximum authorized (50). 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided.");
}
@Test
public void fail_if_description_longer_than_4000() {
assertThatThrownBy(() -> EventValidator.checkEventDescription(repeat("a", 4000 + 1)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Event description length (4001) is longer than the maximum authorized (4000).");
}
}
| 2,377 | 38.633333 | 160 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueChangeDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.core.issue.DefaultIssueComment;
import org.sonar.core.issue.FieldDiffs;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.utils.DateUtils.parseDate;
public class IssueChangeDtoTest {
@Test
public void create_from_comment() {
DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "user_uuid", "the comment");
IssueChangeDto dto = IssueChangeDto.of(comment, "project_uuid");
assertThat(dto.getChangeData()).isEqualTo("the comment");
assertThat(dto.getChangeType()).isEqualTo("comment");
assertThat(dto.getCreatedAt()).isNotNull();
assertThat(dto.getUpdatedAt()).isNotNull();
assertThat(dto.getIssueChangeCreationDate()).isNotNull();
assertThat(dto.getIssueKey()).isEqualTo("ABCDE");
assertThat(dto.getUserUuid()).isEqualTo("user_uuid");
assertThat(dto.getProjectUuid()).isEqualTo("project_uuid");
}
@Test
public void create_from_comment_with_created_at() {
DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "user_uuid", "the comment");
comment.setCreatedAt(parseDate("2015-01-13"));
IssueChangeDto dto = IssueChangeDto.of(comment, "project_uuid");
assertThat(dto.getIssueChangeCreationDate()).isEqualTo(parseDate("2015-01-13").getTime());
}
@Test
public void create_from_diff() {
FieldDiffs diffs = new FieldDiffs();
diffs.setDiff("severity", "INFO", "BLOCKER");
diffs.setUserUuid("user_uuid");
diffs.setCreationDate(parseDate("2015-01-13"));
IssueChangeDto dto = IssueChangeDto.of("ABCDE", diffs, "project_uuid");
assertThat(dto.getChangeData()).isEqualTo("severity=INFO|BLOCKER");
assertThat(dto.getChangeType()).isEqualTo("diff");
assertThat(dto.getCreatedAt()).isNotNull();
assertThat(dto.getUpdatedAt()).isNotNull();
assertThat(dto.getIssueKey()).isEqualTo("ABCDE");
assertThat(dto.getUserUuid()).isEqualTo("user_uuid");
assertThat(dto.getIssueChangeCreationDate()).isEqualTo(parseDate("2015-01-13").getTime());
assertThat(dto.getProjectUuid()).isEqualTo("project_uuid");
}
@Test
public void create_from_diff_with_created_at() {
FieldDiffs diffs = new FieldDiffs();
diffs.setDiff("severity", "INFO", "BLOCKER");
diffs.setUserUuid("user_uuid");
diffs.setCreationDate(parseDate("2015-01-13"));
IssueChangeDto dto = IssueChangeDto.of("ABCDE", diffs, "project_uuid");
assertThat(dto.getIssueChangeCreationDate()).isEqualTo(parseDate("2015-01-13").getTime());
}
@Test
public void to_comment() {
IssueChangeDto changeDto = new IssueChangeDto()
.setKey("EFGH")
.setUserUuid("user_uuid")
.setChangeData("Some text")
.setIssueKey("ABCDE")
.setCreatedAt(System2.INSTANCE.now())
.setUpdatedAt(System2.INSTANCE.now());
DefaultIssueComment comment = changeDto.toComment();
assertThat(comment.key()).isEqualTo("EFGH");
assertThat(comment.markdownText()).isEqualTo("Some text");
assertThat(comment.createdAt()).isNotNull();
assertThat(comment.updatedAt()).isNotNull();
assertThat(comment.userUuid()).isEqualTo("user_uuid");
assertThat(comment.issueKey()).isEqualTo("ABCDE");
}
@Test
public void to_field_diffs_with_issue_creation_date() {
IssueChangeDto changeDto = new IssueChangeDto()
.setKey("EFGH")
.setUserUuid("user_uuid")
.setChangeData("Some text")
.setIssueKey("ABCDE")
.setIssueChangeCreationDate(System2.INSTANCE.now());
FieldDiffs diffs = changeDto.toFieldDiffs();
assertThat(diffs.userUuid()).contains("user_uuid");
assertThat(diffs.issueKey()).contains("ABCDE");
assertThat(diffs.creationDate()).isNotNull();
}
@Test
public void to_field_diffs_with_create_at() {
IssueChangeDto changeDto = new IssueChangeDto()
.setKey("EFGH")
.setUserUuid("user_uuid")
.setChangeData("Some text")
.setIssueKey("ABCDE")
.setCreatedAt(System2.INSTANCE.now());
FieldDiffs diffs = changeDto.toFieldDiffs();
assertThat(diffs.userUuid()).contains("user_uuid");
assertThat(diffs.issueKey()).contains("ABCDE");
assertThat(diffs.creationDate()).isNotNull();
}
@Test
public void getIssueChangeCreationDate_fallback_to_createAt_when_null() {
IssueChangeDto changeDto = new IssueChangeDto()
.setKey("EFGH")
.setUserUuid("user_uuid")
.setChangeData("Some text")
.setIssueKey("ABCDE")
.setCreatedAt(10_000_000L)
.setUpdatedAt(20_000_000L);
assertThat(changeDto.getIssueChangeCreationDate()).isEqualTo(10_000_000L);
}
@Test
public void to_string() {
DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "user_uuid", "the comment");
IssueChangeDto dto = IssueChangeDto.of(comment, "project_uuid");
assertThat(dto.toString()).contains("ABCDE");
}
}
| 5,776 | 35.563291 | 98 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import com.google.protobuf.InvalidProtocolBufferException;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.time.DateUtils;
import org.junit.Test;
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.Duration;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.rule.RuleDto;
import static org.assertj.core.api.Assertions.assertThat;
public class IssueDtoTest {
private static final String TEST_CONTEXT_KEY = "test_context_key";
private static final DbIssues.MessageFormattings EXAMPLE_MESSAGE_FORMATTINGS = DbIssues.MessageFormattings.newBuilder()
.addMessageFormatting(DbIssues.MessageFormatting.newBuilder().setStart(0).setEnd(1).setType(DbIssues.MessageFormattingType.CODE)
.build())
.build();
@Test
public void toDefaultIssue_ShouldSetIssueFields() throws InvalidProtocolBufferException {
Date createdAt = DateUtils.addDays(new Date(), -5);
Date updatedAt = DateUtils.addDays(new Date(), -3);
Date closedAt = DateUtils.addDays(new Date(), -1);
IssueDto dto = new IssueDto()
.setKee("100")
.setType(RuleType.VULNERABILITY)
.setRuleUuid("rule-uuid-1")
.setRuleKey("java", "AvoidCycle")
.setLanguage("xoo")
.setComponentKey("org.sonar.sample:Sample")
.setComponentUuid("CDEF")
.setProjectUuid("GHIJ")
.setProjectKey("org.sonar.sample")
.setStatus(Issue.STATUS_CLOSED)
.setResolution(Issue.RESOLUTION_FALSE_POSITIVE)
.setGap(15.0)
.setEffort(10L)
.setLine(6)
.setSeverity("BLOCKER")
.setMessage("message")
.setMessageFormattings(EXAMPLE_MESSAGE_FORMATTINGS)
.setManualSeverity(true)
.setAssigneeUuid("perceval")
.setAuthorLogin("pierre")
.setIssueCreationDate(createdAt)
.setIssueUpdateDate(updatedAt)
.setIssueCloseDate(closedAt)
.setRuleDescriptionContextKey(TEST_CONTEXT_KEY);
DefaultIssue expected = new DefaultIssue()
.setKey("100")
.setType(RuleType.VULNERABILITY)
.setRuleKey(RuleKey.of("java", "AvoidCycle"))
.setLanguage("xoo")
.setComponentUuid("CDEF")
.setProjectUuid("GHIJ")
.setComponentKey("org.sonar.sample:Sample")
.setProjectKey("org.sonar.sample")
.setStatus(Issue.STATUS_CLOSED)
.setResolution(Issue.RESOLUTION_FALSE_POSITIVE)
.setGap(15.0)
.setEffort(Duration.create(10L))
.setLine(6)
.setSeverity("BLOCKER")
.setMessage("message")
.setMessageFormattings(DbIssues.MessageFormattings.parseFrom(EXAMPLE_MESSAGE_FORMATTINGS.toByteArray()))
.setManualSeverity(true)
.setAssigneeUuid("perceval")
.setAuthorLogin("pierre")
.setCreationDate(DateUtils.truncate(createdAt, Calendar.SECOND))
.setUpdateDate(DateUtils.truncate(updatedAt, Calendar.SECOND))
.setCloseDate(DateUtils.truncate(closedAt, Calendar.SECOND))
.setNew(false)
.setIsNewCodeReferenceIssue(false)
.setRuleDescriptionContextKey(TEST_CONTEXT_KEY)
.setCodeVariants(Set.of())
.setTags(Set.of());
DefaultIssue issue = dto.toDefaultIssue();
assertThat(issue).usingRecursiveComparison().isEqualTo(expected);
}
@Test
public void set_rule() {
IssueDto dto = new IssueDto()
.setKee("100")
.setRule(new RuleDto().setUuid("uuid-1").setRuleKey("AvoidCycle").setRepositoryKey("java").setIsExternal(true))
.setLanguage("xoo");
assertThat(dto.getRuleUuid()).isEqualTo("uuid-1");
assertThat(dto.getRuleRepo()).isEqualTo("java");
assertThat(dto.getRule()).isEqualTo("AvoidCycle");
assertThat(dto.getRuleKey()).hasToString("java:AvoidCycle");
assertThat(dto.getLanguage()).isEqualTo("xoo");
assertThat(dto.isExternal()).isTrue();
}
@Test
public void set_tags() {
IssueDto dto = new IssueDto();
assertThat(dto.getTags()).isEmpty();
assertThat(dto.getTagsString()).isNull();
dto.setTags(Arrays.asList("tag1", "tag2", "tag3"));
assertThat(dto.getTags()).containsOnly("tag1", "tag2", "tag3");
assertThat(dto.getTagsString()).isEqualTo("tag1,tag2,tag3");
dto.setTags(Arrays.asList());
assertThat(dto.getTags()).isEmpty();
dto.setTagsString("tag1, tag2 ,,tag3");
assertThat(dto.getTags()).containsOnly("tag1", "tag2", "tag3");
dto.setTagsString(null);
assertThat(dto.getTags()).isEmpty();
dto.setTagsString("");
assertThat(dto.getTags()).isEmpty();
}
@Test
public void setCodeVariants_shouldReturnCodeVariants() {
IssueDto dto = new IssueDto();
assertThat(dto.getCodeVariants()).isEmpty();
assertThat(dto.getCodeVariantsString()).isNull();
dto.setCodeVariants(Arrays.asList("variant1", "variant2", "variant3"));
assertThat(dto.getCodeVariants()).containsOnly("variant1", "variant2", "variant3");
assertThat(dto.getCodeVariantsString()).isEqualTo("variant1,variant2,variant3");
dto.setCodeVariants(null);
assertThat(dto.getCodeVariants()).isEmpty();
assertThat(dto.getCodeVariantsString()).isNull();
dto.setCodeVariants(List.of());
assertThat(dto.getCodeVariants()).isEmpty();
assertThat(dto.getCodeVariantsString()).isNull();
}
@Test
public void setCodeVariantsString_shouldReturnCodeVariants() {
IssueDto dto = new IssueDto();
dto.setCodeVariantsString("variant1, variant2 ,,variant4");
assertThat(dto.getCodeVariants()).containsOnly("variant1", "variant2", "variant4");
dto.setCodeVariantsString(null);
assertThat(dto.getCodeVariants()).isEmpty();
dto.setCodeVariantsString("");
assertThat(dto.getCodeVariants()).isEmpty();
}
@Test
public void toDtoForComputationInsert_givenDefaultIssueWithAllFields_returnFullIssueDto() {
long now = System.currentTimeMillis();
Date dateNow = Date.from(new Date(now).toInstant().truncatedTo(ChronoUnit.SECONDS));
DefaultIssue defaultIssue = createExampleDefaultIssue(dateNow);
IssueDto issueDto = IssueDto.toDtoForComputationInsert(defaultIssue, "ruleUuid", now);
assertThat(issueDto).extracting(IssueDto::getKey, IssueDto::getType, IssueDto::getRuleKey).containsExactly("key", RuleType.BUG.getDbConstant(), RuleKey.of("repo", "rule"));
assertThat(issueDto).extracting(IssueDto::getIssueCreationDate, IssueDto::getIssueCloseDate,
IssueDto::getIssueUpdateDate, IssueDto::getSelectedAt, IssueDto::getUpdatedAt, IssueDto::getCreatedAt)
.containsExactly(dateNow, dateNow, dateNow, dateNow.getTime(), now, now);
assertThat(issueDto).extracting(IssueDto::getLine, IssueDto::getMessage,
IssueDto::getGap, IssueDto::getEffort, IssueDto::getResolution, IssueDto::getStatus, IssueDto::getSeverity)
.containsExactly(1, "message", 1.0, 1L, Issue.RESOLUTION_FALSE_POSITIVE, Issue.STATUS_CLOSED, "BLOCKER");
assertThat(issueDto).extracting(IssueDto::getTags, IssueDto::getCodeVariants, IssueDto::getAuthorLogin)
.containsExactly(Set.of("todo"), Set.of("variant1", "variant2"), "admin");
assertThat(issueDto).extracting(IssueDto::isManualSeverity, IssueDto::getChecksum, IssueDto::getAssigneeUuid,
IssueDto::isExternal, IssueDto::getComponentUuid, IssueDto::getComponentKey,
IssueDto::getProjectUuid, IssueDto::getProjectKey, IssueDto::getRuleUuid)
.containsExactly(true, "123", "123", true, "123", "componentKey", "123", "projectKey", "ruleUuid");
assertThat(issueDto.isQuickFixAvailable()).isTrue();
assertThat(issueDto.isNewCodeReferenceIssue()).isTrue();
assertThat(issueDto.getOptionalRuleDescriptionContextKey()).contains(TEST_CONTEXT_KEY);
}
@Test
public void toDtoForUpdate_givenDefaultIssueWithAllFields_returnFullIssueDto() {
long now = System.currentTimeMillis();
Date dateNow = Date.from(new Date(now).toInstant().truncatedTo(ChronoUnit.SECONDS));
DefaultIssue defaultIssue = createExampleDefaultIssue(dateNow);
IssueDto issueDto = IssueDto.toDtoForUpdate(defaultIssue, now);
assertThat(issueDto).extracting(IssueDto::getKey, IssueDto::getType, IssueDto::getRuleKey).containsExactly("key", RuleType.BUG.getDbConstant(), RuleKey.of("repo", "rule"));
assertThat(issueDto).extracting(IssueDto::getIssueCreationDate, IssueDto::getIssueCloseDate,
IssueDto::getIssueUpdateDate, IssueDto::getSelectedAt, IssueDto::getUpdatedAt)
.containsExactly(dateNow, dateNow, dateNow, dateNow.getTime(), now);
assertThat(issueDto).extracting(IssueDto::getLine, IssueDto::getMessage,
IssueDto::getGap, IssueDto::getEffort, IssueDto::getResolution, IssueDto::getStatus, IssueDto::getSeverity)
.containsExactly(1, "message", 1.0, 1L, Issue.RESOLUTION_FALSE_POSITIVE, Issue.STATUS_CLOSED, "BLOCKER");
assertThat(issueDto).extracting(IssueDto::getTags, IssueDto::getCodeVariants, IssueDto::getAuthorLogin)
.containsExactly(Set.of("todo"), Set.of("variant1", "variant2"), "admin");
assertThat(issueDto).extracting(IssueDto::isManualSeverity, IssueDto::getChecksum, IssueDto::getAssigneeUuid,
IssueDto::isExternal, IssueDto::getComponentUuid, IssueDto::getComponentKey, IssueDto::getProjectUuid, IssueDto::getProjectKey)
.containsExactly(true, "123", "123", true, "123", "componentKey", "123", "projectKey");
assertThat(issueDto.isQuickFixAvailable()).isTrue();
assertThat(issueDto.isNewCodeReferenceIssue()).isTrue();
assertThat(issueDto.getOptionalRuleDescriptionContextKey()).contains(TEST_CONTEXT_KEY);
}
private DefaultIssue createExampleDefaultIssue(Date dateNow) {
DefaultIssue defaultIssue = new DefaultIssue();
defaultIssue.setKey("key")
.setType(RuleType.BUG)
.setLine(1)
.setMessage("message")
.setGap(1.0)
.setEffort(Duration.create(1))
.setResolution(Issue.RESOLUTION_FALSE_POSITIVE)
.setStatus(Issue.STATUS_CLOSED)
.setSeverity("BLOCKER")
.setManualSeverity(true)
.setChecksum("123")
.setAssigneeUuid("123")
.setRuleKey(RuleKey.of("repo", "rule"))
.setIsFromExternalRuleEngine(true)
.setTags(List.of("todo"))
.setComponentUuid("123")
.setComponentKey("componentKey")
.setProjectUuid("123")
.setProjectKey("projectKey")
.setAuthorLogin("admin")
.setCreationDate(dateNow)
.setCloseDate(dateNow)
.setUpdateDate(dateNow)
.setSelectedAt(dateNow.getTime())
.setQuickFixAvailable(true)
.setIsNewCodeReferenceIssue(true)
.setRuleDescriptionContextKey(TEST_CONTEXT_KEY)
.setCodeVariants(List.of("variant1", "variant2"));
return defaultIssue;
}
}
| 11,632 | 40.398577 | 176 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueQueryParamsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class IssueQueryParamsTest {
private final List<String> ruleRepositories = List.of("js-security", "java");
@Test
public void validate_issue_query_parameters_structure() {
boolean resolvedOnly = false;
long changedSince = 1_000_000L;
String branchUuid = "master-branch-uuid";
IssueQueryParams queryParameters = new IssueQueryParams(branchUuid, null, ruleRepositories, null, resolvedOnly, changedSince);
assertThat(queryParameters.getBranchUuid()).isEqualTo(branchUuid);
assertThat(queryParameters.getLanguages()).isNotNull().isEmpty();
assertThat(queryParameters.getRuleRepositories()).isEqualTo(ruleRepositories);
assertThat(queryParameters.getExcludingRuleRepositories()).isNotNull().isEmpty();
assertThat(queryParameters.isResolvedOnly()).isFalse();
assertThat(queryParameters.getChangedSince()).isEqualTo(changedSince);
}
}
| 1,864 | 38.680851 | 130 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/issue/NewCodeReferenceIssueDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import org.junit.Test;
import org.sonar.core.util.UuidFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class NewCodeReferenceIssueDtoTest {
private static final IssueDto ISSUE_DTO = mock(IssueDto.class);
private static final String KEY = "issue-key";
private static final String UUID = "uuid";
private static final UuidFactory UUID_FACTORY = mock(UuidFactory.class);
@Test
public void create_from_issue_dto() {
when(ISSUE_DTO.getKey()).thenReturn(KEY);
when(UUID_FACTORY.create()).thenReturn(UUID);
long now = System.currentTimeMillis();
NewCodeReferenceIssueDto dto = NewCodeReferenceIssueDto.fromIssueDto(ISSUE_DTO, now, UUID_FACTORY);
assertThat(dto.getUuid()).isEqualTo(UUID);
assertThat(dto.getIssueKey()).isEqualTo(KEY);
assertThat(dto.getCreatedAt()).isNotNull();
}
@Test
public void create_from_issue_key() {
when(UUID_FACTORY.create()).thenReturn(UUID);
long now = System.currentTimeMillis();
NewCodeReferenceIssueDto dto = NewCodeReferenceIssueDto.fromIssueKey(KEY, now, UUID_FACTORY);
assertThat(dto.getUuid()).isEqualTo(UUID);
assertThat(dto.getIssueKey()).isEqualTo(KEY);
assertThat(dto.getCreatedAt()).isNotNull();
}
}
| 2,191 | 34.934426 | 103 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/measure/LargestBranchNclocDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class LargestBranchNclocDtoTest {
private final LargestBranchNclocDto underTest = new LargestBranchNclocDto();
@Test
public void test_getter_and_setter() {
setUnderTest();
assertThat(underTest.getProjectUuid()).isEqualTo("projectUuid");
assertThat(underTest.getProjectName()).isEqualTo("projectName");
assertThat(underTest.getProjectKey()).isEqualTo("projectKey");
assertThat(underTest.getLoc()).isEqualTo(123L);
assertThat(underTest.getBranchName()).isEqualTo("branchName");
assertThat(underTest.getBranchType()).isEqualTo("branchType");
}
private void setUnderTest() {
underTest
.setProjectUuid("projectUuid")
.setProjectName("projectName")
.setProjectKey("projectKey")
.setLoc(123L)
.setBranchName("branchName")
.setBranchType("branchType");
}
}
| 1,798 | 32.943396 | 78 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import com.google.common.base.Strings;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class MeasureDtoTest {
MeasureDto underTest = new MeasureDto();
@Test
public void test_getter_and_setter() {
underTest
.setValue(2d)
.setData("text value");
assertThat(underTest.getValue()).isEqualTo(2d);
assertThat(underTest.getData()).isNotNull();
}
@Test
public void value_with_text_over_4000_characters() {
assertThat(underTest.setData(Strings.repeat("1", 4001)).getData()).isNotNull();
}
@Test
public void text_value_under_4000_characters() {
assertThat(underTest.setData("text value").getData()).isEqualTo("text value");
}
}
| 1,590 | 30.82 | 83 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureTreeQueryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import java.util.Collections;
import org.junit.Test;
import org.sonar.db.component.ComponentTesting;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.measure.MeasureTreeQuery.Strategy.CHILDREN;
import static org.sonar.db.measure.MeasureTreeQuery.Strategy.LEAVES;
public class MeasureTreeQueryTest {
@Test
public void create_query() {
MeasureTreeQuery query = MeasureTreeQuery.builder()
.setStrategy(CHILDREN)
.setQualifiers(asList("FIL", "DIR"))
.setNameOrKeyQuery("teSt")
.setMetricUuids(asList("10", "11"))
.build();
assertThat(query.getStrategy()).isEqualTo(CHILDREN);
assertThat(query.getQualifiers()).containsOnly("FIL", "DIR");
assertThat(query.getNameOrKeyQuery()).isEqualTo("teSt");
assertThat(query.getMetricUuids()).containsOnly("10", "11");
}
@Test
public void create_minimal_query() {
MeasureTreeQuery query = MeasureTreeQuery.builder()
.setStrategy(CHILDREN)
.build();
assertThat(query.getStrategy()).isEqualTo(CHILDREN);
assertThat(query.getQualifiers()).isNull();
assertThat(query.getNameOrKeyQuery()).isNull();
assertThat(query.getMetricUuids()).isNull();
}
@Test
public void test_getNameOrKeyUpperLikeQuery() {
assertThat(MeasureTreeQuery.builder()
.setNameOrKeyQuery("like-\\_%/-value")
.setStrategy(CHILDREN)
.build().getNameOrKeyUpperLikeQuery()).isEqualTo("%LIKE-\\/_/%//-VALUE%");
assertThat(MeasureTreeQuery.builder()
.setStrategy(CHILDREN)
.build().getNameOrKeyUpperLikeQuery()).isNull();
}
@Test
public void test_getUuidPath() {
assertThat(MeasureTreeQuery.builder().setStrategy(CHILDREN)
.build().getUuidPath(ComponentTesting.newPrivateProjectDto("PROJECT_UUID"))).isEqualTo(".PROJECT_UUID.");
assertThat(MeasureTreeQuery.builder().setStrategy(LEAVES)
.build().getUuidPath(ComponentTesting.newPrivateProjectDto("PROJECT_UUID"))).isEqualTo(".PROJECT/_UUID.%");
}
@Test
public void return_empty_when_metrics_is_empty() {
assertThat(MeasureTreeQuery.builder()
.setStrategy(CHILDREN)
.setMetricUuids(Collections.emptyList())
.build().returnsEmpty()).isTrue();
assertThat(MeasureTreeQuery.builder()
.setStrategy(CHILDREN)
.setMetricUuids(null)
.build().returnsEmpty()).isFalse();
}
@Test
public void return_empty_when_qualifiers_is_empty() {
assertThat(MeasureTreeQuery.builder()
.setStrategy(CHILDREN)
.setQualifiers(Collections.emptyList())
.build().returnsEmpty()).isTrue();
assertThat(MeasureTreeQuery.builder()
.setStrategy(CHILDREN)
.setQualifiers(asList("FIL", "DIR"))
.build().returnsEmpty()).isFalse();
}
@Test
public void fail_when_no_strategy() {
assertThatThrownBy(() -> {
MeasureTreeQuery.builder()
.build();
})
.isInstanceOf(NullPointerException.class);
}
}
| 3,924 | 32.262712 | 113 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/measure/PastMeasureDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class PastMeasureDtoTest {
@Test
public void test_getter_and_setter() {
PastMeasureDto dto = new PastMeasureDto()
.setValue(1d)
.setMetricUuid("2");
assertThat(dto.hasValue()).isTrue();
assertThat(dto.getValue()).isEqualTo(1d);
assertThat(dto.getMetricUuid()).isEqualTo("2");
}
@Test
public void test_has_value() {
PastMeasureDto measureWithValue = new PastMeasureDto()
.setValue(1d)
.setMetricUuid("2");
assertThat(measureWithValue.hasValue()).isTrue();
PastMeasureDto measureWithoutValue = new PastMeasureDto()
.setMetricUuid("2");
assertThat(measureWithoutValue.hasValue()).isFalse();
}
@Test
public void get_value_throw_a_NPE_if_value_is_null() {
assertThatThrownBy(() -> new PastMeasureDto().getValue())
.isInstanceOf(NullPointerException.class);
}
}
| 1,881 | 31.448276 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/metric/MetricDtoFunctionsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.metric;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class MetricDtoFunctionsTest {
private MetricDto metric;
@Test
public void isOptimizedForBestValue_at_true() {
metric = new MetricDto()
.setBestValue(42.0d)
.setOptimizedBestValue(true);
boolean result = MetricDtoFunctions.isOptimizedForBestValue().test(metric);
assertThat(result).isTrue();
}
@Test
public void isOptimizedForBestValue_is_false_when_no_best_value() {
metric = new MetricDto()
.setBestValue(null)
.setOptimizedBestValue(true);
boolean result = MetricDtoFunctions.isOptimizedForBestValue().test(metric);
assertThat(result).isFalse();
}
@Test
public void isOptimizedForBestValue_is_false_when_is_not_optimized() {
metric = new MetricDto()
.setBestValue(42.0d)
.setOptimizedBestValue(false);
boolean result = MetricDtoFunctions.isOptimizedForBestValue().test(metric);
assertThat(result).isFalse();
}
}
| 1,880 | 28.857143 | 79 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/metric/MetricDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.metric;
import org.junit.Test;
import static com.google.common.base.Strings.repeat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class MetricDtoTest {
private MetricDto underTest = new MetricDto();
@Test
public void getters_and_setters() {
MetricDto metricDto = new MetricDto()
.setUuid("1")
.setKey("coverage")
.setShortName("Coverage")
.setDescription("Coverage by unit tests")
.setDomain("Tests")
.setValueType("PERCENT")
.setQualitative(true)
.setWorstValue(0d)
.setBestValue(100d)
.setOptimizedBestValue(true)
.setDirection(1)
.setHidden(true)
.setDeleteHistoricalData(true)
.setEnabled(true);
assertThat(metricDto.getUuid()).isEqualTo("1");
assertThat(metricDto.getKey()).isEqualTo("coverage");
assertThat(metricDto.getShortName()).isEqualTo("Coverage");
assertThat(metricDto.getDescription()).isEqualTo("Coverage by unit tests");
assertThat(metricDto.getDomain()).isEqualTo("Tests");
assertThat(metricDto.getValueType()).isEqualTo("PERCENT");
assertThat(metricDto.isQualitative()).isTrue();
assertThat(metricDto.getWorstValue()).isEqualTo(0d);
assertThat(metricDto.getBestValue()).isEqualTo(100d);
assertThat(metricDto.isOptimizedBestValue()).isTrue();
assertThat(metricDto.getDirection()).isOne();
assertThat(metricDto.isHidden()).isTrue();
assertThat(metricDto.isDeleteHistoricalData()).isTrue();
assertThat(metricDto.isEnabled()).isTrue();
}
@Test
public void fail_if_key_longer_than_64_characters() {
String a65 = repeat("a", 65);
assertThatThrownBy(() -> underTest.setKey(a65))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Metric key length (65) is longer than the maximum authorized (64). '" + a65 + "' was provided.");
}
@Test
public void fail_if_name_longer_than_64_characters() {
String a65 = repeat("a", 65);
assertThatThrownBy(() -> underTest.setShortName(a65))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Metric name length (65) is longer than the maximum authorized (64). '" + a65 + "' was provided.");
}
@Test
public void fail_if_description_longer_than_255_characters() {
String a256 = repeat("a", 256);
assertThatThrownBy(() -> underTest.setDescription(a256))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Metric description length (256) is longer than the maximum authorized (255). '" + a256 + "' was provided.");
}
@Test
public void fail_if_domain_longer_than_64_characters() {
String a65 = repeat("a", 65);
assertThatThrownBy(() -> underTest.setDomain(a65))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Metric domain length (65) is longer than the maximum authorized (64). '" + a65 + "' was provided.");
}
}
| 3,810 | 36.362745 | 127 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/newcodeperiod/NewCodePeriodDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.newcodeperiod;
import org.junit.Test;
import org.sonar.api.utils.System2;
import static org.assertj.core.api.Assertions.assertThat;
public class NewCodePeriodDtoTest {
@Test
public void getters_and_setters() {
long currentTime = System2.INSTANCE.now();
NewCodePeriodDto newCodePeriodDto = new NewCodePeriodDto()
.setUuid("uuid")
.setProjectUuid("projectUuid")
.setBranchUuid("branchUuid")
.setCreatedAt(currentTime)
.setUpdatedAt(currentTime)
.setType(NewCodePeriodType.NUMBER_OF_DAYS)
.setValue("1");
assertThat(newCodePeriodDto.getUuid()).isEqualTo("uuid");
assertThat(newCodePeriodDto.getProjectUuid()).isEqualTo("projectUuid");
assertThat(newCodePeriodDto.getBranchUuid()).isEqualTo("branchUuid");
assertThat(newCodePeriodDto.getCreatedAt()).isEqualTo(currentTime);
assertThat(newCodePeriodDto.getUpdatedAt()).isEqualTo(currentTime);
assertThat(newCodePeriodDto.getType()).isEqualTo(NewCodePeriodType.NUMBER_OF_DAYS);
assertThat(newCodePeriodDto.getValue()).isEqualTo("1");
}
}
| 1,935 | 37.72 | 87 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/permission/GlobalPermissionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.permission;
import java.util.Arrays;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class GlobalPermissionTest {
@Test
public void fromKey_returns_enum_with_specified_key() {
for (GlobalPermission p : GlobalPermission.values()) {
assertThat(GlobalPermission.fromKey(p.getKey())).isEqualTo(p);
}
}
@Test
public void fromKey_throws_exception_for_non_existing_keys() {
String non_existing_permission = "non_existing";
assertThatThrownBy(() -> GlobalPermission.fromKey(non_existing_permission))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void contains_returns_true_for_existing_permissions() {
Arrays.stream(GlobalPermission.values())
.map(GlobalPermission::getKey)
.forEach(key -> {
assertThat(GlobalPermission.contains(key)).isTrue();
});
}
@Test
public void contains_returns_false_for_non_existing_permissions() {
String non_existing_permission = "non_existing";
assertThat(GlobalPermission.contains(non_existing_permission)).isFalse();
}
@Test
public void all_in_one_line_contains_all_permissions() {
assertThat(GlobalPermission.ALL_ON_ONE_LINE).isEqualTo("admin, gateadmin, profileadmin, provisioning, scan, applicationcreator, portfoliocreator");
}
}
| 2,251 | 34.1875 | 151 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/permission/PermissionQueryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.permission;
import org.junit.Test;
import org.sonar.db.component.ComponentDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.component.ComponentTesting.newPublicProjectDto;
public class PermissionQueryTest {
@Test
public void create_query() {
ComponentDto project = newPublicProjectDto();
PermissionQuery query = PermissionQuery.builder()
.setEntity(project)
.setPermission("user")
.setSearchQuery("sonar")
.build();
assertThat(query.getEntityUuid()).isEqualTo(project.uuid());
assertThat(query.getPermission()).isEqualTo("user");
assertThat(query.getSearchQuery()).isEqualTo("sonar");
}
@Test
public void create_query_with_pagination() {
PermissionQuery query = PermissionQuery.builder()
.setPageSize(10)
.setPageIndex(5)
.build();
assertThat(query.getPageOffset()).isEqualTo(40);
assertThat(query.getPageSize()).isEqualTo(10);
}
@Test
public void create_query_with_default_pagination() {
PermissionQuery query = PermissionQuery.builder()
.build();
assertThat(query.getPageOffset()).isZero();
assertThat(query.getPageSize()).isEqualTo(20);
}
@Test
public void fail_when_search_query_length_is_less_than_3_characters() {
assertThatThrownBy(() -> {
PermissionQuery.builder()
.setSearchQuery("so")
.build();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Search query should contains at least 3 characters");
}
}
| 2,464 | 31.012987 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/permission/UserPermissionDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.permission;
import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class UserPermissionDtoTest {
@Test
public void toString_shouldReturnInformationAboutAllFieldsExceptUuid() {
UserPermissionDto userPermissionDto = new UserPermissionDto("someUuid", "somePermission", "someUserUuid", "someEntityUuid");
String toStringResult = userPermissionDto.toString();
assertThat(toStringResult).contains(List.of("somePermission", "someUserUuid", "someEntityUuid"));
}
}
| 1,401 | 35.894737 | 128 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/DefaultTemplatesTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.permission.template;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class DefaultTemplatesTest {
private final DefaultTemplates underTest = new DefaultTemplates();
@Test
public void setProject_throws_NPE_if_argument_is_null() {
assertThatThrownBy(() -> underTest.setProjectUuid(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("defaultTemplates.project can't be null");
}
@Test
public void getProject_throws_NPE_if_project_is_null() {
assertThatThrownBy(underTest::getProjectUuid)
.isInstanceOf(NullPointerException.class)
.hasMessage("defaultTemplates.project can't be null");
}
@Test
public void setProjectU() {
String uuid = "uuid-1";
underTest.setProjectUuid(uuid);
assertThat(underTest.getProjectUuid()).isEqualTo(uuid);
}
@Test
public void setApplicationsUuid_accepts_null() {
underTest.setApplicationsUuid(null);
assertThat(underTest.getApplicationsUuid()).isNull();
}
@Test
public void setPortfoliosUuid_accepts_null() {
underTest.setPortfoliosUuid(null);
assertThat(underTest.getPortfoliosUuid()).isNull();
}
@Test
public void check_toString() {
assertThat(underTest).hasToString("DefaultTemplates{projectUuid='null', portfoliosUuid='null', applicationsUuid='null'}");
underTest
.setProjectUuid("a project")
.setApplicationsUuid("an application")
.setPortfoliosUuid("a portfolio");
assertThat(underTest).hasToString("DefaultTemplates{projectUuid='a project', portfoliosUuid='a portfolio', applicationsUuid='an application'}");
}
}
| 2,564 | 32.311688 | 148 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.permission.template;
import com.google.common.base.Strings;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class PermissionTemplateCharacteristicDtoTest {
PermissionTemplateCharacteristicDto underTest = new PermissionTemplateCharacteristicDto();
@Test
public void check_permission_field_length() {
assertThatThrownBy(() -> underTest.setPermission(Strings.repeat("a", 65)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Permission key length (65) is longer than the maximum authorized (64). 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided.");
}
}
| 1,534 | 39.394737 | 174 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/portfolio/PortfolioDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.portfolio;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import static org.assertj.core.api.Assertions.assertThat;
public class PortfolioDtoTest {
@Test
public void setters_and_getters() {
PortfolioDto dto = new PortfolioDto();
dto.setDescription("desc")
.setName("name")
.setKee("kee")
.setParentUuid("parent")
.setRootUuid("root")
.setSelectionExpression("exp")
.setSelectionMode("mode")
.setCreatedAt(1000L)
.setUpdatedAt(2000L);
assertThat(dto.getDescription()).isEqualTo("desc");
assertThat(dto.getName()).isEqualTo("name");
assertThat(dto.getKee()).isEqualTo("kee");
assertThat(dto.getKey()).isEqualTo("kee");
assertThat(dto.getParentUuid()).isEqualTo("parent");
assertThat(dto.getRootUuid()).isEqualTo("root");
assertThat(dto.getSelectionExpression()).isEqualTo("exp");
assertThat(dto.getSelectionMode()).isEqualTo("mode");
assertThat(dto.getCreatedAt()).isEqualTo(1000L);
assertThat(dto.getUpdatedAt()).isEqualTo(2000L);
dto.setKey("new_key");
assertThat(dto.getKey()).isEqualTo("new_key");
}
@Test
public void getQualifier_whenRoot_shouldReturnVW() {
PortfolioDto dto = new PortfolioDto();
assertThat(dto.getQualifier()).isEqualTo(Qualifiers.VIEW);
}
@Test
public void getQualifier_whenNotRoot_shouldReturnSVW() {
PortfolioDto dto = new PortfolioDto().setParentUuid("parent");
assertThat(dto.getQualifier()).isEqualTo(Qualifiers.SUBVIEW);
}
}
| 2,382 | 33.536232 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalComponentPropertyDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.property;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(DataProviderRunner.class)
public class InternalComponentPropertyDtoTest {
@Test
public void setter_and_getter() {
InternalComponentPropertyDto underTest = new InternalComponentPropertyDto()
.setComponentUuid("component1")
.setKey("key1")
.setValue("value1")
.setUuid("uuid1")
.setCreatedAt(10L)
.setUpdatedAt(15L);
assertThat(underTest.getComponentUuid()).isEqualTo("component1");
assertThat(underTest.getKey()).isEqualTo("key1");
assertThat(underTest.getValue()).isEqualTo("value1");
assertThat(underTest.getUuid()).isEqualTo("uuid1");
assertThat(underTest.getCreatedAt()).isEqualTo(10L);
assertThat(underTest.getUpdatedAt()).isEqualTo(15L);
}
@Test
@DataProvider({"null", ""})
public void setKey_throws_IAE_if_key_is_null_or_empty(String key) {
assertThatThrownBy(() -> new InternalComponentPropertyDto().setKey(key))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("key can't be null nor empty");
}
@Test
public void setKey_throws_IAE_if_key_is_too_long() {
String veryLongKey = StringUtils.repeat("a", 513);
assertThatThrownBy(() -> new InternalComponentPropertyDto().setKey(veryLongKey))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("key length (513) is longer than the maximum authorized (512). '%s' was provided", veryLongKey));
}
@Test
public void setValue_throws_IAE_if_value_is_too_long() {
String veryLongValue = StringUtils.repeat("a", 4001);
assertThatThrownBy(() -> new InternalComponentPropertyDto().setValue(veryLongValue))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("value length (4001) is longer than the maximum authorized (4000). '%s' was provided", veryLongValue));
}
@Test
public void setValue_accept_null_value() {
InternalComponentPropertyDto underTest = new InternalComponentPropertyDto().setValue(null);
assertThat(underTest.getValue()).isNull();
}
@Test
public void test_toString() {
InternalComponentPropertyDto underTest = new InternalComponentPropertyDto()
.setUuid("uuid1")
.setComponentUuid("component1")
.setKey("key1")
.setValue("value1")
.setCreatedAt(10L)
.setUpdatedAt(15L);
assertThat(underTest).hasToString("InternalComponentPropertyDto{uuid=uuid1, key=key1, value=value1, componentUuid=component1, updatedAt=15, createdAt=10}");
}
}
| 3,691 | 36.292929 | 160 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertyDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.property;
import com.google.common.base.Strings;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class PropertyDtoTest {
PropertyDto underTest = new PropertyDto();
@Test
public void testEquals() {
assertThat(new PropertyDto().setKey("123").setEntityUuid("uuid123")).isEqualTo(new PropertyDto().setKey("123").setEntityUuid("uuid123"));
assertThat(new PropertyDto().setKey("1234").setEntityUuid("uuid123")).isNotEqualTo(new PropertyDto().setKey("123").setEntityUuid("uuid123"));
assertThat(new PropertyDto().setKey("1234").setEntityUuid("uuid123")).isNotNull();
assertThat(new PropertyDto().setKey("1234").setEntityUuid("uuid123")).isNotEqualTo(new Object());
}
@Test
public void testHashCode() {
assertThat(new PropertyDto().setKey("123").setEntityUuid("uuid123"))
.hasSameHashCodeAs(new PropertyDto().setKey("123").setEntityUuid("uuid123"));
}
@Test
public void testToString() {
assertThat(new PropertyDto().setKey("foo:bar").setValue("value").setEntityUuid("uuid123").setUserUuid("456"))
.hasToString("PropertyDto{foo:bar, value, uuid123, 456}");
}
@Test
public void fail_if_key_longer_than_512_characters() {
String veryLongKey = Strings.repeat("a", 513);
assertThatThrownBy(() -> underTest.setKey(veryLongKey))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Setting key length (513) is longer than the maximum authorized (512). '" + veryLongKey + "' was provided");
}
}
| 2,446 | 39.114754 | 145 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/purge/DbCleanerTestUtils.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.purge;
import org.sonar.api.utils.DateUtils;
public final class DbCleanerTestUtils {
private DbCleanerTestUtils() {
}
public static PurgeableAnalysisDto createAnalysisWithDate(String analysisUuid, String date) {
PurgeableAnalysisDto snapshot = new PurgeableAnalysisDto();
snapshot.setAnalysisUuid(analysisUuid);
snapshot.setDate(DateUtils.parseDate(date).getTime());
return snapshot;
}
public static PurgeableAnalysisDto createAnalysisWithDateTime(String analysisUuid, String datetime) {
PurgeableAnalysisDto snapshot = new PurgeableAnalysisDto();
snapshot.setAnalysisUuid(analysisUuid);
snapshot.setDate(DateUtils.parseDateTime(datetime).getTime());
return snapshot;
}
}
| 1,586 | 35.068182 | 103 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeConfigurationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.purge;
import java.util.Date;
import java.util.Optional;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import static java.util.Collections.emptySet;
import static org.assertj.core.api.Assertions.assertThat;
public class PurgeConfigurationTest {
@Test
public void should_delete_all_closed_issues() {
PurgeConfiguration conf = new PurgeConfiguration("root", "project", 0, Optional.empty(), System2.INSTANCE, emptySet());
assertThat(conf.maxLiveDateOfClosedIssues()).isNull();
conf = new PurgeConfiguration("root", "project", -1, Optional.empty(), System2.INSTANCE, emptySet());
assertThat(conf.maxLiveDateOfClosedIssues()).isNull();
}
@Test
public void should_delete_only_old_closed_issues() {
Date now = DateUtils.parseDate("2013-05-18");
PurgeConfiguration conf = new PurgeConfiguration("root", "project", 30, Optional.empty(), System2.INSTANCE, emptySet());
Date toDate = conf.maxLiveDateOfClosedIssues(now);
assertThat(toDate.getYear()).isEqualTo(113);// =2013
assertThat(toDate.getMonth()).isEqualTo(3); // means April
assertThat(toDate.getDate()).isEqualTo(18);
}
@Test
public void should_have_empty_branch_purge_date() {
PurgeConfiguration conf = new PurgeConfiguration("root", "project", 30, Optional.of(10), System2.INSTANCE, emptySet());
assertThat(conf.maxLiveDateOfInactiveBranches()).isNotEmpty();
long tenDaysAgo = DateUtils.addDays(new Date(System2.INSTANCE.now()), -10).getTime();
assertThat(conf.maxLiveDateOfInactiveBranches().get().getTime()).isBetween(tenDaysAgo - 5000, tenDaysAgo + 5000);
}
@Test
public void should_calculate_branch_purge_date() {
PurgeConfiguration conf = new PurgeConfiguration("root", "project", 30, Optional.empty(), System2.INSTANCE, emptySet());
assertThat(conf.maxLiveDateOfInactiveBranches()).isEmpty();
}
}
| 2,766 | 39.691176 | 124 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeProfilerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.purge;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class PurgeProfilerTest {
private MockedClock clock;
private PurgeProfiler profiler;
@Before
public void prepare() {
clock = new MockedClock();
profiler = new PurgeProfiler(clock);
}
@Test
public void shouldProfilePurge() {
profiler.start("foo");
clock.sleep(10);
profiler.stop();
profiler.start("bar");
clock.sleep(5);
profiler.stop();
profiler.start("foo");
clock.sleep(8);
profiler.stop();
List<String> profilingResult = profiler.getProfilingResult(50);
Assertions.assertThat(profilingResult).hasSize(2);
assertThat(profilingResult.get(0)).contains("foo: 18ms");
assertThat(profilingResult.get(1)).contains("bar: 5ms");
}
@Test
public void shouldResetPurgeProfiling() {
profiler.start("foo");
clock.sleep(10);
profiler.stop();
profiler.reset();
profiler.start("bar");
clock.sleep(5);
profiler.stop();
profiler.start("foo");
clock.sleep(8);
profiler.stop();
List<String> profilingResult = profiler.getProfilingResult(50);
Assertions.assertThat(profilingResult).hasSize(2);
assertThat(profilingResult.get(0)).contains("foo: 8ms");
assertThat(profilingResult.get(1)).contains("bar: 5ms");
}
private static class MockedClock extends PurgeProfiler.Clock {
private long now = 0;
@Override
public long now() {
return now;
}
public void sleep(long duration) {
now += duration;
}
}
}
| 2,520 | 25.536842 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeableAnalysisDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.purge;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class PurgeableAnalysisDtoTest {
@Test
public void testEquals() {
PurgeableAnalysisDto dto1 = new PurgeableAnalysisDto().setAnalysisUuid("u3");
PurgeableAnalysisDto dto2 = new PurgeableAnalysisDto().setAnalysisUuid("u4");
assertThat(dto1.equals(dto2)).isFalse();
assertThat(dto2.equals(dto1)).isFalse();
assertThat(dto1.equals(dto1)).isTrue();
assertThat(dto1.equals(new PurgeableAnalysisDto().setAnalysisUuid("u3"))).isTrue();
assertThat(dto1.equals("bi_bop_a_lou_la")).isFalse();
assertThat(dto1.equals(null)).isFalse();
}
@Test
public void testHasCode() {
PurgeableAnalysisDto dto = new PurgeableAnalysisDto().setAnalysisUuid("u3");
// no uuid => NPE
dto = new PurgeableAnalysisDto();
assertThatThrownBy(dto::hashCode)
.isInstanceOf(NullPointerException.class);
}
@Test
public void testToString() {
PurgeableAnalysisDto dto = new PurgeableAnalysisDto().setAnalysisUuid("u3");
assertThat(dto.toString()).isNotEmpty();
}
}
| 2,038 | 33.559322 | 87 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/purge/period/DefaultPeriodCleanerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.purge.period;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.purge.PurgeDao;
import org.sonar.db.purge.PurgeProfiler;
import org.sonar.db.purge.PurgeableAnalysisDto;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
public class DefaultPeriodCleanerTest {
@Test
public void doClean() {
PurgeDao dao = mock(PurgeDao.class);
DbSession session = mock(DbSession.class);
when(dao.selectPurgeableAnalyses("uuid_123", session)).thenReturn(Arrays.asList(
new PurgeableAnalysisDto().setAnalysisUuid("u999").setDate(System2.INSTANCE.now()),
new PurgeableAnalysisDto().setAnalysisUuid("u456").setDate(System2.INSTANCE.now())
));
Filter filter1 = newFirstSnapshotInListFilter();
Filter filter2 = newFirstSnapshotInListFilter();
PurgeProfiler profiler = new PurgeProfiler();
DefaultPeriodCleaner cleaner = new DefaultPeriodCleaner(dao, profiler);
cleaner.doClean("uuid_123", Arrays.asList(filter1, filter2), session);
InOrder inOrder = Mockito.inOrder(dao, filter1, filter2);
inOrder.verify(filter1).log();
inOrder.verify(dao, times(1)).deleteAnalyses(session, profiler, ImmutableList.of("u999"));
inOrder.verify(filter2).log();
inOrder.verify(dao, times(1)).deleteAnalyses(session, profiler, ImmutableList.of("u456"));
inOrder.verifyNoMoreInteractions();
}
private Filter newFirstSnapshotInListFilter() {
Filter filter1 = mock(Filter.class);
when(filter1.filter(anyList())).thenAnswer(invocation -> Collections.singletonList(((List) invocation.getArguments()[0]).iterator().next()));
return filter1;
}
}
| 2,833 | 38.915493 | 145 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/purge/period/DeleteAllFilterTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.purge.period;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import org.sonar.db.purge.DbCleanerTestUtils;
import org.sonar.db.purge.PurgeableAnalysisDto;
import static org.assertj.core.api.Assertions.assertThat;
public class DeleteAllFilterTest {
@Test
public void shouldDeleteAllSnapshotsPriorToDate() {
Filter filter = new DeleteAllFilter(DateUtils.parseDate("2011-12-25"));
List<PurgeableAnalysisDto> toDelete = filter.filter(Arrays.asList(
DbCleanerTestUtils.createAnalysisWithDate("u1", "2010-01-01"),
DbCleanerTestUtils.createAnalysisWithDate("u2", "2010-12-25"),
DbCleanerTestUtils.createAnalysisWithDate("u3", "2012-01-01")
));
assertThat(toDelete).extracting("analysisUuid").containsOnly("u1", "u2");
}
}
| 1,689 | 35.73913 | 77 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/purge/period/IntervalTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.purge.period;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import org.sonar.db.purge.DbCleanerTestUtils;
import org.sonar.db.purge.PurgeableAnalysisDto;
import static org.assertj.core.api.Assertions.assertThat;
public class IntervalTest {
static int calendarField(Interval interval, int field) {
if (interval.count() == 0) {
return -1;
}
PurgeableAnalysisDto first = interval.get().iterator().next();
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(first.getDate());
return cal.get(field);
}
@Test
public void shouldGroupByIntervals() {
List<PurgeableAnalysisDto> snapshots = Arrays.asList(
DbCleanerTestUtils.createAnalysisWithDate("u1", "2011-04-03"),
DbCleanerTestUtils.createAnalysisWithDate("u2", "2011-05-01"),
DbCleanerTestUtils.createAnalysisWithDate("u3", "2011-05-19"),
DbCleanerTestUtils.createAnalysisWithDate("u4", "2011-06-02"),
DbCleanerTestUtils.createAnalysisWithDate("u5", "2011-06-20"),
DbCleanerTestUtils.createAnalysisWithDate("u6", "2012-06-29") // out of scope
);
List<Interval> intervals = Interval.group(snapshots, DateUtils.parseDate("2010-01-01"), DateUtils.parseDate("2011-12-31"), Calendar.MONTH);
assertThat(intervals).hasSize(3);
assertThat(intervals.get(0).count()).isOne();
assertThat(calendarField(intervals.get(0), Calendar.MONTH)).isEqualTo((Calendar.APRIL));
assertThat(intervals.get(1).count()).isEqualTo(2);
assertThat(calendarField(intervals.get(1), Calendar.MONTH)).isEqualTo((Calendar.MAY));
assertThat(intervals.get(2).count()).isEqualTo(2);
assertThat(calendarField(intervals.get(2), Calendar.MONTH)).isEqualTo((Calendar.JUNE));
}
@Test
public void shouldNotJoinMonthsOfDifferentYears() {
List<PurgeableAnalysisDto> snapshots = Arrays.asList(
DbCleanerTestUtils.createAnalysisWithDate("u1", "2010-04-03"),
DbCleanerTestUtils.createAnalysisWithDate("u2", "2011-04-13")
);
List<Interval> intervals = Interval.group(snapshots,
DateUtils.parseDateTime("2010-01-01T00:00:00+0100"), DateUtils.parseDateTime("2011-12-31T00:00:00+0100"), Calendar.MONTH);
assertThat(intervals).hasSize(2);
assertThat(intervals.get(0).count()).isOne();
assertThat(calendarField(intervals.get(0), Calendar.MONTH)).isEqualTo((Calendar.APRIL));
assertThat(calendarField(intervals.get(0), Calendar.YEAR)).isEqualTo((2010));
assertThat(intervals.get(1).count()).isOne();
assertThat(calendarField(intervals.get(1), Calendar.MONTH)).isEqualTo((Calendar.APRIL));
assertThat(calendarField(intervals.get(1), Calendar.YEAR)).isEqualTo((2011));
}
@Test
public void shouldIgnoreTimeWhenGroupingByIntervals() {
List<PurgeableAnalysisDto> snapshots = Arrays.asList(
DbCleanerTestUtils.createAnalysisWithDateTime("u1", "2011-05-25T00:16:48+0100"),
DbCleanerTestUtils.createAnalysisWithDateTime("u2", "2012-01-26T00:16:48+0100"),
DbCleanerTestUtils.createAnalysisWithDateTime("u3", "2012-01-27T00:16:48+0100")
);
List<Interval> intervals = Interval.group(snapshots,
DateUtils.parseDateTime("2011-05-25T00:00:00+0100"),
DateUtils.parseDateTime("2012-01-26T00:00:00+0100"), Calendar.MONTH);
assertThat(intervals.size()).isOne();
assertThat(intervals.get(0).count()).isOne();
assertThat(intervals.get(0).get().get(0).getAnalysisUuid()).isEqualTo(("u2"));
}
}
| 4,425 | 39.981481 | 143 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/purge/period/KeepOneFilterTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.purge.period;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import org.sonar.db.purge.DbCleanerTestUtils;
import org.sonar.db.purge.PurgeableAnalysisDto;
import static org.assertj.core.api.Assertions.assertThat;
public class KeepOneFilterTest {
private static List<String> analysisUuids(List<PurgeableAnalysisDto> snapshotDtos) {
return snapshotDtos.stream().map(PurgeableAnalysisDto::getAnalysisUuid).toList();
}
@Test
public void shouldOnlyOneSnapshotPerInterval() {
Filter filter = new KeepOneFilter(DateUtils.parseDate("2011-03-25"), DateUtils.parseDate("2011-08-25"), Calendar.MONTH, "month");
List<PurgeableAnalysisDto> toDelete = filter.filter(Arrays.asList(
DbCleanerTestUtils.createAnalysisWithDate("u1", "2010-01-01"), // out of scope -> keep
DbCleanerTestUtils.createAnalysisWithDate("u2", "2011-05-01"), // may -> keep
DbCleanerTestUtils.createAnalysisWithDate("u3", "2011-05-02"), // may -> to be deleted
DbCleanerTestUtils.createAnalysisWithDate("u4", "2011-05-19"), // may -> to be deleted
DbCleanerTestUtils.createAnalysisWithDate("u5", "2011-06-01"), // june -> keep
DbCleanerTestUtils.createAnalysisWithDate("u6", "2012-01-01") // out of scope -> keep
));
assertThat(toDelete).hasSize(2);
assertThat(analysisUuids(toDelete)).containsOnly("u2", "u3");
}
@Test
public void shouldKeepNonDeletableSnapshots() {
Filter filter = new KeepOneFilter(DateUtils.parseDate("2011-03-25"), DateUtils.parseDate("2011-08-25"), Calendar.MONTH, "month");
List<PurgeableAnalysisDto> toDelete = filter.filter(Arrays.asList(
DbCleanerTestUtils.createAnalysisWithDate("u1", "2011-05-01"), // to be deleted
DbCleanerTestUtils.createAnalysisWithDate("u2", "2011-05-02").setLast(true),
DbCleanerTestUtils.createAnalysisWithDate("u3", "2011-05-19").setHasEvents(true).setLast(false),
DbCleanerTestUtils.createAnalysisWithDate("u4", "2011-05-23") // to be deleted
));
assertThat(toDelete).hasSize(2);
assertThat(analysisUuids(toDelete)).contains("u1", "u4");
}
@Test
public void test_isDeletable() {
assertThat(KeepOneFilter.isDeletable(DbCleanerTestUtils.createAnalysisWithDate("u1", "2011-05-01"))).isTrue();
assertThat(KeepOneFilter.isDeletable(DbCleanerTestUtils.createAnalysisWithDate("u1", "2011-05-01").setLast(true))).isFalse();
assertThat(KeepOneFilter.isDeletable(DbCleanerTestUtils.createAnalysisWithDate("u1", "2011-05-01").setHasEvents(true))).isFalse();
}
}
| 3,473 | 42.425 | 134 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/purge/period/KeepWithVersionFilterTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.purge.period;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.sonar.db.purge.DbCleanerTestUtils;
import org.sonar.db.purge.PurgeableAnalysisDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.utils.DateUtils.parseDate;
public class KeepWithVersionFilterTest {
@Test
public void keep_only_analyses_with_a_version() {
Filter underTest = new KeepWithVersionFilter(parseDate("2015-10-18"));
List<PurgeableAnalysisDto> result = underTest.filter(Arrays.asList(
DbCleanerTestUtils.createAnalysisWithDate("u1", "2015-10-17").setVersion("V1"),
DbCleanerTestUtils.createAnalysisWithDate("u2", "2015-10-17").setVersion(null),
DbCleanerTestUtils.createAnalysisWithDate("u3", "2015-10-19").setVersion(null)));
assertThat(result).extracting(PurgeableAnalysisDto::getAnalysisUuid).containsExactlyInAnyOrder("u2");
}
}
| 1,782 | 38.622222 | 105 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/ActiveRuleKeyTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualityprofile;
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.sonar.db.qualityprofile.QualityProfileTesting.newQualityProfileDto;
public class ActiveRuleKeyTest {
@Test
public void of() {
RuleKey ruleKey = RuleKey.of("xoo", "R1");
QProfileDto profile = newQualityProfileDto();
ActiveRuleKey key = ActiveRuleKey.of(profile, ruleKey);
assertThat(key.getRuleProfileUuid()).isEqualTo(profile.getRulesProfileUuid());
assertThat(key.getRuleKey()).isSameAs(ruleKey);
assertThat(key).hasToString(profile.getRulesProfileUuid() + ":xoo:R1");
}
@Test
public void rule_key_can_contain_colons() {
RuleKey ruleKey = RuleKey.of("java", "Key:With:Some::Colons");
QProfileDto profile = newQualityProfileDto();
ActiveRuleKey key = ActiveRuleKey.of(profile, ruleKey);
assertThat(key.getRuleProfileUuid()).isEqualTo(profile.getRulesProfileUuid());
assertThat(key.getRuleKey()).isSameAs(ruleKey);
assertThat(key).hasToString(profile.getRulesProfileUuid() + ":java:Key:With:Some::Colons");
}
@Test
public void parse() {
ActiveRuleKey key = ActiveRuleKey.parse("P1:xoo:R1");
assertThat(key.getRuleProfileUuid()).isEqualTo("P1");
assertThat(key.getRuleKey().repository()).isEqualTo("xoo");
assertThat(key.getRuleKey().rule()).isEqualTo("R1");
}
@Test
public void parse_fail_when_less_than_three_colons() {
try {
ActiveRuleKey.parse("P1:xoo");
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Bad format of activeRule key: P1:xoo");
}
}
@Test
public void equals_and_hashcode() {
ActiveRuleKey key1 = ActiveRuleKey.parse("P1:xoo:R1");
ActiveRuleKey key1b = ActiveRuleKey.parse("P1:xoo:R1");
ActiveRuleKey key2 = ActiveRuleKey.parse("P1:xoo:R2");
ActiveRuleKey key3 = ActiveRuleKey.parse("P2:xoo:R1");
assertThat(key1.equals(key1)).isTrue();
assertThat(key1.equals(key1b)).isTrue();
assertThat(key1.equals(null)).isFalse();
assertThat(key1.equals("P1:xoo:R1")).isFalse();
assertThat(key1.equals(key2)).isFalse();
assertThat(key1.equals(key3)).isFalse();
assertThat(key1).hasSameHashCodeAs(key1);
}
}
| 3,163 | 36.223529 | 95 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/ActiveRuleParamDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualityprofile;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ActiveRuleParamDtoTest {
@Test
public void groupByKey() {
assertThat(ActiveRuleParamDto.groupByKey(Collections.emptyList())).isEmpty();
Collection<ActiveRuleParamDto> dtos = Arrays.asList(
new ActiveRuleParamDto().setKey("foo"), new ActiveRuleParamDto().setKey("bar")
);
Map<String, ActiveRuleParamDto> group = ActiveRuleParamDto.groupByKey(dtos);
assertThat(group).containsOnlyKeys("foo", "bar");
}
}
| 1,521 | 34.395349 | 84 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QProfileChangeDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualityprofile;
import java.util.Collections;
import java.util.Map;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
public class QProfileChangeDtoTest {
private QProfileChangeDto underTest = new QProfileChangeDto();
@Test
public void convert_data_to_map() {
underTest.setData((Map) null);
assertThat(underTest.getDataAsMap()).isEmpty();
underTest.setData(Collections.emptyMap());
assertThat(underTest.getDataAsMap()).isEmpty();
underTest.setData(Map.of("k1", "v1", "k2", "v2"));
assertThat(underTest.getDataAsMap()).containsOnly(entry("k1", "v1"), entry("k2", "v2"));
}
}
| 1,560 | 33.688889 | 92 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDescriptionSectionContextDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.rule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.rule.RuleDescriptionSectionContextDto.DISPLAY_NAME_MUST_BE_SET_ERROR;
import static org.sonar.db.rule.RuleDescriptionSectionContextDto.KEY_MUST_BE_SET_ERROR;
public class RuleDescriptionSectionContextDtoTest {
private static final String CONTEXT_KEY = "key";
private static final String CONTEXT_DISPLAY_NAME = "displayName";
@Test
public void check_of_instantiate_object() {
RuleDescriptionSectionContextDto context = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME);
assertThat(context).extracting(RuleDescriptionSectionContextDto::getKey,
RuleDescriptionSectionContextDto::getDisplayName).contains(CONTEXT_KEY, CONTEXT_DISPLAY_NAME);
}
@Test
public void check_of_with_key_is_empty() {
assertThatThrownBy(() -> RuleDescriptionSectionContextDto.of("", CONTEXT_DISPLAY_NAME))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(KEY_MUST_BE_SET_ERROR);
}
@Test
public void check_of_with_display_name_is_empty() {
assertThatThrownBy(() -> RuleDescriptionSectionContextDto.of(CONTEXT_KEY, ""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(DISPLAY_NAME_MUST_BE_SET_ERROR);
}
@Test
public void equals_with_equals_objects_should_return_true() {
RuleDescriptionSectionContextDto context1 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME);
RuleDescriptionSectionContextDto context2 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME);
assertThat(context1).isEqualTo(context2);
}
@Test
public void equals_with_same_objects_should_return_true() {
RuleDescriptionSectionContextDto context1 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME);
assertThat(context1).isEqualTo(context1);
}
@Test
public void equals_with_one_null_objet_should_return_false() {
RuleDescriptionSectionContextDto context1 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME);
assertThat(context1).isNotEqualTo(null);
}
@Test
public void equals_with_different_display_names_should_return_false() {
RuleDescriptionSectionContextDto context1 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME);
RuleDescriptionSectionContextDto context2 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME + "2");
assertThat(context1).isNotEqualTo(context2);
}
@Test
public void equals_with_different_context_keys_should_return_false() {
RuleDescriptionSectionContextDto context1 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME);
RuleDescriptionSectionContextDto context2 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY + "2", CONTEXT_DISPLAY_NAME);
assertThat(context1).isNotEqualTo(context2);
}
@Test
public void hashcode_with_equals_objects_should_return_same_hash() {
RuleDescriptionSectionContextDto context1 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME);
RuleDescriptionSectionContextDto context2 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME);
assertThat(context1).hasSameHashCodeAs(context2);
}
}
| 4,225 | 42.122449 | 125 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDescriptionSectionDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.rule;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class RuleDescriptionSectionDtoTest {
private static final RuleDescriptionSectionDto SECTION = RuleDescriptionSectionDto.builder()
.key("key")
.uuid("uuid")
.context(RuleDescriptionSectionContextDto.of("key", "displayName"))
.content("desc").build();
@Test
public void setDefault_whenKeyAlreadySet_shouldThrow() {
RuleDescriptionSectionDto.RuleDescriptionSectionDtoBuilder builderWithKey = RuleDescriptionSectionDto.builder()
.key("tagada");
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(builderWithKey::setDefault)
.withMessage("Only one of setDefault and key methods can be called");
}
@Test
public void setKey_whenDefaultAlreadySet_shouldThrow() {
RuleDescriptionSectionDto.RuleDescriptionSectionDtoBuilder builderWithDefault = RuleDescriptionSectionDto.builder()
.setDefault();
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> builderWithDefault.key("balbal"))
.withMessage("Only one of setDefault and key methods can be called");
}
@Test
public void testToString() {
Assertions.assertThat(SECTION)
.hasToString("RuleDescriptionSectionDto[uuid='uuid', key='key', content='desc', context='RuleDescriptionSectionContextDto[key='key', displayName='displayName']']");
}
}
| 2,341 | 38.694915 | 170 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.rule;
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import org.sonar.core.util.Uuids;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.StringUtils.repeat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.rule.RuleDto.ERROR_MESSAGE_SECTION_ALREADY_EXISTS;
import static org.sonar.db.rule.RuleTesting.newRule;
public class RuleDtoTest {
public static final String SECTION_KEY = "section key";
@Test
public void fail_if_key_is_too_long() {
assertThatThrownBy(() -> new RuleDto().setRuleKey(repeat("x", 250)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Rule key is too long: ");
}
@Test
public void fail_if_name_is_too_long() {
assertThatThrownBy(() -> new RuleDto().setName(repeat("x", 300)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Rule name is too long: ");
}
@Test
public void fail_if_tags_are_too_long() {
assertThatThrownBy(() -> {
Set<String> tags = ImmutableSet.of(repeat("a", 2000), repeat("b", 1000), repeat("c", 2000));
new RuleDto().setTags(tags);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Rule tags are too long: ");
}
@Test
public void tags_are_optional() {
RuleDto dto = new RuleDto().setTags(Collections.emptySet());
assertThat(dto.getTags()).isEmpty();
}
@Test
public void tags_are_joined_with_comma() {
Set<String> tags = new TreeSet<>(Set.of("first_tag", "second_tag", "third_tag"));
RuleDto dto = new RuleDto().setTags(tags);
assertThat(dto.getTags()).isEqualTo(tags);
assertThat(dto.getTagsAsString()).isEqualTo("first_tag,second_tag,third_tag");
}
@Test
public void system_tags_are_joined_with_comma() {
Set<String> systemTags = new TreeSet<>(Set.of("first_tag", "second_tag", "third_tag"));
RuleDto dto = new RuleDto().setSystemTags(systemTags);
assertThat(dto.getSystemTags()).isEqualTo(systemTags);
}
@Test
public void security_standards_are_joined_with_comma() {
Set<String> securityStandards = new TreeSet<>(Set.of("first_tag", "second_tag", "third_tag"));
RuleDto dto = new RuleDto().setSecurityStandards(securityStandards);
assertThat(dto.getSecurityStandards()).isEqualTo(securityStandards);
}
@Test
public void equals_is_based_on_uuid() {
String uuid = Uuids.createFast();
RuleDto dto = newRule().setUuid(uuid);
assertThat(dto)
.isEqualTo(dto)
.isEqualTo(newRule().setUuid(uuid))
.isEqualTo(newRule().setRuleKey(dto.getRuleKey()).setUuid(uuid))
.isNotNull()
.isNotEqualTo(new Object())
.isNotEqualTo(newRule().setRuleKey(dto.getRuleKey()).setUuid(Uuids.createFast()))
.isNotEqualTo(newRule().setUuid(Uuids.createFast()));
}
@Test
public void hashcode_is_based_on_uuid() {
String uuid = Uuids.createFast();
RuleDto dto = newRule().setUuid(uuid);
assertThat(dto)
.hasSameHashCodeAs(dto)
.hasSameHashCodeAs(newRule().setUuid(uuid))
.hasSameHashCodeAs(newRule().setRuleKey(dto.getRuleKey()).setUuid(uuid));
assertThat(dto.hashCode())
.isNotEqualTo(new Object().hashCode())
.isNotEqualTo(newRule().setRuleKey(dto.getRuleKey()).setUuid(Uuids.createFast()).hashCode())
.isNotEqualTo(newRule().setUuid(Uuids.createFast()).hashCode());
}
@Test
public void add_rule_description_section_same_key_should_throw_error() {
RuleDto dto = new RuleDto();
RuleDescriptionSectionDto section1 = createSection(SECTION_KEY);
dto.addRuleDescriptionSectionDto(section1);
RuleDescriptionSectionDto section2 = createSection(SECTION_KEY);
assertThatThrownBy(() -> dto.addRuleDescriptionSectionDto(section2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format(ERROR_MESSAGE_SECTION_ALREADY_EXISTS, SECTION_KEY, "null"));
}
@Test
public void add_rule_description_section_with_different_context() {
RuleDto dto = new RuleDto();
RuleDescriptionSectionDto section1 = createSection(RuleDtoTest.SECTION_KEY, "context key 1", "context display Name 1");
dto.addRuleDescriptionSectionDto(section1);
RuleDescriptionSectionDto section2 = createSection(RuleDtoTest.SECTION_KEY, "context key 2", "context display Name 2");
dto.addRuleDescriptionSectionDto(section2);
assertThat(dto.getRuleDescriptionSectionDtos())
.usingRecursiveFieldByFieldElementComparator()
.containsExactlyInAnyOrder(section1, section2);
}
@Test
public void add_rule_description_section_with_same_section_and_context_should_throw_error() {
RuleDto dto = new RuleDto();
String contextKey = randomAlphanumeric(50);
String displayName = randomAlphanumeric(50);
RuleDescriptionSectionDto section1 = createSection(SECTION_KEY, contextKey, displayName);
dto.addRuleDescriptionSectionDto(section1);
RuleDescriptionSectionDto section2 = createSection(SECTION_KEY, contextKey, displayName);
assertThatThrownBy(() -> dto.addRuleDescriptionSectionDto(section2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format(ERROR_MESSAGE_SECTION_ALREADY_EXISTS, SECTION_KEY, contextKey));
}
@NotNull
private static RuleDescriptionSectionDto createSection(String section_key, String contextKey, String contextDisplayName) {
return RuleDescriptionSectionDto.builder()
.key(section_key)
.context(RuleDescriptionSectionContextDto.of(contextKey, contextDisplayName))
.build();
}
@NotNull
private static RuleDescriptionSectionDto createSection(String section_key) {
return RuleDescriptionSectionDto.builder()
.key(section_key)
.build();
}
}
| 6,850 | 36.642857 | 124 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimGroupDaoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.scim;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
import org.apache.commons.lang.StringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.db.DbTester;
import org.sonar.db.user.GroupDto;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Fail.fail;
import static org.assertj.core.groups.Tuple.tuple;
@RunWith(DataProviderRunner.class)
public class ScimGroupDaoTest {
private static final String DISPLAY_NAME_FILTER = "displayName eq \"group2\"";
@Rule
public DbTester db = DbTester.create();
private final ScimGroupDao scimGroupDao = db.getDbClient().scimGroupDao();
@Test
public void findAll_ifNoData_returnsEmptyList() {
assertThat(scimGroupDao.findAll(db.getSession())).isEmpty();
}
@Test
public void findAll_returnsAllEntries() {
ScimGroupDto scimGroup1 = db.users().insertScimGroup(db.users().insertGroup());
ScimGroupDto scimGroup2 = db.users().insertScimGroup(db.users().insertGroup());
List<ScimGroupDto> underTest = scimGroupDao.findAll(db.getSession());
assertThat(underTest).hasSize(2)
.extracting(ScimGroupDto::getGroupUuid, ScimGroupDto::getScimGroupUuid)
.containsExactlyInAnyOrder(
tuple(scimGroup1.getGroupUuid(), scimGroup1.getScimGroupUuid()),
tuple(scimGroup2.getGroupUuid(), scimGroup2.getScimGroupUuid()));
}
@Test
public void countScimGroups_shouldReturnTheTotalNumberOfScimGroups() {
int totalScimGroups = 15;
generateScimGroups(totalScimGroups);
assertThat(scimGroupDao.countScimGroups(db.getSession(), ScimGroupQuery.ALL)).isEqualTo(totalScimGroups);
}
@Test
public void countScimGroups_shouldReturnZero_whenNoScimGroups() {
assertThat(scimGroupDao.countScimGroups(db.getSession(), ScimGroupQuery.ALL)).isZero();
}
@DataProvider
public static Object[][] paginationData() {
return new Object[][] {
{5, 0, 20, List.of("1", "2", "3", "4", "5")},
{9, 0, 5, List.of("1", "2", "3", "4", "5")},
{9, 3, 3, List.of("4", "5", "6")},
{9, 7, 3, List.of("8", "9")},
{5, 5, 20, List.of()},
{5, 0, 0, List.of()}
};
}
@Test
@UseDataProvider("paginationData")
public void findScimGroups_whenPaginationAndStartIndex_shouldReturnTheCorrectNumberOfScimGroups(int totalScimGroups, int offset, int pageSize,
List<String> expectedScimGroupUuidSuffixes) {
generateScimGroups(totalScimGroups);
List<ScimGroupDto> scimGroupDtos = scimGroupDao.findScimGroups(db.getSession(), ScimGroupQuery.ALL, offset, pageSize);
List<String> actualScimGroupsUuids = toScimGroupsUuids(scimGroupDtos);
List<String> expectedScimGroupUuids = toExpectedscimGroupUuids(expectedScimGroupUuidSuffixes);
assertThat(actualScimGroupsUuids).containsExactlyElementsOf(expectedScimGroupUuids);
}
private static List<String> toExpectedscimGroupUuids(List<String> expectedScimGroupUuidSuffixes) {
return expectedScimGroupUuidSuffixes.stream()
.map(expectedScimGroupUuidSuffix -> "scim_uuid_Scim Group" + expectedScimGroupUuidSuffix)
.toList();
}
@Test
public void findScimGroups_whenFilteringByDisplayName_shouldReturnTheExpectedScimGroups() {
insertGroupAndScimGroup("group1");
insertGroupAndScimGroup("group2");
ScimGroupQuery query = ScimGroupQuery.fromScimFilter(DISPLAY_NAME_FILTER);
List<ScimGroupDto> scimGroups = scimGroupDao.findScimGroups(db.getSession(), query, 0, 100);
assertThat(scimGroups).hasSize(1);
assertThat(scimGroups.get(0).getScimGroupUuid()).isEqualTo(createScimGroupUuid("group2"));
}
@Test
public void countScimGroups_whenFilteringByDisplayName_shouldReturnCorrectCount() {
insertGroupAndScimGroup("group1");
insertGroupAndScimGroup("group2");
ScimGroupQuery query = ScimGroupQuery.fromScimFilter(DISPLAY_NAME_FILTER);
int groupCount = scimGroupDao.countScimGroups(db.getSession(), query);
assertThat(groupCount).isEqualTo(1);
}
private void insertGroupAndScimGroup(String groupName) {
GroupDto groupDto = insertGroup(groupName);
insertScimGroup(createScimGroupUuid(groupName), groupDto.getUuid());
}
@Test
public void getManagedGroupsSqlFilter_whenFilterByManagedIsTrue_returnsCorrectQuery() {
String filterManagedUser = scimGroupDao.getManagedGroupSqlFilter(true);
assertThat(filterManagedUser).isEqualTo(" exists (select group_uuid from scim_groups sg where sg.group_uuid = uuid)");
}
@Test
public void getManagedGroupsSqlFilter_whenFilterByManagedIsFalse_returnsCorrectQuery() {
String filterNonManagedUser = scimGroupDao.getManagedGroupSqlFilter(false);
assertThat(filterNonManagedUser).isEqualTo("not exists (select group_uuid from scim_groups sg where sg.group_uuid = uuid)");
}
private List<ScimGroupDto> generateScimGroups(int totalScimGroups) {
return IntStream.range(1, totalScimGroups + 1)
.mapToObj(i -> insertGroup(createGroupName(i)))
.map(groupDto -> insertScimGroup(createScimGroupUuid(groupDto.getName()), groupDto.getUuid()))
.toList();
}
private static String createGroupName(int i) {
return "Scim Group" + i;
}
private GroupDto insertGroup(String name) {
return db.users().insertGroup(name);
}
private static String createScimGroupUuid(String groupName) {
return StringUtils.substring("scim_uuid_" + groupName, 0, 40);
}
private ScimGroupDto insertScimGroup(String scimGroupUuid, String groupUuid) {
ScimGroupDto scimGroupDto = new ScimGroupDto(scimGroupUuid, groupUuid);
Map<String, Object> data = Map.of("scim_uuid", scimGroupDto.getScimGroupUuid(), "group_uuid", scimGroupDto.getGroupUuid());
db.executeInsert("scim_groups", data);
return scimGroupDto;
}
private static List<String> toScimGroupsUuids(Collection<ScimGroupDto> scimGroupDtos) {
return scimGroupDtos.stream()
.map(ScimGroupDto::getScimGroupUuid)
.toList();
}
@Test
public void findByScimUuid_whenScimUuidNotFound_shouldReturnEmptyOptional() {
assertThat(scimGroupDao.findByScimUuid(db.getSession(), "unknownId")).isEmpty();
}
@Test
public void findByScimUuid_whenScimUuidFound_shouldReturnDto() {
ScimGroupDto scimGroupDto = db.users().insertScimGroup(db.users().insertGroup());
db.users().insertScimGroup(db.users().insertGroup());
ScimGroupDto underTest = scimGroupDao.findByScimUuid(db.getSession(), scimGroupDto.getScimGroupUuid())
.orElseGet(() -> fail("Group not found"));
assertThat(underTest.getScimGroupUuid()).isEqualTo(scimGroupDto.getScimGroupUuid());
assertThat(underTest.getGroupUuid()).isEqualTo(scimGroupDto.getGroupUuid());
}
@Test
public void findByGroupUuid_whenScimUuidNotFound_shouldReturnEmptyOptional() {
assertThat(scimGroupDao.findByGroupUuid(db.getSession(), "unknownId")).isEmpty();
}
@Test
public void findByGroupUuid_whenScimUuidFound_shouldReturnDto() {
ScimGroupDto scimGroupDto = db.users().insertScimGroup(db.users().insertGroup());
db.users().insertScimGroup(db.users().insertGroup());
ScimGroupDto underTest = scimGroupDao.findByGroupUuid(db.getSession(), scimGroupDto.getGroupUuid())
.orElseGet(() -> fail("Group not found"));
assertThat(underTest.getScimGroupUuid()).isEqualTo(scimGroupDto.getScimGroupUuid());
assertThat(underTest.getGroupUuid()).isEqualTo(scimGroupDto.getGroupUuid());
}
@Test
public void enableScimForGroup_addsGroupToScimGroups() {
ScimGroupDto underTest = scimGroupDao.enableScimForGroup(db.getSession(), "sqGroup1");
assertThat(underTest.getScimGroupUuid()).isNotBlank();
ScimGroupDto scimGroupDto = scimGroupDao.findByScimUuid(db.getSession(), underTest.getScimGroupUuid()).orElseThrow();
assertThat(underTest.getScimGroupUuid()).isEqualTo(scimGroupDto.getScimGroupUuid());
assertThat(underTest.getGroupUuid()).isEqualTo(scimGroupDto.getGroupUuid());
}
@Test
public void deleteByGroupUuid_shouldDeleteScimGroup() {
ScimGroupDto scimGroupDto = db.users().insertScimGroup(db.users().insertGroup());
scimGroupDao.deleteByGroupUuid(db.getSession(), scimGroupDto.getGroupUuid());
assertThat(scimGroupDao.findAll(db.getSession())).isEmpty();
}
@Test
public void deleteByScimUuid_shouldDeleteScimGroup() {
ScimGroupDto scimGroupDto1 = db.users().insertScimGroup(db.users().insertGroup());
ScimGroupDto scimGroupDto2 = db.users().insertScimGroup(db.users().insertGroup());
scimGroupDao.deleteByScimUuid(db.getSession(), scimGroupDto1.getScimGroupUuid());
List<ScimGroupDto> remainingGroups = scimGroupDao.findAll(db.getSession());
assertThat(remainingGroups).hasSize(1);
ScimGroupDto remainingGroup = remainingGroups.get(0);
assertThat(remainingGroup.getScimGroupUuid()).isEqualTo(scimGroupDto2.getScimGroupUuid());
assertThat(remainingGroup.getGroupUuid()).isEqualTo(scimGroupDto2.getGroupUuid());
}
@Test
public void deleteFromGroupUuid_shouldNotFail_whenNoGroup() {
assertThatCode(() -> scimGroupDao.deleteByGroupUuid(db.getSession(), randomAlphanumeric(6))).doesNotThrowAnyException();
}
@Test
public void deleteAll_should_remove_all_ScimGroups(){
insertScimGroup("scim-group-uuid1", "group-uuid1");
insertScimGroup("scim-group-uuid2", "group-uuid2");
scimGroupDao.deleteAll(db.getSession());
assertThat(scimGroupDao.findAll(db.getSession())).isEmpty();
}
}
| 10,671 | 38.820896 | 144 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimGroupQueryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.scim;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@RunWith(DataProviderRunner.class)
public class ScimGroupQueryTest {
@DataProvider
public static Object[][] filterData() {
ScimGroupQuery queryWithDisplayName = new ScimGroupQuery("testGroup");
return new Object[][] {
{"displayName eq \"testGroup\"", queryWithDisplayName},
{" displayName eq \"testGroup\" ", queryWithDisplayName},
{"displayName eq \"testGroup\"", queryWithDisplayName},
{"DIsPlaynaMe eq \"testGroup\"", queryWithDisplayName},
{"displayName EQ \"testGroup\"", queryWithDisplayName},
{null, ScimGroupQuery.ALL},
{"", ScimGroupQuery.ALL}
};
}
@Test
@UseDataProvider("filterData")
public void fromScimFilter_shouldCorrectlyResolveProperties(String filter, ScimGroupQuery expected) {
ScimGroupQuery scimGroupQuery = ScimGroupQuery.fromScimFilter(filter);
assertThat(scimGroupQuery).usingRecursiveComparison().isEqualTo(expected);
}
@DataProvider
public static Object[][] unsupportedFilterData() {
return new Object[][] {
{"otherProp eq \"testGroup\""},
{"displayName eq \"testGroup\" or displayName eq \"testGroup2\""},
{"displayName eq \"testGroup\" and email eq \"test.user2@okta.local\""},
{"displayName eq \"testGroup\"xjdkfgldkjfhg"}
};
}
@Test
@UseDataProvider("unsupportedFilterData")
public void fromScimFilter_shouldThrowAnException(String filter) {
assertThatIllegalArgumentException()
.isThrownBy(() -> ScimGroupQuery.fromScimFilter(filter))
.withMessage(format("Unsupported filter or value: %s. The only supported filter and operator is 'displayName eq \"displayName\"", filter));
}
@Test
public void empty_shouldHaveNoProperties() {
ScimGroupQuery scimGroupQuery = ScimGroupQuery.ALL;
assertThat(scimGroupQuery.getDisplayName()).isNull();
}
}
| 3,127 | 36.686747 | 145 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimUserDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.scim;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(DataProviderRunner.class)
public class ScimUserDtoTest {
@DataProvider
public static Object[][] testEqualsParameters() {
return new Object[][] {
{new ScimUserDto("uuidA", "userIdA"), new ScimUserDto("uuidA", "userIdA"), true},
{new ScimUserDto("uuidA", "userIdA"), new ScimUserDto("uuidA", "userIdB"), false},
{new ScimUserDto("uuidA", "userIdA"), new ScimUserDto("uuidB", "userIdA"), false},
{new ScimUserDto("uuidA", "userIdA"), new ScimUserDto("uuidB", "userIdB"), false},
};
}
@Test
@UseDataProvider("testEqualsParameters")
public void testEquals(ScimUserDto scimUserDtoA, ScimUserDto scimUserDtoB, boolean expectedResult) {
assertThat(scimUserDtoA.equals(scimUserDtoB)).isEqualTo(expectedResult);
}
}
| 1,935 | 37.72 | 102 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimUserQueryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.scim;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(DataProviderRunner.class)
public class ScimUserQueryTest {
@DataProvider
public static Object[][] filterData() {
ScimUserQuery queryWithUserName = ScimUserQuery.builder().userName("test.user@okta.local").build();
ScimUserQuery emptyQuery = ScimUserQuery.builder().build();
return new Object[][]{
{"userName eq \"test.user@okta.local\"", queryWithUserName},
{" userName eq \"test.user@okta.local\" ", queryWithUserName},
{"userName eq \"test.user@okta.local\"", queryWithUserName},
{"UsERnaMe eq \"test.user@okta.local\"", queryWithUserName},
{"userName EQ \"test.user@okta.local\"", queryWithUserName},
{null, emptyQuery},
{"", emptyQuery}
};
}
@Test
@UseDataProvider("filterData")
public void fromScimFilter_shouldCorrectlyResolveProperties(String filter, ScimUserQuery expected) {
ScimUserQuery scimUserQuery = ScimUserQuery.fromScimFilter(filter);
assertThat(scimUserQuery).usingRecursiveComparison().isEqualTo(expected);
}
@DataProvider
public static Object[][] unsupportedFilterData() {
return new Object[][]{
{"otherProp eq \"test.user@okta.local\""},
{"userName eq \"test.user@okta.local\" or userName eq \"test.user2@okta.local\""},
{"userName eq \"test.user@okta.local\" and email eq \"test.user2@okta.local\""},
{"userName eq \"test.user@okta.local\"xjdkfgldkjfhg"}
};
}
@Test
@UseDataProvider("unsupportedFilterData")
public void fromScimFilter_shouldThrowAnException(String filter) {
assertThatThrownBy(() -> ScimUserQuery.fromScimFilter(filter))
.isInstanceOf(IllegalStateException.class)
.hasMessage(String.format("Unsupported filter value: %s. Format should be 'userName eq \"username\"'", filter));
}
@Test
public void empty_shouldHaveNoProperties() {
ScimUserQuery scimUserQuery = ScimUserQuery.empty();
assertThat(scimUserQuery.getUserName()).isNull();
}
}
| 3,191 | 37.457831 | 118 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/source/FileSourceDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.source;
import com.google.common.base.Joiner;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;
import org.junit.Test;
import org.sonar.db.protobuf.DbFileSources;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class FileSourceDtoTest {
private static final String LOREM_IPSUM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac magna libero. " +
"Integer eu quam vulputate, interdum ante quis, sodales mauris. Nam mollis ornare dolor at maximus. Cras pharetra aliquam fringilla. " +
"Nunc hendrerit, elit eu mattis fermentum, ligula metus malesuada nunc, non fermentum augue tellus eu odio. Praesent ut vestibulum nibh. " +
"Curabitur sit amet dignissim magna, at efficitur dolor. Ut non felis aliquam justo euismod gravida. Morbi eleifend vitae ante eu pulvinar. " +
"Aliquam rhoncus magna quis lorem posuere semper.";
@Test
public void getSourceData_throws_ISE_with_id_fileUuid_and_projectUuid_in_message_when_data_cant_be_read() {
String uuid = "uuid";
String fileUuid = "file uuid";
String projectUuid = "project uuid";
FileSourceDto underTest = new FileSourceDto()
.setBinaryData(new byte[] {1, 2, 3, 4, 5})
.setUuid(uuid)
.setFileUuid(fileUuid)
.setProjectUuid(projectUuid);
assertThatThrownBy(underTest::getSourceData)
.isInstanceOf(IllegalStateException.class)
.hasMessage("Fail to decompress and deserialize source data [uuid=" + uuid + ",fileUuid=" + fileUuid + ",projectUuid=" + projectUuid + "]");
}
@Test
public void getSourceData_reads_Data_object_bigger_than_default_size_limit() {
DbFileSources.Data build = createOver64MBDataStructure();
byte[] bytes = FileSourceDto.encodeSourceData(build);
DbFileSources.Data data = new FileSourceDto().decodeSourceData(bytes);
assertThat(data.getLinesCount()).isEqualTo(build.getLinesCount());
}
private static DbFileSources.Data createOver64MBDataStructure() {
DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder();
DbFileSources.Line.Builder lineBuilder = DbFileSources.Line.newBuilder();
for (int i = 0; i < 199999; i++) {
dataBuilder.addLines(
lineBuilder.setSource(LOREM_IPSUM)
.setLine(i)
.build());
}
return dataBuilder.build();
}
@Test
public void new_FileSourceDto_as_lineCount_0_and_rawLineHashes_to_null() {
FileSourceDto underTest = new FileSourceDto();
assertThat(underTest.getLineCount()).isZero();
assertThat(underTest.getLineHashes()).isEmpty();
assertThat(underTest.getRawLineHashes()).isNull();
}
@Test
public void setLineHashes_null_sets_lineCount_to_0_and_rawLineHashes_to_null() {
FileSourceDto underTest = new FileSourceDto();
underTest.setLineHashes(null);
assertThat(underTest.getLineCount()).isZero();
assertThat(underTest.getLineHashes()).isEmpty();
assertThat(underTest.getRawLineHashes()).isNull();
}
@Test
public void setLineHashes_empty_sets_lineCount_to_1_and_rawLineHashes_to_null() {
FileSourceDto underTest = new FileSourceDto();
underTest.setLineHashes(Collections.emptyList());
assertThat(underTest.getLineCount()).isOne();
assertThat(underTest.getLineHashes()).isEmpty();
assertThat(underTest.getRawLineHashes()).isNull();
}
@Test
public void setLineHashes_sets_lineCount_to_size_of_list_and_rawLineHashes_to_join_by_line_return() {
FileSourceDto underTest = new FileSourceDto();
int expected = 1 + new Random().nextInt(96);
List<String> lineHashes = IntStream.range(0, expected).mapToObj(String::valueOf).toList();
underTest.setLineHashes(lineHashes);
assertThat(underTest.getLineCount()).isEqualTo(expected);
assertThat(underTest.getRawLineHashes()).isEqualTo(Joiner.on('\n').join(lineHashes));
}
}
| 4,821 | 39.864407 | 147 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/source/LineHashVersionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.source;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class LineHashVersionTest {
@Test
public void should_create_from_int() {
assertThat(LineHashVersion.valueOf(0)).isEqualTo(LineHashVersion.WITHOUT_SIGNIFICANT_CODE);
assertThat(LineHashVersion.valueOf(1)).isEqualTo(LineHashVersion.WITH_SIGNIFICANT_CODE);
}
@Test
public void should_throw_exception_if_version_is_too_high() {
assertThatThrownBy(() -> LineHashVersion.valueOf(2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unknown line hash version: 2");
}
@Test
public void should_throw_exception_if_version_is_too_low() {
assertThatThrownBy(() -> LineHashVersion.valueOf(-1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unknown line hash version: -1");
}
}
| 1,777 | 35.285714 | 95 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/user/GroupMembershipQueryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.user;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class GroupMembershipQueryTest {
@Test
public void create_query() {
GroupMembershipQuery underTest = GroupMembershipQuery.builder()
.groupSearch("sonar-users")
.membership(GroupMembershipQuery.IN)
.pageIndex(2)
.pageSize(10)
.build();
assertThat(underTest.groupSearch()).isEqualTo("sonar-users");
assertThat(underTest.membership()).isEqualTo("IN");
assertThat(underTest.pageIndex()).isEqualTo(2);
assertThat(underTest.pageSize()).isEqualTo(10);
}
@Test
public void fail_on_invalid_membership() {
assertThatThrownBy(() -> {
GroupMembershipQuery.builder()
.membership("unknwown")
.build();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Membership is not valid (got unknwown). Availables values are [ANY, IN, OUT]");
}
}
| 1,869 | 32.392857 | 98 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserQueryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.user;
import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Set;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class UserQueryTest {
@Test
public void copyWithNewRangeOfUserUuids_copyAllFieldsCorrectly() {
UserQuery original = createUserQueryWithAllFieldsSet();
Set<String> newRangeOfUsers = Set.of("user1");
UserQuery copy = UserQuery.copyWithNewRangeOfUserUuids(original, newRangeOfUsers);
assertThat(copy)
.usingRecursiveComparison()
.ignoringFields("userUuids")
.isEqualTo(original);
assertThat(copy.getUserUuids()).isEqualTo(newRangeOfUsers);
}
private static UserQuery createUserQueryWithAllFieldsSet() {
return UserQuery.builder()
.userUuids(Set.of("user1", "user2"))
.searchText("search text")
.isActive(true)
.isManagedClause("is managed clause")
.lastConnectionDateFrom(OffsetDateTime.now().minus(1, ChronoUnit.DAYS))
.lastConnectionDateTo(OffsetDateTime.now().plus(1, ChronoUnit.DECADES))
.sonarLintLastConnectionDateFrom(OffsetDateTime.now().plus(2, ChronoUnit.DAYS))
.sonarLintLastConnectionDateTo(OffsetDateTime.now().minus(2, ChronoUnit.DECADES))
.build();
}
}
| 2,130 | 35.118644 | 87 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDtoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.user;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class UserTokenDtoTest {
@Test
public void fail_if_token_hash_is_longer_than_255_characters() {
assertThatThrownBy(() -> new UserTokenDto().setTokenHash(randomAlphabetic(256)))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Token hash length (256) is longer than the maximum authorized (255)");
}
@Test
public void token_isExpired_is_properly_calculated() {
UserTokenDto tokenWithNoExpirationDate = new UserTokenDto();
UserTokenDto expiredToken = new UserTokenDto().setExpirationDate(0L);
UserTokenDto nonExpiredToken = new UserTokenDto().setExpirationDate(ZonedDateTime.now(ZoneId.systemDefault()).plusDays(10).toInstant().toEpochMilli());
assertThat(tokenWithNoExpirationDate.isExpired()).isFalse();
assertThat(expiredToken.isExpired()).isTrue();
assertThat(nonExpiredToken.isExpired()).isFalse();
}
}
| 2,030 | 38.823529 | 156 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/DbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.sql.Connection;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.sonar.api.utils.System2;
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.alm.integration.pat.AlmPatsDbTester;
import org.sonar.db.almsettings.AlmSettingsDbTester;
import org.sonar.db.audit.AuditDbTester;
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.component.ComponentDbTester;
import org.sonar.db.component.ProjectLinkDbTester;
import org.sonar.db.event.EventDbTester;
import org.sonar.db.favorite.FavoriteDbTester;
import org.sonar.db.issue.IssueDbTester;
import org.sonar.db.measure.MeasureDbTester;
import org.sonar.db.newcodeperiod.NewCodePeriodDbTester;
import org.sonar.db.notification.NotificationDbTester;
import org.sonar.db.permission.template.PermissionTemplateDbTester;
import org.sonar.db.plugin.PluginDbTester;
import org.sonar.db.property.InternalComponentPropertyDbTester;
import org.sonar.db.property.PropertyDbTester;
import org.sonar.db.qualitygate.QualityGateDbTester;
import org.sonar.db.qualityprofile.QualityProfileDbTester;
import org.sonar.db.rule.RuleDbTester;
import org.sonar.db.source.FileSourceTester;
import org.sonar.db.user.UserDbTester;
import org.sonar.db.webhook.WebhookDbTester;
import org.sonar.db.webhook.WebhookDeliveryDbTester;
/**
* This class should be called using @Rule.
* Data is truncated between each tests. The schema is created between each test.
*/
public class DbTester extends AbstractDbTester<TestDbImpl> {
private final UuidFactory uuidFactory = new SequenceUuidFactory();
private final System2 system2;
private final AuditPersister auditPersister;
private DbClient client;
private DbSession session = null;
private final UserDbTester userTester;
private final ComponentDbTester componentTester;
private final ProjectLinkDbTester projectLinkTester;
private final FavoriteDbTester favoriteTester;
private final EventDbTester eventTester;
private final PermissionTemplateDbTester permissionTemplateTester;
private final PropertyDbTester propertyTester;
private final QualityGateDbTester qualityGateDbTester;
private final IssueDbTester issueDbTester;
private final RuleDbTester ruleDbTester;
private final NewCodePeriodDbTester newCodePeriodTester;
private final NotificationDbTester notificationDbTester;
private final QualityProfileDbTester qualityProfileDbTester;
private final MeasureDbTester measureDbTester;
private final FileSourceTester fileSourceTester;
private final PluginDbTester pluginDbTester;
private final WebhookDbTester webhookDbTester;
private final WebhookDeliveryDbTester webhookDeliveryDbTester;
private final InternalComponentPropertyDbTester internalComponentPropertyTester;
private final AlmSettingsDbTester almSettingsDbTester;
private final AlmPatsDbTester almPatsDbtester;
private final AuditDbTester auditDbTester;
private DbTester(System2 system2, @Nullable String schemaPath, AuditPersister auditPersister, MyBatisConfExtension... confExtensions) {
super(TestDbImpl.create(schemaPath, confExtensions));
this.system2 = system2;
this.auditPersister = auditPersister;
initDbClient();
this.userTester = new UserDbTester(this);
this.componentTester = new ComponentDbTester(this);
this.projectLinkTester = new ProjectLinkDbTester(this);
this.favoriteTester = new FavoriteDbTester(this);
this.eventTester = new EventDbTester(this);
this.permissionTemplateTester = new PermissionTemplateDbTester(this);
this.propertyTester = new PropertyDbTester(this);
this.qualityGateDbTester = new QualityGateDbTester(this);
this.issueDbTester = new IssueDbTester(this);
this.ruleDbTester = new RuleDbTester(this);
this.notificationDbTester = new NotificationDbTester(this);
this.qualityProfileDbTester = new QualityProfileDbTester(this);
this.measureDbTester = new MeasureDbTester(this);
this.fileSourceTester = new FileSourceTester(this);
this.pluginDbTester = new PluginDbTester(this);
this.webhookDbTester = new WebhookDbTester(this);
this.webhookDeliveryDbTester = new WebhookDeliveryDbTester(this);
this.internalComponentPropertyTester = new InternalComponentPropertyDbTester(this);
this.newCodePeriodTester = new NewCodePeriodDbTester(this);
this.almSettingsDbTester = new AlmSettingsDbTester(this);
this.almPatsDbtester = new AlmPatsDbTester(this);
this.auditDbTester = new AuditDbTester(this);
}
public static DbTester create() {
return create(System2.INSTANCE, new NoOpAuditPersister());
}
public static DbTester create(AuditPersister auditPersister) {
return create(System2.INSTANCE, auditPersister);
}
public static DbTester create(System2 system2) {
return create(system2, new NoOpAuditPersister());
}
public static DbTester create(System2 system2, AuditPersister auditPersister) {
return new DbTester(system2, null, auditPersister);
}
public static DbTester createWithExtensionMappers(System2 system2, Class<?> firstMapperClass, Class<?>... otherMapperClasses) {
return new DbTester(system2, null, new NoOpAuditPersister(), new DbTesterMyBatisConfExtension(firstMapperClass, otherMapperClasses));
}
private void initDbClient() {
FastSpringContainer ioc = new FastSpringContainer();
ioc.add(auditPersister);
ioc.add(db.getMyBatis());
ioc.add(system2);
ioc.add(uuidFactory);
for (Class<?> daoClass : DaoModule.classes()) {
ioc.add(daoClass);
}
ioc.start();
List<Dao> daos = ioc.getComponentsByType(Dao.class);
client = new DbClient(db.getDatabase(), db.getMyBatis(), new TestDBSessions(db.getMyBatis()), daos.toArray(new Dao[daos.size()]));
}
@Override
protected void before() {
db.start();
db.truncateTables();
}
public UserDbTester users() {
return userTester;
}
public ComponentDbTester components() {
return componentTester;
}
public ProjectLinkDbTester projectLinks() {
return projectLinkTester;
}
public FavoriteDbTester favorites() {
return favoriteTester;
}
public EventDbTester events() {
return eventTester;
}
public PermissionTemplateDbTester permissionTemplates() {
return permissionTemplateTester;
}
public PropertyDbTester properties() {
return propertyTester;
}
public QualityGateDbTester qualityGates() {
return qualityGateDbTester;
}
public IssueDbTester issues() {
return issueDbTester;
}
public RuleDbTester rules() {
return ruleDbTester;
}
public NewCodePeriodDbTester newCodePeriods() {
return newCodePeriodTester;
}
public NotificationDbTester notifications() {
return notificationDbTester;
}
public QualityProfileDbTester qualityProfiles() {
return qualityProfileDbTester;
}
public MeasureDbTester measures() {
return measureDbTester;
}
public FileSourceTester fileSources() {
return fileSourceTester;
}
public PluginDbTester pluginDbTester() {
return pluginDbTester;
}
public WebhookDbTester webhooks() {
return webhookDbTester;
}
public WebhookDeliveryDbTester webhookDelivery() {
return webhookDeliveryDbTester;
}
public InternalComponentPropertyDbTester internalComponentProperties() {
return internalComponentPropertyTester;
}
public AlmSettingsDbTester almSettings() {
return almSettingsDbTester;
}
public AlmPatsDbTester almPats() {
return almPatsDbtester;
}
public AuditDbTester audits() {
return auditDbTester;
}
@Override
protected void after() {
if (session != null) {
session.rollback();
session.close();
}
db.stop();
}
public DbSession getSession() {
if (session == null) {
session = db.getMyBatis().openSession(false);
}
return session;
}
public void commit() {
getSession().commit();
}
public DbClient getDbClient() {
return client;
}
public int countRowsOfTable(DbSession dbSession, String tableName) {
return super.countRowsOfTable(tableName, new DbSessionConnectionSupplier(dbSession));
}
public int countSql(DbSession dbSession, String sql) {
return super.countSql(sql, new DbSessionConnectionSupplier(dbSession));
}
public List<Map<String, Object>> select(DbSession dbSession, String selectSql) {
return super.select(selectSql, new DbSessionConnectionSupplier(dbSession));
}
public Map<String, Object> selectFirst(DbSession dbSession, String selectSql) {
return super.selectFirst(selectSql, new DbSessionConnectionSupplier(dbSession));
}
public String getUrl() {
return ((HikariDataSource) db.getDatabase().getDataSource()).getJdbcUrl();
}
private static class DbSessionConnectionSupplier implements ConnectionSupplier {
private final DbSession dbSession;
public DbSessionConnectionSupplier(DbSession dbSession) {
this.dbSession = dbSession;
}
@Override
public Connection get() {
return dbSession.getConnection();
}
@Override
public void close() {
// closing dbSession is not our responsibility
}
}
private static class DbTesterMyBatisConfExtension implements MyBatisConfExtension {
// do not replace with a lambda to allow cache of MyBatis instances in TestDbImpl to work
private final Class<?>[] mapperClasses;
public DbTesterMyBatisConfExtension(Class<?> firstMapperClass, Class<?>... otherMapperClasses) {
this.mapperClasses = Stream.concat(
Stream.of(firstMapperClass),
Arrays.stream(otherMapperClasses))
.sorted(Comparator.comparing(Class::getName))
.toArray(Class<?>[]::new);
}
@Override
public Stream<Class<?>> getMapperClasses() {
return Arrays.stream(mapperClasses);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DbTesterMyBatisConfExtension that = (DbTesterMyBatisConfExtension) o;
return Arrays.equals(mapperClasses, that.mapperClasses);
}
@Override
public int hashCode() {
return Arrays.hashCode(mapperClasses);
}
}
}
| 11,304 | 31.579251 | 137 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/FastSpringContainer.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import org.sonar.core.platform.Container;
import org.sonar.core.platform.StartableBeanPostProcessor;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory;
import org.springframework.context.support.GenericApplicationContext;
/**
* A fast(er) Spring container. It doesn't support several things that are supported in
* {@link org.sonar.core.platform.SpringComponentContainer}, such as:
* <ul>
* <li>Adding extensions</li>
* <li>Use of annotations</li>
* <li>Adding duplicate components from different Classloaders</li>
* <li>Hierarchy of container</li>
* <li>Different initialization strategies</li>
* </ul>
*/
public class FastSpringContainer implements Container {
private final GenericApplicationContext context = new GenericApplicationContext();
public FastSpringContainer() {
((AbstractAutowireCapableBeanFactory) context.getBeanFactory()).setParameterNameDiscoverer(null);
add(StartableBeanPostProcessor.class);
}
@Override
public Container add(Object... objects) {
for (Object o : objects) {
if (o instanceof Class) {
Class<?> clazz = (Class<?>) o;
context.registerBean(clazz.getName(), clazz);
} else {
registerInstance(o);
}
}
return this;
}
public void start() {
context.refresh();
}
private <T> void registerInstance(T instance) {
Supplier<T> supplier = () -> instance;
Class<T> clazz = (Class<T>) instance.getClass();
context.registerBean(clazz.getName(), clazz, supplier);
}
@Override
public <T> T getComponentByType(Class<T> type) {
try {
return context.getBean(type);
} catch (Exception t) {
throw new IllegalStateException("Unable to load component " + type, t);
}
}
@Override public <T> Optional<T> getOptionalComponentByType(Class<T> type) {
try {
return Optional.of(context.getBean(type));
} catch (NoSuchBeanDefinitionException t) {
return Optional.empty();
}
}
@Override
public <T> List<T> getComponentsByType(Class<T> type) {
try {
return new ArrayList<>(context.getBeansOfType(type).values());
} catch (Exception t) {
throw new IllegalStateException("Unable to load components " + type, t);
}
}
@Override
public Container getParent() {
return null;
}
}
| 3,383 | 31.228571 | 101 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/OrchestratorSettingsUtils.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.text.StrSubstitutor;
import org.sonar.api.config.internal.Settings;
import static org.apache.commons.lang.StringUtils.isEmpty;
public class OrchestratorSettingsUtils {
private OrchestratorSettingsUtils() {
// prevents instantiation
}
public static void loadOrchestratorSettings(Settings settings) {
String url = settings.getString("orchestrator.configUrl");
if (isEmpty(url)) {
return;
}
InputStream input = null;
try {
URI uri = new URI(url);
if (url.startsWith("file:")) {
File file = new File(uri);
input = FileUtils.openInputStream(file);
} else {
HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
int responseCode = connection.getResponseCode();
if (responseCode >= 400) {
throw new IllegalStateException("Fail to request: " + uri + ". Status code=" + responseCode);
}
input = connection.getInputStream();
}
Properties props = new Properties();
props.load(input);
settings.addProperties(props);
for (Map.Entry<String, String> entry : settings.getProperties().entrySet()) {
String interpolatedValue = StrSubstitutor.replace(entry.getValue(), System.getenv(), "${", "}");
settings.setProperty(entry.getKey(), interpolatedValue);
}
} catch (Exception e) {
throw new IllegalStateException("Cannot load Orchestrator properties from:" + url, e);
} finally {
IOUtils.closeQuietly(input);
}
}
}
| 2,659 | 33.545455 | 104 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/SQDatabase.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
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.api.config.internal.MapSettings;
import org.sonar.api.config.internal.Settings;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.Version;
import org.slf4j.LoggerFactory;
import org.sonar.core.platform.Container;
import org.sonar.core.platform.SonarQubeVersion;
import org.sonar.core.platform.SpringComponentContainer;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.core.util.logs.Profiler;
import org.sonar.db.dialect.Dialect;
import org.sonar.process.logging.LogbackHelper;
import org.sonar.server.platform.db.migration.MigrationConfigurationModule;
import org.sonar.server.platform.db.migration.engine.MigrationContainer;
import org.sonar.server.platform.db.migration.engine.MigrationContainerImpl;
import org.sonar.server.platform.db.migration.history.MigrationHistoryTableImpl;
import org.sonar.server.platform.db.migration.step.MigrationStep;
import org.sonar.server.platform.db.migration.step.MigrationStepExecutionException;
import org.sonar.server.platform.db.migration.step.MigrationSteps;
import org.sonar.server.platform.db.migration.step.MigrationStepsExecutor;
import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep;
import static com.google.common.base.Preconditions.checkState;
public class SQDatabase extends DefaultDatabase {
private static final String IGNORED_KEYWORDS_OPTION = ";NON_KEYWORDS=VALUE";
private final boolean createSchema;
private SQDatabase(Settings settings, boolean createSchema) {
super(new LogbackHelper(), settings);
this.createSchema = createSchema;
}
public static SQDatabase newDatabase(Settings settings, boolean createSchema) {
return new SQDatabase(settings, createSchema);
}
public static SQDatabase newH2Database(String name, boolean createSchema) {
MapSettings settings = new MapSettings()
.setProperty("sonar.jdbc.dialect", "h2")
.setProperty("sonar.jdbc.driverClassName", "org.h2.Driver")
.setProperty("sonar.jdbc.url", "jdbc:h2:mem:" + name + IGNORED_KEYWORDS_OPTION)
.setProperty("sonar.jdbc.username", "sonar")
.setProperty("sonar.jdbc.password", "sonar");
return new SQDatabase(settings, createSchema);
}
@Override
public void start() {
super.start();
if (createSchema) {
createSchema();
}
}
private void createSchema() {
Connection connection = null;
try {
connection = getDataSource().getConnection();
NoopDatabase noopDatabase = new NoopDatabase(getDialect(), getDataSource());
// create and populate schema
createMigrationHistoryTable(noopDatabase);
executeDbMigrations(noopDatabase);
} catch (SQLException e) {
throw new IllegalStateException("Fail to create schema", e);
} finally {
DatabaseUtils.closeQuietly(connection);
}
}
public static final class H2StepExecutor implements MigrationStepsExecutor {
private static final String STEP_START_PATTERN = "{}...";
private static final String STEP_STOP_PATTERN = "{}: {}";
private final Container container;
public H2StepExecutor(Container container) {
this.container = container;
}
@Override
public void execute(List<RegisteredMigrationStep> steps) {
steps.forEach(step -> execute(step, container));
}
private void execute(RegisteredMigrationStep step, Container container) {
MigrationStep migrationStep = container.getComponentByType(step.getStepClass());
checkState(migrationStep != null, "Can not find instance of " + step.getStepClass());
execute(step, migrationStep);
}
private void execute(RegisteredMigrationStep step, MigrationStep migrationStep) {
Profiler stepProfiler = Profiler.create(LoggerFactory.getLogger(SQDatabase.class));
stepProfiler.startInfo(STEP_START_PATTERN, step);
boolean done = false;
try {
migrationStep.execute();
done = true;
} catch (Exception e) {
throw new MigrationStepExecutionException(step, e);
} finally {
if (done) {
stepProfiler.stopInfo(STEP_STOP_PATTERN, step, "success");
} else {
stepProfiler.stopError(STEP_STOP_PATTERN, step, "failure");
}
}
}
}
private void executeDbMigrations(NoopDatabase noopDatabase) {
SpringComponentContainer container = new SpringComponentContainer();
container.add(noopDatabase);
MigrationConfigurationModule migrationConfigurationModule = new MigrationConfigurationModule();
migrationConfigurationModule.configure(container);
// dependencies required by DB migrations
container.add(new SonarQubeVersion(Version.create(8, 0)));
container.add(UuidFactoryFast.getInstance());
container.add(System2.INSTANCE);
container.add(MapSettings.class);
container.startComponents();
MigrationContainer migrationContainer = new MigrationContainerImpl(container, H2StepExecutor.class);
MigrationSteps migrationSteps = migrationContainer.getComponentByType(MigrationSteps.class);
MigrationStepsExecutor executor = migrationContainer.getComponentByType(MigrationStepsExecutor.class);
executor.execute(migrationSteps.readAll());
}
private void createMigrationHistoryTable(NoopDatabase noopDatabase) {
new MigrationHistoryTableImpl(noopDatabase).start();
}
private static class NoopDatabase implements Database {
private final Dialect dialect;
private final DataSource dataSource;
private NoopDatabase(Dialect dialect, DataSource dataSource) {
this.dialect = dialect;
this.dataSource = dataSource;
}
@Override
public DataSource getDataSource() {
return dataSource;
}
@Override
public Dialect getDialect() {
return dialect;
}
@Override
public void enableSqlLogging(boolean enable) {
}
@Override
public void start() {
// do nothing
}
@Override
public void stop() {
// do nothing
}
}
public void executeScript(String classloaderPath) {
try (Connection connection = getDataSource().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;
}
}
| 8,059 | 34.506608 | 106 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/TestDBSessions.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 final class TestDBSessions implements DBSessions {
private final MyBatis myBatis;
public TestDBSessions(MyBatis myBatis) {
this.myBatis = myBatis;
}
@Override
public DbSession openSession(boolean batch) {
return myBatis.openSession(false);
}
@Override
public void enableCaching() {
// ignored
}
@Override
public void disableCaching() {
// ignored
}
}
| 1,268 | 27.840909 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/TestDbImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.AssumptionViolatedException;
import org.sonar.api.config.internal.Settings;
import org.sonar.db.dialect.H2;
import org.sonar.process.logging.LogbackHelper;
class TestDbImpl extends CoreTestDb {
private static TestDbImpl defaultSchemaBaseTestDb;
// instantiating MyBatis objects is costly => we cache them for default schema
private static final Map<Set<String>, TestDbImpl> defaultSchemaTestDbsWithExtensions = new HashMap<>();
private boolean isDefault;
private MyBatis myBatis;
private TestDbImpl(@Nullable String schemaPath, MyBatisConfExtension... confExtensions) {
super();
isDefault = (schemaPath == null);
init(schemaPath, confExtensions);
}
private TestDbImpl(TestDbImpl base, MyBatis myBatis) {
super(base.getDatabase());
this.isDefault = base.isDefault;
this.myBatis = myBatis;
}
private void init(@Nullable String schemaPath, MyBatisConfExtension[] confExtensions) {
Consumer<Settings> loadOrchestratorSettings = OrchestratorSettingsUtils::loadOrchestratorSettings;
Function<Settings, Database> databaseCreator = settings -> {
String dialect = settings.getString("sonar.jdbc.dialect");
if (dialect != null && !"h2".equals(dialect)) {
return new DefaultDatabase(new LogbackHelper(), settings);
}
return SQDatabase.newH2Database("h2Tests" + DigestUtils.md5Hex(StringUtils.defaultString(schemaPath)), schemaPath == null);
};
Consumer<Database> schemaPathExecutor = database -> {
if (schemaPath == null) {
return;
}
// scripts are assumed to be using H2 specific syntax, ignore the test if not on H2
if (!database.getDialect().getId().equals("h2")) {
database.stop();
throw new AssumptionViolatedException("This test is intended to be run on H2 only");
}
((SQDatabase) database).executeScript(schemaPath);
};
BiConsumer<Database, Boolean> createMyBatis = (db, created) -> myBatis = newMyBatis(db, confExtensions);
init(loadOrchestratorSettings, databaseCreator, schemaPathExecutor, createMyBatis);
}
private static MyBatis newMyBatis(Database db, MyBatisConfExtension[] extensions) {
MyBatis newMyBatis = new MyBatis(db, extensions);
newMyBatis.start();
return newMyBatis;
}
static TestDbImpl create(@Nullable String schemaPath, MyBatisConfExtension... confExtensions) {
if (schemaPath == null) {
if (defaultSchemaBaseTestDb == null) {
defaultSchemaBaseTestDb = new TestDbImpl(null);
}
if (confExtensions.length > 0) {
Set<String> key = Arrays.stream(confExtensions)
.flatMap(MyBatisConfExtension::getMapperClasses)
.map(Class::getName)
.collect(Collectors.toSet());
return defaultSchemaTestDbsWithExtensions.computeIfAbsent(
key,
k -> new TestDbImpl(defaultSchemaBaseTestDb, newMyBatis(defaultSchemaBaseTestDb.getDatabase(), confExtensions)));
}
return defaultSchemaBaseTestDb;
}
return new TestDbImpl(schemaPath, confExtensions);
}
@Override
public void start() {
if (!isDefault && !H2.ID.equals(getDatabase().getDialect().getId())) {
throw new AssumptionViolatedException("Test disabled because it supports only H2");
}
}
@Override
public void stop() {
if (!isDefault) {
super.stop();
}
}
MyBatis getMyBatis() {
return myBatis;
}
}
| 4,657 | 35.968254 | 129 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/alm/integration/pat/AlmPatsDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.integration.pat;
import java.util.function.Consumer;
import org.sonar.db.DbTester;
import org.sonar.db.alm.pat.AlmPatDto;
import static java.util.Arrays.stream;
import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto;
public class AlmPatsDbTester {
private final DbTester db;
public AlmPatsDbTester(DbTester db) {
this.db = db;
}
@SafeVarargs
public final AlmPatDto insert(Consumer<AlmPatDto>... populators) {
return insert(newAlmPatDto(), populators);
}
private AlmPatDto insert(AlmPatDto dto, Consumer<AlmPatDto>[] populators) {
stream(populators).forEach(p -> p.accept(dto));
db.getDbClient().almPatDao().insert(db.getSession(), dto, null, null);
db.commit();
return dto;
}
}
| 1,614 | 31.3 | 77 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/alm/integration/pat/AlmPatsTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.integration.pat;
import org.sonar.db.alm.pat.AlmPatDto;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
public class AlmPatsTesting {
public static AlmPatDto newAlmPatDto() {
AlmPatDto almPatDto = new AlmPatDto();
almPatDto.setAlmSettingUuid(randomAlphanumeric(40));
almPatDto.setPersonalAccessToken(randomAlphanumeric(2000));
almPatDto.setUserUuid(randomAlphanumeric(40));
return almPatDto;
}
}
| 1,321 | 34.72973 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/almsettings/AlmSettingsDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.almsettings;
import java.util.function.Consumer;
import org.sonar.db.DbTester;
import org.sonar.db.alm.setting.AlmSettingDto;
import org.sonar.db.alm.setting.ProjectAlmSettingDto;
import org.sonar.db.project.ProjectDto;
import static java.util.Arrays.stream;
import static org.sonar.db.almsettings.AlmSettingsTesting.newAzureAlmSettingDto;
import static org.sonar.db.almsettings.AlmSettingsTesting.newAzureProjectAlmSettingDto;
import static org.sonar.db.almsettings.AlmSettingsTesting.newBitbucketAlmSettingDto;
import static org.sonar.db.almsettings.AlmSettingsTesting.newBitbucketCloudAlmSettingDto;
import static org.sonar.db.almsettings.AlmSettingsTesting.newBitbucketCloudProjectAlmSettingDto;
import static org.sonar.db.almsettings.AlmSettingsTesting.newBitbucketProjectAlmSettingDto;
import static org.sonar.db.almsettings.AlmSettingsTesting.newGithubAlmSettingDto;
import static org.sonar.db.almsettings.AlmSettingsTesting.newGithubProjectAlmSettingDto;
import static org.sonar.db.almsettings.AlmSettingsTesting.newGitlabAlmSettingDto;
import static org.sonar.db.almsettings.AlmSettingsTesting.newGitlabProjectAlmSettingDto;
public class AlmSettingsDbTester {
private final DbTester db;
public AlmSettingsDbTester(DbTester db) {
this.db = db;
}
@SafeVarargs
public final AlmSettingDto insertGitHubAlmSetting(Consumer<AlmSettingDto>... populators) {
return insert(newGithubAlmSettingDto(), populators);
}
@SafeVarargs
public final AlmSettingDto insertAzureAlmSetting(Consumer<AlmSettingDto>... populators) {
return insert(newAzureAlmSettingDto(), populators);
}
@SafeVarargs
public final AlmSettingDto insertGitlabAlmSetting(Consumer<AlmSettingDto>... populators) {
return insert(newGitlabAlmSettingDto(), populators);
}
@SafeVarargs
public final AlmSettingDto insertBitbucketAlmSetting(Consumer<AlmSettingDto>... populators) {
return insert(newBitbucketAlmSettingDto(), populators);
}
@SafeVarargs
public final AlmSettingDto insertBitbucketCloudAlmSetting(Consumer<AlmSettingDto>... populators) {
return insert(newBitbucketCloudAlmSettingDto(), populators);
}
@SafeVarargs
public final ProjectAlmSettingDto insertGitHubProjectAlmSetting(AlmSettingDto githubAlmSetting, ProjectDto project,
Consumer<ProjectAlmSettingDto>... populators) {
return insertProjectAlmSetting(newGithubProjectAlmSettingDto(githubAlmSetting, project), githubAlmSetting.getKey(),
project.getName(), project.getKey(), populators);
}
public ProjectAlmSettingDto insertAzureProjectAlmSetting(AlmSettingDto azureAlmSetting, ProjectDto project) {
return insertProjectAlmSetting(newAzureProjectAlmSettingDto(azureAlmSetting, project), azureAlmSetting.getKey(),
project.getName(), project.getKey());
}
public ProjectAlmSettingDto insertAzureMonoRepoProjectAlmSetting(AlmSettingDto azureAlmSetting, ProjectDto project) {
return insertProjectAlmSetting(newAzureProjectAlmSettingDto(azureAlmSetting, project), azureAlmSetting.getKey(),
project.getName(), project.getKey(), d -> d.setMonorepo(true));
}
public ProjectAlmSettingDto insertGitlabProjectAlmSetting(AlmSettingDto gitlabAlmSetting, ProjectDto project) {
return insertProjectAlmSetting(newGitlabProjectAlmSettingDto(gitlabAlmSetting, project), gitlabAlmSetting.getKey(),
project.getName(), project.getKey());
}
@SafeVarargs
public final ProjectAlmSettingDto insertAzureProjectAlmSetting(AlmSettingDto azureAlmSetting, ProjectDto project,
Consumer<ProjectAlmSettingDto>... populators) {
return insertProjectAlmSetting(newAzureProjectAlmSettingDto(azureAlmSetting, project), azureAlmSetting.getKey(),
project.getName(), project.getKey(), populators);
}
@SafeVarargs
public final ProjectAlmSettingDto insertGitlabProjectAlmSetting(AlmSettingDto gitlabAlmSetting, ProjectDto project,
Consumer<ProjectAlmSettingDto>... populators) {
return insertProjectAlmSetting(newGitlabProjectAlmSettingDto(gitlabAlmSetting, project), gitlabAlmSetting.getKey(),
project.getName(), project.getKey(), populators);
}
@SafeVarargs
public final ProjectAlmSettingDto insertBitbucketCloudProjectAlmSetting(AlmSettingDto bbCloudAlmSetting, ProjectDto project,
Consumer<ProjectAlmSettingDto>... populators) {
return insertProjectAlmSetting(newBitbucketCloudProjectAlmSettingDto(bbCloudAlmSetting, project), bbCloudAlmSetting.getKey(),
project.getName(), project.getKey(), populators);
}
@SafeVarargs
public final ProjectAlmSettingDto insertBitbucketProjectAlmSetting(AlmSettingDto bitbucketAlmSetting,
ProjectDto project, Consumer<ProjectAlmSettingDto>... populators) {
return insertProjectAlmSetting(newBitbucketProjectAlmSettingDto(bitbucketAlmSetting, project),
bitbucketAlmSetting.getKey(), project.getName(), project.getKey(), populators);
}
@SafeVarargs
private final ProjectAlmSettingDto insertProjectAlmSetting(ProjectAlmSettingDto dto, String key, String projectName,
String projectKey, Consumer<ProjectAlmSettingDto>... populators) {
stream(populators).forEach(p -> p.accept(dto));
db.getDbClient().projectAlmSettingDao().insertOrUpdate(db.getSession(), dto, key, projectName, projectKey);
db.commit();
return dto;
}
private AlmSettingDto insert(AlmSettingDto dto, Consumer<AlmSettingDto>[] populators) {
stream(populators).forEach(p -> p.accept(dto));
db.getDbClient().almSettingDao().insert(db.getSession(), dto);
db.commit();
return dto;
}
}
| 6,394 | 44.678571 | 129 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/almsettings/AlmSettingsTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.almsettings;
import org.sonar.db.alm.setting.ALM;
import org.sonar.db.alm.setting.AlmSettingDto;
import org.sonar.db.alm.setting.ProjectAlmSettingDto;
import org.sonar.db.project.ProjectDto;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.RandomStringUtils.randomNumeric;
public class AlmSettingsTesting {
private AlmSettingsTesting() {
}
public static AlmSettingDto newGithubAlmSettingDto() {
return new AlmSettingDto()
.setKey(randomAlphanumeric(200))
.setUrl(randomAlphanumeric(2000))
.setAppId(randomNumeric(8))
.setClientId(randomNumeric(8))
.setClientSecret(randomAlphanumeric(80))
.setPrivateKey(randomAlphanumeric(2000))
.setAlm(ALM.GITHUB);
}
public static AlmSettingDto newAzureAlmSettingDto() {
return new AlmSettingDto()
.setKey(randomAlphanumeric(200))
.setPersonalAccessToken(randomAlphanumeric(2000))
.setUrl(randomAlphanumeric(2000))
.setAlm(ALM.AZURE_DEVOPS);
}
public static AlmSettingDto newGitlabAlmSettingDto() {
return new AlmSettingDto()
.setKey(randomAlphanumeric(200))
.setPersonalAccessToken(randomAlphanumeric(2000))
.setUrl(randomAlphanumeric(2000))
.setAlm(ALM.GITLAB);
}
public static AlmSettingDto newBitbucketAlmSettingDto() {
return new AlmSettingDto()
.setKey(randomAlphanumeric(200))
.setUrl(randomAlphanumeric(2000))
.setPersonalAccessToken(randomAlphanumeric(2000))
.setAlm(ALM.BITBUCKET);
}
public static AlmSettingDto newBitbucketCloudAlmSettingDto() {
return new AlmSettingDto()
.setKey(randomAlphanumeric(200))
.setClientId(randomAlphanumeric(50))
.setAppId(randomAlphanumeric(80))
.setClientSecret(randomAlphanumeric(50))
.setAlm(ALM.BITBUCKET_CLOUD);
}
public static ProjectAlmSettingDto newGithubProjectAlmSettingDto(AlmSettingDto githubAlmSetting, ProjectDto project) {
return new ProjectAlmSettingDto()
.setAlmSettingUuid(githubAlmSetting.getUuid())
.setProjectUuid(project.getUuid())
.setAlmRepo(randomAlphanumeric(256))
.setSummaryCommentEnabled(true)
.setMonorepo(false);
}
public static ProjectAlmSettingDto newGitlabProjectAlmSettingDto(AlmSettingDto gitlabAlmSetting, ProjectDto project) {
return new ProjectAlmSettingDto()
.setAlmSettingUuid(gitlabAlmSetting.getUuid())
.setProjectUuid(project.getUuid())
.setMonorepo(false);
}
static ProjectAlmSettingDto newAzureProjectAlmSettingDto(AlmSettingDto azureAlmSetting, ProjectDto project) {
return new ProjectAlmSettingDto()
.setAlmSettingUuid(azureAlmSetting.getUuid())
.setProjectUuid(project.getUuid())
.setAlmSlug(randomAlphanumeric(256))
.setAlmRepo(randomAlphanumeric(256))
.setMonorepo(false);
}
public static ProjectAlmSettingDto newBitbucketProjectAlmSettingDto(AlmSettingDto bitbucketAlmSetting, ProjectDto project) {
return new ProjectAlmSettingDto()
.setAlmSettingUuid(bitbucketAlmSetting.getUuid())
.setProjectUuid(project.getUuid())
.setAlmRepo(randomAlphanumeric(256))
.setAlmSlug(randomAlphanumeric(256))
.setMonorepo(false);
}
public static ProjectAlmSettingDto newBitbucketCloudProjectAlmSettingDto(AlmSettingDto bitbucketCloudAlmSetting, ProjectDto project) {
return new ProjectAlmSettingDto()
.setAlmSettingUuid(bitbucketCloudAlmSetting.getUuid())
.setProjectUuid(project.getUuid())
.setAlmRepo(randomAlphanumeric(256))
.setMonorepo(false);
}
}
| 4,470 | 35.647541 | 136 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/audit/AuditDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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 org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
public class AuditDbTester {
private final DbTester db;
private final DbClient dbClient;
private final DbSession dbSession;
public AuditDbTester(DbTester db) {
this.db = db;
this.dbClient = db.getDbClient();
this.dbSession = db.getSession();
}
public final void insertRandomAuditEntry(long createdAt) {
AuditDto auditDto = AuditTesting.newAuditDto(createdAt);
dbClient.auditDao().insert(dbSession, auditDto);
db.commit();
}
}
| 1,431 | 31.545455 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/audit/AuditTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.Random;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
public class AuditTesting {
private static final Random random = new Random();
private AuditTesting() {
throw new IllegalStateException("Utility class");
}
public static AuditDto newAuditDto() {
return newAuditDto(random.nextLong(), "operation");
}
public static AuditDto newAuditDto(String operation) {
return newAuditDto(random.nextLong(), operation);
}
public static AuditDto newAuditDto(long createdAt) {
return newAuditDto(createdAt, "operation");
}
public static AuditDto newAuditDto(long createdAt, String operation) {
AuditDto auditDto = new AuditDto();
auditDto.setUuid(randomAlphanumeric(40));
auditDto.setUserUuid(randomAlphanumeric(255));
auditDto.setUserLogin(randomAlphanumeric(255));
auditDto.setNewValue("{ \"someKey\": \"someValue\", \"anotherKey\": \"\\\"anotherValue\\\" with quotes \\ \n\t\b\f\r\"}");
auditDto.setOperation(operation);
auditDto.setCategory("category");
auditDto.setCreatedAt(createdAt);
return auditDto;
}
}
| 2,001 | 33.517241 | 127 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.