@Override | @Override | ||||
public void execute(SensorContext context) { | public void execute(SensorContext context) { | ||||
Checks<Check> checks = checkFactory.create(XooRulesDefinition.XOO_REPOSITORY); | Checks<Check> checks = checkFactory.create(XooRulesDefinition.XOO_REPOSITORY); | ||||
checks.addAnnotatedChecks((Object[]) Check.ALL); | |||||
checks.addAnnotatedChecks(Check.ALL); | |||||
FilePredicates p = context.fileSystem().predicates(); | FilePredicates p = context.fileSystem().predicates(); | ||||
for (InputFile file : context.fileSystem().inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(Type.MAIN)))) { | for (InputFile file : context.fileSystem().inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(Type.MAIN)))) { | ||||
for (Check check : checks.all()) { | for (Check check : checks.all()) { |
import com.google.common.collect.HashBasedTable; | import com.google.common.collect.HashBasedTable; | ||||
import com.google.common.collect.Lists; | import com.google.common.collect.Lists; | ||||
import com.google.common.collect.Maps; | |||||
import com.google.common.collect.Table; | import com.google.common.collect.Table; | ||||
import java.io.IOException; | import java.io.IOException; | ||||
import java.nio.file.Files; | import java.nio.file.Files; | ||||
import java.util.Collections; | import java.util.Collections; | ||||
import java.util.HashMap; | |||||
import java.util.List; | import java.util.List; | ||||
import java.util.Map; | import java.util.Map; | ||||
import java.util.regex.Matcher; | import java.util.regex.Matcher; | ||||
} | } | ||||
private static void createIssues(InputFile file, SensorContext context) { | private static void createIssues(InputFile file, SensorContext context) { | ||||
Map<Integer, TextPointer> startIssuesPositions = Maps.newHashMap(); | |||||
Map<Integer, TextPointer> endIssuesPositions = Maps.newHashMap(); | |||||
Map<Integer, Table<Integer, Integer, TextPointer>> startFlowsPositions = Maps.newHashMap(); | |||||
Map<Integer, Table<Integer, Integer, TextPointer>> endFlowsPositions = Maps.newHashMap(); | |||||
Map<Integer, TextPointer> startIssuesPositions = new HashMap<>(); | |||||
Map<Integer, TextPointer> endIssuesPositions = new HashMap<>(); | |||||
Map<Integer, Table<Integer, Integer, TextPointer>> startFlowsPositions = new HashMap<>(); | |||||
Map<Integer, Table<Integer, Integer, TextPointer>> endFlowsPositions = new HashMap<>(); | |||||
parseIssues(file, context, startIssuesPositions, endIssuesPositions); | parseIssues(file, context, startIssuesPositions, endIssuesPositions); | ||||
parseFlows(file, startFlowsPositions, endFlowsPositions); | parseFlows(file, startFlowsPositions, endFlowsPositions); |
public TemporaryFolder temp = new TemporaryFolder(); | public TemporaryFolder temp = new TemporaryFolder(); | ||||
private AnalysisErrorSensor sensor; | private AnalysisErrorSensor sensor; | ||||
private SensorContextTester context; | |||||
@Before | @Before | ||||
public void setUp() { | public void setUp() { | ||||
.setModuleBaseDir(baseDir) | .setModuleBaseDir(baseDir) | ||||
.setLines(4) | .setLines(4) | ||||
.build(); | .build(); | ||||
context = SensorContextTester.create(baseDir); | |||||
SensorContextTester context = SensorContextTester.create(baseDir); | |||||
context.fileSystem().add(inputFile); | context.fileSystem().add(inputFile); | ||||
sensor.execute(context); | sensor.execute(context); |
.category(CATEGORY) | .category(CATEGORY) | ||||
.subCategory(SUBCATEGORY) | .subCategory(SUBCATEGORY) | ||||
.type(STRING) | .type(STRING) | ||||
.defaultValue(valueOf("https://api.github.com/")) | |||||
.defaultValue("https://api.github.com/") | |||||
.index(7) | .index(7) | ||||
.build(), | .build(), | ||||
PropertyDefinition.builder(WEB_URL) | PropertyDefinition.builder(WEB_URL) | ||||
.category(CATEGORY) | .category(CATEGORY) | ||||
.subCategory(SUBCATEGORY) | .subCategory(SUBCATEGORY) | ||||
.type(STRING) | .type(STRING) | ||||
.defaultValue(valueOf("https://github.com/")) | |||||
.defaultValue("https://github.com/") | |||||
.index(8) | .index(8) | ||||
.build(), | .build(), | ||||
PropertyDefinition.builder(ORGANIZATIONS) | PropertyDefinition.builder(ORGANIZATIONS) |
static { | static { | ||||
String loginModule = "com.sun.security.auth.module.Krb5LoginModule"; | String loginModule = "com.sun.security.auth.module.Krb5LoginModule"; | ||||
AppConfigurationEntry.LoginModuleControlFlag flag = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED; | AppConfigurationEntry.LoginModuleControlFlag flag = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED; | ||||
CONFIG_LIST[0] = new AppConfigurationEntry(loginModule, flag, new HashMap<String, Object>()); | |||||
CONFIG_LIST[0] = new AppConfigurationEntry(loginModule, flag, new HashMap<>()); | |||||
} | } | ||||
/** | /** |
Attribute attribute = mock(Attribute.class); | Attribute attribute = mock(Attribute.class); | ||||
NamingEnumeration namingEnumeration = mock(NamingEnumeration.class); | NamingEnumeration namingEnumeration = mock(NamingEnumeration.class); | ||||
when(context.getAttributes(Mockito.anyString(), Mockito.<String[]>anyObject())).thenReturn(attributes); | |||||
when(context.getAttributes(Mockito.anyString(), Mockito.anyObject())).thenReturn(attributes); | |||||
when(attributes.get(Mockito.eq("srv"))).thenReturn(attribute); | when(attributes.get(Mockito.eq("srv"))).thenReturn(attribute); | ||||
when(attribute.getAll()).thenReturn(namingEnumeration); | when(attribute.getAll()).thenReturn(namingEnumeration); | ||||
when(namingEnumeration.hasMore()).thenReturn(true, true, true, true, true, false); | when(namingEnumeration.hasMore()).thenReturn(true, true, true, true, true, false); |
public static LdapServer infosupportServer = new LdapServer(USERS_INFOSUPPORT_COM_LDIF, "infosupport.com", "dc=infosupport,dc=com"); | public static LdapServer infosupportServer = new LdapServer(USERS_INFOSUPPORT_COM_LDIF, "infosupport.com", "dc=infosupport,dc=com"); | ||||
@Test | @Test | ||||
public void defaults() throws Exception { | |||||
public void defaults() { | |||||
MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, null); | MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, null); | ||||
LdapSettingsManager settingsManager = new LdapSettingsManager(settings, new LdapAutodiscovery()); | LdapSettingsManager settingsManager = new LdapSettingsManager(settings, new LdapAutodiscovery()); |
} | } | ||||
@Test | @Test | ||||
public void testContextFactoriesWithSingleLdap() throws Exception { | |||||
public void testContextFactoriesWithSingleLdap() { | |||||
LdapSettingsManager settingsManager = new LdapSettingsManager( | LdapSettingsManager settingsManager = new LdapSettingsManager( | ||||
generateSingleLdapSettingsWithUserAndGroupMapping(), new LdapAutodiscovery()); | generateSingleLdapSettingsWithUserAndGroupMapping(), new LdapAutodiscovery()); | ||||
assertThat(settingsManager.getContextFactories().size()).isEqualTo(1); | assertThat(settingsManager.getContextFactories().size()).isEqualTo(1); | ||||
/** | /** | ||||
* Test there are 2 @link{org.sonar.plugins.ldap.LdapContextFactory}s found. | * Test there are 2 @link{org.sonar.plugins.ldap.LdapContextFactory}s found. | ||||
* | * | ||||
* @throws Exception | |||||
* This is not expected. | |||||
*/ | */ | ||||
@Test | @Test | ||||
public void testContextFactoriesWithMultipleLdap() throws Exception { | |||||
public void testContextFactoriesWithMultipleLdap() { | |||||
LdapSettingsManager settingsManager = new LdapSettingsManager( | LdapSettingsManager settingsManager = new LdapSettingsManager( | ||||
generateMultipleLdapSettingsWithUserAndGroupMapping(), new LdapAutodiscovery()); | generateMultipleLdapSettingsWithUserAndGroupMapping(), new LdapAutodiscovery()); | ||||
assertThat(settingsManager.getContextFactories().size()).isEqualTo(2); | assertThat(settingsManager.getContextFactories().size()).isEqualTo(2); | ||||
} | } | ||||
@Test | @Test | ||||
public void testAutodiscover() throws Exception { | |||||
public void testAutodiscover() { | |||||
LdapAutodiscovery ldapAutodiscovery = mock(LdapAutodiscovery.class); | LdapAutodiscovery ldapAutodiscovery = mock(LdapAutodiscovery.class); | ||||
LdapSrvRecord ldap1 = new LdapSrvRecord("ldap://localhost:189", 1, 1); | LdapSrvRecord ldap1 = new LdapSrvRecord("ldap://localhost:189", 1, 1); | ||||
LdapSrvRecord ldap2 = new LdapSrvRecord("ldap://localhost:1899", 1, 1); | LdapSrvRecord ldap2 = new LdapSrvRecord("ldap://localhost:1899", 1, 1); | ||||
} | } | ||||
@Test | @Test | ||||
public void testAutodiscoverFailed() throws Exception { | |||||
public void testAutodiscoverFailed() { | |||||
LdapAutodiscovery ldapAutodiscovery = mock(LdapAutodiscovery.class); | LdapAutodiscovery ldapAutodiscovery = mock(LdapAutodiscovery.class); | ||||
when(ldapAutodiscovery.getLdapServers("example.org")).thenReturn(Collections.<LdapSrvRecord>emptyList()); | |||||
when(ldapAutodiscovery.getLdapServers("example.org")).thenReturn(Collections.emptyList()); | |||||
LdapSettingsManager settingsManager = new LdapSettingsManager( | LdapSettingsManager settingsManager = new LdapSettingsManager( | ||||
generateAutodiscoverSettings(), ldapAutodiscovery); | generateAutodiscoverSettings(), ldapAutodiscovery); | ||||
/** | /** | ||||
* Test there are 2 @link{org.sonar.plugins.ldap.LdapUserMapping}s found. | * Test there are 2 @link{org.sonar.plugins.ldap.LdapUserMapping}s found. | ||||
* | * | ||||
* @throws Exception | |||||
* This is not expected. | |||||
*/ | */ | ||||
@Test | @Test | ||||
public void testUserMappings() throws Exception { | |||||
public void testUserMappings() { | |||||
LdapSettingsManager settingsManager = new LdapSettingsManager( | LdapSettingsManager settingsManager = new LdapSettingsManager( | ||||
generateMultipleLdapSettingsWithUserAndGroupMapping(), new LdapAutodiscovery()); | generateMultipleLdapSettingsWithUserAndGroupMapping(), new LdapAutodiscovery()); | ||||
assertThat(settingsManager.getUserMappings().size()).isEqualTo(2); | assertThat(settingsManager.getUserMappings().size()).isEqualTo(2); | ||||
/** | /** | ||||
* Test there are 2 @link{org.sonar.plugins.ldap.LdapGroupMapping}s found. | * Test there are 2 @link{org.sonar.plugins.ldap.LdapGroupMapping}s found. | ||||
* | * | ||||
* @throws Exception | |||||
* This is not expected. | |||||
*/ | */ | ||||
@Test | @Test | ||||
public void testGroupMappings() throws Exception { | |||||
public void testGroupMappings() { | |||||
LdapSettingsManager settingsManager = new LdapSettingsManager( | LdapSettingsManager settingsManager = new LdapSettingsManager( | ||||
generateMultipleLdapSettingsWithUserAndGroupMapping(), new LdapAutodiscovery()); | generateMultipleLdapSettingsWithUserAndGroupMapping(), new LdapAutodiscovery()); | ||||
assertThat(settingsManager.getGroupMappings().size()).isEqualTo(2); | assertThat(settingsManager.getGroupMappings().size()).isEqualTo(2); | ||||
/** | /** | ||||
* Test what happens when no configuration is set. | * Test what happens when no configuration is set. | ||||
* Normally there will be a contextFactory, but the autodiscovery doesn't work for the test server. | * Normally there will be a contextFactory, but the autodiscovery doesn't work for the test server. | ||||
* @throws Exception | |||||
*/ | */ | ||||
@Test | @Test | ||||
public void testEmptySettings() throws Exception { | |||||
public void testEmptySettings() { | |||||
LdapSettingsManager settingsManager = new LdapSettingsManager( | LdapSettingsManager settingsManager = new LdapSettingsManager( | ||||
new MapSettings(), new LdapAutodiscovery()); | new MapSettings(), new LdapAutodiscovery()); | ||||
public static LdapServer infosupportServer = new LdapServer(USERS_INFOSUPPORT_COM_LDIF, "infosupport.com", "dc=infosupport,dc=com"); | public static LdapServer infosupportServer = new LdapServer(USERS_INFOSUPPORT_COM_LDIF, "infosupport.com", "dc=infosupport,dc=com"); | ||||
@Test | @Test | ||||
public void test() throws Exception { | |||||
public void test() { | |||||
Settings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); | Settings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); | ||||
LdapSettingsManager settingsManager = new LdapSettingsManager(settings, new LdapAutodiscovery()); | LdapSettingsManager settingsManager = new LdapSettingsManager(settings, new LdapAutodiscovery()); | ||||
LdapUsersProvider usersProvider = new LdapUsersProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings()); | LdapUsersProvider usersProvider = new LdapUsersProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings()); |
} | } | ||||
private void closeIssuesForDeletedComponentUuids(Set<String> deletedComponentUuids) { | private void closeIssuesForDeletedComponentUuids(Set<String> deletedComponentUuids) { | ||||
DiskCache<DefaultIssue>.DiskAppender cacheAppender = issueCache.newAppender(); | |||||
try { | |||||
try (DiskCache<DefaultIssue>.DiskAppender cacheAppender = issueCache.newAppender()) { | |||||
for (String deletedComponentUuid : deletedComponentUuids) { | for (String deletedComponentUuid : deletedComponentUuids) { | ||||
List<DefaultIssue> issues = issuesLoader.loadOpenIssues(deletedComponentUuid); | List<DefaultIssue> issues = issuesLoader.loadOpenIssues(deletedComponentUuid); | ||||
for (DefaultIssue issue : issues) { | for (DefaultIssue issue : issues) { | ||||
cacheAppender.append(issue); | cacheAppender.append(issue); | ||||
} | } | ||||
} | } | ||||
} finally { | |||||
cacheAppender.close(); | |||||
} | } | ||||
} | } | ||||
} | } |
i.addComment(c.toComment()); | i.addComment(c.toComment()); | ||||
break; | break; | ||||
default: | default: | ||||
throw new IllegalStateException("Unknow change type: " + c.getChangeType()); | |||||
throw new IllegalStateException("Unknown change type: " + c.getChangeType()); | |||||
} | } | ||||
} | } | ||||
if (!periodHolder.hasPeriod() && !analysisMetadataHolder.isPullRequest()) { | if (!periodHolder.hasPeriod() && !analysisMetadataHolder.isPullRequest()) { | ||||
return; | return; | ||||
} | } | ||||
double unresolvedVariations = (double) currentCounters.counterForPeriod().unresolved; | |||||
double unresolvedVariations = currentCounters.counterForPeriod().unresolved; | |||||
measureRepository.add(component, metricRepository.getByKey(NEW_VIOLATIONS_KEY), Measure.newMeasureBuilder() | measureRepository.add(component, metricRepository.getByKey(NEW_VIOLATIONS_KEY), Measure.newMeasureBuilder() | ||||
.setVariation(unresolvedVariations) | .setVariation(unresolvedVariations) | ||||
.createNoValue()); | .createNoValue()); | ||||
Multiset<String> bag = currentCounters.counterForPeriod().severityBag; | Multiset<String> bag = currentCounters.counterForPeriod().severityBag; | ||||
Metric metric = metricRepository.getByKey(metricKey); | Metric metric = metricRepository.getByKey(metricKey); | ||||
measureRepository.add(component, metric, Measure.newMeasureBuilder() | measureRepository.add(component, metric, Measure.newMeasureBuilder() | ||||
.setVariation((double) bag.count(severity)) | |||||
.setVariation(bag.count(severity)) | |||||
.createNoValue()); | .createNoValue()); | ||||
} | } | ||||
Multiset<RuleType> bag = currentCounters.counterForPeriod().typeBag; | Multiset<RuleType> bag = currentCounters.counterForPeriod().typeBag; | ||||
Metric metric = metricRepository.getByKey(metricKey); | Metric metric = metricRepository.getByKey(metricKey); | ||||
measureRepository.add(component, metric, Measure.newMeasureBuilder() | measureRepository.add(component, metric, Measure.newMeasureBuilder() | ||||
.setVariation((double) bag.count(type)) | |||||
.setVariation(bag.count(type)) | |||||
.createNoValue()); | .createNoValue()); | ||||
} | } | ||||
} | } |
import org.sonar.core.issue.FieldDiffs; | import org.sonar.core.issue.FieldDiffs; | ||||
import org.sonar.core.issue.IssueChangeContext; | import org.sonar.core.issue.IssueChangeContext; | ||||
import org.sonar.core.util.Uuids; | import org.sonar.core.util.Uuids; | ||||
import org.sonar.db.component.KeyType; | |||||
import org.sonar.server.issue.IssueFieldsSetter; | import org.sonar.server.issue.IssueFieldsSetter; | ||||
import org.sonar.server.issue.workflow.IssueWorkflow; | import org.sonar.server.issue.workflow.IssueWorkflow; | ||||
} | } | ||||
return of(setCommonProperties(Measure.newMeasureBuilder(), measureDto) | return of(setCommonProperties(Measure.newMeasureBuilder(), measureDto) | ||||
.create(value.doubleValue(), org.sonar.api.measures.Metric.MAX_DECIMAL_SCALE, data)); | |||||
.create(value, org.sonar.api.measures.Metric.MAX_DECIMAL_SCALE, data)); | |||||
} | } | ||||
private static Optional<Measure> toBooleanMeasure(LiveMeasureDto measureDto, @Nullable Double value, @Nullable String data) { | private static Optional<Measure> toBooleanMeasure(LiveMeasureDto measureDto, @Nullable Double value, @Nullable String data) { |
} | } | ||||
public Measure create(int value, @Nullable String data) { | public Measure create(int value, @Nullable String data) { | ||||
return createInternal(ValueType.INT, (double) value, data); | |||||
return createInternal(ValueType.INT, value, data); | |||||
} | } | ||||
public Measure create(int value) { | public Measure create(int value) { |
} | } | ||||
return of(setCommonProperties(Measure.newMeasureBuilder(), measureDto) | return of(setCommonProperties(Measure.newMeasureBuilder(), measureDto) | ||||
.create(value.doubleValue(), org.sonar.api.measures.Metric.MAX_DECIMAL_SCALE, data)); | |||||
.create(value, org.sonar.api.measures.Metric.MAX_DECIMAL_SCALE, data)); | |||||
} | } | ||||
private static Optional<Measure> toBooleanMeasure(MeasureDto measureDto, @Nullable Double value, String data) { | private static Optional<Measure> toBooleanMeasure(MeasureDto measureDto, @Nullable Double value, String data) { |
@Override | @Override | ||||
public void start() { | public void start() { | ||||
DbSession dbSession = dbClient.openSession(false); | |||||
try { | |||||
try (DbSession dbSession = dbClient.openSession(false)) { | |||||
List<MetricDto> metricList = dbClient.metricDao().selectEnabled(dbSession); | List<MetricDto> metricList = dbClient.metricDao().selectEnabled(dbSession); | ||||
this.metricsByKey = from(metricList).transform(MetricDtoToMetric.INSTANCE).uniqueIndex(MetricToKey.INSTANCE); | this.metricsByKey = from(metricList).transform(MetricDtoToMetric.INSTANCE).uniqueIndex(MetricToKey.INSTANCE); | ||||
this.metricsById = from(metricList).transform(MetricDtoToMetric.INSTANCE).uniqueIndex(MetricToId.INSTANCE); | this.metricsById = from(metricList).transform(MetricDtoToMetric.INSTANCE).uniqueIndex(MetricToId.INSTANCE); | ||||
} finally { | |||||
dbSession.close(); | |||||
} | } | ||||
} | } | ||||
import org.sonar.server.issue.notification.EmailMessage; | import org.sonar.server.issue.notification.EmailMessage; | ||||
import org.sonar.server.issue.notification.EmailTemplate; | import org.sonar.server.issue.notification.EmailTemplate; | ||||
import static java.nio.charset.StandardCharsets.UTF_8; | |||||
import static org.sonar.api.utils.DateUtils.formatDateTime; | import static org.sonar.api.utils.DateUtils.formatDateTime; | ||||
public class ReportAnalysisFailureNotificationEmailTemplate implements EmailTemplate { | public class ReportAnalysisFailureNotificationEmailTemplate implements EmailTemplate { | ||||
private static String encode(String toEncode) { | private static String encode(String toEncode) { | ||||
try { | try { | ||||
return URLEncoder.encode(toEncode, "UTF-8"); | |||||
return URLEncoder.encode(toEncode, UTF_8.name()); | |||||
} catch (UnsupportedEncodingException e) { | } catch (UnsupportedEncodingException e) { | ||||
throw new IllegalStateException("Encoding not supported", e); | throw new IllegalStateException("Encoding not supported", e); | ||||
} | } |
new PostProjectAnalysisTask[] {postProjectAnalysisTask}); | new PostProjectAnalysisTask[] {postProjectAnalysisTask}); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
qualityGateHolder.setQualityGate(new QualityGate(QUALITY_GATE_ID, QUALITY_GATE_NAME, of(CONDITION_1, CONDITION_2))); | qualityGateHolder.setQualityGate(new QualityGate(QUALITY_GATE_ID, QUALITY_GATE_NAME, of(CONDITION_1, CONDITION_2))); | ||||
qualityGateStatusHolder.setStatus(QualityGateStatus.OK, ImmutableMap.of( | qualityGateStatusHolder.setStatus(QualityGateStatus.OK, ImmutableMap.of( | ||||
CONDITION_1, ConditionStatus.create(ConditionStatus.EvaluationStatus.OK, "value"), | CONDITION_1, ConditionStatus.create(ConditionStatus.EvaluationStatus.OK, "value"), |
package org.sonar.ce.task.projectanalysis.component; | package org.sonar.ce.task.projectanalysis.component; | ||||
import com.google.common.base.Function; | import com.google.common.base.Function; | ||||
import com.google.common.base.Predicate; | |||||
import com.google.common.collect.ImmutableSet; | import com.google.common.collect.ImmutableSet; | ||||
import com.tngtech.java.junit.dataprovider.DataProvider; | import com.tngtech.java.junit.dataprovider.DataProvider; | ||||
import com.tngtech.java.junit.dataprovider.DataProviderRunner; | import com.tngtech.java.junit.dataprovider.DataProviderRunner; | ||||
import com.tngtech.java.junit.dataprovider.UseDataProvider; | import com.tngtech.java.junit.dataprovider.UseDataProvider; | ||||
import java.util.Arrays; | import java.util.Arrays; | ||||
import java.util.Set; | import java.util.Set; | ||||
import java.util.stream.Collectors; | |||||
import javax.annotation.Nullable; | import javax.annotation.Nullable; | ||||
import org.junit.Rule; | import org.junit.Rule; | ||||
import org.junit.Test; | import org.junit.Test; | ||||
@RunWith(DataProviderRunner.class) | @RunWith(DataProviderRunner.class) | ||||
public class CrawlerDepthLimitTest { | public class CrawlerDepthLimitTest { | ||||
private static final Set<Type> REPORT_TYPES = from(asList(Type.values())).filter(new Predicate<Type>() { | |||||
@Override | |||||
public boolean apply(Type input) { | |||||
return input.isReportType(); | |||||
} | |||||
}).toSet(); | |||||
private static final Set<Type> VIEWS_TYPES = from(asList(Type.values())).filter(new Predicate<Type>() { | |||||
@Override | |||||
public boolean apply(Type input) { | |||||
return input.isViewsType(); | |||||
} | |||||
}).toSet(); | |||||
private static final Set<Type> REPORT_TYPES = Arrays.stream(Type.values()).filter(Type::isReportType).collect(Collectors.toSet()); | |||||
private static final Set<Type> VIEWS_TYPES = Arrays.stream(Type.values()).filter(Type::isViewsType).collect(Collectors.toSet()); | |||||
@Rule | @Rule | ||||
public ExpectedException expectedException = ExpectedException.none(); | public ExpectedException expectedException = ExpectedException.none(); | ||||
for (Type type : types) { | for (Type type : types) { | ||||
assertThat(depthLimit.isHigherThan(type)).as("isHigherThan(%s)", type).isTrue(); | assertThat(depthLimit.isHigherThan(type)).as("isHigherThan(%s)", type).isTrue(); | ||||
} | } | ||||
for (Type reportType : from(REPORT_TYPES).filter(not(in(Arrays.asList(types))))) { | |||||
for (Type reportType : from(REPORT_TYPES).filter(not(in(asList(types))))) { | |||||
assertThat(depthLimit.isHigherThan(reportType)).as("isHigherThan(%s)", reportType).isFalse(); | assertThat(depthLimit.isHigherThan(reportType)).as("isHigherThan(%s)", reportType).isFalse(); | ||||
} | } | ||||
} | } | ||||
for (Type type : types) { | for (Type type : types) { | ||||
assertThat(depthLimit.isHigherThan(type)).as("isHigherThan(%s)", type).isTrue(); | assertThat(depthLimit.isHigherThan(type)).as("isHigherThan(%s)", type).isTrue(); | ||||
} | } | ||||
for (Type reportType : from(VIEWS_TYPES).filter(not(in(Arrays.asList(types))))) { | |||||
for (Type reportType : from(VIEWS_TYPES).filter(not(in(asList(types))))) { | |||||
assertThat(depthLimit.isHigherThan(reportType)).as("isHigherThan(%s)", reportType).isFalse(); | assertThat(depthLimit.isHigherThan(reportType)).as("isHigherThan(%s)", reportType).isFalse(); | ||||
} | } | ||||
} | } | ||||
for (Type type : types) { | for (Type type : types) { | ||||
assertThat(depthLimit.isDeeperThan(type)).as("isDeeperThan(%s)", type).isTrue(); | assertThat(depthLimit.isDeeperThan(type)).as("isDeeperThan(%s)", type).isTrue(); | ||||
} | } | ||||
for (Type reportType : from(REPORT_TYPES).filter(not(in(Arrays.asList(types))))) { | |||||
for (Type reportType : from(REPORT_TYPES).filter(not(in(asList(types))))) { | |||||
assertThat(depthLimit.isDeeperThan(reportType)).as("isDeeperThan(%s)", reportType).isFalse(); | assertThat(depthLimit.isDeeperThan(reportType)).as("isDeeperThan(%s)", reportType).isFalse(); | ||||
} | } | ||||
} | } | ||||
for (Type type : types) { | for (Type type : types) { | ||||
assertThat(depthLimit.isDeeperThan(type)).as("isDeeperThan(%s)", type).isTrue(); | assertThat(depthLimit.isDeeperThan(type)).as("isDeeperThan(%s)", type).isTrue(); | ||||
} | } | ||||
for (Type reportType : from(VIEWS_TYPES).filter(not(in(Arrays.asList(types))))) { | |||||
for (Type reportType : from(VIEWS_TYPES).filter(not(in(asList(types))))) { | |||||
assertThat(depthLimit.isDeeperThan(reportType)).as("isDeeperThan(%s)", reportType).isFalse(); | assertThat(depthLimit.isDeeperThan(reportType)).as("isDeeperThan(%s)", reportType).isFalse(); | ||||
} | } | ||||
} | } |
} | } | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
FileUtils.listFiles(tempDir.toFile(), new AbstractFileFilter() { | FileUtils.listFiles(tempDir.toFile(), new AbstractFileFilter() { | ||||
@Override | @Override | ||||
public boolean accept(File file) { | public boolean accept(File file) { | ||||
}; | }; | ||||
} | } | ||||
private static Collection<File> listDumpFilesForTaskUuid(String taskUuid) throws IOException { | |||||
private static Collection<File> listDumpFilesForTaskUuid(String taskUuid) { | |||||
return FileUtils.listFiles(tempDir.toFile(), new AbstractFileFilter() { | return FileUtils.listFiles(tempDir.toFile(), new AbstractFileFilter() { | ||||
@Override | @Override | ||||
public boolean accept(File file) { | public boolean accept(File file) { |
@Rule | @Rule | ||||
public PeriodHolderRule periodsHolder = new PeriodHolderRule(); | public PeriodHolderRule periodsHolder = new PeriodHolderRule(); | ||||
FormulaExecutorComponentVisitor underTest; | |||||
private FormulaExecutorComponentVisitor underTest; | |||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
underTest = FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) | underTest = FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) | ||||
.buildFor(Lists.newArrayList( | .buildFor(Lists.newArrayList( | ||||
AverageFormula.Builder.newBuilder() | AverageFormula.Builder.newBuilder() |
} | } | ||||
} | } | ||||
private class FakeCounter implements Counter<FakeCounter> { | |||||
private static class FakeCounter implements Counter<FakeCounter> { | |||||
private int value = 0; | private int value = 0; | ||||
@Override | @Override | ||||
} | } | ||||
} | } | ||||
private class FakeVariationCounter implements Counter<FakeVariationCounter> { | |||||
private static class FakeVariationCounter implements Counter<FakeVariationCounter> { | |||||
private final IntValue values = new IntValue(); | private final IntValue values = new IntValue(); | ||||
@Override | @Override |
FormulaExecutorComponentVisitor underTest; | FormulaExecutorComponentVisitor underTest; | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
underTest = FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) | underTest = FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) | ||||
.buildFor(Lists.newArrayList(createIntSumFormula(LINES_KEY))); | .buildFor(Lists.newArrayList(createIntSumFormula(LINES_KEY))); | ||||
} | } |
tracker = new TrackerExecution(baseInputFactory, rawInputFactory, closedIssuesInputFactory, new Tracker<>(), issuesLoader, analysisMetadataHolder); | tracker = new TrackerExecution(baseInputFactory, rawInputFactory, closedIssuesInputFactory, new Tracker<>(), issuesLoader, analysisMetadataHolder); | ||||
prBranchTracker = new PullRequestTrackerExecution(baseInputFactory, rawInputFactory, new Tracker<>(), newLinesRepository); | prBranchTracker = new PullRequestTrackerExecution(baseInputFactory, rawInputFactory, new Tracker<>(), newLinesRepository); | ||||
mergeBranchTracker = new ReferenceBranchTrackerExecution(rawInputFactory, mergeInputFactory, new Tracker<>()); | mergeBranchTracker = new ReferenceBranchTrackerExecution(rawInputFactory, mergeInputFactory, new Tracker<>()); | ||||
trackingDelegator = new IssueTrackingDelegator(prBranchTracker, mergeBranchTracker, tracker, analysisMetadataHolder); | trackingDelegator = new IssueTrackingDelegator(prBranchTracker, mergeBranchTracker, tracker, analysisMetadataHolder); | ||||
treeRootHolder.setRoot(PROJECT); | treeRootHolder.setRoot(PROJECT); | ||||
issueCache = new IssueCache(temp.newFile(), System2.INSTANCE); | issueCache = new IssueCache(temp.newFile(), System2.INSTANCE); |
IssuesRepositoryVisitor underTest = new IssuesRepositoryVisitor(componentIssuesRepository); | IssuesRepositoryVisitor underTest = new IssuesRepositoryVisitor(componentIssuesRepository); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
treeRootHolder.setRoot(PROJECT); | treeRootHolder.setRoot(PROJECT); | ||||
} | } | ||||
private MovedIssueVisitor underTest = new MovedIssueVisitor(analysisMetadataHolder, movedFilesRepository, new IssueFieldsSetter()); | private MovedIssueVisitor underTest = new MovedIssueVisitor(analysisMetadataHolder, movedFilesRepository, new IssueFieldsSetter()); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
analysisMetadataHolder.setAnalysisDate(ANALYSIS_DATE); | analysisMetadataHolder.setAnalysisDate(ANALYSIS_DATE); | ||||
when(movedFilesRepository.getOriginalFile(any(Component.class))) | when(movedFilesRepository.getOriginalFile(any(Component.class))) | ||||
.thenReturn(Optional.absent()); | .thenReturn(Optional.absent()); |
private List<DefaultIssue> baseIssues = new ArrayList<>(); | private List<DefaultIssue> baseIssues = new ArrayList<>(); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
when(rawFactory.create(FILE)).thenReturn(createInput(rawIssues)); | when(rawFactory.create(FILE)).thenReturn(createInput(rawIssues)); | ||||
when(baseFactory.create(FILE)).thenReturn(createInput(baseIssues)); | when(baseFactory.create(FILE)).thenReturn(createInput(baseIssues)); | ||||
private RuleRepositoryImpl underTest = new RuleRepositoryImpl(adHocRuleCreator, dbClient, analysisMetadataHolder); | private RuleRepositoryImpl underTest = new RuleRepositoryImpl(adHocRuleCreator, dbClient, analysisMetadataHolder); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
when(dbClient.openSession(anyBoolean())).thenReturn(dbSession); | when(dbClient.openSession(anyBoolean())).thenReturn(dbSession); | ||||
when(dbClient.ruleDao()).thenReturn(ruleDao); | when(dbClient.ruleDao()).thenReturn(ruleDao); | ||||
when(ruleDao.selectAll(any(DbSession.class), eq(ORGANIZATION_UUID))).thenReturn(ImmutableList.of(AB_RULE)); | when(ruleDao.selectAll(any(DbSession.class), eq(ORGANIZATION_UUID))).thenReturn(ImmutableList.of(AB_RULE)); |
public RuleRepositoryRule add(DumbRule rule) { | public RuleRepositoryRule add(DumbRule rule) { | ||||
rulesByKey.put(requireNonNull(rule.getKey()), rule); | rulesByKey.put(requireNonNull(rule.getKey()), rule); | ||||
rulesById.put(requireNonNull(rule.getId()), rule); | |||||
rulesById.put(rule.getId(), rule); | |||||
return this; | return this; | ||||
} | } | ||||
new IssueFieldsSetter(), mock(ComponentsWithUnprocessedIssues.class)); | new IssueFieldsSetter(), mock(ComponentsWithUnprocessedIssues.class)); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
when(dbClient.openSession(false)).thenReturn(dbSession); | when(dbClient.openSession(false)).thenReturn(dbSession); | ||||
when(dbClient.fileSourceDao()).thenReturn(fileSourceDao); | when(dbClient.fileSourceDao()).thenReturn(fileSourceDao); | ||||
when(movedFilesRepository.getOriginalFile(any(Component.class))) | when(movedFilesRepository.getOriginalFile(any(Component.class))) |
Predicate<Measure> underTest = BestValueOptimization.from(createMetric(Metric.MetricType.RATING, A.getIndex()), FILE_COMPONENT); | Predicate<Measure> underTest = BestValueOptimization.from(createMetric(Metric.MetricType.RATING, A.getIndex()), FILE_COMPONENT); | ||||
assertThat(underTest.test(newMeasureBuilder().create(A.getIndex()))).isTrue(); | assertThat(underTest.test(newMeasureBuilder().create(A.getIndex()))).isTrue(); | ||||
assertThat(underTest.test(newMeasureBuilder().setVariation((double) A.getIndex()).createNoValue())).isTrue(); | |||||
assertThat(underTest.test(newMeasureBuilder().setVariation(A.getIndex()).createNoValue())).isTrue(); | |||||
assertThat(underTest.test(newMeasureBuilder().create(B.getIndex()))).isFalse(); | assertThat(underTest.test(newMeasureBuilder().create(B.getIndex()))).isFalse(); | ||||
assertThat(underTest.test(newMeasureBuilder().setVariation((double) B.getIndex()).createNoValue())).isFalse(); | |||||
assertThat(underTest.test(newMeasureBuilder().setVariation(B.getIndex()).createNoValue())).isFalse(); | |||||
} | } | ||||
@Test | @Test |
package org.sonar.ce.task.projectanalysis.measure; | package org.sonar.ce.task.projectanalysis.measure; | ||||
import com.google.common.base.Function; | import com.google.common.base.Function; | ||||
import com.google.common.base.Predicate; | |||||
import com.google.common.collect.ImmutableList; | import com.google.common.collect.ImmutableList; | ||||
import com.tngtech.java.junit.dataprovider.DataProvider; | import com.tngtech.java.junit.dataprovider.DataProvider; | ||||
import com.tngtech.java.junit.dataprovider.DataProviderRunner; | import com.tngtech.java.junit.dataprovider.DataProviderRunner; | ||||
} | } | ||||
private Measure getSomeMeasureByValueType(final Metric.MetricType metricType) { | private Measure getSomeMeasureByValueType(final Metric.MetricType metricType) { | ||||
return from(MEASURES).filter(new Predicate<Measure>() { | |||||
@Override | |||||
public boolean apply(@Nullable Measure input) { | |||||
return input.getValueType() == metricType.getValueType(); | |||||
} | |||||
}).first().get(); | |||||
return from(MEASURES).filter(input -> input.getValueType() == metricType.getValueType()).first().get(); | |||||
} | } | ||||
@Test | @Test |
assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create(false, null).getQualityGateStatus()).isEqualTo(someStatus); | assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create(false, null).getQualityGateStatus()).isEqualTo(someStatus); | ||||
assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create(1, null).getQualityGateStatus()).isEqualTo(someStatus); | assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create(1, null).getQualityGateStatus()).isEqualTo(someStatus); | ||||
assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create((long) 1, null).getQualityGateStatus()).isEqualTo(someStatus); | assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create((long) 1, null).getQualityGateStatus()).isEqualTo(someStatus); | ||||
assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create((double) 1, 1, null).getQualityGateStatus()).isEqualTo(someStatus); | |||||
assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create(1, 1, null).getQualityGateStatus()).isEqualTo(someStatus); | |||||
assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create("str").getQualityGateStatus()).isEqualTo(someStatus); | assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create("str").getQualityGateStatus()).isEqualTo(someStatus); | ||||
assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create(Measure.Level.OK).getQualityGateStatus()).isEqualTo(someStatus); | assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create(Measure.Level.OK).getQualityGateStatus()).isEqualTo(someStatus); | ||||
} | } | ||||
assertThat(newMeasureBuilder().create(false, someData).getData()).isEqualTo(someData); | assertThat(newMeasureBuilder().create(false, someData).getData()).isEqualTo(someData); | ||||
assertThat(newMeasureBuilder().create(1, someData).getData()).isEqualTo(someData); | assertThat(newMeasureBuilder().create(1, someData).getData()).isEqualTo(someData); | ||||
assertThat(newMeasureBuilder().create((long) 1, someData).getData()).isEqualTo(someData); | assertThat(newMeasureBuilder().create((long) 1, someData).getData()).isEqualTo(someData); | ||||
assertThat(newMeasureBuilder().create((double) 1, 1, someData).getData()).isEqualTo(someData); | |||||
assertThat(newMeasureBuilder().create(1, 1, someData).getData()).isEqualTo(someData); | |||||
} | } | ||||
@Test | @Test |
private MeasureToMeasureDto underTest = new MeasureToMeasureDto(analysisMetadataHolder, treeRootHolder); | private MeasureToMeasureDto underTest = new MeasureToMeasureDto(analysisMetadataHolder, treeRootHolder); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
analysisMetadataHolder.setUuid(ANALYSIS_UUID); | analysisMetadataHolder.setUuid(ANALYSIS_UUID); | ||||
} | } | ||||
{Measure.newMeasureBuilder().create(true, SOME_DATA), SOME_BOOLEAN_METRIC}, | {Measure.newMeasureBuilder().create(true, SOME_DATA), SOME_BOOLEAN_METRIC}, | ||||
{Measure.newMeasureBuilder().create(1, SOME_DATA), SOME_INT_METRIC}, | {Measure.newMeasureBuilder().create(1, SOME_DATA), SOME_INT_METRIC}, | ||||
{Measure.newMeasureBuilder().create((long) 1, SOME_DATA), SOME_LONG_METRIC}, | {Measure.newMeasureBuilder().create((long) 1, SOME_DATA), SOME_LONG_METRIC}, | ||||
{Measure.newMeasureBuilder().create((double) 2, 1, SOME_DATA), SOME_DOUBLE_METRIC}, | |||||
{Measure.newMeasureBuilder().create(2, 1, SOME_DATA), SOME_DOUBLE_METRIC}, | |||||
{Measure.newMeasureBuilder().create(SOME_STRING), SOME_STRING_METRIC}, | {Measure.newMeasureBuilder().create(SOME_STRING), SOME_STRING_METRIC}, | ||||
{Measure.newMeasureBuilder().create(Measure.Level.OK), SOME_LEVEL_METRIC} | {Measure.newMeasureBuilder().create(Measure.Level.OK), SOME_LEVEL_METRIC} | ||||
}; | }; | ||||
@Test | @Test | ||||
public void toMeasureDto_maps_value_and_data_from_data_field_for_DOUBLE_metric() { | public void toMeasureDto_maps_value_and_data_from_data_field_for_DOUBLE_metric() { | ||||
MeasureDto trueMeasureDto = underTest.toMeasureDto(Measure.newMeasureBuilder().create((double) 789, 1, SOME_DATA), SOME_DOUBLE_METRIC, SOME_COMPONENT); | |||||
MeasureDto trueMeasureDto = underTest.toMeasureDto(Measure.newMeasureBuilder().create(789, 1, SOME_DATA), SOME_DOUBLE_METRIC, SOME_COMPONENT); | |||||
assertThat(trueMeasureDto.getValue()).isEqualTo(789); | assertThat(trueMeasureDto.getValue()).isEqualTo(789); | ||||
assertThat(trueMeasureDto.getData()).isEqualTo(SOME_DATA); | assertThat(trueMeasureDto.getData()).isEqualTo(SOME_DATA); |
private QualityGateServiceImpl underTest = new QualityGateServiceImpl(dbClient, metricRepository); | private QualityGateServiceImpl underTest = new QualityGateServiceImpl(dbClient, metricRepository); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
when(dbClient.qualityGateDao()).thenReturn(qualityGateDao); | when(dbClient.qualityGateDao()).thenReturn(qualityGateDao); | ||||
when(dbClient.gateConditionDao()).thenReturn(qualityGateConditionDao); | when(dbClient.gateConditionDao()).thenReturn(qualityGateConditionDao); | ||||
private VisitorsCrawler underTest; | private VisitorsCrawler underTest; | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
when(ratingSettings.getDebtRatingGrid()).thenReturn(new DebtRatingGrid(RATING_GRID)); | when(ratingSettings.getDebtRatingGrid()).thenReturn(new DebtRatingGrid(RATING_GRID)); | ||||
underTest = new VisitorsCrawler(Arrays.asList(new NewMaintainabilityMeasuresVisitor(metricRepository, measureRepository, newLinesRepository, ratingSettings))); | underTest = new VisitorsCrawler(Arrays.asList(new NewMaintainabilityMeasuresVisitor(metricRepository, measureRepository, newLinesRepository, ratingSettings))); | ||||
} | } |
import static org.assertj.core.api.Assertions.assertThat; | import static org.assertj.core.api.Assertions.assertThat; | ||||
import static org.mockito.Mockito.mock; | import static org.mockito.Mockito.mock; | ||||
import static org.mockito.Mockito.verify; | |||||
import static org.mockito.Mockito.when; | import static org.mockito.Mockito.when; | ||||
import static org.sonar.api.utils.log.LoggerLevel.TRACE; | import static org.sonar.api.utils.log.LoggerLevel.TRACE; | ||||
import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; | import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; |
} | } | ||||
public ScmInfoRepositoryRule setScmInfo(int fileRef, Map<Integer, Changeset> changesets) { | public ScmInfoRepositoryRule setScmInfo(int fileRef, Map<Integer, Changeset> changesets) { | ||||
scmInfoByFileRef.put(fileRef, new ScmInfoImpl(changesets.values().stream().toArray(Changeset[]::new))); | |||||
scmInfoByFileRef.put(fileRef, new ScmInfoImpl(changesets.values().toArray(new Changeset[0]))); | |||||
return this; | return this; | ||||
} | } | ||||
} | } |
}; | }; | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
when(dbClient.openSession(false)).thenReturn(dbSession); | when(dbClient.openSession(false)).thenReturn(dbSession); | ||||
when(dbClient.componentDao()).thenReturn(componentDao); | when(dbClient.componentDao()).thenReturn(componentDao); | ||||
when(dbClient.fileSourceDao()).thenReturn(fileSourceDao); | when(dbClient.fileSourceDao()).thenReturn(fileSourceDao); |
ProjectAnalysisDataChange[] dataChanges = IntStream.range(0, 5 + new Random().nextInt(5)) | ProjectAnalysisDataChange[] dataChanges = IntStream.range(0, 5 + new Random().nextInt(5)) | ||||
.mapToObj(i -> mock(ProjectAnalysisDataChange.class)) | .mapToObj(i -> mock(ProjectAnalysisDataChange.class)) | ||||
.toArray(ProjectAnalysisDataChange[]::new); | .toArray(ProjectAnalysisDataChange[]::new); | ||||
InOrder inOrder = Mockito.inOrder((Object[]) dataChanges); | |||||
InOrder inOrder = Mockito.inOrder(dataChanges); | |||||
when(projectAnalysisDataChanges.getDataChanges()).thenReturn(Arrays.asList(dataChanges)); | when(projectAnalysisDataChanges.getDataChanges()).thenReturn(Arrays.asList(dataChanges)); | ||||
underTest.execute(new TestComputationStepContext()); | underTest.execute(new TestComputationStepContext()); |
} | } | ||||
} | } | ||||
public class Counter { | |||||
public static class Counter { | |||||
private int value = 0; | private int value = 0; | ||||
public void add(int value) { | public void add(int value) { |
integrateCrossProjectDuplications, dbClient); | integrateCrossProjectDuplications, dbClient); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
ComponentDto project = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert()); | ComponentDto project = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert()); | ||||
dbClient.componentDao().insert(dbSession, project); | dbClient.componentDao().insert(dbSession, project); | ||||
SnapshotDto projectSnapshot = SnapshotTesting.newAnalysis(project); | SnapshotDto projectSnapshot = SnapshotTesting.newAnalysis(project); |
} | } | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
organization = dbTester.organizations().insert(); | organization = dbTester.organizations().insert(); | ||||
project = dbTester.components().insertMainBranch(organization); | project = dbTester.components().insertMainBranch(organization); | ||||
private ComputationStep underTest; | private ComputationStep underTest; | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
when(baseAnalysis.getUuid()).thenReturn(BASE_ANALYSIS_UUID); | when(baseAnalysis.getUuid()).thenReturn(BASE_ANALYSIS_UUID); | ||||
analysisMetadataHolder.setUuid(ANALYSIS_UUID); | analysisMetadataHolder.setUuid(ANALYSIS_UUID); | ||||
analysisMetadataHolder.setBaseAnalysis(baseAnalysis); | analysisMetadataHolder.setBaseAnalysis(baseAnalysis); |
public MetricRepositoryRule metricRepository = new MetricRepositoryRule(); | public MetricRepositoryRule metricRepository = new MetricRepositoryRule(); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
MetricDto metric = db.measures().insertMetric(m -> m.setKey(DUPLICATIONS_DATA_KEY).setValueType(Metric.ValueType.STRING.name())); | MetricDto metric = db.measures().insertMetric(m -> m.setKey(DUPLICATIONS_DATA_KEY).setValueType(Metric.ValueType.STRING.name())); | ||||
insertComponent(PROJECT_KEY, PROJECT_UUID); | insertComponent(PROJECT_KEY, PROJECT_UUID); | ||||
insertComponent(FILE_1_KEY, FILE_1_UUID); | insertComponent(FILE_1_KEY, FILE_1_UUID); |
ComputationStep underTest = new CommentMeasuresStep(treeRootHolder, metricRepository, measureRepository); | ComputationStep underTest = new CommentMeasuresStep(treeRootHolder, metricRepository, measureRepository); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
treeRootHolder.setRoot( | treeRootHolder.setRoot( | ||||
builder(PROJECT, ROOT_REF) | builder(PROJECT, ROOT_REF) | ||||
.addChildren( | .addChildren( |
CoverageMeasuresStep underTest = new CoverageMeasuresStep(treeRootHolder, metricRepository, measureRepository, reportReader); | CoverageMeasuresStep underTest = new CoverageMeasuresStep(treeRootHolder, metricRepository, measureRepository, reportReader); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
treeRootHolder.setRoot( | treeRootHolder.setRoot( | ||||
builder(PROJECT, ROOT_REF) | builder(PROJECT, ROOT_REF) | ||||
.addChildren( | .addChildren( |
ComputationStep underTest = new LanguageDistributionMeasuresStep(treeRootHolder, metricRepository, measureRepository); | ComputationStep underTest = new LanguageDistributionMeasuresStep(treeRootHolder, metricRepository, measureRepository); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
treeRootHolder.setRoot( | treeRootHolder.setRoot( | ||||
builder(PROJECT, ROOT_REF) | builder(PROJECT, ROOT_REF) | ||||
.addChildren( | .addChildren( |
private Date now; | private Date now; | ||||
private MutableDisabledComponentsHolder disabledComponentsHolder = mock(MutableDisabledComponentsHolder.class, RETURNS_DEEP_STUBS); | private MutableDisabledComponentsHolder disabledComponentsHolder = mock(MutableDisabledComponentsHolder.class, RETURNS_DEEP_STUBS); | ||||
private PersistComponentsStep underTest; | private PersistComponentsStep underTest; | ||||
private BranchPersister branchPersister; | |||||
@Before | @Before | ||||
public void setup() throws Exception { | public void setup() throws Exception { | ||||
when(system2.now()).thenReturn(now.getTime()); | when(system2.now()).thenReturn(now.getTime()); | ||||
db.organizations().insertForUuid(ORGANIZATION_UUID); | db.organizations().insertForUuid(ORGANIZATION_UUID); | ||||
branchPersister = mock(BranchPersister.class); | |||||
BranchPersister branchPersister = mock(BranchPersister.class); | |||||
underTest = new PersistComponentsStep(dbClient, treeRootHolder, dbIdsRepository, system2, disabledComponentsHolder, analysisMetadataHolder, branchPersister); | underTest = new PersistComponentsStep(dbClient, treeRootHolder, dbIdsRepository, system2, disabledComponentsHolder, analysisMetadataHolder, branchPersister); | ||||
} | } | ||||
ComputationStep underTest = new CommentMeasuresStep(treeRootHolder, metricRepository, measureRepository); | ComputationStep underTest = new CommentMeasuresStep(treeRootHolder, metricRepository, measureRepository); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
treeRootHolder.setRoot( | treeRootHolder.setRoot( | ||||
builder(VIEW, ROOT_REF) | builder(VIEW, ROOT_REF) | ||||
.addChildren( | .addChildren( |
CoverageMeasuresStep underTest = new CoverageMeasuresStep(treeRootHolder, metricRepository, measureRepository); | CoverageMeasuresStep underTest = new CoverageMeasuresStep(treeRootHolder, metricRepository, measureRepository); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
treeRootHolder.setRoot( | treeRootHolder.setRoot( | ||||
builder(VIEW, ROOT_REF) | builder(VIEW, ROOT_REF) | ||||
.addChildren( | .addChildren( |
@Override | @Override | ||||
public AnalysisMetadataHolderRule setAnalysisDate(long date) { | public AnalysisMetadataHolderRule setAnalysisDate(long date) { | ||||
checkNotNull(date, "Date must not be null"); | |||||
this.analysisDate.setProperty(date); | this.analysisDate.setProperty(date); | ||||
return this; | return this; | ||||
} | } |
public MetricRepositoryRule add(Metric metric) { | public MetricRepositoryRule add(Metric metric) { | ||||
requireNonNull(metric.getKey(), "key can not be null"); | requireNonNull(metric.getKey(), "key can not be null"); | ||||
requireNonNull(metric.getId(), "id can not be null"); | |||||
checkState(!metricsByKey.containsKey(metric.getKey()), format("Repository already contains a metric for key %s", metric.getKey())); | checkState(!metricsByKey.containsKey(metric.getKey()), format("Repository already contains a metric for key %s", metric.getKey())); | ||||
checkState(!metricsById.containsKey((long) metric.getId()), format("Repository already contains a metric for id %s", metric.getId())); | checkState(!metricsById.containsKey((long) metric.getId()), format("Repository already contains a metric for id %s", metric.getId())); |
*/ | */ | ||||
package org.sonar.ce.taskprocessor; | package org.sonar.ce.taskprocessor; | ||||
import com.google.common.base.Function; | |||||
import com.google.common.base.Joiner; | |||||
import com.google.common.collect.ArrayListMultimap; | import com.google.common.collect.ArrayListMultimap; | ||||
import com.google.common.collect.ImmutableMap; | |||||
import com.google.common.collect.Maps; | |||||
import com.google.common.collect.Multimap; | import com.google.common.collect.Multimap; | ||||
import java.util.Collection; | import java.util.Collection; | ||||
import java.util.Map; | import java.util.Map; | ||||
import java.util.Optional; | import java.util.Optional; | ||||
import java.util.function.Function; | |||||
import java.util.stream.Collectors; | |||||
import javax.annotation.Nonnull; | import javax.annotation.Nonnull; | ||||
import org.sonar.ce.task.CeTask; | import org.sonar.ce.task.CeTask; | ||||
import org.sonar.ce.task.taskprocessor.CeTaskProcessor; | import org.sonar.ce.task.taskprocessor.CeTaskProcessor; | ||||
import static com.google.common.base.Preconditions.checkArgument; | import static com.google.common.base.Preconditions.checkArgument; | ||||
import static com.google.common.collect.FluentIterable.from; | |||||
import static java.lang.String.CASE_INSENSITIVE_ORDER; | import static java.lang.String.CASE_INSENSITIVE_ORDER; | ||||
import static java.lang.String.format; | import static java.lang.String.format; | ||||
* PicoContainer the current object belongs to. | * PicoContainer the current object belongs to. | ||||
*/ | */ | ||||
public class CeTaskProcessorRepositoryImpl implements CeTaskProcessorRepository { | public class CeTaskProcessorRepositoryImpl implements CeTaskProcessorRepository { | ||||
private static final Joiner COMMA_JOINER = Joiner.on(", "); | |||||
private final Map<String, CeTaskProcessor> taskProcessorByCeTaskType; | private final Map<String, CeTaskProcessor> taskProcessorByCeTaskType; | ||||
public CeTaskProcessorRepositoryImpl(CeTaskProcessor[] taskProcessors) { | public CeTaskProcessorRepositoryImpl(CeTaskProcessor[] taskProcessors) { | ||||
private static Map<String, CeTaskProcessor> indexTaskProcessors(CeTaskProcessor[] taskProcessors) { | private static Map<String, CeTaskProcessor> indexTaskProcessors(CeTaskProcessor[] taskProcessors) { | ||||
Multimap<String, CeTaskProcessor> permissiveIndex = buildPermissiveCeTaskProcessorIndex(taskProcessors); | Multimap<String, CeTaskProcessor> permissiveIndex = buildPermissiveCeTaskProcessorIndex(taskProcessors); | ||||
checkUniqueHandlerPerCeTaskType(permissiveIndex); | checkUniqueHandlerPerCeTaskType(permissiveIndex); | ||||
return ImmutableMap.copyOf(Maps.transformValues(permissiveIndex.asMap(), CeTaskProcessorCollectionToFirstElement.INSTANCE)); | |||||
return permissiveIndex.asMap().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, y -> CeTaskProcessorCollectionToFirstElement.INSTANCE.apply(y.getValue()))); | |||||
} | } | ||||
private static Multimap<String, CeTaskProcessor> buildPermissiveCeTaskProcessorIndex(CeTaskProcessor[] taskProcessors) { | private static Multimap<String, CeTaskProcessor> buildPermissiveCeTaskProcessorIndex(CeTaskProcessor[] taskProcessors) { | ||||
"There can be only one CeTaskProcessor instance registered as the processor for CeTask type %s. " + | "There can be only one CeTaskProcessor instance registered as the processor for CeTask type %s. " + | ||||
"More than one found. Please fix your configuration: %s", | "More than one found. Please fix your configuration: %s", | ||||
entry.getKey(), | entry.getKey(), | ||||
COMMA_JOINER.join(from(entry.getValue()).transform(ToClassName.INSTANCE).toSortedList(CASE_INSENSITIVE_ORDER)))); | |||||
entry.getValue().stream().map(ToClassName.INSTANCE).sorted(CASE_INSENSITIVE_ORDER).collect(Collectors.joining(", ")))); | |||||
} | } | ||||
} | } | ||||
connectedClients.add(clientUUID1); | connectedClients.add(clientUUID1); | ||||
connectedClients.add(clientUUID2); | connectedClients.add(clientUUID2); | ||||
connectedClients.add(clientUUID3); | connectedClients.add(clientUUID3); | ||||
Map modifiableWorkerMap = new HashMap(); | |||||
modifiableWorkerMap.putAll(workerMap); | |||||
Map modifiableWorkerMap = new HashMap(workerMap); | |||||
when(hzClientWrapper.getUuid()).thenReturn(clientUUID1); | when(hzClientWrapper.getUuid()).thenReturn(clientUUID1); | ||||
when(hzClientWrapper.getMemberUuids()).thenReturn(connectedClients); | when(hzClientWrapper.getMemberUuids()).thenReturn(connectedClients); |
return new File("src/test/plugins/sonar-test2-plugin/target/sonar-test2-plugin-0.1-SNAPSHOT.jar"); | return new File("src/test/plugins/sonar-test2-plugin/target/sonar-test2-plugin-0.1-SNAPSHOT.jar"); | ||||
} | } | ||||
private class DumbFileSystem implements ServerFileSystem { | |||||
private static class DumbFileSystem implements ServerFileSystem { | |||||
private final TemporaryFolder temp; | private final TemporaryFolder temp; | ||||
private File tempDir; | private File tempDir; | ||||
*/ | */ | ||||
package org.sonar.ce.container; | package org.sonar.ce.container; | ||||
import com.google.common.collect.Maps; | |||||
import java.io.File; | import java.io.File; | ||||
import java.util.Collection; | import java.util.Collection; | ||||
import java.util.HashMap; | |||||
import java.util.Map; | import java.util.Map; | ||||
import org.junit.After; | import org.junit.After; | ||||
import org.junit.Rule; | import org.junit.Rule; | ||||
*/ | */ | ||||
@Override | @Override | ||||
public Map<String, Plugin> load(Map<String, PluginInfo> infoByKeys) { | public Map<String, Plugin> load(Map<String, PluginInfo> infoByKeys) { | ||||
Map<String, Plugin> result = Maps.newHashMap(); | |||||
Map<String, Plugin> result = new HashMap<>(); | |||||
for (String pluginKey : infoByKeys.keySet()) { | for (String pluginKey : infoByKeys.keySet()) { | ||||
result.put(pluginKey, mock(Plugin.class)); | result.put(pluginKey, mock(Plugin.class)); | ||||
} | } |
.map(ComponentAdapter::getComponentImplementation) | .map(ComponentAdapter::getComponentImplementation) | ||||
.collect(Collectors.toList())).doesNotContain( | .collect(Collectors.toList())).doesNotContain( | ||||
(Class) CeDistributedInformationImpl.class).contains( | (Class) CeDistributedInformationImpl.class).contains( | ||||
(Class) StandaloneCeDistributedInformation.class); | |||||
StandaloneCeDistributedInformation.class); | |||||
assertThat(picoContainer.getParent().getParent().getParent().getParent()).isNull(); | assertThat(picoContainer.getParent().getParent().getParent().getParent()).isNull(); | ||||
} finally { | } finally { | ||||
underTest.stop(); | underTest.stop(); |
processingExecutorService.runFutures(); | processingExecutorService.runFutures(); | ||||
} | } | ||||
private class TestCeWorkerFactory implements CeWorkerFactory { | |||||
private static class TestCeWorkerFactory implements CeWorkerFactory { | |||||
private final Iterator<CeWorker> ceWorkers; | private final Iterator<CeWorker> ceWorkers; | ||||
private TestCeWorkerFactory(CeWorker... ceWorkers) { | private TestCeWorkerFactory(CeWorker... ceWorkers) { |
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | ||||
if (method.getName().startsWith("execute")) { | if (method.getName().startsWith("execute")) { | ||||
Profiler profiler = Profiler.create(ProfiledDataSource.SQL_LOGGER).start(); | Profiler profiler = Profiler.create(ProfiledDataSource.SQL_LOGGER).start(); | ||||
Object result = null; | |||||
Object result; | |||||
try { | try { | ||||
result = InvocationUtils.invokeQuietly(statement, method, args); | result = InvocationUtils.invokeQuietly(statement, method, args); | ||||
} finally { | } finally { |
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | ||||
if (method.getName().startsWith("execute")) { | if (method.getName().startsWith("execute")) { | ||||
Profiler profiler = Profiler.create(ProfiledDataSource.SQL_LOGGER).start(); | Profiler profiler = Profiler.create(ProfiledDataSource.SQL_LOGGER).start(); | ||||
Object result = null; | |||||
Object result; | |||||
try { | try { | ||||
result = InvocationUtils.invokeQuietly(statement, method, args); | result = InvocationUtils.invokeQuietly(statement, method, args); | ||||
} finally { | } finally { |
public void toUniqueAndSortedList_throws_NPE_if_arg_is_a_set_containing_a_null() { | public void toUniqueAndSortedList_throws_NPE_if_arg_is_a_set_containing_a_null() { | ||||
expectedException.expect(NullPointerException.class); | expectedException.expect(NullPointerException.class); | ||||
toUniqueAndSortedList(new HashSet<>(asList("A", (String) null, "C"))); | |||||
toUniqueAndSortedList(new HashSet<>(asList("A", null, "C"))); | |||||
} | } | ||||
@Test | @Test |
import java.util.Arrays; | import java.util.Arrays; | ||||
import java.util.Collections; | import java.util.Collections; | ||||
import java.util.Date; | import java.util.Date; | ||||
import java.util.HashMap; | |||||
import java.util.HashSet; | import java.util.HashSet; | ||||
import java.util.Iterator; | import java.util.Iterator; | ||||
import java.util.List; | import java.util.List; | ||||
import static com.google.common.base.Preconditions.checkArgument; | import static com.google.common.base.Preconditions.checkArgument; | ||||
import static com.google.common.collect.Lists.asList; | import static com.google.common.collect.Lists.asList; | ||||
import static com.google.common.collect.Lists.newArrayList; | |||||
import static com.google.common.collect.Maps.newHashMap; | |||||
import static java.sql.ResultSetMetaData.columnNoNulls; | import static java.sql.ResultSetMetaData.columnNoNulls; | ||||
import static java.sql.ResultSetMetaData.columnNullable; | import static java.sql.ResultSetMetaData.columnNullable; | ||||
import static org.assertj.core.api.Assertions.assertThat; | import static org.assertj.core.api.Assertions.assertThat; | ||||
private static List<Map<String, Object>> getHashMap(ResultSet resultSet) throws Exception { | private static List<Map<String, Object>> getHashMap(ResultSet resultSet) throws Exception { | ||||
ResultSetMetaData metaData = resultSet.getMetaData(); | ResultSetMetaData metaData = resultSet.getMetaData(); | ||||
int colCount = metaData.getColumnCount(); | int colCount = metaData.getColumnCount(); | ||||
List<Map<String, Object>> rows = newArrayList(); | |||||
List<Map<String, Object>> rows = new ArrayList<>(); | |||||
while (resultSet.next()) { | while (resultSet.next()) { | ||||
Map<String, Object> columns = newHashMap(); | |||||
Map<String, Object> columns = new HashMap<>(); | |||||
for (int i = 1; i <= colCount; i++) { | for (int i = 1; i <= colCount; i++) { | ||||
Object value = resultSet.getObject(i); | Object value = resultSet.getObject(i); | ||||
if (value instanceof Clob) { | if (value instanceof Clob) { |
import com.google.common.annotations.VisibleForTesting; | import com.google.common.annotations.VisibleForTesting; | ||||
import com.google.common.collect.ImmutableSet; | import com.google.common.collect.ImmutableSet; | ||||
import com.google.common.collect.Lists; | import com.google.common.collect.Lists; | ||||
import com.google.common.collect.Maps; | |||||
import java.util.Collection; | import java.util.Collection; | ||||
import java.util.HashMap; | import java.util.HashMap; | ||||
import java.util.HashSet; | import java.util.HashSet; | ||||
branchModules.forEach(module -> branchBaseKeys.put(module.getKey(), branchBaseKey(module.getKey()))); | branchModules.forEach(module -> branchBaseKeys.put(module.getKey(), branchBaseKey(module.getKey()))); | ||||
}); | }); | ||||
Map<ResourceDto, List<ResourceDto>> allResourcesByModuleMap = Maps.newHashMap(); | |||||
Map<ResourceDto, List<ResourceDto>> allResourcesByModuleMap = new HashMap<>(); | |||||
for (ResourceDto module : modules) { | for (ResourceDto module : modules) { | ||||
allResourcesByModuleMap.put(module, mapper.selectProjectResources(module.getUuid())); | allResourcesByModuleMap.put(module, mapper.selectProjectResources(module.getUuid())); | ||||
} | } |
import com.google.common.base.Predicate; | import com.google.common.base.Predicate; | ||||
import com.google.common.collect.Collections2; | import com.google.common.collect.Collections2; | ||||
import com.google.common.collect.Lists; | import com.google.common.collect.Lists; | ||||
import com.google.common.collect.Maps; | |||||
import java.util.ArrayList; | import java.util.ArrayList; | ||||
import java.util.Collection; | import java.util.Collection; | ||||
import java.util.Collections; | |||||
import java.util.List; | import java.util.List; | ||||
import java.util.Map; | import java.util.Map; | ||||
import java.util.Set; | import java.util.Set; | ||||
} | } | ||||
public List<MetricDto> selectEnabled(DbSession session, @Nullable Boolean isCustom, int offset, int limit) { | public List<MetricDto> selectEnabled(DbSession session, @Nullable Boolean isCustom, int offset, int limit) { | ||||
Map<String, Object> properties = Maps.newHashMapWithExpectedSize(1); | |||||
Map<String, Object> properties; | |||||
if (isCustom != null) { | if (isCustom != null) { | ||||
properties.put("isCustom", isCustom); | |||||
properties = Collections.singletonMap("isCustom", isCustom); | |||||
} else { | |||||
properties = Collections.emptyMap(); | |||||
} | } | ||||
return mapper(session).selectAllEnabled(properties, new RowBounds(offset, limit)); | return mapper(session).selectAllEnabled(properties, new RowBounds(offset, limit)); |
public void saveGlobalProperties(Map<String, String> properties) { | public void saveGlobalProperties(Map<String, String> properties) { | ||||
try (DbSession session = mybatis.openSession(false)) { | try (DbSession session = mybatis.openSession(false)) { | ||||
PropertiesMapper mapper = getMapper(session); | PropertiesMapper mapper = getMapper(session); | ||||
properties.entrySet().forEach(entry -> { | |||||
mapper.deleteGlobalProperty(entry.getKey()); | |||||
save(mapper, entry.getKey(), null, null, entry.getValue()); | |||||
properties.forEach((key, value) -> { | |||||
mapper.deleteGlobalProperty(key); | |||||
save(mapper, key, null, null, value); | |||||
}); | }); | ||||
session.commit(); | session.commit(); | ||||
} | } |
import com.google.common.collect.ArrayListMultimap; | import com.google.common.collect.ArrayListMultimap; | ||||
import com.google.common.collect.ImmutableMap; | import com.google.common.collect.ImmutableMap; | ||||
import com.google.common.collect.Maps; | |||||
import com.google.common.collect.Multimap; | import com.google.common.collect.Multimap; | ||||
import com.google.common.collect.Multiset; | import com.google.common.collect.Multiset; | ||||
import java.util.Collection; | import java.util.Collection; | ||||
import java.util.HashMap; | |||||
import java.util.List; | import java.util.List; | ||||
import java.util.Map; | import java.util.Map; | ||||
import org.apache.ibatis.session.RowBounds; | import org.apache.ibatis.session.RowBounds; | ||||
} | } | ||||
public Map<String, Integer> countUsersByGroups(DbSession session, Collection<Integer> groupIds) { | public Map<String, Integer> countUsersByGroups(DbSession session, Collection<Integer> groupIds) { | ||||
Map<String, Integer> result = Maps.newHashMap(); | |||||
Map<String, Integer> result = new HashMap<>(); | |||||
executeLargeInputs( | executeLargeInputs( | ||||
groupIds, | groupIds, | ||||
input -> { | input -> { |
underTest.insertOrUpdate(dbSession, BITBUCKETCLOUD, ANOTHER_REPO, "foo", null, "http://foo"); | underTest.insertOrUpdate(dbSession, BITBUCKETCLOUD, ANOTHER_REPO, "foo", null, "http://foo"); | ||||
assertThat(underTest.selectByRepoIds(dbSession, GITHUB, Arrays.asList(A_REPO, ANOTHER_REPO, "foo"))) | assertThat(underTest.selectByRepoIds(dbSession, GITHUB, Arrays.asList(A_REPO, ANOTHER_REPO, "foo"))) | ||||
.extracting(ProjectAlmBindingDto::getUuid, t -> t.getAlm(), ProjectAlmBindingDto::getRepoId, ProjectAlmBindingDto::getProjectUuid, | |||||
.extracting(ProjectAlmBindingDto::getUuid, ProjectAlmBindingDto::getAlm, ProjectAlmBindingDto::getRepoId, ProjectAlmBindingDto::getProjectUuid, | |||||
ProjectAlmBindingDto::getUrl, ProjectAlmBindingDto::getGithubSlug) | ProjectAlmBindingDto::getUrl, ProjectAlmBindingDto::getGithubSlug) | ||||
.containsExactlyInAnyOrder( | .containsExactlyInAnyOrder( | ||||
tuple("uuid1", GITHUB, A_REPO, A_UUID, A_URL, A_GITHUB_SLUG), | tuple("uuid1", GITHUB, A_REPO, A_UUID, A_URL, A_GITHUB_SLUG), |
dbSession.commit(); | dbSession.commit(); | ||||
assertThat(db.select("select uuid as \"UUID\", kee as \"KEE\" from projects")) | assertThat(db.select("select uuid as \"UUID\", kee as \"KEE\" from projects")) | ||||
.extracting(t -> (String) t.get("UUID"), t -> (String) t.get("KEE")) | |||||
.extracting(t -> t.get("UUID"), t -> t.get("KEE")) | |||||
.containsOnly( | .containsOnly( | ||||
Tuple.tuple("A", "org.struts:struts"), | Tuple.tuple("A", "org.struts:struts"), | ||||
Tuple.tuple("B", "struts:core"), | Tuple.tuple("B", "struts:core"), | ||||
dbSession.commit(); | dbSession.commit(); | ||||
assertThat(db.select("select uuid as \"UUID\", kee as \"KEE\" from projects")) | assertThat(db.select("select uuid as \"UUID\", kee as \"KEE\" from projects")) | ||||
.extracting(t -> (String) t.get("UUID"), t -> (String) t.get("KEE")) | |||||
.extracting(t -> t.get("UUID"), t -> t.get("KEE")) | |||||
.containsOnly( | .containsOnly( | ||||
Tuple.tuple("A", "org.apache.struts:struts"), | Tuple.tuple("A", "org.apache.struts:struts"), | ||||
Tuple.tuple("B", "org.apache.struts:struts-core"), | Tuple.tuple("B", "org.apache.struts:struts-core"), | ||||
dbSession.commit(); | dbSession.commit(); | ||||
assertThat(db.select("select uuid as \"UUID\", kee as \"KEE\" from projects")) | assertThat(db.select("select uuid as \"UUID\", kee as \"KEE\" from projects")) | ||||
.extracting(t -> (String) t.get("UUID"), t -> (String) t.get("KEE")) | |||||
.extracting(t -> t.get("UUID"), t -> t.get("KEE")) | |||||
.containsOnly( | .containsOnly( | ||||
Tuple.tuple("A", "org.struts:struts"), | Tuple.tuple("A", "org.struts:struts"), | ||||
Tuple.tuple("B", "org.struts:struts-core"), | Tuple.tuple("B", "org.struts:struts-core"), | ||||
dbSession.commit(); | dbSession.commit(); | ||||
assertThat(db.select("select uuid as \"UUID\", kee as \"KEE\" from projects")) | assertThat(db.select("select uuid as \"UUID\", kee as \"KEE\" from projects")) | ||||
.extracting(t -> (String) t.get("UUID"), t -> (String) t.get("KEE")) | |||||
.extracting(t -> t.get("UUID"), t -> t.get("KEE")) | |||||
.containsOnly( | .containsOnly( | ||||
Tuple.tuple("A", "org.apache.struts:struts"), | Tuple.tuple("A", "org.apache.struts:struts"), | ||||
Tuple.tuple("B", "org.apache.struts:struts-core"), | Tuple.tuple("B", "org.apache.struts:struts-core"), |
import java.sql.SQLException; | import java.sql.SQLException; | ||||
import org.apache.commons.io.FileUtils; | import org.apache.commons.io.FileUtils; | ||||
import static java.nio.charset.StandardCharsets.UTF_8; | |||||
public class DumpSQSchema { | public class DumpSQSchema { | ||||
public static void main(String[] args) { | public static void main(String[] args) { | ||||
System.exit(1); | System.exit(1); | ||||
} | } | ||||
Charset charset = Charset.forName("UTF8"); | |||||
Charset charset = UTF_8; | |||||
String oldContent = FileUtils.readFileToString(targetFile, charset); | String oldContent = FileUtils.readFileToString(targetFile, charset); | ||||
String newContent = dumper.dumpToText(); | String newContent = dumper.dumpToText(); | ||||
boolean upToDate = newContent.equals(oldContent); | boolean upToDate = newContent.equals(oldContent); |
private System2 system2 = new AlwaysIncreasingSystem2(); | private System2 system2 = new AlwaysIncreasingSystem2(); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
OrganizationDto organizationDto = dbTester.organizations().insert(); | OrganizationDto organizationDto = dbTester.organizations().insert(); | ||||
project = ComponentTesting.newPrivateProjectDto(organizationDto); | project = ComponentTesting.newPrivateProjectDto(organizationDto); | ||||
dbTester.getDbClient().componentDao().insert(dbSession, project); | dbTester.getDbClient().componentDao().insert(dbSession, project); | ||||
ComponentDto component = randomComponent(organization); | ComponentDto component = randomComponent(organization); | ||||
IssueDto issue = insertNewClosedIssue(component, ruleType); | IssueDto issue = insertNewClosedIssue(component, ruleType); | ||||
Date date = new Date(); | Date date = new Date(); | ||||
IssueChangeDto changes[] = new IssueChangeDto[] { | |||||
IssueChangeDto[] changes = new IssueChangeDto[] { | |||||
insertToClosedDiff(issue, DateUtils.addDays(date, -10)), | insertToClosedDiff(issue, DateUtils.addDays(date, -10)), | ||||
insertToClosedDiff(issue, DateUtils.addDays(date, -60)), | insertToClosedDiff(issue, DateUtils.addDays(date, -60)), | ||||
insertToClosedDiff(issue, date), | insertToClosedDiff(issue, date), | ||||
ComponentDto component = randomComponent(organization); | ComponentDto component = randomComponent(organization); | ||||
IssueDto issue = insertNewClosedIssue(component, ruleType); | IssueDto issue = insertNewClosedIssue(component, ruleType); | ||||
Date date = new Date(); | Date date = new Date(); | ||||
IssueChangeDto changes[] = new IssueChangeDto[] { | |||||
IssueChangeDto[] changes = new IssueChangeDto[] { | |||||
insertToClosedDiff(issue, DateUtils.addDays(date, -10), Issue.STATUS_CLOSED, Issue.STATUS_REOPENED), | insertToClosedDiff(issue, DateUtils.addDays(date, -10), Issue.STATUS_CLOSED, Issue.STATUS_REOPENED), | ||||
insertToClosedDiff(issue, DateUtils.addDays(date, -60)), | insertToClosedDiff(issue, DateUtils.addDays(date, -60)), | ||||
insertToClosedDiff(issue, date), | insertToClosedDiff(issue, date), |
private MetricDto metric; | private MetricDto metric; | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
metric = db.measures().insertMetric(); | metric = db.measures().insertMetric(); | ||||
} | } | ||||
private String randomPermission = "p" + random.nextInt(); | private String randomPermission = "p" + random.nextInt(); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
organization = db.organizations().insert(); | organization = db.organizations().insert(); | ||||
user = db.users().insertUser(); | user = db.users().insertUser(); | ||||
group1 = db.users().insertGroup(organization, "group1"); | group1 = db.users().insertGroup(organization, "group1"); |
private String defaultOrganizationUuid; | private String defaultOrganizationUuid; | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
defaultOrganizationUuid = db.getDefaultOrganization().getUuid(); | defaultOrganizationUuid = db.getDefaultOrganization().getUuid(); | ||||
} | } | ||||
assertThat(underTest.selectUserIdsByQuery(dbSession, query)).containsExactly(expectedUserIds.toArray(new Integer[0])); | assertThat(underTest.selectUserIdsByQuery(dbSession, query)).containsExactly(expectedUserIds.toArray(new Integer[0])); | ||||
List<UserPermissionDto> currentPermissions = underTest.selectUserPermissionsByQuery(dbSession, query, expectedUserIds); | List<UserPermissionDto> currentPermissions = underTest.selectUserPermissionsByQuery(dbSession, query, expectedUserIds); | ||||
assertThat(currentPermissions).hasSize(expectedPermissions.length); | assertThat(currentPermissions).hasSize(expectedPermissions.length); | ||||
List<Tuple> expectedPermissionsAsTuple = Arrays.stream(expectedPermissions) | |||||
Tuple[] expectedPermissionsAsTuple = Arrays.stream(expectedPermissions) | |||||
.map(expectedPermission -> tuple(expectedPermission.getUserId(), expectedPermission.getPermission(), expectedPermission.getComponentId(), | .map(expectedPermission -> tuple(expectedPermission.getUserId(), expectedPermission.getPermission(), expectedPermission.getComponentId(), | ||||
expectedPermission.getOrganizationUuid())) | expectedPermission.getOrganizationUuid())) | ||||
.collect(Collectors.toList()); | |||||
.toArray(Tuple[]::new); | |||||
assertThat(currentPermissions) | assertThat(currentPermissions) | ||||
.extracting(UserPermissionDto::getUserId, UserPermissionDto::getPermission, UserPermissionDto::getComponentId, UserPermissionDto::getOrganizationUuid) | .extracting(UserPermissionDto::getUserId, UserPermissionDto::getPermission, UserPermissionDto::getComponentId, UserPermissionDto::getOrganizationUuid) | ||||
.containsOnly(expectedPermissionsAsTuple.toArray(new Tuple[0])); | |||||
.containsOnly(expectedPermissionsAsTuple); | |||||
// test method "countUsers()" | // test method "countUsers()" | ||||
long distinctUsers = stream(expectedPermissions).mapToLong(UserPermissionDto::getUserId).distinct().count(); | long distinctUsers = stream(expectedPermissions).mapToLong(UserPermissionDto::getUserId).distinct().count(); |
private PermissionTemplateDao underTest = new PermissionTemplateDao(system2); | private PermissionTemplateDao underTest = new PermissionTemplateDao(system2); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
when(system2.now()).thenReturn(NOW.getTime()); | when(system2.now()).thenReturn(NOW.getTime()); | ||||
} | } | ||||
} | } | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
} | } | ||||
dbSession.commit(); | dbSession.commit(); | ||||
assertThat(db.select("select metric_id as \"METRIC\",analysis_uuid as \"ANALYSIS\" from project_measures")) | assertThat(db.select("select metric_id as \"METRIC\",analysis_uuid as \"ANALYSIS\" from project_measures")) | ||||
.extracting(t -> ((Long) t.get("METRIC")).intValue(), t -> (String) t.get("ANALYSIS")) | |||||
.extracting(t -> ((Long) t.get("METRIC")).intValue(), t -> t.get("ANALYSIS")) | |||||
.containsOnly( | .containsOnly( | ||||
tuple(metricWithHistory.getId(), lastAnalysis.getUuid()), | tuple(metricWithHistory.getId(), lastAnalysis.getUuid()), | ||||
tuple(metricWithoutHistory.getId(), lastAnalysis.getUuid()), | tuple(metricWithoutHistory.getId(), lastAnalysis.getUuid()), |
private PurgeMapper purgeMapper; | private PurgeMapper purgeMapper; | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
dbSession = db.getDbClient().openSession(false); | dbSession = db.getDbClient().openSession(false); | ||||
purgeMapper = dbSession.getMapper(PurgeMapper.class); | purgeMapper = dbSession.getMapper(PurgeMapper.class); | ||||
} | } |
verify(logger).info(contains("bar: 5ms")); | verify(logger).info(contains("bar: 5ms")); | ||||
} | } | ||||
private class MockedClock extends PurgeProfiler.Clock { | |||||
private static class MockedClock extends PurgeProfiler.Clock { | |||||
private long now = 0; | private long now = 0; | ||||
@Override | @Override |
import org.sonar.db.DbTester; | import org.sonar.db.DbTester; | ||||
import static java.util.Arrays.asList; | import static java.util.Arrays.asList; | ||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat; | |||||
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; | import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; | ||||
public class QProfileChangeDaoTest { | public class QProfileChangeDaoTest { |
private GroupMembershipDao underTest = db.getDbClient().groupMembershipDao(); | private GroupMembershipDao underTest = db.getDbClient().groupMembershipDao(); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
organizationDto = db.organizations().insert(); | organizationDto = db.organizations().insert(); | ||||
user1 = db.users().insertUser(u -> u.setLogin("admin login").setName("Admin name").setEmail("admin@email.com")); | user1 = db.users().insertUser(u -> u.setLogin("admin login").setName("Admin name").setEmail("admin@email.com")); | ||||
user2 = db.users().insertUser(u -> u.setLogin("not.admin").setName("Not Admin").setEmail("Not Admin")); | user2 = db.users().insertUser(u -> u.setLogin("not.admin").setName("Not Admin").setEmail("Not Admin")); |
@Test | @Test | ||||
public void insert_user() { | public void insert_user() { | ||||
Long date = DateUtils.parseDate("2014-06-20").getTime(); | |||||
long date = DateUtils.parseDate("2014-06-20").getTime(); | |||||
UserDto userDto = new UserDto() | UserDto userDto = new UserDto() | ||||
.setId(1) | .setId(1) |
new MigrationHistoryTableImpl(noopDatabase).start(); | new MigrationHistoryTableImpl(noopDatabase).start(); | ||||
} | } | ||||
private class NoopDatabase implements Database { | |||||
private static class NoopDatabase implements Database { | |||||
private final Dialect dialect; | private final Dialect dialect; | ||||
private final DataSource dataSource; | private final DataSource dataSource; | ||||
MyBatisConfExtension[] extensionArray = confExtensions.length == 0 ? null : confExtensions; | MyBatisConfExtension[] extensionArray = confExtensions.length == 0 ? null : confExtensions; | ||||
if (schemaPath == null) { | if (schemaPath == null) { | ||||
if (defaultSchemaBaseTestDb == null) { | if (defaultSchemaBaseTestDb == null) { | ||||
defaultSchemaBaseTestDb = new TestDbImpl((String) null); | |||||
defaultSchemaBaseTestDb = new TestDbImpl(null); | |||||
} | } | ||||
if (extensionArray != null) { | if (extensionArray != null) { | ||||
return defaultSchemaTestDbsWithExtensions.computeIfAbsent( | return defaultSchemaTestDbsWithExtensions.computeIfAbsent( |
public class NotificationDbTester { | public class NotificationDbTester { | ||||
private static final String PROP_NOTIFICATION_PREFIX = "notification"; | private static final String PROP_NOTIFICATION_PREFIX = "notification"; | ||||
private final DbTester db; | |||||
private final DbClient dbClient; | private final DbClient dbClient; | ||||
private final DbSession dbSession; | private final DbSession dbSession; | ||||
public NotificationDbTester(DbTester db) { | public NotificationDbTester(DbTester db) { | ||||
this.db = db; | |||||
this.dbClient = db.getDbClient(); | this.dbClient = db.getDbClient(); | ||||
this.dbSession = db.getSession(); | this.dbSession = db.getSession(); | ||||
} | } |
} | } | ||||
public static GroupDto newGroupDto() { | public static GroupDto newGroupDto() { | ||||
GroupDto group = new GroupDto() | |||||
return new GroupDto() | |||||
.setId(nextInt()) | .setId(nextInt()) | ||||
.setOrganizationUuid(randomAlphanumeric(40)) | .setOrganizationUuid(randomAlphanumeric(40)) | ||||
.setName(randomAlphanumeric(255)) | .setName(randomAlphanumeric(255)) | ||||
.setDescription(randomAlphanumeric(200)) | .setDescription(randomAlphanumeric(200)) | ||||
.setCreatedAt(new Date(nextLong())) | .setCreatedAt(new Date(nextLong())) | ||||
.setUpdatedAt(new Date(nextLong())); | .setUpdatedAt(new Date(nextLong())); | ||||
return group; | |||||
} | } | ||||
} | } |
}); | }); | ||||
} | } | ||||
} | } | ||||
return res.stream().toArray(Object[][]::new); | |||||
return res.toArray(new Object[0][]); | |||||
} | } | ||||
@Test | @Test |
public class MigrationContainerImplTest { | public class MigrationContainerImplTest { | ||||
private ComponentContainer parent = new ComponentContainer(); | private ComponentContainer parent = new ComponentContainer(); | ||||
private MigrationContainerPopulator populator = new MigrationContainerPopulator() { | |||||
@Override | |||||
public void populateContainer(MigrationContainer container) { | |||||
container.add(StartCallCounter.class); | |||||
} | |||||
}; | |||||
private MigrationContainerPopulator populator = container -> container.add(StartCallCounter.class); | |||||
private MigrationContainerImpl underTest = new MigrationContainerImpl(parent, populator); | private MigrationContainerImpl underTest = new MigrationContainerImpl(parent, populator); | ||||
*/ | */ | ||||
package org.sonar.server.platform.db.migration.engine; | package org.sonar.server.platform.db.migration.engine; | ||||
import java.sql.SQLException; | |||||
import java.util.stream.Stream; | import java.util.stream.Stream; | ||||
import org.junit.Before; | import org.junit.Before; | ||||
import org.junit.Test; | import org.junit.Test; | ||||
private MigrationContainerPopulatorImpl underTest = new MigrationContainerPopulatorImpl(); | private MigrationContainerPopulatorImpl underTest = new MigrationContainerPopulatorImpl(); | ||||
@Before | @Before | ||||
public void setUp() throws Exception { | |||||
public void setUp() { | |||||
migrationContainer.add(migrationSteps); | migrationContainer.add(migrationSteps); | ||||
} | } | ||||
private static abstract class NoopMigrationStep implements MigrationStep { | private static abstract class NoopMigrationStep implements MigrationStep { | ||||
@Override | @Override | ||||
public void execute() throws SQLException { | |||||
public void execute() { | |||||
throw new UnsupportedOperationException("execute not implemented"); | throw new UnsupportedOperationException("execute not implemented"); | ||||
} | } | ||||
} | } |
*/ | */ | ||||
package org.sonar.server.platform.db.migration.engine; | package org.sonar.server.platform.db.migration.engine; | ||||
import java.sql.SQLException; | |||||
import java.util.List; | import java.util.List; | ||||
import java.util.Optional; | import java.util.Optional; | ||||
import org.junit.Test; | import org.junit.Test; | ||||
private MigrationHistory migrationHistory = mock(MigrationHistory.class); | private MigrationHistory migrationHistory = mock(MigrationHistory.class); | ||||
private ComponentContainer serverContainer = new ComponentContainer(); | private ComponentContainer serverContainer = new ComponentContainer(); | ||||
private MigrationStepsExecutor stepsExecutor = mock(MigrationStepsExecutor.class); | private MigrationStepsExecutor stepsExecutor = mock(MigrationStepsExecutor.class); | ||||
private MigrationContainerPopulator populator = new MigrationContainerPopulator() { | |||||
@Override | |||||
public void populateContainer(MigrationContainer container) { | |||||
container.add(stepsExecutor); | |||||
} | |||||
}; | |||||
private MigrationContainerPopulator populator = container -> container.add(stepsExecutor); | |||||
private MigrationSteps migrationSteps = mock(MigrationSteps.class); | private MigrationSteps migrationSteps = mock(MigrationSteps.class); | ||||
private MapSettings settings = new MapSettings(); | private MapSettings settings = new MapSettings(); | ||||
private static class TestBlueGreenMigrationStep implements MigrationStep { | private static class TestBlueGreenMigrationStep implements MigrationStep { | ||||
@Override | @Override | ||||
public void execute() throws SQLException { | |||||
public void execute() { | |||||
} | } | ||||
} | } |
new DataChange(db.database()) { | new DataChange(db.database()) { | ||||
@Override | @Override | ||||
public void execute(Context context) throws SQLException { | public void execute(Context context) throws SQLException { | ||||
context.prepareSelect("select id from persons where id>=?").setLong(1, 2L).get(new RowReader<Long>() { | |||||
@Override | |||||
public Long read(Row row) { | |||||
throw new IllegalStateException("Unexpected error"); | |||||
} | |||||
context.prepareSelect("select id from persons where id>=?").setLong(1, 2L).get((RowReader<Long>) row -> { | |||||
throw new IllegalStateException("Unexpected error"); | |||||
}); | }); | ||||
} | } | ||||
}.execute(); | }.execute(); | ||||
new DataChange(db.database()) { | new DataChange(db.database()) { | ||||
@Override | @Override | ||||
public void execute(Context context) throws SQLException { | public void execute(Context context) throws SQLException { | ||||
context.prepareSelect("select id from persons where id>=?").setLong(1, 2L).list(new RowReader<Long>() { | |||||
@Override | |||||
public Long read(Row row) { | |||||
throw new IllegalStateException("Unexpected error"); | |||||
} | |||||
context.prepareSelect("select id from persons where id>=?").setLong(1, 2L).list((RowReader<Long>) row -> { | |||||
throw new IllegalStateException("Unexpected error"); | |||||
}); | }); | ||||
} | } | ||||
}.execute(); | }.execute(); | ||||
public void bad_parameterized_query() throws Exception { | public void bad_parameterized_query() throws Exception { | ||||
insertPersons(); | insertPersons(); | ||||
final List<Long> ids = new ArrayList<>(); | |||||
DataChange change = new DataChange(db.database()) { | DataChange change = new DataChange(db.database()) { | ||||
@Override | @Override | ||||
public void execute(Context context) throws SQLException { | public void execute(Context context) throws SQLException { | ||||
// parameter value is not set | // parameter value is not set | ||||
ids.addAll(context.prepareSelect("select id from persons where id>=?").list(Select.LONG_READER)); | |||||
context.prepareSelect("select id from persons where id>=?").list(Select.LONG_READER); | |||||
} | } | ||||
}; | }; | ||||
new DataChange(db.database()) { | new DataChange(db.database()) { | ||||
@Override | @Override | ||||
public void execute(Context context) throws SQLException { | public void execute(Context context) throws SQLException { | ||||
context.prepareSelect("select id from persons order by id desc").scroll(new Select.RowHandler() { | |||||
@Override | |||||
public void handle(Row row) throws SQLException { | |||||
ids.add(row.getNullableLong(1)); | |||||
} | |||||
}); | |||||
context.prepareSelect("select id from persons order by id desc").scroll(row -> ids.add(row.getNullableLong(1))); | |||||
} | } | ||||
}.execute(); | }.execute(); | ||||
assertThat(ids).containsExactly(3L, 2L, 1L); | assertThat(ids).containsExactly(3L, 2L, 1L); | ||||
@Override | @Override | ||||
public void execute(Context context) throws SQLException { | public void execute(Context context) throws SQLException { | ||||
final Upsert upsert = context.prepareUpsert("update persons set login=?, age=? where id=?"); | final Upsert upsert = context.prepareUpsert("update persons set login=?, age=? where id=?"); | ||||
context.prepareSelect("select id from persons").scroll(new Select.RowHandler() { | |||||
@Override | |||||
public void handle(Row row) { | |||||
throw new IllegalStateException("Unexpected error"); | |||||
} | |||||
context.prepareSelect("select id from persons").scroll(row -> { | |||||
throw new IllegalStateException("Unexpected error"); | |||||
}); | }); | ||||
upsert.commit().close(); | upsert.commit().close(); | ||||
} | } | ||||
MassUpdate massUpdate = context.prepareMassUpdate(); | MassUpdate massUpdate = context.prepareMassUpdate(); | ||||
massUpdate.select("select id from persons where id>=?").setLong(1, 2L); | massUpdate.select("select id from persons where id>=?").setLong(1, 2L); | ||||
massUpdate.update("update persons set login=?, age=? where id=?"); | massUpdate.update("update persons set login=?, age=? where id=?"); | ||||
massUpdate.execute(new MassUpdate.Handler() { | |||||
@Override | |||||
public boolean handle(Row row, SqlStatement update) throws SQLException { | |||||
long id = row.getNullableLong(1); | |||||
update | |||||
.setString(1, "login" + id) | |||||
.setInt(2, 10 + (int) id) | |||||
.setLong(3, id); | |||||
return true; | |||||
} | |||||
massUpdate.execute((row, update) -> { | |||||
long id = row.getNullableLong(1); | |||||
update | |||||
.setString(1, "login" + id) | |||||
.setInt(2, 10 + (int) id) | |||||
.setLong(3, id); | |||||
return true; | |||||
}); | }); | ||||
} | } | ||||
}.execute(); | }.execute(); | ||||
MassUpdate massUpdate = context.prepareMassUpdate(); | MassUpdate massUpdate = context.prepareMassUpdate(); | ||||
massUpdate.select("select id from persons where id>=?").setLong(1, 2L); | massUpdate.select("select id from persons where id>=?").setLong(1, 2L); | ||||
massUpdate.update("update persons set login=?, age=? where id=?"); | massUpdate.update("update persons set login=?, age=? where id=?"); | ||||
massUpdate.execute(new MassUpdate.Handler() { | |||||
@Override | |||||
public boolean handle(Row row, SqlStatement update) { | |||||
throw new IllegalStateException("Unexpected error"); | |||||
} | |||||
massUpdate.execute((row, update) -> { | |||||
throw new IllegalStateException("Unexpected error"); | |||||
}); | }); | ||||
} | } | ||||
}.execute(); | }.execute(); | ||||
MassUpdate massUpdate = context.prepareMassUpdate(); | MassUpdate massUpdate = context.prepareMassUpdate(); | ||||
massUpdate.select("select id from persons where id>=?").setLong(1, 2L); | massUpdate.select("select id from persons where id>=?").setLong(1, 2L); | ||||
massUpdate.update("update persons set login=?, age=? where id=?"); | massUpdate.update("update persons set login=?, age=? where id=?"); | ||||
massUpdate.execute(new MassUpdate.Handler() { | |||||
@Override | |||||
public boolean handle(Row row, SqlStatement update) { | |||||
return false; | |||||
} | |||||
}); | |||||
massUpdate.execute((row, update) -> false); | |||||
} | } | ||||
}.execute(); | }.execute(); | ||||
MassUpdate massUpdate = context.prepareMassUpdate(); | MassUpdate massUpdate = context.prepareMassUpdate(); | ||||
massUpdate.select("select id from persons where id>=?").setLong(1, 2L); | massUpdate.select("select id from persons where id>=?").setLong(1, 2L); | ||||
// update is not set | // update is not set | ||||
massUpdate.execute(new MassUpdate.Handler() { | |||||
@Override | |||||
public boolean handle(Row row, SqlStatement update) { | |||||
return false; | |||||
} | |||||
}); | |||||
massUpdate.execute((row, update) -> false); | |||||
} | } | ||||
}; | }; | ||||
try { | try { |
*/ | */ | ||||
package org.sonar.server.platform.db.migration.step; | package org.sonar.server.platform.db.migration.step; | ||||
import java.sql.SQLException; | |||||
import java.util.List; | import java.util.List; | ||||
import java.util.Random; | import java.util.Random; | ||||
import org.junit.Rule; | import org.junit.Rule; | ||||
private static abstract class NoopMigrationStep implements MigrationStep { | private static abstract class NoopMigrationStep implements MigrationStep { | ||||
@Override | @Override | ||||
public void execute() throws SQLException { | |||||
public void execute() { | |||||
throw new IllegalStateException("execute is not implemented"); | throw new IllegalStateException("execute is not implemented"); | ||||
} | } | ||||
} | } |
private boolean called = false; | private boolean called = false; | ||||
@Override | @Override | ||||
public void execute() throws SQLException { | |||||
public void execute() { | |||||
checkState(!called, "execute must not be called twice"); | checkState(!called, "execute must not be called twice"); | ||||
this.called = true; | this.called = true; | ||||
calledSteps.add(getClass()); | calledSteps.add(getClass()); | ||||
private static final RuntimeException THROWN_EXCEPTION = new RuntimeException("Faking failing migration step"); | private static final RuntimeException THROWN_EXCEPTION = new RuntimeException("Faking failing migration step"); | ||||
@Override | @Override | ||||
public void execute() throws SQLException { | |||||
public void execute() { | |||||
throw THROWN_EXCEPTION; | throw THROWN_EXCEPTION; | ||||
} | } | ||||
} | } |
File homeDir = temp.newFolder(); | File homeDir = temp.newFolder(); | ||||
File dataDir = temp.newFolder(); | File dataDir = temp.newFolder(); | ||||
File logDir = temp.newFolder(); | File logDir = temp.newFolder(); | ||||
ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, () -> new TestProcessBuilder()); | |||||
ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, TestProcessBuilder::new); | |||||
EsScriptCommand command = createEsScriptCommand(tempDir, homeDir, dataDir, logDir); | EsScriptCommand command = createEsScriptCommand(tempDir, homeDir, dataDir, logDir); | ||||
File outdatedEsDir = new File(dataDir, "es"); | File outdatedEsDir = new File(dataDir, "es"); |
return member; | return member; | ||||
} | } | ||||
private class TestHazelcastMember implements HazelcastMember { | |||||
private static class TestHazelcastMember implements HazelcastMember { | |||||
private final Map<Member, List<String>> hostsPerMember; | private final Map<Member, List<String>> hostsPerMember; | ||||
private final Cluster cluster = mock(Cluster.class); | private final Cluster cluster = mock(Cluster.class); | ||||
} | } | ||||
@Test | @Test | ||||
public void constructor_sets_mandatory_JVM_options_for_java11() throws IOException { | |||||
public void constructor_sets_mandatory_JVM_options_for_java11() { | |||||
when(javaVersion.isAtLeastJava11()).thenReturn(true); | when(javaVersion.isAtLeastJava11()).thenReturn(true); | ||||
underTest = new WebJvmOptions(tmpDir, javaVersion); | underTest = new WebJvmOptions(tmpDir, javaVersion); | ||||
); | ); | ||||
} | } | ||||
private class MemoryAppender<E> extends AppenderBase<E> { | |||||
private static class MemoryAppender<E> extends AppenderBase<E> { | |||||
private final List<E> events = new ArrayList(); | private final List<E> events = new ArrayList(); | ||||
@Override | @Override |