ProjectIssuesDashboard template;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
IssueFilterDao issueFilterDao = new IssueFilterDao(dbTester.myBatis());
template = new ProjectIssuesDashboard(issueFilterDao);
}
NewAlerts dispatcher = new NewAlerts(notificationManager);
@Test
- public void should_not_dispatch_if_not_alerts_notification() throws Exception {
+ public void should_not_dispatch_if_not_alerts_notification() {
Notification notification = new Notification("other-notif");
dispatcher.performDispatch(notification, context);
}
@Test
- public void shouldDoNothingIfNoScmData() throws ParseException {
+ public void shouldDoNothingIfNoScmData() {
when(context.getMeasure(CoreMetrics.COVERAGE_LINE_HITS_DATA))
.thenReturn(new Measure(CoreMetrics.COVERAGE_LINE_HITS_DATA, "1=10"));
}
@Test
- public void shouldDoNothingIfNoCoverageData() throws ParseException {
+ public void shouldDoNothingIfNoCoverageData() {
writer.writeComponentChangesets(BatchReport.Changesets.newBuilder()
.setComponentRef(1)
.addChangeset(Changeset.newBuilder()
}
@Test
- public void shouldGetNewLines() throws ParseException {
+ public void shouldGetNewLines() {
when(context.getMeasure(CoreMetrics.COVERAGE_LINE_HITS_DATA)).thenReturn(
new Measure(CoreMetrics.COVERAGE_LINE_HITS_DATA, "10=2;11=3"));
writer.writeComponentChangesets(BatchReport.Changesets.newBuilder()
}
@Test
- public void shouldGetNewConditions() throws ParseException {
+ public void shouldGetNewConditions() {
when(context.getMeasure(CoreMetrics.COVERAGE_LINE_HITS_DATA)).thenReturn(
new Measure(CoreMetrics.COVERAGE_LINE_HITS_DATA, "10=2;11=3"));
when(context.getMeasure(CoreMetrics.CONDITIONS_BY_LINE)).thenReturn(
}
@Test
- public void shouldNotGetNewConditionsWhenNewLineHasNoConditions() throws ParseException {
+ public void shouldNotGetNewConditionsWhenNewLineHasNoConditions() {
when(context.getMeasure(CoreMetrics.COVERAGE_LINE_HITS_DATA)).thenReturn(
new Measure(CoreMetrics.COVERAGE_LINE_HITS_DATA, "10=2;11=3"));
when(context.getMeasure(CoreMetrics.CONDITIONS_BY_LINE)).thenReturn(
}
@Test
- public void shouldLeaveNullValueWhenNothingHasChanged() throws Exception {
+ public void shouldLeaveNullValueWhenNothingHasChanged() {
when(context.getMeasure(CoreMetrics.COVERAGE_LINE_HITS_DATA)).thenReturn(
new Measure(CoreMetrics.COVERAGE_LINE_HITS_DATA, "2=1;3=1"));
}
@Test
- public void shouldThrowAnExceptionWhenUnableToSendTestEmail() throws Exception {
+ public void shouldThrowAnExceptionWhenUnableToSendTestEmail() {
configure();
server.stop();
}
@Test
- public void shouldNotSendEmailWhenHostnameNotConfigured() throws Exception {
+ public void shouldNotSendEmailWhenHostnameNotConfigured() {
EmailMessage emailMessage = new EmailMessage()
.setTo("user@nowhere")
.setSubject("Foo")
}
@Test
- public void shouldNotThrowAnExceptionWhenUnableToSendEmail() throws Exception {
+ public void shouldNotThrowAnExceptionWhenUnableToSendEmail() {
configure();
server.stop();
}
@Test
- public void shouldSendTestEmailWithSTARTTLS() throws Exception {
+ public void shouldSendTestEmailWithSTARTTLS() {
server.getServer().setEnableTLS(true);
server.getServer().setRequireTLS(true);
configure();
}
@Test
- public void add_java_options() throws Exception {
+ public void add_java_options() {
JavaCommand command = new JavaCommand("foo");
assertThat(command.getJavaOptions()).isEmpty();
public class JavaProcessLauncherTest {
@Test
- public void fail_to_launch() throws Exception {
+ public void fail_to_launch() {
JavaCommand command = new JavaCommand("test");
JavaProcessLauncher launcher = new JavaProcessLauncher(new Timeouts());
try {
* Safeguard
*/
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
try {
if (monitor != null) {
monitor.stop();
}
@Test
- public void fail_to_start_if_no_commands() throws Exception {
+ public void fail_to_start_if_no_commands() {
monitor = newDefaultMonitor();
try {
monitor.start(Collections.<JavaCommand>emptyList());
this.httpPort = httpPort;
}
- JavaCommand newCommand() throws IOException {
+ JavaCommand newCommand() {
return new JavaCommand(commandKey)
.addClasspath(testJar.getAbsolutePath())
.setClassName("org.sonar.process.test.HttpProcess")
return readTimeFromFile("terminatedAt");
}
- boolean wasReady() throws IOException {
+ boolean wasReady() {
return fileExists("readyAt");
}
public class StreamGobblerTest {
@Test
- public void forward_stream_to_log() throws Exception {
+ public void forward_stream_to_log() {
InputStream stream = IOUtils.toInputStream("one\nsecond log\nthird log\n");
Logger logger = mock(Logger.class);
}
@Test
- public void encrypt() throws Exception {
+ public void encrypt() {
AesCipher cipher = new AesCipher(pathToSecretKey());
String encryptedText = cipher.encrypt("this is a secret");
}
@Test
- public void encrypt_bad_key() throws Exception {
+ public void encrypt_bad_key() {
thrown.expect(RuntimeException.class);
thrown.expectMessage("Invalid AES key");
}
@Test
- public void decrypt() throws Exception {
+ public void decrypt() {
AesCipher cipher = new AesCipher(pathToSecretKey());
// the following value has been encrypted with the key /org/sonar/api/config/AesCipherTest/aes_secret_key.txt
}
@Test
- public void decrypt_bad_key() throws Exception {
+ public void decrypt_bad_key() {
AesCipher cipher = new AesCipher(getPath("bad_secret_key.txt"));
try {
}
@Test
- public void decrypt_other_key() throws Exception {
+ public void decrypt_other_key() {
AesCipher cipher = new AesCipher(getPath("other_secret_key.txt"));
try {
}
@Test
- public void encryptThenDecrypt() throws Exception {
+ public void encryptThenDecrypt() {
AesCipher cipher = new AesCipher(pathToSecretKey());
assertThat(cipher.decrypt(cipher.encrypt("foo"))).isEqualTo("foo");
}
@Test
- public void hasSecretKey() throws Exception {
+ public void hasSecretKey() {
AesCipher cipher = new AesCipher(pathToSecretKey());
assertThat(cipher.hasSecretKey()).isTrue();
}
@Test
- public void doesNotHaveSecretKey() throws Exception {
+ public void doesNotHaveSecretKey() {
AesCipher cipher = new AesCipher("/my/twitter/id/is/SimonBrandhof");
assertThat(cipher.hasSecretKey()).isFalse();
return Resources.getResource(AesCipherTest.class, "AesCipherTest/" + file).getPath();
}
- private static String pathToSecretKey() throws Exception {
+ private static String pathToSecretKey() {
return getPath("aes_secret_key.txt");
}
}
@Test
- public void loadPropsFromCommandLineArgs_missing_argument() throws Exception {
+ public void loadPropsFromCommandLineArgs_missing_argument() {
try {
ConfigurationUtils.loadPropsFromCommandLineArgs(new String[0]);
fail();
}
@Test
- public void private_constructor() throws Exception {
+ public void private_constructor() {
assertThat(TestUtils.hasOnlyPrivateConstructors(ConfigurationUtils.class)).isTrue();
}
}
public class LifecycleTest {
@Test
- public void equals_and_hashcode() throws Exception {
+ public void equals_and_hashcode() {
Lifecycle init = new Lifecycle();
assertThat(init.equals(init)).isTrue();
assertThat(init.equals(new Lifecycle())).isTrue();
}
@Test
- public void try_to_move() throws Exception {
+ public void try_to_move() {
Lifecycle lifecycle = new Lifecycle();
assertThat(lifecycle.getState()).isEqualTo(State.INIT);
}
@Test
- public void newConsoleAppender() throws Exception {
+ public void newConsoleAppender() {
LoggerContext ctx = sut.getRootContext();
ConsoleAppender appender = sut.newConsoleAppender(ctx, "MY_APPENDER", "%msg%n");
}
@Test
- public void configureLogger() throws Exception {
+ public void configureLogger() {
LoggerContext ctx = sut.getRootContext();
Logger logger = sut.configureLogger(ctx, "my_logger", Level.WARN);
}
@Test
- public void createRollingPolicy_defaults() throws Exception {
+ public void createRollingPolicy_defaults() {
LoggerContext ctx = sut.getRootContext();
LogbackHelper.RollingPolicy policy = sut.createRollingPolicy(ctx, props, "sonar");
FileAppender appender = policy.createAppender("SONAR_FILE");
}
@Test
- public void createRollingPolicy_none() throws Exception {
+ public void createRollingPolicy_none() {
props.set("sonar.log.rollingPolicy", "none");
LoggerContext ctx = sut.getRootContext();
LogbackHelper.RollingPolicy policy = sut.createRollingPolicy(ctx, props, "sonar");
}
@Test
- public void createRollingPolicy_size() throws Exception {
+ public void createRollingPolicy_size() {
props.set("sonar.log.rollingPolicy", "size:1MB");
props.set("sonar.log.maxFiles", "20");
LoggerContext ctx = sut.getRootContext();
}
@Test
- public void createRollingPolicy_time() throws Exception {
+ public void createRollingPolicy_time() {
props.set("sonar.log.rollingPolicy", "time:yyyy-MM");
props.set("sonar.log.maxFiles", "20");
}
@Test
- public void createRollingPolicy_fail_if_unknown_policy() throws Exception {
+ public void createRollingPolicy_fail_if_unknown_policy() {
props.set("sonar.log.rollingPolicy", "unknown:foo");
try {
LoggerContext ctx = sut.getRootContext();
public class LoopbackAddressTest {
@Test
- public void get() throws Exception {
+ public void get() {
assertThat(LoopbackAddress.get()).isNotNull();
assertThat(LoopbackAddress.get().isLoopbackAddress()).isTrue();
assertThat(LoopbackAddress.get().getHostAddress()).isNotNull();
}
@Test
- public void fail_to_get_loopback_address() throws Exception {
+ public void fail_to_get_loopback_address() {
Enumeration<NetworkInterface> ifaces = Iterators.asEnumeration(Collections.<NetworkInterface>emptyList().iterator());
try {
LoopbackAddress.doGet(ifaces);
}
@Test
- public void private_constructor() throws Exception {
+ public void private_constructor() {
assertThat(TestUtils.hasOnlyPrivateConstructors(LoopbackAddress.class)).isTrue();
}
}
* Test environment does not necessarily follows all checks.
*/
@Test
- public void check() throws Exception {
+ public void check() {
MinimumViableSystem mve = new MinimumViableSystem();
try {
}
@Test
- public void checkJavaVersion() throws Exception {
+ public void checkJavaVersion() {
MinimumViableSystem mve = new MinimumViableSystem();
// yes, sources are compiled with a supported Java version!
}
@Test
- public void checkJavaOption() throws Exception {
+ public void checkJavaOption() {
String key = "MinimumViableEnvironmentTest.test.prop";
MinimumViableSystem mve = new MinimumViableSystem()
.setRequiredJavaOption(key, "true");
public class NetworkUtilsTest {
@Test
- public void find_free_port() throws Exception {
+ public void find_free_port() {
int port = NetworkUtils.freePort();
assertThat(port).isGreaterThan(0);
}
@Test
- public void find_multiple_free_port() throws Exception {
+ public void find_multiple_free_port() {
int port1 = NetworkUtils.freePort();
int port2 = NetworkUtils.freePort();
}
@Test
- public void private_constructor() throws Exception {
+ public void private_constructor() {
assertThat(TestUtils.hasOnlyPrivateConstructors(NetworkUtils.class)).isTrue();
}
}
}
@Test
- public void fail_to_launch_multiple_times() throws Exception {
+ public void fail_to_launch_multiple_times() {
Props props = new Props(new Properties());
props.set(ProcessEntryPoint.PROPERTY_PROCESS_KEY, "test");
props.set(ProcessEntryPoint.PROPERTY_TERMINATION_TIMEOUT, "30000");
}
@Test
- public void terminate_if_startup_error() throws Exception {
+ public void terminate_if_startup_error() {
Props props = new Props(new Properties());
props.set(ProcessEntryPoint.PROPERTY_PROCESS_KEY, "foo");
props.set(ProcessEntryPoint.PROPERTY_TERMINATION_TIMEOUT, "30000");
public class ProcessPropertiesTest {
@Test
- public void init_defaults() throws Exception {
+ public void init_defaults() {
Props props = new Props(new Properties());
ProcessProperties.completeDefaults(props);
}
@Test
- public void do_not_override_existing_properties() throws Exception {
+ public void do_not_override_existing_properties() {
Properties p = new Properties();
p.setProperty("sonar.jdbc.username", "angela");
Props props = new Props(p);
}
@Test
- public void use_random_port_if_zero() throws Exception {
+ public void use_random_port_if_zero() {
Properties p = new Properties();
p.setProperty("sonar.search.port", "0");
Props props = new Props(p);
}
@Test
- public void private_constructor() throws Exception {
+ public void private_constructor() {
assertThat(TestUtils.hasOnlyPrivateConstructors(ProcessProperties.class)).isTrue();
}
}
public class ProcessUtilsTest {
@Test
- public void private_constructor() throws Exception {
+ public void private_constructor() {
assertThat(TestUtils.hasOnlyPrivateConstructors(ProcessUtils.class)).isTrue();
}
}
public TemporaryFolder temp = new TemporaryFolder();
@Test
- public void value() throws Exception {
+ public void value() {
Properties p = new Properties();
p.setProperty("foo", "bar");
Props props = new Props(p);
}
@Test
- public void valueAsInt() throws Exception {
+ public void valueAsInt() {
Properties p = new Properties();
p.setProperty("foo", "33");
p.setProperty("blank", "");
}
@Test
- public void valueAsInt_not_integer() throws Exception {
+ public void valueAsInt_not_integer() {
Properties p = new Properties();
p.setProperty("foo", "bar");
Props props = new Props(p);
}
@Test
- public void booleanOf() throws Exception {
+ public void booleanOf() {
Properties p = new Properties();
p.setProperty("foo", "True");
p.setProperty("bar", "false");
}
@Test
- public void booleanOf_default_value() throws Exception {
+ public void booleanOf_default_value() {
Properties p = new Properties();
p.setProperty("foo", "true");
p.setProperty("bar", "false");
}
@Test
- public void setDefault() throws Exception {
+ public void setDefault() {
Properties p = new Properties();
p.setProperty("foo", "foo_value");
Props props = new Props(p);
}
@Test
- public void set() throws Exception {
+ public void set() {
Properties p = new Properties();
p.setProperty("foo", "old_foo");
Props props = new Props(p);
}
@Test
- public void raw_properties() throws Exception {
+ public void raw_properties() {
Properties p = new Properties();
p.setProperty("encrypted_prop", "{aes}abcde");
p.setProperty("clear_prop", "foo");
public class SystemExitTest {
@Test
- public void do_not_exit_if_in_shutdown_hook() throws Exception {
+ public void do_not_exit_if_in_shutdown_hook() {
SystemExit systemExit = new SystemExit();
systemExit.setInShutdownHook();
}
@Test
- public void exit_if_not_in_shutdown_hook() throws Exception {
+ public void exit_if_not_in_shutdown_hook() {
final AtomicInteger got = new AtomicInteger();
SystemExit systemExit = new SystemExit() {
@Override
}
@Test
- public void log_to_console() throws Exception {
+ public void log_to_console() {
LoggerContext ctx = sut.configure();
Logger root = ctx.getLogger(Logger.ROOT_LOGGER_NAME);
public TemporaryFolder temp = new TemporaryFolder();
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
if (searchServer != null) {
searchServer.stop();
searchServer.awaitStop();
ListUpdate.UpdateListScriptFactory factory;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
factory = new ListUpdate.UpdateListScriptFactory();
}
}
@Test
- public void update_list() throws Exception {
+ public void update_list() {
String listField = "listField";
Collection<Map<String, Object>> mapFields;
public Benchmark benchmark = new Benchmark();
@Test
- public void benchmark() throws Exception {
+ public void benchmark() {
// initialization - feed issues/issueAuthorization with projects and hardcoded users
indexAuthorizations();
persistFileSources(reportDir);
}
- private void persistFileSources(File reportDir) throws SQLException {
+ private void persistFileSources(File reportDir) {
LOGGER.info("Persist file sources");
DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), new FileSourceDao(dbTester.myBatis()));
return dto;
}
- private byte[] generateData() throws IOException {
+ private byte[] generateData() {
FileSourceDb.Data.Builder dataBuilder = FileSourceDb.Data.newBuilder();
FileSourceDb.Line.Builder lineBuilder = FileSourceDb.Line.newBuilder();
for (int i = 1; i <= NUMBER_OF_LINES; i++) {
public Benchmark benchmark = new Benchmark();
@Test
- public void benchmark() throws Exception {
+ public void benchmark() {
// index source lines
benchmarkIndexing();
private Settings settings = new Settings();
@Before
- public void before() throws Exception {
+ public void before() {
this.projectSettingsFactory = mock(ProjectSettingsFactory.class);
this.sut = new ProjectCleaner(dao, periodCleaner, profiler, purgeListener, issueIndex);
}
@Test
- public void no_profiling_when_property_is_false() throws Exception {
+ public void no_profiling_when_property_is_false() {
settings.setProperty(CoreProperties.PROFILING_LOG_PROPERTY, false);
sut.purge(mock(DbSession.class), mock(IdUuidPair.class), settings);
}
@Test
- public void no_indexing_when_no_issue_to_delete() throws Exception {
+ public void no_indexing_when_no_issue_to_delete() {
sut.purge(mock(DbSession.class), mock(IdUuidPair.class), settings);
verifyZeroInteractions(issueIndex);
}
@Test
- public void profiling_when_property_is_true() throws Exception {
+ public void profiling_when_property_is_true() {
settings.setProperty(CoreProperties.PROFILING_LOG_PROPERTY, true);
sut.purge(mock(DbSession.class), mock(IdUuidPair.class), settings);
}
@Test
- public void call_period_cleaner_index_client_and_purge_dao() throws Exception {
+ public void call_period_cleaner_index_client_and_purge_dao() {
settings.setProperty(DbCleanerConstants.DAYS_BEFORE_DELETING_CLOSED_ISSUES, 5);
sut.purge(mock(DbSession.class), mock(IdUuidPair.class), settings);
}
@Test
- public void if_dao_purge_fails_it_should_not_interrupt_program_execution() throws Exception {
+ public void if_dao_purge_fails_it_should_not_interrupt_program_execution() {
doThrow(RuntimeException.class).when(dao).purge(any(DbSession.class), any(PurgeConfiguration.class), any(PurgeListener.class));
sut.purge(mock(DbSession.class), mock(IdUuidPair.class), settings);
}
@Test
- public void if_profiler_cleaning_fails_it_should_not_interrupt_program_execution() throws Exception {
+ public void if_profiler_cleaning_fails_it_should_not_interrupt_program_execution() {
doThrow(RuntimeException.class).when(periodCleaner).clean(any(DbSession.class), anyLong(), any(Settings.class));
sut.purge(mock(DbSession.class), mock(IdUuidPair.class), settings);
}
@Test
- public void insert_and_index() throws Exception {
+ public void insert_and_index() {
when(system.now()).thenReturn(1_500_000_000_000L);
Activity activity = new Activity();
RubyQProfileActivityService rubyQProfileActivityService;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
rubyQProfileActivityService = new RubyQProfileActivityService(service);
}
@Test
- public void search() throws Exception {
+ public void search() {
Date since = DateUtils.parseDate("2014-05-19");
Date to = DateUtils.parseDate("2014-06-19");
}
@Test
- public void search_with_empty_fields() throws Exception {
+ public void search_with_empty_fields() {
Result<QProfileActivity> result = mock(Result.class);
when(result.getHits()).thenReturn(Lists.<QProfileActivity>newArrayList());
when(result.getTotal()).thenReturn(10L);
ActivityDao sut;
@Before
- public void before() throws Exception {
+ public void before() {
sut = new ActivityDao(dbTester.myBatis(), system);
}
@Test
- public void insert() throws Exception {
+ public void insert() {
when(system.now()).thenReturn(1_500_000_000_000L);
ActivityDto dto = new ActivityDto()
.setKey("UUID_1").setAction("THE_ACTION").setType("THE_TYPE")
IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext();
@Test
- public void define() throws Exception {
+ public void define() {
ActivityIndexDefinition def = new ActivityIndexDefinition(new Settings());
def.define(context);
}
@Test
- public void enable_cluster() throws Exception {
+ public void enable_cluster() {
Settings settings = new Settings();
settings.setProperty(ProcessProperties.CLUSTER_ACTIVATE, true);
ActivityIndexDefinition def = new ActivityIndexDefinition(settings);
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
DbUtils.closeQuietly(connection);
}
* Iterate over two rows in table.
*/
@Test
- public void traverse() throws Exception {
+ public void traverse() {
dbTester.prepareDbUnit(getClass(), "traverse.xml");
ActivityResultSetIterator it = ActivityResultSetIterator.create(client, connection, 0L);
}
@Test
- public void traverse_after_date() throws Exception {
+ public void traverse_after_date() {
dbTester.prepareDbUnit(getClass(), "traverse.xml");
ActivityResultSetIterator it = ActivityResultSetIterator.create(client, connection, DateUtils.parseDate("2014-12-01").getTime());
}
@Test
- public void nothing_to_traverse() throws Exception {
+ public void nothing_to_traverse() {
dbTester.prepareDbUnit(getClass(), "traverse.xml");
ActivityResultSetIterator it = ActivityResultSetIterator.create(client, connection, DateUtils.parseDate("2030-01-01").getTime());
ActivityService service;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
ws = tester.get(ActivitiesWebService.class);
service = tester.get(ActivityService.class);
}
@Test
- public void define() throws Exception {
+ public void define() {
WebService.Context context = new WebService.Context();
ws.define(context);
StartupLogs sut = new StartupLogs(props, logger);
@Test
- public void logAjp() throws Exception {
+ public void logAjp() {
Connector connector = newConnector("AJP/1.3", "http");
when(tomcat.getService().findConnectors()).thenReturn(new Connector[] {connector});
}
@Test
- public void logHttp() throws Exception {
+ public void logHttp() {
Connector connector = newConnector("HTTP/1.1", "http");
when(tomcat.getService().findConnectors()).thenReturn(new Connector[] {connector});
}
@Test
- public void logHttps_default_ciphers() throws Exception {
+ public void logHttps_default_ciphers() {
Connector connector = newConnector("HTTP/1.1", "https");
when(tomcat.getService().findConnectors()).thenReturn(new Connector[] {connector});
}
@Test
- public void logHttps_overridden_ciphers() throws Exception {
+ public void logHttps_overridden_ciphers() {
Connector connector = mock(Connector.class);
when(connector.getScheme()).thenReturn("https");
when(connector.getPort()).thenReturn(1234);
}
@Test
- public void unsupported_connector() throws Exception {
+ public void unsupported_connector() {
Connector connector = mock(Connector.class, Mockito.RETURNS_DEEP_STUBS);
when(connector.getProtocol()).thenReturn("SPDY/1.1");
when(connector.getScheme()).thenReturn("spdy");
// ---- connectors
@Test
- public void configure_thread_pool() throws Exception {
+ public void configure_thread_pool() {
Properties p = new Properties();
p.setProperty("sonar.web.http.minThreads", "2");
p.setProperty("sonar.web.http.maxThreads", "30");
}
@Test
- public void configure_default_thread_pool() throws Exception {
+ public void configure_default_thread_pool() {
Props props = new Props(new Properties());
TomcatConnectors.configure(tomcat, props);
}
@Test
- public void different_thread_pools_for_connectors() throws Exception {
+ public void different_thread_pools_for_connectors() {
Properties p = new Properties();
p.setProperty("sonar.web.port", "9000");
p.setProperty("sonar.web.http.minThreads", "2");
}
@Test
- public void http_and_ajp_and_https_ports_should_be_different() throws Exception {
+ public void http_and_ajp_and_https_ports_should_be_different() {
Properties p = new Properties();
p.setProperty("sonar.web.port", "9000");
p.setProperty("sonar.ajp.port", "9000");
}
@Test
- public void bind_to_all_addresses_by_default() throws Exception {
+ public void bind_to_all_addresses_by_default() {
Properties p = new Properties();
p.setProperty("sonar.web.port", "9000");
p.setProperty("sonar.ajp.port", "9009");
}
@Test
- public void bind_to_specific_address() throws Exception {
+ public void bind_to_specific_address() {
Properties p = new Properties();
p.setProperty("sonar.web.port", "9000");
p.setProperty("sonar.web.https.port", "9443");
}
@Test
- public void enable_client_auth() throws Exception {
+ public void enable_client_auth() {
Properties p = new Properties();
}
@Test
- public void require_client_auth() throws Exception {
+ public void require_client_auth() {
Properties p = new Properties();
}
@Test
- public void log_to_console() throws Exception {
+ public void log_to_console() {
LoggerContext ctx = sut.configure(props);
Logger root = ctx.getLogger(Logger.ROOT_LOGGER_NAME);
}
@Test
- public void enable_debug_logs() throws Exception {
+ public void enable_debug_logs() {
props.set("sonar.log.level", "DEBUG");
LoggerContext ctx = sut.configure(props);
assertThat(ctx.getLogger(Logger.ROOT_LOGGER_NAME).getLevel()).isEqualTo(Level.DEBUG);
}
@Test
- public void enable_trace_logs() throws Exception {
+ public void enable_trace_logs() {
props.set("sonar.log.level", "TRACE");
LoggerContext ctx = sut.configure(props);
assertThat(ctx.getLogger(Logger.ROOT_LOGGER_NAME).getLevel()).isEqualTo(Level.TRACE);
}
@Test
- public void configure_rails_dev_mode() throws Exception {
+ public void configure_rails_dev_mode() {
props.set("sonar.web.dev", "true");
Context context = mock(Context.class);
}
@Test
- public void configure_production_mode() throws Exception {
+ public void configure_production_mode() {
props.set("sonar.web.dev", "false");
Context context = mock(Context.class);
}
@Test
- public void context_path_must_start_with_slash() throws Exception {
+ public void context_path_must_start_with_slash() {
Properties p = new Properties();
p.setProperty("sonar.web.context", "foo");
}
@Test
- public void root_context_path_must_be_blank() throws Exception {
+ public void root_context_path_must_be_blank() {
Properties p = new Properties();
p.setProperty("sonar.web.context", "/");
}
@Test
- public void default_context_path_is_root() throws Exception {
+ public void default_context_path_is_root() {
String context = Webapp.getContextPath(new Props(new Properties()));
assertThat(context).isEqualTo("");
}
WsTester tester = new WsTester(new AuthenticationWs());
@Test
- public void define_ws() throws Exception {
+ public void define_ws() {
WebService.Controller controller = tester.controller("api/authentication");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
}
@Test
- public void get_index() throws Exception {
+ public void get_index() {
BatchIndex batchIndex = new BatchIndex(server);
batchIndex.start();
}
@Test
- public void get_file() throws Exception {
+ public void get_file() {
BatchIndex batchIndex = new BatchIndex(server);
batchIndex.start();
* /etc/passwd
*/
@Test
- public void check_location_of_file() throws Exception {
+ public void check_location_of_file() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Bad filename: ../sonar-batch.jar");
}
@Test
- public void file_does_not_exist() throws Exception {
+ public void file_does_not_exist() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Bad filename: other.jar");
WsTester tester;
@Before
- public void before() throws IOException {
+ public void before() {
tester = new WsTester(new BatchWs(batchIndex,
new GlobalRepositoryAction(mock(DbClient.class), mock(PropertiesDao.class)),
new ProjectRepositoryAction(mock(ProjectRepositoryLoader.class)),
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
DbClient dbClient = mock(DbClient.class);
when(dbClient.openSession(false)).thenReturn(session);
when(dbClient.metricDao()).thenReturn(metricDao);
IssuesAction issuesAction;
@Before
- public void before() throws Exception {
+ public void before() {
db.truncateTables();
es.truncateIndices();
this.session = db.myBatis().openSession(false);
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester = new WsTester(new BatchWs(mock(BatchIndex.class), new ProjectRepositoryAction(projectRepositoryLoader)));
}
}
@Test
- public void return_project_settings() throws Exception {
+ public void return_project_settings() {
ComponentDto project = ComponentTesting.newProjectDto();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void not_returned_secured_settings_with_only_preview_permission() throws Exception {
+ public void not_returned_secured_settings_with_only_preview_permission() {
ComponentDto project = ComponentTesting.newProjectDto();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.PREVIEW_EXECUTION).addProjectUuidPermissions(UserRole.USER, project.uuid());
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void return_project_with_module_settings() throws Exception {
+ public void return_project_with_module_settings() {
ComponentDto project = ComponentTesting.newProjectDto();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void return_project_with_module_settings_inherited_from_project() throws Exception {
+ public void return_project_with_module_settings_inherited_from_project() {
ComponentDto project = ComponentTesting.newProjectDto();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void return_project_with_module_with_sub_module() throws Exception {
+ public void return_project_with_module_with_sub_module() {
ComponentDto project = ComponentTesting.newProjectDto();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void return_project_with_two_modules() throws Exception {
+ public void return_project_with_two_modules() {
ComponentDto project = ComponentTesting.newProjectDto();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void return_provisioned_project_settings() throws Exception {
+ public void return_provisioned_project_settings() {
// No snapshot attached on the project -> provisioned project
ComponentDto project = ComponentTesting.newProjectDto();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
}
@Test
- public void return_sub_module_settings() throws Exception {
+ public void return_sub_module_settings() {
ComponentDto project = ComponentTesting.newProjectDto();
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void return_sub_module_settings_including_settings_from_parent_modules() throws Exception {
+ public void return_sub_module_settings_including_settings_from_parent_modules() {
ComponentDto project = ComponentTesting.newProjectDto();
tester.get(DbClient.class).componentDao().insert(dbSession, project);
addDefaultProfile();
}
@Test
- public void return_sub_module_settings_only_inherited_from_project() throws Exception {
+ public void return_sub_module_settings_only_inherited_from_project() {
ComponentDto project = ComponentTesting.newProjectDto();
tester.get(DbClient.class).componentDao().insert(dbSession, project);
addDefaultProfile();
}
@Test
- public void return_sub_module_settings_inherited_from_project_and_module() throws Exception {
+ public void return_sub_module_settings_inherited_from_project_and_module() {
ComponentDto project = ComponentTesting.newProjectDto();
tester.get(DbClient.class).componentDao().insert(dbSession, project);
addDefaultProfile();
}
@Test
- public void return_quality_profile_from_project_profile() throws Exception {
+ public void return_quality_profile_from_project_profile() {
Date ruleUpdatedAt = DateUtils.parseDateTime("2014-01-14T13:00:00+0100");
ComponentDto project = ComponentTesting.newProjectDto();
}
@Test
- public void return_quality_profile_from_default_profile() throws Exception {
+ public void return_quality_profile_from_default_profile() {
Date ruleUpdatedAt = DateUtils.parseDateTime("2014-01-14T13:00:00+0100");
ComponentDto project = ComponentTesting.newProjectDto();
}
@Test
- public void return_quality_profile_from_given_profile_name() throws Exception {
+ public void return_quality_profile_from_given_profile_name() {
Date ruleUpdatedAt = DateUtils.parseDateTime("2014-01-14T13:00:00+0100");
ComponentDto project = ComponentTesting.newProjectDto();
}
@Test
- public void return_quality_profiles_even_when_project_does_not_exists() throws Exception {
+ public void return_quality_profiles_even_when_project_does_not_exists() {
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
Date ruleUpdatedAt = DateUtils.parseDateTime("2014-01-14T13:00:00+0100");
}
@Test
- public void return_provisioned_project_profile() throws Exception {
+ public void return_provisioned_project_profile() {
Date ruleUpdatedAt = DateUtils.parseDateTime("2014-01-14T13:00:00+0100");
// No snapshot attached on the project -> provisioned project
}
@Test
- public void fail_when_no_quality_profile_for_a_language() throws Exception {
+ public void fail_when_no_quality_profile_for_a_language() {
ComponentDto project = ComponentTesting.newProjectDto().setKey("org.codehaus.sonar:sonar");
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void return_active_rules() throws Exception {
+ public void return_active_rules() {
ComponentDto project = ComponentTesting.newProjectDto();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void return_only_active_rules_from_project_profile() throws Exception {
+ public void return_only_active_rules_from_project_profile() {
ComponentDto project = ComponentTesting.newProjectDto();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void return_more_than_10_active_rules() throws Exception {
+ public void return_more_than_10_active_rules() {
ComponentDto project = ComponentTesting.newProjectDto();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void return_custom_rule() throws Exception {
+ public void return_custom_rule() {
Date ruleUpdatedAt = DateUtils.parseDateTime("2014-01-14T13:00:00+0100");
ComponentDto project = ComponentTesting.newProjectDto();
}
@Test
- public void return_manual_rules() throws Exception {
+ public void return_manual_rules() {
ComponentDto project = ComponentTesting.newProjectDto();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void fail_if_no_permission() throws Exception {
+ public void fail_if_no_permission() {
MockUserSession.set().setLogin("john").setGlobalPermissions();
ComponentDto project = ComponentTesting.newProjectDto();
}
@Test
- public void fail_when_not_preview_and_only_dry_run_permission() throws Exception {
+ public void fail_when_not_preview_and_only_dry_run_permission() {
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.PREVIEW_EXECUTION);
ComponentDto project = ComponentTesting.newProjectDto();
}
@Test
- public void return_file_data_from_single_project() throws Exception {
+ public void return_file_data_from_single_project() {
ComponentDto project = ComponentTesting.newProjectDto();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void return_file_data_from_multi_modules() throws Exception {
+ public void return_file_data_from_multi_modules() {
ComponentDto project = ComponentTesting.newProjectDto();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
tester.get(DbClient.class).componentDao().insert(dbSession, project);
}
@Test
- public void return_file_data_from_module() throws Exception {
+ public void return_file_data_from_module() {
ComponentDto project = ComponentTesting.newProjectDto();
tester.get(DbClient.class).componentDao().insert(dbSession, project);
addDefaultProfile();
UsersAction usersAction;
@Before
- public void before() throws Exception {
+ public void before() {
es.truncateIndices();
userIndex = new UserIndex(es.client());
ComponentCleanerService service;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
db = tester.get(DbClient.class);
}
@Test
- public void delete_project() throws Exception {
+ public void delete_project() {
ComponentDto project = ComponentTesting.newProjectDto();
db.componentDao().insert(session, project);
session.commit();
}
@Test
- public void remove_issue_permission_index_when_deleting_a_project() throws Exception {
+ public void remove_issue_permission_index_when_deleting_a_project() {
ComponentDto project = ComponentTesting.newProjectDto();
db.componentDao().insert(session, project);
}
@Test
- public void remove_issue_when_deleting_a_project() throws Exception {
+ public void remove_issue_when_deleting_a_project() {
// ARRANGE
ComponentDto project = ComponentTesting.newProjectDto();
db.componentDao().insert(session, project);
}
@Test(expected = IllegalArgumentException.class)
- public void fail_to_delete_not_project() throws Exception {
+ public void fail_to_delete_not_project() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
db.componentDao().insert(session, project, file);
public class ComponentQueryTest {
@Test
- public void should_build_query() throws Exception {
+ public void should_build_query() {
ComponentQuery query = ComponentQuery.builder()
.keys(newArrayList("org.codehaus"))
.names(newArrayList("Sona"))
}
@Test
- public void should_accept_null_sort() throws Exception {
+ public void should_accept_null_sort() {
ComponentQuery query = ComponentQuery.builder().sort(null).build();
assertThat(query.sort()).isNull();
}
@Test
- public void should_sort_by_name_asc_by_default() throws Exception {
+ public void should_sort_by_name_asc_by_default() {
ComponentQuery query = ComponentQuery.builder().build();
assertThat(query.sort()).isEqualTo(ComponentQuery.SORT_BY_NAME);
assertThat(query.asc()).isTrue();
}
@Test
- public void should_throw_exception_if_sort_is_not_valid() throws Exception {
+ public void should_throw_exception_if_sort_is_not_valid() {
try {
ComponentQuery.builder()
.sort("UNKNOWN")
}
@Test
- public void should_build_non_paginated_query() throws Exception {
+ public void should_build_non_paginated_query() {
ComponentQuery query = ComponentQuery.builder().pageSize(ComponentQuery.NO_PAGINATION).build();
assertThat(query.pageSize()).isEqualTo(ComponentQuery.NO_PAGINATION);
assertThat(query.pageIndex()).isEqualTo(ComponentQuery.DEFAULT_PAGE_INDEX);
ComponentService service;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
db = tester.get(DbClient.class);
session = db.openSession(false);
}
@Test
- public void get_by_key() throws Exception {
+ public void get_by_key() {
ComponentDto project = createProject("sample:root");
assertThat(service.getByKey(project.getKey())).isNotNull();
}
@Test
- public void get_nullable_by_key() throws Exception {
+ public void get_nullable_by_key() {
ComponentDto project = createProject("sample:root");
assertThat(service.getNullableByKey(project.getKey())).isNotNull();
assertThat(service.getNullableByKey("unknown")).isNull();
}
@Test
- public void get_by_uuid() throws Exception {
+ public void get_by_uuid() {
ComponentDto project = createProject("sample:root");
assertThat(service.getByUuid(project.uuid())).isNotNull();
}
@Test
- public void get_nullable_by_uuid() throws Exception {
+ public void get_nullable_by_uuid() {
ComponentDto project = createProject("sample:root");
assertThat(service.getNullableByUuid(project.uuid())).isNotNull();
assertThat(service.getNullableByUuid("unknown")).isNull();
}
@Test
- public void update_project_key() throws Exception {
+ public void update_project_key() {
ComponentDto project = createProject("sample:root");
ComponentDto file = ComponentTesting.newFileDto(project).setKey("sample:root:src/File.xoo");
tester.get(ComponentDao.class).insert(session, file);
}
@Test
- public void update_module_key() throws Exception {
+ public void update_module_key() {
ComponentDto project = createProject("sample:root");
ComponentDto module = ComponentTesting.newModuleDto(project).setKey("sample:root:module");
tester.get(ComponentDao.class).insert(session, module);
}
@Test
- public void update_provisioned_project_key() throws Exception {
+ public void update_provisioned_project_key() {
ComponentDto provisionedProject = ComponentTesting.newProjectDto().setKey("provisionedProject");
tester.get(ComponentDao.class).insert(session, provisionedProject);
}
@Test(expected = ForbiddenException.class)
- public void fail_to_update_project_key_without_admin_permission() throws Exception {
+ public void fail_to_update_project_key_without_admin_permission() {
ComponentDto project = createProject("sample:root");
MockUserSession.set().setLogin("john").addProjectUuidPermissions(UserRole.USER, project.uuid());
service.updateKey(project.key(), "sample2:root");
}
@Test
- public void check_module_keys_before_renaming() throws Exception {
+ public void check_module_keys_before_renaming() {
ComponentDto project = createProject("sample:root");
ComponentDto module = ComponentTesting.newModuleDto(project).setKey("sample:root:module");
tester.get(ComponentDao.class).insert(session, module);
}
@Test
- public void check_module_keys_before_renaming_return_duplicate_key() throws Exception {
+ public void check_module_keys_before_renaming_return_duplicate_key() {
ComponentDto project = createProject("sample:root");
ComponentDto module = ComponentTesting.newModuleDto(project).setKey("sample:root:module");
tester.get(ComponentDao.class).insert(session, module);
}
@Test(expected = ForbiddenException.class)
- public void fail_to_check_module_keys_before_renaming_without_admin_permission() throws Exception {
+ public void fail_to_check_module_keys_before_renaming_without_admin_permission() {
ComponentDto project = createProject("sample:root");
MockUserSession.set().setLogin("john").addProjectUuidPermissions(UserRole.USER, project.uuid());
service.checkModuleKeysBeforeRenaming(project.key(), "sample", "sample2");
}
@Test
- public void bulk_update_project_key() throws Exception {
+ public void bulk_update_project_key() {
ComponentDto project = createProject("sample:root");
ComponentDto module = ComponentTesting.newModuleDto(project).setKey("sample:root:module");
tester.get(ComponentDao.class).insert(session, module);
}
@Test
- public void bulk_update_provisioned_project_key() throws Exception {
+ public void bulk_update_provisioned_project_key() {
ComponentDto provisionedProject = ComponentTesting.newProjectDto().setKey("provisionedProject");
tester.get(ComponentDao.class).insert(session, provisionedProject);
}
@Test(expected = ForbiddenException.class)
- public void fail_to_bulk_update_project_key_without_admin_permission() throws Exception {
+ public void fail_to_bulk_update_project_key_without_admin_permission() {
ComponentDto project = createProject("sample:root");
MockUserSession.set().setLogin("john").addProjectPermissions(UserRole.USER, project.key());
service.bulkUpdateKey("sample:root", "sample", "sample2");
}
@Test
- public void create_project() throws Exception {
+ public void create_project() {
executeStartupTasksToCreateDefaultPermissionTemplate();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.PROVISIONING);
}
@Test
- public void create_new_project_with_branch() throws Exception {
+ public void create_new_project_with_branch() {
executeStartupTasksToCreateDefaultPermissionTemplate();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.PROVISIONING);
}
@Test
- public void create_view() throws Exception {
+ public void create_view() {
executeStartupTasksToCreateDefaultPermissionTemplate();
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.PROVISIONING);
}
@Test
- public void fail_to_create_new_component_on_invalid_key() throws Exception {
+ public void fail_to_create_new_component_on_invalid_key() {
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.PROVISIONING);
try {
}
@Test
- public void fail_to_create_new_component_on_invalid_branch() throws Exception {
+ public void fail_to_create_new_component_on_invalid_branch() {
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.PROVISIONING);
try {
}
@Test
- public void fail_to_create_new_component_if_key_already_exists() throws Exception {
+ public void fail_to_create_new_component_if_key_already_exists() {
MockUserSession.set().setLogin("john").setGlobalPermissions(GlobalPermissions.PROVISIONING);
ComponentDto project = ComponentTesting.newProjectDto().setKey("struts");
}
@Test
- public void should_return_project_uuids() throws Exception {
+ public void should_return_project_uuids() {
ComponentDto project = createProject("sample:root");
String moduleKey = "sample:root:module";
ComponentDto module = ComponentTesting.newModuleDto(project).setKey(moduleKey);
}
@Test
- public void should_fail_on_components_not_found() throws Exception {
+ public void should_fail_on_components_not_found() {
String moduleKey = "sample:root:module";
String fileKey = "sample:root:module:Foo.xoo";
}
@Test
- public void should_fail_silently_on_components_not_found_if_told_so() throws Exception {
+ public void should_fail_silently_on_components_not_found_if_told_so() {
String moduleKey = "sample:root:module";
String fileKey = "sample:root:module:Foo.xoo";
}
@Test
- public void should_skip_pagination() throws Exception {
+ public void should_skip_pagination() {
ComponentQuery query = ComponentQuery.builder().pageSize(ComponentQuery.NO_PAGINATION)
.pageIndex(ComponentQuery.DEFAULT_PAGE_INDEX).build();
System2 system2;
@Before
- public void createDao() throws Exception {
+ public void createDao() {
session = getMyBatis().openSession(false);
system2 = mock(System2.class);
dao = new ComponentDao(system2);
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
}
@Test
- public void find_modules_by_project() throws Exception {
+ public void find_modules_by_project() {
setupData("multi-modules");
List<ComponentDto> results = dao.findModulesByProject("org.struts:struts", session);
}
@Test
- public void find_sub_projects_by_component_keys() throws Exception {
+ public void find_sub_projects_by_component_keys() {
setupData("multi-modules");
// Sub project of a file
}
@Test
- public void select_enabled_modules_tree() throws Exception {
+ public void select_enabled_modules_tree() {
setupData("multi-modules");
// From root project
}
@Test
- public void select_all_modules_tree() throws Exception {
+ public void select_all_modules_tree() {
setupData("multi-modules");
// From root project, disabled sub module is returned
}
@Test
- public void select_enabled_module_files_tree_from_module() throws Exception {
+ public void select_enabled_module_files_tree_from_module() {
setupData("select_module_files_tree");
// From root project
}
@Test
- public void select_enabled_module_files_tree_from_project() throws Exception {
+ public void select_enabled_module_files_tree_from_project() {
setupData("select_module_files_tree");
// From root project
ComponentIndexDao dao;
@Before
- public void createDao() throws Exception {
+ public void createDao() {
dbTester.truncateTables();
session = dbTester.myBatis().openSession(false);
dao = new ComponentIndexDao();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void select_project_ids_from_query_and_view_or_sub_view_uuid() throws Exception {
+ public void select_project_ids_from_query_and_view_or_sub_view_uuid() {
dbTester.prepareDbUnit(getClass(), "select_project_ids_from_query_and_view_or_sub_view_uuid.xml");
String viewUuid = "EFGH";
ComponentLinkDao dao;
@Before
- public void createDao() throws Exception {
+ public void createDao() {
session = dbTester.myBatis().openSession(false);
dao = new ComponentLinkDao();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void select_by_component_uuid() throws Exception {
+ public void select_by_component_uuid() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
List<ComponentLinkDto> links = dao.selectByComponentUuid(session, "ABCD");
}
@Test
- public void insert() throws Exception {
+ public void insert() {
dbTester.prepareDbUnit(getClass(), "empty.xml");
dao.insert(session, new ComponentLinkDto()
}
@Test
- public void update() throws Exception {
+ public void update() {
dbTester.prepareDbUnit(getClass(), "update.xml");
dao.update(session, new ComponentLinkDto()
}
@Test
- public void delete() throws Exception {
+ public void delete() {
dbTester.prepareDbUnit(getClass(), "delete.xml");
dao.delete(session, 1L);
System2 system2;
@Before
- public void createDao() throws Exception {
+ public void createDao() {
session = getMyBatis().openSession(false);
system2 = mock(System2.class);
sut = new SnapshotDao(system2);
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
DbClient dbClient = mock(DbClient.class);
when(dbClient.openSession(false)).thenReturn(session);
when(dbClient.componentDao()).thenReturn(componentDao);
}
@Test
- public void fail_on_unknown_component() throws Exception {
+ public void fail_on_unknown_component() {
MockUserSession.set().setLogin("john").addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
when(componentDao.getNullableByUuid(session, COMPONENT_UUID)).thenReturn(null);
WebService.Controller controller;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
WsTester tester = new WsTester(new ComponentsWs(new ComponentAppAction(mock(DbClient.class), mock(Durations.class), mock(I18n.class)), new SearchAction(mock(DbClient.class))));
controller = tester.controller("api/components");
}
@Test
- public void define_controller() throws Exception {
+ public void define_controller() {
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
assertThat(controller.since()).isEqualTo("4.2");
}
@Test
- public void define_suggestions_action() throws Exception {
+ public void define_suggestions_action() {
WebService.Action action = controller.action("suggestions");
assertThat(action).isNotNull();
assertThat(action.isInternal()).isTrue();
}
@Test
- public void define_app_action() throws Exception {
+ public void define_app_action() {
WebService.Action action = controller.action("app");
assertThat(action).isNotNull();
assertThat(action.isInternal()).isTrue();
}
@Test
- public void define_search_action() throws Exception {
+ public void define_search_action() {
WebService.Action action = controller.action("search");
assertThat(action).isNotNull();
assertThat(action.isInternal()).isTrue();
WsTester tester = new WsTester(new EventsWs());
@Test
- public void define_ws() throws Exception {
+ public void define_ws() {
WebService.Controller controller = tester.controller("api/events");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
WebService.Controller controller;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
WsTester tester = new WsTester(new ProjectsWs());
controller = tester.controller("api/projects");
}
@Test
- public void define_controller() throws Exception {
+ public void define_controller() {
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
assertThat(controller.since()).isEqualTo("2.10");
}
@Test
- public void define_index_action() throws Exception {
+ public void define_index_action() {
WebService.Action action = controller.action("index");
assertThat(action).isNotNull();
assertThat(action.handler()).isInstanceOf(RailsHandler.class);
}
@Test
- public void define_create_action() throws Exception {
+ public void define_create_action() {
WebService.Action action = controller.action("create");
assertThat(action).isNotNull();
assertThat(action.handler()).isInstanceOf(RailsHandler.class);
}
@Test
- public void define_destroy_action() throws Exception {
+ public void define_destroy_action() {
WebService.Action action = controller.action("destroy");
assertThat(action).isNotNull();
assertThat(action.handler()).isInstanceOf(RailsHandler.class);
WebService.Controller controller;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
WsTester tester = new WsTester(new ResourcesWs());
controller = tester.controller("api/resources");
}
@Test
- public void define_controller() throws Exception {
+ public void define_controller() {
assertThat(controller).isNotNull();
assertThat(controller.since()).isEqualTo("2.10");
assertThat(controller.description()).isNotEmpty();
}
@Test
- public void define_index_action() throws Exception {
+ public void define_index_action() {
WebService.Action action = controller.action("index");
assertThat(action).isNotNull();
assertThat(action.handler()).isInstanceOf(RailsHandler.class);
}
@Test
- public void define_search_action() throws Exception {
+ public void define_search_action() {
WebService.Action action = controller.action("search");
assertThat(action).isNotNull();
assertThat(action.handler()).isInstanceOf(RailsHandler.class);
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis(),
new ComponentDao(), new AuthorizationDao(dbTester.myBatis()), new ComponentIndexDao()
public class ComputationContainerTest {
@Test
- public void componentClasses() throws Exception {
+ public void componentClasses() {
assertThat(ComputationContainer.componentClasses()).isNotEmpty();
}
}
ComputationContext sut = new ComputationContext(mock(BatchReportReader.class), mock(ComponentDto.class));
@Test(expected = IllegalStateException.class)
- public void setProjectSettings() throws Exception {
+ public void setProjectSettings() {
sut.setProjectSettings(mock(Settings.class));
sut.setProjectSettings(mock(Settings.class));
}
ProjectSettingsFactory settingsFactory = mock(ProjectSettingsFactory.class, Mockito.RETURNS_DEEP_STUBS);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), new ComponentDao(), new SnapshotDao(system));
sut = new ComputationService(dbClient, steps, activityService, settingsFactory, tempFolder, system);
}
@Test
- public void handle_error_during_queue_pop() throws Exception {
+ public void handle_error_during_queue_pop() {
when(queue.pop()).thenThrow(new IllegalStateException());
sut.run();
}
@Test
- public void add_report_to_queue() throws Exception {
+ public void add_report_to_queue() {
// must:
// 1. insert metadata in db
// 2. copy report content to directory /data/analysis
}
@Test
- public void find_by_project_key() throws Exception {
+ public void find_by_project_key() {
sut.add("P1", generateData());
assertThat(sut.selectByProjectKey("P1")).hasSize(1).extracting("projectKey").containsExactly("P1");
assertThat(sut.selectByProjectKey("P2")).isEmpty();
}
@Test
- public void do_not_pop_corrupted_item() throws Exception {
+ public void do_not_pop_corrupted_item() {
ReportQueue.Item item = sut.add("P1", generateData());
// emulate corruption: file is missing on FS
}
@Test
- public void clear() throws Exception {
+ public void clear() {
sut.add("P1", generateData());
sut.add("P2", generateData());
assertThat(analysisDir()).exists().isDirectory();
}
@Test
- public void clear_do_not_fail_when_directory_do_not_exist() throws Exception {
+ public void clear_do_not_fail_when_directory_do_not_exist() {
sut.clear();
sut.clear();
}
@Test(expected = IllegalStateException.class)
- public void add_on_non_existent_project() throws Exception {
+ public void add_on_non_existent_project() {
sut.add("UNKNOWN_PROJECT_KEY", generateData());
}
@Test
- public void reset_to_pending_status() throws Exception {
+ public void reset_to_pending_status() {
// 2 pending
sut.add("P1", generateData());
sut.add("P2", generateData());
}
@Test
- public void insert_multiple_reports() throws Exception {
+ public void insert_multiple_reports() {
db.prepareDbUnit(getClass(), "empty.xml");
AnalysisReportDto report1 = newDefaultAnalysisReport().setUuid("UUID_1");
}
@After
- public void after() throws Exception {
+ public void after() {
sut.afterReportProcessing();
}
@Test
- public void store_issues_on_disk() throws Exception {
+ public void store_issues_on_disk() {
process();
assertThat(Iterators.getOnlyElement(outputIssues.traverse()).key()).isEqualTo("ISSUE_A");
}
@Test
- public void copy_rule_tags_on_new_issues() throws Exception {
+ public void copy_rule_tags_on_new_issues() {
inputIssue.setIsNew(true);
rule.setTags(ImmutableSet.of("bug", "performance"));
rule.setSystemTags(ImmutableSet.of("blocker"));
}
@Test
- public void do_not_copy_rule_tags_on_existing_issues() throws Exception {
+ public void do_not_copy_rule_tags_on_existing_issues() {
inputIssue.setIsNew(false);
rule.setTags(ImmutableSet.of("bug", "performance"));
rule.setSystemTags(ImmutableSet.of("blocker"));
}
@Test
- public void guess_author_of_new_issues() throws Exception {
+ public void guess_author_of_new_issues() {
inputIssue.setIsNew(true);
inputIssue.setLine(3);
when(lineCache.lineAuthor(3)).thenReturn("charlie");
}
@Test
- public void do_not_fail_if_missing_author_for_new_issues() throws Exception {
+ public void do_not_fail_if_missing_author_for_new_issues() {
inputIssue.setIsNew(true);
inputIssue.setLine(3);
when(lineCache.lineAuthor(3)).thenReturn(null);
}
@Test
- public void do_not_guess_author_of_existing_issues() throws Exception {
+ public void do_not_guess_author_of_existing_issues() {
inputIssue.setIsNew(false);
inputIssue.setLine(3);
when(lineCache.lineAuthor(3)).thenReturn("charlie");
}
@Test
- public void auto_assign_new_issues() throws Exception {
+ public void auto_assign_new_issues() {
inputIssue.setIsNew(true);
inputIssue.setAuthorLogin("charlie");
when(scmAccountCache.getNullable("charlie")).thenReturn("char.lie");
}
@Test
- public void do_not_auto_assign_existing_issues() throws Exception {
+ public void do_not_auto_assign_existing_issues() {
inputIssue.setIsNew(false);
inputIssue.setAuthorLogin("charlie");
when(scmAccountCache.getNullable("charlie")).thenReturn("char.lie");
}
@Test
- public void do_not_override_author_and_assignee_set_by_old_batch_plugins() throws Exception {
+ public void do_not_override_author_and_assignee_set_by_old_batch_plugins() {
inputIssue.setIsNew(true);
// these fields were provided during project analysis, for instance
}
@Test
- public void assign_default_assignee_when_available() throws Exception {
+ public void assign_default_assignee_when_available() {
inputIssue.setIsNew(true);
String wolinski = "wolinski";
when(context.getProjectSettings().getString(CoreProperties.DEFAULT_ISSUE_ASSIGNEE)).thenReturn(wolinski);
}
@Test
- public void do_not_assign_default_assignee_when_not_found_in_index() throws Exception {
+ public void do_not_assign_default_assignee_when_not_found_in_index() {
inputIssue.setIsNew(true);
String wolinski = "wolinski";
when(context.getProjectSettings().getString(CoreProperties.DEFAULT_ISSUE_ASSIGNEE)).thenReturn(wolinski);
public static DbTester dbTester = new DbTester();
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
}
@Test
- public void load_by_key() throws Exception {
+ public void load_by_key() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), new RuleDao());
RuleCacheLoader loader = new RuleCacheLoader(dbClient);
}
@Test
- public void load_by_keys_is_not_supported() throws Exception {
+ public void load_by_keys_is_not_supported() {
DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), new RuleDao());
RuleCacheLoader loader = new RuleCacheLoader(dbClient);
try {
public class RuleCacheTest {
@Test
- public void ruleName() throws Exception {
+ public void ruleName() {
RuleCacheLoader loader = mock(RuleCacheLoader.class);
when(loader.load(RuleKey.of("squid", "R002"))).thenReturn(new RuleDto().setName("Rule Two"));
RuleCache cache = new RuleCache(loader);
public static EsTester esTester = new EsTester().addDefinitions(new UserIndexDefinition(new Settings()));
@Before
- public void setUp() throws Exception {
+ public void setUp() {
esTester.truncateIndices();
}
}
@Test
- public void load_by_multiple_scm_accounts_is_not_supported_yet() throws Exception {
+ public void load_by_multiple_scm_accounts_is_not_supported_yet() {
UserIndex index = new UserIndex(esTester.client());
ScmAccountCacheLoader loader = new ScmAccountCacheLoader(index);
try {
}
@Test
- public void line_author_from_report() throws Exception {
+ public void line_author_from_report() {
BatchReportWriter reportWriter = new BatchReportWriter(dir);
reportWriter.writeComponentChangesets(BatchReport.Changesets.newBuilder()
.setComponentRef(123_456_789)
}
@Test(expected = IllegalStateException.class)
- public void fail_when_component_ref_is_not_filled() throws Exception {
+ public void fail_when_component_ref_is_not_filled() {
sut.init("ANY_UUID", null, new BatchReportReader(dir));
sut.lineAuthor(0);
}
MetricCache sut;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.prepareDbUnit(getClass(), "metrics.xml");
sut = new MetricCache(new DbClient(db.database(), db.myBatis(), new MetricDao()));
}
@Test
- public void cache_give_access_to_enabled_metrics() throws Exception {
+ public void cache_give_access_to_enabled_metrics() {
assertThat(sut.get("ncloc").getId()).isEqualTo(1);
assertThat(sut.get("coverage").getId()).isEqualTo(2);
}
@Test(expected = NotFoundException.class)
- public void fail_when_metric_not_found() throws Exception {
+ public void fail_when_metric_not_found() {
sut.get("complexity");
}
}
public class ComputeFileSourceDataTest {
@Test
- public void compute_one_line() throws Exception {
+ public void compute_one_line() {
ComputeFileSourceData computeFileSourceData = new ComputeFileSourceData(
newArrayList("line1").iterator(),
Lists.<LineReader>newArrayList(new MockLineReader()),
}
@Test
- public void compute_two_lines() throws Exception {
+ public void compute_two_lines() {
ComputeFileSourceData computeFileSourceData = new ComputeFileSourceData(
newArrayList("line1", "line2").iterator(),
Lists.<LineReader>newArrayList(new MockLineReader()),
}
@Test
- public void compute_missing_last_line() throws Exception {
+ public void compute_missing_last_line() {
ComputeFileSourceData computeFileSourceData = new ComputeFileSourceData(
newArrayList("line1").iterator(),
Lists.<LineReader>newArrayList(new MockLineReader()),
}
@Test
- public void remove_tabs_and_spaces_in_line_hashes() throws Exception {
+ public void remove_tabs_and_spaces_in_line_hashes() {
String refLineHashes = new ComputeFileSourceData(
newArrayList("line1").iterator(),
Lists.<LineReader>newArrayList(new MockLineReader()),
}
@Test
- public void compute_line_hashes_of_empty_lines() throws Exception {
+ public void compute_line_hashes_of_empty_lines() {
assertThat(new ComputeFileSourceData(
newArrayList(" ").iterator(),
Lists.<LineReader>newArrayList(new MockLineReader()),
public class CoverageLineReaderTest {
@Test
- public void set_coverage() throws Exception {
+ public void set_coverage() {
CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(BatchReport.Coverage.newBuilder()
.setLine(1)
.setConditions(10)
}
@Test
- public void set_coverage_on_uncovered_lines() throws Exception {
+ public void set_coverage_on_uncovered_lines() {
CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(BatchReport.Coverage.newBuilder()
.setLine(1)
.setUtHits(false)
}
@Test
- public void set_coverage_without_line_hits() throws Exception {
+ public void set_coverage_without_line_hits() {
CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(BatchReport.Coverage.newBuilder()
.setLine(1)
.build()).iterator());
}
@Test
- public void set_overall_line_hits_with_only_ut() throws Exception {
+ public void set_overall_line_hits_with_only_ut() {
CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(BatchReport.Coverage.newBuilder()
.setLine(1)
.setUtHits(true)
}
@Test
- public void set_overall_line_hits_with_only_it() throws Exception {
+ public void set_overall_line_hits_with_only_it() {
CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(BatchReport.Coverage.newBuilder()
.setLine(1)
.setUtHits(false)
}
@Test
- public void set_overall_line_hits_with_ut_and_it() throws Exception {
+ public void set_overall_line_hits_with_ut_and_it() {
CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(BatchReport.Coverage.newBuilder()
.setLine(1)
.setUtHits(true)
}
@Test
- public void nothing_to_do_when_no_coverage_info() throws Exception {
+ public void nothing_to_do_when_no_coverage_info() {
CoverageLineReader computeCoverageLine = new CoverageLineReader(Collections.<BatchReport.Coverage>emptyList().iterator());
FileSourceDb.Line.Builder lineBuilder = FileSourceDb.Data.newBuilder().addLinesBuilder().setLine(1);
}
@Test
- public void nothing_to_do_when_no_coverage_info_for_current_line() throws Exception {
+ public void nothing_to_do_when_no_coverage_info_for_current_line() {
CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(
BatchReport.Coverage.newBuilder()
.setLine(1)
}
@Test
- public void nothing_to_do_when_no_coverage_info_for_next_line() throws Exception {
+ public void nothing_to_do_when_no_coverage_info_for_next_line() {
CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(
BatchReport.Coverage.newBuilder()
.setLine(1)
FileSourceDb.Line.Builder line4 = sourceData.addLinesBuilder().setSource("line4").setLine(4);
@Test
- public void read_nothing() throws Exception {
+ public void read_nothing() {
DuplicationLineReader reader = new DuplicationLineReader(Collections.<BatchReport.Duplication>emptyList());
reader.read(line1);
}
@Test
- public void read_duplication_with_duplicates_on_same_file() throws Exception {
+ public void read_duplication_with_duplicates_on_same_file() {
DuplicationLineReader reader = new DuplicationLineReader(newArrayList(
BatchReport.Duplication.newBuilder()
.setOriginPosition(BatchReport.Range.newBuilder()
}
@Test
- public void read_duplication_with_duplicates_on_other_file() throws Exception {
+ public void read_duplication_with_duplicates_on_other_file() {
DuplicationLineReader reader = new DuplicationLineReader(newArrayList(
BatchReport.Duplication.newBuilder()
.setOriginPosition(BatchReport.Range.newBuilder()
}
@Test
- public void read_duplication_with_duplicates_on_other_file_from_other_project() throws Exception {
+ public void read_duplication_with_duplicates_on_other_file_from_other_project() {
DuplicationLineReader reader = new DuplicationLineReader(newArrayList(
BatchReport.Duplication.newBuilder()
.setOriginPosition(BatchReport.Range.newBuilder()
}
@Test
- public void read_many_duplications() throws Exception {
+ public void read_many_duplications() {
DuplicationLineReader reader = new DuplicationLineReader(newArrayList(
BatchReport.Duplication.newBuilder()
.setOriginPosition(BatchReport.Range.newBuilder()
}
@Test
- public void should_be_sorted_by_line_block() throws Exception {
+ public void should_be_sorted_by_line_block() {
DuplicationLineReader reader = new DuplicationLineReader(newArrayList(
BatchReport.Duplication.newBuilder()
.setOriginPosition(BatchReport.Range.newBuilder()
}
@Test
- public void should_be_sorted_by_line_length() throws Exception {
+ public void should_be_sorted_by_line_length() {
DuplicationLineReader reader = new DuplicationLineReader(newArrayList(
BatchReport.Duplication.newBuilder()
.setOriginPosition(BatchReport.Range.newBuilder()
public class RangeOffsetHelperTest {
@Test
- public void append_range() throws Exception {
+ public void append_range() {
assertThat(RangeOffsetHelper.offsetToString(BatchReport.Range.newBuilder()
.setStartLine(1).setEndLine(1)
.setStartOffset(2).setEndOffset(3)
}
@Test
- public void append_range_not_finishing_in_current_line() throws Exception {
+ public void append_range_not_finishing_in_current_line() {
assertThat( RangeOffsetHelper.offsetToString(BatchReport.Range.newBuilder()
.setStartLine(1).setEndLine(3)
.setStartOffset(2).setEndOffset(3)
}
@Test
- public void append_range_that_began_in_previous_line_and_finish_in_current_line() throws Exception {
+ public void append_range_that_began_in_previous_line_and_finish_in_current_line() {
assertThat(RangeOffsetHelper.offsetToString(BatchReport.Range.newBuilder()
.setStartLine(1).setEndLine(3)
.setStartOffset(2).setEndOffset(3)
}
@Test
- public void append_range_that_began_in_previous_line_and_not_finishing_in_current_line() throws Exception {
+ public void append_range_that_began_in_previous_line_and_not_finishing_in_current_line() {
assertThat(RangeOffsetHelper.offsetToString(BatchReport.Range.newBuilder()
.setStartLine(1).setEndLine(3)
.setStartOffset(2).setEndOffset(3)
}
@Test
- public void do_nothing_if_offset_is_empty() throws Exception {
+ public void do_nothing_if_offset_is_empty() {
assertThat(RangeOffsetHelper.offsetToString(BatchReport.Range.newBuilder()
.setStartLine(1).setEndLine(1)
.setStartOffset(0).setEndOffset(0)
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
if (sut != null) {
sut.close();
}
}
@Test
- public void read_report() throws Exception {
+ public void read_report() {
sut = new ReportIterator<>(file, BatchReport.Coverage.PARSER);
assertThat(sut.next().getLine()).isEqualTo(1);
}
@Test
- public void do_not_fail_when_calling_has_next_with_iterator_already_closed() throws Exception {
+ public void do_not_fail_when_calling_has_next_with_iterator_already_closed() {
sut = new ReportIterator<>(file, BatchReport.Coverage.PARSER);
assertThat(sut.next().getLine()).isEqualTo(1);
assertThat(sut.hasNext()).isFalse();
public class ScmLineReaderTest {
@Test
- public void set_scm() throws Exception {
+ public void set_scm() {
BatchReport.Changesets scmReport = BatchReport.Changesets.newBuilder()
.addChangeset(BatchReport.Changesets.Changeset.newBuilder()
.setAuthor("john")
}
@Test
- public void set_only_author() throws Exception {
+ public void set_only_author() {
BatchReport.Changesets scmReport = BatchReport.Changesets.newBuilder()
.addChangeset(BatchReport.Changesets.Changeset.newBuilder()
.setAuthor("john")
}
@Test
- public void set_only_date() throws Exception {
+ public void set_only_date() {
BatchReport.Changesets scmReport = BatchReport.Changesets.newBuilder()
.addChangeset(BatchReport.Changesets.Changeset.newBuilder()
.setDate(123456789L)
}
@Test
- public void set_only_revision() throws Exception {
+ public void set_only_revision() {
BatchReport.Changesets scmReport = BatchReport.Changesets.newBuilder()
.addChangeset(BatchReport.Changesets.Changeset.newBuilder()
.setRevision("rev-1")
}
@Test
- public void fail_when_changeset_is_empty() throws Exception {
+ public void fail_when_changeset_is_empty() {
BatchReport.Changesets scmReport = BatchReport.Changesets.newBuilder()
.addChangeset(BatchReport.Changesets.Changeset.newBuilder()
.build())
FileSourceDb.Line.Builder line4 = sourceData.addLinesBuilder().setSource("line4").setLine(4);
@Test
- public void read_nothing() throws Exception {
+ public void read_nothing() {
SymbolsLineReader symbolsLineReader = new SymbolsLineReader(Collections.<BatchReport.Symbols.Symbol>emptyList());
symbolsLineReader.read(line1);
}
@Test
- public void read_symbols() throws Exception {
+ public void read_symbols() {
List<BatchReport.Symbols.Symbol> symbols = newArrayList(
BatchReport.Symbols.Symbol.newBuilder()
.setDeclaration(BatchReport.Range.newBuilder()
}
@Test
- public void read_symbols_with_reference_on_same_line() throws Exception {
+ public void read_symbols_with_reference_on_same_line() {
List<BatchReport.Symbols.Symbol> symbols = newArrayList(
BatchReport.Symbols.Symbol.newBuilder()
.setDeclaration(BatchReport.Range.newBuilder()
}
@Test
- public void read_symbols_with_two_references() throws Exception {
+ public void read_symbols_with_two_references() {
List<BatchReport.Symbols.Symbol> symbols = newArrayList(
BatchReport.Symbols.Symbol.newBuilder()
.setDeclaration(BatchReport.Range.newBuilder()
}
@Test
- public void read_symbols_with_two_references_on_the_same_line() throws Exception {
+ public void read_symbols_with_two_references_on_the_same_line() {
List<BatchReport.Symbols.Symbol> symbols = newArrayList(
BatchReport.Symbols.Symbol.newBuilder()
.setDeclaration(BatchReport.Range.newBuilder()
}
@Test
- public void read_symbols_when_reference_line_is_before_declaration_line() throws Exception {
+ public void read_symbols_when_reference_line_is_before_declaration_line() {
List<BatchReport.Symbols.Symbol> symbols = newArrayList(
BatchReport.Symbols.Symbol.newBuilder()
.setDeclaration(BatchReport.Range.newBuilder()
}
@Test
- public void read_many_symbols_on_lines() throws Exception {
+ public void read_many_symbols_on_lines() {
List<BatchReport.Symbols.Symbol> symbols = newArrayList(
BatchReport.Symbols.Symbol.newBuilder()
.setDeclaration(BatchReport.Range.newBuilder()
}
@Test
- public void symbol_declaration_should_be_sorted_by_offset() throws Exception {
+ public void symbol_declaration_should_be_sorted_by_offset() {
List<BatchReport.Symbols.Symbol> symbols = newArrayList(
BatchReport.Symbols.Symbol.newBuilder()
.setDeclaration(BatchReport.Range.newBuilder()
}
@Test
- public void symbol_declaration_should_be_sorted_by_line() throws Exception {
+ public void symbol_declaration_should_be_sorted_by_line() {
List<BatchReport.Symbols.Symbol> symbols = newArrayList(
BatchReport.Symbols.Symbol.newBuilder()
.setDeclaration(BatchReport.Range.newBuilder()
}
@Test
- public void read_symbols_defined_on_many_lines() throws Exception {
+ public void read_symbols_defined_on_many_lines() {
List<BatchReport.Symbols.Symbol> symbols = newArrayList(
BatchReport.Symbols.Symbol.newBuilder()
.setDeclaration(BatchReport.Range.newBuilder()
}
@Test
- public void read_symbols_declared_on_a_whole_line() throws Exception {
+ public void read_symbols_declared_on_a_whole_line() {
List<BatchReport.Symbols.Symbol> symbols = newArrayList(
BatchReport.Symbols.Symbol.newBuilder()
.setDeclaration(BatchReport.Range.newBuilder()
ApplyPermissionsStep step = new ApplyPermissionsStep(indexer);
@Test
- public void index_issue_permissions() throws Exception {
+ public void index_issue_permissions() {
step.execute(mock(ComputationContext.class));
verify(indexer).index();
}
*/
public abstract class BaseStepTest {
- protected abstract ComputationStep step() throws IOException;
+ protected abstract ComputationStep step();
@Test
- public void test_metadata() throws Exception {
+ public void test_metadata() {
assertThat(step().toString()).isNotEmpty();
assertThat(step().getDescription()).isNotEmpty();
assertThat(step().supportedProjectQualifiers().length).isGreaterThan(0);
}
@Test
- public void get_uuid_from_ref() throws Exception {
+ public void get_uuid_from_ref() {
BatchReportWriter writer = new BatchReportWriter(reportDir);
writer.writeComponent(BatchReport.Component.newBuilder()
.setRef(1)
public class ComputationStepsTest {
@Test
- public void ordered_steps() throws Exception {
+ public void ordered_steps() {
ComputationSteps registry = new ComputationSteps(
// unordered
mock(ApplyPermissionsStep.class),
}
@Test
- public void fail_if_a_step_is_not_registered_in_picocontainer() throws Exception {
+ public void fail_if_a_step_is_not_registered_in_picocontainer() {
try {
new ComputationSteps(mock(ParseReportStep.class));
fail();
IndexComponentsStep sut = new IndexComponentsStep(resourceIndexerDao);
@Test
- public void call_indexProject_of_dao() throws IOException {
+ public void call_indexProject_of_dao() {
ComponentDto project = mock(ComponentDto.class);
when(project.getId()).thenReturn(123L);
ComputationContext context = new ComputationContext(mock(BatchReportReader.class), project);
IndexIssuesStep sut;
@Test
- public void call_indexers() throws Exception {
+ public void call_indexers() {
IssueAuthorizationIndexer authorizationIndexer = mock(IssueAuthorizationIndexer.class);
IssueIndexer issueIndexer = mock(IssueIndexer.class);
sut = new IndexIssuesStep(authorizationIndexer, issueIndexer);
DbClient dbClient;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), new FileSourceDao(null));
}
@Override
- protected ComputationStep step() throws IOException {
+ protected ComputationStep step() {
SourceLineIndexer sourceLineIndexer = new SourceLineIndexer(dbClient, esTester.client());
sourceLineIndexer.setEnabled(true);
return new IndexSourceLinesStep(sourceLineIndexer);
}
@Test
- public void supported_project_qualifiers() throws Exception {
+ public void supported_project_qualifiers() {
assertThat(step().supportedProjectQualifiers()).containsOnly(Qualifiers.PROJECT);
}
DbClient dbClient;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), new FileSourceDao(null));
}
@Override
- protected ComputationStep step() throws IOException {
+ protected ComputationStep step() {
TestIndexer testIndexer = new TestIndexer(dbClient, esTester.client());
testIndexer.setEnabled(true);
return new IndexTestsStep(testIndexer);
}
@Test
- public void supported_project_qualifiers() throws Exception {
+ public void supported_project_qualifiers() {
assertThat(step().supportedProjectQualifiers()).containsOnly(Qualifiers.PROJECT);
}
IndexViewsStep sut = new IndexViewsStep(indexer);
@Test
- public void index_views() throws Exception {
+ public void index_views() {
when(context.getProject()).thenReturn(ComponentTesting.newProjectDto("ABCD").setQualifier(Qualifiers.VIEW));
sut.execute(context);
PersistComponentLinksStep step;
@Before
- public void setup() throws Exception {
+ public void setup() {
session = dbTester.myBatis().openSession(false);
dao = new ComponentLinkDao();
DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), dao);
}
@Override
- protected ComputationStep step() throws IOException {
+ protected ComputationStep step() {
return step;
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void execute_only_on_projects() throws Exception {
+ public void execute_only_on_projects() {
assertThat(step.supportedProjectQualifiers()).containsOnly("TRK");
}
}
@Override
- protected ComputationStep step() throws IOException {
+ protected ComputationStep step() {
return sut;
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void nothing_to_do_when_no_duplication() throws Exception {
+ public void nothing_to_do_when_no_duplication() {
saveDuplicationMetric();
initReportWithProjectAndFile();
}
@Test
- public void persist_duplications_on_same_file() throws Exception {
+ public void persist_duplications_on_same_file() {
MetricDto duplicationMetric = saveDuplicationMetric();
BatchReportWriter writer = initReportWithProjectAndFile();
}
@Test
- public void persist_duplications_on_same_file_linked_on_a_folder() throws Exception {
+ public void persist_duplications_on_same_file_linked_on_a_folder() {
saveDuplicationMetric();
BatchReportWriter writer = new BatchReportWriter(reportDir);
}
@Test
- public void persist_duplications_on_same_file_linked_on_sub_folder() throws Exception {
+ public void persist_duplications_on_same_file_linked_on_sub_folder() {
saveDuplicationMetric();
BatchReportWriter writer = new BatchReportWriter(reportDir);
}
@Test
- public void persist_duplications_on_different_files() throws Exception {
+ public void persist_duplications_on_different_files() {
saveDuplicationMetric();
BatchReportWriter writer = initReportWithProjectAndFile();
}
@Test
- public void persist_duplications_on_different_projects() throws Exception {
+ public void persist_duplications_on_different_projects() {
saveDuplicationMetric();
BatchReportWriter writer = initReportWithProjectAndFile();
assertThat(dto.get("textValue")).isEqualTo("<duplications><g><b s=\"1\" l=\"5\" r=\"PROJECT_KEY:file\"/><b s=\"6\" l=\"5\" r=\"PROJECT2_KEY:file2\"/></g></duplications>");
}
- private BatchReportWriter initReportWithProjectAndFile() throws IOException {
+ private BatchReportWriter initReportWithProjectAndFile() {
BatchReportWriter writer = new BatchReportWriter(reportDir);
writer.writeMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
PersistEventsStep step;
@Before
- public void setup() throws Exception {
+ public void setup() {
session = dbTester.myBatis().openSession(false);
dao = new EventDao();
DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), dao);
}
@Override
- protected ComputationStep step() throws IOException {
+ protected ComputationStep step() {
return step;
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void execute_only_on_projects() throws Exception {
+ public void execute_only_on_projects() {
assertThat(step.supportedProjectQualifiers()).containsOnly("TRK");
}
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Override
- protected ComputationStep step() throws IOException {
+ protected ComputationStep step() {
return new PersistFileDependenciesStep(dbClient, system2);
}
@Test
- public void supported_project_qualifiers() throws Exception {
+ public void supported_project_qualifiers() {
assertThat(step().supportedProjectQualifiers()).containsOnly(Qualifiers.PROJECT);
}
@Test
- public void persist_file_dependencies() throws Exception {
+ public void persist_file_dependencies() {
writer.writeComponent(BatchReport.Component.newBuilder()
.setRef(1)
.setType(Constants.ComponentType.PROJECT)
}
@Test
- public void nothing_to_persist() throws Exception {
+ public void nothing_to_persist() {
writer.writeComponent(BatchReport.Component.newBuilder()
.setRef(1)
.setType(Constants.ComponentType.PROJECT)
}
@Override
- protected ComputationStep step() throws IOException {
+ protected ComputationStep step() {
return sut;
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
ComputationStep step;
@Override
- protected ComputationStep step() throws IOException {
+ protected ComputationStep step() {
return step;
}
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void insert_new_issue() throws Exception {
+ public void insert_new_issue() {
dbTester.prepareDbUnit(getClass(), "insert_new_issue.xml");
issueCache.newAppender().append(new DefaultIssue()
}
@Test
- public void close_issue() throws Exception {
+ public void close_issue() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
issueCache.newAppender().append(new DefaultIssue()
}
@Test
- public void add_comment() throws Exception {
+ public void add_comment() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
issueCache.newAppender().append(new DefaultIssue()
}
@Test
- public void add_change() throws Exception {
+ public void add_change() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
issueCache.newAppender().append(new DefaultIssue()
private BatchReport.Component component;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbClient = mock(DbClient.class, Mockito.RETURNS_DEEP_STUBS);
ruleCache = mock(RuleCache.class, Mockito.RETURNS_DEEP_STUBS);
metricCache = mock(MetricCache.class, Mockito.RETURNS_DEEP_STUBS);
}
@Test
- public void map_full_batch_measure() throws Exception {
+ public void map_full_batch_measure() {
BatchReport.Measure batchMeasure = BatchReport.Measure.newBuilder()
.setValueType(Constants.MeasureValueType.DOUBLE)
.setDoubleValue(123.123d)
}
@Test
- public void map_minimal_batch_measure() throws Exception {
+ public void map_minimal_batch_measure() {
BatchReport.Measure batchMeasure = BatchReport.Measure.newBuilder()
.setValueType(Constants.MeasureValueType.INT)
.setMetricKey("metric-key")
}
@Test
- public void map_boolean_batch_measure() throws Exception {
+ public void map_boolean_batch_measure() {
BatchReport.Measure batchMeasure = BatchReport.Measure.newBuilder()
.setValueType(Constants.MeasureValueType.BOOLEAN)
.setBooleanValue(true)
}
@Test
- public void map_double_batch_measure() throws Exception {
+ public void map_double_batch_measure() {
BatchReport.Measure batchMeasure = BatchReport.Measure.newBuilder()
.setValueType(Constants.MeasureValueType.DOUBLE)
.setDoubleValue(3.2)
}
@Test
- public void map_int_batch_measure() throws Exception {
+ public void map_int_batch_measure() {
BatchReport.Measure batchMeasure = BatchReport.Measure.newBuilder()
.setValueType(Constants.MeasureValueType.INT)
.setIntValue(3)
}
@Test
- public void map_long_batch_measure() throws Exception {
+ public void map_long_batch_measure() {
BatchReport.Measure batchMeasure = BatchReport.Measure.newBuilder()
.setValueType(Constants.MeasureValueType.LONG)
.setLongValue(3L)
}
@Test(expected = IllegalStateException.class)
- public void fail_when_no_metric_key() throws Exception {
+ public void fail_when_no_metric_key() {
BatchReport.Measure measure = BatchReport.Measure.newBuilder()
.setValueType(MeasureValueType.STRING)
.setStringValue("string-value")
}
@Test(expected = IllegalStateException.class)
- public void fail_when_no_value() throws Exception {
+ public void fail_when_no_value() {
BatchReport.Measure measure = BatchReport.Measure.newBuilder()
.setMetricKey("repo:metric-key")
.build();
}
@Test(expected = IllegalStateException.class)
- public void fail_when_forbid_metric() throws Exception {
+ public void fail_when_forbid_metric() {
BatchReport.Measure measure = BatchReport.Measure.newBuilder()
.setMetricKey("duplications_data")
.build();
}
@Override
- protected ComputationStep step() throws IOException {
+ protected ComputationStep step() {
return sut;
}
}
}
@Override
- protected ComputationStep step() throws IOException {
+ protected ComputationStep step() {
return sut;
}
@Test
- public void persist_number_of_days_since_last_commit_from_report() throws Exception {
+ public void persist_number_of_days_since_last_commit_from_report() {
long threeDaysAgo = DateUtils.addDays(new Date(), -3).getTime();
BatchReportWriter reportWriter = initReportWithProjectAndFile();
reportWriter.writeComponentChangesets(
}
@Test
- public void persist_number_of_days_since_last_commit_from_index() throws Exception {
+ public void persist_number_of_days_since_last_commit_from_index() {
Date sixDaysAgo = DateUtils.addDays(new Date(), -6);
when(sourceLineIndex.lastCommitDateOnProject("project-uuid")).thenReturn(sixDaysAgo);
initReportWithProjectAndFile();
}
@Test
- public void no_scm_information_in_report_and_index() throws Exception {
+ public void no_scm_information_in_report_and_index() {
initReportWithProjectAndFile();
ComputationContext context = new ComputationContext(new BatchReportReader(dir), ComponentTesting.newProjectDto("project-uuid"));
db.assertDbUnit(getClass(), "empty.xml");
}
- private BatchReportWriter initReportWithProjectAndFile() throws IOException {
+ private BatchReportWriter initReportWithProjectAndFile() {
BatchReportWriter writer = new BatchReportWriter(dir);
writer.writeMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
MyBatis.closeQuietly(session);
}
@Override
- protected ComputationStep step() throws IOException {
+ protected ComputationStep step() {
return sut;
}
@Test
- public void no_test_in_database_and_batch_report() throws Exception {
+ public void no_test_in_database_and_batch_report() {
sut.execute(new ComputationContext(new BatchReportReader(reportDir), newProjectDto()));
assertThat(dbClient.fileSourceDao().selectTest(TEST_FILE_UUID_1)).isNull();
}
@Test
- public void insert_several_tests_in_a_report() throws Exception {
+ public void insert_several_tests_in_a_report() {
BatchReportWriter writer = new BatchReportWriter(reportDir);
List<BatchReport.Test> batchTests = Arrays.asList(
newTest(1), newTest(2)
}
@Test
- public void insert_all_data_of_a_test() throws Exception {
+ public void insert_all_data_of_a_test() {
BatchReportWriter writer = new BatchReportWriter(reportDir);
writer.writeTests(TEST_FILE_REF_1, Arrays.asList(newTest(1)));
writer.writeCoverageDetails(TEST_FILE_REF_1, Arrays.asList(newCoverageDetail(1, MAIN_FILE_REF_1)));
}
@Test
- public void insert_tests_without_coverage_details() throws Exception {
+ public void insert_tests_without_coverage_details() {
BatchReportWriter writer = new BatchReportWriter(reportDir);
List<BatchReport.Test> batchTests = Arrays.asList(newTest(1));
writer.writeTests(TEST_FILE_REF_1, batchTests);
}
@Test
- public void insert_coverage_details_not_taken_into_account() throws Exception {
+ public void insert_coverage_details_not_taken_into_account() {
BatchReportWriter writer = new BatchReportWriter(reportDir);
List<BatchReport.Test> batchTests = Arrays.asList(newTest(1));
writer.writeTests(TEST_FILE_REF_1, batchTests);
}
@Test
- public void aggregate_coverage_details() throws Exception {
+ public void aggregate_coverage_details() {
BatchReportWriter writer = new BatchReportWriter(reportDir);
writer.writeTests(TEST_FILE_REF_1, Arrays.asList(newTest(1)));
writer.writeCoverageDetails(TEST_FILE_REF_1, Arrays.asList(
}
@Test
- public void update_existing_test() throws Exception {
+ public void update_existing_test() {
// ARRANGE
dbClient.fileSourceDao().insert(session, new FileSourceDto()
.setProjectUuid(PROJECT_UUID)
.build();
}
- private BatchReportWriter initBasicReport() throws IOException {
+ private BatchReportWriter initBasicReport() {
BatchReportWriter writer = new BatchReportWriter(reportDir);
writer.writeMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
public TemporaryFolder temp = new TemporaryFolder();
@Test
- public void call_purge_method_of_the_purge_task() throws IOException {
+ public void call_purge_method_of_the_purge_task() {
ComponentDto project = mock(ComponentDto.class);
when(project.getId()).thenReturn(123L);
when(project.uuid()).thenReturn("UUID-1234");
}
@Test
- public void only_support_views() throws Exception {
+ public void only_support_views() {
assertThat(sut.supportedProjectQualifiers()).containsOnly(Qualifiers.VIEW);
}
}
@Test
- public void do_not_send_notifications_if_no_subscribers() throws Exception {
+ public void do_not_send_notifications_if_no_subscribers() {
when(context.getProject().uuid()).thenReturn("PROJECT_UUID");
when(notifService.hasProjectSubscribersForTypes("PROJECT_UUID", SendIssueNotificationsStep.NOTIF_TYPES)).thenReturn(false);
}
@Test
- public void send_notifications_if_subscribers() throws Exception {
+ public void send_notifications_if_subscribers() {
issueCache.newAppender().append(new DefaultIssue()
.setSeverity(Severity.BLOCKER)).close();
}
@Override
- protected ComputationStep step() throws IOException {
+ protected ComputationStep step() {
return sut;
}
}
}
@Test
- public void one_switch_with_a_snapshot_and_his_children() throws IOException {
+ public void one_switch_with_a_snapshot_and_his_children() {
db.prepareDbUnit(getClass(), "snapshots.xml");
BatchReport.Metadata metadata = BatchReport.Metadata.newBuilder()
public class ComputationWebServiceTest {
@Test
- public void define() throws Exception {
+ public void define() {
ComputationWebService ws = new ComputationWebService(new ComputationWsAction() {
@Override
public void define(WebService.NewController controller) {
ActivityService activityService;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
sut = tester.get(HistoryWsAction.class);
activityService = tester.get(ActivityService.class);
Response response;
@Before
- public void before() throws Exception {
+ public void before() {
queue = mock(ReportQueue.class);
sut = new IsQueueEmptyWebService.IsQueueEmptyWsAction(queue);
private ReportQueue queue;
@Before
- public void setup() throws Exception {
+ public void setup() {
queue = mock(ReportQueue.class);
tester = new WsTester(new ComputationWebService(new QueueWsAction(queue)));
}
}
@Test
- public void define() throws Exception {
+ public void define() {
assertThat(tester.controller(ComputationWebService.API_ENDPOINT).action("queue")).isNotNull();
}
}
}
@Test
- public void define_metadata() throws Exception {
+ public void define_metadata() {
WebService.Context context = new WebService.Context();
WebService.NewController controller = context.createController("api/computation");
sut.define(controller);
WsTester tester = new WsTester(new PropertiesWs());
@Test
- public void define_ws() throws Exception {
+ public void define_ws() {
WebService.Controller controller = tester.controller("api/properties");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
private DbSession session;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dao = new WidgetDao(dbTester.myBatis());
session = dbTester.myBatis().openSession(false);
}
}
@Test
- public void should_select_all() throws Exception {
+ public void should_select_all() {
dbTester.prepareDbUnit(this.getClass(), "before.xml");
session.commit();
}
@Before
- public void before() throws Exception {
+ public void before() {
this.session = db.myBatis().openSession(false);
this.dao = new FakeDao(System2.INSTANCE);
}
}
@Test
- public void can_insert_and_select_by_key() throws Exception {
+ public void can_insert_and_select_by_key() {
long t0 = System.currentTimeMillis() - 1000;
String key = Uuids.create();
}
@Test
- public void synchronize_to_es_after_date() throws Exception {
+ public void synchronize_to_es_after_date() {
long t0 = System.currentTimeMillis() - 1000;
String key = Uuids.create();
Settings settings = new Settings();
@Test
- public void should_start_and_stop_tcp_h2_database() throws Exception {
+ public void should_start_and_stop_tcp_h2_database() {
settings.setProperty(DatabaseProperties.PROP_URL, "jdbc:h2:tcp:localhost");
final EmbeddedDatabase embeddedDatabase = mock(EmbeddedDatabase.class);
}
@Test
- public void should_not_start_mem_h2_database() throws Exception {
+ public void should_not_start_mem_h2_database() {
settings.setProperty(DatabaseProperties.PROP_URL, "jdbc:h2:mem");
final EmbeddedDatabase embeddedDatabase = mock(EmbeddedDatabase.class);
public ExpectedException throwable = ExpectedException.none();
@Test(timeout = 5000)
- public void should_start_and_stop() throws IOException {
+ public void should_start_and_stop() {
int port = NetworkUtils.freePort();
EmbeddedDatabase database = new EmbeddedDatabase(testSettings(port));
}
@Test
- public void should_return_embedded_data_directory() throws Exception {
+ public void should_return_embedded_data_directory() {
Settings settings = testSettings(0);
EmbeddedDatabase database = new EmbeddedDatabase(settings);
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
DbUtils.closeQuietly(connection);
}
public class AddColumnsBuilderTest {
@Test
- public void add_columns_on_h2() throws Exception {
+ public void add_columns_on_h2() {
assertThat(new AddColumnsBuilder(new H2(), "issues")
.addColumn(new AddColumnsBuilder.ColumnDef()
.setName("date_in_ms")
}
@Test
- public void add_columns_on_mysql() throws Exception {
+ public void add_columns_on_mysql() {
assertThat(new AddColumnsBuilder(new MySql(), "issues")
.addColumn(new AddColumnsBuilder.ColumnDef()
.setName("date_in_ms")
}
@Test
- public void add_columns_on_oracle() throws Exception {
+ public void add_columns_on_oracle() {
assertThat(new AddColumnsBuilder(new Oracle(), "issues")
.addColumn(new AddColumnsBuilder.ColumnDef()
.setName("date_in_ms")
}
@Test
- public void add_columns_on_postgresql() throws Exception {
+ public void add_columns_on_postgresql() {
assertThat(new AddColumnsBuilder(new PostgreSql(), "issues")
.addColumn(new AddColumnsBuilder.ColumnDef()
.setName("date_in_ms")
}
@Test
- public void add_columns_on_mssql() throws Exception {
+ public void add_columns_on_mssql() {
assertThat(new AddColumnsBuilder(new MsSql(), "issues")
.addColumn(new AddColumnsBuilder.ColumnDef()
.setName("date_in_ms")
}
@Test
- public void fail_when_column_name_is_in_upper_case() throws Exception {
+ public void fail_when_column_name_is_in_upper_case() {
try {
new AddColumnsBuilder.ColumnDef()
.setName("DATE_IN_MS")
}
@Test
- public void fail_when_column_name_contains_invalid_character() throws Exception {
+ public void fail_when_column_name_contains_invalid_character() {
try {
new AddColumnsBuilder.ColumnDef()
.setName("date-in/ms")
public ExpectedException thrown = ExpectedException.none();
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table persons");
}
DatabaseMigrator migrator;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
migrator = new DatabaseMigrator(dbClient, migrations, serverUpgradeStatus, null);
}
@Test
- public void should_support_only_creation_of_h2_database() throws Exception {
+ public void should_support_only_creation_of_h2_database() {
when(dbClient.database().getDialect()).thenReturn(new MySql());
assertThat(migrator.createDatabase()).isFalse();
}
@Test
- public void fail_if_execute_unknown_migration() throws Exception {
+ public void fail_if_execute_unknown_migration() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Database migration not found: org.xxx.UnknownMigration");
}
@Test
- public void execute_migration() throws Exception {
+ public void execute_migration() {
assertThat(FakeMigrationStep.executed).isFalse();
migrator.executeMigration(FakeMigrationStep.class.getName());
assertThat(FakeMigrationStep.executed).isTrue();
}
@Test
- public void should_create_schema_on_h2() throws Exception {
+ public void should_create_schema_on_h2() {
Dialect supportedDialect = new H2();
when(dbClient.database().getDialect()).thenReturn(supportedDialect);
Connection connection = mock(Connection.class);
public class DropColumnsBuilderTest {
@Test
- public void drop_columns_on_mysql() throws Exception {
+ public void drop_columns_on_mysql() {
assertThat(new DropColumnsBuilder(new MySql(), "issues", "date_in_ms", "name")
.build()).isEqualTo("ALTER TABLE issues DROP COLUMN date_in_ms, DROP COLUMN name");
}
@Test
- public void drop_columns_on_oracle() throws Exception {
+ public void drop_columns_on_oracle() {
assertThat(new DropColumnsBuilder(new Oracle(), "issues", "date_in_ms", "name")
.build()).isEqualTo("ALTER TABLE issues DROP (date_in_ms, name)");
}
@Test
- public void drop_columns_on_postgresql() throws Exception {
+ public void drop_columns_on_postgresql() {
assertThat(new DropColumnsBuilder(new PostgreSql(), "issues", "date_in_ms", "name")
.build()).isEqualTo("ALTER TABLE issues DROP COLUMN date_in_ms, DROP COLUMN name");
}
@Test
- public void drop_columns_on_mssql() throws Exception {
+ public void drop_columns_on_mssql() {
assertThat(new DropColumnsBuilder(new MsSql(), "issues", "date_in_ms", "name")
.build()).isEqualTo("ALTER TABLE issues DROP COLUMN date_in_ms, name");
}
@Test(expected = IllegalStateException.class)
- public void fail_to_drop_columns_on_h2() throws Exception {
+ public void fail_to_drop_columns_on_h2() {
new DropColumnsBuilder(new H2(), "issues", "date_in_ms", "name")
.build();
}
public class MigrationStepsTest {
@Test
- public void check_number_of_migrations() throws Exception {
+ public void check_number_of_migrations() {
assertThat(MigrationSteps.CLASSES).isNotEmpty();
}
}
private PlatformDatabaseMigration underTest = new PlatformDatabaseMigration(rubyBridge, executorService, platform);
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
pool.shutdownNow();
}
private PlatformDatabaseMigration underTest = new PlatformDatabaseMigration(rubyBridge, executorService, platform);
@Test
- public void status_is_NONE_when_component_is_created() throws Exception {
+ public void status_is_NONE_when_component_is_created() {
assertThat(underTest.status()).isEqualTo(DatabaseMigration.Status.NONE);
}
@Test
- public void startedAt_is_null_when_component_is_created() throws Exception {
+ public void startedAt_is_null_when_component_is_created() {
assertThat(underTest.startedAt()).isNull();
}
@Test
- public void failureError_is_null_when_component_is_created() throws Exception {
+ public void failureError_is_null_when_component_is_created() {
assertThat(underTest.failureError()).isNull();
}
@Test
- public void startit_calls_databasemigration_trigger_in_a_separate_thread() throws Exception {
+ public void startit_calls_databasemigration_trigger_in_a_separate_thread() {
when(rubyBridge.databaseMigration()).thenReturn(rubyDatabaseMigration);
when(rubyBridge.railsRoutes()).thenReturn(rubyRailsRoutes);
}
@Test
- public void status_is_SUCCEEDED_and_failure_is_null_when_trigger_runs_without_an_exception() throws Exception {
+ public void status_is_SUCCEEDED_and_failure_is_null_when_trigger_runs_without_an_exception() {
when(rubyBridge.databaseMigration()).thenReturn(rubyDatabaseMigration);
when(rubyBridge.railsRoutes()).thenReturn(rubyRailsRoutes);
}
@Test
- public void status_is_FAILED_and_failure_stores_the_exception_when_trigger_throws_an_exception() throws Exception {
+ public void status_is_FAILED_and_failure_stores_the_exception_when_trigger_throws_an_exception() {
mockTriggerThrowsError();
underTest.startIt();
}
@Test
- public void successive_calls_to_startIt_reset_status_startedAt_and_failureError() throws Exception {
+ public void successive_calls_to_startIt_reset_status_startedAt_and_failureError() {
mockTriggerThrowsError();
underTest.startIt();
public class ProgressTest {
@Test
- public void log_progress() throws Exception {
+ public void log_progress() {
Logger logger = mock(Logger.class);
ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
}
@Test
- public void log_remaining_time() throws Exception {
+ public void log_remaining_time() {
Logger logger = mock(Logger.class);
ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
public class ViolationConvertersTest {
@Test
- public void default_number_of_threads() throws Exception {
+ public void default_number_of_threads() {
assertThat(new ViolationConverters(new Settings()).numberOfThreads()).isEqualTo(ViolationConverters.DEFAULT_THREADS);
}
@Test
- public void configure_number_of_threads() throws Exception {
+ public void configure_number_of_threads() {
Settings settings = new Settings();
settings.setProperty(ViolationConverters.THREADS_PROPERTY, 2);
assertThat(new ViolationConverters(settings).numberOfThreads()).isEqualTo(2);
}
@Test
- public void number_of_threads_should_not_be_negative() throws Exception {
+ public void number_of_threads_should_not_be_negative() {
try {
Settings settings = new Settings();
settings.setProperty(ViolationConverters.THREADS_PROPERTY, -2);
public static DbTester db = new DbTester().schema(ViolationMigrationTest.class, "schema.sql");
@Test
- public void migrate_violations() throws Exception {
+ public void migrate_violations() {
db.prepareDbUnit(getClass(), "migrate_violations.xml");
new ViolationMigrationStep(db.database(), new Settings()).execute();
}
@Test
- public void no_violations_to_migrate() throws Exception {
+ public void no_violations_to_migrate() {
db.prepareDbUnit(getClass(), "no_violations_to_migrate.xml");
new ViolationMigrationStep(db.database(), new Settings()).execute();
ConvertIssueDebtToMinutesMigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(system2.now()).thenReturn(DateUtils.parseDateTime("2014-02-19T19:10:03+0100").getTime());
when(propertiesDao.selectGlobalProperty(WorkDurationConvertor.HOURS_IN_DAY_PROPERTY)).thenReturn(new PropertyDto().setValue("8"));
DevelopmentCostMeasuresMigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(propertiesDao.selectGlobalProperty(WorkDurationConvertor.HOURS_IN_DAY_PROPERTY)).thenReturn(new PropertyDto().setValue("8"));
migration = new DevelopmentCostMeasuresMigrationStep(db.database(), propertiesDao);
IssueChangelogMigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(system2.now()).thenReturn(DateUtils.parseDateTime("2014-02-19T19:10:03+0100").getTime());
when(propertiesDao.selectGlobalProperty(WorkDurationConvertor.HOURS_IN_DAY_PROPERTY)).thenReturn(new PropertyDto().setValue("8"));
}
@Test
- public void convert_data_containing_only_debt_change() throws Exception {
+ public void convert_data_containing_only_debt_change() {
assertThat(migration.convertChangelog("technicalDebt=1|2")).isEqualTo("technicalDebt=1|2");
assertThat(migration.convertChangelog("technicalDebt=100|200")).isEqualTo("technicalDebt=60|120");
assertThat(migration.convertChangelog("technicalDebt=10000|20000")).isEqualTo("technicalDebt=480|960");
}
@Test
- public void convert_data_beginning_with_debt_change() throws Exception {
+ public void convert_data_beginning_with_debt_change() {
assertThat(migration.convertChangelog("technicalDebt=100|200,status=RESOLVED|REOPENED")).isEqualTo("technicalDebt=60|120,status=RESOLVED|REOPENED");
assertThat(migration.convertChangelog("technicalDebt=|200,status=RESOLVED|REOPENED")).isEqualTo("technicalDebt=|120,status=RESOLVED|REOPENED");
assertThat(migration.convertChangelog("technicalDebt=100|,status=RESOLVED|REOPENED")).isEqualTo("technicalDebt=60|,status=RESOLVED|REOPENED");
}
@Test
- public void convert_data_finishing_with_debt_change() throws Exception {
+ public void convert_data_finishing_with_debt_change() {
assertThat(migration.convertChangelog("status=RESOLVED|REOPENED,technicalDebt=100|200")).isEqualTo("status=RESOLVED|REOPENED,technicalDebt=60|120");
assertThat(migration.convertChangelog("status=RESOLVED|REOPENED,technicalDebt=|200")).isEqualTo("status=RESOLVED|REOPENED,technicalDebt=|120");
assertThat(migration.convertChangelog("status=RESOLVED|REOPENED,technicalDebt=100|")).isEqualTo("status=RESOLVED|REOPENED,technicalDebt=60|");
}
@Test
- public void convert_data_with_debt_change_in_the_middle() throws Exception {
+ public void convert_data_with_debt_change_in_the_middle() {
assertThat(migration.convertChangelog("status=RESOLVED|REOPENED,technicalDebt=100|200,resolution=")).isEqualTo("status=RESOLVED|REOPENED,technicalDebt=60|120,resolution=");
assertThat(migration.convertChangelog("status=RESOLVED|REOPENED,technicalDebt=|200,resolution=")).isEqualTo("status=RESOLVED|REOPENED,technicalDebt=|120,resolution=");
assertThat(migration.convertChangelog("status=RESOLVED|REOPENED,technicalDebt=100|,resolution=")).isEqualTo("status=RESOLVED|REOPENED,technicalDebt=60|,resolution=");
NotResolvedIssuesOnRemovedComponentsMigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(system2.now()).thenReturn(DateUtils.parseDate("2014-04-09").getTime());
migration = new NotResolvedIssuesOnRemovedComponentsMigrationStep(db.database(), system2);
RequirementMeasuresMigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
migration = new RequirementMeasuresMigrationStep(db.database());
}
TechnicalDebtMeasuresMigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(propertiesDao.selectGlobalProperty(WorkDurationConvertor.HOURS_IN_DAY_PROPERTY)).thenReturn(new PropertyDto().setValue("8"));
migration = new TechnicalDebtMeasuresMigrationStep(db.database(), propertiesDao);
WorkDurationConvertor convertor = new WorkDurationConvertor(propertiesDao);
@Test
- public void convert_from_long() throws Exception {
+ public void convert_from_long() {
convertor.init();
when(propertiesDao.selectGlobalProperty(WorkDurationConvertor.HOURS_IN_DAY_PROPERTY)).thenReturn(new PropertyDto().setValue(Integer.toString(HOURS_IN_DAY)));
}
@Test
- public void convert_from_long_use_default_value_for_hours_in_day_when_no_property() throws Exception {
+ public void convert_from_long_use_default_value_for_hours_in_day_when_no_property() {
convertor.init();
assertThat(convertor.createFromLong(1)).isEqualTo(ONE_MINUTE);
}
@Test
- public void fail_convert_from_long_on_bad_hours_in_day_property() throws Exception {
+ public void fail_convert_from_long_on_bad_hours_in_day_property() {
when(propertiesDao.selectGlobalProperty(WorkDurationConvertor.HOURS_IN_DAY_PROPERTY)).thenReturn(new PropertyDto().setValue("-2"));
WorkDurationConvertor workDurationConvertor = new WorkDurationConvertor(propertiesDao);
try {
}
@Test
- public void convert_from_days() throws Exception {
+ public void convert_from_days() {
convertor.init();
when(propertiesDao.selectGlobalProperty(WorkDurationConvertor.HOURS_IN_DAY_PROPERTY)).thenReturn(new PropertyDto().setValue(Integer.toString(HOURS_IN_DAY)));
}
@Test
- public void fail_it_init_has_not_been_called() throws Exception {
+ public void fail_it_init_has_not_been_called() {
when(propertiesDao.selectGlobalProperty(WorkDurationConvertor.HOURS_IN_DAY_PROPERTY)).thenReturn(new PropertyDto().setValue(Integer.toString(HOURS_IN_DAY)));
try {
DbSession session;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(system2.now()).thenReturn(DateUtils.parseDate("2014-03-13").getTime());
dao = new ActivityDao(db.myBatis(), system2);
dbClient = new DbClient(db.database(), db.myBatis(), dao);
}
@Test
- public void migrate() throws Exception {
+ public void migrate() {
db.prepareDbUnit(getClass(), "active_rules_changes.xml");
migration.execute();
assertThat(db.countRowsOfTable("activities")).isEqualTo(5);
}
@Test
- public void migrate_when_no_changelog() throws Exception {
+ public void migrate_when_no_changelog() {
db.prepareDbUnit(getClass(), "migrate_when_no_changelog.xml");
migration.execute();
ConvertProfileMeasuresMigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
DbClient dbClient = new DbClient(db.database(), db.myBatis());
migration = new ConvertProfileMeasuresMigrationStep(dbClient);
}
FeedQProfileDatesMigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table active_rule_changes");
db.executeUpdateSql("truncate table active_rule_param_changes");
DbClient dbClient = new DbClient(db.database(), db.myBatis());
}
@Test
- public void feed_created_at_and_updated_at() throws Exception {
+ public void feed_created_at_and_updated_at() {
db.prepareDbUnit(getClass(), "feed_created_at_and_updated_at.xml");
migration.execute();
}
@Test
- public void use_default_dates_when_no_changes() throws Exception {
+ public void use_default_dates_when_no_changes() {
db.prepareDbUnit(getClass(), "use_default_dates_when_no_changes.xml");
migration.execute();
IssueActionPlanKeyMigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(system2.now()).thenReturn(DateUtils.parseDate("2014-04-28").getTime());
migration = new IssueActionPlanKeyMigrationStep(db.database(), system2);
MeasureDataMigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
migration = new MeasureDataMigrationStep(db.database());
}
System2 system = mock(System2.class);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table rules_parameters");
db.executeUpdateSql("truncate table active_rules");
db.executeUpdateSql("truncate table active_rule_parameters");
MigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
DbClient dbClient = new DbClient(db.database(), db.myBatis());
migration = new DeleteMeasuresOnDeletedProfilesMigrationStep(dbClient);
}
System2 system = mock(System2.class);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table rules");
db.executeUpdateSql("truncate table rules_parameters");
DbClient dbClient = new DbClient(db.database(), db.myBatis());
}
@Test
- public void is_unescaped() throws Exception {
+ public void is_unescaped() {
assertThat(DeleteUnescapedActivities.isUnescaped(
"ruleKey=findbugs:PT_RELATIVE_PATH_TRAVERSAL;profileKey=java-findbugs-74105;severity=MAJOR;" +
"key=java-findbugs-74105:findbugs:PT_RELATIVE_PATH_TRAVERSAL"))
System2 system;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table metrics");
db.executeUpdateSql("truncate table snapshots");
db.executeUpdateSql("truncate table snapshot_sources");
System2 system = mock(System2.class);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table projects");
migration = new InsertProjectsAuthorizationUpdatedAtMigrationStep(db.database(), system);
when(system.now()).thenReturn(123456789L);
MigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table projects");
db.executeUpdateSql("truncate table snapshots");
dbClient = new DbClient(db.database(), db.myBatis());
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
System2 system = mock(System2.class);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table issue_filters");
migration = new RemoveSortFieldFromIssueFiltersMigrationStep(db.database(), system);
when(system.now()).thenReturn(DateUtils.parseDate("2014-10-29").getTime());
System2 system = mock(System2.class);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table issue_filters");
migration = new ReplaceIssueFiltersProjectKeyByUuid(db.database(), system);
when(system.now()).thenReturn(DateUtils.parseDate("2014-10-29").getTime());
MigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
migration = new AddIssuesColumns(db.database());
}
System2 system = mock(System2.class);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table characteristics");
when(system.now()).thenReturn(DateUtils.parseDate("2015-02-15").getTime());
}
@Test
- public void fail_if_usability_exists_as_sub_characteristic() throws Exception {
+ public void fail_if_usability_exists_as_sub_characteristic() {
db.prepareDbUnit(getClass(), "fail_if_usability_exists_as_sub_characteristic.xml");
try {
}
@Test
- public void fail_if_compliance_already_exists_as_characteristic() throws Exception {
+ public void fail_if_compliance_already_exists_as_characteristic() {
db.prepareDbUnit(getClass(), "fail_if_compliance_already_exists_as_characteristic.xml");
try {
}
@Test
- public void fail_if_compliance_already_exists_under_wrong_characteristic() throws Exception {
+ public void fail_if_compliance_already_exists_under_wrong_characteristic() {
db.prepareDbUnit(getClass(), "fail_if_compliance_already_exists_under_wrong_characteristic.xml");
try {
System2 system = mock(System2.class);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table authors");
db.executeUpdateSql("truncate table users");
migration = new CopyScmAccountsFromAuthorsToUsers(db.database(), system);
Database database;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
database = mock(Database.class);
migration = new DropIssuesColumns(database);
}
@Test
- public void generate_sql_on_postgresql() throws Exception {
+ public void generate_sql_on_postgresql() {
when(database.getDialect()).thenReturn(new PostgreSql());
assertThat(migration.generateSql()).isEqualTo(
"ALTER TABLE issues DROP COLUMN issue_creation_date, DROP COLUMN issue_update_date, DROP COLUMN issue_close_date, DROP COLUMN component_id, DROP COLUMN root_component_id"
public static DbTester db = new DbTester().schema(FeedEventsLongDatesTest.class, "schema.sql");
@Before
- public void before() throws Exception {
+ public void before() {
db.prepareDbUnit(getClass(), "before.xml");
}
FeedIssueComponentUuids sut;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.truncateTables();
sut = new FeedIssueComponentUuids(db.database());
System2 system;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table rules");
db.executeUpdateSql("truncate table issues");
public static DbTester db = new DbTester().schema(FeedManualMeasuresLongDatesTest.class, "schema.sql");
@Before
- public void before() throws Exception {
+ public void before() {
db.prepareDbUnit(getClass(), "before.xml");
}
public static DbTester db = new DbTester().schema(FeedSemaphoresLongDatesTest.class, "schema.sql");
@Before
- public void before() throws Exception {
+ public void before() {
db.prepareDbUnit(getClass(), "before.xml");
}
MigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
migration = new RemovePermissionsOnModulesMigrationStep(db.database());
}
System2 system = mock(System2.class);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table issue_filters");
migration = new RenameComponentRelatedParamsInIssueFilters(db.database(), system);
when(system.now()).thenReturn(DateUtils.parseDate("2014-10-29").getTime());
System2 system;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table projects");
migration = new UpdateProjectsModuleUuidPath(db.database());
AddDependenciesColumns migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
migration = new AddDependenciesColumns(db.database());
}
AddDependenciesComponentUuidColumns migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
migration = new AddDependenciesComponentUuidColumns(db.database());
}
Database database;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
database = mock(Database.class);
migration = new DropDependenciesComponentColumns(database);
}
@Test
- public void generate_sql_on_postgresql() throws Exception {
+ public void generate_sql_on_postgresql() {
when(database.getDialect()).thenReturn(new PostgreSql());
assertThat(migration.generateSql()).isEqualTo(
"ALTER TABLE dependencies DROP COLUMN from_resource_id, DROP COLUMN to_resource_id"
MigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table dependencies");
db.executeUpdateSql("truncate table projects");
MigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table events");
db.executeUpdateSql("truncate table projects");
MigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table file_sources");
migration = new FeedFileSourcesDataType(db.database());
MigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table project_links");
migration = new FeedProjectLinksComponentUuid(db.database());
MigrationStep migration;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.executeUpdateSql("truncate table projects");
db.executeUpdateSql("truncate table project_qprofiles");
db.executeUpdateSql("truncate table properties");
public static ServerTester serverTester = new ServerTester();
@Before
- public void setUp() throws Exception {
+ public void setUp() {
serverTester.clearDbAndIndexes();
serverTester.get(Platform.class).executeStartupTasks();
}
@Test
- public void find_default_characteristics() throws Exception {
+ public void find_default_characteristics() {
DebtModelService debtModelService = serverTester.get(DebtModelService.class);
// Only root characteristics
}
@Test
- public void create_characteristic() throws Exception {
+ public void create_characteristic() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
DebtModelService debtModelService = serverTester.get(DebtModelService.class);
}
@Test
- public void create_sub_characteristic() throws Exception {
+ public void create_sub_characteristic() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
DebtModelService debtModelService = serverTester.get(DebtModelService.class);
DebtModelBackup debtModelBackup;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
when(system2.now()).thenReturn(now.getTime());
}
@Test
- public void backup() throws Exception {
+ public void backup() {
when(dao.selectEnabledCharacteristics(session)).thenReturn(newArrayList(
new CharacteristicDto().setId(1).setKey("PORTABILITY").setName("Portability updated").setOrder(2),
new CharacteristicDto().setId(2).setKey("COMPILER").setName("Compiler updated").setParentId(1)
}
@Test
- public void backup_with_disabled_rules() throws Exception {
+ public void backup_with_disabled_rules() {
when(dao.selectEnabledCharacteristics(session)).thenReturn(newArrayList(
new CharacteristicDto().setId(1).setKey("PORTABILITY").setName("Portability updated").setOrder(2),
new CharacteristicDto().setId(2).setKey("COMPILER").setName("Compiler updated").setParentId(1)
}
@Test
- public void backup_with_rule_having_default_linear_and_overridden_offset() throws Exception {
+ public void backup_with_rule_having_default_linear_and_overridden_offset() {
when(dao.selectEnabledCharacteristics(session)).thenReturn(newArrayList(
new CharacteristicDto().setId(1).setKey("PORTABILITY").setName("Portability updated").setOrder(2),
new CharacteristicDto().setId(2).setKey("COMPILER").setName("Compiler updated").setParentId(1)
}
@Test
- public void backup_from_language() throws Exception {
+ public void backup_from_language() {
when(dao.selectEnabledCharacteristics(session)).thenReturn(newArrayList(
new CharacteristicDto().setId(1).setKey("PORTABILITY").setName("Portability updated").setOrder(2),
new CharacteristicDto().setId(2).setKey("COMPILER").setName("Compiler updated").setParentId(1)
}
@Test
- public void create_characteristics_when_restoring_characteristics() throws Exception {
+ public void create_characteristics_when_restoring_characteristics() {
when(dao.selectEnabledCharacteristics(session)).thenReturn(Collections.<CharacteristicDto>emptyList());
debtModelBackup.restoreCharacteristics(
}
@Test
- public void update_characteristics_when_restoring_characteristics() throws Exception {
+ public void update_characteristics_when_restoring_characteristics() {
when(dao.selectEnabledCharacteristics(session)).thenReturn(newArrayList(
// Order and name have changed
new CharacteristicDto().setId(1).setKey("PORTABILITY").setName("Portability updated").setOrder(2).setCreatedAt(oldDate).setUpdatedAt(oldDate),
}
@Test
- public void update_parent_when_restoring_characteristics() throws Exception {
+ public void update_parent_when_restoring_characteristics() {
when(dao.selectEnabledCharacteristics(session)).thenReturn(newArrayList(
// Parent has changed
new CharacteristicDto().setId(1).setKey("PORTABILITY").setName("Portability updated").setParentId(1).setOrder(1).setCreatedAt(oldDate).setUpdatedAt(oldDate),
}
@Test
- public void disable_no_more_existing_characteristics_when_restoring_characteristics() throws Exception {
+ public void disable_no_more_existing_characteristics_when_restoring_characteristics() {
CharacteristicDto dto1 = new CharacteristicDto().setId(1).setKey("PORTABILITY").setName("Portability").setOrder(1);
CharacteristicDto dto2 = new CharacteristicDto().setId(2).setKey("COMPILER").setName("Compiler").setParentId(1);
}
@Test
- public void reset_model() throws Exception {
+ public void reset_model() {
when(characteristicsXMLImporter.importXML(any(Reader.class))).thenReturn(new DebtModel()
.addRootCharacteristic(new DefaultDebtCharacteristic().setKey("PORTABILITY").setName("Portability").setOrder(1))
.addSubCharacteristic(new DefaultDebtCharacteristic().setKey("COMPILER").setName("Compiler"), "PORTABILITY"));
}
@Test
- public void reset_model_when_no_default_value() throws Exception {
+ public void reset_model_when_no_default_value() {
when(characteristicsXMLImporter.importXML(any(Reader.class))).thenReturn(new DebtModel()
.addRootCharacteristic(new DefaultDebtCharacteristic().setKey("PORTABILITY").setName("Portability").setOrder(1))
.addSubCharacteristic(new DefaultDebtCharacteristic().setKey("COMPILER").setName("Compiler"), "PORTABILITY"));
}
@Test
- public void reset_model_on_custom_rules() throws Exception {
+ public void reset_model_on_custom_rules() {
when(characteristicsXMLImporter.importXML(any(Reader.class))).thenReturn(new DebtModel()
.addRootCharacteristic(new DefaultDebtCharacteristic().setKey("PORTABILITY").setName("Portability").setOrder(1))
.addSubCharacteristic(new DefaultDebtCharacteristic().setKey("COMPILER").setName("Compiler"), "PORTABILITY"));
}
@Test
- public void reset_model_do_not_load_rule_definitions_if_no_rule() throws Exception {
+ public void reset_model_do_not_load_rule_definitions_if_no_rule() {
when(characteristicsXMLImporter.importXML(any(Reader.class))).thenReturn(new DebtModel()
.addRootCharacteristic(new DefaultDebtCharacteristic().setKey("PORTABILITY").setName("Portability").setOrder(1))
.addSubCharacteristic(new DefaultDebtCharacteristic().setKey("COMPILER").setName("Compiler"), "PORTABILITY"));
}
@Test
- public void restore_from_xml() throws Exception {
+ public void restore_from_xml() {
when(characteristicsXMLImporter.importXML(anyString())).thenReturn(new DebtModel()
.addRootCharacteristic(new DefaultDebtCharacteristic().setKey("PORTABILITY").setName("Portability").setOrder(1))
.addSubCharacteristic(new DefaultDebtCharacteristic().setKey("COMPILER").setName("Compiler"), "PORTABILITY"));
}
@Test
- public void restore_from_xml_disable_rule_debt_when_not_in_xml_and_rule_have_default_debt_values() throws Exception {
+ public void restore_from_xml_disable_rule_debt_when_not_in_xml_and_rule_have_default_debt_values() {
when(characteristicsXMLImporter.importXML(anyString())).thenReturn(new DebtModel()
.addRootCharacteristic(new DefaultDebtCharacteristic().setKey("PORTABILITY").setName("Portability").setOrder(1))
.addSubCharacteristic(new DefaultDebtCharacteristic().setKey("COMPILER").setName("Compiler"), "PORTABILITY"));
}
@Test
- public void restore_from_xml_and_language() throws Exception {
+ public void restore_from_xml_and_language() {
when(characteristicsXMLImporter.importXML(anyString())).thenReturn(new DebtModel()
.addRootCharacteristic(new DefaultDebtCharacteristic().setKey("PORTABILITY").setName("Portability").setOrder(1))
.addSubCharacteristic(new DefaultDebtCharacteristic().setKey("COMPILER").setName("Compiler"), "PORTABILITY"));
}
@Test
- public void restore_from_xml_and_language_disable_no_more_existing_characteristics() throws Exception {
+ public void restore_from_xml_and_language_disable_no_more_existing_characteristics() {
when(characteristicsXMLImporter.importXML(anyString())).thenReturn(new DebtModel()
.addRootCharacteristic(new DefaultDebtCharacteristic().setKey("PORTABILITY").setName("Portability").setOrder(1)));
}
@Test
- public void restore_from_xml_and_language_with_rule_not_in_xml() throws Exception {
+ public void restore_from_xml_and_language_with_rule_not_in_xml() {
when(characteristicsXMLImporter.importXML(anyString())).thenReturn(new DebtModel()
.addRootCharacteristic(new DefaultDebtCharacteristic().setKey("PORTABILITY").setName("Portability").setOrder(1))
.addSubCharacteristic(new DefaultDebtCharacteristic().setKey("COMPILER").setName("Compiler"), "PORTABILITY"));
}
@Test
- public void restore_from_xml_add_warning_message_when_rule_from_xml_is_not_found() throws Exception {
+ public void restore_from_xml_add_warning_message_when_rule_from_xml_is_not_found() {
when(characteristicsXMLImporter.importXML(anyString())).thenReturn(new DebtModel()
.addRootCharacteristic(new DefaultDebtCharacteristic().setKey("PORTABILITY").setName("Portability").setOrder(1))
.addSubCharacteristic(new DefaultDebtCharacteristic().setKey("COMPILER").setName("Compiler"), "PORTABILITY"));
}
@Test
- public void restore_from_xml_add_error_message_when_illegal_argument_exception() throws Exception {
+ public void restore_from_xml_add_error_message_when_illegal_argument_exception() {
when(characteristicsXMLImporter.importXML(anyString())).thenReturn(new DebtModel()
.addRootCharacteristic(new DefaultDebtCharacteristic().setKey("PORTABILITY").setName("Portability").setOrder(1))
.addSubCharacteristic(new DefaultDebtCharacteristic().setKey("COMPILER").setName("Compiler"), "PORTABILITY"));
DebtModelLookup service;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
service = new DebtModelLookup(dao);
}
DebtModelOperations service;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(system2.now()).thenReturn(now.getTime());
MockUserSession.set().setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
}
@Test
- public void contributing_plugin_list() throws Exception {
+ public void contributing_plugin_list() {
initModel();
Collection<String> contributingPluginList = modelFinder.getContributingPluginList();
assertThat(contributingPluginList.size()).isEqualTo(2);
}
@Test
- public void get_content_for_xml_file() throws Exception {
+ public void get_content_for_xml_file() {
initModel();
Reader xmlFileReader = null;
try {
}
@Test
- public void return_xml_file_path_for_plugin() throws Exception {
+ public void return_xml_file_path_for_plugin() {
initModel();
assertThat(modelFinder.getXMLFilePath("foo")).isEqualTo(TEST_XML_PREFIX_PATH + "foo-model.xml");
}
@Test
- public void contain_default_model() throws Exception {
+ public void contain_default_model() {
modelFinder = new DebtModelPluginRepository(mock(PluginRepository.class));
modelFinder.start();
assertThat(modelFinder.getContributingPluginKeyToClassLoader().keySet()).containsOnly("technical-debt");
}
- private void initModel() throws MalformedURLException {
+ private void initModel() {
Map<String, ClassLoader> contributingPluginKeyToClassLoader = Maps.newHashMap();
contributingPluginKeyToClassLoader.put("csharp", newClassLoader());
contributingPluginKeyToClassLoader.put("java", newClassLoader());
modelFinder = new DebtModelPluginRepository(contributingPluginKeyToClassLoader, TEST_XML_PREFIX_PATH);
}
- private ClassLoader newClassLoader() throws MalformedURLException {
+ private ClassLoader newClassLoader() {
ClassLoader loader = mock(ClassLoader.class);
when(loader.getResourceAsStream(anyString())).thenAnswer(new Answer<InputStream>() {
public InputStream answer(InvocationOnMock invocation) throws Throwable {
DebtModelService service;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
service = new DebtModelService(debtModelOperations, debtModelLookup, debtModelBackup);
}
}
@Test
- public void sort_root_characteristics_by_order_and_sub_characteristics_by_name() throws Exception {
+ public void sort_root_characteristics_by_order_and_sub_characteristics_by_name() {
DebtModel debtModel = new DebtModel()
.addRootCharacteristic(new DefaultDebtCharacteristic().setKey("EFFICIENCY").setName("Efficiency").setOrder(4))
.addRootCharacteristic(new DefaultDebtCharacteristic().setKey("USABILITY").setName("Usability").setOrder(3))
}
@Test
- public void pretty_print_exported_xml() throws Exception {
+ public void pretty_print_exported_xml() {
DebtModel debtModel = new DebtModel()
.addRootCharacteristic(new DefaultDebtCharacteristic().setId(1).setKey("USABILITY").setName("Usability").setOrder(1))
.addRootCharacteristic(new DefaultDebtCharacteristic().setId(2).setKey("EFFICIENCY").setName("Efficiency").setOrder(2))
FileDependencyDao dao;
@Before
- public void setup() throws Exception {
+ public void setup() {
dbTester.truncateTables();
session = dbTester.myBatis().openSession(false);
dao = new FileDependencyDao();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void select_from_parents() throws Exception {
+ public void select_from_parents() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
List<FileDependencyDto> dtos = dao.selectFromParents(session, "MNOP", "QRST", 1L);
}
@Test
- public void select_all() throws Exception {
+ public void select_all() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
assertThat(dao.selectAll(session)).hasSize(3);
}
@Test
- public void insert() throws Exception {
+ public void insert() {
dao.insert(session, new FileDependencyDto()
.setFromComponentUuid("ABCD")
.setToComponentUuid("EFGH")
WebService.Controller controller;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
WsTester tester = new WsTester(new DependenciesWs(new ShowAction(mock(DbClient.class))));
controller = tester.controller("api/dependencies");
}
@Test
- public void define_controller() throws Exception {
+ public void define_controller() {
assertThat(controller).isNotNull();
assertThat(controller.description()).isNull();
assertThat(controller.since()).isEqualTo("5.2");
}
@Test
- public void define_search_action() throws Exception {
+ public void define_search_action() {
WebService.Action action = controller.action("show");
assertThat(action).isNotNull();
assertThat(action.isPost()).isFalse();
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), new ComponentDao(), new SnapshotDao(System2.INSTANCE), new FileDependencyDao());
session = dbClient.openSession(false);
ComponentDto project;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
project = ComponentTesting.newProjectDto()
.setId(1L)
.setName("SonarQube")
}
@Test
- public void write_duplications() throws Exception {
+ public void write_duplications() {
String key1 = "org.codehaus.sonar:sonar-ws-client:src/main/java/org/sonar/wsclient/services/PropertyDeleteQuery.java";
ComponentDto file1 = ComponentTesting.newFileDto(project).setId(10L).setKey(key1).setLongName("PropertyDeleteQuery").setParentProjectId(5L);
String key2 = "org.codehaus.sonar:sonar-ws-client:src/main/java/org/sonar/wsclient/services/PropertyUpdateQuery.java";
}
@Test
- public void write_duplications_without_sub_project() throws Exception {
+ public void write_duplications_without_sub_project() {
String key1 = "org.codehaus.sonar:sonar-ws-client:src/main/java/org/sonar/wsclient/services/PropertyDeleteQuery.java";
ComponentDto file1 = ComponentTesting.newFileDto(project).setId(10L).setKey(key1).setLongName("PropertyDeleteQuery");
String key2 = "org.codehaus.sonar:sonar-ws-client:src/main/java/org/sonar/wsclient/services/PropertyUpdateQuery.java";
}
@Test
- public void write_duplications_with_a_removed_component() throws Exception {
+ public void write_duplications_with_a_removed_component() {
String key1 = "org.codehaus.sonar:sonar-ws-client:src/main/java/org/sonar/wsclient/services/PropertyDeleteQuery.java";
ComponentDto file1 = ComponentTesting.newFileDto(project).setId(10L).setKey(key1).setLongName("PropertyDeleteQuery");
}
@Test
- public void write_nothing_when_no_data() throws Exception {
+ public void write_nothing_when_no_data() {
test(Collections.<DuplicationsParser.Block>emptyList(), "{\"duplications\": [], \"files\": {}}");
}
ComponentDto project2;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
project1 = ComponentTesting.newProjectDto()
.setId(1L)
.setName("SonarQube")
}
@Test
- public void empty_list_when_no_data() throws Exception {
+ public void empty_list_when_no_data() {
assertThat(parser.parse(currentFile, null, session)).isEmpty();
}
}
@Test
- public void compare_duplications() throws Exception {
+ public void compare_duplications() {
ComponentDto currentFile = ComponentTesting.newFileDto(project1).setId(11L);
ComponentDto fileOnSameProject = ComponentTesting.newFileDto(project1).setId(12L);
ComponentDto fileOnDifferentProject = ComponentTesting.newFileDto(project2).setId(13L);
new ShowAction(mock(DbClient.class), mock(ComponentDao.class), mock(MeasureDao.class), mock(DuplicationsParser.class), mock(DuplicationsJsonWriter.class))));
@Test
- public void define_ws() throws Exception {
+ public void define_ws() {
WebService.Controller controller = tester.controller("api/duplications");
assertThat(controller).isNotNull();
assertThat(controller.since()).isEqualTo("4.4");
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(dbClient.openSession(false)).thenReturn(session);
tester = new WsTester(new DuplicationsWs(new ShowAction(dbClient, componentDao, measureDao, parser, duplicationsJsonWriter)));
}
public EsTester esTester = new EsTester().addDefinitions(new FakeIndexDefinition().setReplicas(1));
@Test
- public void index_nothing() throws Exception {
+ public void index_nothing() {
esTester.truncateIndices();
BulkIndexer indexer = new BulkIndexer(esTester.client(), FakeIndexDefinition.INDEX);
}
@Test
- public void index_documents() throws Exception {
+ public void index_documents() {
BulkIndexer indexer = new BulkIndexer(esTester.client(), FakeIndexDefinition.INDEX);
indexer.start();
indexer.add(newIndexRequest(42));
}
@Test
- public void large_indexing() throws Exception {
+ public void large_indexing() {
// index has one replica
assertThat(replicas()).isEqualTo(1);
}
@Test
- public void disable_refresh() throws Exception {
+ public void disable_refresh() {
BulkIndexer indexer = new BulkIndexer(esTester.client(), FakeIndexDefinition.INDEX)
.setDisableRefresh(true);
indexer.start();
public class DefaultIndexSettingsTest {
@Test
- public void defaults() throws Exception {
+ public void defaults() {
ImmutableMap<String, String> map = DefaultIndexSettings.defaults().build().getAsMap();
assertThat(map).isNotEmpty();
}
@Test
- public void only_statics() throws Exception {
+ public void only_statics() {
TestUtils.hasOnlyPrivateConstructors(DefaultIndexSettings.class);
}
public EsTester es = new EsTester();
@Test
- public void proxify_requests() throws Exception {
+ public void proxify_requests() {
EsClient client = es.client();
client.start();
assertThat(client.nativeClient()).isNotNull();
public class EsUtilsTest {
@Test
- public void convertToDocs_empty() throws Exception {
+ public void convertToDocs_empty() {
SearchHits hits = mock(SearchHits.class, Mockito.RETURNS_MOCKS);
List<BaseDoc> docs = EsUtils.convertToDocs(hits, new Function<Map<String, Object>, BaseDoc>() {
@Override
}
@Test
- public void convertToDocs() throws Exception {
+ public void convertToDocs() {
SearchHits hits = mock(SearchHits.class, Mockito.RETURNS_MOCKS);
when(hits.getHits()).thenReturn(new SearchHit[]{mock(SearchHit.class)});
List<BaseDoc> docs = EsUtils.convertToDocs(hits, new Function<Map<String, Object>, BaseDoc>() {
}
@Test
- public void util_class() throws Exception {
+ public void util_class() {
assertThat(TestUtils.hasOnlyPrivateConstructors(EsUtils.class));
}
@Test
- public void es_date_format() throws Exception {
+ public void es_date_format() {
assertThat(EsUtils.formatDateTime(new Date(1_500_000_000_000L))).startsWith("2017-07-");
assertThat(EsUtils.formatDateTime(null)).isNull();
public class IndexDefinitionContextTest {
@Test
- public void create_indices() throws Exception {
+ public void create_indices() {
IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext();
context.create("issues");
}
@Test
- public void fail_to_create_twice_the_same_index() throws Exception {
+ public void fail_to_create_twice_the_same_index() {
IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext();
context.create("issues");
public class IndexDefinitionHashTest {
@Test
- public void of() throws Exception {
+ public void of() {
IndexDefinitions.Index indexV1 = new IndexDefinitions.Index(createIndex());
String hashV1 = new IndexDefinitionHash().of(indexV1);
assertThat(hashV1).isNotEmpty();
public class NewIndexTest {
@Test
- public void most_basic_index() throws Exception {
+ public void most_basic_index() {
NewIndex index = new NewIndex("issues");
assertThat(index.getName()).isEqualTo("issues");
assertThat(index.getTypes()).isEmpty();
}
@Test
- public void index_name_is_lower_case() throws Exception {
+ public void index_name_is_lower_case() {
try {
new NewIndex("Issues");
fail();
}
@Test
- public void define_fields() throws Exception {
+ public void define_fields() {
NewIndex index = new NewIndex("issues");
NewIndex.NewIndexType mapping = index.createType("issue");
mapping.setAttribute("dynamic", "true");
}
@Test
- public void define_string_field() throws Exception {
+ public void define_string_field() {
NewIndex index = new NewIndex("issues");
NewIndex.NewIndexType mapping = index.createType("issue");
mapping.stringFieldBuilder("basic_field").build();
}
@Test
- public void string_doc_values() throws Exception {
+ public void string_doc_values() {
NewIndex index = new NewIndex("issues");
NewIndex.NewIndexType mapping = index.createType("issue");
mapping.stringFieldBuilder("the_doc_value").docValues().build();
}
@Test
- public void analyzed_strings_must_not_be_doc_values() throws Exception {
+ public void analyzed_strings_must_not_be_doc_values() {
NewIndex index = new NewIndex("issues");
NewIndex.NewIndexType mapping = index.createType("issue");
try {
}
@Test
- public void do_not_disable_search_on_searchable_fields() throws Exception {
+ public void do_not_disable_search_on_searchable_fields() {
NewIndex index = new NewIndex("issues");
NewIndex.NewIndexType mapping = index.createType("issue");
try {
public class SearchOptionsTest {
@Test
- public void defaults() throws Exception {
+ public void defaults() {
SearchOptions options = new SearchOptions();
assertThat(options.getFacets()).isEmpty();
}
@Test
- public void page_shortcut_for_limit_and_offset() throws Exception {
+ public void page_shortcut_for_limit_and_offset() {
SearchOptions options = new SearchOptions().setPage(3, 10);
assertThat(options.getLimit()).isEqualTo(10);
}
@Test
- public void page_starts_at_one() throws Exception {
+ public void page_starts_at_one() {
SearchOptions options = new SearchOptions().setPage(1, 10);
assertThat(options.getLimit()).isEqualTo(10);
assertThat(options.getOffset()).isEqualTo(0);
}
@Test
- public void with_zero_page_size() throws Exception {
+ public void with_zero_page_size() {
SearchOptions options = new SearchOptions().setPage(1, 0);
assertThat(options.getLimit()).isEqualTo(SearchOptions.MAX_LIMIT);
assertThat(options.getOffset()).isEqualTo(0);
}
@Test
- public void page_must_be_strictly_positive() throws Exception {
+ public void page_must_be_strictly_positive() {
try {
new SearchOptions().setPage(0, 10);
fail();
}
@Test
- public void use_max_limit_if_negative() throws Exception {
+ public void use_max_limit_if_negative() {
SearchOptions options = new SearchOptions().setPage(2, -1);
assertThat(options.getLimit()).isEqualTo(SearchOptions.MAX_LIMIT);
}
@Test
- public void max_limit() throws Exception {
+ public void max_limit() {
SearchOptions options = new SearchOptions().setLimit(42);
assertThat(options.getLimit()).isEqualTo(42);
}
@Test
- public void disable_limit() throws Exception {
+ public void disable_limit() {
SearchOptions options = new SearchOptions().disableLimit();
assertThat(options.getLimit()).isEqualTo(999999);
}
@Test
- public void max_page_size() throws Exception {
+ public void max_page_size() {
SearchOptions options = new SearchOptions().setPage(3, QueryContext.MAX_LIMIT + 10);
assertThat(options.getOffset()).isEqualTo(QueryContext.MAX_LIMIT * 2);
assertThat(options.getLimit()).isEqualTo(QueryContext.MAX_LIMIT);
}
@Test
- public void hasField() throws Exception {
+ public void hasField() {
// parameter is missing -> all the fields are returned by default
SearchOptions options = new SearchOptions();
assertThat(options.hasField("repo")).isTrue();
}
@Test
- public void writeJson() throws Exception {
+ public void writeJson() {
SearchOptions options = new SearchOptions().setPage(3, 10);
StringWriter json = new StringWriter();
JsonWriter jsonWriter = JsonWriter.of(json).beginObject();
}
@Test
- public void writeDeprecatedJson() throws Exception {
+ public void writeDeprecatedJson() {
SearchOptions options = new SearchOptions().setPage(3, 10);
StringWriter json = new StringWriter();
JsonWriter jsonWriter = JsonWriter.of(json).beginObject();
}
@Test
- public void writeDeprecatedJson_exact_nb_of_pages() throws Exception {
+ public void writeDeprecatedJson_exact_nb_of_pages() {
SearchOptions options = new SearchOptions().setPage(3, 10);
StringWriter json = new StringWriter();
JsonWriter jsonWriter = JsonWriter.of(json).beginObject();
}
@Test(expected = UnsupportedOperationException.class)
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
esTester.client().prepareBulk().get("1");
}
@Test(expected = UnsupportedOperationException.class)
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
esTester.client().prepareBulk().get(TimeValue.timeValueMinutes(1));
}
@Test(expected = UnsupportedOperationException.class)
- public void execute_is_not_yet_implemented() throws Exception {
+ public void execute_is_not_yet_implemented() {
esTester.client().prepareBulk().execute();
}
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareClearCache().get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareClearCache().get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareClearCache().execute();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareHealth().get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareHealth().get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareHealth().execute();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareState().get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareState().get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareState().execute();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareClusterStats().get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareClusterStats().get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareClusterStats().execute();
fail();
}
@Test
- public void fail_to_count_bad_query() throws Exception {
+ public void fail_to_count_bad_query() {
try {
esTester.client().prepareCount("unknown_index1, unknown_index2").setTypes("unknown_type").get();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareCount(FakeIndexDefinition.INDEX).get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareCount(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareCount(FakeIndexDefinition.INDEX).execute();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareCreate(generateNewIndexName()).get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareCreate(generateNewIndexName()).get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareCreate(generateNewIndexName()).execute();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareDeleteByQuery().get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareDeleteByQuery().get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareDeleteByQuery().execute();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareDelete("fakes", "fake", "the_id").get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareDelete("fakes", "fake", "the_id").get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareDelete("fakes", "fake", "the_id").execute();
fail();
}
@Test
- public void fail_to_refresh() throws Exception {
+ public void fail_to_refresh() {
try {
esTester.client().prepareFlush("unknown").get();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareFlush(FakeIndexDefinition.INDEX).get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareFlush(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareFlush(FakeIndexDefinition.INDEX).execute();
fail();
}
@Test
- public void fail_to_get_bad_query() throws Exception {
+ public void fail_to_get_bad_query() {
GetRequestBuilder requestBuilder = esTester.client().prepareGet()
.setIndex("unknown")
.setType("test")
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareGet().get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareGet().get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareGet().execute();
fail();
}
@Test
- public void fail_if_bad_query() throws Exception {
+ public void fail_if_bad_query() {
IndexRequestBuilder requestBuilder = esTester.client().prepareIndex("unknownIndex", "unknownType");
try {
requestBuilder.get();
}
@Test
- public void fail_if_bad_query_with_basic_profiling() throws Exception {
+ public void fail_if_bad_query_with_basic_profiling() {
IndexRequestBuilder requestBuilder = esTester.client().prepareIndex("unknownIndex", "unknownType");
try {
requestBuilder.get();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareIndex(FakeIndexDefinition.INDEX, FakeIndexDefinition.TYPE).get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareIndex(FakeIndexDefinition.INDEX, FakeIndexDefinition.TYPE).get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void do_not_support_execute_method() throws Exception {
+ public void do_not_support_execute_method() {
try {
esTester.client().prepareIndex(FakeIndexDefinition.INDEX, FakeIndexDefinition.TYPE).execute();
fail();
}
@Test
- public void fail_to_exists() throws Exception {
+ public void fail_to_exists() {
try {
esTester.client().prepareIndicesExist().get();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareIndicesExist().get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareIndicesExist().get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareIndicesExist().execute();
fail();
}
@Test
- public void fail_to_stats() throws Exception {
+ public void fail_to_stats() {
try {
esTester.client().prepareStats("unknown").get();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareStats(FakeIndexDefinition.INDEX).get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareStats(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareStats(FakeIndexDefinition.INDEX).execute();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareMultiGet().get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareMultiGet().get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareMultiGet().execute();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareNodesStats(FakeIndexDefinition.INDEX).get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareNodesStats(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareNodesStats(FakeIndexDefinition.INDEX).execute();
fail();
}
@Test
- public void fail_on_bad_query() throws Exception {
+ public void fail_on_bad_query() {
try {
esTester.client().preparePutMapping().get();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().preparePutMapping().get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().preparePutMapping().get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().preparePutMapping().execute();
fail();
}
@Test
- public void fail_to_refresh() throws Exception {
+ public void fail_to_refresh() {
try {
esTester.client().prepareRefresh("unknown").get();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareRefresh(FakeIndexDefinition.INDEX).get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareRefresh(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareRefresh(FakeIndexDefinition.INDEX).execute();
fail();
}
@Test
- public void fail_to_search_bad_query() throws Exception {
+ public void fail_to_search_bad_query() {
try {
esTester.client().prepareSearch(FakeIndexDefinition.INDEX).setQuery("bad query").get();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareSearch(FakeIndexDefinition.INDEX).get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareSearch(FakeIndexDefinition.INDEX).get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareSearch(FakeIndexDefinition.INDEX).execute();
fail();
}
@Test
- public void fail_to_search_bad_query() throws Exception {
+ public void fail_to_search_bad_query() {
try {
esTester.client().prepareSearchScroll("unknown").get();
fail();
}
@Test
- public void get_with_string_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_string_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareSearchScroll("scrollId").get("1");
fail();
}
@Test
- public void get_with_time_value_timeout_is_not_yet_implemented() throws Exception {
+ public void get_with_time_value_timeout_is_not_yet_implemented() {
try {
esTester.client().prepareSearchScroll("scrollId").get(TimeValue.timeValueMinutes(1));
fail();
}
@Test
- public void execute_should_throw_an_unsupported_operation_exception() throws Exception {
+ public void execute_should_throw_an_unsupported_operation_exception() {
try {
esTester.client().prepareSearchScroll("scrollId").execute();
fail();
EventDao dao;
@Before
- public void setup() throws Exception {
+ public void setup() {
dbTester.truncateTables();
session = dbTester.myBatis().openSession(false);
dao = new EventDao();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void select_by_component_uuid() throws Exception {
+ public void select_by_component_uuid() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
List<EventDto> dtos = dao.selectByComponentUuid(session, "ABCD");
}
@Test
- public void return_different_categories() throws Exception {
+ public void return_different_categories() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
List<EventDto> dtos = dao.selectByComponentUuid(session, "ABCD");
}
@Test
- public void insert() throws Exception {
+ public void insert() {
dbTester.prepareDbUnit(getClass(), "empty.xml");
dao.insert(session, new EventDto()
}
@Test
- public void delete() throws Exception {
+ public void delete() {
dbTester.prepareDbUnit(getClass(), "delete.xml");
dao.delete(session, 1L);
public class BadRequestExceptionTest {
@Test
- public void text_error() throws Exception {
+ public void text_error() {
BadRequestException exception = new BadRequestException("error");
assertThat(exception.getMessage()).isEqualTo("error");
}
}
@Test
- public void to_string() throws Exception {
+ public void to_string() {
assertThat(Message.of("key1", "param1").toString()).isEqualTo("Message{key=key1, params=[param1]}");
assertThat(Message.of("key1").toString()).isEqualTo("Message{key=key1, params=[]}");
}
public class VerificationsTest {
@Test
- public void check() throws Exception {
+ public void check() {
// no exception
Verifications.check(true, "my.l10n.key", "foo", "bar");
}
@Test
- public void should_fail_if_tag_is_not_valid() throws Exception {
+ public void should_fail_if_tag_is_not_valid() {
throwable.expect(IllegalArgumentException.class);
throwable.expectMessage("Tag 'th ag' is invalid. Rule tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'");
}
@Test
- public void should_fail_if_assignee_is_not_verified() throws Exception {
+ public void should_fail_if_assignee_is_not_verified() {
throwable.expect(IllegalArgumentException.class);
throwable.expectMessage("Assignee is missing from the execution parameters");
}
@Test
- public void get_issue_by_key() throws Exception {
+ public void get_issue_by_key() {
service.getIssueByKey("ABCD");
verify(issueService).getByKey("ABCD");
}
@Test
- public void list_transitions_by_issue_key() throws Exception {
+ public void list_transitions_by_issue_key() {
service.listTransitions("ABCD");
verify(issueService).listTransitions(eq("ABCD"));
}
@Test
- public void list_transitions_by_issue() throws Exception {
+ public void list_transitions_by_issue() {
Issue issue = new DefaultIssue().setKey("ABCD");
service.listTransitions(issue);
verify(issueService).listTransitions(eq(issue));
}
@Test
- public void list_status() throws Exception {
+ public void list_status() {
service.listStatus();
verify(issueService).listStatus();
}
@Test
- public void list_resolutions() throws Exception {
+ public void list_resolutions() {
assertThat(service.listResolutions()).isEqualTo(Issue.RESOLUTIONS);
}
}
@Test
- public void do_transition() throws Exception {
+ public void do_transition() {
service.doTransition("ABCD", Issue.STATUS_RESOLVED);
verify(issueService).doTransition(eq("ABCD"), eq(Issue.STATUS_RESOLVED));
}
}
@Test
- public void list_tags() throws Exception {
+ public void list_tags() {
List<String> tags = Arrays.asList("tag1", "tag2", "tag3");
when(issueService.listTags(null, 0)).thenReturn(tags);
assertThat(service.listTags()).isEqualTo(tags);
}
@Test
- public void list_tags_for_component() throws Exception {
+ public void list_tags_for_component() {
Map<String, Long> tags = ImmutableMap.of("tag1", 1L, "tag2", 2L, "tag3", 3L);
int pageSize = 42;
IssueQuery query = IssueQuery.builder().build();
UserSession userSession;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
db = tester.get(DbClient.class);
session = db.openSession(false);
}
@Test
- public void bulk_change() throws Exception {
+ public void bulk_change() {
UserDto user = new UserDto().setLogin("fred").setName("Fred");
db.userDao().insert(session, user);
}
@Test
- public void bulk_change_on_500_issues() throws Exception {
+ public void bulk_change_on_500_issues() {
List<String> issueKeys = newArrayList();
for (int i = 0; i < 500; i++) {
IssueDto issue = IssueTesting.newDto(rule, file, project).setStatus(Issue.STATUS_OPEN);
}
@Test
- public void fail_if_bulk_change_on_more_than_500_issues() throws Exception {
+ public void fail_if_bulk_change_on_more_than_500_issues() {
List<String> issueKeys = newArrayList();
for (int i = 0; i < 510; i++) {
issueKeys.add("issue-" + i);
IssueChangelogService service;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
service = new IssueChangelogService(changeDao, userFinder, issueService, formatter);
}
@Test
- public void load_changelog_and_related_users() throws Exception {
+ public void load_changelog_and_related_users() {
FieldDiffs userChange = new FieldDiffs().setUserLogin("arthur").setDiff("severity", "MAJOR", "BLOCKER");
FieldDiffs scanChange = new FieldDiffs().setDiff("status", "RESOLVED", "CLOSED");
when(changeDao.selectChangelogByIssue("ABCDE")).thenReturn(Arrays.asList(userChange, scanChange));
}
@Test
- public void format_diffs() throws Exception {
+ public void format_diffs() {
FieldDiffs diffs = new FieldDiffs().setUserLogin("arthur").setDiff("severity", "MAJOR", "BLOCKER");
MockUserSession.set();
service.formatDiffs(diffs);
ComponentDto file;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
db = tester.get(DbClient.class);
indexClient = tester.get(IndexClient.class);
}
@Test
- public void add_comment() throws Exception {
+ public void add_comment() {
IssueDto issue = IssueTesting.newDto(rule, file, project);
tester.get(IssueDao.class).insert(session, issue);
session.commit();
}
@Test
- public void add_comment_on_removed_issue() throws Exception {
+ public void add_comment_on_removed_issue() {
RuleDto removedRule = RuleTesting.newDto(RuleKey.of("removed", "rule")).setStatus(RuleStatus.REMOVED);
tester.get(RuleDao.class).insert(session, removedRule);
}
@Test
- public void find_comments() throws Exception {
+ public void find_comments() {
issueCommentService.findComments("ABCD");
verify(changeDao).selectCommentsByIssues(session, newArrayList("ABCD"));
}
@Test
- public void should_find_comment() throws Exception {
+ public void should_find_comment() {
issueCommentService.findComment("ABCD");
verify(changeDao).selectCommentByKey("ABCD");
}
@Test
- public void should_add_comment() throws Exception {
+ public void should_add_comment() {
IssueDto issueDto = IssueTesting.newDto(RuleTesting.newXooX1().setId(500), ComponentTesting.newFileDto(ComponentTesting.newProjectDto()), ComponentTesting.newProjectDto());
when(issueService.getByKeyForUpdate(session, "ABCD")).thenReturn(issueDto);
when(issueCommentService.findComments(session, "ABCD")).thenReturn(newArrayList(new DefaultIssueComment()));
}
@Test
- public void should_be_logged_when_adding_comment() throws Exception {
+ public void should_be_logged_when_adding_comment() {
throwable.expect(UnauthorizedException.class);
MockUserSession.set().setLogin(null);
}
@Test
- public void should_prevent_adding_empty_comment() throws Exception {
+ public void should_prevent_adding_empty_comment() {
throwable.expect(BadRequestException.class);
issueCommentService.addComment("myIssue", " ", MockUserSession.get());
}
@Test
- public void should_prevent_adding_null_comment() throws Exception {
+ public void should_prevent_adding_null_comment() {
throwable.expect(BadRequestException.class);
issueCommentService.addComment("myIssue", null, MockUserSession.get());
}
@Test
- public void fail_if_comment_not_inserted_in_db() throws Exception {
+ public void fail_if_comment_not_inserted_in_db() {
IssueDto issueDto = IssueTesting.newDto(RuleTesting.newXooX1().setId(500), ComponentTesting.newFileDto(ComponentTesting.newProjectDto()), ComponentTesting.newProjectDto());
when(issueService.getByKeyForUpdate(session, "ABCD")).thenReturn(issueDto);
// Comment has not be inserted in db
}
@Test
- public void should_delete_comment() throws Exception {
+ public void should_delete_comment() {
when(changeDao.selectCommentByKey("ABCD")).thenReturn(new DefaultIssueComment().setUserLogin("admin").setIssueKey("EFGH"));
issueCommentService.deleteComment("ABCD", MockUserSession.get());
}
@Test
- public void should_not_delete_not_found_comment() throws Exception {
+ public void should_not_delete_not_found_comment() {
throwable.expect(NotFoundException.class);
when(changeDao.selectCommentByKey("ABCD")).thenReturn(null);
}
@Test
- public void should_prevent_delete_others_comment() throws Exception {
+ public void should_prevent_delete_others_comment() {
throwable.expect(ForbiddenException.class);
when(changeDao.selectCommentByKey("ABCD")).thenReturn(new DefaultIssueComment().setUserLogin("julien"));
}
@Test
- public void should_update_comment() throws Exception {
+ public void should_update_comment() {
when(changeDao.selectCommentByKey("ABCD")).thenReturn(new DefaultIssueComment().setIssueKey("EFGH").setUserLogin("admin"));
issueCommentService.editComment("ABCD", "updated comment", MockUserSession.get());
}
@Test
- public void should_not_update_not_found_comment() throws Exception {
+ public void should_not_update_not_found_comment() {
throwable.expect(NotFoundException.class);
when(changeDao.selectCommentByKey("ABCD")).thenReturn(null);
}
@Test
- public void should_prevent_updating_empty_comment() throws Exception {
+ public void should_prevent_updating_empty_comment() {
throwable.expect(BadRequestException.class);
issueCommentService.editComment("ABCD", "", MockUserSession.get());
}
@Test
- public void should_prevent_updating_null_comment() throws Exception {
+ public void should_prevent_updating_null_comment() {
throwable.expect(BadRequestException.class);
issueCommentService.editComment("ABCD", null, MockUserSession.get());
}
@Test
- public void should_prevent_updating_others_comment() throws Exception {
+ public void should_prevent_updating_others_comment() {
throwable.expect(ForbiddenException.class);
when(changeDao.selectCommentByKey("ABCD")).thenReturn(new DefaultIssueComment().setUserLogin("julien"));
IssueQueryService issueQueryService;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(dbClient.openSession(false)).thenReturn(session);
when(dbClient.componentDao()).thenReturn(componentDao);
when(dbClient.authorDao()).thenReturn(authorDao);
}
@Test
- public void should_search_in_tree_with_component_root_uuids_but_unknown_qualifiers() throws Exception {
+ public void should_search_in_tree_with_component_root_uuids_but_unknown_qualifiers() {
Map<String, Object> map = newHashMap();
map.put("componentRootUuids", newArrayList("ABCD"));
}
@Test
- public void should_search_in_tree_with_component_roots_but_different_qualifiers() throws Exception {
+ public void should_search_in_tree_with_component_roots_but_different_qualifiers() {
Map<String, Object> map = newHashMap();
map.put("componentRoots", newArrayList("org.apache.struts:struts", "org.codehaus.sonar:sonar-server"));
}
@Test
- public void should_search_in_tree_with_view() throws Exception {
+ public void should_search_in_tree_with_view() {
String viewUuid = "ABCD";
Map<String, Object> map = newHashMap();
map.put("componentRootUuids", newArrayList(viewUuid));
}
@Test
- public void should_search_in_tree_with_subview_but_bad_permissions() throws Exception {
+ public void should_search_in_tree_with_subview_but_bad_permissions() {
String subViewUuid = "ABCD";
Map<String, Object> map = newHashMap();
map.put("componentRootUuids", newArrayList(subViewUuid));
}
@Test
- public void should_search_in_tree_with_project_uuid() throws Exception {
+ public void should_search_in_tree_with_project_uuid() {
String projectUuid = "ABCD";
Map<String, Object> map = newHashMap();
map.put("componentUuids", newArrayList(projectUuid));
}
@Test
- public void should_search_on_component_only_with_project_key() throws Exception {
+ public void should_search_on_component_only_with_project_key() {
String projectKey = "org.apache.struts:struts";
String projectUuid = "ABCD";
Map<String, Object> map = newHashMap();
}
@Test
- public void should_search_on_developer() throws Exception {
+ public void should_search_on_developer() {
String devUuid = "DEV:anakin.skywalker";
String login1 = "anakin@skywalker.name";
String login2 = "darth.vader";
}
@Test
- public void should_override_authors_when_searching_on_developer() throws Exception {
+ public void should_override_authors_when_searching_on_developer() {
String devUuid = "DEV:anakin.skywalker";
String login = "anakin@skywalker.name";
Map<String, Object> map = newHashMap();
}
@Test
- public void should_search_on_developer_technical_project() throws Exception {
+ public void should_search_on_developer_technical_project() {
String projectUuid = "sample1";
String devUuid = "DEV:anakin.skywalker";
String login1 = "anakin@skywalker.name";
}
@Test
- public void should_search_in_tree_with_module_uuid() throws Exception {
+ public void should_search_in_tree_with_module_uuid() {
String moduleUuid = "ABCD";
Map<String, Object> map = newHashMap();
map.put("componentUuids", newArrayList(moduleUuid));
}
@Test
- public void should_search_in_tree_with_directory_uuid() throws Exception {
+ public void should_search_in_tree_with_directory_uuid() {
String directoryUuid = "ABCD";
String directoryPath = "/some/module/relative/path";
String moduleUuid = "BCDE";
}
@Test
- public void should_search_on_source_file() throws Exception {
+ public void should_search_on_source_file() {
String fileUuid = "ABCD";
Map<String, Object> map = newHashMap();
map.put("componentUuids", newArrayList(fileUuid));
}
@Test
- public void should_search_on_test_file() throws Exception {
+ public void should_search_on_test_file() {
String fileUuid = "ABCD";
Map<String, Object> map = newHashMap();
map.put("componentUuids", newArrayList(fileUuid));
public class IssueQueryTest {
@Test
- public void build_query() throws Exception {
+ public void build_query() {
IssueQuery query = IssueQuery.builder()
.issueKeys(newArrayList("ABCDE"))
.severities(newArrayList(Severity.BLOCKER))
}
@Test
- public void build_query_without_dates() throws Exception {
+ public void build_query_without_dates() {
IssueQuery query = IssueQuery.builder()
.issueKeys(newArrayList("ABCDE"))
.createdAfter(null)
}
@Test
- public void throw_exception_if_sort_is_not_valid() throws Exception {
+ public void throw_exception_if_sort_is_not_valid() {
try {
IssueQuery.builder()
.sort("UNKNOWN")
}
@Test
- public void collection_params_should_not_be_null_but_empty() throws Exception {
+ public void collection_params_should_not_be_null_but_empty() {
IssueQuery query = IssueQuery.builder()
.issueKeys(null)
.componentUuids(null)
}
@Test
- public void should_accept_null_sort() throws Exception {
+ public void should_accept_null_sort() {
IssueQuery query = IssueQuery.builder().sort(null).build();
assertThat(query.sort()).isNull();
}
IssueService service;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
db = tester.get(DbClient.class);
IssueIndex = tester.get(IssueIndex.class);
}
@Test
- public void get_by_key() throws Exception {
+ public void get_by_key() {
RuleDto rule = newRule();
ComponentDto project = newProject();
ComponentDto file = newFile(project);
}
@Test
- public void can_facet() throws Exception {
+ public void can_facet() {
RuleDto rule = newRule();
ComponentDto project = newProject();
ComponentDto file = newFile(project);
}
@Test
- public void should_fail_on_unverified_action_plan() throws Exception {
+ public void should_fail_on_unverified_action_plan() {
throwable.expect(IllegalArgumentException.class);
throwable.expectMessage("Action plan is missing from the execution parameters");
}
@Test
- public void should_unplan_if_action_plan_is_empty() throws Exception {
+ public void should_unplan_if_action_plan_is_empty() {
String planKey = "";
Map<String, Object> properties = newHashMap();
properties.put("plan", planKey);
}
@Test
- public void should_fail_if_tag_is_not_valid() throws Exception {
+ public void should_fail_if_tag_is_not_valid() {
throwable.expect(IllegalArgumentException.class);
throwable.expectMessage("Tag 'th ag' is invalid. Rule tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'");
public class RulesAggregationTest {
@Test
- public void empty() throws Exception {
+ public void empty() {
RulesAggregation rulesAggregation = new RulesAggregation();
assertThat(rulesAggregation.rules()).isEmpty();
}
@Test
- public void count_rules() throws Exception {
+ public void count_rules() {
RulesAggregation rulesAggregation = new RulesAggregation();
RuleKey ruleKey = RuleKey.of("xoo", "S001");
RuleDto ruleDto = RuleTesting.newDto(ruleKey).setName("Rule name");
}
@Test
- public void count_rules_with_different_rules() throws Exception {
+ public void count_rules_with_different_rules() {
RulesAggregation rulesAggregation = new RulesAggregation();
RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("xoo", "S001")).setName("Rule name 1");
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void load_component_id_from_db() throws Exception {
+ public void load_component_id_from_db() {
setupData("load_component_id_from_db");
session.commit();
}
@Test
- public void load_project_id_from_db() throws Exception {
+ public void load_project_id_from_db() {
setupData("load_project_id_from_db");
session.commit();
}
@Test
- public void should_insert_new_issues() throws Exception {
+ public void should_insert_new_issues() {
setupData("should_insert_new_issues");
DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "emmerik", "the comment");
}
@Test
- public void should_update_issues() throws Exception {
+ public void should_update_issues() {
setupData("should_update_issues");
IssueChangeContext context = IssueChangeContext.createUser(new Date(), "emmerik");
WsTester tester = new WsTester(new ActionPlanWs());
@Test
- public void define_controller() throws Exception {
+ public void define_controller() {
WebService.Controller controller = tester.controller("api/action_plans");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
}
@Test
- public void define_search_action() throws Exception {
+ public void define_search_action() {
WebService.Controller controller = tester.controller("api/action_plans");
WebService.Action action = controller.action("search");
}
@Test
- public void define_create_action() throws Exception {
+ public void define_create_action() {
WebService.Controller controller = tester.controller("api/action_plans");
WebService.Action action = controller.action("create");
}
@Test
- public void define_delete_action() throws Exception {
+ public void define_delete_action() {
WebService.Controller controller = tester.controller("api/action_plans");
WebService.Action action = controller.action("delete");
}
@Test
- public void define_update_action() throws Exception {
+ public void define_update_action() {
WebService.Controller controller = tester.controller("api/action_plans");
WebService.Action action = controller.action("update");
}
@Test
- public void define_open_action() throws Exception {
+ public void define_open_action() {
WebService.Controller controller = tester.controller("api/action_plans");
WebService.Action action = controller.action("open");
}
@Test
- public void define_close_action() throws Exception {
+ public void define_close_action() {
WebService.Controller controller = tester.controller("api/action_plans");
WebService.Action action = controller.action("close");
private DbSession session;
@Before
- public void before() throws Exception {
+ public void before() {
this.session = getMyBatis().openSession(false);
this.sut = new IssueDao(getMyBatis());
}
}
@Test
- public void insert() throws Exception {
+ public void insert() {
IssueDto dto = new IssueDto();
dto.setComponent(new ComponentDto().setKey("struts:Action").setId(123L).setUuid("component-uuid"));
dto.setProject(new ComponentDto().setKey("struts").setId(100L).setUuid("project-uuid"));
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
action = new AppAction(service, writer);
tester = new WsTester(new IssueFilterWs(action, mock(ShowAction.class), mock(FavoritesAction.class)));
}
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
action = new FavoritesAction(service);
tester = new WsTester(new IssueFilterWs(mock(AppAction.class), mock(ShowAction.class), action));
}
}
@Test
- public void should_change_shared_filter_ownership_when_admin() throws Exception {
+ public void should_change_shared_filter_ownership_when_admin() {
IssueFilterDto sharedFilter = new IssueFilterDto().setId(1L).setName("My filter").setUserLogin("former.owner").setShared(true);
IssueFilterDto expectedDto = new IssueFilterDto().setName("My filter").setUserLogin("new.owner").setShared(true);
}
@Test
- public void should_deny_filter_ownership_change_when_not_admin() throws Exception {
+ public void should_deny_filter_ownership_change_when_not_admin() {
String currentUser = "dave.loper";
IssueFilterDto sharedFilter = new IssueFilterDto().setId(1L).setName("My filter").setUserLogin(currentUser).setShared(true);
}
@Test
- public void should_create_filter_provided_by_platform() throws Exception {
+ public void should_create_filter_provided_by_platform() {
ArgumentCaptor<IssueFilterDto> filterCaptor = ArgumentCaptor.forClass(IssueFilterDto.class);
IssueFilterWriter writer = new IssueFilterWriter();
@Test
- public void write_filter() throws Exception {
+ public void write_filter() {
UserSession userSession = MockUserSession.set();
test(userSession,
new IssueFilterDto()
}
@Test
- public void can_modify_if_logged_user_own_filter() throws Exception {
+ public void can_modify_if_logged_user_own_filter() {
UserSession userSession = MockUserSession.set().setLogin("simon");
test(userSession,
new IssueFilterDto()
}
@Test
- public void can_modify_if_logged_user_has_permission() throws Exception {
+ public void can_modify_if_logged_user_has_permission() {
UserSession userSession = MockUserSession.set().setLogin("simon").setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
test(userSession,
new IssueFilterDto()
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
ws = new IssueFilterWs(new AppAction(service, issueFilterWriter), new ShowAction(service, issueFilterWriter), new FavoritesAction(service));
tester = new WsTester(ws);
}
@Test
- public void define_ws() throws Exception {
+ public void define_ws() {
WebService.Controller controller = tester.controller("api/issue_filters");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
private System2 system;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
IssueFilterDao issueFilterDao = new IssueFilterDao(db.myBatis());
LoadedTemplateDao loadedTemplateDao = new LoadedTemplateDao(db.myBatis());
system = mock(System2.class);
}
@Test
- public void should_do_nothing_if_not_needed() throws Exception {
+ public void should_do_nothing_if_not_needed() {
db.prepareDbUnit(getClass(), "do_nothing.xml");
taskUnderTest.start();
taskUnderTest.stop();
}
@Test
- public void should_register_issue_filters() throws Exception {
+ public void should_register_issue_filters() {
Date now = DateUtils.parseDateTime("2011-04-25T01:15:00+0200");
when(system.now()).thenReturn(now.getTime());
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
action = new ShowAction(service, writer);
tester = new WsTester(new IssueFilterWs(mock(AppAction.class), action, mock(FavoritesAction.class)));
}
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
DbUtils.closeQuietly(connection);
}
@Test
- public void select_all() throws Exception {
+ public void select_all() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
Collection<IssueAuthorizationDao.Dto> dtos = dao.selectAfterDate(client, connection, 0L);
}
@Test
- public void select_after_date() throws Exception {
+ public void select_after_date() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
Collection<IssueAuthorizationDao.Dto> dtos = dao.selectAfterDate(client, connection, 1500000000L);
}
@Test
- public void no_authorization() throws Exception {
+ public void no_authorization() {
dbTester.prepareDbUnit(getClass(), "no_authorization.xml");
Collection<IssueAuthorizationDao.Dto> dtos = dao.selectAfterDate(client, connection, 0L);
public static EsTester esTester = new EsTester().addDefinitions(new IssueIndexDefinition(new Settings()));
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
esTester.truncateIndices();
}
@Test
- public void index_nothing() throws Exception {
+ public void index_nothing() {
IssueAuthorizationIndexer indexer = createIndexer();
indexer.index();
}
@Test
- public void index() throws Exception {
+ public void index() {
dbTester.prepareDbUnit(getClass(), "index.xml");
IssueAuthorizationIndexer indexer = createIndexer();
}
@Test
- public void do_not_fail_when_deleting_unindexed_project() throws Exception {
+ public void do_not_fail_when_deleting_unindexed_project() {
IssueAuthorizationIndexer indexer = createIndexer();
indexer.deleteProject("UNKNOWN", true);
assertThat(esTester.countDocuments("issues", "authorization")).isZero();
}
@Test
- public void delete_permissions() throws Exception {
+ public void delete_permissions() {
IssueAuthorizationIndexer indexer = createIndexer();
IssueAuthorizationDao.Dto authorization = new IssueAuthorizationDao.Dto("ABC", System.currentTimeMillis());
authorization.addUser("guy");
IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext();
@Test
- public void define() throws Exception {
+ public void define() {
IssueIndexDefinition def = new IssueIndexDefinition(new Settings());
def.define(context);
}
@Test
- public void enable_cluster() throws Exception {
+ public void enable_cluster() {
Settings settings = new Settings();
settings.setProperty(ProcessProperties.CLUSTER_ACTIVATE, true);
IssueIndexDefinition def = new IssueIndexDefinition(settings);
ViewIndexer viewIndexer;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.truncateIndices();
issueIndexer = new IssueIndexer(null, tester.client());
issueAuthorizationIndexer = new IssueAuthorizationIndexer(null, tester.client());
}
@Test
- public void get_by_key() throws Exception {
+ public void get_by_key() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
IssueDoc issue = IssueTesting.newDoc("ISSUE1", file);
}
@Test
- public void get_by_key_with_attributes() throws Exception {
+ public void get_by_key_with_attributes() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
IssueDoc issue = IssueTesting.newDoc("ISSUE1", file).setAttributes((KeyValueFormat.format(ImmutableMap.of("jira-issue-key", "SONAR-1234"))));
}
@Test(expected = IllegalStateException.class)
- public void comments_field_is_not_available() throws Exception {
+ public void comments_field_is_not_available() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
IssueDoc issue = IssueTesting.newDoc("ISSUE1", file);
}
@Test(expected = IllegalStateException.class)
- public void is_new_field_is_not_available() throws Exception {
+ public void is_new_field_is_not_available() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
IssueDoc issue = IssueTesting.newDoc("ISSUE1", file);
}
@Test(expected = NotFoundException.class)
- public void fail_to_get_unknown_key() throws Exception {
+ public void fail_to_get_unknown_key() {
index.getByKey("unknown");
}
@Test
- public void filter_by_keys() throws Exception {
+ public void filter_by_keys() {
ComponentDto project = ComponentTesting.newProjectDto();
indexIssues(
}
@Test
- public void filter_by_projects() throws Exception {
+ public void filter_by_projects() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto module = ComponentTesting.newModuleDto(project);
ComponentDto subModule = ComponentTesting.newModuleDto(module);
}
@Test
- public void facets_on_projects() throws Exception {
+ public void facets_on_projects() {
ComponentDto project = ComponentTesting.newProjectDto("ABCD");
ComponentDto project2 = ComponentTesting.newProjectDto("EFGH");
}
@Test
- public void filter_by_modules() throws Exception {
+ public void filter_by_modules() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto module = ComponentTesting.newModuleDto(project);
ComponentDto subModule = ComponentTesting.newModuleDto(module);
}
@Test
- public void filter_by_components_on_contextualized_search() throws Exception {
+ public void filter_by_components_on_contextualized_search() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto module = ComponentTesting.newModuleDto(project);
ComponentDto subModule = ComponentTesting.newModuleDto(module);
}
@Test
- public void filter_by_components_on_non_contextualized_search() throws Exception {
+ public void filter_by_components_on_non_contextualized_search() {
ComponentDto project = ComponentTesting.newProjectDto("project");
ComponentDto file1 = ComponentTesting.newFileDto(project, "file1");
ComponentDto module = ComponentTesting.newModuleDto(project).setUuid("module");
}
@Test
- public void facets_on_components() throws Exception {
+ public void facets_on_components() {
ComponentDto project = ComponentTesting.newProjectDto("A");
ComponentDto file1 = ComponentTesting.newFileDto(project, "ABCD");
ComponentDto file2 = ComponentTesting.newFileDto(project, "BCDE");
}
@Test
- public void filter_by_directories() throws Exception {
+ public void filter_by_directories() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file1 = ComponentTesting.newFileDto(project).setPath("src/main/xoo/F1.xoo");
ComponentDto file2 = ComponentTesting.newFileDto(project).setPath("F2.xoo");
}
@Test
- public void facets_on_directories() throws Exception {
+ public void facets_on_directories() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file1 = ComponentTesting.newFileDto(project).setPath("src/main/xoo/F1.xoo");
ComponentDto file2 = ComponentTesting.newFileDto(project).setPath("F2.xoo");
}
@Test
- public void filter_by_views() throws Exception {
+ public void filter_by_views() {
ComponentDto project1 = ComponentTesting.newProjectDto();
ComponentDto file1 = ComponentTesting.newFileDto(project1);
ComponentDto project2 = ComponentTesting.newProjectDto();
}
@Test
- public void filter_by_severities() throws Exception {
+ public void filter_by_severities() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void facets_on_severities() throws Exception {
+ public void facets_on_severities() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void filter_by_statuses() throws Exception {
+ public void filter_by_statuses() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void facets_on_statuses() throws Exception {
+ public void facets_on_statuses() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void filter_by_resolutions() throws Exception {
+ public void filter_by_resolutions() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void facets_on_resolutions() throws Exception {
+ public void facets_on_resolutions() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void filter_by_resolved() throws Exception {
+ public void filter_by_resolved() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void filter_by_action_plans() throws Exception {
+ public void filter_by_action_plans() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void facets_on_action_plans() throws Exception {
+ public void facets_on_action_plans() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void filter_by_planned() throws Exception {
+ public void filter_by_planned() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void filter_by_rules() throws Exception {
+ public void filter_by_rules() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
RuleKey ruleKey = RuleKey.of("repo", "X1");
}
@Test
- public void filter_by_languages() throws Exception {
+ public void filter_by_languages() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
RuleKey ruleKey = RuleKey.of("repo", "X1");
}
@Test
- public void facets_on_languages() throws Exception {
+ public void facets_on_languages() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
RuleKey ruleKey = RuleKey.of("repo", "X1");
}
@Test
- public void filter_by_assignees() throws Exception {
+ public void filter_by_assignees() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void facets_on_assignees() throws Exception {
+ public void facets_on_assignees() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void facets_on_assignees_supports_dashes() throws Exception {
+ public void facets_on_assignees_supports_dashes() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void filter_by_assigned() throws Exception {
+ public void filter_by_assigned() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void filter_by_reporters() throws Exception {
+ public void filter_by_reporters() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void filter_by_authors() throws Exception {
+ public void filter_by_authors() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void facets_on_authors() throws Exception {
+ public void facets_on_authors() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void filter_by_created_after() throws Exception {
+ public void filter_by_created_after() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void filter_by_created_before() throws Exception {
+ public void filter_by_created_before() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void filter_by_created_after_and_before() throws Exception {
+ public void filter_by_created_after_and_before() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void filter_by_created_before_must_be_lower_than_after() throws Exception {
+ public void filter_by_created_before_must_be_lower_than_after() {
try {
index.search(IssueQuery.builder().createdAfter(DateUtils.parseDate("2014-09-20")).createdBefore(DateUtils.parseDate("2014-09-19")).build(), new SearchOptions());
Fail.failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
}
@Test
- public void filter_by_created_after_must_not_be_in_future() throws Exception {
+ public void filter_by_created_after_must_not_be_in_future() {
try {
index.search(IssueQuery.builder().createdAfter(new Date(Long.MAX_VALUE)).build(), new SearchOptions());
Fail.failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
}
@Test
- public void filter_by_created_at() throws Exception {
+ public void filter_by_created_at() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void facet_on_created_at_with_less_than_20_days() throws Exception {
+ public void facet_on_created_at_with_less_than_20_days() {
SearchOptions options = fixtureForCreatedAtFacet();
}
@Test
- public void facet_on_created_at_with_less_than_20_weeks() throws Exception {
+ public void facet_on_created_at_with_less_than_20_weeks() {
SearchOptions SearchOptions = fixtureForCreatedAtFacet();
}
@Test
- public void facet_on_created_at_with_less_than_20_months() throws Exception {
+ public void facet_on_created_at_with_less_than_20_months() {
SearchOptions SearchOptions = fixtureForCreatedAtFacet();
}
@Test
- public void facet_on_created_at_with_more_than_20_months() throws Exception {
+ public void facet_on_created_at_with_more_than_20_months() {
SearchOptions SearchOptions = fixtureForCreatedAtFacet();
Map<String, Long> createdAt = index.search(IssueQuery.builder()
}
@Test
- public void facet_on_created_at_with_bounds_outside_of_data() throws Exception {
+ public void facet_on_created_at_with_bounds_outside_of_data() {
SearchOptions options = fixtureForCreatedAtFacet();
Map<String, Long> createdAt = index.search(IssueQuery.builder()
}
@Test
- public void facet_on_created_at_without_start_bound() throws Exception {
+ public void facet_on_created_at_without_start_bound() {
SearchOptions SearchOptions = fixtureForCreatedAtFacet();
Map<String, Long> createdAt = index.search(IssueQuery.builder()
}
@Test
- public void facet_on_created_at_without_issues() throws Exception {
+ public void facet_on_created_at_without_issues() {
SearchOptions SearchOptions = new SearchOptions().addFacets("createdAt");
Map<String, Long> createdAt = index.search(IssueQuery.builder().build(),
}
@Test
- public void paging() throws Exception {
+ public void paging() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
for (int i = 0; i < 12; i++) {
}
@Test
- public void search_with_max_limit() throws Exception {
+ public void search_with_max_limit() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
List<IssueDoc> issues = newArrayList();
}
@Test
- public void sort_by_status() throws Exception {
+ public void sort_by_status() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void sort_by_severity() throws Exception {
+ public void sort_by_severity() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void sort_by_assignee() throws Exception {
+ public void sort_by_assignee() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void sort_by_creation_date() throws Exception {
+ public void sort_by_creation_date() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void sort_by_update_date() throws Exception {
+ public void sort_by_update_date() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void sort_by_close_date() throws Exception {
+ public void sort_by_close_date() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file = ComponentTesting.newFileDto(project);
}
@Test
- public void sort_by_file_and_line() throws Exception {
+ public void sort_by_file_and_line() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto file1 = ComponentTesting.newFileDto(project, "F1").setPath("src/main/xoo/org/sonar/samples/File.xoo");
ComponentDto file2 = ComponentTesting.newFileDto(project, "F2").setPath("src/main/xoo/org/sonar/samples/File2.xoo");
}
@Test
- public void authorized_issues_on_groups() throws Exception {
+ public void authorized_issues_on_groups() {
ComponentDto project1 = ComponentTesting.newProjectDto().setKey("project1");
ComponentDto project2 = ComponentTesting.newProjectDto().setKey("project2");
ComponentDto project3 = ComponentTesting.newProjectDto().setKey("project3");
}
@Test
- public void authorized_issues_on_user() throws Exception {
+ public void authorized_issues_on_user() {
ComponentDto project1 = ComponentTesting.newProjectDto().setKey("project1");
ComponentDto project2 = ComponentTesting.newProjectDto().setKey("project2");
ComponentDto project3 = ComponentTesting.newProjectDto().setKey("project3");
}
@Test
- public void authorized_issues_on_user_and_group() throws Exception {
+ public void authorized_issues_on_user_and_group() {
ComponentDto project1 = ComponentTesting.newProjectDto().setKey("project1");
ComponentDto project2 = ComponentTesting.newProjectDto().setKey("project2");
}
@Test
- public void search_issues_for_batch_return_needed_fields() throws Exception {
+ public void search_issues_for_batch_return_needed_fields() {
ComponentDto project = ComponentTesting.newProjectDto("PROJECT");
ComponentDto file = ComponentTesting.newFileDto(project).setPath("src/File.xoo");
}
@Test
- public void search_issues_for_batch() throws Exception {
+ public void search_issues_for_batch() {
ComponentDto project = ComponentTesting.newProjectDto();
ComponentDto module = ComponentTesting.newModuleDto(project);
ComponentDto subModule = ComponentTesting.newModuleDto(module);
}
@Test
- public void fail_to_search_issues_for_batch_on_not_allowed_scope() throws Exception {
+ public void fail_to_search_issues_for_batch_on_not_allowed_scope() {
try {
index.selectIssuesForBatch(new ComponentDto().setScope(Scopes.DIRECTORY));
failBecauseExceptionWasNotThrown(IllegalStateException.class);
}
@Test
- public void search_issues_for_batch_return_only_authorized_issues() throws Exception {
+ public void search_issues_for_batch_return_only_authorized_issues() {
ComponentDto project1 = ComponentTesting.newProjectDto().setKey("project1");
ComponentDto project2 = ComponentTesting.newProjectDto().setKey("project2");
public static EsTester esTester = new EsTester().addDefinitions(new IssueIndexDefinition(new Settings()));
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
esTester.truncateIndices();
}
@Test
- public void index_nothing() throws Exception {
+ public void index_nothing() {
IssueIndexer indexer = createIndexer();
indexer.index(Iterators.<IssueDoc>emptyIterator());
assertThat(esTester.countDocuments(IssueIndexDefinition.INDEX, IssueIndexDefinition.TYPE_ISSUE)).isEqualTo(0L);
}
@Test
- public void index_nothing_if_disabled() throws Exception {
+ public void index_nothing_if_disabled() {
dbTester.prepareDbUnit(getClass(), "index.xml");
createIndexer().setEnabled(false).index();
}
@Test
- public void index() throws Exception {
+ public void index() {
dbTester.prepareDbUnit(getClass(), "index.xml");
IssueIndexer indexer = createIndexer();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
DbUtils.closeQuietly(connection);
}
@Test
- public void iterator_over_one_issue() throws Exception {
+ public void iterator_over_one_issue() {
dbTester.prepareDbUnit(getClass(), "one_issue.xml");
IssueResultSetIterator it = IssueResultSetIterator.create(client, connection, 0L);
Map<String, IssueDoc> issuesByKey = issuesByKey(it);
}
@Test
- public void iterator_over_issues() throws Exception {
+ public void iterator_over_issues() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
IssueResultSetIterator it = IssueResultSetIterator.create(client, connection, 0L);
Map<String, IssueDoc> issuesByKey = issuesByKey(it);
}
@Test
- public void extract_directory_path() throws Exception {
+ public void extract_directory_path() {
dbTester.prepareDbUnit(getClass(), "extract_directory_path.xml");
IssueResultSetIterator it = IssueResultSetIterator.create(client, connection, 0L);
Map<String, IssueDoc> issuesByKey = issuesByKey(it);
}
@Test
- public void extract_file_path() throws Exception {
+ public void extract_file_path() {
dbTester.prepareDbUnit(getClass(), "extract_file_path.xml");
IssueResultSetIterator it = IssueResultSetIterator.create(client, connection, 0L);
Map<String, IssueDoc> issuesByKey = issuesByKey(it);
}
@Test
- public void select_after_date() throws Exception {
+ public void select_after_date() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
IssueResultSetIterator it = IssueResultSetIterator.create(client, connection, 1420000000000L);
}
@Test
- public void should_not_dispatch_if_other_notification_type() throws Exception {
+ public void should_not_dispatch_if_other_notification_type() {
Notification notification = new Notification("other-notif");
dispatcher.performDispatch(notification, context);
}
@Test
- public void should_not_dispatch_if_other_notification_type() throws Exception {
+ public void should_not_dispatch_if_other_notification_type() {
Notification notification = new Notification("other");
sut.performDispatch(notification, context);
IssueChangeNotification notification = new IssueChangeNotification();
@Test
- public void set_issue() throws Exception {
+ public void set_issue() {
DefaultIssue issue = new DefaultIssue()
.setKey("ABCD")
.setReporter("arthur")
}
@Test
- public void set_issue_with_current_change_having_no_old_value() throws Exception {
+ public void set_issue_with_current_change_having_no_old_value() {
DefaultIssue issue = new DefaultIssue()
.setKey("ABCD")
.setReporter("arthur")
}
@Test
- public void set_issue_with_current_change_having_no_new_value() throws Exception {
+ public void set_issue_with_current_change_having_no_new_value() {
DefaultIssue issue = new DefaultIssue()
.setKey("ABCD")
.setReporter("arthur")
}
@Test
- public void set_project() throws Exception {
+ public void set_project() {
IssueChangeNotification result = notification.setProject(new ComponentDto().setKey("MyService").setLongName("My Service"));
assertThat(result.getFieldValue("projectKey")).isEqualTo("MyService");
assertThat(result.getFieldValue("projectName")).isEqualTo("My Service");
}
@Test
- public void set_component() throws Exception {
+ public void set_component() {
IssueChangeNotification result = notification.setComponent(new ComponentDto().setKey("MyService").setLongName("My Service"));
assertThat(result.getFieldValue("componentName")).isEqualTo("My Service");
}
@Test
- public void set_change_author_login() throws Exception {
+ public void set_change_author_login() {
IssueChangeNotification result = notification.setChangeAuthorLogin("stephane");
assertThat(result.getFieldValue("changeAuthor")).isEqualTo("stephane");
}
@Test
- public void set_rule_name() throws Exception {
+ public void set_rule_name() {
IssueChangeNotification result = notification.setRuleName("Xoo Rule");
assertThat(result.getFieldValue("ruleName")).isEqualTo("Xoo Rule");
}
@Test
- public void setComment() throws Exception {
+ public void setComment() {
IssueChangeNotification result = notification.setComment("My comment");
assertThat(result.getFieldValue("comment")).isEqualTo("My comment");
}
}
@Test
- public void message_id() throws Exception {
+ public void message_id() {
Notification notification = newNotification();
EmailMessage message = sut.format(notification);
}
@Test
- public void subject() throws Exception {
+ public void subject() {
Notification notification = newNotification();
EmailMessage message = sut.format(notification);
}
@Test
- public void do_not_dispatch_if_no_new_notification() throws Exception {
+ public void do_not_dispatch_if_no_new_notification() {
Notification notification = new Notification("other-notif");
sut.performDispatch(notification, context);
MyNewIssuesNotification sut = new MyNewIssuesNotification(mock(UserIndex.class), mock(RuleIndex.class), mock(DbClient.class), mock(Durations.class));
@Test
- public void set_assignee() throws Exception {
+ public void set_assignee() {
sut.setAssignee("myAssignee");
assertThat(sut.getFieldValue(FIELD_ASSIGNEE)).isEqualTo("myAssignee");
}
@Test
- public void set_with_a_specific_type() throws Exception {
+ public void set_with_a_specific_type() {
assertThat(sut.getType()).isEqualTo(MyNewIssuesNotification.TYPE);
}
}
@Test
- public void message_id() throws Exception {
+ public void message_id() {
Notification notification = newNotification();
EmailMessage message = template.format(notification);
}
@Test
- public void subject() throws Exception {
+ public void subject() {
Notification notification = newNotification();
EmailMessage message = template.format(notification);
}
@Test
- public void shouldNotDispatchIfNotNewViolationsNotification() throws Exception {
+ public void shouldNotDispatchIfNotNewViolationsNotification() {
Notification notification = new Notification("other-notif");
dispatcher.performDispatch(notification, context);
NewIssuesNotification sut = new NewIssuesNotification(userIndex, ruleIndex, dbClient, durations);
@Test
- public void set_project() throws Exception {
+ public void set_project() {
ComponentDto component = ComponentTesting.newProjectDto()
.setLongName("project-long-name")
.setUuid("project-uuid")
}
@Test
- public void set_date() throws Exception {
+ public void set_date() {
Date date = new Date();
sut.setAnalysisDate(date);
}
@Test
- public void set_statistics() throws Exception {
+ public void set_statistics() {
ComponentDto component = ComponentTesting.newProjectDto()
.setLongName("project-long-name");
addIssueNTimes(newIssue1(), 5);
}
@Test
- public void set_debt() throws Exception {
+ public void set_debt() {
when(durations.format(any(Locale.class), any(Duration.class))).thenReturn("55 min");
sut.setDebt(Duration.create(55));
NewIssuesStatistics sut = new NewIssuesStatistics();
@Test
- public void add_issues_with_correct_global_statistics() throws Exception {
+ public void add_issues_with_correct_global_statistics() {
DefaultIssue issue = defaultIssue();
sut.add(issue);
}
@Test
- public void do_not_have_issues_when_no_issue_added() throws Exception {
+ public void do_not_have_issues_when_no_issue_added() {
assertThat(sut.globalStatistics().hasIssues()).isFalse();
}
IssueService service;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester = new WsTester(new IssuesWs(new AuthorsAction(service)));
controller = tester.controller("api/issues");
}
}
@Test
- public void should_define() throws Exception {
+ public void should_define() {
Action action = tester.controller("api/issues").action("component_tags");
assertThat(action.description()).isNotEmpty();
assertThat(action.responseExampleAsString()).isNotEmpty();
IssueActionsWriter writer;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
writer = new IssueActionsWriter(issueService, actionService);
}
@Test
- public void write_all_standard_actions() throws Exception {
+ public void write_all_standard_actions() {
Issue issue = new DefaultIssue()
.setKey("ABCD")
.setComponentUuid("BCDE")
}
@Test
- public void write_plugin_actions() throws Exception {
+ public void write_plugin_actions() {
Issue issue = new DefaultIssue()
.setKey("ABCD")
.setComponentKey("sample:src/main/xoo/sample/Sample.xoo")
}
@Test
- public void write_only_comment_action() throws Exception {
+ public void write_only_comment_action() {
Issue issue = new DefaultIssue()
.setKey("ABCD")
.setComponentKey("sample:src/main/xoo/sample/Sample.xoo")
}
@Test
- public void write_no_action_if_not_logged() throws Exception {
+ public void write_no_action_if_not_logged() {
Issue issue = new DefaultIssue()
.setKey("ABCD")
.setComponentKey("sample:src/main/xoo/sample/Sample.xoo")
}
@Test
- public void write_actions_without_assign_to_me() throws Exception {
+ public void write_actions_without_assign_to_me() {
Issue issue = new DefaultIssue()
.setKey("ABCD")
.setComponentKey("sample:src/main/xoo/sample/Sample.xoo")
}
@Test
- public void write_transitions() throws Exception {
+ public void write_transitions() {
Issue issue = new DefaultIssue()
.setKey("ABCD")
.setComponentKey("sample:src/main/xoo/sample/Sample.xoo")
}
@Test
- public void write_no_transitions() throws Exception {
+ public void write_no_transitions() {
Issue issue = new DefaultIssue()
.setKey("ABCD")
.setComponentKey("sample:src/main/xoo/sample/Sample.xoo")
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(dbClient.openSession(false)).thenReturn(session);
when(dbClient.componentDao()).thenReturn(componentDao);
}
@Test
- public void should_define() throws Exception {
+ public void should_define() {
Action action = tester.controller("api/issues").action("tags");
assertThat(action.description()).isNotEmpty();
assertThat(action.responseExampleAsString()).isNotEmpty();
public class IssuesWsTest {
@Test
- public void define_actions() throws Exception {
+ public void define_actions() {
BaseIssuesWsAction action1 = mock(BaseIssuesWsAction.class);
BaseIssuesWsAction action2 = mock(BaseIssuesWsAction.class);
IssuesWs ws = new IssuesWs(action1, action2);
WsTester wsTester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
db = tester.get(DbClient.class);
wsTester = tester.get(WsTester.class);
WsTester wsTester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
db = tester.get(DbClient.class);
wsTester = tester.get(WsTester.class);
}
@Test
- public void define_action() throws Exception {
+ public void define_action() {
WebService.Controller controller = wsTester.controller("api/issues");
WebService.Action show = controller.action("search");
}
@Test
- public void should_define() throws Exception {
+ public void should_define() {
Action action = tester.controller("api/issues").action("set_tags");
assertThat(action.description()).isNotEmpty();
assertThat(action.responseExampleAsString()).isNull();
}
@Test
- public void should_be_well_defined() throws Exception {
+ public void should_be_well_defined() {
Controller controller = tester.controller(CONTROLLER_LANGUAGES);
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
}
@Test
- public void keep_error_but_do_not_fail() throws Exception {
+ public void keep_error_but_do_not_fail() {
Map<String, Object> filterMap = ImmutableMap.of("qualifiers", (Object) "TRK");
MeasureFilterFactory factory = mock(MeasureFilterFactory.class);
when(factory.create(filterMap)).thenThrow(new IllegalArgumentException());
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void get_value_by_key() throws Exception {
+ public void get_value_by_key() {
db.prepareDbUnit(getClass(), "shared.xml");
MeasureDto result = sut.findByComponentKeyAndMetricKey(session, "org.struts:struts-core:src/org/struts/RequestContext.java", "ncloc");
@Test
// TODO the string must be longer than 4000 char to be persisted in the data field
- public void get_data_by_key() throws Exception {
+ public void get_data_by_key() {
db.prepareDbUnit(getClass(), "shared.xml");
MeasureDto result = sut.findByComponentKeyAndMetricKey(session, "org.struts:struts-core:src/org/struts/RequestContext.java", "authors_by_line");
}
@Test
- public void get_text_value_by_key() throws Exception {
+ public void get_text_value_by_key() {
db.prepareDbUnit(getClass(), "shared.xml");
MeasureDto result = sut.findByComponentKeyAndMetricKey(session, "org.struts:struts-core:src/org/struts/RequestContext.java", "coverage_line_hits_data");
}
@Test
- public void find_by_component_key_and_metrics() throws Exception {
+ public void find_by_component_key_and_metrics() {
db.prepareDbUnit(getClass(), "shared.xml");
List<MeasureDto> results = sut.findByComponentKeyAndMetricKeys(session, "org.struts:struts-core:src/org/struts/RequestContext.java",
}
@Test
- public void find_by_component_key_and_metric() throws Exception {
+ public void find_by_component_key_and_metric() {
db.prepareDbUnit(getClass(), "shared.xml");
MeasureDto result = sut.findByComponentKeyAndMetricKey(session, "org.struts:struts-core:src/org/struts/RequestContext.java", "ncloc");
}
@Test
- public void exists_by_key() throws Exception {
+ public void exists_by_key() {
db.prepareDbUnit(getClass(), "shared.xml");
assertThat(sut.existsByKey(session, "org.struts:struts-core:src/org/struts/RequestContext.java", "ncloc")).isTrue();
}
@Test
- public void insert() throws Exception {
+ public void insert() {
db.prepareDbUnit(getClass(), "empty.xml");
sut.insert(session, new MeasureDto()
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void get_by_key() throws Exception {
+ public void get_by_key() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
MetricDto result = dao.selectByKey(session, "coverage");
}
@Test
- public void get_manual_metric() throws Exception {
+ public void get_manual_metric() {
dbTester.prepareDbUnit(getClass(), "manual_metric.xml");
MetricDto result = dao.selectByKey(session, "manual");
}
@Test
- public void find_all_enabled() throws Exception {
+ public void find_all_enabled() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
assertThat(dao.selectEnabled(session)).hasSize(2);
}
@Test
- public void insert() throws Exception {
+ public void insert() {
dao.insert(session, new MetricDto()
.setId(1)
.setKey("coverage")
WsTester tester = new WsTester(new ManualMeasuresWs());
@Test
- public void define_ws() throws Exception {
+ public void define_ws() {
WebService.Controller controller = tester.controller("api/manual_measures");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
WsTester tester = new WsTester(new MetricsWs());
@Test
- public void define_ws() throws Exception {
+ public void define_ws() {
WebService.Controller controller = tester.controller("api/metrics");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
WebService.Controller controller;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
WsTester tester = new WsTester(new TimeMachineWs());
controller = tester.controller("api/timemachine");
}
@Test
- public void define_controller() throws Exception {
+ public void define_controller() {
assertThat(controller).isNotNull();
assertThat(controller.since()).isEqualTo("2.10");
assertThat(controller.description()).isNotEmpty();
}
@Test
- public void define_index_action() throws Exception {
+ public void define_index_action() {
WebService.Action action = controller.action("index");
assertThat(action).isNotNull();
assertThat(action.handler()).isInstanceOf(RailsHandler.class);
}
@Test
- public void shouldLogEvery10Minutes() throws InterruptedException {
+ public void shouldLogEvery10Minutes() {
setUpMocks();
// Emulate 2 notifications in DB
when(manager.getFromQueue()).thenReturn(notification).thenReturn(notification).thenReturn(null);
public ExpectedException throwable = ExpectedException.none();
@Test
- public void should_populate_with_params() throws Exception {
+ public void should_populate_with_params() {
Map<String, Object> params = Maps.newHashMap();
params.put("template_key", "my_template_key");
}
@Test
- public void should_invalidate_query_with_empty_name() throws Exception {
+ public void should_invalidate_query_with_empty_name() {
throwable.expect(BadRequestException.class);
throwable.expectMessage("Permission template is mandatory");
}
@Test
- public void should_invalidate_query_with_no_components() throws Exception {
+ public void should_invalidate_query_with_no_components() {
throwable.expect(BadRequestException.class);
throwable.expectMessage("Please provide at least one entry to which the permission template should be applied");
ComponentDto project;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
db = tester.get(DbClient.class);
session = db.openSession(false);
}
@Test
- public void add_project_permission_to_user() throws Exception {
+ public void add_project_permission_to_user() {
// init
MockUserSession.set().setLogin("admin").addProjectPermissions(UserRole.ADMIN, project.key());
UserDto user = new UserDto().setLogin("john").setName("John");
}
@Test
- public void remove_project_permission_to_user() throws Exception {
+ public void remove_project_permission_to_user() {
MockUserSession.set().setLogin("admin").addProjectPermissions(UserRole.ADMIN, project.key());
UserDto user1 = new UserDto().setLogin("user1").setName("User1");
}
@Test
- public void remove_all_component_user_permissions() throws Exception {
+ public void remove_all_component_user_permissions() {
MockUserSession.set().setLogin("admin").addProjectPermissions(UserRole.ADMIN, project.key());
UserDto user = new UserDto().setLogin("user1").setName("User1");
}
@Test
- public void add_and_remove_permission_to_group() throws Exception {
+ public void add_and_remove_permission_to_group() {
// init
MockUserSession.set().setLogin("admin").addProjectPermissions(UserRole.ADMIN, project.key());
GroupDto group = new GroupDto().setName("group1");
}
@Test
- public void find_users_with_permission_template() throws Exception {
+ public void find_users_with_permission_template() {
service.findUsersWithPermissionTemplate(ImmutableMap.<String, Object>of(
"permission", "user",
"template", "my_template",
}
@Test
- public void find_groups_with_permission_template() throws Exception {
+ public void find_groups_with_permission_template() {
service.findGroupsWithPermissionTemplate(ImmutableMap.<String, Object>of(
"permission", "user",
"template", "my_template",
}
@Test
- public void should_create_permission_template() throws Exception {
+ public void should_create_permission_template() {
when(permissionTemplateDao.createPermissionTemplate(DEFAULT_KEY, DEFAULT_DESC, DEFAULT_PATTERN)).thenReturn(DEFAULT_TEMPLATE);
PermissionTemplate permissionTemplate = service.createPermissionTemplate(DEFAULT_KEY, DEFAULT_DESC, DEFAULT_PATTERN);
}
@Test
- public void should_enforce_unique_template_name() throws Exception {
+ public void should_enforce_unique_template_name() {
expected.expect(BadRequestException.class);
expected.expectMessage("A template with that name already exists");
}
@Test
- public void should_reject_empty_name_on_creation() throws Exception {
+ public void should_reject_empty_name_on_creation() {
expected.expect(BadRequestException.class);
expected.expectMessage("Name can't be blank");
}
@Test
- public void should_reject_invalid_key_pattern_on_creation() throws Exception {
+ public void should_reject_invalid_key_pattern_on_creation() {
expected.expect(BadRequestException.class);
expected.expectMessage("Invalid pattern: [azerty. Should be a valid Java regular expression.");
}
@Test
- public void should_delete_permission_template() throws Exception {
+ public void should_delete_permission_template() {
when(permissionTemplateDao.selectTemplateByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
service.deletePermissionTemplate(1L);
}
@Test
- public void should_retrieve_permission_template() throws Exception {
+ public void should_retrieve_permission_template() {
List<PermissionTemplateUserDto> usersPermissions = Lists.newArrayList(
buildUserPermission("user_scan", GlobalPermissions.SCAN_EXECUTION),
}
@Test
- public void should_retrieve_all_permission_templates() throws Exception {
+ public void should_retrieve_all_permission_templates() {
PermissionTemplateDto template1 =
new PermissionTemplateDto().setId(1L).setName("template1").setDescription("template1");
PermissionTemplateDto template2 =
}
@Test
- public void should_retrieve_all_permission_templates_from_project() throws Exception {
+ public void should_retrieve_all_permission_templates_from_project() {
MockUserSession.set().setLogin("admin").addProjectPermissions(UserRole.ADMIN, "org.sample.Sample");
PermissionTemplateDto template1 =
}
@Test
- public void should_update_permission_template() throws Exception {
+ public void should_update_permission_template() {
service.updatePermissionTemplate(1L, "new_name", "new_description", null);
}
@Test
- public void should_validate_template_name_on_update_if_applicable() throws Exception {
+ public void should_validate_template_name_on_update_if_applicable() {
expected.expect(BadRequestException.class);
expected.expectMessage("A template with that name already exists");
}
@Test
- public void should_validate_template_key_pattern_on_update_if_applicable() throws Exception {
+ public void should_validate_template_key_pattern_on_update_if_applicable() {
expected.expect(BadRequestException.class);
expected.expectMessage("Invalid pattern: [azerty. Should be a valid Java regular expression.");
}
@Test
- public void should_skip_name_validation_where_not_applicable() throws Exception {
+ public void should_skip_name_validation_where_not_applicable() {
PermissionTemplateDto template1 =
new PermissionTemplateDto().setId(1L).setName("template1").setDescription("template1");
PermissionTemplateDto template2 =
}
@Test
- public void should_add_user_permission() throws Exception {
+ public void should_add_user_permission() {
UserDto userDto = new UserDto().setId(1L).setLogin("user").setName("user");
when(userDao.selectActiveUserByLogin("user")).thenReturn(userDto);
when(permissionTemplateDao.selectTemplateByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
}
@Test
- public void should_validate_provided_user_login() throws Exception {
+ public void should_validate_provided_user_login() {
expected.expect(BadRequestException.class);
expected.expectMessage("Unknown user:");
}
@Test
- public void should_remove_user_permission() throws Exception {
+ public void should_remove_user_permission() {
UserDto userDto = new UserDto().setId(1L).setLogin("user").setName("user");
when(userDao.selectActiveUserByLogin("user")).thenReturn(userDto);
when(permissionTemplateDao.selectTemplateByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
}
@Test
- public void should_add_group_permission() throws Exception {
+ public void should_add_group_permission() {
GroupDto groupDto = new GroupDto().setId(1L).setName("group");
when(userDao.selectGroupByName("group")).thenReturn(groupDto);
when(permissionTemplateDao.selectTemplateByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
}
@Test
- public void should_validate_provided_group_name() throws Exception {
+ public void should_validate_provided_group_name() {
expected.expect(BadRequestException.class);
expected.expectMessage("Unknown group:");
}
@Test
- public void should_remove_group_permission() throws Exception {
+ public void should_remove_group_permission() {
GroupDto groupDto = new GroupDto().setId(1L).setName("group");
when(userDao.selectGroupByName("group")).thenReturn(groupDto);
when(permissionTemplateDao.selectTemplateByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
}
@Test
- public void should_add_permission_to_anyone_group() throws Exception {
+ public void should_add_permission_to_anyone_group() {
when(permissionTemplateDao.selectTemplateByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
service.addGroupPermission(DEFAULT_KEY, DEFAULT_PERMISSION, "Anyone");
}
@Test
- public void should_remove_permission_from_anyone_group() throws Exception {
+ public void should_remove_permission_from_anyone_group() {
when(permissionTemplateDao.selectTemplateByKey(DEFAULT_KEY)).thenReturn(DEFAULT_TEMPLATE);
service.removeGroupPermission(DEFAULT_KEY, DEFAULT_PERMISSION, "Anyone");
}
@Test
- public void should_remove_group_from_templates() throws Exception {
+ public void should_remove_group_from_templates() {
GroupDto groupDto = new GroupDto().setId(1L).setName("group");
when(userDao.selectGroupByName("group", session)).thenReturn(groupDto);
public ExpectedException thrown = ExpectedException.none();
@Test
- public void populate_from_params() throws Exception {
+ public void populate_from_params() {
Map<String, Object> params = Maps.newHashMap();
params.put("user", "my_login");
params.put("group", "my_group");
}
@Test
- public void validate_user_query() throws Exception {
+ public void validate_user_query() {
Map<String, Object> validUserParams = Maps.newHashMap();
validUserParams.put("user", "my_login");
validUserParams.put("permission", GlobalPermissions.SYSTEM_ADMIN);
}
@Test
- public void validate_group_query() throws Exception {
+ public void validate_group_query() {
Map<String, Object> validGroupParams = Maps.newHashMap();
validGroupParams.put("group", "my_group");
validGroupParams.put("permission", GlobalPermissions.SYSTEM_ADMIN);
}
@Test
- public void reject_inconsistent_query() throws Exception {
+ public void reject_inconsistent_query() {
Map<String, Object> inconsistentParams = Maps.newHashMap();
inconsistentParams.put("user", "my_login");
inconsistentParams.put("group", "my_group");
}
@Test
- public void detect_missing_user_or_group() throws Exception {
+ public void detect_missing_user_or_group() {
Map<String, Object> inconsistentParams = Maps.newHashMap();
inconsistentParams.put("permission", "admin");
}
@Test
- public void detect_missing_permission() throws Exception {
+ public void detect_missing_permission() {
Map<String, Object> inconsistentParams = Maps.newHashMap();
inconsistentParams.put("user", "my_login");
}
@Test
- public void validate_global_permission_reference() throws Exception {
+ public void validate_global_permission_reference() {
Map<String, Object> inconsistentParams = Maps.newHashMap();
inconsistentParams.put("user", "my_login");
inconsistentParams.put("permission", "invalid");
}
@Test
- public void validate_component_permission_reference() throws Exception {
+ public void validate_component_permission_reference() {
Map<String, Object> inconsistentParams = Maps.newHashMap();
inconsistentParams.put("user", "my_login");
inconsistentParams.put("component", "org.sample.Sample");
PermissionFinder finder;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(resourceDao.getResource(any(ResourceQuery.class))).thenReturn(new ResourceDto().setId(100L).setName("org.sample.Sample"));
finder = new PermissionFinder(permissionDao, resourceDao, permissionTemplateDao);
}
@Test
- public void find_users() throws Exception {
+ public void find_users() {
when(permissionDao.selectUsers(any(PermissionQuery.class), anyLong(), anyInt(), anyInt())).thenReturn(
newArrayList(new UserWithPermissionDto().setName("user1").setPermission("user"))
);
}
@Test
- public void fail_to_find_users_when_component_not_found() throws Exception {
+ public void fail_to_find_users_when_component_not_found() {
when(resourceDao.getResource(any(ResourceQuery.class))).thenReturn(null);
try {
}
@Test
- public void find_users_with_paging() throws Exception {
+ public void find_users_with_paging() {
finder.findUsersWithPermission(PermissionQuery.builder().permission("user").pageIndex(3).pageSize(10).build());
ArgumentCaptor<Integer> argumentOffset = ArgumentCaptor.forClass(Integer.class);
}
@Test
- public void find_users_with_paging_having_more_results() throws Exception {
+ public void find_users_with_paging_having_more_results() {
when(permissionDao.selectUsers(any(PermissionQuery.class), anyLong(), anyInt(), anyInt())).thenReturn(newArrayList(
new UserWithPermissionDto().setName("user1").setPermission("user"),
new UserWithPermissionDto().setName("user2").setPermission("user"),
}
@Test
- public void find_users_with_paging_having_no_more_results() throws Exception {
+ public void find_users_with_paging_having_no_more_results() {
when(permissionDao.selectUsers(any(PermissionQuery.class), anyLong(), anyInt(), anyInt())).thenReturn(newArrayList(
new UserWithPermissionDto().setName("user1").setPermission("user"),
new UserWithPermissionDto().setName("user2").setPermission("user"),
}
@Test
- public void find_groups() throws Exception {
+ public void find_groups() {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(
newArrayList(new GroupWithPermissionDto().setName("users").setPermission("user"))
);
}
@Test
- public void find_groups_should_be_paginated() throws Exception {
+ public void find_groups_should_be_paginated() {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(newArrayList(
new GroupWithPermissionDto().setName("Anyone").setPermission("user"),
new GroupWithPermissionDto().setName("Admin").setPermission("user"),
}
@Test
- public void find_groups_should_filter_membership() throws Exception {
+ public void find_groups_should_filter_membership() {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(newArrayList(
new GroupWithPermissionDto().setName("Anyone").setPermission("user"),
new GroupWithPermissionDto().setName("Admin").setPermission("user"),
}
@Test
- public void find_groups_with_added_anyone_group() throws Exception {
+ public void find_groups_with_added_anyone_group() {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(
newArrayList(new GroupWithPermissionDto().setName("users").setPermission("user"))
);
}
@Test
- public void find_groups_without_adding_anyone_group_when_search_text_do_not_matched() throws Exception {
+ public void find_groups_without_adding_anyone_group_when_search_text_do_not_matched() {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(
newArrayList(new GroupWithPermissionDto().setName("users").setPermission("user"))
);
}
@Test
- public void find_groups_with_added_anyone_group_when_search_text_matched() throws Exception {
+ public void find_groups_with_added_anyone_group_when_search_text_matched() {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(
newArrayList(new GroupWithPermissionDto().setName("MyAnyGroup").setPermission("user"))
);
}
@Test
- public void find_groups_without_adding_anyone_group_when_out_membership_selected() throws Exception {
+ public void find_groups_without_adding_anyone_group_when_out_membership_selected() {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(
newArrayList(new GroupWithPermissionDto().setName("users").setPermission("user"))
);
@Test
- public void find_users_from_permission_template() throws Exception {
+ public void find_users_from_permission_template() {
when(permissionTemplateDao.selectTemplateByKey(anyString())).thenReturn(new PermissionTemplateDto().setId(1L).setKee("my_template"));
when(permissionTemplateDao.selectUsers(any(PermissionQuery.class), anyLong(), anyInt(), anyInt())).thenReturn(
}
@Test
- public void fail_to_find_users_from_permission_template_when_template_not_found() throws Exception {
+ public void fail_to_find_users_from_permission_template_when_template_not_found() {
when(permissionTemplateDao.selectTemplateByKey(anyString())).thenReturn(null);
try {
}
@Test
- public void find_groups_from_permission_template() throws Exception {
+ public void find_groups_from_permission_template() {
when(permissionTemplateDao.selectTemplateByKey(anyString())).thenReturn(new PermissionTemplateDto().setId(1L).setKee("my_template"));
when(permissionTemplateDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(
}
@Test
- public void fail_to_find_groups_from_permission_template_when_template_not_found() throws Exception {
+ public void fail_to_find_groups_from_permission_template_when_template_not_found() {
when(permissionTemplateDao.selectTemplateByKey(anyString())).thenReturn(null);
try {
public class PermissionQueryParserTest {
@Test
- public void to_query_with_all_params() throws Exception {
+ public void to_query_with_all_params() {
Map<String, Object> params = newHashMap();
params.put("permission", "admin");
params.put("template", "my_template_key");
}
@Test
- public void to_query_with_include_membership_parameter() throws Exception {
+ public void to_query_with_include_membership_parameter() {
Map<String, Object> params = newHashMap();
params.put("permission", "admin");
params.put("selected", "selected");
}
@Test
- public void to_query_with_exclude_membership_parameter() throws Exception {
+ public void to_query_with_exclude_membership_parameter() {
Map<String, Object> params = newHashMap();
params.put("permission", "admin");
params.put("selected", "deselected");
}
@Test
- public void to_query_with_any_membership_parameter() throws Exception {
+ public void to_query_with_any_membership_parameter() {
Map<String, Object> params = newHashMap();
params.put("permission", "admin");
params.put("selected", "all");
public class PermissionQueryTest {
@Test
- public void fail_on_null_permission() throws Exception {
+ public void fail_on_null_permission() {
PermissionQuery.Builder builder = PermissionQuery.builder();
builder.permission(null);
}
@Test
- public void fail_on_invalid_membership() throws Exception {
+ public void fail_on_invalid_membership() {
PermissionQuery.Builder builder = PermissionQuery.builder();
builder.permission("admin");
builder.membership("unknwown");
public class PermissionTemplateTest {
@Test
- public void should_populate_template_with_permissions() throws Exception {
+ public void should_populate_template_with_permissions() {
PermissionTemplateDto permissionTemplateDto = new PermissionTemplateDto()
.setId(1L)
}
@Test
- public void should_execute_on_valid_parameters() throws Exception {
+ public void should_execute_on_valid_parameters() {
final PermissionTemplateDao permissionTemplateDao = mock(PermissionTemplateDao.class);
when(permissionTemplateDao.selectTemplateByKey("my_template")).thenReturn(new PermissionTemplateDto().setId(1L));
}
@Test
- public void should_validate_template_reference() throws Exception {
+ public void should_validate_template_reference() {
expected.expect(BadRequestException.class);
expected.expectMessage("Unknown template:");
}
@Test
- public void should_validate_permission_reference() throws Exception {
+ public void should_validate_permission_reference() {
expected.expect(BadRequestException.class);
expected.expectMessage("Invalid permission:");
}
@Test
- public void should_check_that_user_is_logged_in() throws Exception {
+ public void should_check_that_user_is_logged_in() {
expected.expect(UnauthorizedException.class);
expected.expectMessage("Authentication is required");
}
@Test
- public void should_check_that_user_is_a_system_admin() throws Exception {
+ public void should_check_that_user_is_a_system_admin() {
expected.expect(ForbiddenException.class);
expected.expectMessage("Insufficient privileges");
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester = new WsTester(new PermissionsWs());
}
@Test
- public void define_controller() throws Exception {
+ public void define_controller() {
WebService.Controller controller = tester.controller("api/permissions");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
}
@Test
- public void define_add_action() throws Exception {
+ public void define_add_action() {
WebService.Controller controller = tester.controller("api/permissions");
WebService.Action action = controller.action("add");
}
@Test
- public void define_remove_action() throws Exception {
+ public void define_remove_action() {
WebService.Controller controller = tester.controller("api/permissions");
WebService.Action action = controller.action("remove");
BackendCleanup backendCleanup;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
backendCleanup = new BackendCleanup(esTester.client(), dbTester.myBatis());
}
@Test
- public void clear_db() throws Exception {
+ public void clear_db() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
backendCleanup.clearDb();
}
@Test
- public void servlet_container_should_instantiate_only_a_single_master_instance() throws Exception {
+ public void servlet_container_should_instantiate_only_a_single_master_instance() {
new MasterServletFilter();
thrown.expect(IllegalStateException.class);
private ServerSettings settings;
@Before
- public void init() throws URISyntaxException {
+ public void init() {
dao = mock(PropertiesDao.class);
settings = new ServerSettings(
}
@Test
- public void deployRubyRailsApps_no_apps() throws Exception {
+ public void deployRubyRailsApps_no_apps() {
ServerFileSystem fileSystem = mock(ServerFileSystem.class);
File tempDir = this.temp.getRoot();
when(fileSystem.getTempDir()).thenReturn(tempDir);
ServerImpl server;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
settings = new Settings().setProperty(ProcessProperties.PATH_HOME, sonarHome.getRoot().getAbsolutePath());
new File(sonarHome.getRoot(), "web/deploy").mkdirs();
ServerSettings settings;
@Before
- public void before() throws Exception {
+ public void before() {
properties = new Properties();
properties.put("hello", "world");
properties.put("in_file", "true");
DatabaseMonitor sut;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
DatabaseVersion dbVersion = new DatabaseVersion(dbTester.myBatis());
DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis());
sut = new DatabaseMonitor(dbVersion, dbClient);
public static EsTester esTester = new EsTester().addDefinitions(new IssueIndexDefinition(new Settings()));
@Test
- public void name() throws Exception {
+ public void name() {
EsMonitor monitor = new EsMonitor(esTester.client());
assertThat(monitor.name()).isEqualTo("ElasticSearch");
}
@Test
- public void cluster_attributes() throws Exception {
+ public void cluster_attributes() {
EsMonitor monitor = new EsMonitor(esTester.client());
LinkedHashMap<String, Object> attributes = monitor.attributes();
assertThat(monitor.getState()).isEqualTo(ClusterHealthStatus.GREEN.name());
}
@Test
- public void node_attributes() throws Exception {
+ public void node_attributes() {
EsMonitor monitor = new EsMonitor(esTester.client());
LinkedHashMap<String, Object> attributes = monitor.attributes();
Map nodesAttributes = (Map)attributes.get("Nodes");
}
@Test
- public void index_attributes() throws Exception {
+ public void index_attributes() {
EsMonitor monitor = new EsMonitor(esTester.client());
LinkedHashMap<String, Object> attributes = monitor.attributes();
Map indicesAttributes = (Map)attributes.get("Indices");
public class JvmPropertiesMonitorTest {
@Test
- public void attributes() throws Exception {
+ public void attributes() {
JvmPropertiesMonitor sut = new JvmPropertiesMonitor();
LinkedHashMap<String, Object> attributes = sut.attributes();
PluginsMonitor sut = new PluginsMonitor(new FakePluginRepository());;
@Test
- public void name() throws Exception {
+ public void name() {
assertThat(sut.name()).isEqualTo("Plugins");
}
@Test
- public void plugin_name_and_version() throws Exception {
+ public void plugin_name_and_version() {
LinkedHashMap<String, Object> attributes = sut.attributes();
assertThat(attributes).containsKeys("key-1", "key-2");
Server server = mock(Server.class);
@Test
- public void getServerId() throws Exception {
+ public void getServerId() {
when(server.getStartedAt()).thenReturn(DateUtils.parseDate("2015-01-01"));
SonarQubeMonitor monitor = new SonarQubeMonitor(settings, new SecurityRealmFactory(settings), server);
SystemMonitor sut = new SystemMonitor();
@Test
- public void name() throws Exception {
+ public void name() {
assertThat(sut.name()).isEqualTo("System");
}
@Test
- public void system_properties() throws Exception {
+ public void system_properties() {
LinkedHashMap<String, Object> attributes = sut.attributes();
assertThat(attributes).containsKeys("System Date", "Processors");
WsTester.TestResponse response = new WsTester.TestResponse();
@Before
- public void wireMocksTogether() throws Exception {
+ public void wireMocksTogether() {
when(database.getDialect()).thenReturn(dialect);
}
WsTester tester = new WsTester(new ServerWs());
@Test
- public void define_controller() throws Exception {
+ public void define_controller() {
WebService.Controller controller = tester.controller("api/server");
assertThat(controller).isNotNull();
assertThat(controller.since()).isEqualTo("2.10");
}
@Test
- public void define_index_action() throws Exception {
+ public void define_index_action() {
WebService.Controller controller = tester.controller("api/server");
WebService.Action action = controller.action("index");
}
@Test
- public void define_setup_action() throws Exception {
+ public void define_setup_action() {
WebService.Controller controller = tester.controller("api/server");
WebService.Action action = controller.action("setup");
SystemInfoWsAction sut = new SystemInfoWsAction(monitor1, monitor2);
@Test(expected = ForbiddenException.class)
- public void should_fail_when_does_not_have_admin_right() throws Exception {
+ public void should_fail_when_does_not_have_admin_right() {
MockUserSession.set()
.setLogin("login")
.setName("name")
}
@Test
- public void write_json() throws Exception {
+ public void write_json() {
MockUserSession.set()
.setLogin("login")
.setName("name")
public class SystemWsTest {
@Test
- public void define() throws Exception {
+ public void define() {
SystemRestartWsAction action1 = new SystemRestartWsAction(mock(Settings.class), mock(Platform.class));
SystemInfoWsAction action2 = new SystemInfoWsAction();
SystemWs ws = new SystemWs(action1, action2);
private WsTester.TestResponse response = new WsTester.TestResponse();
@Before
- public void wireMocks() throws Exception {
+ public void wireMocks() {
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(updateCenter);
when(updateCenter.getDate()).thenReturn(DateUtils.parseDateTime("2015-04-24T16:08:36+0200"));
}
@Test
- public void action_updates_is_defined() throws Exception {
+ public void action_updates_is_defined() {
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
}
@Test
- public void download_from_url() throws Exception {
+ public void download_from_url() {
Plugin test = new Plugin("test");
Release test10 = new Release(test, "1.0").setDownloadUrl("http://server/test-1.0.jar");
test.addRelease(test10);
* SONAR-4685
*/
@Test
- public void download_from_redirect_url() throws Exception {
+ public void download_from_redirect_url() {
Plugin test = new Plugin("plugin-test");
Release test10 = new Release(test, "1.0").setDownloadUrl("http://server/redirect?r=release&g=test&a=test&v=1.0&e=jar");
test.addRelease(test10);
}
@Test
- public void throw_exception_if_could_not_download() throws Exception {
+ public void throw_exception_if_could_not_download() {
Plugin test = new Plugin("test");
Release test10 = new Release(test, "1.0").setDownloadUrl("file://not_found");
test.addRelease(test10);
}
@Test
- public void throw_exception_if_download_fail() throws Exception {
+ public void throw_exception_if_download_fail() {
Plugin test = new Plugin("test");
Release test10 = new Release(test, "1.0").setDownloadUrl("http://server/test-1.0.jar");
test.addRelease(test10);
// SONAR-5011
@Test
- public void download_common_transitive_dependency() throws Exception {
+ public void download_common_transitive_dependency() {
Plugin test1 = new Plugin("test1");
Release test1R = new Release(test1, "1.0").setDownloadUrl("http://server/test1-1.0.jar");
test1.addRelease(test1R);
private HttpServletRequest request;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
servlet = new StaticResourcesServlet();
request = mock(HttpServletRequest.class);
}
}
@Before
- public void wireMocksTogether() throws Exception {
+ public void wireMocksTogether() {
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(updateCenter);
when(updateCenter.getDate()).thenReturn(DateUtils.parseDateTime("2015-04-24T16:08:36+0200"));
}
private AvailablePluginsWsAction underTest = new AvailablePluginsWsAction(updateCenterFactory, new PluginWSCommons());
@Test
- public void action_available_is_defined() throws Exception {
+ public void action_available_is_defined() {
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
}
@Test
- public void plugins_are_sorted_by_name_then_key_and_made_unique() throws Exception {
+ public void plugins_are_sorted_by_name_then_key_and_made_unique() {
when(updateCenter.findAvailablePlugins()).thenReturn(of(
pluginUpdate("key2", "name2"),
pluginUpdate("key1", "name2"),
public ExpectedException expectedException = ExpectedException.none();
@Before
- public void setUp() throws Exception {
+ public void setUp() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
}
@Test
- public void action_cancel_all_is_defined() throws Exception {
+ public void action_cancel_all_is_defined() {
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
public ExpectedException expectedException = ExpectedException.none();
@Before
- public void wireMocks() throws Exception {
+ public void wireMocks() {
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(updateCenter);
MockUserSession.set().setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
}
@Test
- public void action_install_is_defined() throws Exception {
+ public void action_install_is_defined() {
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
private PluginMetadata corePlugin = corePlugin("core1", 10);
@Test
- public void action_installed_is_defined() throws Exception {
+ public void action_installed_is_defined() {
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
private WsTester.TestResponse response = new WsTester.TestResponse();
@Test
- public void action_pending_is_defined() throws Exception {
+ public void action_pending_is_defined() {
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
private static final PluginUpdate.Status SOME_STATUS = PluginUpdate.Status.COMPATIBLE;
@Test(expected = NullPointerException.class)
- public void plugin_can_not_be_null_and_builderFor_enforces_it_with_NPE() throws Exception {
+ public void plugin_can_not_be_null_and_builderFor_enforces_it_with_NPE() {
PluginUpdateAggregateBuilder.builderFor(null);
}
@Test(expected = IllegalArgumentException.class)
- public void add_throws_IAE_when_plugin_is_not_equal_to_the_one_of_the_builder() throws Exception {
+ public void add_throws_IAE_when_plugin_is_not_equal_to_the_one_of_the_builder() {
PluginUpdateAggregateBuilder builder = PluginUpdateAggregateBuilder.builderFor(PLUGIN_1);
builder.add(createPluginUpdate(PLUGIN_2));
}
@Test
- public void add_uses_equals_which_takes_only_key_into_account() throws Exception {
+ public void add_uses_equals_which_takes_only_key_into_account() {
PluginUpdateAggregateBuilder builder = PluginUpdateAggregateBuilder.builderFor(PLUGIN_1);
builder.add(createPluginUpdate(new Plugin(PLUGIN_1.getKey())));
private PluginUpdateAggregator underTest = new PluginUpdateAggregator();
@Test
- public void aggregates_returns_an_empty_collection_when_plugin_collection_is_null() throws Exception {
+ public void aggregates_returns_an_empty_collection_when_plugin_collection_is_null() {
assertThat(underTest.aggregate(null)).isEmpty();
}
@Test
- public void aggregates_returns_an_empty_collection_when_plugin_collection_is_empty() throws Exception {
+ public void aggregates_returns_an_empty_collection_when_plugin_collection_is_empty() {
assertThat(underTest.aggregate(Collections.<PluginUpdate>emptyList())).isEmpty();
}
@Test
- public void aggregates_groups_pluginUpdate_per_plugin_key() throws Exception {
+ public void aggregates_groups_pluginUpdate_per_plugin_key() {
Collection<PluginUpdateAggregator.PluginUpdateAggregate> aggregates = underTest.aggregate(ImmutableList.of(
createPluginUpdate("key1"),
createPluginUpdate("key1"),
}
@Test
- public void aggregate_put_pluginUpdates_with_same_plugin_in_the_same_PluginUpdateAggregate() throws Exception {
+ public void aggregate_put_pluginUpdates_with_same_plugin_in_the_same_PluginUpdateAggregate() {
PluginUpdate pluginUpdate1 = createPluginUpdate("key1");
PluginUpdate pluginUpdate2 = createPluginUpdate("key1");
PluginUpdate pluginUpdate3 = createPluginUpdate("key1");
private WsTester tester = new WsTester(new PluginsWs(new DummyPluginsWsAction()));
@Test
- public void defines_controller_and_binds_PluginsWsActions() throws Exception {
+ public void defines_controller_and_binds_PluginsWsActions() {
WebService.Controller controller = tester.controller("api/plugins");
assertThat(controller).isNotNull();
public ExpectedException expectedException = ExpectedException.none();
@Before
- public void setUp() throws Exception {
+ public void setUp() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
}
}
@Test
- public void action_uninstall_is_defined() throws Exception {
+ public void action_uninstall_is_defined() {
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
public ExpectedException expectedException = ExpectedException.none();
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(updateCenter);
MockUserSession.set().setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
}
@Test
- public void action_update_is_defined() throws Exception {
+ public void action_update_is_defined() {
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
);
@Test
- public void action_updatable_is_defined() throws Exception {
+ public void action_updatable_is_defined() {
WsTester wsTester = new WsTester();
WebService.NewController newController = wsTester.context().createController(DUMMY_CONTROLLER_KEY);
}
@Test
- public void newProjectSettings_returns_a_ProjectSettings() throws Exception {
+ public void newProjectSettings_returns_a_ProjectSettings() {
Settings projectSettings = sut.newProjectSettings(1L);
assertThat(projectSettings).isInstanceOf(ProjectSettings.class);
}
@Test
- public void transform_empty_list_into_empty_map() throws Exception {
+ public void transform_empty_list_into_empty_map() {
Map<String, String> propertyMap = sut.getPropertyMap(Lists.<PropertyDto>newArrayList());
assertThat(propertyMap).isEmpty();
}
@Test
- public void transform_list_of_properties_in_map_key_value() throws Exception {
+ public void transform_list_of_properties_in_map_key_value() {
PropertyDto property1 = new PropertyDto().setKey("1").setValue("val1");
PropertyDto property2 = new PropertyDto().setKey("2").setValue("val2");
PropertyDto property3 = new PropertyDto().setKey("3").setValue("val3");
private Settings settings;
@Before
- public void before() throws Exception {
+ public void before() {
this.settings = mock(Settings.class);
}
@Test
- public void call_global_settings_method_when_no_project_specific_settings() throws Exception {
+ public void call_global_settings_method_when_no_project_specific_settings() {
this.sut = new ProjectSettings(settings, Maps.<String, String>newHashMap());
sut.getInt("anyKey");
}
@Test(expected = NumberFormatException.class)
- public void getInt_property_throws_exception_when_value_is_not_formatted_correctly() throws Exception {
+ public void getInt_property_throws_exception_when_value_is_not_formatted_correctly() {
HashMap<String, String> properties = Maps.newHashMap();
properties.put("intKey", "wrongIntValue");
this.sut = new ProjectSettings(settings, properties);
}
@Test
- public void getInt_property_return_0_when_empty_property() throws Exception {
+ public void getInt_property_return_0_when_empty_property() {
HashMap<String, String> properties = Maps.newHashMap();
properties.put("intKey", "");
this.sut = new ProjectSettings(settings, properties);
}
@Test
- public void getInt_property_return_the_int_value() throws Exception {
+ public void getInt_property_return_the_int_value() {
HashMap<String, String> properties = Maps.newHashMap();
properties.put("intKey", "123");
this.sut = new ProjectSettings(settings, properties);
}
@Test
- public void getString_returns_String_property() throws Exception {
+ public void getString_returns_String_property() {
HashMap<String, String> properties = Maps.newHashMap();
properties.put("stringKey", "stringValue");
this.sut = new ProjectSettings(settings, properties);
}
@Test
- public void getBoolean_returns_exception_when_value_is_not_formatted_correctly() throws Exception {
+ public void getBoolean_returns_exception_when_value_is_not_formatted_correctly() {
HashMap<String, String> properties = Maps.newHashMap();
properties.put("boolKey", "wronglyFormattedBoolean");
this.sut = new ProjectSettings(settings, properties);
}
@Test
- public void getBoolean_returns_false_when_value_is_empty() throws Exception {
+ public void getBoolean_returns_false_when_value_is_empty() {
HashMap<String, String> properties = Maps.newHashMap();
properties.put("boolKey", "");
this.sut = new ProjectSettings(settings, properties);
}
@Test
- public void getBoolean_returns_true_when_value_is_true_ignoring_case() throws Exception {
+ public void getBoolean_returns_true_when_value_is_true_ignoring_case() {
HashMap<String, String> properties = Maps.newHashMap();
properties.put("boolKey1", "true");
properties.put("boolKey2", "True");
}
@Test
- public void should_list_qgates() throws Exception {
+ public void should_list_qgates() {
List<QualityGateDto> allQgates = Lists.newArrayList(new QualityGateDto().setName("Gate One"), new QualityGateDto().setName("Gate Two"));
when(dao.selectAll()).thenReturn(allQgates);
assertThat(qGates.list()).isEqualTo(allQgates);
}
@Test
- public void should_create_qgate() throws Exception {
+ public void should_create_qgate() {
String name = "SG-1";
QualityGateDto sg1 = qGates.create(name);
assertThat(sg1.getName()).isEqualTo(name);
}
@Test(expected = ForbiddenException.class)
- public void should_fail_create_on_anonymous() throws Exception {
+ public void should_fail_create_on_anonymous() {
UserSessionTestUtils.setUserSession(unauthenticatedUserSession);
assertThat(qGates.currentUserHasWritePermission()).isFalse();
qGates.create("polop");
}
@Test(expected = ForbiddenException.class)
- public void should_fail_create_on_missing_permission() throws Exception {
+ public void should_fail_create_on_missing_permission() {
UserSessionTestUtils.setUserSession(unauthorizedUserSession);
qGates.create("polop");
}
@Test(expected = BadRequestException.class)
- public void should_fail_create_on_empty_name() throws Exception {
+ public void should_fail_create_on_empty_name() {
qGates.create("");
}
@Test(expected = BadRequestException.class)
- public void should_fail_create_on_duplicate_name() throws Exception {
+ public void should_fail_create_on_duplicate_name() {
String name = "SG-1";
when(dao.selectByName(name)).thenReturn(new QualityGateDto().setName(name).setId(42L));
qGates.create(name);
}
@Test
- public void should_get_qgate_by_id() throws Exception {
+ public void should_get_qgate_by_id() {
long id = 42L;
final String name = "Golden";
QualityGateDto existing = new QualityGateDto().setId(id).setName(name);
}
@Test
- public void should_get_qgate_by_name() throws Exception {
+ public void should_get_qgate_by_name() {
long id = 42L;
final String name = "Golden";
QualityGateDto existing = new QualityGateDto().setId(id).setName(name);
}
@Test(expected = NotFoundException.class)
- public void should_fail_to_find_qgate_by_name() throws Exception {
+ public void should_fail_to_find_qgate_by_name() {
qGates.get("Does not exist");
}
@Test
- public void should_rename_qgate() throws Exception {
+ public void should_rename_qgate() {
long id = 42L;
String name = "SG-1";
QualityGateDto existing = new QualityGateDto().setId(id).setName("Golden");
}
@Test
- public void should_allow_rename_with_same_name() throws Exception {
+ public void should_allow_rename_with_same_name() {
long id = 42L;
String name = "SG-1";
QualityGateDto existing = new QualityGateDto().setId(id).setName(name);
}
@Test(expected = NotFoundException.class)
- public void should_fail_rename_on_inexistent_qgate() throws Exception {
+ public void should_fail_rename_on_inexistent_qgate() {
qGates.rename(42L, "Unknown");
}
@Test(expected = BadRequestException.class)
- public void should_fail_rename_on_duplicate_name() throws Exception {
+ public void should_fail_rename_on_duplicate_name() {
long id = 42L;
String name = "SG-1";
QualityGateDto existing = new QualityGateDto().setId(id).setName("Golden");
}
@Test
- public void should_select_default_qgate() throws Exception {
+ public void should_select_default_qgate() {
long defaultId = 42L;
String defaultName = "Default Name";
when(dao.selectById(defaultId)).thenReturn(new QualityGateDto().setId(defaultId).setName(defaultName));
}
@Test
- public void should_unset_default_qgate() throws Exception {
+ public void should_unset_default_qgate() {
qGates.setDefault(null);
verify(propertiesDao).deleteGlobalProperty("sonar.qualitygate");
}
@Test
- public void should_delete_qgate() throws Exception {
+ public void should_delete_qgate() {
long idToDelete = 42L;
String name = "To Delete";
QualityGateDto toDelete = new QualityGateDto().setId(idToDelete).setName(name);
}
@Test
- public void should_delete_qgate_if_non_default() throws Exception {
+ public void should_delete_qgate_if_non_default() {
long idToDelete = 42L;
String name = "To Delete";
QualityGateDto toDelete = new QualityGateDto().setId(idToDelete).setName(name);
}
@Test
- public void should_delete_qgate_even_if_default() throws Exception {
+ public void should_delete_qgate_even_if_default() {
long idToDelete = 42L;
String name = "To Delete";
QualityGateDto toDelete = new QualityGateDto().setId(idToDelete).setName(name);
}
@Test
- public void should_return_default_qgate_if_set() throws Exception {
+ public void should_return_default_qgate_if_set() {
String defaultName = "Sonar way";
long defaultId = 42L;
when(propertiesDao.selectGlobalProperty("sonar.qualitygate")).thenReturn(new PropertyDto().setValue(Long.toString(defaultId)));
}
@Test
- public void should_return_null_default_qgate_if_unset() throws Exception {
+ public void should_return_null_default_qgate_if_unset() {
when(propertiesDao.selectGlobalProperty("sonar.qualitygate")).thenReturn(new PropertyDto().setValue(""));
assertThat(qGates.getDefault()).isNull();
}
}
@Test
- public void should_list_conditions() throws Exception {
+ public void should_list_conditions() {
long qGateId = 42L;
long metric1Id = 1L;
String metric1Key = "polop";
}
@Test(expected = IllegalStateException.class)
- public void should_do_a_sanity_check_when_listing_conditions() throws Exception {
+ public void should_do_a_sanity_check_when_listing_conditions() {
long qGateId = 42L;
long metric1Id = 1L;
String metric1Key = "polop";
}
@Test
- public void should_delete_condition() throws Exception {
+ public void should_delete_condition() {
long idToDelete = 42L;
QualityGateConditionDto toDelete = new QualityGateConditionDto().setId(idToDelete);
when(conditionDao.selectById(idToDelete)).thenReturn(toDelete);
}
@Test(expected = NotFoundException.class)
- public void should_fail_delete_condition() throws Exception {
+ public void should_fail_delete_condition() {
qGates.deleteCondition(42L);
}
}
@Test
- public void should_copy_qgate() throws Exception {
+ public void should_copy_qgate() {
String name = "Atlantis";
long sourceId = 42L;
final long destId = 43L;
}
@Test
- public void define_ws() throws Exception {
+ public void define_ws() {
Controller controller = tester.controller("api/qualitygates");
assertThat(controller).isNotNull();
assertThat(controller.path()).isEqualTo("api/qualitygates");
}
@Test
- public void synchronize_index() throws Exception {
+ public void synchronize_index() {
Date beginning = new Date();
}
@Test
- public void insert_and_index_active_rule_param() throws InterruptedException {
+ public void insert_and_index_active_rule_param() {
// insert and index
QualityProfileDto profileDto = QProfileTesting.newXooP1();
db.qualityProfileDao().insert(dbSession, profileDto);
}
@Test
- public void find_active_rules() throws Exception {
+ public void find_active_rules() {
QualityProfileDto profile1 = QProfileTesting.newXooP1();
QualityProfileDto profile2 = QProfileTesting.newXooP2();
db.qualityProfileDao().insert(dbSession, profile1, profile2);
BuiltInProfiles cache;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
cache = new BuiltInProfiles();
}
@Test
- public void add_profiles() throws Exception {
+ public void add_profiles() {
cache.put("java", "Default");
cache.put("java", "Sonar Way");
cache.put("js", "Default");
}
@Test
- public void not_add_same_profile_name() throws Exception {
+ public void not_add_same_profile_name() {
cache.put("java", "Default");
cache.put("java", "Default");
}
@After
- public void after() throws Exception {
+ public void after() {
dbSession.close();
}
}
@Test
- public void fail_to_backup_unknown_profile() throws Exception {
+ public void fail_to_backup_unknown_profile() {
try {
tester.get(QProfileBackuper.class).backup("unknown", new StringWriter());
fail();
}
@After
- public void after() throws Exception {
+ public void after() {
dbSession.close();
}
@Test
- public void compare_empty_profiles() throws Exception {
+ public void compare_empty_profiles() {
QProfileComparisonResult result = comparison.compare(left.getKey(), right.getKey());
assertThat(result.left().getKey()).isEqualTo(left.getKey());
assertThat(result.right().getKey()).isEqualTo(right.getKey());
}
@Test
- public void compare_same() throws Exception {
+ public void compare_same() {
RuleActivation commonActivation = new RuleActivation(xooRule1.getKey())
.setSeverity(Severity.CRITICAL)
.setParameter("min", "7")
}
@Test
- public void compare_only_left() throws Exception {
+ public void compare_only_left() {
ruleActivator.activate(dbSession, new RuleActivation(xooRule1.getKey()), left);
dbSession.commit();
}
@Test
- public void compare_only_right() throws Exception {
+ public void compare_only_right() {
ruleActivator.activate(dbSession, new RuleActivation(xooRule1.getKey()), right);
dbSession.commit();
}
@Test
- public void compare_disjoint() throws Exception {
+ public void compare_disjoint() {
ruleActivator.activate(dbSession, new RuleActivation(xooRule1.getKey()), left);
ruleActivator.activate(dbSession, new RuleActivation(xooRule2.getKey()), right);
dbSession.commit();
}
@Test
- public void compare_modified_severity() throws Exception {
+ public void compare_modified_severity() {
ruleActivator.activate(dbSession, new RuleActivation(xooRule1.getKey()).setSeverity(Severity.CRITICAL), left);
ruleActivator.activate(dbSession, new RuleActivation(xooRule1.getKey()).setSeverity(Severity.BLOCKER), right);
dbSession.commit();
}
@Test
- public void compare_modified_param() throws Exception {
+ public void compare_modified_param() {
ruleActivator.activate(dbSession, new RuleActivation(xooRule1.getKey()).setParameter("max", "20"), left);
ruleActivator.activate(dbSession, new RuleActivation(xooRule1.getKey()).setParameter("max", "30"), right);
dbSession.commit();
}
@Test
- public void compare_different_params() throws Exception {
+ public void compare_different_params() {
ruleActivator.activate(dbSession, new RuleActivation(xooRule1.getKey()).setParameter("max", "20"), left);
ruleActivator.activate(dbSession, new RuleActivation(xooRule1.getKey()).setParameter("min", "5"), right);
dbSession.commit();
}
@Test(expected = IllegalArgumentException.class)
- public void fail_on_unknown_left() throws Exception {
+ public void fail_on_unknown_left() {
comparison.compare("polop", right.getKey());
}
@Test(expected = IllegalArgumentException.class)
- public void fail_on_unknown_right() throws Exception {
+ public void fail_on_unknown_right() {
comparison.compare(left.getKey(), "polop");
}
}
}
@After
- public void after() throws Exception {
+ public void after() {
dbSession.close();
}
@Test
- public void create_target_profile() throws Exception {
+ public void create_target_profile() {
// source
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
activation.setSeverity(Severity.BLOCKER);
}
@Test
- public void update_target_profile() throws Exception {
+ public void update_target_profile() {
// source with x1 activated
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
activation.setSeverity(Severity.BLOCKER);
}
@Test
- public void create_target_profile_with_same_parent_than_source() throws Exception {
+ public void create_target_profile_with_same_parent_than_source() {
// two profiles : parent and its child
db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP2().setParentKee(QProfileTesting.XOO_P1_KEY));
}
@Test
- public void fail_to_copy_on_self() throws Exception {
+ public void fail_to_copy_on_self() {
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
activation.setSeverity(Severity.BLOCKER);
activation.setParameter("max", "7");
}
@After
- public void after() throws Exception {
+ public void after() {
dbSession.close();
}
@Test
- public void exportersForLanguage() throws Exception {
+ public void exportersForLanguage() {
assertThat(exporters.exportersForLanguage("xoo")).hasSize(2);
assertThat(exporters.exportersForLanguage("java")).hasSize(1);
assertThat(exporters.exportersForLanguage("java").get(0)).isInstanceOf(StandardExporter.class);
}
@Test
- public void mimeType() throws Exception {
+ public void mimeType() {
assertThat(exporters.mimeType("xootool")).isEqualTo("plain/custom");
// default mime type
}
@Test
- public void profile_importers_for_language() throws Exception {
+ public void profile_importers_for_language() {
assertThat(exporters.findProfileImportersForLanguage("xoo")).hasSize(3);
}
@Test
- public void import_xml() throws Exception {
+ public void import_xml() {
QualityProfileDto profileDto = QProfileTesting.newDto(QProfileName.createFor("xoo", "import_xml"), "import_xml");
db.qualityProfileDao().insert(dbSession, profileDto);
dbSession.commit();
}
@Test
- public void import_xml_return_messages() throws Exception {
+ public void import_xml_return_messages() {
QProfileResult result = exporters.importXml(QProfileTesting.newXooP1(), "XooProfileImporterWithMessages", "<xml/>", dbSession);
dbSession.commit();
}
@Test
- public void fail_to_import_xml_when_error_in_importer() throws Exception {
+ public void fail_to_import_xml_when_error_in_importer() {
try {
exporters.importXml(QProfileTesting.newXooP1(), "XooProfileImporterWithError", "<xml/>", dbSession);
fail();
}
@Test
- public void fail_to_import_xml_on_unknown_importer() throws Exception {
+ public void fail_to_import_xml_on_unknown_importer() {
try {
exporters.importXml(QProfileTesting.newXooP1(), "Unknown", "<xml/>", dbSession);
fail();
}
@After
- public void after() throws Exception {
+ public void after() {
dbSession.close();
}
public class QProfileNameTest {
@Test
- public void equals_and_hashcode() throws Exception {
+ public void equals_and_hashcode() {
QProfileName xooP1 = new QProfileName("xoo", "p1");
assertThat(xooP1).isEqualTo(xooP1);
assertThat(xooP1).isNotEqualTo(new QProfileName("xoo", "p2"));
}
@Test
- public void to_string() throws Exception {
+ public void to_string() {
assertThat(new QProfileName("xoo", "p1").toString()).isEqualTo("{lang=xoo, name=p1}");
}
}
}
@After
- public void after() throws Exception {
+ public void after() {
dbSession.close();
}
@Test
- public void add_project() throws Exception {
+ public void add_project() {
projectOperations.addProject(profile.getKey(), project.uuid(), authorizedProfileAdminUserSession);
assertThat(factory.getByProjectAndLanguage(PROJECT_KEY, profile.getLanguage())).isNotNull();
}
@Test
- public void add_project_with_only_project_admin_permission() throws Exception {
+ public void add_project_with_only_project_admin_permission() {
projectOperations.addProject(profile.getKey(), project.uuid(), authorizedProjectAdminUserSession);
assertThat(factory.getByProjectAndLanguage(PROJECT_KEY, profile.getLanguage())).isNotNull();
}
@Test
- public void remove_project_from_project_id() throws Exception {
+ public void remove_project_from_project_id() {
projectOperations.addProject(profile.getKey(), project.uuid(), authorizedProfileAdminUserSession);
assertThat(factory.getByProjectAndLanguage(PROJECT_KEY, profile.getLanguage())).isNotNull();
}
@Test
- public void remove_project_from_language() throws Exception {
+ public void remove_project_from_language() {
projectOperations.addProject(profile.getKey(), project.uuid(), authorizedProfileAdminUserSession);
assertThat(factory.getByProjectAndLanguage(PROJECT_KEY, profile.getLanguage())).isNotNull();
}
@Test
- public void remove_all_projects() throws Exception {
+ public void remove_all_projects() {
ComponentDto project1 = new ComponentDto()
.setUuid("BCDE")
.setKey("project1")
}
@After
- public void after() throws Exception {
+ public void after() {
dbSession.close();
}
}
@Test
- public void reset_language_profile() throws Exception {
+ public void reset_language_profile() {
RulesProfile defProfile = RulesProfile.create("Basic", ServerTester.Xoo.KEY);
defProfile.activateRule(
org.sonar.api.rules.Rule.create("xoo", "x1").setParams(newArrayList(new RuleParam().setKey("acceptWhitespace"))),
}
@Test
- public void reset_language_profile_param_when_rule_definition_has_changed() throws Exception {
+ public void reset_language_profile_param_when_rule_definition_has_changed() {
RulesProfile defProfile = RulesProfile.create("Basic", ServerTester.Xoo.KEY);
defProfile.activateRule(org.sonar.api.rules.Rule.create("xoo", "x1"), null);
}
@After
- public void after() throws Exception {
+ public void after() {
dbSession.close();
}
@Test
- public void create_profile() throws Exception {
+ public void create_profile() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN).setLogin("me");
QualityProfileDto profile = service.create(QProfileName.createFor("xoo", "New Profile"), null).profile();
}
@Test
- public void create_profile_with_xml() throws Exception {
+ public void create_profile_with_xml() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN).setLogin("me");
db.ruleDao().insert(dbSession, RuleTesting.newDto(RuleKey.of("xoo", "R1")).setLanguage("xoo").setSeverity("MINOR"));
}
@Test
- public void count_by_all_profiles() throws Exception {
+ public void count_by_all_profiles() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN).setLogin("me");
service.activate(XOO_P1_KEY, new RuleActivation(RuleTesting.XOO_X1).setSeverity("BLOCKER"));
}
@Test
- public void count_by_deprecated() throws Exception {
+ public void count_by_deprecated() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN).setLogin("me");
// create deprecated rule
}
@Test
- public void search_qprofile_activity() throws InterruptedException {
+ public void search_qprofile_activity() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN).setLogin("david");
UserDto user = new UserDto().setLogin("david").setName("David").setEmail("dav@id.com").setCreatedAt(System.currentTimeMillis()).setUpdatedAt(System.currentTimeMillis());
}
@Test
- public void search_qprofile_activity_without_severity() throws InterruptedException {
+ public void search_qprofile_activity_without_severity() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN).setLogin("me");
RuleKey ruleKey = RuleKey.of("xoo", "deleted_rule");
}
@Test
- public void search_qprofile_activity_with_user_not_found() throws InterruptedException {
+ public void search_qprofile_activity_with_user_not_found() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN).setLogin("david");
// We need an actual rule in DB to test RuleName in Activity
}
@Test
- public void search_qprofile_activity_with_rule_not_found() throws InterruptedException {
+ public void search_qprofile_activity_with_rule_not_found() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN).setLogin("me");
RuleKey ruleKey = RuleKey.of("xoo", "deleted_rule");
}
@Test
- public void search_activity_by_qprofile() throws InterruptedException {
+ public void search_activity_by_qprofile() {
tester.get(ActivityService.class).save(
ActiveRuleChange.createFor(ActiveRuleChange.Type.ACTIVATED, ActiveRuleKey.of(XOO_P1_KEY, RuleTesting.XOO_X1)).toActivity());
}
@Test
- public void search_activity_by_qprofile_having_dashes_in_keys() throws InterruptedException {
+ public void search_activity_by_qprofile_having_dashes_in_keys() {
tester.get(ActivityService.class).save(
ActiveRuleChange.createFor(ActiveRuleChange.Type.ACTIVATED, ActiveRuleKey.of("java-default", RuleTesting.XOO_X1)).toActivity());
tester.get(ActivityService.class).save(
}
@Test
- public void set_default() throws Exception {
+ public void set_default() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN).setLogin("me");
assertThat(service.getDefault("xoo")).isNull();
}
@Test
- public void to_string() throws Exception {
+ public void to_string() {
assertThat(new QProfile().setId(1).setName("Default").setLanguage("java").setParent("Parent").toString())
.contains("[id=1,key=<null>,name=Default,language=java,parent=Parent,isDefault=false]");
}
@Test
- public void is_inherited() throws Exception {
+ public void is_inherited() {
assertThat(new QProfile().setId(1).setName("Default").setLanguage("java").setParent("Parent").isInherited()).isTrue();
assertThat(new QProfile().setId(1).setName("Default").setLanguage("java").setParent(null).isInherited()).isFalse();
}
QProfiles qProfiles;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
qProfiles = new QProfiles(projectOperations, projectLookup, profileLookup);
}
@Test
- public void search_profile_by_id() throws Exception {
+ public void search_profile_by_id() {
qProfiles.profile(1);
verify(profileLookup).profile(1);
}
@Test
- public void search_profile_by_name_and_language() throws Exception {
+ public void search_profile_by_name_and_language() {
qProfiles.profile("Default", "java");
verify(profileLookup).profile("Default", "java");
}
@Test
- public void search_profiles() throws Exception {
+ public void search_profiles() {
qProfiles.allProfiles();
verify(profileLookup).allProfiles();
}
@Test
- public void search_profiles_by_language() throws Exception {
+ public void search_profiles_by_language() {
qProfiles.profilesByLanguage("java");
verify(profileLookup).profiles("java");
}
@Test
- public void search_parent_profile() throws Exception {
+ public void search_parent_profile() {
QProfile profile = new QProfile().setId(1).setParent("Parent").setLanguage("java");
qProfiles.parent(profile);
verify(profileLookup).parent(profile);
}
@Test
- public void search_children() throws Exception {
+ public void search_children() {
QProfile profile = new QProfile();
qProfiles.children(profile);
verify(profileLookup).children(profile);
}
@Test
- public void search_ancestors() throws Exception {
+ public void search_ancestors() {
QProfile profile = new QProfile();
qProfiles.ancestors(profile);
verify(profileLookup).ancestors(profile);
}
@Test
- public void projects() throws Exception {
+ public void projects() {
qProfiles.projects(1);
verify(projectLookup).projects(1);
}
@Test
- public void count_projects() throws Exception {
+ public void count_projects() {
QProfile profile = new QProfile();
qProfiles.countProjects(profile);
verify(projectLookup).countProjects(profile);
}
@Test
- public void get_profiles_from_project_and_language() throws Exception {
+ public void get_profiles_from_project_and_language() {
qProfiles.findProfileByProjectAndLanguage(1, "java");
verify(projectLookup).findProfileByProjectAndLanguage(1, "java");
}
@Test
- public void add_project() throws Exception {
+ public void add_project() {
qProfiles.addProject("sonar-way-java", "ABCD");
verify(projectOperations).addProject(eq("sonar-way-java"), eq("ABCD"), any(UserSession.class));
}
@Test
- public void remove_project_by_quality_profile_key() throws Exception {
+ public void remove_project_by_quality_profile_key() {
qProfiles.removeProject("sonar-way-java", "ABCD");
verify(projectOperations).removeProject(eq("sonar-way-java"), eq("ABCD"), any(UserSession.class));
}
@Test
- public void remove_project_by_language() throws Exception {
+ public void remove_project_by_language() {
qProfiles.removeProjectByLanguage("java", 10L);
verify(projectOperations).removeProject(eq("java"), eq(10L), any(UserSession.class));
}
@Test
- public void remove_all_projects() throws Exception {
+ public void remove_all_projects() {
qProfiles.removeAllProjects("sonar-way-java");
verify(projectOperations).removeAllProjects(eq("sonar-way-java"), any(UserSession.class));
}
DbSession dbSession;
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
if (dbSession != null) {
dbSession.close();
}
}
@Test
- public void register_existing_profile_definitions() throws Exception {
+ public void register_existing_profile_definitions() {
tester = new ServerTester().addXoo().addComponents(XooRulesDefinition.class, XooProfileDefinition.class);
tester.start();
dbSession = dbClient().openSession(false);
}
@Test
- public void register_profile_definitions() throws Exception {
+ public void register_profile_definitions() {
tester = new ServerTester().addXoo().addComponents(XooRulesDefinition.class, XooProfileDefinition.class);
tester.start();
dbSession = dbClient().openSession(false);
}
@Test
- public void do_not_register_profile_if_missing_language() throws Exception {
+ public void do_not_register_profile_if_missing_language() {
// xoo language is not installed
tester = new ServerTester().addComponents(XooRulesDefinition.class, XooProfileDefinition.class);
tester.start();
}
@Test
- public void fail_if_two_definitions_are_marked_as_default_on_the_same_language() throws Exception {
+ public void fail_if_two_definitions_are_marked_as_default_on_the_same_language() {
tester = new ServerTester().addXoo().addComponents(new SimpleProfileDefinition("one", true), new SimpleProfileDefinition("two", true));
try {
}
@Test
- public void mark_profile_as_default() throws Exception {
+ public void mark_profile_as_default() {
tester = new ServerTester().addXoo().addComponents(new SimpleProfileDefinition("one", false), new SimpleProfileDefinition("two", true));
tester.start();
}
@Test
- public void use_sonar_way_as_default_profile_if_none_are_marked_as_default() throws Exception {
+ public void use_sonar_way_as_default_profile_if_none_are_marked_as_default() {
tester = new ServerTester().addXoo().addComponents(new SimpleProfileDefinition("Sonar way", false), new SimpleProfileDefinition("Other way", false));
tester.start();
}
@Test
- public void do_not_reset_default_profile_if_still_valid() throws Exception {
+ public void do_not_reset_default_profile_if_still_valid() {
tester = new ServerTester().addXoo().addComponents(new SimpleProfileDefinition("one", true), new SimpleProfileDefinition("two", false));
tester.start();
* Probably for db migration
*/
@Test
- public void clean_up_profiles_if_missing_loaded_template() throws Exception {
+ public void clean_up_profiles_if_missing_loaded_template() {
tester = new ServerTester().addXoo().addComponents(XooRulesDefinition.class, XooProfileDefinition.class);
tester.start();
}
@After
- public void after() throws Exception {
+ public void after() {
dbSession.close();
}
@Test
- public void activate() throws Exception {
+ public void activate() {
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
activation.setSeverity(Severity.BLOCKER);
activation.setParameter("max", "7");
}
@Test
- public void activate_with_profile_dto() throws Exception {
+ public void activate_with_profile_dto() {
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
activation.setSeverity(Severity.BLOCKER);
activation.setParameter("max", "7");
}
@Test
- public void activate_with_default_severity_and_parameter() throws Exception {
+ public void activate_with_default_severity_and_parameter() {
activate(new RuleActivation(RuleTesting.XOO_X1), XOO_P1_KEY);
assertThat(countActiveRules(XOO_P1_KEY)).isEqualTo(1);
* SONAR-5841
*/
@Test
- public void activate_with_empty_parameter_having_no_default_value() throws Exception {
+ public void activate_with_empty_parameter_having_no_default_value() {
activate(new RuleActivation(RuleTesting.XOO_X1)
.setParameter("min", ""),
XOO_P1_KEY);
* SONAR-5841
*/
@Test
- public void activate_with_empty_parameters() throws Exception {
+ public void activate_with_empty_parameters() {
activate(new RuleActivation(RuleTesting.XOO_X1)
.setParameters(ImmutableMap.of("max", "", "min", "")),
XOO_P1_KEY);
* SONAR-5840
*/
@Test
- public void activate_rule_with_negative_integer_value_on_parameter_having_no_default_value() throws Exception {
+ public void activate_rule_with_negative_integer_value_on_parameter_having_no_default_value() {
activate(new RuleActivation(RuleTesting.XOO_X1)
.setParameter("min", "-10"),
XOO_P1_KEY);
}
@Test
- public void activation_ignores_unsupported_parameters() throws Exception {
+ public void activation_ignores_unsupported_parameters() {
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
activation.setParameter("xxx", "yyy");
activate(activation, XOO_P1_KEY);
}
@Test
- public void update_activation_severity_and_parameters() throws Exception {
+ public void update_activation_severity_and_parameters() {
// initial activation
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
activation.setSeverity(Severity.BLOCKER);
}
@Test
- public void update_activation_with_parameter_without_default_value() throws Exception {
+ public void update_activation_with_parameter_without_default_value() {
// initial activation -> param "max" has a default value
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
activation.setSeverity(Severity.BLOCKER);
}
@Test
- public void update_activation_but_new_parameter() throws Exception {
+ public void update_activation_but_new_parameter() {
// initial activation
ActiveRuleKey activeRuleKey = ActiveRuleKey.of(XOO_P1_KEY, RuleTesting.XOO_X1);
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
}
@Test
- public void ignore_activation_without_changes() throws Exception {
+ public void ignore_activation_without_changes() {
// initial activation
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
activation.setSeverity(Severity.BLOCKER);
}
@Test
- public void do_not_change_severity_and_params_if_unset_and_already_activated() throws Exception {
+ public void do_not_change_severity_and_params_if_unset_and_already_activated() {
// initial activation
ActiveRuleKey activeRuleKey = ActiveRuleKey.of(XOO_P1_KEY, RuleTesting.XOO_X1);
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
}
@Test
- public void revert_activation_to_default_severity_and_parameters() throws Exception {
+ public void revert_activation_to_default_severity_and_parameters() {
// initial activation
ActiveRuleKey activeRuleKey = ActiveRuleKey.of(XOO_P1_KEY, RuleTesting.XOO_X1);
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
}
@Test
- public void ignore_parameters_when_activating_custom_rule() throws Exception {
+ public void ignore_parameters_when_activating_custom_rule() {
// initial activation
ActiveRuleKey activeRuleKey = ActiveRuleKey.of(XOO_P1_KEY, CUSTOM_RULE_KEY);
RuleActivation activation = new RuleActivation(CUSTOM_RULE_KEY);
}
@Test
- public void fail_to_activate_if_template() throws Exception {
+ public void fail_to_activate_if_template() {
RuleActivation activation = new RuleActivation(TEMPLATE_RULE_KEY);
try {
}
@Test
- public void fail_to_activate_if_different_languages() throws Exception {
+ public void fail_to_activate_if_different_languages() {
// profile and rule have different languages
RuleActivation activation = new RuleActivation(RuleKey.of("squid", "j1"));
}
@Test
- public void fail_to_activate_if_unknown_rule() throws Exception {
+ public void fail_to_activate_if_unknown_rule() {
// profile and rule have different languages
RuleActivation activation = new RuleActivation(RuleKey.of("xoo", "x3"));
}
@Test
- public void fail_to_activate_if_rule_with_removed_status() throws Exception {
+ public void fail_to_activate_if_rule_with_removed_status() {
RuleDto ruleDto = db.ruleDao().getByKey(dbSession, RuleTesting.XOO_X1);
ruleDto.setStatus(RuleStatus.REMOVED);
db.ruleDao().update(dbSession, ruleDto);
}
@Test
- public void fail_to_activate_if_manual_rule() throws Exception {
+ public void fail_to_activate_if_manual_rule() {
RuleActivation activation = new RuleActivation(MANUAL_RULE_KEY);
try {
}
@Test
- public void fail_to_activate_if_unknown_profile() throws Exception {
+ public void fail_to_activate_if_unknown_profile() {
try {
activate(new RuleActivation(RuleTesting.XOO_X1), "unknown");
fail();
}
@Test
- public void fail_to_activate_if_invalid_parameter() throws Exception {
+ public void fail_to_activate_if_invalid_parameter() {
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
activation.setParameter("max", "foo");
}
@Test
- public void deactivate() throws Exception {
+ public void deactivate() {
// activation
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
activation.setSeverity(Severity.BLOCKER);
}
@Test
- public void ignore_deactivation_if_rule_not_activated() throws Exception {
+ public void ignore_deactivation_if_rule_not_activated() {
// deactivation
ActiveRuleKey key = ActiveRuleKey.of(XOO_P1_KEY, RuleTesting.XOO_X1);
ruleActivator.deactivate(key);
}
@Test
- public void deactivation_fails_if_rule_not_found() throws Exception {
+ public void deactivation_fails_if_rule_not_found() {
ActiveRuleKey key = ActiveRuleKey.of(XOO_P1_KEY, RuleKey.of("xoo", "x3"));
try {
ruleActivator.deactivate(key);
}
@Test
- public void deactivation_fails_if_profile_not_found() throws Exception {
+ public void deactivation_fails_if_profile_not_found() {
ActiveRuleKey key = ActiveRuleKey.of("unknown", RuleTesting.XOO_X1);
try {
ruleActivator.deactivate(key);
}
@Test
- public void allow_to_deactivate_removed_rule() throws Exception {
+ public void allow_to_deactivate_removed_rule() {
// activation
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
activate(activation, XOO_P1_KEY);
// INHERITANCE OF PROFILES
@Test
- public void activate_on_child_profile_but_not_on_parent() throws Exception {
+ public void activate_on_child_profile_but_not_on_parent() {
createChildProfiles();
// activate on child profile, but not on root
}
@Test
- public void propagate_activation_on_child_profiles() throws Exception {
+ public void propagate_activation_on_child_profiles() {
createChildProfiles();
// activate on root profile
}
@Test
- public void propagate_activation_update_on_child_profiles() throws Exception {
+ public void propagate_activation_update_on_child_profiles() {
createChildProfiles();
// activate on root profile
}
@Test
- public void do_not_propagate_activation_update_on_child_overrides() throws Exception {
+ public void do_not_propagate_activation_update_on_child_overrides() {
createChildProfiles();
// activate on root profile P1
}
@Test
- public void active_on_parent_a_rule_already_activated_on_child() throws Exception {
+ public void active_on_parent_a_rule_already_activated_on_child() {
createChildProfiles();
// activate on child profile
}
@Test
- public void do_not_override_on_child_if_same_values() throws Exception {
+ public void do_not_override_on_child_if_same_values() {
createChildProfiles();
// activate on root profile
}
@Test
- public void propagate_deactivation_on_child_profiles() throws Exception {
+ public void propagate_deactivation_on_child_profiles() {
createChildProfiles();
// activate on root profile
}
@Test
- public void propagate_deactivation_even_on_child_overrides() throws Exception {
+ public void propagate_deactivation_even_on_child_overrides() {
createChildProfiles();
// activate on root profile
}
@Test
- public void do_not_deactivate_inherited_or_overridden_rule() throws Exception {
+ public void do_not_deactivate_inherited_or_overridden_rule() {
createChildProfiles();
// activate on root profile
}
@Test
- public void reset_child_profile() throws Exception {
+ public void reset_child_profile() {
createChildProfiles();
// activate on root profile
}
@Test
- public void reset_is_not_propagated_to_child_overrides() throws Exception {
+ public void reset_is_not_propagated_to_child_overrides() {
createChildProfiles();
// activate on root profile
}
@Test
- public void ignore_reset_if_not_activated() throws Exception {
+ public void ignore_reset_if_not_activated() {
createChildProfiles();
RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1).setReset(true);
activate(activation, XOO_P1_KEY);
}
@Test
- public void bulk_change_severity() throws Exception {
+ public void bulk_change_severity() {
createChildProfiles();
// activate two rules on root profile P1 (propagated to P2 and P3)
}
@Test
- public void define_controller() throws Exception {
+ public void define_controller() {
WebService.Controller controller = tester.controller("api/profiles");
assertThat(controller).isNotNull();
assertThat(controller.path()).isEqualTo("api/profiles");
}
@Test
- public void define_list_action() throws Exception {
+ public void define_list_action() {
WebService.Controller controller = tester.controller("api/profiles");
WebService.Action restoreProfiles = controller.action("list");
}
@Test
- public void define_index_action() throws Exception {
+ public void define_index_action() {
WebService.Controller controller = tester.controller("api/profiles");
WebService.Action restoreProfiles = controller.action("index");
}
@Test
- public void define_backup_action() throws Exception {
+ public void define_backup_action() {
WebService.Controller controller = tester.controller("api/profiles");
WebService.Action restoreProfiles = controller.action("backup");
}
@Test
- public void define_restore_action() throws Exception {
+ public void define_restore_action() {
WebService.Controller controller = tester.controller("api/profiles");
WebService.Action restoreProfiles = controller.action("restore");
}
@Test
- public void define_destroy_action() throws Exception {
+ public void define_destroy_action() {
WebService.Controller controller = tester.controller("api/profiles");
WebService.Action restoreProfiles = controller.action("destroy");
}
@Test
- public void define_set_as_default_action() throws Exception {
+ public void define_set_as_default_action() {
WebService.Controller controller = tester.controller("api/profiles");
WebService.Action restoreProfiles = controller.action("set_as_default");
private WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
DbClient dbClient = new DbClient(db.database(), db.myBatis());
tester = new WsTester(new QProfilesWs(
WsTester wsTester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
db = tester.get(DbClient.class);
ws = tester.get(QProfilesWs.class);
}
@After
- public void after() throws Exception {
+ public void after() {
dbSession.close();
}
private DbSession session;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
db = tester.get(DbClient.class);
session = db.openSession(false);
private QProfileCopier qProfileCopier;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester = new WsTester(new QProfilesWs(
mock(RuleActivationActions.class),
mock(BulkRuleActivationActions.class),
}
@After
- public void after() throws Exception {
+ public void after() {
dbSession.close();
}
private DbSession session;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
qualityProfileDao = new QualityProfileDao(dbTester.myBatis(), mock(System2.class));
componentDao = new ComponentDao();
QProfileExporters exporters;
@Before
- public void before() throws Exception {
+ public void before() {
qualityProfileDao = new QualityProfileDao(db.myBatis(), mock(System2.class));
dbClient = new DbClient(db.database(), db.myBatis(), qualityProfileDao);
session = dbClient.openSession(false);
}
@After
- public void after() throws Exception {
+ public void after() {
session.close();
}
private DbSession session;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
db = tester.get(DbClient.class);
session = db.openSession(false);
private RoleDao roleDao;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
dbClient = new DbClient(dbTester.database(), dbTester.myBatis(),
new QualityProfileDao(dbTester.myBatis(), mock(System2.class)),
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
qualityProfileDao = new QualityProfileDao(dbTester.myBatis(), mock(System2.class));
dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), qualityProfileDao);
private WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester = new WsTester(new QProfilesWs(
mock(RuleActivationActions.class),
mock(BulkRuleActivationActions.class),
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester = new WsTester(new QProfilesWs(
mock(RuleActivationActions.class),
mock(BulkRuleActivationActions.class),
private QProfileLoader profileLoader;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
qualityProfileDao = new QualityProfileDao(dbTester.myBatis(), mock(System2.class));
dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), qualityProfileDao);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
qualityProfileDao = new QualityProfileDao(dbTester.myBatis(), mock(System2.class));
dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), qualityProfileDao);
session.commit();
}
- private void checkDefaultProfile(String language, String key) throws Exception {
+ private void checkDefaultProfile(String language, String key) {
assertThat(dbClient.qualityProfileDao().getDefaultProfile(language).getKey()).isEqualTo(key);
}
}
WsTester wsTester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
db = tester.get(DbClient.class);
ws = tester.get(QProfilesWs.class);
}
@Test
- public void define_controller() throws Exception {
+ public void define_controller() {
assertThat(controller).isNotNull();
assertThat(controller.path()).isEqualTo(QProfilesWs.API_ENDPOINT);
assertThat(controller.description()).isNotEmpty();
}
@Test
- public void define_restore_built_action() throws Exception {
+ public void define_restore_built_action() {
WebService.Action restoreProfiles = controller.action("restore_built_in");
assertThat(restoreProfiles).isNotNull();
assertThat(restoreProfiles.isPost()).isTrue();
}
@Test
- public void define_search() throws Exception {
+ public void define_search() {
WebService.Action search = controller.action("search");
assertThat(search).isNotNull();
assertThat(search.isPost()).isFalse();
}
@Test
- public void define_activate_rule_action() throws Exception {
+ public void define_activate_rule_action() {
WebService.Action restoreProfiles = controller.action(RuleActivationActions.ACTIVATE_ACTION);
assertThat(restoreProfiles).isNotNull();
assertThat(restoreProfiles.isPost()).isTrue();
}
@Test
- public void define_deactivate_rule_action() throws Exception {
+ public void define_deactivate_rule_action() {
WebService.Action restoreProfiles = controller.action(RuleActivationActions.DEACTIVATE_ACTION);
assertThat(restoreProfiles).isNotNull();
assertThat(restoreProfiles.isPost()).isTrue();
}
@Test
- public void define_add_project_action() throws Exception {
+ public void define_add_project_action() {
WebService.Action addProject = controller.action("add_project");
assertThat(addProject).isNotNull();
assertThat(addProject.isPost()).isTrue();
}
@Test
- public void define_remove_project_action() throws Exception {
+ public void define_remove_project_action() {
WebService.Action removeProject = controller.action("remove_project");
assertThat(removeProject).isNotNull();
assertThat(removeProject.isPost()).isTrue();
}
@Test
- public void define_set_default_action() throws Exception {
+ public void define_set_default_action() {
WebService.Action setDefault = controller.action("set_default");
assertThat(setDefault).isNotNull();
assertThat(setDefault.isPost()).isTrue();
}
@Test
- public void define_projects_action() throws Exception {
+ public void define_projects_action() {
WebService.Action projects = controller.action("projects");
assertThat(projects).isNotNull();
assertThat(projects.isPost()).isFalse();
}
@Test
- public void define_backup_action() throws Exception {
+ public void define_backup_action() {
WebService.Action backup = controller.action("backup");
assertThat(backup).isNotNull();
assertThat(backup.isPost()).isFalse();
}
@Test
- public void define_restore_action() throws Exception {
+ public void define_restore_action() {
WebService.Action restore = controller.action("restore");
assertThat(restore).isNotNull();
assertThat(restore.isPost()).isTrue();
assertThat(restore.params()).hasSize(1);
}
- public void define_bulk_activate_rule_action() throws Exception {
+ public void define_bulk_activate_rule_action() {
WebService.Action restoreProfiles = controller.action(BulkRuleActivationActions.BULK_ACTIVATE_ACTION);
assertThat(restoreProfiles).isNotNull();
assertThat(restoreProfiles.isPost()).isTrue();
}
@Test
- public void define_bulk_deactivate_rule_action() throws Exception {
+ public void define_bulk_deactivate_rule_action() {
WebService.Action restoreProfiles = controller.action(BulkRuleActivationActions.BULK_DEACTIVATE_ACTION);
assertThat(restoreProfiles).isNotNull();
assertThat(restoreProfiles.isPost()).isTrue();
}
@Test
- public void define_create_action() throws Exception {
+ public void define_create_action() {
WebService.Action create = controller.action("create");
assertThat(create).isNotNull();
assertThat(create.isPost()).isTrue();
}
@Test
- public void define_importers_action() throws Exception {
+ public void define_importers_action() {
WebService.Action importers = controller.action("importers");
assertThat(importers).isNotNull();
assertThat(importers.isPost()).isFalse();
}
@Test
- public void define_changelog_action() throws Exception {
+ public void define_changelog_action() {
WebService.Action changelog = controller.action("changelog");
assertThat(changelog).isNotNull();
assertThat(changelog.isPost()).isFalse();
}
@Test
- public void define_change_parent_action() throws Exception {
+ public void define_change_parent_action() {
WebService.Action changeParent = controller.action("change_parent");
assertThat(changeParent).isNotNull();
assertThat(changeParent.isPost()).isTrue();
}
@Test
- public void define_compare_action() throws Exception {
+ public void define_compare_action() {
WebService.Action compare = controller.action("compare");
assertThat(compare).isNotNull();
assertThat(compare.isPost()).isFalse();
}
@Test
- public void define_copy_action() throws Exception {
+ public void define_copy_action() {
WebService.Action copy = controller.action("copy");
assertThat(copy).isNotNull();
assertThat(copy.isPost()).isTrue();
}
@Test
- public void define_delete_action() throws Exception {
+ public void define_delete_action() {
WebService.Action delete = controller.action("delete");
assertThat(delete).isNotNull();
assertThat(delete.isPost()).isTrue();
}
@Test
- public void define_export_action() throws Exception {
+ public void define_export_action() {
WebService.Action export = controller.action("export");
assertThat(export).isNotNull();
assertThat(export.isPost()).isFalse();
}
@Test
- public void define_exporters_action() throws Exception {
+ public void define_exporters_action() {
WebService.Action exporters = controller.action("exporters");
assertThat(exporters).isNotNull();
assertThat(exporters.isPost()).isFalse();
}
@Test
- public void define_inheritance_action() throws Exception {
+ public void define_inheritance_action() {
WebService.Action inheritance = controller.action("inheritance");
assertThat(inheritance).isNotNull();
assertThat(inheritance.isPost()).isFalse();
}
@Test
- public void define_rename_action() throws Exception {
+ public void define_rename_action() {
WebService.Action rename = controller.action("rename");
assertThat(rename).isNotNull();
assertThat(rename.isPost()).isTrue();
PlatformRackBridge underTest;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test(expected = RuntimeException.class)
- public void getRubyRuntime_throws_RE_when_RackApplicationFactory_is_not_in_ServletContext() throws Exception {
+ public void getRubyRuntime_throws_RE_when_RackApplicationFactory_is_not_in_ServletContext() {
underTest.getRubyRuntime();
}
@Test
- public void getRubyRuntime_returns_Ruby_instance_from_rack_application() throws Exception {
+ public void getRubyRuntime_returns_Ruby_instance_from_rack_application() {
when(servletContext.getAttribute("rack.factory")).thenReturn(rackApplicationFactory);
when(rackApplicationFactory.getApplication()).thenReturn(rackApplication);
private PlatformRubyBridge underTest;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(rackBridge.getRubyRuntime()).thenReturn(container.getProvider().getRuntime());
underTest = new PlatformRubyBridge(rackBridge);
}
private DbSession session;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
finder = tester.get(DefaultRuleFinder.class);
dbClient = tester.get(DbClient.class);
session = dbClient.openSession(false);
}
@Test
- public void wrap_deprecated_rule_repositories() throws Exception {
+ public void wrap_deprecated_rule_repositories() {
RulesDefinition.Context context = new RulesDefinition.Context();
new DeprecatedRulesDefinitionLoader(i18n, debtModelRepository, importer, new RuleRepository[] {new CheckstyleRules()}).complete(context);
}
@Test
- public void emulate_the_day_deprecated_api_can_be_dropped() throws Exception {
+ public void emulate_the_day_deprecated_api_can_be_dropped() {
RulesDefinition.Context context = new RulesDefinition.Context();
// no more RuleRepository !
}
@Test
- public void use_l10n_bundles() throws Exception {
+ public void use_l10n_bundles() {
RulesDefinition.Context context = new RulesDefinition.Context();
when(i18n.getName("checkstyle", "ConstantName")).thenReturn("Constant Name");
when(i18n.getDescription("checkstyle", "ConstantName")).thenReturn("Checks that constant names conform to the specified format");
}
@Test
- public void define_rule_debt() throws Exception {
+ public void define_rule_debt() {
RulesDefinition.Context context = new RulesDefinition.Context();
List<DebtModelXMLExporter.RuleDebt> ruleDebts = newArrayList(
}
@Test
- public void fail_on_invalid_rule_debt() throws Exception {
+ public void fail_on_invalid_rule_debt() {
RulesDefinition.Context context = new RulesDefinition.Context();
List<DebtModelXMLExporter.RuleDebt> ruleDebts = newArrayList(
}
@Test
- public void register_rules_at_startup() throws Exception {
+ public void register_rules_at_startup() {
register(new Rules() {
@Override
public void init(RulesDefinition.NewRepository repository) {
* 4. start server -> db is up-to-date (no changes) but rules must be re-indexed
*/
@Test
- public void index_rules_even_if_no_changes() throws Exception {
+ public void index_rules_even_if_no_changes() {
Rules rules = new Rules() {
@Override
public void init(RulesDefinition.NewRepository repository) {
}
@Test
- public void do_not_update_rules_if_no_changes() throws Exception {
+ public void do_not_update_rules_if_no_changes() {
Rules rules = new Rules() {
@Override
public void init(RulesDefinition.NewRepository repository) {
}
@Test
- public void deactivate_removed_rules_only_if_repository_still_exists() throws Exception {
+ public void deactivate_removed_rules_only_if_repository_still_exists() {
register(new Rules() {
@Override
public void init(RulesDefinition.NewRepository repository) {
}
@Test
- public void do_not_deactivate_removed_rules_if_repository_accidentally_uninstalled() throws Exception {
+ public void do_not_deactivate_removed_rules_if_repository_accidentally_uninstalled() {
Rules rules = new Rules() {
@Override
public void init(RulesDefinition.NewRepository repository) {
}
@Test
- public void update_active_rules_on_param_changes() throws Exception {
+ public void update_active_rules_on_param_changes() {
register(new Rules() {
@Override
public void init(RulesDefinition.NewRepository repository) {
}
@Test
- public void fail_if_debt_characteristic_is_root() throws Exception {
+ public void fail_if_debt_characteristic_is_root() {
try {
register(new Rules() {
@Override
}
@Test
- public void update_custom_rule_on_template_change() throws Exception {
+ public void update_custom_rule_on_template_change() {
register(new Rules() {
@Override
public void init(RulesDefinition.NewRepository repository) {
}
@Test
- public void do_not_update_custom_rule_if_no_template_change() throws Exception {
+ public void do_not_update_custom_rule_if_no_template_change() {
Rules rules = new Rules() {
@Override
public void init(RulesDefinition.NewRepository repository) {
}
@Test
- public void do_not_update_custom_rule_params_from_template() throws Exception {
+ public void do_not_update_custom_rule_params_from_template() {
register(new Rules() {
@Override
public void init(RulesDefinition.NewRepository repository) {
}
@After
- public void after() throws Exception {
+ public void after() {
dbSession.close();
}
RubyRuleService service;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
service = new RubyRuleService(ruleService, updater);
}
@Test
- public void find_by_key() throws Exception {
+ public void find_by_key() {
service.findByKey("squid:S001");
verify(ruleService).getByKey(RuleKey.of("squid", "S001"));
}
@Test
- public void search_rules() throws Exception {
+ public void search_rules() {
when(ruleService.search(any(RuleQuery.class), any(QueryContext.class))).thenReturn(mock(Result.class));
HashMap<String, Object> params = newHashMap();
}
@Test
- public void search_rules_activated_on_a_profile() throws Exception {
+ public void search_rules_activated_on_a_profile() {
when(ruleService.search(any(RuleQuery.class), any(QueryContext.class))).thenReturn(mock(Result.class));
HashMap<String, Object> params = newHashMap();
}
@Test
- public void search_rules_without_page_size_param() throws Exception {
+ public void search_rules_without_page_size_param() {
when(ruleService.search(any(RuleQuery.class), any(QueryContext.class))).thenReturn(mock(Result.class));
HashMap<String, Object> params = newHashMap();
}
@Test
- public void search_all_rules() throws Exception {
+ public void search_all_rules() {
List<Rule> rules = newArrayList(mock(Rule.class));
Result serviceResult = mock(Result.class);
when(serviceResult.scroll()).thenReturn(rules.iterator());
}
@Test
- public void update_rule() throws Exception {
+ public void update_rule() {
when(ruleService.search(any(RuleQuery.class), any(QueryContext.class))).thenReturn(mock(Result.class));
service.updateRule(ImmutableMap.<String, Object>of("ruleKey", "squid:S001"));
}
@Test
- public void search_manual_rules() throws Exception {
+ public void search_manual_rules() {
when(ruleService.search(any(RuleQuery.class), any(QueryContext.class))).thenReturn(mock(Result.class));
service.searchManualRules();
}
@Test
- public void create_manual_rules() throws Exception {
+ public void create_manual_rules() {
service.createManualRule(ImmutableMap.<String, Object>of("manualKey", "MY_MANUAL"));
verify(ruleService).create(any(NewRule.class));
}
@Test
- public void update_manual_rules() throws Exception {
+ public void update_manual_rules() {
service.updateManualRule(ImmutableMap.<String, Object>of("ruleKey", "manual:MY_MANUAL"));
verify(ruleService).update(any(RuleUpdate.class));
}
@Test
- public void delete_manual_rules() throws Exception {
+ public void delete_manual_rules() {
service.deleteManualRule("manual:MY_MANUAL");
verify(ruleService).delete(RuleKey.of("manual", "MY_MANUAL"));
}
@Test
- public void insert_in_db_and_multiget_in_es() throws InterruptedException {
+ public void insert_in_db_and_multiget_in_es() {
// insert db
RuleDto ruleDto = RuleTesting.newXooX1();
RuleDto ruleDto2 = RuleTesting.newXooX2();
}
@Test
- public void insert_in_db_and_index_in_es() throws InterruptedException {
+ public void insert_in_db_and_index_in_es() {
// insert db
RuleDto ruleDto = RuleTesting.newXooX1();
dao.insert(dbSession, ruleDto);
}
@Test
- public void insert_rule_tags_in_db_and_index_in_es() throws InterruptedException {
+ public void insert_rule_tags_in_db_and_index_in_es() {
// insert db
RuleDto ruleDto = RuleTesting.newXooX1();
dao.insert(dbSession, ruleDto);
}
@Test
- public void insert_and_update_rule_param() throws InterruptedException {
+ public void insert_and_update_rule_param() {
// insert db
RuleDto ruleDto = RuleTesting.newXooX1();
@Test
@Deprecated
- public void has_id() throws Exception {
+ public void has_id() {
RuleDto ruleDto = RuleTesting.newXooX1();
dao.insert(dbSession, ruleDto);
@Test
- public void insert_update_characteristics() throws Exception {
+ public void insert_update_characteristics() {
CharacteristicDto char1 = DebtTesting.newCharacteristicDto("c1");
db.debtCharacteristicDao().insert(char1, dbSession);
}
@Test
- public void insert_update_debt_overload() throws Exception {
+ public void insert_update_debt_overload() {
RuleDto ruleDto = RuleTesting.newXooX1()
.setRemediationFunction(null)
}
@Test
- public void create_custom_rule() throws Exception {
+ public void create_custom_rule() {
// insert template rule
RuleDto templateRule = createTemplateRule();
}
@Test
- public void create_custom_rule_with_empty_parameter_value() throws Exception {
+ public void create_custom_rule_with_empty_parameter_value() {
// insert template rule
RuleDto templateRule = createTemplateRule();
}
@Test
- public void create_custom_rule_with_no_parameter_value() throws Exception {
+ public void create_custom_rule_with_no_parameter_value() {
// insert template rule
RuleDto templateRule = createTemplateRuleWithIntArrayParam();
}
@Test
- public void create_custom_rule_with_multiple_parameter_values() throws Exception {
+ public void create_custom_rule_with_multiple_parameter_values() {
// insert template rule
RuleDto templateRule = createTemplateRuleWithIntArrayParam();
}
@Test
- public void create_custom_rule_with_invalid_parameter() throws Exception {
+ public void create_custom_rule_with_invalid_parameter() {
// insert template rule
RuleDto templateRule = createTemplateRuleWithIntArrayParam();
}
@Test
- public void create_custom_rule_with_invalid_parameters() throws Exception {
+ public void create_custom_rule_with_invalid_parameters() {
// insert template rule
RuleDto templateRule = createTemplateRuleWithTwoIntParams();
@Test
- public void reactivate_custom_rule_if_already_exists_in_removed_status() throws Exception {
+ public void reactivate_custom_rule_if_already_exists_in_removed_status() {
String key = "CUSTOM_RULE";
// insert template rule
}
@Test
- public void generate_reactivation_exception_when_rule_exists_in_removed_status_and_prevent_reactivation_parameter_is_true() throws Exception {
+ public void generate_reactivation_exception_when_rule_exists_in_removed_status_and_prevent_reactivation_parameter_is_true() {
String key = "CUSTOM_RULE";
// insert template rule
}
@Test
- public void fail_to_create_custom_rule_when_invalid_key() throws Exception {
+ public void fail_to_create_custom_rule_when_invalid_key() {
// insert template rule
RuleDto templateRule = createTemplateRule();
}
@Test
- public void fail_to_create_custom_rule_when_rule_key_already_exists() throws Exception {
+ public void fail_to_create_custom_rule_when_rule_key_already_exists() {
// insert template rule
RuleDto templateRule = createTemplateRule();
}
@Test
- public void fail_to_create_custom_rule_when_missing_name() throws Exception {
+ public void fail_to_create_custom_rule_when_missing_name() {
// insert template rule
RuleDto templateRule = createTemplateRule();
}
@Test
- public void fail_to_create_custom_rule_when_missing_description() throws Exception {
+ public void fail_to_create_custom_rule_when_missing_description() {
// insert template rule
RuleDto templateRule = createTemplateRule();
}
@Test
- public void fail_to_create_custom_rule_when_missing_severity() throws Exception {
+ public void fail_to_create_custom_rule_when_missing_severity() {
// insert template rule
RuleDto templateRule = createTemplateRule();
}
@Test
- public void fail_to_create_custom_rule_when_invalid_severity() throws Exception {
+ public void fail_to_create_custom_rule_when_invalid_severity() {
// insert template rule
RuleDto templateRule = createTemplateRule();
}
@Test
- public void fail_to_create_custom_rule_when_missing_status() throws Exception {
+ public void fail_to_create_custom_rule_when_missing_status() {
// insert template rule
RuleDto templateRule = createTemplateRule();
}
@Test
- public void fail_to_create_custom_rule_when_wrong_rule_template() throws Exception {
+ public void fail_to_create_custom_rule_when_wrong_rule_template() {
// insert rule
RuleDto rule = dao.insert(dbSession,
RuleTesting.newDto(RuleKey.of("java", "S001")).setIsTemplate(false));
}
@Test
- public void create_manual_rule() throws Exception {
+ public void create_manual_rule() {
NewRule newRule = NewRule.createForManualRule("MANUAL_RULE")
.setName("My manual")
.setMarkdownDescription("Some description");
}
@Test
- public void create_manual_rule_with_severity() throws Exception {
+ public void create_manual_rule_with_severity() {
NewRule newRule = NewRule.createForManualRule("MANUAL_RULE")
.setName("My manual")
.setMarkdownDescription("Some description")
}
@Test
- public void reactivate_manual_rule_if_already_exists_in_removed_status() throws Exception {
+ public void reactivate_manual_rule_if_already_exists_in_removed_status() {
String key = "MANUAL_RULE";
// insert a removed rule
}
@Test
- public void fail_to_create_manual_rule_when_missing_key() throws Exception {
+ public void fail_to_create_manual_rule_when_missing_key() {
try {
NewRule.createForManualRule("")
.setName("My manual")
}
@Test
- public void fail_to_create_manual_rule_when_invalid_key() throws Exception {
+ public void fail_to_create_manual_rule_when_invalid_key() {
NewRule newRule = NewRule.createForManualRule("*INVALID*")
.setName("My custom")
.setHtmlDescription("Some description");
}
@Test
- public void fail_to_create_manual_rule_when_rule_key_already_exists() throws Exception {
+ public void fail_to_create_manual_rule_when_rule_key_already_exists() {
NewRule newRule = NewRule.createForManualRule("MANUAL_RULE")
.setName("My manual")
.setHtmlDescription("Some description");
}
@Test
- public void fail_to_create_manual_rule_when_missing_name() throws Exception {
+ public void fail_to_create_manual_rule_when_missing_name() {
NewRule newRule = NewRule.createForManualRule("MANUAL_RULE")
.setHtmlDescription("Some description");
}
@Test
- public void fail_to_create_manual_rule_when_missing_description() throws Exception {
+ public void fail_to_create_manual_rule_when_missing_description() {
NewRule newRule = NewRule.createForManualRule("MANUAL_RULE")
.setName("My manual");
}
@Test
- public void fail_to_create_manual_rule_with_status() throws Exception {
+ public void fail_to_create_manual_rule_with_status() {
try {
NewRule.createForManualRule("MANUAL_RULE")
.setName("My manual")
}
@Test
- public void fail_to_create_manual_rule_with_parameters() throws Exception {
+ public void fail_to_create_manual_rule_with_parameters() {
try {
NewRule.createForManualRule("MANUAL_RULE")
.setName("My manual")
}
@Test
- public void delete_custom_rule() throws Exception {
+ public void delete_custom_rule() {
// Create template rule
RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("xoo", "T1")).setLanguage("xoo");
dao.insert(dbSession, templateRule);
}
@Test
- public void delete_manual_rule() throws Exception {
+ public void delete_manual_rule() {
// Create manual rule
RuleDto manualRule = RuleTesting.newManualRule("Manual_Rule");
dao.insert(dbSession, manualRule);
}
@Test
- public void fail_to_delete_if_not_custom_or_not_manual() throws Exception {
+ public void fail_to_delete_if_not_custom_or_not_manual() {
// Create rule
RuleKey ruleKey = RuleKey.of("java", "S001");
dao.insert(dbSession, RuleTesting.newDto(ruleKey));
RuleOperations operations;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(dbClient.openSession(false)).thenReturn(session);
when(dbClient.ruleDao()).thenReturn(ruleDao);
when(dbClient.debtCharacteristicDao()).thenReturn(characteristicDao);
}
@Test
- public void update_rule() throws Exception {
+ public void update_rule() {
RuleDto dto = new RuleDto().setId(1).setRepositoryKey("squid").setRuleKey("UselessImportCheck")
.setSubCharacteristicId(6).setRemediationFunction("CONSTANT_ISSUE").setRemediationOffset("10min");
RuleKey ruleKey = RuleKey.of("squid", "UselessImportCheck");
}
@Test
- public void update_rule_set_overridden_values_to_null_when_new_values_are_equals_to_default_values() throws Exception {
+ public void update_rule_set_overridden_values_to_null_when_new_values_are_equals_to_default_values() {
RuleDto dto = new RuleDto().setId(1).setRepositoryKey("squid").setRuleKey("UselessImportCheck")
.setSubCharacteristicId(6).setRemediationFunction("CONSTANT_ISSUE").setRemediationOffset("10min")
.setDefaultSubCharacteristicId(2).setDefaultRemediationFunction("CONSTANT_ISSUE").setDefaultRemediationOffset("10min");
}
@Test
- public void not_update_rule_if_same_sub_characteristic_and_function() throws Exception {
+ public void not_update_rule_if_same_sub_characteristic_and_function() {
RuleDto dto = new RuleDto().setId(1).setRepositoryKey("squid").setRuleKey("UselessImportCheck")
.setSubCharacteristicId(2).setRemediationFunction("CONSTANT_ISSUE").setRemediationOffset("10min");
RuleKey ruleKey = RuleKey.of("squid", "UselessImportCheck");
}
@Test
- public void update_rule_set_characteristic_if_different_from_default_one() throws Exception {
+ public void update_rule_set_characteristic_if_different_from_default_one() {
RuleDto dto = new RuleDto().setId(1).setRepositoryKey("squid").setRuleKey("UselessImportCheck")
.setDefaultSubCharacteristicId(2).setDefaultRemediationFunction("CONSTANT_ISSUE").setDefaultRemediationOffset("10min");
RuleKey ruleKey = RuleKey.of("squid", "UselessImportCheck");
}
@Test
- public void update_rule_set_remediation_function_if_different_from_default_one() throws Exception {
+ public void update_rule_set_remediation_function_if_different_from_default_one() {
RuleDto dto = new RuleDto().setId(1).setRepositoryKey("squid").setRuleKey("UselessImportCheck")
.setDefaultSubCharacteristicId(6).setDefaultRemediationFunction("CONSTANT_ISSUE").setDefaultRemediationOffset("10min");
RuleKey ruleKey = RuleKey.of("squid", "UselessImportCheck");
}
@Test
- public void disable_rule_debt_when_update_rule_with_no_sub_characteristic() throws Exception {
+ public void disable_rule_debt_when_update_rule_with_no_sub_characteristic() {
RuleDto dto = new RuleDto().setId(1).setRepositoryKey("squid").setRuleKey("UselessImportCheck")
.setDefaultSubCharacteristicId(6).setDefaultRemediationFunction("LINEAR").setDefaultRemediationCoefficient("10min")
.setSubCharacteristicId(6)
}
@Test
- public void disable_rule_debt_when_update_rule_with_no_function() throws Exception {
+ public void disable_rule_debt_when_update_rule_with_no_function() {
RuleDto dto = new RuleDto().setId(1).setRepositoryKey("squid").setRuleKey("UselessImportCheck")
.setDefaultSubCharacteristicId(6).setDefaultRemediationFunction("CONSTANT_ISSUE").setDefaultRemediationOffset("10min");
RuleKey ruleKey = RuleKey.of("squid", "UselessImportCheck");
}
@Test
- public void disable_characteristic_on_rule_having_no_debt_info() throws Exception {
+ public void disable_characteristic_on_rule_having_no_debt_info() {
RuleDto dto = new RuleDto().setId(1).setRepositoryKey("squid").setRuleKey("UselessImportCheck");
RuleKey ruleKey = RuleKey.of("squid", "UselessImportCheck");
}
@Test
- public void not_disable_characteristic_when_update_rule_if_already_disabled() throws Exception {
+ public void not_disable_characteristic_when_update_rule_if_already_disabled() {
RuleDto dto = new RuleDto().setId(1).setRepositoryKey("squid").setRuleKey("UselessImportCheck").setSubCharacteristicId(-1);
RuleKey ruleKey = RuleKey.of("squid", "UselessImportCheck");
}
@Test
- public void fail_to_update_rule_on_unknown_rule() throws Exception {
+ public void fail_to_update_rule_on_unknown_rule() {
RuleKey ruleKey = RuleKey.of("squid", "UselessImportCheck");
when(ruleDao.getNullableByKey(session, ruleKey)).thenReturn(null);
}
@Test
- public void fail_to_update_rule_on_unknown_sub_characteristic() throws Exception {
+ public void fail_to_update_rule_on_unknown_sub_characteristic() {
RuleDto dto = new RuleDto().setId(1).setRepositoryKey("squid").setRuleKey("UselessImportCheck")
.setSubCharacteristicId(2).setRemediationFunction("CONSTANT_ISSUE").setRemediationOffset("10min");
RuleKey ruleKey = RuleKey.of("squid", "UselessImportCheck");
}
@Test
- public void fail_to_update_rule_on_invalid_coefficient() throws Exception {
+ public void fail_to_update_rule_on_invalid_coefficient() {
RuleDto dto = new RuleDto().setId(1).setRepositoryKey("squid").setRuleKey("UselessImportCheck")
.setSubCharacteristicId(2).setRemediationFunction("LINEAR").setRemediationCoefficient("1h");
RuleKey ruleKey = RuleKey.of("squid", "UselessImportCheck");
}
@Test
- public void get_rule_by_key() throws Exception {
+ public void get_rule_by_key() {
MockUserSession.set()
.setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
.setLogin("me");
}
@Test
- public void get_non_null_rule_by_key() throws Exception {
+ public void get_non_null_rule_by_key() {
MockUserSession.set()
.setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
.setLogin("me");
}
@Test
- public void get_rule_by_key_escape_description_on_manual_rule() throws Exception {
+ public void get_rule_by_key_escape_description_on_manual_rule() {
MockUserSession.set()
.setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
.setLogin("me");
}
@Test
- public void get_rule_by_keys() throws Exception {
+ public void get_rule_by_keys() {
MockUserSession.set()
.setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
.setLogin("me");
}
@Test
- public void list_tags() throws InterruptedException {
+ public void list_tags() {
// insert db
RuleKey key1 = RuleKey.of("javascript", "S001");
RuleKey key2 = RuleKey.of("java", "S001");
}
@Test
- public void update_rule() throws Exception {
+ public void update_rule() {
MockUserSession.set()
.setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
.setLogin("me");
}
@Test(expected = UnauthorizedException.class)
- public void do_not_update_if_not_granted() throws Exception {
+ public void do_not_update_if_not_granted() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
RuleKey key = RuleKey.of("java", "S001");
}
@Test
- public void create_rule() throws Exception {
+ public void create_rule() {
MockUserSession.set()
.setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
.setLogin("me");
}
@Test(expected = UnauthorizedException.class)
- public void do_not_create_if_not_granted() throws Exception {
+ public void do_not_create_if_not_granted() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
service.create(NewRule.createForCustomRule("MY_CUSTOM", RuleKey.of("java", "S001")));
}
@Test
- public void delete_rule() throws Exception {
+ public void delete_rule() {
MockUserSession.set()
.setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
.setLogin("me");
}
@Test(expected = UnauthorizedException.class)
- public void do_not_delete_if_not_granted() throws Exception {
+ public void do_not_delete_if_not_granted() {
MockUserSession.set().setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
service.delete(RuleKey.of("java", "S001"));
public class RuleTagHelperTest {
@Test
- public void applyTags() throws Exception {
+ public void applyTags() {
RuleDto rule = new RuleDto().setTags(Sets.newHashSet("performance"));
boolean changed = RuleTagHelper.applyTags(rule, Sets.newHashSet("java8", "security"));
assertThat(rule.getTags()).containsOnly("java8", "security");
}
@Test
- public void applyTags_remove_all_existing_tags() throws Exception {
+ public void applyTags_remove_all_existing_tags() {
RuleDto rule = new RuleDto().setTags(Sets.newHashSet("performance"));
boolean changed = RuleTagHelper.applyTags(rule, Collections.<String>emptySet());
assertThat(rule.getTags()).isEmpty();
}
@Test
- public void applyTags_no_changes() throws Exception {
+ public void applyTags_no_changes() {
RuleDto rule = new RuleDto().setTags(Sets.newHashSet("performance"));
boolean changed = RuleTagHelper.applyTags(rule, Sets.newHashSet("performance"));
assertThat(rule.getTags()).containsOnly("performance");
}
@Test
- public void applyTags_validate_format() throws Exception {
+ public void applyTags_validate_format() {
RuleDto rule = new RuleDto();
boolean changed = RuleTagHelper.applyTags(rule, Sets.newHashSet("java8", "security"));
assertThat(rule.getTags()).containsOnly("java8", "security");
}
@Test
- public void applyTags_do_not_duplicate_system_tags() throws Exception {
+ public void applyTags_do_not_duplicate_system_tags() {
RuleDto rule = new RuleDto()
.setTags(Sets.newHashSet("performance"))
.setSystemTags(Sets.newHashSet("security"));
}
@Test
- public void do_not_update_rule_with_removed_status() throws Exception {
+ public void do_not_update_rule_with_removed_status() {
ruleDao.insert(dbSession, RuleTesting.newDto(RULE_KEY).setStatus(RuleStatus.REMOVED));
dbSession.commit();
}
@Test
- public void no_changes() throws Exception {
+ public void no_changes() {
ruleDao.insert(dbSession, RuleTesting.newDto(RULE_KEY)
// the following fields are not supposed to be updated
.setNoteData("my *note*")
}
@Test
- public void set_markdown_note() throws Exception {
+ public void set_markdown_note() {
MockUserSession.set().setLogin("me");
ruleDao.insert(dbSession, RuleTesting.newDto(RULE_KEY)
}
@Test
- public void remove_markdown_note() throws Exception {
+ public void remove_markdown_note() {
ruleDao.insert(dbSession, RuleTesting.newDto(RULE_KEY)
.setNoteData("my *note*")
.setNoteUserLogin("me"));
}
@Test
- public void set_tags() throws Exception {
+ public void set_tags() {
// insert db
ruleDao.insert(dbSession, RuleTesting.newDto(RULE_KEY)
.setTags(Sets.newHashSet("security"))
}
@Test
- public void remove_tags() throws Exception {
+ public void remove_tags() {
ruleDao.insert(dbSession, RuleTesting.newDto(RULE_KEY)
.setTags(Sets.newHashSet("security"))
.setSystemTags(Sets.newHashSet("java8", "javadoc")));
}
@Test
- public void override_debt() throws Exception {
+ public void override_debt() {
insertDebtCharacteristics(dbSession);
ruleDao.insert(dbSession, RuleTesting.newDto(RULE_KEY)
.setDefaultSubCharacteristicId(hardReliabilityId)
}
@Test
- public void override_debt_only_offset() throws Exception {
+ public void override_debt_only_offset() {
insertDebtCharacteristics(dbSession);
ruleDao.insert(dbSession, RuleTesting.newDto(RULE_KEY)
.setDefaultSubCharacteristicId(hardReliabilityId)
}
@Test
- public void override_debt_from_linear_with_offset_to_constant() throws Exception {
+ public void override_debt_from_linear_with_offset_to_constant() {
insertDebtCharacteristics(dbSession);
ruleDao.insert(dbSession, RuleTesting.newDto(RULE_KEY)
.setDefaultSubCharacteristicId(hardReliabilityId)
}
@Test
- public void reset_debt() throws Exception {
+ public void reset_debt() {
insertDebtCharacteristics(dbSession);
ruleDao.insert(dbSession, RuleTesting.newDto(RULE_KEY)
.setDefaultSubCharacteristicId(hardReliabilityId)
}
@Test
- public void unset_debt() throws Exception {
+ public void unset_debt() {
insertDebtCharacteristics(dbSession);
ruleDao.insert(dbSession, RuleTesting.newDto(RULE_KEY)
.setDefaultSubCharacteristicId(hardReliabilityId)
}
@Test
- public void update_custom_rule() throws Exception {
+ public void update_custom_rule() {
// Create template rule
RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
ruleDao.insert(dbSession, templateRule);
}
@Test
- public void update_custom_rule_with_empty_parameter() throws Exception {
+ public void update_custom_rule_with_empty_parameter() {
// Create template rule
RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
ruleDao.insert(dbSession, templateRule);
}
@Test
- public void update_active_rule_parameters_when_updating_custom_rule() throws Exception {
+ public void update_active_rule_parameters_when_updating_custom_rule() {
// Create template rule with 3 parameters
RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001")).setLanguage("xoo");
ruleDao.insert(dbSession, templateRule);
}
@Test
- public void fail_to_update_custom_rule_when_empty_name() throws Exception {
+ public void fail_to_update_custom_rule_when_empty_name() {
// Create template rule
RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
ruleDao.insert(dbSession, templateRule);
}
@Test
- public void fail_to_update_custom_rule_when_empty_description() throws Exception {
+ public void fail_to_update_custom_rule_when_empty_description() {
// Create template rule
RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
ruleDao.insert(dbSession, templateRule);
}
@Test
- public void update_manual_rule() throws Exception {
+ public void update_manual_rule() {
// Create manual rule
RuleDto manualRule = RuleTesting.newManualRule("My manual")
.setName("Old name")
}
@Test
- public void fail_to_update_manual_rule_if_status_is_set() throws Exception {
+ public void fail_to_update_manual_rule_if_status_is_set() {
// Create manual rule
RuleDto manualRule = RuleTesting.newManualRule("My manual");
ruleDao.insert(dbSession, manualRule);
}
@Test
- public void fail_to_update_manual_rule_if_parameters_are_set() throws Exception {
+ public void fail_to_update_manual_rule_if_parameters_are_set() {
// Create manual rule
RuleDto manualRule = RuleTesting.newManualRule("My manual");
ruleDao.insert(dbSession, manualRule);
}
@Test
- public void fail_to_update_plugin_rule_if_name_is_set() throws Exception {
+ public void fail_to_update_plugin_rule_if_name_is_set() {
// Create rule rule
RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("squid", "S01"));
ruleDao.insert(dbSession, ruleDto);
}
@Test
- public void fail_to_update_plugin_rule_if_description_is_set() throws Exception {
+ public void fail_to_update_plugin_rule_if_description_is_set() {
// Create rule rule
RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("squid", "S01"));
ruleDao.insert(dbSession, ruleDto);
}
@Test
- public void fail_to_update_plugin_rule_if_severity_is_set() throws Exception {
+ public void fail_to_update_plugin_rule_if_severity_is_set() {
// Create rule rule
RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("squid", "S01"));
ruleDao.insert(dbSession, ruleDto);
private System2 system2;
@Before
- public void before() throws Exception {
+ public void before() {
this.session = getMyBatis().openSession(false);
this.system2 = mock(System2.class);
this.dao = new RuleDao(system2);
}
@Test
- public void select_all() throws Exception {
+ public void select_all() {
setupData("selectAll");
List<RuleDto> ruleDtos = dao.findAll(session);
}
@Test
- public void select_enables_and_non_manual() throws Exception {
+ public void select_enables_and_non_manual() {
setupData("select_enables_and_non_manual");
List<RuleDto> ruleDtos = dao.findByEnabledAndNotManual(session);
}
@Test
- public void select_by_id() throws Exception {
+ public void select_by_id() {
setupData("selectById");
RuleDto ruleDto = dao.getById(session, 2);
}
@Test
- public void select_by_rule_key() throws Exception {
+ public void select_by_rule_key() {
setupData("select_by_rule_key");
assertThat(dao.getNullableByKey(session, RuleKey.of("checkstyle", "AvoidComparison"))).isNotNull();
assertThat(dao.getNullableByKey(session, RuleKey.of("checkstyle", "Unknown"))).isNull();
}
@Test
- public void select_by_name() throws Exception {
+ public void select_by_name() {
setupData("select_by_name");
RuleDto ruleDto = dao.getByName("Avoid Null", session);
}
@Test
- public void select_non_manual() throws Exception {
+ public void select_non_manual() {
setupData("selectNonManual");
List<RuleDto> ruleDtos = dao.findByNonManual(session);
session.commit();
}
@Test
- public void select_parameters() throws Exception {
+ public void select_parameters() {
setupData("selectParameters");
List<RuleParamDto> ruleDtos = dao.findAllRuleParams(session);
}
@Test
- public void select_parameters_by_rule_id() throws Exception {
+ public void select_parameters_by_rule_id() {
setupData("select_parameters_by_rule_id");
RuleDto rule = dao.getById(session, 1);
List<RuleParamDto> ruleDtos = dao.findRuleParamsByRuleKey(session, rule.getKey());
}
@Test
- public void getByKey() throws InterruptedException {
+ public void getByKey() {
RuleDto ruleDto = RuleTesting.newDto(RuleKey.of("javascript", "S001"));
dao.insert(dbSession, ruleDto);
dbSession.commit();
}
@Test
- public void getByKey_null_if_not_found() throws InterruptedException {
+ public void getByKey_null_if_not_found() {
Rule rule = index.getNullableByKey(RuleKey.of("javascript", "unknown"));
assertThat(rule).isNull();
}
@Test
- public void search_all_rules() throws InterruptedException {
+ public void search_all_rules() {
dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("javascript", "S001")));
dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")));
dbSession.commit();
}
@Test
- public void scroll_all_rules() throws InterruptedException {
+ public void scroll_all_rules() {
int max = 100;
for (int i = 0; i < max; i++) {
dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "scroll_" + i)));
}
@Test
- public void search_by_has_debt_characteristic() throws InterruptedException {
+ public void search_by_has_debt_characteristic() {
CharacteristicDto char1 = DebtTesting.newCharacteristicDto("c1")
.setEnabled(true)
.setName("char1");
}
@Test
- public void facet_on_debt_characteristic() throws InterruptedException {
+ public void facet_on_debt_characteristic() {
CharacteristicDto char1 = DebtTesting.newCharacteristicDto("c1")
.setEnabled(true)
.setName("char1");
}
@Test
- public void search_by_any_of_languages() throws InterruptedException {
+ public void search_by_any_of_languages() {
dao.insert(dbSession,
RuleTesting.newDto(RuleKey.of("java", "S001")).setLanguage("java"),
RuleTesting.newDto(RuleKey.of("javascript", "S002")).setLanguage("js"));
}
@Test
- public void search_by_characteristics() throws InterruptedException {
+ public void search_by_characteristics() {
CharacteristicDto char1 = DebtTesting.newCharacteristicDto("RELIABILITY");
db.debtCharacteristicDao().insert(char1, dbSession);
}
@Test
- public void search_by_characteristics_with_default_and_overridden_char() throws InterruptedException {
+ public void search_by_characteristics_with_default_and_overridden_char() {
CharacteristicDto char1 = DebtTesting.newCharacteristicDto("RELIABILITY");
db.debtCharacteristicDao().insert(char1, dbSession);
}
@Test
- public void search_by_any_of_severities() throws InterruptedException {
+ public void search_by_any_of_severities() {
dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setSeverity(Severity.BLOCKER));
dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setSeverity(Severity.INFO));
dbSession.commit();
}
@Test
- public void search_by_any_of_statuses() throws InterruptedException {
+ public void search_by_any_of_statuses() {
dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setStatus(RuleStatus.BETA));
dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setStatus(RuleStatus.READY));
dbSession.commit();
}
@Test
- public void fail_sort_by_language() throws InterruptedException {
+ public void fail_sort_by_language() {
try {
// Sorting on a field not tagged as sortable
new RuleQuery().setSortField(RuleNormalizer.RuleField.LANGUAGE);
}
@Test
- public void search_by_profile() throws InterruptedException {
+ public void search_by_profile() {
QualityProfileDto qualityProfileDto1 = QProfileTesting.newXooP1();
QualityProfileDto qualityProfileDto2 = QProfileTesting.newXooP2();
db.qualityProfileDao().insert(dbSession, qualityProfileDto1, qualityProfileDto2);
}
@Test
- public void search_by_profile_and_inheritance() throws InterruptedException {
+ public void search_by_profile_and_inheritance() {
QualityProfileDto qualityProfileDto1 = QProfileTesting.newXooP1();
QualityProfileDto qualityProfileDto2 = QProfileTesting.newXooP2().setParentKee(QProfileTesting.XOO_P1_KEY);
db.qualityProfileDao().insert(dbSession, qualityProfileDto1, qualityProfileDto2);
}
@Test
- public void search_by_profile_and_active_severity() throws InterruptedException {
+ public void search_by_profile_and_active_severity() {
QualityProfileDto qualityProfileDto1 = QProfileTesting.newXooP1();
QualityProfileDto qualityProfileDto2 = QProfileTesting.newXooP2();
db.qualityProfileDao().insert(dbSession, qualityProfileDto1, qualityProfileDto2);
}
@Test
- public void complex_param_value() throws InterruptedException {
+ public void complex_param_value() {
String value = "//expression[primary/qualifiedIdentifier[count(IDENTIFIER) = 2]/IDENTIFIER[2]/@tokenValue = 'firstOf' and primary/identifierSuffix/arguments/expression[not(primary) or primary[not(qualifiedIdentifier) or identifierSuffix]]]";
QualityProfileDto profile = QProfileTesting.newXooP1();
}
@Test
- public void search_by_tag() throws InterruptedException {
+ public void search_by_tag() {
dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setTags(ImmutableSet.of("tag1")));
dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setTags(ImmutableSet.of("tag2")));
dbSession.commit();
}
@Test
- public void search_by_is_template() throws InterruptedException {
+ public void search_by_is_template() {
dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setIsTemplate(false));
dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setIsTemplate(true));
dbSession.commit();
}
@Test
- public void search_by_template_key() throws InterruptedException {
+ public void search_by_template_key() {
RuleDto templateRule = RuleTesting.newDto(RuleKey.of("java", "S001")).setIsTemplate(true);
dao.insert(dbSession, templateRule);
dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S001_MY_CUSTOM")).setTemplateId(templateRule.getId()));
}
@Test
- public void search_by_template_key_with_params() throws InterruptedException {
+ public void search_by_template_key_with_params() {
RuleDto templateRule = RuleTesting.newDto(RuleKey.of("java", "S001")).setIsTemplate(true);
RuleParamDto ruleParamDto = RuleParamDto.createFor(templateRule).setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*");
dao.insert(dbSession, templateRule);
}
@Test
- public void show_custom_rule() throws InterruptedException {
+ public void show_custom_rule() {
RuleDto templateRule = RuleTesting.newDto(RuleKey.of("java", "S001")).setIsTemplate(true);
dao.insert(dbSession, templateRule);
dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S001_MY_CUSTOM")).setTemplateId(templateRule.getId()));
}
@Test
- public void scroll_byIds() throws Exception {
+ public void scroll_byIds() {
Set<Integer> ids = new HashSet<Integer>();
for (int i = 0; i < 150; i++) {
RuleDto rule = RuleTesting.newDto(RuleKey.of("scroll", "r_" + i));
}
@Test
- public void search_protected_chars() throws InterruptedException {
+ public void search_protected_chars() {
String nameWithProtectedChars = "ja#va&sc\"r:ipt";
RuleDto ruleDto = RuleTesting.newXooX1().setName(nameWithProtectedChars);
DbSession session;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
wsTester = tester.get(WsTester.class);
ruleDao = tester.get(RuleDao.class);
}
@Test
- public void fail_if_custom_key_and_manual_key_parameters_are_not_set() throws Exception {
+ public void fail_if_custom_key_and_manual_key_parameters_are_not_set() {
MockUserSession.set()
.setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
.setLogin("me");
RuleService ruleService;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester = new WsTester(new RulesWebService(new DeleteAction(ruleService)));
}
DebtModel debtModel = mock(DebtModel.class);
@Test
- public void toQueryOptions_load_all_fields() throws Exception {
+ public void toQueryOptions_load_all_fields() {
RuleMapping mapping = new RuleMapping(languages, macroInterpreter, debtModel);
SimpleGetRequest request = new SimpleGetRequest();
request.setParam("p", "1");
}
@Test
- public void toQueryOptions_load_only_few_simple_fields() throws Exception {
+ public void toQueryOptions_load_only_few_simple_fields() {
RuleMapping mapping = new RuleMapping(languages, macroInterpreter, debtModel);
SimpleGetRequest request = new SimpleGetRequest();
request.setParam("p", "1");
}
@Test
- public void toQueryOptions_langName_requires_lang() throws Exception {
+ public void toQueryOptions_langName_requires_lang() {
RuleMapping mapping = new RuleMapping(languages, macroInterpreter, debtModel);
SimpleGetRequest request = new SimpleGetRequest();
request.setParam("p", "1");
}
@Test
- public void toQueryOptions_debt_requires_group_of_fields() throws Exception {
+ public void toQueryOptions_debt_requires_group_of_fields() {
RuleMapping mapping = new RuleMapping(languages, macroInterpreter, debtModel);
SimpleGetRequest request = new SimpleGetRequest();
request.setParam("p", "1");
}
@Test
- public void toQueryOptions_html_note_requires_markdown_note() throws Exception {
+ public void toQueryOptions_html_note_requires_markdown_note() {
RuleMapping mapping = new RuleMapping(languages, macroInterpreter, debtModel);
SimpleGetRequest request = new SimpleGetRequest();
request.setParam("p", "1");
}
@Test
- public void toQueryOptions_debt_characteristics() throws Exception {
+ public void toQueryOptions_debt_characteristics() {
RuleMapping mapping = new RuleMapping(languages, macroInterpreter, debtModel);
SimpleGetRequest request = new SimpleGetRequest();
request.setParam("p", "1");
}
@Test
- public void toQueryOptions_debt_overloaded() throws Exception {
+ public void toQueryOptions_debt_overloaded() {
RuleMapping mapping = new RuleMapping(languages, macroInterpreter, debtModel);
SimpleGetRequest request = new SimpleGetRequest();
request.setParam("p", "1");
int softReliabilityId, hardReliabilityId;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
db = tester.get(DbClient.class);
ruleDao = tester.get(RuleDao.class);
}
@Test
- public void define() throws Exception {
+ public void define() {
WebService.Context context = new WebService.Context();
ws.define(context);
DbSession session;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
wsTester = tester.get(WsTester.class);
ruleService = tester.get(RuleService.class);
DbSession session;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
wsTester = tester.get(WsTester.class);
ruleService = tester.get(RuleService.class);
}
@Test
- public void fail_to_update_custom_when_description_is_empty() throws Exception {
+ public void fail_to_update_custom_when_description_is_empty() {
MockUserSession.set()
.setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
.setLogin("me");
public class BaseDocTest {
@Test
- public void getField() throws Exception {
+ public void getField() {
Map<String, Object> fields = Maps.newHashMap();
fields.put("a_string", "foo");
fields.put("a_int", 42);
}
@Test
- public void getField_fails_if_missing_field() throws Exception {
+ public void getField_fails_if_missing_field() {
Map<String, Object> fields = Collections.emptyMap();
BaseDoc doc = new BaseDoc(fields) {
};
}
@Test
- public void getFieldAsDate() throws Exception {
+ public void getFieldAsDate() {
BaseDoc doc = new BaseDoc(Maps.<String,Object>newHashMap()) {
};
long now = System.currentTimeMillis();
}
@Test
- public void getNullableFieldAsDate() throws Exception {
+ public void getNullableFieldAsDate() {
BaseDoc doc = new BaseDoc(Maps.<String,Object>newHashMap()) {
};
long now = System.currentTimeMillis();
SearchClient searchClient;
@Before
- public void setup() throws IOException {
+ public void setup() {
EsServerHolder holder = EsServerHolder.get();
Settings settings = new Settings();
settings.setProperty(ProcessProperties.CLUSTER_ACTIVATE, false);
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
if (searchClient != null) {
searchClient.stop();
}
public static EsTester esTester = new EsTester().addDefinitions(new FacetsTestDefinition());
@Before
- public void setUp() throws Exception {
+ public void setUp() {
esTester.truncateIndices();
}
@Test
- public void should_ignore_result_without_aggregations() throws Exception {
+ public void should_ignore_result_without_aggregations() {
Facets facets = new Facets(mock(SearchResponse.class));
assertThat(facets.getFacets()).isEmpty();
assertThat(facets.getFacetKeys("polop")).isEmpty();
QueryContext options;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
MockUserSession.set().setLogin("john").setUserGroups("sonar-users");
options = new QueryContext();
}
@Test
- public void user_and_groups() throws Exception {
+ public void user_and_groups() {
assertThat(options.getUserLogin()).isEqualTo("john");
assertThat(options.getUserGroups()).containsOnly("sonar-users", "Anyone");
}
@Test
- public void page_shortcut_for_limit_and_offset() throws Exception {
+ public void page_shortcut_for_limit_and_offset() {
options.setPage(3, 10);
assertThat(options.getLimit()).isEqualTo(10);
}
@Test
- public void page_starts_at_one() throws Exception {
+ public void page_starts_at_one() {
options.setPage(1, 10);
assertThat(options.getLimit()).isEqualTo(10);
assertThat(options.getOffset()).isEqualTo(0);
}
@Test
- public void with_zero_page_size() throws Exception {
+ public void with_zero_page_size() {
options.setPage(1, 0);
assertThat(options.getLimit()).isEqualTo(0);
assertThat(options.getOffset()).isEqualTo(0);
}
@Test
- public void page_must_be_strictly_positive() throws Exception {
+ public void page_must_be_strictly_positive() {
try {
options.setPage(0, 10);
fail();
}
@Test
- public void page_size_must_be_positive() throws Exception {
+ public void page_size_must_be_positive() {
try {
options.setPage(2, -1);
fail();
}
@Test
- public void max_limit() throws Exception {
+ public void max_limit() {
options.setLimit(42);
assertThat(options.getLimit()).isEqualTo(42);
}
@Test
- public void set_max_limit() throws Exception {
+ public void set_max_limit() {
options.setMaxLimit();
assertThat(options.getLimit()).isEqualTo(QueryContext.MAX_LIMIT);
}
@Test
- public void max_page_size() throws Exception {
+ public void max_page_size() {
options.setPage(3, QueryContext.MAX_LIMIT + 10);
assertThat(options.getOffset()).isEqualTo(QueryContext.MAX_LIMIT * 2);
assertThat(options.getLimit()).isEqualTo(QueryContext.MAX_LIMIT);
}
@Test
- public void getFieldsToReturn() throws Exception {
+ public void getFieldsToReturn() {
assertThat(options.getFieldsToReturn()).isEmpty();
options.setFieldsToReturn(Arrays.asList("one", "two"));
}
@Test
- public void support_immutable_fields() throws Exception {
+ public void support_immutable_fields() {
options.setFieldsToReturn(ImmutableList.of("one", "two"));
assertThat(options.getFieldsToReturn()).containsOnly("one", "two");
}
@Test
- public void do_not_request_facets_by_default() throws Exception {
+ public void do_not_request_facets_by_default() {
assertThat(options.isFacet()).isFalse();
options.addFacets(Arrays.asList("polop"));
SearchClient searchClient;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
searchClient = tester.get(SearchClient.class);
}
@Test
- public void prepare_multi_search_is_not_yet_implemented() throws Exception {
+ public void prepare_multi_search_is_not_yet_implemented() {
try {
searchClient.prepareMultiSearch();
fail();
}
@Test
- public void prepare_update_is_not_yet_implemented() throws Exception {
+ public void prepare_update_is_not_yet_implemented() {
try {
searchClient.prepareUpdate();
fail();
}
@Test
- public void prepare_delete_is_not_yet_implemented() throws Exception {
+ public void prepare_delete_is_not_yet_implemented() {
try {
searchClient.prepareDelete();
fail();
}
@Test
- public void delete_by_query_is_not_supported() throws Exception {
+ public void delete_by_query_is_not_supported() {
try {
searchClient.prepareDeleteByQuery();
fail();
}
@Test
- public void prepare_percolate_is_not_yet_implemented() throws Exception {
+ public void prepare_percolate_is_not_yet_implemented() {
try {
searchClient.preparePercolate();
fail();
}
@Test
- public void prepare_multi_percolate_is_not_yet_implemented() throws Exception {
+ public void prepare_multi_percolate_is_not_yet_implemented() {
try {
searchClient.prepareMultiPercolate();
fail();
}
@Test
- public void prepare_suggest_is_not_yet_implemented() throws Exception {
+ public void prepare_suggest_is_not_yet_implemented() {
try {
searchClient.prepareSuggest("index");
fail();
}
@Test
- public void prepare_more_like_this_is_not_yet_implemented() throws Exception {
+ public void prepare_more_like_this_is_not_yet_implemented() {
try {
searchClient.prepareMoreLikeThis("index", "tpye", "id");
fail();
}
@Test
- public void prepare_term_vector_is_not_yet_implemented() throws Exception {
+ public void prepare_term_vector_is_not_yet_implemented() {
try {
searchClient.prepareTermVector("index", "tpye", "id");
fail();
}
@Test
- public void prepare_multi_term_vectors_is_not_yet_implemented() throws Exception {
+ public void prepare_multi_term_vectors_is_not_yet_implemented() {
try {
searchClient.prepareMultiTermVectors();
fail();
}
@Test
- public void prepare_explain_is_not_yet_implemented() throws Exception {
+ public void prepare_explain_is_not_yet_implemented() {
try {
searchClient.prepareExplain("index", "tpye", "id");
fail();
}
@Test
- public void prepare_clear_scroll_is_not_yet_implemented() throws Exception {
+ public void prepare_clear_scroll_is_not_yet_implemented() {
try {
searchClient.prepareClearScroll();
fail();
Index index;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
index = mock(Index.class);
when(index.getIndexName()).thenReturn(TEST_INDEX.getIndexName());
}
@Test
- public void get_delete_request() throws Exception {
+ public void get_delete_request() {
String key = "test_key";
DeleteKey<String> deleteAction = new DeleteKey<String>(TEST_INDEX.getIndexType(), key);
Index index;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
index = mock(Index.class);
when(index.getIndexName()).thenReturn(TEST_INDEX.getIndexName());
}
@Test
- public void get_delete_request() throws Exception {
+ public void get_delete_request() {
RefreshIndex refreshAction = new RefreshIndex(TEST_INDEX.getIndexType());
try {
public class SearchOptionsTest {
@Test
- public void create_from_http_request() throws Exception {
+ public void create_from_http_request() {
SimpleGetRequest request = new SimpleGetRequest();
request.setParam("p", "3");
request.setParam("ps", "10");
}
@Test
- public void hasField() throws Exception {
+ public void hasField() {
SimpleGetRequest request = new SimpleGetRequest();
request.setParam("p", "3");
request.setParam("ps", "10");
}
@Test
- public void hasField_always_true_by_default() throws Exception {
+ public void hasField_always_true_by_default() {
SimpleGetRequest request = new SimpleGetRequest();
request.setParam("p", "3");
request.setParam("ps", "10");
}
@Test
- public void hasField_no_if_empty_value() throws Exception {
+ public void hasField_no_if_empty_value() {
SimpleGetRequest request = new SimpleGetRequest();
request.setParam("p", "3");
request.setParam("ps", "10");
}
@Test
- public void write_statistics_to_json_response() throws Exception {
+ public void write_statistics_to_json_response() {
SimpleGetRequest request = new SimpleGetRequest();
request.setParam("p", "3");
request.setParam("ps", "10");
}
@Test
- public void defineFieldsParam() throws Exception {
+ public void defineFieldsParam() {
WebService.Context context = new WebService.Context();
new WebService() {
@Override
}
@Test
- public void definePageParams() throws Exception {
+ public void definePageParams() {
WebService.Context context = new WebService.Context();
new WebService() {
@Override
}
@Test
- public void should_extract_lower_bounds_from_serialized_rules() throws Exception {
+ public void should_extract_lower_bounds_from_serialized_rules() {
List<OpeningHtmlTag> openingTagsEntries = decorationDataHolder.getOpeningTagsEntries();
}
@Test
- public void should_extract_upper_bounds_from_serialized_rules() throws Exception {
+ public void should_extract_upper_bounds_from_serialized_rules() {
List<Integer> offsets = decorationDataHolder.getClosingTagsOffsets();
public class HtmlTextDecoratorTest {
@Test
- public void should_decorate_simple_character_range() throws Exception {
+ public void should_decorate_simple_character_range() {
String packageDeclaration = "package org.sonar.core.source;";
}
@Test
- public void should_decorate_multiple_lines_characters_range() throws Exception {
+ public void should_decorate_multiple_lines_characters_range() {
String firstCommentLine = "/*";
String secondCommentLine = " * Test";
}
@Test
- public void should_highlight_multiple_words_in_one_line() throws Exception {
+ public void should_highlight_multiple_words_in_one_line() {
String classDeclaration = "public class MyClass implements MyInterface {";
}
@Test
- public void should_allow_multiple_levels_highlighting() throws Exception {
+ public void should_allow_multiple_levels_highlighting() {
String javaDocSample =
"/**" + LF_END_OF_LINE +
}
@Test
- public void should_support_crlf_line_breaks() throws Exception {
+ public void should_support_crlf_line_breaks() {
String crlfCodeSample =
"/**" + CR_END_OF_LINE + LF_END_OF_LINE +
}
@Test
- public void should_close_tags_at_end_of_file() throws Exception {
+ public void should_close_tags_at_end_of_file() {
String classDeclarationSample =
"/*" + LF_END_OF_LINE +
}
@Test
- public void should_escape_markup_chars() throws Exception {
+ public void should_escape_markup_chars() {
String javadocWithHtml =
"/**\n" +
}
@Test
- public void should_escape_ampersand_char() throws Exception {
+ public void should_escape_ampersand_char() {
String javadocWithAmpersandChar =
"/**\n" +
}
@Test
- public void should_support_cr_line_breaks() throws Exception {
+ public void should_support_cr_line_breaks() {
String crCodeSample =
"/**" + CR_END_OF_LINE +
}
@Test
- public void should_support_multiple_empty_lines_at_end_of_file() throws Exception {
+ public void should_support_multiple_empty_lines_at_end_of_file() {
String classDeclarationSample =
"/*" + LF_END_OF_LINE +
}
@Test
- public void returned_code_begin_from_given_param() throws Exception {
+ public void returned_code_begin_from_given_param() {
String javadocWithHtml =
"/**\n" +
}
@Test
- public void returned_code_end_to_given_param() throws Exception {
+ public void returned_code_end_to_given_param() {
String javadocWithHtml =
"/**\n" +
}
@Test
- public void returned_code_is_between_from_and_to_params() throws Exception {
+ public void returned_code_is_between_from_and_to_params() {
String javadocWithHtml =
"/**\n" +
SourceService service;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
service = new SourceService(sourceDecorator, sourceLineIndex);
}
@Test
- public void get_html_lines() throws Exception {
+ public void get_html_lines() {
when(sourceLineIndex.getLines(COMPONENT_UUID, 1, Integer.MAX_VALUE)).thenReturn(
Arrays.asList(new SourceLineDoc().setSource("source").setHighlighting("highlight").setSymbols("symbols")));
}
@Test
- public void get_block_of_lines() throws Exception {
+ public void get_block_of_lines() {
when(sourceLineIndex.getLines(COMPONENT_UUID, 1, Integer.MAX_VALUE)).thenReturn(
Arrays.asList(new SourceLineDoc().setSource("source").setHighlighting("highlight").setSymbols("symbols"),
}
@Test
- public void getLinesAsTxt() throws Exception {
+ public void getLinesAsTxt() {
when(sourceLineIndex.getLines(COMPONENT_UUID, 1, Integer.MAX_VALUE)).thenReturn(
Arrays.asList(
new SourceLineDoc().setSource("line1"),
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void select() throws Exception {
+ public void select() {
setupData("shared");
FileSourceDto fileSourceDto = sut.selectSource("FILE1_UUID");
}
@Test
- public void select_data() throws Exception {
+ public void select_data() {
setupData("shared");
InputStreamToStringFunction fn = new InputStreamToStringFunction();
}
@Test
- public void select_line_hashes() throws Exception {
+ public void select_line_hashes() {
setupData("shared");
ReaderToStringFunction fn = new ReaderToStringFunction();
}
@Test
- public void no_line_hashes_on_unknown_file() throws Exception {
+ public void no_line_hashes_on_unknown_file() {
setupData("shared");
ReaderToStringFunction fn = new ReaderToStringFunction();
}
@Test
- public void insert() throws Exception {
+ public void insert() {
setupData("shared");
sut.insert(new FileSourceDto()
}
@Test
- public void update() throws Exception {
+ public void update() {
setupData("shared");
sut.update(new FileSourceDto()
}
@Test
- public void update_date_when_updated_date_is_zero() throws Exception {
+ public void update_date_when_updated_date_is_zero() {
setupData("update_date_when_updated_date_is_zero");
sut.updateDateWhenUpdatedDateIsZero(session, "ABCD", 1500000000002L);
IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext();
@Test
- public void define() throws Exception {
+ public void define() {
IndexDefinition def = new SourceLineIndexDefinition(new Settings());
def.define(context);
}
@Test
- public void enable_cluster() throws Exception {
+ public void enable_cluster() {
Settings settings = new Settings();
settings.setProperty(ProcessProperties.CLUSTER_ACTIVATE, true);
IndexDefinition def = new SourceLineIndexDefinition(settings);
}
@Test
- public void fail_to_get_line_when_line_is_not_greater_than_0() throws Exception {
+ public void fail_to_get_line_when_line_is_not_greater_than_0() {
try {
index.getLine("file1", 0);
} catch (Exception e) {
}
@Test
- public void fail_to_get_line_on_unknown_file() throws Exception {
+ public void fail_to_get_line_on_unknown_file() {
try {
index.getLine("file1", 1);
} catch (Exception e) {
}
@Test
- public void last_commit_null_when_not_found() throws Exception {
+ public void last_commit_null_when_not_found() {
Date date = index.lastCommitDateOnProject("fake-project-uuid");
assertThat(date).isNull();
}
@Test
- public void index_source_lines_with_big_test_data() throws Exception {
+ public void index_source_lines_with_big_test_data() {
Integer bigValue = Short.MAX_VALUE * 2;
FileSourceDb.Data.Builder dataBuilder = FileSourceDb.Data.newBuilder();
}
@Test
- public void filter_by_date() throws Exception {
+ public void filter_by_date() {
db.prepareDbUnit(getClass(), "shared.xml");
iterator = SourceLineResultSetIterator.create(dbClient, connection, 2000000000000L, null);
WsTester tester;
@Before
- public void before() throws Exception {
+ public void before() {
db.truncateTables();
this.session = db.myBatis().openSession(false);
}
@Test
- public void fail_to_show_hashes_if_file_does_not_exist() throws Exception {
+ public void fail_to_show_hashes_if_file_does_not_exist() {
MockUserSession.set().setLogin("polop").addProjectUuidPermissions(UserRole.USER, PROJECT_UUID);
try {
WsTester.TestRequest request = tester.newGetRequest("api/sources", "hash").setParam("key", COMPONENT_KEY);
ComponentDto file = ComponentTesting.newFileDto(project);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(dbClient.componentDao()).thenReturn(componentDao);
when(dbClient.openSession(false)).thenReturn(session);
tester = new WsTester(new SourcesWs(new IndexAction(dbClient, sourceService)));
WsTester wsTester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
esTester.truncateIndices();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
}
@Test
- public void fail_to_show_source_if_no_source_found() throws Exception {
+ public void fail_to_show_source_if_no_source_found() {
newFile();
MockUserSession.set().setLogin("login").addProjectUuidPermissions(UserRole.CODEVIEWER, PROJECT_UUID);
ComponentDto file = ComponentTesting.newFileDto(project);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(dbClient.componentDao()).thenReturn(componentDao);
when(dbClient.openSession(false)).thenReturn(session);
tester = new WsTester(new SourcesWs(new RawAction(dbClient, sourceService)));
DbSession session;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
esTester.truncateIndices();
dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), new ComponentDao());
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
ComponentDto file = ComponentTesting.newFileDto(project);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(dbClient.componentDao()).thenReturn(componentDao);
when(dbClient.openSession(false)).thenReturn(session);
tester = new WsTester(new SourcesWs(new ShowAction(sourceService, dbClient)));
WsTester tester = new WsTester(new SourcesWs(showAction, rawAction, linesAction, hashAction, indexAction));
@Test
- public void define_ws() throws Exception {
+ public void define_ws() {
WebService.Controller controller = tester.controller("api/sources");
assertThat(controller).isNotNull();
assertThat(controller.since()).isEqualTo("4.2");
CopyRequirementsFromCharacteristicsToRules service;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(system2.now()).thenReturn(DateUtils.parseDate("2014-03-13").getTime());
dbClient = new DbClient(db.database(), db.myBatis(), new RuleDao(system2), new LoadedTemplateDao(db.myBatis()));
service = new CopyRequirementsFromCharacteristicsToRules(dbClient, null);
}
@Test
- public void copy_requirements_from_characteristics_to_rules() throws Exception {
+ public void copy_requirements_from_characteristics_to_rules() {
db.prepareDbUnit(getClass(), "copy_requirements_from_characteristics_to_rules.xml");
service.start();
* SONAR-5335
*/
@Test
- public void convert_constant_issue_with_coeff_to_constant_issue_with_offset() throws Exception {
+ public void convert_constant_issue_with_coeff_to_constant_issue_with_offset() {
db.prepareDbUnit(getClass(), "convert_constant_issue_with_coeff_to_constant_issue_with_offset.xml");
service.start();
}
@Test
- public void remove_requirements_data_from_characteristics() throws Exception {
+ public void remove_requirements_data_from_characteristics() {
db.prepareDbUnit(getClass(), "remove_requirements_data_from_characteristics.xml");
service.start();
}
@Test
- public void do_nothing_when_already_executed() throws Exception {
+ public void do_nothing_when_already_executed() {
db.prepareDbUnit(getClass(), "do_nothing_when_already_executed.xml");
service.start();
}
@Test
- public void convert_duration() throws Exception {
+ public void convert_duration() {
assertThat(CopyRequirementsFromCharacteristicsToRules.convertDuration(1.0, "h")).isEqualTo("1h");
assertThat(CopyRequirementsFromCharacteristicsToRules.convertDuration(15.0, "d")).isEqualTo("15d");
assertThat(CopyRequirementsFromCharacteristicsToRules.convertDuration(5.0, "min")).isEqualTo("5min");
}
@Test
- public void is_debt_default_values_same_as_overridden_values() throws Exception {
+ public void is_debt_default_values_same_as_overridden_values() {
assertThat(CopyRequirementsFromCharacteristicsToRules.isDebtDefaultValuesSameAsOverriddenValues(new RuleDto()
.setDefaultSubCharacteristicId(1).setSubCharacteristicId(1)
.setDefaultRemediationFunction("LINEAR_OFFSET").setRemediationFunction("LINEAR_OFFSET")
}
@Test
- public void dont_fail_when_medium_test() throws Exception {
+ public void dont_fail_when_medium_test() {
Settings settings = new Settings();
DefaultServerFileSystem fs = mock(DefaultServerFileSystem.class);
RegisterDebtModel registerDebtModel;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
registerDebtModel = new RegisterDebtModel(dao, debtModelBackup);
}
@Test
- public void create_debt_model() throws Exception {
+ public void create_debt_model() {
when(dao.selectEnabledCharacteristics()).thenReturn(Collections.<CharacteristicDto>emptyList());
registerDebtModel.start();
}
@Test
- public void not_create_debt_model_if_already_exists() throws Exception {
+ public void not_create_debt_model_if_already_exists() {
when(dao.selectEnabledCharacteristics()).thenReturn(newArrayList(new CharacteristicDto()));
registerDebtModel.start();
}
@Test
- public void should_insert_and_register_default_permission_template() throws Exception {
+ public void should_insert_and_register_default_permission_template() {
LoadedTemplateDto expectedTemplate = new LoadedTemplateDto().setKey(PermissionTemplateDto.DEFAULT.getKee())
.setType(LoadedTemplateDto.PERMISSION_TEMPLATE_TYPE);
PermissionTemplateDto permissionTemplate = PermissionTemplateDto.DEFAULT.setId(1L);
}
@Test
- public void should_skip_insertion_and_registration() throws Exception {
+ public void should_skip_insertion_and_registration() {
when(loadedTemplateDao.countByTypeAndKey(LoadedTemplateDto.PERMISSION_TEMPLATE_TYPE, PermissionTemplateDto.DEFAULT.getKee()))
.thenReturn(1);
}
@Test
- public void should_reference_TRK_template_as_default_when_present() throws Exception {
+ public void should_reference_TRK_template_as_default_when_present() {
when(settings.getString(RegisterPermissionTemplates.DEFAULT_PROJECTS_TEMPLATE_PROPERTY)).thenReturn("my_projects_template");
LoadedTemplateDto expectedTemplate = new LoadedTemplateDto().setKey(PermissionTemplateDto.DEFAULT.getKee())
public DbTester dbTester = new DbTester();
@Test
- public void should_rename_widgets() throws Exception {
+ public void should_rename_widgets() {
dbTester.prepareDbUnit(this.getClass(), "before.xml");
doStart();
}
@Test
- public void should_skip_when_already_executed() throws Exception {
+ public void should_skip_when_already_executed() {
dbTester.prepareDbUnit(this.getClass(), "after.xml");
doStart();
CoverageService service;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
MyBatis myBatis = mock(MyBatis.class);
when(myBatis.openSession(false)).thenReturn(session);
service = new CoverageService(myBatis, measureDao, snapshotPerspectives);
}
@Test
- public void check_permission() throws Exception {
+ public void check_permission() {
String projectKey = "org.sonar.sample";
MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, projectKey, COMPONENT_KEY);
}
@Test
- public void get_hits_data() throws Exception {
+ public void get_hits_data() {
service.getHits(COMPONENT_KEY, CoverageService.TYPE.UT);
verify(measureDao).findByComponentKeyAndMetricKey(session, COMPONENT_KEY, CoreMetrics.COVERAGE_LINE_HITS_DATA_KEY);
}
@Test
- public void not_get_hits_data_if_no_data() throws Exception {
+ public void not_get_hits_data_if_no_data() {
when(measureDao.findByComponentKeyAndMetricKey(eq(session), anyString(), anyString())).thenReturn(null);
assertThat(service.getHits(COMPONENT_KEY, CoverageService.TYPE.UT)).isEqualTo(Collections.emptyMap());
}
@Test
- public void get_conditions_data() throws Exception {
+ public void get_conditions_data() {
service.getConditions(COMPONENT_KEY, CoverageService.TYPE.UT);
verify(measureDao).findByComponentKeyAndMetricKey(session, COMPONENT_KEY, CoreMetrics.CONDITIONS_BY_LINE_KEY);
}
@Test
- public void get_covered_conditions_data() throws Exception {
+ public void get_covered_conditions_data() {
service.getCoveredConditions(COMPONENT_KEY, CoverageService.TYPE.UT);
verify(measureDao).findByComponentKeyAndMetricKey(session, COMPONENT_KEY, CoreMetrics.COVERED_CONDITIONS_BY_LINE_KEY);
}
@Test
- public void get_test_cases_by_lines() throws Exception {
+ public void get_test_cases_by_lines() {
MutableTestable testable = mock(MutableTestable.class);
when(snapshotPerspectives.as(MutableTestable.class, COMPONENT_KEY)).thenReturn(testable);
}
@Test
- public void not_get_test_cases_by_lines_if_no_testable() throws Exception {
+ public void not_get_test_cases_by_lines_if_no_testable() {
when(snapshotPerspectives.as(MutableTestable.class, COMPONENT_KEY)).thenReturn(null);
assertThat(service.getTestCases(COMPONENT_KEY, CoverageService.TYPE.UT)).isEqualTo(Collections.emptyMap());
TestIndex sut = new TestIndex(es.client());
@Before
- public void setup() throws Exception {
+ public void setup() {
es.truncateIndices();
}
}
@Test
- public void filter_by_date() throws Exception {
+ public void filter_by_date() {
db.prepareDbUnit(getClass(), "shared.xml");
sut = TestResultSetIterator.create(dbClient, connection, 2000000000000L, null);
}
}
- private static List<FileSourceDb.Test> newFakeTests(int numberOfTests) throws IOException {
+ private static List<FileSourceDb.Test> newFakeTests(int numberOfTests) {
List<FileSourceDb.Test> tests = new ArrayList<>();
for (int i = 1; i <= numberOfTests; i++) {
FileSourceDb.Test.Builder test = FileSourceDb.Test.newBuilder()
private TestIndex testIndex;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbClient = mock(DbClient.class, RETURNS_DEEP_STUBS);
testIndex = mock(TestIndex.class, RETURNS_DEEP_STUBS);
ws = new WsTester(new TestsWs(new TestsCoveredFilesAction(dbClient, testIndex)));
public static EsTester es = new EsTester().addDefinitions(new TestIndexDefinition(new Settings()));
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbClient = new DbClient(db.database(), db.myBatis(), new ComponentDao());
dbSession = dbClient.openSession(false);
db.truncateTables();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
dbSession.close();
}
WebService.Controller controller;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
WsTester tester = new WsTester(new TestsWs(
new TestsListAction(mock(DbClient.class), mock(TestIndex.class)),
new TestsCoveredFilesAction(mock(DbClient.class), mock(TestIndex.class))));
}
@Test
- public void define_controller() throws Exception {
+ public void define_controller() {
assertThat(controller).isNotNull();
assertThat(controller.since()).isEqualTo("4.4");
assertThat(controller.description()).isNotEmpty();
}
@Test
- public void define_list_action() throws Exception {
+ public void define_list_action() {
WebService.Action action = controller.action("list");
assertThat(action).isNotNull();
assertThat(action.isInternal()).isFalse();
}
@Test
- public void define_covered_files() throws Exception {
+ public void define_covered_files() {
WebService.Action action = controller.action("covered_files");
assertThat(action).isNotNull();
assertThat(action.isInternal()).isFalse();
RubyTextService text = new RubyTextService(macroInterpreter);
@Test
- public void interpretMacros() throws Exception {
+ public void interpretMacros() {
text.interpretMacros("text with macros");
verify(macroInterpreter, times(1)).interpret("text with macros");
}
@Test
- public void markdownToHtml() throws Exception {
+ public void markdownToHtml() {
String html = text.markdownToHtml("some *markdown*");
assertThat(html).isEqualTo("some <em>markdown</em>");
}
@Test
- public void should_escape_markdown_input() throws Exception {
+ public void should_escape_markdown_input() {
String html = text.markdownToHtml("a > b");
assertThat(html).isEqualTo("a > b");
}
@Before
- public void setUp() throws Exception {
+ public void setUp() {
jRubyI18n = new JRubyI18n(i18n, durations);
}
}
@Test
- public void default_locale_should_be_english() throws Exception {
+ public void default_locale_should_be_english() {
assertThat(JRubyI18n.toLocale(null)).isEqualTo(Locale.ENGLISH);
}
@Test
- public void message() throws Exception {
+ public void message() {
jRubyI18n.message("en", "my.key", "default");
verify(i18n).message(any(Locale.class), eq("my.key"), eq("default"));
}
@Test
- public void age_from_now() throws Exception {
+ public void age_from_now() {
Date date = new Date();
jRubyI18n.ageFromNow(date);
verify(i18n).ageFromNow(any(Locale.class), eq(date));
}
@Test
- public void format_work_duration() throws Exception {
+ public void format_work_duration() {
jRubyI18n.formatDuration(Duration.create(10L), "SHORT");
verify(durations).format(any(Locale.class), eq(Duration.create(10L)), eq(Durations.DurationFormat.SHORT));
}
@Test
- public void format_long_work_duration() throws Exception {
+ public void format_long_work_duration() {
jRubyI18n.formatLongDuration(10L, "SHORT");
verify(durations).format(any(Locale.class), eq(Duration.create(10L)), eq(Durations.DurationFormat.SHORT));
}
@Test
- public void format_date_time() throws Exception {
+ public void format_date_time() {
Date date = new Date();
jRubyI18n.formatDateTime(date);
verify(i18n).formatDateTime(any(Locale.class), eq(date));
}
@Test
- public void shouldAcceptAvailableMeasuresForNoRequiredMeasures() throws Exception {
+ public void shouldAcceptAvailableMeasuresForNoRequiredMeasures() {
class MyView extends FakeView {
MyView() {
super("fake");
}
@Test
- public void shouldAcceptAvailableMeasuresForMandatoryMeasures() throws Exception {
+ public void shouldAcceptAvailableMeasuresForMandatoryMeasures() {
@RequiredMeasures(allOf = {"lines", "ncloc"})
class MyView extends FakeView {
MyView() {
}
@Test
- public void shouldAcceptAvailableMeasuresForOneOfNeededMeasures() throws Exception {
+ public void shouldAcceptAvailableMeasuresForOneOfNeededMeasures() {
@RequiredMeasures(anyOf = {"lines", "ncloc"})
class MyView extends FakeView {
MyView() {
}
@Test
- public void shouldAcceptAvailableMeasuresForMandatoryAndOneOfNeededMeasures() throws Exception {
+ public void shouldAcceptAvailableMeasuresForMandatoryAndOneOfNeededMeasures() {
@RequiredMeasures(allOf = {"lines", "ncloc"}, anyOf = {"duplications", "duplictated_blocks"})
class MyView extends FakeView {
MyView() {
private ResourceTypes resourceTypes;
@Before
- public void before() throws Exception {
+ public void before() {
dbTester.truncateTables();
System2 system = mock(System2.class);
}
@After
- public void after() throws Exception {
+ public void after() {
session.close();
}
private ActiveDashboardDao activeDashboardDao;
@Before
- public void before() throws Exception {
+ public void before() {
dbTester.truncateTables();
userDao = new UserDao(dbTester.myBatis(), mock(System2.class));
}
@After
- public void after() throws Exception {
+ public void after() {
session.close();
}
private I18n i18n;
@Before
- public void before() throws Exception {
+ public void before() {
settings = new Settings();
i18n = mock(I18n.class);
when(i18n.message(any(Locale.class), anyString(), anyString())).thenAnswer(new Answer<String>() {
WsTester tester;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester = new WsTester(new UpdateCenterWs());
}
@Test
- public void define_controller() throws Exception {
+ public void define_controller() {
WebService.Controller controller = tester.controller("api/updatecenter");
assertThat(controller).isNotNull();
assertThat(controller.since()).isEqualTo("2.10");
}
@Test
- public void define_installed_plugins_action() throws Exception {
+ public void define_installed_plugins_action() {
WebService.Controller controller = tester.controller("api/updatecenter");
WebService.Action action = controller.action("installed_plugins");
public ExpectedException thrown = ExpectedException.none();
@Test
- public void parse_query() throws Exception {
+ public void parse_query() {
service.find(ImmutableMap.<String, Object>of(
"logins", "simon,loic",
"includeDeactivated", "true",
}
@Test
- public void self_deactivation_is_not_possible() throws Exception {
+ public void self_deactivation_is_not_possible() {
try {
MockUserSession.set().setLogin("simon").setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
service.deactivate("simon");
}
@Test
- public void user_deactivation_requires_admin_permission() throws Exception {
+ public void user_deactivation_requires_admin_permission() {
try {
MockUserSession.set().setLogin("simon").setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN);
service.deactivate("julien");
}
@Test
- public void deactivate_user() throws Exception {
+ public void deactivate_user() {
MockUserSession.set().setLogin("simon").setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
service.deactivate("julien");
verify(userUpdater).deactivateUserByLogin("julien");
}
@Test
- public void fail_to_deactivate_when_blank_login() throws Exception {
+ public void fail_to_deactivate_when_blank_login() {
MockUserSession.set().setLogin("simon").setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
try {
service.deactivate("");
}
@Test
- public void create() throws Exception {
+ public void create() {
Map<String, Object> params = newHashMap();
params.put("login", "john");
params.put("name", "John");
}
@Test
- public void update() throws Exception {
+ public void update() {
Map<String, Object> params = newHashMap();
params.put("login", "john");
params.put("name", "John");
}
@Test
- public void update_only_name() throws Exception {
+ public void update_only_name() {
Map<String, Object> params = newHashMap();
params.put("login", "john");
params.put("name", "John");
}
@Test
- public void update_only_email() throws Exception {
+ public void update_only_email() {
Map<String, Object> params = newHashMap();
params.put("login", "john");
params.put("email", "john@email.com");
}
@Test
- public void update_only_scm_accounts() throws Exception {
+ public void update_only_scm_accounts() {
Map<String, Object> params = newHashMap();
params.put("login", "john");
params.put("scm_accounts", newArrayList("jn"));
}
@Test
- public void update_only_password() throws Exception {
+ public void update_only_password() {
Map<String, Object> params = newHashMap();
params.put("login", "john");
params.put("password", "1234");
}
@Test
- public void get_by_login() throws Exception {
+ public void get_by_login() {
service.getByLogin("john");
verify(userIndex).getNullableByLogin("john");
}
@Test
- public void index() throws Exception {
+ public void index() {
service.index();
verify(userUpdater).index();
}
GroupMembershipFinder finder;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
when(userDao.selectActiveUserByLogin("arthur")).thenReturn(new UserDto().setId(100L).setName("arthur"));
finder = new GroupMembershipFinder(userDao, groupMembershipDao);
}
@Test
- public void find() throws Exception {
+ public void find() {
GroupMembershipQuery query = GroupMembershipQuery.builder().login("arthur").build();
when(groupMembershipDao.selectGroups(eq(query), anyLong(), anyInt(), anyInt())).thenReturn(
newArrayList(new GroupMembershipDto().setId(1L).setName("users").setDescription("Users group").setUserId(100L))
}
@Test
- public void find_with_paging() throws Exception {
+ public void find_with_paging() {
GroupMembershipQuery query = GroupMembershipQuery.builder().login("arthur").pageIndex(3).pageSize(10).build();
finder.find(query);
}
@Test
- public void find_with_paging_having_more_results() throws Exception {
+ public void find_with_paging_having_more_results() {
GroupMembershipQuery query = GroupMembershipQuery.builder().login("arthur").pageIndex(1).pageSize(2).build();
when(groupMembershipDao.selectGroups(eq(query), anyLong(), anyInt(), anyInt())).thenReturn(newArrayList(
new GroupMembershipDto().setId(1L).setName("group1"),
}
@Test
- public void find_with_paging_having_no_more_results() throws Exception {
+ public void find_with_paging_having_no_more_results() {
GroupMembershipQuery query = GroupMembershipQuery.builder().login("arthur").pageIndex(1).pageSize(10).build();
when(groupMembershipDao.selectGroups(eq(query), anyLong(), anyInt(), anyInt())).thenReturn(newArrayList(
new GroupMembershipDto().setId(1L).setName("group1"),
GroupMembershipService service;
@Before
- public void before() throws Exception {
+ public void before() {
GroupMembershipDao membershipDao = new GroupMembershipDao(getMyBatis());
UserDao userDao = new UserDao(getMyBatis(), System2.INSTANCE);
GroupMembershipFinder finder = new GroupMembershipFinder(userDao, membershipDao);
public class RubyUserSessionTest {
@Test
- public void should_set_session() throws Exception {
+ public void should_set_session() {
RubyUserSession.setSession(123, "karadoc", "Karadoc", newArrayList("sonar-users"), "fr");
UserSession session = UserSession.get();
}
@Test
- public void should_set_anonymous_session() throws Exception {
+ public void should_set_anonymous_session() {
RubyUserSession.setSession(null, null, null, null, "fr");
UserSession session = UserSession.get();
public ExpectedException thrown = ExpectedException.none();
@Test
- public void getSession_get_anonymous_by_default() throws Exception {
+ public void getSession_get_anonymous_by_default() {
UserSession.remove();
UserSession session = UserSession.get();
}
@Test
- public void get_session() throws Exception {
+ public void get_session() {
UserSession.set(new UserSession().setUserId(123).setLogin("karadoc").setLocale(Locale.FRENCH));
UserSession session = UserSession.get();
}
@Test
- public void login_should_not_be_empty() throws Exception {
+ public void login_should_not_be_empty() {
UserSession session = new UserSession().setLogin("");
assertThat(session.login()).isNull();
assertThat(session.isLoggedIn()).isFalse();
}
@Test
- public void has_global_permission() throws Exception {
+ public void has_global_permission() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao);
}
@Test
- public void check_global_Permission_ok() throws Exception {
+ public void check_global_Permission_ok() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao);
}
@Test(expected = ForbiddenException.class)
- public void check_global_Permission_ko() throws Exception {
+ public void check_global_Permission_ko() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao);
}
@Test
- public void has_project_permission() throws Exception {
+ public void has_project_permission() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao).setUserId(1);
when(authorizationDao.selectAuthorizedRootProjectsKeys(1, UserRole.USER)).thenReturn(newArrayList("com.foo:Bar"));
}
@Test
- public void has_project_permission_by_uuid() throws Exception {
+ public void has_project_permission_by_uuid() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao).setUserId(1);
when(authorizationDao.selectAuthorizedRootProjectsUuids(1, UserRole.USER)).thenReturn(newArrayList("ABCD"));
}
@Test
- public void check_project_permission_ok() throws Exception {
+ public void check_project_permission_ok() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao).setUserId(1);
when(authorizationDao.selectAuthorizedRootProjectsKeys(1, UserRole.USER)).thenReturn(newArrayList("com.foo:Bar"));
}
@Test(expected = ForbiddenException.class)
- public void check_project_permission_ko() throws Exception {
+ public void check_project_permission_ko() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao).setUserId(1);
when(authorizationDao.selectAuthorizedRootProjectsKeys(1, UserRole.USER)).thenReturn(newArrayList("com.foo:Bar2"));
}
@Test
- public void check_project_uuid_permission_ok() throws Exception {
+ public void check_project_uuid_permission_ok() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao).setUserId(1);
}
@Test(expected = ForbiddenException.class)
- public void check_project_uuid_permission_ko() throws Exception {
+ public void check_project_uuid_permission_ko() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao).setUserId(1);
}
@Test
- public void has_component_permission() throws Exception {
+ public void has_component_permission() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
ResourceDao resourceDao = mock(ResourceDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao, resourceDao).setUserId(1);
}
@Test
- public void check_component_key_permission_ok() throws Exception {
+ public void check_component_key_permission_ok() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
ResourceDao resourceDao = mock(ResourceDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao, resourceDao).setUserId(1);
}
@Test(expected = ForbiddenException.class)
- public void check_component_key_permission_ko() throws Exception {
+ public void check_component_key_permission_ko() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
ResourceDao resourceDao = mock(ResourceDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao, resourceDao).setUserId(1);
}
@Test
- public void check_component_uuid_permission_ok() throws Exception {
+ public void check_component_uuid_permission_ok() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
ResourceDao resourceDao = mock(ResourceDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao,resourceDao).setUserId(1);
}
@Test(expected = ForbiddenException.class)
- public void check_component_uuid_permission_ko() throws Exception {
+ public void check_component_uuid_permission_ko() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
ResourceDao resourceDao = mock(ResourceDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao,resourceDao).setUserId(1);
}
@Test(expected = ForbiddenException.class)
- public void check_component_key_permission_when_project_not_found() throws Exception {
+ public void check_component_key_permission_when_project_not_found() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
ResourceDao resourceDao = mock(ResourceDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao, resourceDao).setUserId(1);
}
@Test(expected = ForbiddenException.class)
- public void check_component_dto_permission_ko() throws Exception {
+ public void check_component_dto_permission_ko() {
AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
ResourceDao resourceDao = mock(ResourceDao.class);
UserSession session = new SpyUserSession("marius", authorizationDao, resourceDao).setUserId(1);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
db.truncateTables();
es.truncateIndices();
settings = new Settings();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void create_user() throws Exception {
+ public void create_user() {
when(system2.now()).thenReturn(1418215735482L);
createDefaultGroup();
}
@Test
- public void create_user_with_minimum_fields() throws Exception {
+ public void create_user_with_minimum_fields() {
when(system2.now()).thenReturn(1418215735482L);
createDefaultGroup();
}
@Test
- public void create_user_with_scm_accounts_containing_blank_or_null_entries() throws Exception {
+ public void create_user_with_scm_accounts_containing_blank_or_null_entries() {
when(system2.now()).thenReturn(1418215735482L);
createDefaultGroup();
}
@Test
- public void create_user_with_scm_accounts_containing_one_blank_entry() throws Exception {
+ public void create_user_with_scm_accounts_containing_one_blank_entry() {
when(system2.now()).thenReturn(1418215735482L);
createDefaultGroup();
}
@Test
- public void create_user_with_scm_accounts_containing_duplications() throws Exception {
+ public void create_user_with_scm_accounts_containing_duplications() {
when(system2.now()).thenReturn(1418215735482L);
createDefaultGroup();
}
@Test
- public void fail_to_create_user_with_missing_login() throws Exception {
+ public void fail_to_create_user_with_missing_login() {
try {
userUpdater.create(NewUser.create()
.setLogin(null)
}
@Test
- public void fail_to_create_user_with_invalid_login() throws Exception {
+ public void fail_to_create_user_with_invalid_login() {
try {
userUpdater.create(NewUser.create()
.setLogin("/marius/")
}
@Test
- public void fail_to_create_user_with_too_short_login() throws Exception {
+ public void fail_to_create_user_with_too_short_login() {
try {
userUpdater.create(NewUser.create()
.setLogin("ma")
}
@Test
- public void fail_to_create_user_with_too_long_login() throws Exception {
+ public void fail_to_create_user_with_too_long_login() {
try {
userUpdater.create(NewUser.create()
.setLogin(Strings.repeat("m", 256))
}
@Test
- public void fail_to_create_user_with_missing_name() throws Exception {
+ public void fail_to_create_user_with_missing_name() {
try {
userUpdater.create(NewUser.create()
.setLogin("marius")
}
@Test
- public void fail_to_create_user_with_too_long_name() throws Exception {
+ public void fail_to_create_user_with_too_long_name() {
try {
userUpdater.create(NewUser.create()
.setLogin("marius")
}
@Test
- public void fail_to_create_user_with_too_long_email() throws Exception {
+ public void fail_to_create_user_with_too_long_email() {
try {
userUpdater.create(NewUser.create()
.setLogin("marius")
}
@Test
- public void fail_to_create_user_with_missing_password() throws Exception {
+ public void fail_to_create_user_with_missing_password() {
try {
userUpdater.create(NewUser.create()
.setLogin("marius")
}
@Test
- public void fail_to_create_user_with_missing_password_confirmation() throws Exception {
+ public void fail_to_create_user_with_missing_password_confirmation() {
try {
userUpdater.create(NewUser.create()
.setLogin("marius")
}
@Test
- public void fail_to_create_user_with_password_not_matching_password_confirmation() throws Exception {
+ public void fail_to_create_user_with_password_not_matching_password_confirmation() {
try {
userUpdater.create(NewUser.create()
.setLogin("marius")
}
@Test
- public void fail_to_create_user_with_many_errors() throws Exception {
+ public void fail_to_create_user_with_many_errors() {
try {
userUpdater.create(NewUser.create()
.setLogin("")
}
@Test
- public void fail_to_create_user_when_scm_account_is_already_used() throws Exception {
+ public void fail_to_create_user_when_scm_account_is_already_used() {
db.prepareDbUnit(getClass(), "fail_to_create_user_when_scm_account_is_already_used.xml");
try {
}
@Test
- public void fail_to_create_user_when_scm_account_is_already_used_by_many_user() throws Exception {
+ public void fail_to_create_user_when_scm_account_is_already_used_by_many_user() {
db.prepareDbUnit(getClass(), "fail_to_create_user_when_scm_account_is_already_used_by_many_user.xml");
try {
}
@Test
- public void fail_to_create_user_when_scm_account_is_user_login() throws Exception {
+ public void fail_to_create_user_when_scm_account_is_user_login() {
try {
userUpdater.create(NewUser.create()
.setLogin("marius")
}
@Test
- public void fail_to_create_user_when_scm_account_is_user_email() throws Exception {
+ public void fail_to_create_user_when_scm_account_is_user_email() {
try {
userUpdater.create(NewUser.create()
.setLogin("marius")
}
@Test
- public void notify_new_user() throws Exception {
+ public void notify_new_user() {
createDefaultGroup();
userUpdater.create(NewUser.create()
}
@Test
- public void associate_default_group_when_creating_user() throws Exception {
+ public void associate_default_group_when_creating_user() {
createDefaultGroup();
userUpdater.create(NewUser.create()
}
@Test
- public void fail_to_associate_default_group_to_user_if_no_default_group() throws Exception {
+ public void fail_to_associate_default_group_to_user_if_no_default_group() {
settings.setProperty(CoreProperties.CORE_DEFAULT_GROUP, (String) null);
try {
}
@Test
- public void reactivate_user_when_creating_user_with_existing_login() throws Exception {
+ public void reactivate_user_when_creating_user_with_existing_login() {
db.prepareDbUnit(getClass(), "reactivate_user.xml");
when(system2.now()).thenReturn(1418215735486L);
createDefaultGroup();
}
@Test
- public void fail_to_reactivate_user_if_not_disabled() throws Exception {
+ public void fail_to_reactivate_user_if_not_disabled() {
db.prepareDbUnit(getClass(), "fail_to_reactivate_user_if_not_disabled.xml");
createDefaultGroup();
}
@Test
- public void associate_default_groups_when_reactivating_user() throws Exception {
+ public void associate_default_groups_when_reactivating_user() {
db.prepareDbUnit(getClass(), "associate_default_groups_when_reactivating_user.xml");
createDefaultGroup();
}
@Test
- public void update_user() throws Exception {
+ public void update_user() {
db.prepareDbUnit(getClass(), "update_user.xml");
when(system2.now()).thenReturn(1418215735486L);
createDefaultGroup();
}
@Test
- public void update_user_with_scm_accounts_containing_blank_entry() throws Exception {
+ public void update_user_with_scm_accounts_containing_blank_entry() {
db.prepareDbUnit(getClass(), "update_user.xml");
createDefaultGroup();
}
@Test
- public void update_only_user_name() throws Exception {
+ public void update_only_user_name() {
db.prepareDbUnit(getClass(), "update_user.xml");
createDefaultGroup();
}
@Test
- public void update_only_user_email() throws Exception {
+ public void update_only_user_email() {
db.prepareDbUnit(getClass(), "update_user.xml");
createDefaultGroup();
}
@Test
- public void update_only_scm_accounts() throws Exception {
+ public void update_only_scm_accounts() {
db.prepareDbUnit(getClass(), "update_user.xml");
createDefaultGroup();
}
@Test
- public void update_scm_accounts_with_same_values() throws Exception {
+ public void update_scm_accounts_with_same_values() {
db.prepareDbUnit(getClass(), "update_user.xml");
createDefaultGroup();
}
@Test
- public void remove_scm_accounts() throws Exception {
+ public void remove_scm_accounts() {
db.prepareDbUnit(getClass(), "update_user.xml");
createDefaultGroup();
}
@Test
- public void update_only_user_password() throws Exception {
+ public void update_only_user_password() {
db.prepareDbUnit(getClass(), "update_user.xml");
createDefaultGroup();
}
@Test
- public void associate_default_group_when_updating_user() throws Exception {
+ public void associate_default_group_when_updating_user() {
db.prepareDbUnit(getClass(), "associate_default_groups_when_updating_user.xml");
createDefaultGroup();
}
@Test
- public void not_associate_default_group_when_updating_user_if_already_existing() throws Exception {
+ public void not_associate_default_group_when_updating_user_if_already_existing() {
db.prepareDbUnit(getClass(), "not_associate_default_group_when_updating_user_if_already_existing.xml");
settings.setProperty(CoreProperties.CORE_DEFAULT_GROUP, "sonar-users");
session.commit();
}
@Test
- public void fail_to_update_user_when_scm_account_is_already_used() throws Exception {
+ public void fail_to_update_user_when_scm_account_is_already_used() {
db.prepareDbUnit(getClass(), "fail_to_update_user_when_scm_account_is_already_used.xml");
createDefaultGroup();
}
@Test
- public void fail_to_update_user_when_scm_account_is_user_login() throws Exception {
+ public void fail_to_update_user_when_scm_account_is_user_login() {
db.prepareDbUnit(getClass(), "update_user.xml");
createDefaultGroup();
}
@Test
- public void fail_to_update_user_when_scm_account_is_existing_user_email() throws Exception {
+ public void fail_to_update_user_when_scm_account_is_existing_user_email() {
db.prepareDbUnit(getClass(), "update_user.xml");
createDefaultGroup();
}
@Test
- public void fail_to_update_user_when_scm_account_is_new_user_email() throws Exception {
+ public void fail_to_update_user_when_scm_account_is_new_user_email() {
db.prepareDbUnit(getClass(), "update_user.xml");
createDefaultGroup();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
}
@Test
- public void find_by_user_login() throws Exception {
+ public void find_by_user_login() {
setupData("find_by_user_login");
assertThat(dao.findByUserLogin(session, "john")).hasSize(2);
}
@Test
- public void insert() throws Exception {
+ public void insert() {
when(system2.now()).thenReturn(DateUtils.parseDate("2014-09-08").getTime());
setupData("empty");
private DbSession session;
@Before
- public void before() throws Exception {
+ public void before() {
db.truncateTables();
this.session = db.myBatis().openSession(false);
private DbSession session;
@Before
- public void before() throws Exception {
+ public void before() {
db.truncateTables();
this.session = db.myBatis().openSession(false);
this.dao = new UserGroupDao();
IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext();
@Test
- public void define() throws Exception {
+ public void define() {
UserIndexDefinition def = new UserIndexDefinition(new Settings());
def.define(context);
}
@Test
- public void enable_cluster() throws Exception {
+ public void enable_cluster() {
Settings settings = new Settings();
settings.setProperty(ProcessProperties.CLUSTER_ACTIVATE, true);
UserIndexDefinition def = new UserIndexDefinition(settings);
}
@Test
- public void fail_to_get_by_login_on_unknown_user() throws Exception {
+ public void fail_to_get_by_login_on_unknown_user() {
try {
index.getByLogin("unknown");
fail();
public static EsTester esTester = new EsTester().addDefinitions(new UserIndexDefinition(new Settings()));
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
esTester.truncateIndices();
}
@Test
- public void index_nothing() throws Exception {
+ public void index_nothing() {
UserIndexer indexer = createIndexer();
indexer.index();
assertThat(esTester.countDocuments(UserIndexDefinition.INDEX, UserIndexDefinition.TYPE_USER)).isEqualTo(0L);
}
@Test
- public void index() throws Exception {
+ public void index() {
dbTester.prepareDbUnit(getClass(), "index.xml");
UserIndexer indexer = createIndexer();
}
@Test
- public void do_nothing_if_disabled() throws Exception {
+ public void do_nothing_if_disabled() {
dbTester.prepareDbUnit(getClass(), "index.xml");
createIndexer().setEnabled(false).index();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
DbUtils.closeQuietly(connection);
}
@Test
- public void iterator_over_users() throws Exception {
+ public void iterator_over_users() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
UserResultSetIterator it = UserResultSetIterator.create(client, connection, 0L);
Map<String, UserDoc> usersByLogin = Maps.uniqueIndex(it, new Function<UserDoc, String>() {
}
@Test
- public void select_after_date() throws Exception {
+ public void select_after_date() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
UserResultSetIterator it = UserResultSetIterator.create(client, connection, 1520000000000L);
DbSession session;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
esTester.truncateIndices();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
I18n i18n;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
esTester.truncateIndices();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
I18n i18n;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
esTester.truncateIndices();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
WsTester tester = new WsTester(new FavoritesWs());
@Test
- public void define_ws() throws Exception {
+ public void define_ws() {
WebService.Controller controller = tester.controller("api/favorites");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
DbSession session;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
System2 system2 = new System2();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
UserIndex index;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
esTester.truncateIndices();
index = new UserIndex(esTester.client());
DbSession session;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
esTester.truncateIndices();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
WsTester tester = new WsTester(new UserPropertiesWs());
@Test
- public void define_ws() throws Exception {
+ public void define_ws() {
WebService.Controller controller = tester.controller("api/user_properties");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
WebService.Controller controller;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
WsTester tester = new WsTester(new UsersWs(
new CreateAction(mock(UserIndex.class), mock(UserUpdater.class), mock(I18n.class)),
new UpdateAction(mock(UserIndex.class), mock(UserUpdater.class)),
}
@Test
- public void define_controller() throws Exception {
+ public void define_controller() {
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
assertThat(controller.since()).isEqualTo("3.6");
}
@Test
- public void define_search_action() throws Exception {
+ public void define_search_action() {
WebService.Action action = controller.action("search");
assertThat(action).isNotNull();
assertThat(action.isPost()).isFalse();
}
@Test
- public void define_create_action() throws Exception {
+ public void define_create_action() {
WebService.Action action = controller.action("create");
assertThat(action).isNotNull();
assertThat(action.isPost()).isTrue();
}
@Test
- public void define_update_action() throws Exception {
+ public void define_update_action() {
WebService.Action action = controller.action("update");
assertThat(action).isNotNull();
assertThat(action.isPost()).isTrue();
}
@Test
- public void define_change_password_action() throws Exception {
+ public void define_change_password_action() {
WebService.Action action = controller.action("change_password");
assertThat(action).isNotNull();
assertThat(action.isPost()).isTrue();
}
@Test
- public void define_deactivate_action() throws Exception {
+ public void define_deactivate_action() {
WebService.Action action = controller.action("deactivate");
assertThat(action).isNotNull();
assertThat(action.isPost()).isTrue();
}
@Test
- public void define_current_action() throws Exception {
+ public void define_current_action() {
WebService.Action action = controller.action("current");
assertThat(action).isNotNull();
assertThat(action.isPost()).isFalse();
BooleanTypeValidation validation;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
validation = new BooleanTypeValidation();
}
public class CloseableIteratorTest {
@Test
- public void iterate() throws Exception {
+ public void iterate() {
SimpleCloseableIterator it = new SimpleCloseableIterator();
assertThat(it.isClosed).isFalse();
}
@Test
- public void call_next_without_hasNext() throws Exception {
+ public void call_next_without_hasNext() {
SimpleCloseableIterator it = new SimpleCloseableIterator();
assertThat(it.next()).isEqualTo(1);
assertThat(it.next()).isEqualTo(2);
}
@Test
- public void automatic_close_if_traversal_error() throws Exception {
+ public void automatic_close_if_traversal_error() {
FailureCloseableIterator it = new FailureCloseableIterator();
try {
it.next();
}
@Test
- public void remove_is_not_supported_by_default() throws Exception {
+ public void remove_is_not_supported_by_default() {
SimpleCloseableIterator it = new SimpleCloseableIterator();
try {
it.remove();
}
@Test
- public void remove_can_be_overridden() throws Exception {
+ public void remove_can_be_overridden() {
RemovableCloseableIterator it = new RemovableCloseableIterator();
it.remove();
assertThat(it.isRemoved).isTrue();
}
@Test
- public void has_next_should_not_call_do_next_when_already_closed() throws Exception {
+ public void has_next_should_not_call_do_next_when_already_closed() {
DoNextShouldNotBeCalledWhenClosedIterator it = new DoNextShouldNotBeCalledWhenClosedIterator();
it.next();
DateCollector collector = new DateCollector();
@Test
- public void max_is_zero_if_no_dates() throws Exception {
+ public void max_is_zero_if_no_dates() {
assertThat(collector.getMax()).isEqualTo(0L);
}
@Test
- public void max() throws Exception {
+ public void max() {
collector.add(DateUtils.parseDate("2013-06-01"));
collector.add(null);
collector.add(DateUtils.parseDate("2014-01-01"));
FloatTypeValidation validation;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
validation = new FloatTypeValidation();
}
IntegerTypeValidation validation;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
validation = new IntegerTypeValidation();
}
}
@Test
- public void create() throws Exception {
+ public void create() {
ProgressLogger progress = ProgressLogger.create(getClass(), new AtomicLong());
// default values
}
@Test
- public void toInteger() throws Exception {
+ public void toInteger() {
assertThat(RubyUtils.toInteger(null)).isNull();
assertThat(RubyUtils.toInteger("")).isNull();
assertThat(RubyUtils.toInteger(" ")).isNull();
}
@Test
- public void toInteger_unexpected_class() throws Exception {
+ public void toInteger_unexpected_class() {
throwable.expect(IllegalArgumentException.class);
RubyUtils.toInteger(1.2);
}
@Test
- public void toDouble() throws Exception {
+ public void toDouble() {
assertThat(RubyUtils.toDouble(null)).isNull();
assertThat(RubyUtils.toDouble("")).isNull();
assertThat(RubyUtils.toDouble(" ")).isNull();
}
@Test
- public void toDouble_unexpected_class() throws Exception {
+ public void toDouble_unexpected_class() {
throwable.expect(IllegalArgumentException.class);
RubyUtils.toDouble(true);
}
@Test
- public void toBoolean() throws Exception {
+ public void toBoolean() {
assertThat(RubyUtils.toBoolean(null)).isNull();
assertThat(RubyUtils.toBoolean("")).isNull();
assertThat(RubyUtils.toBoolean(" ")).isNull();
}
@Test
- public void toBoolean_unexpected_class() throws Exception {
+ public void toBoolean_unexpected_class() {
throwable.expect(IllegalArgumentException.class);
RubyUtils.toBoolean(333);
}
@Test
- public void toDate() throws Exception {
+ public void toDate() {
assertThat(RubyUtils.toDate(null)).isNull();
assertThat(RubyUtils.toDate("")).isNull();
assertThat(RubyUtils.toDate(" ")).isNull();
}
@Test
- public void toDate_bad_format() throws Exception {
+ public void toDate_bad_format() {
throwable.expect(SonarException.class);
RubyUtils.toDate("01/02/2013");
}
@Test
- public void toDate_unexpected_class() throws Exception {
+ public void toDate_unexpected_class() {
throwable.expect(IllegalArgumentException.class);
RubyUtils.toDate(333);
}
@Test
- public void toLong() throws Exception {
+ public void toLong() {
assertThat(RubyUtils.toLong(null)).isNull();
assertThat(RubyUtils.toLong(2)).isEqualTo(2L);
assertThat(RubyUtils.toLong(3L)).isEqualTo(3L);
}
@Test
- public void toLong_unexpected_class() throws Exception {
+ public void toLong_unexpected_class() {
throwable.expect(IllegalArgumentException.class);
RubyUtils.toLong(false);
public class SlugTest {
@Test
- public void slugify() throws Exception {
+ public void slugify() {
assertThat(Slug.slugify("foo")).isEqualTo("foo");
assertThat(Slug.slugify(" FOO ")).isEqualTo("foo");
assertThat(Slug.slugify("he's here")).isEqualTo("he-s-here");
StringListTypeValidation validation;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
validation = new StringListTypeValidation();
}
StringTypeValidation validation;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
validation = new StringTypeValidation();
}
TextTypeValidation validation;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
validation = new TextTypeValidation();
}
public class TypeValidationsTest {
@Test
- public void validate() throws Exception {
+ public void validate() {
TypeValidation fakeTypeValidation = mock(TypeValidation.class);
when(fakeTypeValidation.key()).thenReturn("Fake");
}
@Test
- public void validate__multiple_values() throws Exception {
+ public void validate__multiple_values() {
TypeValidation fakeTypeValidation = mock(TypeValidation.class);
when(fakeTypeValidation.key()).thenReturn("Fake");
}
@Test
- public void fail_on_unknown_type() throws Exception {
+ public void fail_on_unknown_type() {
TypeValidation fakeTypeValidation = mock(TypeValidation.class);
when(fakeTypeValidation.key()).thenReturn("Fake");
@Test
public void fail_to_serialize() throws Exception {
class Unserializable implements Serializable {
- private void writeObject(ObjectOutputStream out) throws IOException {
+ private void writeObject(ObjectOutputStream out) {
throw new UnsupportedOperationException("expected error");
}
}
MemoryCache<String, String> cache = new MemoryCache<>(loader);
@Test
- public void getNullable() throws Exception {
+ public void getNullable() {
when(loader.load("foo")).thenReturn("bar");
assertThat(cache.getNullable("foo")).isEqualTo("bar");
assertThat(cache.getNullable("foo")).isEqualTo("bar");
}
@Test
- public void get_throws_exception_if_not_exists() throws Exception {
+ public void get_throws_exception_if_not_exists() {
when(loader.load("foo")).thenReturn("bar");
assertThat(cache.get("foo")).isEqualTo("bar");
assertThat(cache.get("foo")).isEqualTo("bar");
}
@Test
- public void getAllNullable() throws Exception {
+ public void getAllNullable() {
// ask for 3 keys but only 2 are available in backed (third key is missing)
List<String> keys = Arrays.asList("one", "two", "three");
Map<String, String> values = new HashMap<>();
IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext();
@Test
- public void define() throws Exception {
+ public void define() {
ViewIndexDefinition def = new ViewIndexDefinition(new Settings());
def.define(context);
}
@Test
- public void enable_cluster() throws Exception {
+ public void enable_cluster() {
Settings settings = new Settings();
settings.setProperty(ProcessProperties.CLUSTER_ACTIVATE, true);
ViewIndexDefinition def = new ViewIndexDefinition(settings);
}
@Test
- public void not_find_all_view_uuids() throws Exception {
+ public void not_find_all_view_uuids() {
List<String> result = newArrayList(index.findAllViewUuids());
assertThat(result).isEmpty();
IssueIndex index;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
tester.clearDbAndIndexes();
dbSession = tester.get(DbClient.class).openSession(false);
index = tester.get(IssueIndex.class);
}
@Test
- public void clear_views_lookup_cache_on_index_view_uuid() throws Exception {
+ public void clear_views_lookup_cache_on_index_view_uuid() {
String viewUuid = "ABCD";
RuleDto rule = RuleTesting.newXooX1();
ViewIndexer indexer;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
dbTester.truncateTables();
esTester.truncateIndices();
indexer = new ViewIndexer(new DbClient(dbTester.database(), dbTester.myBatis(), new ComponentDao()), esTester.client());
}
@Test
- public void index_nothing() throws Exception {
+ public void index_nothing() {
indexer.index();
assertThat(esTester.countDocuments(ViewIndexDefinition.INDEX, ViewIndexDefinition.TYPE_VIEW)).isEqualTo(0L);
}
@Test
- public void index() throws Exception {
+ public void index() {
dbTester.prepareDbUnit(getClass(), "index.xml");
indexer.index();
}
@Test
- public void index_root_view() throws Exception {
+ public void index_root_view() {
dbTester.prepareDbUnit(getClass(), "index.xml");
indexer.index("EFGH");
}
@Test
- public void index_view_doc() throws Exception {
+ public void index_view_doc() {
indexer.index(new ViewDoc().setUuid("EFGH").setProjects(newArrayList("KLMN", "JKLM")));
List<ViewDoc> docs = esTester.getDocuments("views", "view", ViewDoc.class);
ListingWs ws = new ListingWs();
@Test
- public void define_ws() throws Exception {
+ public void define_ws() {
WsTester tester = new WsTester(ws);
WebService.Controller controller = tester.controller("api/webservices");
assertThat(controller).isNotNull();
HttpServletRequest source = mock(HttpServletRequest.class);
@Test
- public void call_method() throws Exception {
+ public void call_method() {
ServletRequest request = new ServletRequest(source, Collections.<String, Object>emptyMap());
request.method();
verify(source).getMethod();
}
@Test
- public void has_param_from_source() throws Exception {
+ public void has_param_from_source() {
when(source.getParameterMap()).thenReturn(ImmutableMap.of("param", new String[]{"value"}));
ServletRequest request = new ServletRequest(source, Collections.<String, Object>emptyMap());
assertThat(request.hasParam("param")).isTrue();
}
@Test
- public void has_param_from_params() throws Exception {
+ public void has_param_from_params() {
ServletRequest request = new ServletRequest(source, ImmutableMap.<String, Object>of("param", "value"));
assertThat(request.hasParam("param")).isTrue();
}
@Test
- public void read_param_from_source() throws Exception {
+ public void read_param_from_source() {
when(source.getParameter("param")).thenReturn("value");
ServletRequest request = new ServletRequest(source, Collections.<String, Object>emptyMap());
assertThat(request.readParam("param")).isEqualTo("value");
}
@Test
- public void read_param_from_param() throws Exception {
+ public void read_param_from_param() {
ServletRequest request = new ServletRequest(source, ImmutableMap.<String, Object>of("param1", "value", "param2", 1));
assertThat(request.readParam("param1")).isEqualTo("value");
assertThat(request.readParam("param2")).isNull();
}
@Test
- public void read_input_stream() throws Exception {
+ public void read_input_stream() {
RubyFile file = mock(RubyFile.class);
ServletRequest request = new ServletRequest(source, ImmutableMap.<String, Object>of("param1", file, "param2", "value"));
request.readInputStreamParam("param1");
}
@Test
- public void to_string() throws Exception {
+ public void to_string() {
when(source.getRequestURL()).thenReturn(new StringBuffer("http:localhost:9000/api/issues"));
ServletRequest request = new ServletRequest(source, Collections.<String, Object>emptyMap());
assertThat(request.toString()).isEqualTo("http:localhost:9000/api/issues");
}
@Test
- public void load_ws_definitions_at_startup() throws Exception {
+ public void load_ws_definitions_at_startup() {
assertThat(engine.controllers()).hasSize(1);
assertThat(engine.controllers().get(0).path()).isEqualTo("api/system");
}
@Test
- public void execute_request() throws Exception {
+ public void execute_request() {
ValidatingRequest request = new SimpleRequest("GET");
ServletResponse response = new ServletResponse();
engine.execute(request, response, "api/system", "health");
}
@Test
- public void no_content() throws Exception {
+ public void no_content() {
ValidatingRequest request = new SimpleRequest("GET");
ServletResponse response = new ServletResponse();
engine.execute(request, response, "api/system", "alive");
}
@Test
- public void bad_controller() throws Exception {
+ public void bad_controller() {
ValidatingRequest request = new SimpleRequest("GET");
ServletResponse response = new ServletResponse();
engine.execute(request, response, "api/xxx", "health");
}
@Test
- public void bad_action() throws Exception {
+ public void bad_action() {
ValidatingRequest request = new SimpleRequest("GET");
ServletResponse response = new ServletResponse();
engine.execute(request, response, "api/system", "xxx");
}
@Test
- public void method_get_not_allowed() throws Exception {
+ public void method_get_not_allowed() {
ValidatingRequest request = new SimpleRequest("GET");
ServletResponse response = new ServletResponse();
engine.execute(request, response, "api/system", "ping");
}
@Test
- public void method_post_required() throws Exception {
+ public void method_post_required() {
ValidatingRequest request = new SimpleRequest("POST");
ServletResponse response = new ServletResponse();
engine.execute(request, response, "api/system", "ping");
}
@Test
- public void unknown_parameter_is_set() throws Exception {
+ public void unknown_parameter_is_set() {
ValidatingRequest request = new SimpleRequest("GET").setParam("unknown", "Unknown");
ServletResponse response = new ServletResponse();
engine.execute(request, response, "api/system", "fail_with_undeclared_parameter");
}
@Test
- public void required_parameter_is_not_set() throws Exception {
+ public void required_parameter_is_not_set() {
ValidatingRequest request = new SimpleRequest("GET");
ServletResponse response = new ServletResponse();
engine.execute(request, response, "api/system", "print");
}
@Test
- public void optional_parameter_is_not_set() throws Exception {
+ public void optional_parameter_is_not_set() {
ValidatingRequest request = new SimpleRequest("GET").setParam("message", "Hello World");
ServletResponse response = new ServletResponse();
engine.execute(request, response, "api/system", "print");
}
@Test
- public void optional_parameter_is_set() throws Exception {
+ public void optional_parameter_is_set() {
ValidatingRequest request = new SimpleRequest("GET")
.setParam("message", "Hello World")
.setParam("author", "Marcel");
}
@Test
- public void param_value_is_in_possible_values() throws Exception {
+ public void param_value_is_in_possible_values() {
ValidatingRequest request = new SimpleRequest("GET")
.setParam("message", "Hello World")
.setParam("format", "json");
}
@Test
- public void param_value_is_not_in_possible_values() throws Exception {
+ public void param_value_is_not_in_possible_values() {
ValidatingRequest request = new SimpleRequest("GET")
.setParam("message", "Hello World")
.setParam("format", "html");
}
@Test
- public void internal_error() throws Exception {
+ public void internal_error() {
ValidatingRequest request = new SimpleRequest("GET");
ServletResponse response = new ServletResponse();
engine.execute(request, response, "api/system", "fail");
}
@Test
- public void bad_request_with_i18n_message() throws Exception {
+ public void bad_request_with_i18n_message() {
MockUserSession.set().setLocale(Locale.ENGLISH);
ValidatingRequest request = new SimpleRequest("GET").setParam("count", "3");
ServletResponse response = new ServletResponse();
}
@Test
- public void bad_request_with_multiple_messages() throws Exception {
+ public void bad_request_with_multiple_messages() {
ValidatingRequest request = new SimpleRequest("GET").setParam("count", "3");
ServletResponse response = new ServletResponse();
}
@Test
- public void bad_request_with_multiple_i18n_messages() throws Exception {
+ public void bad_request_with_multiple_i18n_messages() {
MockUserSession.set().setLocale(Locale.ENGLISH);
ValidatingRequest request = new SimpleRequest("GET").setParam("count", "3");
}
@Test
- public void get() throws Exception {
+ public void get() {
HttpRequestFactory requestFactory = mock(HttpRequestFactory.class);
SonarClient client = new SonarClient(requestFactory);
}
@Test
- public void post() throws Exception {
+ public void post() {
HttpRequestFactory requestFactory = mock(HttpRequestFactory.class);
SonarClient client = new SonarClient(requestFactory);
}
@Test
- public void fail_if_odd_number_arguments() throws Exception {
+ public void fail_if_odd_number_arguments() {
HttpRequestFactory requestFactory = mock(HttpRequestFactory.class);
SonarClient client = new SonarClient(requestFactory);
}
@Test
- public void fail_if_null_property_key() throws Exception {
+ public void fail_if_null_property_key() {
HttpRequestFactory requestFactory = mock(HttpRequestFactory.class);
SonarClient client = new SonarClient(requestFactory);
}
@Test(expected = ConnectionException.class)
- public void failWhenConnectionIsClosed() throws Exception {
+ public void failWhenConnectionIsClosed() {
Sonar fakeSonar = Sonar.create("http://localhost:70");
fakeSonar.findAll(MetricQuery.all());
}
}
@Test
- public void beginning_slash_is_optional() throws Exception {
+ public void beginning_slash_is_optional() {
HttpRequestFactory factory = new HttpRequestFactory(httpServer.url());
factory.get("api/foo", Collections.<String, Object>emptyMap());
assertThat(httpServer.requestedPath()).isEqualTo("/api/foo");
}
@Test
- public void should_create_action_plan() throws Exception {
+ public void should_create_action_plan() {
HttpRequestFactory requestFactory = new HttpRequestFactory(httpServer.url());
httpServer.stubResponseBody("{\"actionPlan\": {\"key\": \"382f6f2e-ad9d-424a-b973-9b065e04348a\"}}");
}
@Test
- public void fail_if_rate_is_greater_than_timeout() throws Exception {
+ public void fail_if_rate_is_greater_than_timeout() {
try {
DefaultSystemClient client = new DefaultSystemClient(mock(HttpRequestFactory.class));
client.migrate(5L, 50L);
public class PluginUnmarshallerTest extends UnmarshallerTestCase {
@Test
- public void toModel() throws Exception {
+ public void toModel() {
WSUtils.setInstance(new JdkUtils());
List<Plugin> plugins = new PluginUnmarshaller().toModels(loadFile("/plugins/plugins.json"));
}
@Test
- public void should_accept_null_values() throws Exception {
+ public void should_accept_null_values() {
TimeMachine timeMachine = new TimeMachineUnmarshaller().toModel(loadFile("/timemachine/null-values.json"));
assertThat(timeMachine.getCells()[0].getValues().length).isEqualTo(2);
}
@Test
- public void should_cast_values() throws Exception {
+ public void should_cast_values() {
TimeMachine timeMachine = new TimeMachineUnmarshaller().toModel(loadFile("/timemachine/typed-values.json"));
assertThat(timeMachine.getCells()[0].getValues().length).isEqualTo(2);
}
@Test
- public void should_create_user() throws Exception {
+ public void should_create_user() {
httpServer.stubResponseBody("{\"user\":{\"login\":\"daveloper\",\"name\":\"daveloper\",\"email\":null}}");
UserParameters params = UserParameters.create().login("daveloper").password("pass1").passwordConfirmation("pass1");
}
@Test
- public void should_update_user() throws Exception {
+ public void should_update_user() {
httpServer.stubResponseBody("{\"user\":{\"login\":\"daveloper\",\"name\":\"daveloper\",\"email\":\"new_email\"}}");
UserParameters params = UserParameters.create().login("daveloper").email("new_email");
}
@Test
- public void should_deactivate_user() throws Exception {
+ public void should_deactivate_user() {
httpServer.stubStatusCode(200);
client.deactivate("daveloper");
}
@Test
- public void should_replace_logins() throws Exception {
+ public void should_replace_logins() {
UserQuery query = UserQuery.create().logins("simon").logins("loic");
assertThat(query.urlParams().get("logins")).isEqualTo("loic");
}
@Test
- public void should_search_by_text() throws Exception {
+ public void should_search_by_text() {
UserQuery query = UserQuery.create().searchText("sim");
assertThat(query.urlParams().get("s")).isEqualTo("sim");
}
@Test
- public void configure_defaults() throws Exception {
+ public void configure_defaults() {
LoggerContext ctx = sut.configure(props);
Logger gobbler = ctx.getLogger(AppLogging.GOBBLER_LOGGER);
}
@Test
- public void configure_no_rotation() throws Exception {
+ public void configure_no_rotation() {
props.set("sonar.log.rollingPolicy", "none");
LoggerContext ctx = sut.configure(props);
}
@Test
- public void copyGobblerToConsole() throws Exception {
+ public void copyGobblerToConsole() {
props.set("sonar.log.console", "true");
LoggerContext ctx = sut.configure(props);
CommandLineParser parser = new CommandLineParser();
@Test
- public void parseArguments() throws Exception {
+ public void parseArguments() {
System.setProperty("CommandLineParserTest.unused", "unused");
System.setProperty("sonar.CommandLineParserTest.used", "used");
}
@Test
- public void argumentsToProperties() throws Exception {
+ public void argumentsToProperties() {
Properties p = parser.argumentsToProperties(new String[] {"-Dsonar.foo=bar", "-Dsonar.whitespace=foo bar"});
assertThat(p).hasSize(2);
assertThat(p.getProperty("sonar.foo")).isEqualTo("bar");
JdbcSettings settings = new JdbcSettings();
@Test
- public void driver_provider() throws Exception {
+ public void driver_provider() {
assertThat(settings.driverProvider("jdbc:oracle:thin:@localhost/XE")).isEqualTo(JdbcSettings.Provider.ORACLE);
assertThat(settings.driverProvider("jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance"))
.isEqualTo(JdbcSettings.Provider.MYSQL);
}
@Test
- public void check_mysql_parameters() throws Exception {
+ public void check_mysql_parameters() {
// minimal -> ok
settings.checkUrlParameters(JdbcSettings.Provider.MYSQL,
"jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8");
public class ProtobufUtilTest {
@Test
- public void only_utils() throws Exception {
+ public void only_utils() {
assertThat(TestUtils.hasOnlyPrivateConstructors(ProtobufUtil.class));
}
public class GlobalRepositoriesTest {
@Test
- public void to_json() throws Exception {
+ public void to_json() {
GlobalRepositories ref = new GlobalRepositories();
ref.addMetric(new Metric(1, "ncloc", "INT", "Description", -1, "NCLOC", true, false, 2.0, 1.0, true));
ref.addGlobalSetting("prop", "value");
}
@Test
- public void read_metadata() throws Exception {
+ public void read_metadata() {
BatchReportWriter writer = new BatchReportWriter(dir);
BatchReport.Metadata.Builder metadata = BatchReport.Metadata.newBuilder()
.setAnalysisDate(15000000L)
}
@Test(expected = IllegalStateException.class)
- public void fail_if_missing_metadata_file() throws Exception {
+ public void fail_if_missing_metadata_file() {
sut.readMetadata();
}
@Test
- public void read_components() throws Exception {
+ public void read_components() {
BatchReportWriter writer = new BatchReportWriter(dir);
BatchReport.Component.Builder component = BatchReport.Component.newBuilder()
.setRef(1)
}
@Test(expected = IllegalStateException.class)
- public void fail_if_missing_file_on_component() throws Exception {
+ public void fail_if_missing_file_on_component() {
sut.readComponent(UNKNOWN_COMPONENT_REF);
}
@Test
- public void read_issues() throws Exception {
+ public void read_issues() {
BatchReportWriter writer = new BatchReportWriter(dir);
BatchReport.Issue issue = BatchReport.Issue.newBuilder()
.setUuid("ISSUE_A")
}
@Test(expected = IllegalStateException.class)
- public void fail_if_missing_file_on_deleted_component() throws Exception {
+ public void fail_if_missing_file_on_deleted_component() {
sut.readDeletedComponentIssues(UNKNOWN_COMPONENT_REF);
}
@Test
- public void empty_list_if_no_issue_found() throws Exception {
+ public void empty_list_if_no_issue_found() {
assertThat(sut.readComponentIssues(UNKNOWN_COMPONENT_REF)).isEmpty();
}
@Test
- public void read_measures() throws Exception {
+ public void read_measures() {
BatchReportWriter writer = new BatchReportWriter(dir);
BatchReport.Measure.Builder measure = BatchReport.Measure.newBuilder()
.setStringValue("value_a");
}
@Test
- public void empty_list_if_no_measure_found() throws Exception {
+ public void empty_list_if_no_measure_found() {
assertThat(sut.readComponentMeasures(UNKNOWN_COMPONENT_REF)).isEmpty();
}
@Test
- public void read_changesets() throws Exception {
+ public void read_changesets() {
BatchReportWriter writer = new BatchReportWriter(dir);
BatchReport.Changesets.Builder scm = BatchReport.Changesets.newBuilder()
.setComponentRef(1)
}
@Test
- public void null_if_no_changeset_found() throws Exception {
+ public void null_if_no_changeset_found() {
assertThat(sut.readChangesets(UNKNOWN_COMPONENT_REF)).isNull();
}
@Test
- public void read_duplications() throws Exception {
+ public void read_duplications() {
BatchReportWriter writer = new BatchReportWriter(dir);
writer.writeMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1).build());
}
@Test
- public void empty_list_if_no_duplication_found() throws Exception {
+ public void empty_list_if_no_duplication_found() {
assertThat(sut.readComponentDuplications(UNKNOWN_COMPONENT_REF)).isEmpty();
}
}
@Test
- public void return_null_if_no_highlighting_found() throws Exception {
+ public void return_null_if_no_highlighting_found() {
assertThat(sut.readComponentSyntaxHighlighting(UNKNOWN_COMPONENT_REF)).isNull();
}
@Test
- public void read_symbols() throws Exception {
+ public void read_symbols() {
BatchReportWriter writer = new BatchReportWriter(dir);
writer.writeMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
}
@Test
- public void empty_list_if_no_symbol_found() throws Exception {
+ public void empty_list_if_no_symbol_found() {
assertThat(sut.readComponentSymbols(UNKNOWN_COMPONENT_REF)).isEmpty();
}
}
@Test
- public void return_null_if_no_coverage_found() throws Exception {
+ public void return_null_if_no_coverage_found() {
assertThat(sut.readComponentCoverage(UNKNOWN_COMPONENT_REF)).isNull();
}
}
@Test
- public void null_if_no_test_found() throws Exception {
+ public void null_if_no_test_found() {
assertThat(sut.readTests(UNKNOWN_COMPONENT_REF)).isNull();
}
}
@Test
- public void null_if_no_coverage_detail_found() throws Exception {
+ public void null_if_no_coverage_detail_found() {
assertThat(sut.readCoverageDetails(UNKNOWN_COMPONENT_REF)).isNull();
}
}
@Test
- public void null_if_no_file_dependencies_found() throws Exception {
+ public void null_if_no_file_dependencies_found() {
assertThat(sut.readFileDependencies(UNKNOWN_COMPONENT_REF)).isNull();
}
@Test
- public void read_module_dependencies() throws Exception {
+ public void read_module_dependencies() {
BatchReportWriter writer = new BatchReportWriter(dir);
writer.writeModuleDependencies(1, Arrays.asList(BatchReport.ModuleDependencies.ModuleDependency.newBuilder()
.setKey("PROJECT_1")
}
@Test
- public void empty_list_if_no_module_dependencies_found() throws Exception {
+ public void empty_list_if_no_module_dependencies_found() {
assertThat(sut.readModuleDependencies(UNKNOWN_COMPONENT_REF)).isEmpty();
}
}
@Test
- public void create_dir_if_does_not_exist() throws Exception {
+ public void create_dir_if_does_not_exist() {
FileUtils.deleteQuietly(dir);
sut = new BatchReportWriter(dir);
}
@Test
- public void write_metadata() throws Exception {
+ public void write_metadata() {
BatchReport.Metadata.Builder metadata = BatchReport.Metadata.newBuilder()
.setAnalysisDate(15000000L)
.setProjectKey("PROJECT_A")
}
@Test
- public void write_component() throws Exception {
+ public void write_component() {
// no data yet
assertThat(sut.hasComponentData(FileStructure.Domain.COMPONENT, 1)).isFalse();
}
@Test
- public void write_issues() throws Exception {
+ public void write_issues() {
// no data yet
assertThat(sut.hasComponentData(FileStructure.Domain.ISSUES, 1)).isFalse();
}
@Test
- public void write_issues_of_deleted_component() throws Exception {
+ public void write_issues_of_deleted_component() {
// no data yet
assertThat(sut.hasComponentData(FileStructure.Domain.ISSUES_ON_DELETED, 1)).isFalse();
}
@Test
- public void write_measures() throws Exception {
+ public void write_measures() {
assertThat(sut.hasComponentData(FileStructure.Domain.MEASURES, 1)).isFalse();
BatchReport.Measure measure = BatchReport.Measure.newBuilder()
}
@Test
- public void write_scm() throws Exception {
+ public void write_scm() {
assertThat(sut.hasComponentData(FileStructure.Domain.CHANGESETS, 1)).isFalse();
BatchReport.Changesets scm = BatchReport.Changesets.newBuilder()
}
@Test
- public void write_duplications() throws Exception {
+ public void write_duplications() {
assertThat(sut.hasComponentData(FileStructure.Domain.DUPLICATIONS, 1)).isFalse();
BatchReport.Duplication duplication = BatchReport.Duplication.newBuilder()
}
@Test
- public void write_symbols() throws Exception {
+ public void write_symbols() {
// no data yet
assertThat(sut.hasComponentData(FileStructure.Domain.SYMBOLS, 1)).isFalse();
}
@Test
- public void write_syntax_highlighting() throws Exception {
+ public void write_syntax_highlighting() {
// no data yet
assertThat(sut.hasComponentData(FileStructure.Domain.SYNTAX_HIGHLIGHTINGS, 1)).isFalse();
}
@Test
- public void write_coverage() throws Exception {
+ public void write_coverage() {
// no data yet
assertThat(sut.hasComponentData(FileStructure.Domain.COVERAGES, 1)).isFalse();
}
@Test
- public void write_tests() throws Exception {
+ public void write_tests() {
assertThat(sut.hasComponentData(FileStructure.Domain.TESTS, 1)).isFalse();
sut.writeTests(1, Arrays.asList(
}
@Test
- public void write_coverage_details() throws Exception {
+ public void write_coverage_details() {
assertThat(sut.hasComponentData(FileStructure.Domain.COVERAGE_DETAILS, 1)).isFalse();
sut.writeCoverageDetails(1, Arrays.asList(
}
@Test
- public void write_file_dependencies() throws Exception {
+ public void write_file_dependencies() {
assertThat(sut.hasComponentData(FileStructure.Domain.FILE_DEPENDENCIES, 1)).isFalse();
sut.writeFileDependencies(1, Arrays.asList(BatchReport.FileDependency.getDefaultInstance()));
}
@Test
- public void write_module_dependencies() throws Exception {
+ public void write_module_dependencies() {
assertThat(sut.hasComponentData(FileStructure.Domain.MODULE_DEPENDENCIES, 1)).isFalse();
sut.writeModuleDependencies(1, Arrays.asList(BatchReport.ModuleDependencies.ModuleDependency.getDefaultInstance()));
System2 system2;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
system2 = mock(System2.class);
}
}
@Test
- public void shouldFailIfNotSameServerId() throws Exception {
+ public void shouldFailIfNotSameServerId() {
when(propertiesDao.selectGlobalProperty(CoreProperties.SERVER_ID)).thenReturn(new PropertyDto().setValue("11111111"));
thrown.expect(MessageException.class);
}
@Test
- public void shouldUseDefaultUserNameWhenFaillingIfNotSameServerIdAndNoUserNameFound() throws Exception {
+ public void shouldUseDefaultUserNameWhenFaillingIfNotSameServerIdAndNoUserNameFound() {
when(propertiesDao.selectGlobalProperty(CoreProperties.SERVER_ID)).thenReturn(new PropertyDto().setValue("11111111"));
settings.removeProperty(DatabaseProperties.PROP_USER);
}
@Test
- public void shouldFailIfCantGetServerId() throws Exception {
+ public void shouldFailIfCantGetServerId() {
when(server.request("/api/server")).thenThrow(new IllegalStateException());
thrown.expect(IllegalStateException.class);
}
@Test
- public void should_fail_to_get_plugin_index() throws Exception {
+ public void should_fail_to_get_plugin_index() {
thrown.expect(IllegalStateException.class);
ServerClient server = mock(ServerClient.class);
}
@Before
- public void setUp() throws Exception {
+ public void setUp() {
mode = mock(DefaultAnalysisMode.class);
}
}
@Test
- public void extend_classloader_with_jdbc_driver() throws Exception {
+ public void extend_classloader_with_jdbc_driver() {
FileCache cache = mock(FileCache.class);
File fakeDriver = new File(Resources.getResource(JdbcDriverHolderTest.class, "JdbcDriverHolderTest/jdbc-driver.jar").getFile());
}
@Test
- public void do_nothing_when_jdbc_driver_file_is_empty() throws Exception {
+ public void do_nothing_when_jdbc_driver_file_is_empty() {
FileCache cache = mock(FileCache.class);
ServerClient server = mock(ServerClient.class);
}
@Test
- public void should_remove_url_ending_slash() throws Exception {
+ public void should_remove_url_ending_slash() {
BootstrapProperties settings = mock(BootstrapProperties.class);
when(settings.property("sonar.host.url")).thenReturn("http://localhost:8080/sonar/");
}
@Test
- public void should_find_by_previous_analysis() throws ParseException {
+ public void should_find_by_previous_analysis() {
final Date date = DateUtils.parseDate("2010-05-18");
Snapshot snapshot = new Snapshot();
snapshot.setCreatedAtMs(date.getTime());
DebtDecorator decorator;
@Before
- public void before() throws Exception {
+ public void before() {
when(perspectives.as(Issuable.class, resource)).thenReturn(issuable);
RulesBuilder rulesBuilder = new RulesBuilder();
rulesBuilder.add(ruleKey1).setName("rule1").setDebtSubCharacteristic("MEMORY_EFFICIENCY");
}
@Test
- public void generates_metrics() throws Exception {
+ public void generates_metrics() {
assertThat(decorator.generatesMetrics()).hasSize(1);
}
@Test
- public void execute_on_project() throws Exception {
+ public void execute_on_project() {
assertThat(decorator.shouldExecuteOnProject(null)).isTrue();
}
}
@Test
- public void add_technical_debt_from_one_issue_and_no_parent() throws Exception {
+ public void add_technical_debt_from_one_issue_and_no_parent() {
Issue issue = createIssue("rule1", "repo1").setDebt(Duration.create(ONE_DAY_IN_MINUTES));
when(issuable.issues()).thenReturn(newArrayList(issue));
}
@Test
- public void add_technical_debt_from_one_issue_without_debt() throws Exception {
+ public void add_technical_debt_from_one_issue_without_debt() {
Issue issue = createIssue("rule1", "repo1").setDebt(null);
when(issuable.issues()).thenReturn(newArrayList(issue));
}
@Test
- public void add_technical_debt_from_one_issue_and_propagate_to_parents() throws Exception {
+ public void add_technical_debt_from_one_issue_and_propagate_to_parents() {
Issue issue = createIssue("rule1", "repo1").setDebt(Duration.create(ONE_DAY_IN_MINUTES));
when(issuable.issues()).thenReturn(newArrayList(issue));
}
@Test
- public void add_technical_debt_from_issues() throws Exception {
+ public void add_technical_debt_from_issues() {
Long technicalDebt1 = ONE_DAY_IN_MINUTES;
Long technicalDebt2 = 2 * ONE_DAY_IN_MINUTES;
}
@Test
- public void add_technical_debt_from_current_and_children_measures() throws Exception {
+ public void add_technical_debt_from_current_and_children_measures() {
Issue issue1 = createIssue("rule1", "repo1").setDebt(Duration.create(ONE_DAY_IN_MINUTES));
Issue issue2 = createIssue("rule1", "repo1").setDebt(Duration.create(ONE_DAY_IN_MINUTES));
when(issuable.issues()).thenReturn(newArrayList(issue1, issue2));
}
@Test
- public void add_technical_debt_only_from_children_measures() throws Exception {
+ public void add_technical_debt_only_from_children_measures() {
when(issuable.issues()).thenReturn(Collections.<Issue>emptyList());
when(context.getChildrenMeasures(any(MeasuresFilter.class))).thenReturn(Lists.<Measure>newArrayList(
}
@Test
- public void always_save_technical_debt_for_positive_values() throws Exception {
+ public void always_save_technical_debt_for_positive_values() {
// for a project
DecoratorContext context = mock(DecoratorContext.class);
when(context.getResource()).thenReturn(new Project("foo"));
}
@Test
- public void always_save_technical_debt_for_project_if_top_characteristic() throws Exception {
+ public void always_save_technical_debt_for_project_if_top_characteristic() {
DecoratorContext context = mock(DecoratorContext.class);
when(context.getResource()).thenReturn(new Project("foo"));
* SQALE-147
*/
@Test
- public void never_save_technical_debt_for_project_if_not_top_characteristic() throws Exception {
+ public void never_save_technical_debt_for_project_if_not_top_characteristic() {
DecoratorContext context = mock(DecoratorContext.class);
when(context.getResource()).thenReturn(new Project("foo"));
}
@Test
- public void not_save_technical_debt_for_file_if_zero() throws Exception {
+ public void not_save_technical_debt_for_file_if_zero() {
DecoratorContext context = mock(DecoratorContext.class);
when(context.getResource()).thenReturn(File.create("foo"));
}
@Test
- public void provide_model() throws Exception {
+ public void provide_model() {
CharacteristicDto rootCharacteristicDto = new CharacteristicDto()
.setId(1)
.setKey("MEMORY_EFFICIENCY")
Duration fiveDaysDebt = Duration.create(fiveDays);
@Before
- public void setUp() throws Exception {
+ public void setUp() {
issueChangelogDebtCalculator = new IssueChangelogDebtCalculator();
}
@Test
- public void calculate_new_technical_debt_with_one_diff_in_changelog() throws Exception {
+ public void calculate_new_technical_debt_with_one_diff_in_changelog() {
Issue issue = new DefaultIssue().setKey("A").setCreationDate(tenDaysAgo).setDebt(twoDaysDebt).setChanges(
newArrayList(
// changelog created at is null because it has just been created on the current analysis
}
@Test
- public void calculate_new_technical_debt_with_many_diffs_in_changelog() throws Exception {
+ public void calculate_new_technical_debt_with_many_diffs_in_changelog() {
Issue issue = new DefaultIssue().setKey("A").setCreationDate(tenDaysAgo).setDebt(fiveDaysDebt).setChanges(
newArrayList(
new FieldDiffs().setDiff("technicalDebt", twoDays, fiveDays).setCreationDate(null),
}
@Test
- public void calculate_new_technical_debt_with_null_date() throws Exception {
+ public void calculate_new_technical_debt_with_null_date() {
Issue issue = new DefaultIssue().setKey("A").setCreationDate(tenDaysAgo).setDebt(twoDaysDebt).setChanges(
newArrayList(
new FieldDiffs().setDiff("technicalDebt", oneDay, twoDays).setCreationDate(null)
}
@Test
- public void calculate_new_technical_debt_when_new_debt_is_null() throws Exception {
+ public void calculate_new_technical_debt_when_new_debt_is_null() {
Issue issue = new DefaultIssue().setKey("A").setCreationDate(tenDaysAgo).setDebt(null).setChanges(
newArrayList(
new FieldDiffs().setDiff("technicalDebt", oneDay, null).setCreationDate(null),
}
@Test
- public void generates_metrics() throws Exception {
+ public void generates_metrics() {
assertThat(decorator.generatesMetrics()).hasSize(1);
}
@Test
- public void execute_on_project() throws Exception {
+ public void execute_on_project() {
assertThat(decorator.shouldExecuteOnProject(null)).isTrue();
}
}
@Test
- public void generates_metrics() throws Exception {
+ public void generates_metrics() {
SqaleRatingDecorator decorator = new SqaleRatingDecorator();
assertThat(decorator.generatesMetrics()).hasSize(3);
}
}
@Test
- public void execute_on_project() throws Exception {
+ public void execute_on_project() {
SqaleRatingDecorator decorator = new SqaleRatingDecorator();
assertThat(decorator.shouldExecuteOnProject(null)).isTrue();
}
@Test
- public void not_execute_on_unit_test() throws Exception {
+ public void not_execute_on_unit_test() {
File resource = mock(File.class);
when(resource.getQualifier()).thenReturn(Qualifiers.UNIT_TEST_FILE);
DecoratorContext context = mock(DecoratorContext.class);
}
@Test
- public void return_grade_lower_bound() throws Exception {
+ public void return_grade_lower_bound() {
assertThat(ratingGrid.getGradeLowerBound(SqaleRatingGrid.SqaleRating.A)).isEqualTo(0);
assertThat(ratingGrid.getGradeLowerBound(SqaleRatingGrid.SqaleRating.B)).isEqualTo(0.1);
assertThat(ratingGrid.getGradeLowerBound(SqaleRatingGrid.SqaleRating.C)).isEqualTo(0.2);
}
@Test
- public void return_rating_matching_density() throws Exception {
+ public void return_rating_matching_density() {
assertThat(ratingGrid.getRatingForDensity(0)).isEqualTo(1);
assertThat(ratingGrid.getRatingForDensity(0.05)).isEqualTo(1);
assertThat(ratingGrid.getRatingForDensity(0.1)).isEqualTo(2);
}
@Test
- public void fail_on_invalid_density() throws Exception {
+ public void fail_on_invalid_density() {
throwable.expect(RuntimeException.class);
ratingGrid.getRatingForDensity(-1);
}
@Test
- public void load_rating_grid() throws Exception {
+ public void load_rating_grid() {
settings.setProperty(CoreProperties.RATING_GRID, "1,3.4,8,50");
SqaleRatingSettings configurationLoader = new SqaleRatingSettings(settings);
}
@Test
- public void load_work_units_for_language() throws Exception {
+ public void load_work_units_for_language() {
settings.setProperty(CoreProperties.DEVELOPMENT_COST, "50");
SqaleRatingSettings configurationLoader = new SqaleRatingSettings(settings);
}
@Test
- public void load_size_metric_for_language() throws Exception {
+ public void load_size_metric_for_language() {
settings.setProperty(CoreProperties.SIZE_METRIC, "complexity");
SqaleRatingSettings configurationLoader = new SqaleRatingSettings(settings);
}
@Test
- public void load_overridden_values_for_language() throws Exception {
+ public void load_overridden_values_for_language() {
String aLanguage = "aLanguage";
String anotherLanguage = "anotherLanguage";
}
@Test
- public void fail_on_invalid_rating_grid_configuration() throws Exception {
+ public void fail_on_invalid_rating_grid_configuration() {
throwable.expect(IllegalArgumentException.class);
settings.setProperty(CoreProperties.RATING_GRID, "a b c");
}
@Test
- public void fail_on_invalid_work_unit_value() throws Exception {
+ public void fail_on_invalid_work_unit_value() {
throwable.expect(IllegalArgumentException.class);
settings.setProperty(CoreProperties.DEVELOPMENT_COST, "a");
SqaleRatingSettings configurationLoader = new SqaleRatingSettings(settings);
}
@Test
- public void fail_on_unknown_metric_key() throws Exception {
+ public void fail_on_unknown_metric_key() {
throwable.expect(IllegalArgumentException.class);
settings.setProperty(CoreProperties.SIZE_METRIC, "unknown");
SqaleRatingSettings configurationLoader = new SqaleRatingSettings(settings);
}
@Test
- public void use_generic_value_when_specific_setting_is_missing() throws Exception {
+ public void use_generic_value_when_specific_setting_is_missing() {
String aLanguage = "aLanguage";
settings.setProperty(CoreProperties.SIZE_METRIC, "complexity");
public class ResourceFiltersTest {
@Test
- public void warn_on_resource_filters() throws Exception {
+ public void warn_on_resource_filters() {
Logger logger = mock(Logger.class);
ResourceFilter[] filters = {mock(ResourceFilter.class)};
new ResourceFilters(logger, filters);
}
@Test
- public void ok_if_no_resource_filters() throws Exception {
+ public void ok_if_no_resource_filters() {
// just for verify that it does not fail. Should check that no warning is logged.
new ResourceFilters();
}
private PastSnapshotFinderByPreviousVersion finder;
@Before
- public void before() throws Exception {
+ public void before() {
finder = new PastSnapshotFinderByPreviousVersion(getSession(), getMyBatis());
}
Caches caches;
@Before
- public void start() throws Exception {
+ public void start() {
caches = CachesTest.createCacheOnTemp(temp);
caches.start();
}
}
@Test
- public void should_add_clone_groups() throws Exception {
+ public void should_add_clone_groups() {
DuplicationCache cache = new DuplicationCache(caches);
DefaultDuplication group1 = new DefaultDuplication()
Caches caches;
@Before
- public void start() throws Exception {
+ public void start() {
caches = CachesTest.createCacheOnTemp(temp);
caches.start();
}
}
@Test
- public void one_part_key() throws Exception {
+ public void one_part_key() {
Cache<String> cache = caches.createCache("capitals");
assertThat(cache.get("france")).isNull();
}
@Test
- public void two_parts_key() throws Exception {
+ public void two_parts_key() {
Cache<String> cache = caches.createCache("capitals");
assertThat(cache.get("europe", "france")).isNull();
}
@Test
- public void three_parts_key() throws Exception {
+ public void three_parts_key() {
Cache<String> cache = caches.createCache("places");
assertThat(cache.get("europe", "france", "paris")).isNull();
}
@Test
- public void remove_versus_clear() throws Exception {
+ public void remove_versus_clear() {
Cache<String> cache = caches.createCache("capitals");
cache.put("europe", "france", "paris");
cache.put("europe", "italy", "rome");
}
@Test
- public void empty_cache() throws Exception {
+ public void empty_cache() {
Cache<String> cache = caches.createCache("empty");
assertThat(cache.get("foo")).isNull();
Caches caches;
@Before
- public void prepare() throws Exception {
+ public void prepare() {
caches = createCacheOnTemp(temp);
}
}
@Test
- public void should_stop_and_clean_temp_dir() throws Exception {
+ public void should_stop_and_clean_temp_dir() {
File tempDir = caches.tempDir();
assertThat(tempDir).isDirectory().exists();
assertThat(caches.persistit()).isNotNull();
}
@Test
- public void should_create_cache() throws Exception {
+ public void should_create_cache() {
caches.start();
Cache<Element> cache = caches.createCache("foo");
assertThat(cache).isNotNull();
}
@Test
- public void should_not_create_cache_twice() throws Exception {
+ public void should_not_create_cache_twice() {
caches.start();
caches.<Element>createCache("foo");
try {
public class ResourceCacheTest {
@Test
- public void should_cache_resource() throws Exception {
+ public void should_cache_resource() {
ResourceCache cache = new ResourceCache();
String componentKey = "struts:src/org/struts/Action.java";
Resource resource = File.create("org/struts/Action.java").setEffectiveKey(componentKey);
}
@Test
- public void should_fail_if_missing_component_key() throws Exception {
+ public void should_fail_if_missing_component_key() {
ResourceCache cache = new ResourceCache();
Resource resource = File.create("org/struts/Action.java").setEffectiveKey(null);
try {
private final Issue issue = mock(Issue.class);
@Test
- public void should_accept_when_no_filter() throws Exception {
+ public void should_accept_when_no_filter() {
assertThat(new DefaultIssueFilterChain().accept(issue)).isTrue();
}
}
@Test
- public void should_accept_if_all_filters_pass() throws Exception {
+ public void should_accept_if_all_filters_pass() {
assertThat(new DefaultIssueFilterChain(
new PassingFilter(),
new PassingFilter(),
}
@Test
- public void should_accept_and_not_go_further_if_filter_accepts() throws Exception {
+ public void should_accept_and_not_go_further_if_filter_accepts() {
assertThat(new DefaultIssueFilterChain(
new PassingFilter(),
new AcceptingFilter(),
}
@Test
- public void should_refuse_and_not_go_further_if_filter_refuses() throws Exception {
+ public void should_refuse_and_not_go_further_if_filter_refuses() {
assertThat(new DefaultIssueFilterChain(
new PassingFilter(),
new RefusingFilter(),
DefaultProjectIssues projectIssues = new DefaultProjectIssues(cache);
@Test
- public void should_get_all_issues() throws Exception {
+ public void should_get_all_issues() {
DefaultIssue issueOnModule = new DefaultIssue().setKey("1").setRuleKey(SQUID_RULE_KEY).setComponentKey("org.apache:struts-core");
DefaultIssue issueInModule = new DefaultIssue().setKey("2").setRuleKey(SQUID_RULE_KEY).setComponentKey("org.apache:struts-core:Action");
DefaultIssue resolvedIssueInModule = new DefaultIssue().setKey("3").setRuleKey(SQUID_RULE_KEY).setComponentKey("org.apache:struts-core:Action")
ProjectTree projectTree = mock(ProjectTree.class);
@Test
- public void file_should_be_issuable() throws Exception {
+ public void file_should_be_issuable() {
IssuableFactory factory = new IssuableFactory(moduleIssues, cache, projectTree);
Component component = new ResourceComponent(File.create("foo/bar.c").setEffectiveKey("foo/bar.c"));
Issuable issuable = factory.loadPerspective(Issuable.class, component);
}
@Test
- public void project_should_be_issuable() throws Exception {
+ public void project_should_be_issuable() {
IssuableFactory factory = new IssuableFactory(moduleIssues, cache, projectTree);
Component component = new ResourceComponent(new Project("Foo").setEffectiveKey("foo"));
Issuable issuable = factory.loadPerspective(Issuable.class, component);
Caches caches;
@Before
- public void start() throws Exception {
+ public void start() {
caches = CachesTest.createCacheOnTemp(temp);
caches.start();
}
}
@Test
- public void should_add_new_issue() throws Exception {
+ public void should_add_new_issue() {
IssueCache cache = new IssueCache(caches);
DefaultIssue issue1 = new DefaultIssue().setKey("111").setComponentKey("org.struts.Action");
DefaultIssue issue2 = new DefaultIssue().setKey("222").setComponentKey("org.struts.Action");
}
@Test
- public void should_update_existing_issue() throws Exception {
+ public void should_update_existing_issue() {
IssueCache cache = new IssueCache(caches);
DefaultIssue issue = new DefaultIssue().setKey("111").setComponentKey("org.struts.Action").setSeverity(Severity.BLOCKER);
cache.put(issue);
}
@Test
- public void should_get_all_issues() throws Exception {
+ public void should_get_all_issues() {
IssueCache cache = new IssueCache(caches);
DefaultIssue issue1 = new DefaultIssue().setKey("111").setComponentKey("org.struts.Action").setSeverity(Severity.BLOCKER);
DefaultIssue issue2 = new DefaultIssue().setKey("222").setComponentKey("org.struts.Filter").setSeverity(Severity.INFO);
public class IssueFiltersTest {
@Test
- public void accept_when_filter_chain_is_empty() throws Exception {
+ public void accept_when_filter_chain_is_empty() {
org.sonar.api.issue.IssueFilter ok = mock(org.sonar.api.issue.IssueFilter.class);
when(ok.accept(any(Issue.class))).thenReturn(true);
}
@Test
- public void fail_on_unknown_rule() throws Exception {
+ public void fail_on_unknown_rule() {
initModuleIssues();
DefaultIssue issue = new DefaultIssue().setRuleKey(SQUID_RULE_KEY);
}
@Test
- public void fail_if_rule_has_no_name_and_issue_has_no_message() throws Exception {
+ public void fail_if_rule_has_no_name_and_issue_has_no_message() {
ruleBuilder.add(RuleKey.of("squid", "AvoidCycle"));
initModuleIssues();
DefaultIssue issue = new DefaultIssue().setRuleKey(SQUID_RULE_KEY).setMessage("");
}
@Test
- public void ignore_null_active_rule() throws Exception {
+ public void ignore_null_active_rule() {
ruleBuilder.add(SQUID_RULE_KEY).setName(SQUID_RULE_NAME);
initModuleIssues();
}
@Test
- public void ignore_null_rule_of_active_rule() throws Exception {
+ public void ignore_null_rule_of_active_rule() {
ruleBuilder.add(SQUID_RULE_KEY).setName(SQUID_RULE_NAME);
activeRulesBuilder.create(SQUID_RULE_KEY).activate();
initModuleIssues();
}
@Test
- public void add_issue_to_cache() throws Exception {
+ public void add_issue_to_cache() {
ruleBuilder.add(SQUID_RULE_KEY).setName(SQUID_RULE_NAME);
activeRulesBuilder.create(SQUID_RULE_KEY).setSeverity(Severity.INFO).activate();
initModuleIssues();
}
@Test
- public void use_severity_from_active_rule_if_no_severity_on_issue() throws Exception {
+ public void use_severity_from_active_rule_if_no_severity_on_issue() {
ruleBuilder.add(SQUID_RULE_KEY).setName(SQUID_RULE_NAME);
activeRulesBuilder.create(SQUID_RULE_KEY).setSeverity(Severity.INFO).activate();
initModuleIssues();
}
@Test
- public void use_rule_name_if_no_message() throws Exception {
+ public void use_rule_name_if_no_message() {
ruleBuilder.add(SQUID_RULE_KEY).setName(SQUID_RULE_NAME);
activeRulesBuilder.create(SQUID_RULE_KEY).setSeverity(Severity.INFO).setName(SQUID_RULE_NAME).activate();
initModuleIssues();
}
@Test
- public void add_deprecated_violation() throws Exception {
+ public void add_deprecated_violation() {
ruleBuilder.add(SQUID_RULE_KEY).setName(SQUID_RULE_NAME);
activeRulesBuilder.create(SQUID_RULE_KEY).setSeverity(Severity.INFO).activate();
initModuleIssues();
}
@Test
- public void filter_issue() throws Exception {
+ public void filter_issue() {
ruleBuilder.add(SQUID_RULE_KEY).setName(SQUID_RULE_NAME);
activeRulesBuilder.create(SQUID_RULE_KEY).setSeverity(Severity.INFO).activate();
initModuleIssues();
}
@Test
- public void set_debt_with_linear_function() throws Exception {
+ public void set_debt_with_linear_function() {
ruleBuilder.add(SQUID_RULE_KEY)
.setName(SQUID_RULE_NAME)
.setDebtSubCharacteristic("COMPILER_RELATED_PORTABILITY")
}
@Test
- public void set_debt_with_linear_with_offset_function() throws Exception {
+ public void set_debt_with_linear_with_offset_function() {
ruleBuilder.add(SQUID_RULE_KEY)
.setName(SQUID_RULE_NAME)
.setDebtSubCharacteristic("COMPILER_RELATED_PORTABILITY")
}
@Test
- public void set_debt_with_constant_issue_function() throws Exception {
+ public void set_debt_with_constant_issue_function() {
ruleBuilder.add(SQUID_RULE_KEY)
.setName(SQUID_RULE_NAME)
.setDebtSubCharacteristic("COMPILER_RELATED_PORTABILITY")
}
@Test
- public void fail_to_set_debt_with_constant_issue_function_when_effort_to_fix_is_set() throws Exception {
+ public void fail_to_set_debt_with_constant_issue_function_when_effort_to_fix_is_set() {
ruleBuilder.add(SQUID_RULE_KEY)
.setName(SQUID_RULE_NAME)
.setDebtSubCharacteristic("COMPILER_RELATED_PORTABILITY")
}
@Test
- public void shouldMatchWithStandardPatterns() throws IOException {
+ public void shouldMatchWithStandardPatterns() {
patternMatcher.addPatternForComponent(JAVA_FILE, createPattern("org.foo.Hello;checkstyle:MagicNumber;[15-200]"));
assertThat(patternMatcher.getMatchingPattern(create(CHECKSTYLE_RULE, JAVA_FILE, 150))).isNotNull();
}
@Test
- public void shouldNotMatchWithStandardPatterns() throws IOException {
+ public void shouldNotMatchWithStandardPatterns() {
patternMatcher.addPatternForComponent(JAVA_FILE, createPattern("org.foo.Hello;checkstyle:MagicNumber;[15-200]"));
assertThat(patternMatcher.getMatchingPattern(create(CHECKSTYLE_RULE, JAVA_FILE, 5))).isNull();
}
@Test
- public void shouldMatchWithExtraPattern() throws IOException {
+ public void shouldMatchWithExtraPattern() {
patternMatcher.addPatternForComponent(JAVA_FILE, createPattern("org.foo.Hello;*;[15-200]"));
assertThat(patternMatcher.getMatchingPattern(create(CHECKSTYLE_RULE, JAVA_FILE, 150))).isNotNull();
}
@Test
- public void shouldNotMatchWithExtraPattern() throws IOException {
+ public void shouldNotMatchWithExtraPattern() {
patternMatcher.addPatternForComponent(JAVA_FILE, createPattern("org.foo.Hello;*;[15-200]"));
assertThat(patternMatcher.getMatchingPattern(create(CHECKSTYLE_RULE, JAVA_FILE, 5))).isNull();
}
@Test
- public void shouldExecute() throws IOException {
+ public void shouldExecute() {
when(exclusionPatternInitializer.hasConfiguredPatterns()).thenReturn(true);
when(inclusionPatternInitializer.hasConfiguredPatterns()).thenReturn(true);
assertThat(scanner.shouldExecuteOnProject(null)).isTrue();
}
@Test
- public void shouldAnalyseFilesOnlyWhenRegexConfigured() throws IOException {
+ public void shouldAnalyseFilesOnlyWhenRegexConfigured() {
File javaFile1 = new File(baseDir, "src/main/java/Foo.java");
fs.add(new DeprecatedDefaultInputFile("polop", "src/main/java/Foo.java")
.setType(InputFile.Type.MAIN));
Caches caches;
@Before
- public void before() throws Exception {
+ public void before() {
caches = createCacheOnTemp(temp);
caches.start();
stack = new InitialOpenIssuesStack(caches);
public class IssueHandlersTest {
@Test
- public void should_execute_handlers() throws Exception {
+ public void should_execute_handlers() {
IssueHandler h1 = mock(IssueHandler.class);
IssueHandler h2 = mock(IssueHandler.class);
IssueUpdater updater = mock(IssueUpdater.class);
}
@Test
- public void should_not_be_executed_on_classes_not_methods() throws Exception {
+ public void should_not_be_executed_on_classes_not_methods() {
DecoratorContext context = mock(DecoratorContext.class);
decorator.decorate(JavaClass.create("org.foo.Bar"), context);
verifyZeroInteractions(context, issueCache, tracking, handlers, workflow);
}
@Test
- public void should_process_open_issues() throws Exception {
+ public void should_process_open_issues() {
Resource file = File.create("Action.java").setEffectiveKey("struts:Action.java").setId(123);
final DefaultIssue issue = new DefaultIssue();
}
@Test
- public void should_register_unmatched_issues_as_end_of_life() throws Exception {
+ public void should_register_unmatched_issues_as_end_of_life() {
// "Unmatched" issues existed in previous scan but not in current one -> they have to be closed
Resource file = File.create("Action.java").setEffectiveKey("struts:Action.java").setId(123);
}
@Test
- public void should_register_issues_on_deleted_components() throws Exception {
+ public void should_register_issues_on_deleted_components() {
Project project = new Project("struts");
DefaultIssue openIssue = new DefaultIssue();
when(issueCache.byComponent("struts")).thenReturn(Arrays.asList(openIssue));
}
@Test
- public void merge_matched_issue() throws Exception {
+ public void merge_matched_issue() {
ServerIssue previousIssue = new ServerIssueFromDb(new IssueDto().setKee("ABCDE").setResolution(null).setStatus("OPEN").setRuleKey("squid", "AvoidCycle")
.setLine(10).setSeverity("MAJOR").setMessage("Message").setEffortToFix(1.5).setDebt(1L).setProjectKey("sample"));
DefaultIssue issue = new DefaultIssue();
}
@Test
- public void merge_matched_issue_on_manual_severity() throws Exception {
+ public void merge_matched_issue_on_manual_severity() {
ServerIssue previousIssue = new ServerIssueFromDb(new IssueDto().setKee("ABCDE").setResolution(null).setStatus("OPEN").setRuleKey("squid", "AvoidCycle")
.setLine(10).setManualSeverity(true).setSeverity("MAJOR").setMessage("Message").setEffortToFix(1.5).setDebt(1L));
DefaultIssue issue = new DefaultIssue();
}
@Test
- public void merge_issue_changelog_with_previous_changelog() throws Exception {
+ public void merge_issue_changelog_with_previous_changelog() {
when(initialOpenIssues.selectChangelog("ABCDE")).thenReturn(newArrayList(new IssueChangeDto().setIssueKey("ABCD").setCreatedAt(System2.INSTANCE.now())));
ServerIssue previousIssue = new ServerIssueFromDb(new IssueDto().setKee("ABCDE").setResolution(null).setStatus("OPEN").setRuleKey("squid", "AvoidCycle")
}
@Test
- public void dont_load_checksum_if_no_new_issue() throws Exception {
+ public void dont_load_checksum_if_no_new_issue() {
sourceHashHolder = mock(SourceHashHolder.class);
ServerIssue referenceIssue = newReferenceIssue("2 branches need to be covered", null, "squid", "AvoidCycle", null);
LanguageDistributionDecorator decorator;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
decorator = new LanguageDistributionDecorator();
}
public ExpectedException thrown = ExpectedException.none();
@Test
- public void bootstrap() throws Exception {
+ public void bootstrap() {
ProjectDefinition def = mock(ProjectDefinition.class);
MavenSession session = mock(MavenSession.class);
MavenProject rootProject = new MavenProject();
}
@Test
- public void should_fail_if_no_top_level_project() throws Exception {
+ public void should_fail_if_no_top_level_project() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Maven session does not declare a top level project");
// SONAR-5330
@Test
- public void scanProjectWithSourceSymlink() throws Exception {
+ public void scanProjectWithSourceSymlink() {
if (!System2.INSTANCE.isOsWindows()) {
File projectDir = new File("src/test/resources/mediumtest/xoo/sample-with-symlink");
TaskResult result = tester
private AnalysisMode analysisMode;
@Before
- public void prepare() throws Exception {
+ public void prepare() {
settings = new Settings();
analysisMode = mock(AnalysisMode.class);
optimizer = new PostJobOptimizer(settings, analysisMode);
}
@Test
- public void should_run_analyzer_with_no_metadata() throws Exception {
+ public void should_run_analyzer_with_no_metadata() {
DefaultPostJobDescriptor descriptor = new DefaultPostJobDescriptor();
assertThat(optimizer.shouldExecute(descriptor)).isTrue();
}
@Test
- public void should_optimize_on_settings() throws Exception {
+ public void should_optimize_on_settings() {
DefaultPostJobDescriptor descriptor = new DefaultPostJobDescriptor()
.requireProperty("sonar.foo.reportPath");
assertThat(optimizer.shouldExecute(descriptor)).isFalse();
}
@Test
- public void should_disabled_in_preview() throws Exception {
+ public void should_disabled_in_preview() {
DefaultPostJobDescriptor descriptor = new DefaultPostJobDescriptor()
.disabledInPreview();
assertThat(optimizer.shouldExecute(descriptor)).isTrue();
return project;
}
- private void fakeAnalysis(PhasesSumUpTimeProfiler profiler, final Project module) throws InterruptedException {
+ private void fakeAnalysis(PhasesSumUpTimeProfiler profiler, final Project module) {
// Start of moduleA
profiler.onProjectAnalysis(projectEvent(module, true));
initializerPhase(profiler);
profiler.onProjectAnalysis(projectEvent(module, false));
}
- private void decoratorPhase(PhasesSumUpTimeProfiler profiler) throws InterruptedException {
+ private void decoratorPhase(PhasesSumUpTimeProfiler profiler) {
Decorator decorator1 = new FakeDecorator1();
Decorator decorator2 = new FakeDecorator2();
// Start of decorator phase
profiler.onDecoratorsPhase(decoratorsEvent(false));
}
- private void batchStep(PhasesSumUpTimeProfiler profiler) throws InterruptedException {
+ private void batchStep(PhasesSumUpTimeProfiler profiler) {
// Start of batch step
profiler.onBatchStep(new BatchStepEvent("Free memory", true));
clock.sleep(9);
profiler.onBatchStep(new BatchStepEvent("Free memory", false));
}
- private void initializerPhase(PhasesSumUpTimeProfiler profiler) throws InterruptedException {
+ private void initializerPhase(PhasesSumUpTimeProfiler profiler) {
Initializer initializer = new FakeInitializer();
// Start of initializer phase
profiler.onInitializersPhase(initializersEvent(true));
profiler.onInitializersPhase(initializersEvent(false));
}
- private void sensorPhase(PhasesSumUpTimeProfiler profiler) throws InterruptedException {
+ private void sensorPhase(PhasesSumUpTimeProfiler profiler) {
Sensor sensor = new FakeSensor();
// Start of sensor phase
profiler.onSensorsPhase(sensorsEvent(true));
profiler.onSensorsPhase(sensorsEvent(false));
}
- private void persistersPhase(PhasesSumUpTimeProfiler profiler) throws InterruptedException {
+ private void persistersPhase(PhasesSumUpTimeProfiler profiler) {
ScanPersister persister = new FakeScanPersister();
// Start of persister phase
profiler.onPersistersPhase(persistersEvent(true));
profiler.onPersistersPhase(persistersEvent(false));
}
- private void postJobPhase(PhasesSumUpTimeProfiler profiler) throws InterruptedException {
+ private void postJobPhase(PhasesSumUpTimeProfiler profiler) {
PostJob postJob = new FakePostJob();
// Start of sensor phase
profiler.onPostJobsPhase(postJobsEvent(true));
}
@Test
- public void should_be_executed_if_quality_gate_is_enabled() throws Exception {
+ public void should_be_executed_if_quality_gate_is_enabled() {
assertThat(verifier.shouldExecuteOnProject((Project) project)).isTrue();
when(qualityGate.isEnabled()).thenReturn(false);
assertThat(verifier.shouldExecuteOnProject((Project) project)).isFalse();
}
@Test
- public void should_log_successful_analysis() throws Exception {
+ public void should_log_successful_analysis() {
Settings settings = new Settings();
settings.setProperty(CoreProperties.SERVER_BASE_URL, "http://myserver/");
ReportPublisher job = new ReportPublisher(settings, mock(ServerClient.class), mock(Server.class), reactor, mode, mock(TempFolder.class), new ReportPublisherStep[0]);
}
@Test
- public void should_log_successful_preview_analysis() throws Exception {
+ public void should_log_successful_preview_analysis() {
Settings settings = new Settings();
when(mode.isPreview()).thenReturn(true);
ReportPublisher job = new ReportPublisher(settings, mock(ServerClient.class), mock(Server.class), reactor, mode, mock(TempFolder.class), new ReportPublisherStep[0]);
DecoratorContext decoratorContext = mock(DecoratorContext.class);
@Test
- public void don_t_run_on_leaf() throws Exception {
+ public void don_t_run_on_leaf() {
QProfileDecorator decorator = new QProfileDecorator();
when(project.getModules()).thenReturn(Collections.<Project>emptyList());
assertThat(decorator.shouldExecuteOnProject(project)).isFalse();
}
@Test
- public void aggregate() throws Exception {
+ public void aggregate() {
Measure measureModuleA = new Measure(CoreMetrics.QUALITY_PROFILES, "[" + JAVA_JSON + "]");
Measure measureModuleB = new Measure(CoreMetrics.QUALITY_PROFILES, "[" + JAVA_JSON + "]");
Measure measureModuleC = new Measure(CoreMetrics.QUALITY_PROFILES, "[" + PHP_JSON + "]");
}
@Test
- public void aggregate_different_profiles_with_same_language() throws Exception {
+ public void aggregate_different_profiles_with_same_language() {
Measure measureModuleA = new Measure(CoreMetrics.QUALITY_PROFILES, "[" + JAVA_JSON + "]");
Measure measureModuleB = new Measure(CoreMetrics.QUALITY_PROFILES, "[" + JAVA2_JSON + "]");
when(decoratorContext.getChildrenMeasures(CoreMetrics.QUALITY_PROFILES)).thenReturn(Arrays.asList(measureModuleA, measureModuleB));
}
@Test
- public void to_string() throws Exception {
+ public void to_string() {
QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs, mock(AnalysisMode.class));
assertThat(sensor.toString()).isEqualTo("QProfileSensor");
}
@Test
- public void no_execution_in_preview() throws Exception {
+ public void no_execution_in_preview() {
AnalysisMode analysisMode = mock(AnalysisMode.class);
when(analysisMode.isPreview()).thenReturn(true);
QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs, analysisMode);
}
@Test
- public void no_qprofiles() throws Exception {
+ public void no_qprofiles() {
when(moduleQProfiles.findAll()).thenReturn(Collections.<QProfile>emptyList());
QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs, mock(AnalysisMode.class));
}
@Test
- public void mark_profiles_as_used() throws Exception {
+ public void mark_profiles_as_used() {
when(moduleQProfiles.findByLanguage("java")).thenReturn(JAVA_PROFILE);
when(moduleQProfiles.findByLanguage("php")).thenReturn(PHP_PROFILE);
when(moduleQProfiles.findByLanguage("abap")).thenReturn(null);
}
@Test
- public void store_measures_on_single_lang_module() throws Exception {
+ public void store_measures_on_single_lang_module() {
when(moduleQProfiles.findByLanguage("java")).thenReturn(JAVA_PROFILE);
when(moduleQProfiles.findByLanguage("php")).thenReturn(PHP_PROFILE);
when(moduleQProfiles.findByLanguage("abap")).thenReturn(null);
}
@Test
- public void store_measures_on_multi_lang_module() throws Exception {
+ public void store_measures_on_multi_lang_module() {
when(moduleQProfiles.findByLanguage("java")).thenReturn(JAVA_PROFILE);
when(moduleQProfiles.findByLanguage("php")).thenReturn(PHP_PROFILE);
when(moduleQProfiles.findByLanguage("abap")).thenReturn(null);
RulesProfileProvider provider = new RulesProfileProvider();
@Test
- public void merge_profiles() throws Exception {
+ public void merge_profiles() {
QProfile qProfile = new QProfile().setKey("java-sw").setName("Sonar way").setLanguage("java");
when(qProfiles.findAll()).thenReturn(Arrays.asList(qProfile));
}
@Test
- public void keep_compatibility_with_single_language_projects() throws Exception {
+ public void keep_compatibility_with_single_language_projects() {
settings.setProperty("sonar.language", "java");
QProfile qProfile = new QProfile().setKey("java-sw").setName("Sonar way").setLanguage("java");
RulesProvider provider;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
debtModel = new DefaultDebtModel()
.addCharacteristic(new DefaultDebtCharacteristic()
.setId(100)
}
@Test
- public void build_rules() throws Exception {
+ public void build_rules() {
setupData("shared");
Rules rules = provider.provide(ruleDao, debtModel, durations);
}
@Test
- public void build_rules_with_default_debt_definitions() throws Exception {
+ public void build_rules_with_default_debt_definitions() {
setupData("build_rules_with_default_debt_definitions");
Rules rules = provider.provide(ruleDao, debtModel, durations);
}
@Test
- public void build_rules_with_overridden_debt_definitions() throws Exception {
+ public void build_rules_with_overridden_debt_definitions() {
setupData("build_rules_with_overridden_debt_definitions");
Rules rules = provider.provide(ruleDao, debtModel, durations);
}
@Test
- public void build_rules_with_default_and_overridden_debt_definitions() throws Exception {
+ public void build_rules_with_default_and_overridden_debt_definitions() {
setupData("build_rules_with_default_and_overridden_debt_definitions");
Rules rules = provider.provide(ruleDao, debtModel, durations);
}
@Test
- public void build_rules_with_default_characteristic_and_overridden_function() throws Exception {
+ public void build_rules_with_default_characteristic_and_overridden_function() {
setupData("build_rules_with_default_characteristic_and_overridden_function");
Rules rules = provider.provide(ruleDao, debtModel, durations);
}
@Test
- public void build_rules_with_overridden_characteristic_and_default_function() throws Exception {
+ public void build_rules_with_overridden_characteristic_and_default_function() {
setupData("build_rules_with_overridden_characteristic_and_default_function");
Rules rules = provider.provide(ruleDao, debtModel, durations);
}
@Test
- public void build_rules_with_disable_characteristic() throws Exception {
+ public void build_rules_with_disable_characteristic() {
setupData("build_rules_with_disable_characteristic");
Rules rules = provider.provide(ruleDao, debtModel, durations);
}
@Test
- public void build_rules_with_default_characteristic_and_disable_characteristic() throws Exception {
+ public void build_rules_with_default_characteristic_and_disable_characteristic() {
setupData("build_rules_with_default_characteristic_and_disable_characteristic");
Rules rules = provider.provide(ruleDao, debtModel, durations);
}
@Test
- public void fail_if_characteristic_not_found() throws Exception {
+ public void fail_if_characteristic_not_found() {
setupData("fail_if_characteristic_not_found");
try {
}
@Test
- public void fail_if_no_function() throws Exception {
+ public void fail_if_no_function() {
setupData("fail_if_no_function");
try {
static final String PHP_JSON = "{\"key\":\"p2\",\"language\":\"php\",\"name\":\"Sonar Way\",\"rulesUpdatedAt\":\"2014-02-20T00:00:00+0000\"}";
@Test
- public void from_and_to_json() throws Exception {
+ public void from_and_to_json() {
QProfile java = new QProfile().setKey("p1").setName("Sonar Way").setLanguage("java")
.setRulesUpdatedAt(UtcDateUtils.parseDateTime("2014-01-15T00:00:00+0000"));
QProfile php = new QProfile().setKey("p2").setName("Sonar Way").setLanguage("php")
}
@Test
- public void do_not_duplicate_profiles() throws Exception {
+ public void do_not_duplicate_profiles() {
QProfile java = new QProfile().setKey("p1").setName("Sonar Way").setLanguage("java");
QProfile php = new QProfile().setKey("p2").setName("Sonar Way").setLanguage("php");
}
@Test
- public void group_profiles_by_key() throws Exception {
+ public void group_profiles_by_key() {
QProfile java = new QProfile().setKey("p1").setName("Sonar Way").setLanguage("java");
QProfile php = new QProfile().setKey("p2").setName("Sonar Way").setLanguage("php");
}
@Test
- public void shouldFailIfUnexistingModuleFile() throws IOException {
+ public void shouldFailIfUnexistingModuleFile() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("The properties file of the module 'module1' does not exist: "
+ TestUtils.getResource(this.getClass(), "multi-module-with-unexisting-file").getAbsolutePath() + File.separator + "any-folder"
loadProjectDefinition("multi-module-with-unexisting-file");
}
- private ProjectDefinition loadProjectDefinition(String projectFolder) throws IOException {
+ private ProjectDefinition loadProjectDefinition(String projectFolder) {
Map<String, String> props = Maps.<String, String>newHashMap();
Properties runnerProps = ProjectReactorBuilder.toProperties(TestUtils.getResource(this.getClass(), projectFolder + "/sonar-project.properties"));
for (final String name : runnerProps.stringPropertyNames()) {
}
@Test
- public void language_is_not_set() throws Exception {
+ public void language_is_not_set() {
LanguageVerifier verifier = new LanguageVerifier(settings, languages, fs);
verifier.start();
}
@Test
- public void language_is_valid() throws Exception {
+ public void language_is_valid() {
settings.setProperty("sonar.language", "java");
LanguageVerifier verifier = new LanguageVerifier(settings, languages, fs);
}
@Test
- public void language_is_not_valid() throws Exception {
+ public void language_is_not_valid() {
thrown.expect(MessageException.class);
thrown.expectMessage("You must install a plugin that supports the language 'php'");
public ExpectedException thrown = ExpectedException.none();
@Test
- public void shouldDefineSimpleProject() throws IOException {
+ public void shouldDefineSimpleProject() {
ProjectDefinition projectDefinition = loadProjectDefinition("simple-project");
assertThat(projectDefinition.getKey()).isEqualTo("com.foo.project");
}
@Test
- public void shouldFailIfUnexistingSourceDirectory() throws IOException {
+ public void shouldFailIfUnexistingSourceDirectory() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("The folder 'unexisting-source-dir' does not exist for 'com.foo.project' (base directory = "
+ TestUtils.getResource(this.getClass(), "simple-project-with-unexisting-source-dir") + ")");
}
@Test
- public void fail_if_sources_not_set() throws IOException {
+ public void fail_if_sources_not_set() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("You must define the following mandatory properties for 'com.foo.project': sonar.sources");
loadProjectDefinition("simple-project-with-missing-source-dir");
}
@Test
- public void shouldNotFailIfBlankSourceDirectory() throws IOException {
+ public void shouldNotFailIfBlankSourceDirectory() {
loadProjectDefinition("simple-project-with-blank-source-dir");
}
// SONAR-4876
@Test
- public void shouldDefineMultiModuleProjectWithModuleKey() throws IOException {
+ public void shouldDefineMultiModuleProjectWithModuleKey() {
ProjectDefinition rootProject = loadProjectDefinition("multi-module-definitions-moduleKey");
// CHECK ROOT
}
@Test
- public void shouldDefineMultiModuleProjectWithBaseDir() throws IOException {
+ public void shouldDefineMultiModuleProjectWithBaseDir() {
ProjectDefinition rootProject = loadProjectDefinition("multi-module-with-basedir");
List<ProjectDefinition> modules = rootProject.getSubProjects();
assertThat(modules.size()).isEqualTo(1);
}
@Test
- public void shouldFailIfUnexistingModuleBaseDir() throws IOException {
+ public void shouldFailIfUnexistingModuleBaseDir() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("The base directory of the module 'module1' does not exist: "
+ TestUtils.getResource(this.getClass(), "multi-module-with-unexisting-basedir").getAbsolutePath() + File.separator + "module1");
}
@Test
- public void shouldFailIfUnexistingSourceFolderInheritedInMultimodule() throws IOException {
+ public void shouldFailIfUnexistingSourceFolderInheritedInMultimodule() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("The folder 'unexisting-source-dir' does not exist for 'com.foo.project:module1' (base directory = "
+ TestUtils.getResource(this.getClass(), "multi-module-with-unexisting-source-dir").getAbsolutePath() + File.separator + "module1)");
}
@Test
- public void shouldNotFailIfUnexistingTestBinLibFolderInheritedInMultimodule() throws IOException {
+ public void shouldNotFailIfUnexistingTestBinLibFolderInheritedInMultimodule() {
loadProjectDefinition("multi-module-with-unexisting-test-bin-lib-dir");
}
@Test
- public void shouldFailIfExplicitUnexistingTestFolder() throws IOException {
+ public void shouldFailIfExplicitUnexistingTestFolder() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("The folder 'tests' does not exist for 'com.foo.project' (base directory = "
+ TestUtils.getResource(this.getClass(), "simple-project-with-unexisting-test-dir").getAbsolutePath());
}
@Test
- public void shouldFailIfExplicitUnexistingBinaryFolder() throws IOException {
+ public void shouldFailIfExplicitUnexistingBinaryFolder() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("The folder 'bin' does not exist for 'com.foo.project' (base directory = "
+ TestUtils.getResource(this.getClass(), "simple-project-with-unexisting-binary").getAbsolutePath());
}
@Test
- public void shouldFailIfExplicitUnmatchingLibFolder() throws IOException {
+ public void shouldFailIfExplicitUnmatchingLibFolder() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("No files nor directories matching 'libs/*.txt' in directory "
+ TestUtils.getResource(this.getClass(), "simple-project-with-unexisting-lib").getAbsolutePath());
}
@Test
- public void shouldGetLibDirectory() throws IOException {
+ public void shouldGetLibDirectory() {
ProjectDefinition def = loadProjectDefinition("simple-project-with-lib-dir");
assertThat(def.getLibraries()).hasSize(1);
File libDir = new File(def.getLibraries().get(0));
}
@Test
- public void shouldFailIfExplicitUnexistingTestFolderOnModule() throws IOException {
+ public void shouldFailIfExplicitUnexistingTestFolderOnModule() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("The folder 'tests' does not exist for 'module1' (base directory = "
+ TestUtils.getResource(this.getClass(), "multi-module-with-explicit-unexisting-test-dir").getAbsolutePath() + File.separator + "module1)");
}
@Test
- public void shouldFailIfExplicitUnexistingBinaryFolderOnModule() throws IOException {
+ public void shouldFailIfExplicitUnexistingBinaryFolderOnModule() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("The folder 'bin' does not exist for 'module1' (base directory = "
+ TestUtils.getResource(this.getClass(), "multi-module-with-explicit-unexisting-binary-dir").getAbsolutePath() + File.separator + "module1)");
}
@Test
- public void shouldFailIfExplicitUnmatchingLibFolderOnModule() throws IOException {
+ public void shouldFailIfExplicitUnmatchingLibFolderOnModule() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("No files nor directories matching 'lib/*.jar' in directory "
+ TestUtils.getResource(this.getClass(), "multi-module-with-explicit-unexisting-lib").getAbsolutePath() + File.separator + "module1");
}
@Test
- public void multiModuleProperties() throws IOException {
+ public void multiModuleProperties() {
ProjectDefinition projectDefinition = loadProjectDefinition("big-multi-module-definitions-all-in-root");
assertThat(projectDefinition.getProperties().getProperty("module11.property")).isNull();
}
@Test
- public void shouldFilterFiles() throws Exception {
+ public void shouldFilterFiles() {
File baseDir = TestUtils.getResource(this.getClass(), "shouldFilterFiles");
assertThat(ProjectReactorBuilder.getLibraries(baseDir, "in*.txt")).hasSize(1);
assertThat(ProjectReactorBuilder.getLibraries(baseDir, "*.txt")).hasSize(2);
}
@Test
- public void shouldWorkWithAbsolutePath() throws Exception {
+ public void shouldWorkWithAbsolutePath() {
File baseDir = new File("not-exists");
String absolutePattern = TestUtils.getResource(this.getClass(), "shouldFilterFiles").getAbsolutePath() + "/in*.txt";
assertThat(ProjectReactorBuilder.getLibraries(baseDir.getParentFile(), absolutePattern)).hasSize(1);
}
@Test
- public void shouldFailToLoadPropertiesFile() throws Exception {
+ public void shouldFailToLoadPropertiesFile() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Impossible to read the property file");
ProjectReactorBuilder.toProperties(new File("foo.properties"));
}
- private ProjectDefinition loadProjectDefinition(String projectFolder) throws IOException {
+ private ProjectDefinition loadProjectDefinition(String projectFolder) {
Map<String, String> props = loadProps(projectFolder);
TaskProperties bootstrapProps = new TaskProperties(props, null);
ProjectReactor projectReactor = new ProjectReactorBuilder(bootstrapProps).execute();
}
@Test
- public void shouldDefineProjectWithBuildDir() throws IOException {
+ public void shouldDefineProjectWithBuildDir() {
ProjectDefinition rootProject = loadProjectDefinition("simple-project-with-build-dir");
File buildDir = rootProject.getBuildDir();
assertThat(buildDir).isDirectory().exists();
}
@Test
- public void not_fail_if_provisioning_enforced_and_project_exists() throws Exception {
+ public void not_fail_if_provisioning_enforced_and_project_exists() {
String key = "project-key";
settings.setProperty(CoreProperties.CORE_PREVENT_AUTOMATIC_PROJECT_CREATION, true);
when(resourceDao.findByKey(key)).thenReturn(mock(Component.class));
}
@Test
- public void not_fail_if_provisioning_enforced_and_project_with_branch_exists() throws Exception {
+ public void not_fail_if_provisioning_enforced_and_project_with_branch_exists() {
String key = "project-key";
settings.setProperty(CoreProperties.CORE_PREVENT_AUTOMATIC_PROJECT_CREATION, true);
when(resourceDao.findByKey(key + ":branch")).thenReturn(mock(Component.class));
}
@Test(expected = SonarException.class)
- public void fail_if_provisioning_enforced_and_project_not_provisioned() throws Exception {
+ public void fail_if_provisioning_enforced_and_project_not_provisioned() {
String key = "project-key";
settings.setProperty(CoreProperties.CORE_PREVENT_AUTOMATIC_PROJECT_CREATION, true);
when(resourceDao.findByKey(key)).thenReturn(null);
// SONAR-4692
@Test(expected = SonarException.class)
- public void fail_if_module_part_of_another_project() throws Exception {
+ public void fail_if_module_part_of_another_project() {
String rootProjectKey = "project-key";
String moduleKey = "module-key";
ResourceDto rootResource = mock(ResourceDto.class);
// SONAR-4692
@Test
- public void not_fail_if_module_part_of_same_project() throws Exception {
+ public void not_fail_if_module_part_of_same_project() {
String rootProjectKey = "project-key";
String moduleKey = "module-key";
ResourceDto rootResource = mock(ResourceDto.class);
// SONAR-4692
@Test
- public void not_fail_if_new_module() throws Exception {
+ public void not_fail_if_new_module() {
String rootProjectKey = "project-key";
String moduleKey = "module-key";
public TemporaryFolder temp = new TemporaryFolder();
@Test
- public void key() throws Exception {
+ public void key() {
FilePredicate predicate = new AdditionalFilePredicates.KeyPredicate("struts:Action.java");
DefaultInputFile inputFile = new DeprecatedDefaultInputFile("struts", "Action.java");
}
@Test
- public void should_index() throws Exception {
+ public void should_index() {
DefaultModuleFileSystem fs = new DefaultModuleFileSystem(moduleInputFileCache,
new Project("foo"), settings, fileIndexer, initializer, componentIndexer);
FileSystemFilter filter = mock(FileSystemFilter.class);
@Test
- public void no_filters() throws Exception {
+ public void no_filters() {
DeprecatedFileFilters filters = new DeprecatedFileFilters();
InputFile inputFile = new DeprecatedDefaultInputFile("foo", "src/main/java/Foo.java");
}
@Test
- public void trim_pattern() throws IOException {
+ public void trim_pattern() {
Settings settings = new Settings();
settings.setProperty(CoreProperties.PROJECT_EXCLUSIONS_PROPERTY, " **/*Dao.java ");
ExclusionFilters filter = new ExclusionFilters(new FileExclusions(settings));
public class InputFileBuilderFactoryTest {
@Test
- public void create_builder() throws Exception {
+ public void create_builder() {
PathResolver pathResolver = new PathResolver();
LanguageDetectionFactory langDetectionFactory = mock(LanguageDetectionFactory.class, Mockito.RETURNS_MOCKS);
StatusDetectionFactory statusDetectionFactory = mock(StatusDetectionFactory.class, Mockito.RETURNS_MOCKS);
public TemporaryFolder temp = new TemporaryFolder();
@Before
- public void start() throws Exception {
+ public void start() {
}
@After
}
@Test
- public void fail_if_invalid_language() throws Exception {
+ public void fail_if_invalid_language() {
thrown.expect(MessageException.class);
thrown.expectMessage("No language is installed with key 'unknown'. Please update property 'sonar.language'");
public class StatusDetectionTest {
@Test
- public void detect_status() throws Exception {
+ public void detect_status() {
ProjectRepositories ref = new ProjectRepositories();
ref.addFileData("foo", "src/Foo.java", new FileData("ABCDE", true));
ref.addFileData("foo", "src/Bar.java", new FileData("FGHIJ", true));
private MeasureCache cache;
@Before
- public void start() throws Exception {
+ public void start() {
caches = CachesTest.createCacheOnTemp(temp);
caches.start();
metricFinder = mock(MetricFinder.class);
}
@Test
- public void should_add_measure() throws Exception {
+ public void should_add_measure() {
Project p = new Project("struts");
assertThat(cache.entries()).hasSize(0);
}
@Test
- public void should_add_measure_with_big_data() throws Exception {
+ public void should_add_measure_with_big_data() {
Project p = new Project("struts");
assertThat(cache.entries()).hasSize(0);
* This test fails with stock PersisitIt.
*/
@Test
- public void should_add_measure_with_too_big_data_for_persistit_pre_patch() throws Exception {
+ public void should_add_measure_with_too_big_data_for_persistit_pre_patch() {
Project p = new Project("struts");
assertThat(cache.entries()).hasSize(0);
}
@Test
- public void should_add_measure_with_too_big_data_for_persistit() throws Exception {
+ public void should_add_measure_with_too_big_data_for_persistit() {
Project p = new Project("struts");
assertThat(cache.entries()).hasSize(0);
}
@Test
- public void should_add_measure_with_same_metric() throws Exception {
+ public void should_add_measure_with_same_metric() {
Project p = new Project("struts");
assertThat(cache.entries()).hasSize(0);
}
@Test
- public void should_get_measures() throws Exception {
+ public void should_get_measures() {
Project p = new Project("struts");
Resource dir = Directory.create("foo/bar").setEffectiveKey("struts:foo/bar");
Resource file1 = Directory.create("foo/bar/File1.txt").setEffectiveKey("struts:foo/bar/File1.txt");
}
@Test
- public void should_run_analyzer_with_no_metadata() throws Exception {
+ public void should_run_analyzer_with_no_metadata() {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor();
assertThat(optimizer.shouldExecute(descriptor)).isTrue();
}
@Test
- public void should_optimize_on_language() throws Exception {
+ public void should_optimize_on_language() {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor()
.onlyOnLanguages("java", "php");
assertThat(optimizer.shouldExecute(descriptor)).isFalse();
}
@Test
- public void should_optimize_on_type() throws Exception {
+ public void should_optimize_on_type() {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor()
.onlyOnFileType(InputFile.Type.MAIN);
assertThat(optimizer.shouldExecute(descriptor)).isFalse();
}
@Test
- public void should_optimize_on_both_type_and_language() throws Exception {
+ public void should_optimize_on_both_type_and_language() {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor()
.onlyOnLanguages("java", "php")
.onlyOnFileType(InputFile.Type.MAIN);
}
@Test
- public void should_optimize_on_repository() throws Exception {
+ public void should_optimize_on_repository() {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor()
.createIssuesForRuleRepositories("squid");
assertThat(optimizer.shouldExecute(descriptor)).isFalse();
}
@Test
- public void should_optimize_on_settings() throws Exception {
+ public void should_optimize_on_settings() {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor()
.requireProperty("sonar.foo.reportPath");
assertThat(optimizer.shouldExecute(descriptor)).isFalse();
}
@Test
- public void should_disabled_in_preview() throws Exception {
+ public void should_disabled_in_preview() {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor()
.disabledInPreview();
assertThat(optimizer.shouldExecute(descriptor)).isTrue();
public ExpectedException throwable = ExpectedException.none();
@Test
- public void should_store_highlighting_rules() throws Exception {
+ public void should_store_highlighting_rules() {
SensorStorage sensorStorage = mock(SensorStorage.class);
DefaultInputFile inputFile = new DefaultInputFile("foo", "src/Foo.php")
.initMetadata(new FileMetadata().readMetadata(new StringReader("azerty\nbla bla")));
}
@Test
- public void should_order_symbol_and_references() throws Exception {
+ public void should_order_symbol_and_references() {
Symbolizable.SymbolTableBuilder symbolTableBuilder = new DefaultSymbolTable.Builder(inputFile);
Symbol firstSymbol = symbolTableBuilder.newSymbol(10, 20);
}
@Test
- public void should_reject_reference_conflicting_with_declaration() throws Exception {
+ public void should_reject_reference_conflicting_with_declaration() {
throwable.expect(UnsupportedOperationException.class);
Symbolizable.SymbolTableBuilder symbolTableBuilder = new DefaultSymbolTable.Builder(inputFile);
public class DefaultSymbolizableTest {
@Test
- public void should_update_cache_when_done() throws Exception {
+ public void should_update_cache_when_done() {
DefaultSensorStorage sensorStorage = mock(DefaultSensorStorage.class);
DefaultInputFile inputFile = new DefaultInputFile("foo", "src/Foo.php")
public class HighlightableBuilderTest {
@Test
- public void should_load_default_perspective() throws Exception {
+ public void should_load_default_perspective() {
Resource file = File.create("foo.c").setEffectiveKey("myproject:path/to/foo.c");
Component component = new ResourceComponent(file);
public class SymbolizableBuilderTest {
@Test
- public void should_load_perspective() throws Exception {
+ public void should_load_perspective() {
Resource file = File.create("foo.c").setEffectiveKey("myproject:path/to/foo.c");
Component component = new ResourceComponent(file);
public class UtcDateUtilsTest {
@Test
- public void parse_then_format() throws Exception {
+ public void parse_then_format() {
Date date = UtcDateUtils.parseDateTime("2014-01-14T14:00:00+0200");
assertThat(UtcDateUtils.formatDateTime(date)).isEqualTo("2014-01-14T12:00:00+0000");
}
@Test
- public void fail_if_bad_format() throws Exception {
+ public void fail_if_bad_format() {
try {
UtcDateUtils.parseDateTime("2014-01-14");
fail();
public class ComponentDtoTest {
@Test
- public void setters_and_getters() throws Exception {
+ public void setters_and_getters() {
ComponentDto componentDto = new ComponentDto()
.setId(1L)
.setKey("org.struts:struts-core:src/org/struts/RequestContext.java")
}
@Test
- public void equals_and_hashcode() throws Exception {
+ public void equals_and_hashcode() {
ComponentDto dto = new ComponentDto().setId(1L);
ComponentDto dtoWithSameId = new ComponentDto().setId(1L);
ComponentDto dtoWithDifferentId = new ComponentDto().setId(2L);
}
@Test
- public void toString_does_not_fail_if_empty() throws Exception {
+ public void toString_does_not_fail_if_empty() {
ComponentDto dto = new ComponentDto();
assertThat(dto.toString()).isNotEmpty();
}
@Test
- public void is_root_project() throws Exception {
+ public void is_root_project() {
assertThat(new ComponentDto().setModuleUuid("ABCD").isRootProject()).isFalse();
assertThat(new ComponentDto().setModuleUuid("ABCD").setScope(Scopes.DIRECTORY).isRootProject()).isFalse();
assertThat(new ComponentDto().setModuleUuid(null).setScope(Scopes.PROJECT).setQualifier(Qualifiers.PROJECT).isRootProject()).isTrue();
public class GraphPerspectiveBuilderTest {
@Test
- public void should_return_null_on_null_component() throws Exception {
+ public void should_return_null_on_null_component() {
String componentKey = "org.foo.Bar";
}
@Test
- public void should_load_perspective() throws Exception {
+ public void should_load_perspective() {
ScanGraph graph = ScanGraph.create();
MutablePerspective expectedPerspective = mock(MutablePerspective.class);
}
@Test
- public void should_create_perspective_when_loaded_one_is_null() throws Exception {
+ public void should_create_perspective_when_loaded_one_is_null() {
String perspectiveKey = "perspectiveKey";
private PurgeProfiler profiler;
@Before
- public void before() throws Exception {
+ public void before() {
this.purgeDao = mock(PurgeDao.class);
this.resourceDao = mock(ResourceDao.class);
when(resourceDao.getResource(anyLong())).thenReturn(new ResourceDto().setQualifier(Qualifiers.PROJECT).setUuid("1").setId(1L));
}
@Test
- public void call_dao_delete_when_deleting() throws Exception {
+ public void call_dao_delete_when_deleting() {
when(resourceDao.getResource(123L)).thenReturn(new ResourceDto().setId(123L).setUuid("A"));
sut.delete(123L);
private ActiveDashboardDao dao;
@Before
- public void createDao() throws Exception {
+ public void createDao() {
dbTester.truncateTables();
dao = new ActiveDashboardDao(dbTester.myBatis());
}
@Test
- public void shouldInsert() throws Exception {
+ public void shouldInsert() {
dbTester.prepareDbUnit(getClass(), "shouldInsert.xml");
ActiveDashboardDto dashboard = new ActiveDashboardDto();
}
@Test
- public void shouldInsertWithNoUser() throws Exception {
+ public void shouldInsertWithNoUser() {
dbTester.prepareDbUnit(getClass(), "shouldInsert.xml");
ActiveDashboardDto dashboard = new ActiveDashboardDto();
}
@Test
- public void shouldGetMaxOrderIndexForNullUser() throws Exception {
+ public void shouldGetMaxOrderIndexForNullUser() {
dbTester.prepareDbUnit(getClass(), "shouldGetMaxOrderIndexForNullUser.xml");
int index = dao.selectMaxOrderIndexForNullUser();
}
@Test
- public void shouldGetZeroMaxOrderIndex() throws Exception {
+ public void shouldGetZeroMaxOrderIndex() {
dbTester.prepareDbUnit(getClass(), "empty.xml");
int index = dao.selectMaxOrderIndexForNullUser();
}
@Test
- public void should_get_dashboards_for_anonymous() throws Exception {
+ public void should_get_dashboards_for_anonymous() {
dbTester.prepareDbUnit(getClass(), "shouldSelectDashboardsForAnonymous.xml");
assertThat(dao.selectGlobalDashboardsForUserLogin(null)).hasSize(2).extracting("id").containsExactly(2L, 1L);
}
@Test
- public void should_get_dashboards_for_user() throws Exception {
+ public void should_get_dashboards_for_user() {
dbTester.prepareDbUnit(getClass(), "shouldSelectDashboardsForUser.xml");
assertThat(dao.selectGlobalDashboardsForUserLogin("obiwan")).hasSize(2).extracting("id").containsExactly(2L, 1L);
}
@Test
- public void should_get_project_dashboards_for_anonymous() throws Exception {
+ public void should_get_project_dashboards_for_anonymous() {
dbTester.prepareDbUnit(getClass(), "shouldSelectProjectDashboardsForAnonymous.xml");
assertThat(dao.selectProjectDashboardsForUserLogin(null)).hasSize(2).extracting("id").containsExactly(2L, 1L);
}
@Test
- public void should_get_project_dashboards_for_user() throws Exception {
+ public void should_get_project_dashboards_for_user() {
dbTester.prepareDbUnit(getClass(), "shouldSelectProjectDashboardsForUser.xml");
assertThat(dao.selectProjectDashboardsForUserLogin("obiwan")).hasSize(2).extracting("id").containsExactly(2L, 1L);
}
@Test
- public void shouldInsertWithNullableColumns() throws Exception {
+ public void shouldInsertWithNullableColumns() {
dbTester.prepareDbUnit(getClass(), "shouldInsert.xml");
DashboardDto dashboardDto = new DashboardDto();
private DuplicationDao dao;
@Before
- public void createDao() throws Exception {
+ public void createDao() {
dao = new DuplicationDao(getMyBatis());
}
@Test
- public void shouldGetByHash() throws Exception {
+ public void shouldGetByHash() {
setupData("shouldGetByHash");
List<DuplicationUnitDto> blocks = dao.selectCandidates(10, 7, "java");
}
@Test
- public void shouldInsert() throws Exception {
+ public void shouldInsert() {
setupData("shouldInsert");
dao.insert(Arrays.asList(new DuplicationUnitDto(1, 2, "bb", 0, 1, 2)));
public class GraphsonReaderTest {
@Test
- public void inputGraphModeExtended() throws Exception {
+ public void inputGraphModeExtended() {
TinkerGraph graph = new TinkerGraph();
String json = "{ \"mode\":\"EXTENDED\", \"vertices\": [ {\"_id\":1, \"_type\":\"vertex\", \"test\": { \"type\":\"string\", \"value\":\"please work\"}, \"testlist\":{\"type\":\"list\", \"value\":[{\"type\":\"int\", \"value\":1}, {\"type\":\"int\",\"value\":2}, {\"type\":\"int\",\"value\":3}, {\"type\":\"unknown\",\"value\":null}]}, \"testmap\":{\"type\":\"map\", \"value\":{\"big\":{\"type\":\"long\", \"value\":10000000000}, \"small\":{\"type\":\"double\", \"value\":0.4954959595959}, \"nullKey\":{\"type\":\"unknown\", \"value\":null}}}}, {\"_id\":2, \"_type\":\"vertex\", \"testagain\":{\"type\":\"string\", \"value\":\"please work again\"}}], \"edges\":[{\"_id\":100, \"_type\":\"edge\", \"_outV\":1, \"_inV\":2, \"_label\":\"works\", \"teste\": {\"type\":\"string\", \"value\":\"please worke\"}, \"keyNull\":{\"type\":\"unknown\", \"value\":null}}]}";
}
@Test
- public void inputGraphModeNormal() throws Exception {
+ public void inputGraphModeNormal() {
TinkerGraph graph = new TinkerGraph();
String json = "{ \"mode\":\"NORMAL\",\"vertices\": [ {\"_id\":1, \"_type\":\"vertex\", \"test\": \"please work\", \"testlist\":[1, 2, 3, null], \"testmap\":{\"big\":10000000000, \"small\":0.4954959595959, \"nullKey\":null}}, {\"_id\":2, \"_type\":\"vertex\", \"testagain\":\"please work again\"}], \"edges\":[{\"_id\":100, \"_type\":\"edge\", \"_outV\":1, \"_inV\":2, \"_label\":\"works\", \"teste\": \"please worke\", \"keyNull\":null}]}";
}
@Test
- public void inputGraphModeCompact() throws Exception {
+ public void inputGraphModeCompact() {
TinkerGraph graph = new TinkerGraph();
String json = "{ \"mode\":\"COMPACT\",\"vertices\": [ {\"_id\":1, \"test\": \"please work\", \"testlist\":[1, 2, 3, null], \"testmap\":{\"big\":10000000000, \"small\":0.4954959595959, \"nullKey\":null}}, {\"_id\":2, \"testagain\":\"please work again\"}], \"edges\":[{\"_id\":100, \"_outV\":1, \"_inV\":2, \"_label\":\"works\", \"teste\": \"please worke\", \"keyNull\":null}]}";
}
@Test
- public void vertexFromJsonIgnoreKeyValid() throws Exception {
+ public void vertexFromJsonIgnoreKeyValid() {
Graph g = new TinkerGraph();
ElementFactory factory = new ElementFactory(g);
}
@Test
- public void override_toString() throws ClassNotFoundException {
+ public void override_toString() {
assertThat(i18nClassloader.toString()).isEqualTo("i18n-classloader");
}
ActionPlan noDeadline = new DefaultActionPlan().setDeadLine(null);
@Test
- public void compare_plans_with_deadlines() throws Exception {
+ public void compare_plans_with_deadlines() {
List<ActionPlan> plans = Arrays.asList(shortTerm, longTerm);
Collections.sort(plans, new ActionPlanDeadlineComparator());
assertThat(plans).containsSequence(shortTerm, longTerm);
}
@Test
- public void end_with_plans_without_deadline() throws Exception {
+ public void end_with_plans_without_deadline() {
List<ActionPlan> plans = Arrays.asList(noDeadline, longTerm, shortTerm);
Collections.sort(plans, new ActionPlanDeadlineComparator());
assertThat(plans).containsSequence(shortTerm, longTerm, noDeadline);
public class DefaultIssueBuilderTest {
@Test
- public void build_new_issue() throws Exception {
+ public void build_new_issue() {
String componentKey = "org.apache.struts:struts-core:Action.java";
String projectKey = "org.apache.struts";
DefaultIssue issue = (DefaultIssue) new DefaultIssueBuilder()
IssueUpdater updater;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
updater = new IssueUpdater();
}
@Test
- public void assign() throws Exception {
+ public void assign() {
User user = new DefaultUser().setLogin("emmerik").setName("Emmerik");
boolean updated = updater.assign(issue, user, context);
}
@Test
- public void unassign() throws Exception {
+ public void unassign() {
issue.setAssignee("morgan");
boolean updated = updater.assign(issue, null, context);
assertThat(updated).isTrue();
}
@Test
- public void change_assignee() throws Exception {
+ public void change_assignee() {
User user = new DefaultUser().setLogin("emmerik").setName("Emmerik");
issue.setAssignee("morgan");
}
@Test
- public void not_change_assignee() throws Exception {
+ public void not_change_assignee() {
User user = new DefaultUser().setLogin("morgan").setName("Morgan");
issue.setAssignee("morgan");
}
@Test
- public void set_severity() throws Exception {
+ public void set_severity() {
boolean updated = updater.setSeverity(issue, "BLOCKER", context);
assertThat(updated).isTrue();
assertThat(issue.severity()).isEqualTo("BLOCKER");
}
@Test
- public void set_past_severity() throws Exception {
+ public void set_past_severity() {
issue.setSeverity("BLOCKER");
boolean updated = updater.setPastSeverity(issue, "INFO", context);
assertThat(updated).isTrue();
}
@Test
- public void update_severity() throws Exception {
+ public void update_severity() {
issue.setSeverity("BLOCKER");
boolean updated = updater.setSeverity(issue, "MINOR", context);
}
@Test
- public void not_change_severity() throws Exception {
+ public void not_change_severity() {
issue.setSeverity("MINOR");
boolean updated = updater.setSeverity(issue, "MINOR", context);
assertThat(updated).isFalse();
}
@Test
- public void not_revert_manual_severity() throws Exception {
+ public void not_revert_manual_severity() {
issue.setSeverity("MINOR").setManualSeverity(true);
try {
updater.setSeverity(issue, "MAJOR", context);
}
@Test
- public void set_manual_severity() throws Exception {
+ public void set_manual_severity() {
issue.setSeverity("BLOCKER");
boolean updated = updater.setManualSeverity(issue, "MINOR", context);
}
@Test
- public void not_change_manual_severity() throws Exception {
+ public void not_change_manual_severity() {
issue.setSeverity("MINOR").setManualSeverity(true);
boolean updated = updater.setManualSeverity(issue, "MINOR", context);
assertThat(updated).isFalse();
}
@Test
- public void set_line() throws Exception {
+ public void set_line() {
boolean updated = updater.setLine(issue, 123);
assertThat(updated).isTrue();
assertThat(issue.line()).isEqualTo(123);
}
@Test
- public void set_past_line() throws Exception {
+ public void set_past_line() {
issue.setLine(42);
boolean updated = updater.setPastLine(issue, 123);
assertThat(updated).isTrue();
}
@Test
- public void not_change_line() throws Exception {
+ public void not_change_line() {
issue.setLine(123);
boolean updated = updater.setLine(issue, 123);
assertThat(updated).isFalse();
}
@Test
- public void set_resolution() throws Exception {
+ public void set_resolution() {
boolean updated = updater.setResolution(issue, "OPEN", context);
assertThat(updated).isTrue();
assertThat(issue.resolution()).isEqualTo("OPEN");
}
@Test
- public void not_change_resolution() throws Exception {
+ public void not_change_resolution() {
issue.setResolution("FIXED");
boolean updated = updater.setResolution(issue, "FIXED", context);
assertThat(updated).isFalse();
}
@Test
- public void set_status() throws Exception {
+ public void set_status() {
boolean updated = updater.setStatus(issue, "OPEN", context);
assertThat(updated).isTrue();
assertThat(issue.status()).isEqualTo("OPEN");
}
@Test
- public void not_change_status() throws Exception {
+ public void not_change_status() {
issue.setStatus("CLOSED");
boolean updated = updater.setStatus(issue, "CLOSED", context);
assertThat(updated).isFalse();
}
@Test
- public void set_new_attribute_value() throws Exception {
+ public void set_new_attribute_value() {
boolean updated = updater.setAttribute(issue, "JIRA", "FOO-123", context);
assertThat(updated).isTrue();
assertThat(issue.attribute("JIRA")).isEqualTo("FOO-123");
}
@Test
- public void unset_attribute() throws Exception {
+ public void unset_attribute() {
issue.setAttribute("JIRA", "FOO-123");
boolean updated = updater.setAttribute(issue, "JIRA", null, context);
assertThat(updated).isTrue();
}
@Test
- public void not_update_attribute() throws Exception {
+ public void not_update_attribute() {
issue.setAttribute("JIRA", "FOO-123");
boolean updated = updater.setAttribute(issue, "JIRA", "FOO-123", context);
assertThat(updated).isFalse();
}
@Test
- public void plan_with_no_existing_plan() throws Exception {
+ public void plan_with_no_existing_plan() {
ActionPlan newActionPlan = DefaultActionPlan.create("newName");
boolean updated = updater.plan(issue, newActionPlan, context);
}
@Test
- public void plan_with_existing_plan() throws Exception {
+ public void plan_with_existing_plan() {
issue.setActionPlanKey("formerActionPlan");
ActionPlan newActionPlan = DefaultActionPlan.create("newName").setKey("newKey");
}
@Test
- public void unplan() throws Exception {
+ public void unplan() {
issue.setActionPlanKey("formerActionPlan");
boolean updated = updater.plan(issue, null, context);
}
@Test
- public void not_plan_again() throws Exception {
+ public void not_plan_again() {
issue.setActionPlanKey("existingActionPlan");
ActionPlan newActionPlan = DefaultActionPlan.create("existingActionPlan").setKey("existingActionPlan");
}
@Test
- public void set_effort_to_fix() throws Exception {
+ public void set_effort_to_fix() {
boolean updated = updater.setEffortToFix(issue, 3.14, context);
assertThat(updated).isTrue();
assertThat(issue.isChanged()).isTrue();
}
@Test
- public void not_set_effort_to_fix_if_unchanged() throws Exception {
+ public void not_set_effort_to_fix_if_unchanged() {
issue.setEffortToFix(3.14);
boolean updated = updater.setEffortToFix(issue, 3.14, context);
assertThat(updated).isFalse();
}
@Test
- public void set_past_effort() throws Exception {
+ public void set_past_effort() {
issue.setEffortToFix(3.14);
boolean updated = updater.setPastEffortToFix(issue, 1.0, context);
assertThat(updated).isTrue();
}
@Test
- public void set_past_technical_debt() throws Exception {
+ public void set_past_technical_debt() {
Duration newDebt = Duration.create(15 * 8 * 60);
Duration previousDebt = Duration.create(10 * 8 * 60);
issue.setDebt(newDebt);
}
@Test
- public void set_past_technical_debt_without_previous_value() throws Exception {
+ public void set_past_technical_debt_without_previous_value() {
Duration newDebt = Duration.create(15 * 8 * 60);
issue.setDebt(newDebt);
boolean updated = updater.setPastTechnicalDebt(issue, null, context);
}
@Test
- public void set_past_technical_debt_with_null_new_value() throws Exception {
+ public void set_past_technical_debt_with_null_new_value() {
issue.setDebt(null);
Duration previousDebt = Duration.create(10 * 8 * 60);
boolean updated = updater.setPastTechnicalDebt(issue, previousDebt, context);
}
@Test
- public void set_message() throws Exception {
+ public void set_message() {
boolean updated = updater.setMessage(issue, "the message", context);
assertThat(updated).isTrue();
assertThat(issue.isChanged()).isTrue();
}
@Test
- public void set_past_message() throws Exception {
+ public void set_past_message() {
issue.setMessage("new message");
boolean updated = updater.setPastMessage(issue, "past message", context);
assertThat(updated).isTrue();
}
@Test
- public void set_author() throws Exception {
+ public void set_author() {
boolean updated = updater.setAuthorLogin(issue, "eric", context);
assertThat(updated).isTrue();
assertThat(issue.authorLogin()).isEqualTo("eric");
}
@Test
- public void set_project() throws Exception {
+ public void set_project() {
boolean updated = updater.setProject(issue, "sample", context);
assertThat(updated).isTrue();
assertThat(issue.projectKey()).isEqualTo("sample");
}
@Test
- public void set_past_project() throws Exception {
+ public void set_past_project() {
issue.setProjectKey("new project key");
boolean updated = updater.setPastProject(issue, "past project key", context);
assertThat(updated).isTrue();
}
@Test
- public void not_set_past_project_if_no_change() throws Exception {
+ public void not_set_past_project_if_no_change() {
issue.setProjectKey("key");
boolean updated = updater.setPastProject(issue, "key", context);
assertThat(updated).isFalse();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
public class IssueChangeDtoTest {
@Test
- public void create_from_comment() throws Exception {
+ public void create_from_comment() {
DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "emmerik", "the comment");
IssueChangeDto dto = IssueChangeDto.of(comment);
}
@Test
- public void create_from_comment_with_created_at() throws Exception {
+ public void create_from_comment_with_created_at() {
DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "emmerik", "the comment");
comment.setCreatedAt(parseDate("2015-01-13"));
}
@Test
- public void create_from_diff() throws Exception {
+ public void create_from_diff() {
FieldDiffs diffs = new FieldDiffs();
diffs.setDiff("severity", "INFO", "BLOCKER");
diffs.setUserLogin("emmerik");
}
@Test
- public void create_from_diff_with_created_at() throws Exception {
+ public void create_from_diff_with_created_at() {
FieldDiffs diffs = new FieldDiffs();
diffs.setDiff("severity", "INFO", "BLOCKER");
diffs.setUserLogin("emmerik");
}
@Test
- public void to_comment() throws Exception {
+ public void to_comment() {
IssueChangeDto changeDto = new IssueChangeDto()
.setKey("EFGH")
.setUserLogin("emmerik")
}
@Test
- public void to_field_diffs_with_issue_creation_date() throws Exception {
+ public void to_field_diffs_with_issue_creation_date() {
IssueChangeDto changeDto = new IssueChangeDto()
.setKey("EFGH")
.setUserLogin("emmerik")
}
@Test
- public void to_field_diffs_with_create_at() throws Exception {
+ public void to_field_diffs_with_create_at() {
IssueChangeDto changeDto = new IssueChangeDto()
.setKey("EFGH")
.setUserLogin("emmerik")
}
@Test
- public void to_string() throws Exception {
+ public void to_string() {
DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "emmerik", "the comment");
IssueChangeDto dto = IssueChangeDto.of(comment);
assertThat(dto.toString()).contains("ABCDE");
}
@Test
- public void insert_diff() throws Exception {
+ public void insert_diff() {
IssueChangeDto dto = new IssueChangeDto();
dto.setKey(null /* no key on field changes */);
dto.setUserLogin("emmerik");
}
@Test
- public void insert_comment() throws Exception {
+ public void insert_comment() {
IssueChangeDto dto = new IssueChangeDto();
dto.setKey("COMMENT-1234");
dto.setUserLogin("emmerik");
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
}
@Test
- public void insert() throws Exception {
+ public void insert() {
IssueDto dto = new IssueDto();
dto.setComponentUuid("uuid-123");
dto.setProjectUuid("uuid-100");
}
@Test
- public void update() throws Exception {
+ public void update() {
setupData("testUpdate");
IssueDto dto = new IssueDto();
}
@Test
- public void updateBeforeSelectedDate_without_conflict() throws Exception {
+ public void updateBeforeSelectedDate_without_conflict() {
setupData("testUpdate");
IssueDto dto = new IssueDto();
}
@Test
- public void updateBeforeSelectedDate_with_conflict() throws Exception {
+ public void updateBeforeSelectedDate_with_conflict() {
setupData("updateBeforeSelectedDate_with_conflict");
IssueDto dto = new IssueDto();
}
@After
- public void after() throws Exception {
+ public void after() {
session.close();
}
@Test
- public void batch_insert_new_issues() throws Exception {
+ public void batch_insert_new_issues() {
FakeBatchSaver saver = new FakeBatchSaver(getMyBatis(), new FakeRuleFinder());
DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "emmerik", "the comment");
}
@Test
- public void batch_insert_new_issues_with_session() throws Exception {
+ public void batch_insert_new_issues_with_session() {
FakeBatchSaver saver = new FakeBatchSaver(getMyBatis(), new FakeRuleFinder());
DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "emmerik", "the comment");
}
@Test
- public void server_insert_new_issues_with_session() throws Exception {
+ public void server_insert_new_issues_with_session() {
ComponentDto project = new ComponentDto().setId(10L).setUuid("uuid-10");
ComponentDto component = new ComponentDto().setId(100L).setUuid("uuid-100");
FakeServerSaver saver = new FakeServerSaver(getMyBatis(), new FakeRuleFinder(), component, project);
}
@Test
- public void batch_update_issues() throws Exception {
+ public void batch_update_issues() {
setupData("should_update_issues");
FakeBatchSaver saver = new FakeBatchSaver(getMyBatis(), new FakeRuleFinder());
}
@Test
- public void server_update_issues() throws Exception {
+ public void server_update_issues() {
setupData("should_update_issues");
ComponentDto project = new ComponentDto().setId(10L).setUuid("whatever-uuid");
public class UpdateConflictResolverTest {
@Test
- public void should_reload_issue_and_resolve_conflict() throws Exception {
+ public void should_reload_issue_and_resolve_conflict() {
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
.setRuleKey(RuleKey.of("squid", "AvoidCycles"))
}
@Test
- public void should_keep_changes_made_by_user() throws Exception {
+ public void should_keep_changes_made_by_user() {
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
.setRuleKey(RuleKey.of("squid", "AvoidCycles"))
}
@Test
- public void severity_changed_by_user_should_be_kept() throws Exception {
+ public void severity_changed_by_user_should_be_kept() {
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
.setRuleKey(RuleKey.of("squid", "AvoidCycles"))
DefaultIssue issue = new DefaultIssue();
@Test
- public void should_be_end_of_life() throws Exception {
+ public void should_be_end_of_life() {
IsEndOfLife condition = new IsEndOfLife(true);
assertThat(condition.matches(issue.setEndOfLife(true))).isTrue();
assertThat(condition.matches(issue.setEndOfLife(false))).isFalse();
}
@Test
- public void should_not_be_end_of_life() throws Exception {
+ public void should_not_be_end_of_life() {
IsEndOfLife condition = new IsEndOfLife(false);
assertThat(condition.matches(issue.setEndOfLife(true))).isFalse();
assertThat(condition.matches(issue.setEndOfLife(false))).isTrue();
DefaultIssue issue = new DefaultIssue();
@Test
- public void should_match() throws Exception {
+ public void should_match() {
IsManual condition = new IsManual(true);
assertThat(condition.matches(issue.setReporter("you"))).isTrue();
assertThat(condition.matches(issue.setReporter(null))).isFalse();
}
@Test
- public void should_match_dead() throws Exception {
+ public void should_match_dead() {
IsManual condition = new IsManual(false);
assertThat(condition.matches(issue.setReporter("you"))).isFalse();
assertThat(condition.matches(issue.setReporter(null))).isTrue();
IssueWorkflow workflow = new IssueWorkflow(new FunctionExecutor(updater), updater);
@Test
- public void init_state_machine() throws Exception {
+ public void init_state_machine() {
assertThat(workflow.machine()).isNull();
workflow.start();
assertThat(workflow.machine()).isNotNull();
}
@Test
- public void list_statuses() throws Exception {
+ public void list_statuses() {
workflow.start();
// order is important for UI
assertThat(workflow.statusKeys()).containsSequence(Issue.STATUS_OPEN, Issue.STATUS_CONFIRMED, Issue.STATUS_REOPENED, Issue.STATUS_RESOLVED, Issue.STATUS_CLOSED);
}
@Test
- public void list_out_transitions_from_status_open() throws Exception {
+ public void list_out_transitions_from_status_open() {
workflow.start();
DefaultIssue issue = new DefaultIssue().setStatus(Issue.STATUS_OPEN);
}
@Test
- public void list_out_transitions_from_status_confirmed() throws Exception {
+ public void list_out_transitions_from_status_confirmed() {
workflow.start();
DefaultIssue issue = new DefaultIssue().setStatus(Issue.STATUS_CONFIRMED);
}
@Test
- public void list_out_transitions_from_status_resolved() throws Exception {
+ public void list_out_transitions_from_status_resolved() {
workflow.start();
DefaultIssue issue = new DefaultIssue().setStatus(Issue.STATUS_RESOLVED);
}
@Test
- public void list_out_transitions_from_status_reopen() throws Exception {
+ public void list_out_transitions_from_status_reopen() {
workflow.start();
DefaultIssue issue = new DefaultIssue().setStatus(Issue.STATUS_REOPENED);
}
@Test
- public void list_no_out_transition_from_status_closed() throws Exception {
+ public void list_no_out_transition_from_status_closed() {
workflow.start();
DefaultIssue issue = new DefaultIssue().setStatus(Issue.STATUS_CLOSED);
}
@Test
- public void list_out_transitions_from_status_closed_on_manual_issue() throws Exception {
+ public void list_out_transitions_from_status_closed_on_manual_issue() {
workflow.start();
// Manual issue because of reporter
}
@Test
- public void fail_if_unknown_status_when_listing_transitions() throws Exception {
+ public void fail_if_unknown_status_when_listing_transitions() {
workflow.start();
DefaultIssue issue = new DefaultIssue().setStatus("xxx");
@Test
- public void do_automatic_transition() throws Exception {
+ public void do_automatic_transition() {
workflow.start();
DefaultIssue issue = new DefaultIssue()
}
@Test
- public void close_open_dead_issue() throws Exception {
+ public void close_open_dead_issue() {
workflow.start();
DefaultIssue issue = new DefaultIssue()
}
@Test
- public void close_reopened_dead_issue() throws Exception {
+ public void close_reopened_dead_issue() {
workflow.start();
DefaultIssue issue = new DefaultIssue()
}
@Test
- public void close_confirmed_dead_issue() throws Exception {
+ public void close_confirmed_dead_issue() {
workflow.start();
DefaultIssue issue = new DefaultIssue()
@Test
- public void fail_if_unknown_status_on_automatic_trans() throws Exception {
+ public void fail_if_unknown_status_on_automatic_trans() {
workflow.start();
DefaultIssue issue = new DefaultIssue()
}
@Test
- public void flag_as_false_positive() throws Exception {
+ public void flag_as_false_positive() {
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
.setStatus(Issue.STATUS_OPEN)
}
@Test
- public void wont_fix() throws Exception {
+ public void wont_fix() {
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
.setStatus(Issue.STATUS_OPEN)
}
@Test
- public void manual_issues_be_resolved_then_closed() throws Exception {
+ public void manual_issues_be_resolved_then_closed() {
// Manual issue because of reporter
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
}
@Test
- public void manual_issues_be_confirmed_then_kept_open() throws Exception {
+ public void manual_issues_be_confirmed_then_kept_open() {
// Manual issue because of reporter
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
}
@Test
- public void manual_issue_on_removed_rule_be_closed() throws Exception {
+ public void manual_issue_on_removed_rule_be_closed() {
// Manual issue because of reporter
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
}
@Test
- public void manual_issue_on_removed_component_be_closed() throws Exception {
+ public void manual_issue_on_removed_component_be_closed() {
// Manual issue because of reporter
DefaultIssue issue = new DefaultIssue()
.setKey("ABCDE")
public class SetAssigneeTest {
@Test
- public void assign() throws Exception {
+ public void assign() {
User user = new DefaultUser().setLogin("eric").setName("eric");
SetAssignee function = new SetAssignee(user);
Function.Context context = mock(Function.Context.class);
}
@Test
- public void unassign() throws Exception {
+ public void unassign() {
Function.Context context = mock(Function.Context.class);
SetAssignee.UNASSIGN.execute(context);
verify(context, times(1)).setAssignee(null);
public class SetCloseDateTest {
@Test
- public void should_set_close_date() throws Exception {
+ public void should_set_close_date() {
SetCloseDate function = new SetCloseDate(true);
Function.Context context = mock(Function.Context.class);
function.execute(context);
SetEndOfLife function = new SetEndOfLife();
@Test
- public void should_resolve_as_fixed() throws Exception {
+ public void should_resolve_as_fixed() {
Issue issue = new DefaultIssue().setEndOfLife(true).setOnDisabledRule(false);
when(context.issue()).thenReturn(issue);
function.execute(context);
}
@Test
- public void should_resolve_as_removed_when_rule_is_disabled() throws Exception {
+ public void should_resolve_as_removed_when_rule_is_disabled() {
Issue issue = new DefaultIssue().setEndOfLife(true).setOnDisabledRule(true);
when(context.issue()).thenReturn(issue);
function.execute(context);
}
@Test
- public void should_fail_if_issue_is_not_resolved() throws Exception {
+ public void should_fail_if_issue_is_not_resolved() {
Issue issue = new DefaultIssue().setEndOfLife(false);
when(context.issue()).thenReturn(issue);
try {
}
@Test
- public void line_number_must_be_unset() throws Exception {
+ public void line_number_must_be_unset() {
Issue issue = new DefaultIssue().setEndOfLife(true).setLine(10);
when(context.issue()).thenReturn(issue);
function.execute(context);
public class SetResolutionTest {
@Test
- public void execute() throws Exception {
+ public void execute() {
SetResolution function = new SetResolution("FIXED");
Function.Context context = mock(Function.Context.class);
function.execute(context);
public class StateMachineTest {
@Test
- public void keep_order_of_state_keys() throws Exception {
+ public void keep_order_of_state_keys() {
StateMachine machine = StateMachine.builder().states("OPEN", "RESOLVED", "CLOSED").build();
assertThat(machine.stateKeys()).containsSequence("OPEN", "RESOLVED", "CLOSED");
}
@Test
- public void stateKey() throws Exception {
+ public void stateKey() {
StateMachine machine = StateMachine.builder()
.states("OPEN", "RESOLVED", "CLOSED")
.transition(Transition.builder("resolve").from("OPEN").to("RESOLVED").build())
Transition t1 = Transition.builder("close").from("OPEN").to("CLOSED").build();
@Test
- public void key_should_be_set() throws Exception {
+ public void key_should_be_set() {
try {
new State("", new Transition[0]);
fail();
}
@Test
- public void key_should_be_upper_case() throws Exception {
+ public void key_should_be_upper_case() {
try {
new State("close", new Transition[0]);
fail();
}
@Test
- public void no_duplicated_out_transitions() throws Exception {
+ public void no_duplicated_out_transitions() {
try {
new State("CLOSE", new Transition[]{t1, t1});
fail();
}
@Test
- public void key_should_be_set() throws Exception {
+ public void key_should_be_set() {
try {
Transition.builder("").from("OPEN").to("CLOSED").build();
fail();
}
@Test
- public void key_should_be_lower_case() throws Exception {
+ public void key_should_be_lower_case() {
try {
Transition.builder("CLOSE").from("OPEN").to("CLOSED").build();
fail();
}
@Test
- public void originating_status_should_be_set() throws Exception {
+ public void originating_status_should_be_set() {
try {
Transition.builder("close").from("").to("CLOSED").build();
fail();
}
@Test
- public void destination_status_should_be_set() throws Exception {
+ public void destination_status_should_be_set() {
try {
Transition.builder("close").from("OPEN").to("").build();
fail();
}
@Test
- public void should_verify_conditions() throws Exception {
+ public void should_verify_conditions() {
DefaultIssue issue = new DefaultIssue();
Transition transition = Transition.builder("close")
.from("OPEN").to("CLOSED")
}
@Test
- public void value_with_text_over_4000_characters() throws Exception {
+ public void value_with_text_over_4000_characters() {
assertThat(sut.setData(Strings.repeat("1", 4001)).getData()).isNotNull();
}
@Test
- public void text_value_under_4000_characters() throws Exception {
+ public void text_value_under_4000_characters() {
assertThat(sut.setData("text value").getData()).isEqualTo("text value");
}
@Test(expected = IndexOutOfBoundsException.class)
- public void fail_to_set_out_of_bounds_variation() throws Exception {
+ public void fail_to_set_out_of_bounds_variation() {
sut.setVariation(6, 1d);
}
@Test(expected = IndexOutOfBoundsException.class)
- public void fail_to_get_out_of_bounds_variation() throws Exception {
+ public void fail_to_get_out_of_bounds_variation() {
sut.getVariation(6);
}
@Test(expected = IllegalArgumentException.class)
- public void fail_if_non_existent_severity() throws Exception {
+ public void fail_if_non_existent_severity() {
sut.setSeverity("MAYOR");
}
@Test
- public void severity_values_are_retrieved() throws Exception {
+ public void severity_values_are_retrieved() {
assertThat(sut.getSeverity()).isNull();
for (String severity : Severity.ALL) {
public class MetricDtoTest {
@Test
- public void getters_and_setters() throws Exception {
+ public void getters_and_setters() {
MetricDto metricDto = new MetricDto()
.setId(1)
.setKey("coverage")
}
@Test
- public void shouldPersist() throws Exception {
+ public void shouldPersist() {
Notification notification = new Notification("test");
manager.scheduleForSending(notification);
}
@Test
- public void shouldGetFromQueueAndDelete() throws Exception {
+ public void shouldGetFromQueueAndDelete() {
Notification notification = new Notification("test");
NotificationQueueDto dto = NotificationQueueDto.toNotificationQueueDto(notification);
List<NotificationQueueDto> dtos = Arrays.asList(dto);
}
@Test
- public void select_groups_for_project_permission() throws Exception {
+ public void select_groups_for_project_permission() {
setupData("groups_with_permissions");
PermissionQuery query = PermissionQuery.builder().permission("user").build();
}
@Test
- public void anyone_group_is_not_returned_when_it_has_no_permission() throws Exception {
+ public void anyone_group_is_not_returned_when_it_has_no_permission() {
setupData("groups_with_permissions");
// Anyone group has not the permission 'admin', so it's not returned
}
@Test
- public void select_groups_for_global_permission() throws Exception {
+ public void select_groups_for_global_permission() {
setupData("groups_with_permissions");
PermissionQuery query = PermissionQuery.builder().permission("admin").build();
}
@Test
- public void search_by_groups_name() throws Exception {
+ public void search_by_groups_name() {
setupData("groups_with_permissions");
List<GroupWithPermissionDto> result = dao.selectGroups(PermissionQuery.builder().permission("user").search("aDMini").build(), COMPONENT_ID);
}
@Test
- public void search_groups_should_be_sorted_by_group_name() throws Exception {
+ public void search_groups_should_be_sorted_by_group_name() {
setupData("groups_with_permissions_should_be_sorted_by_group_name");
List<GroupWithPermissionDto> result = dao.selectGroups(PermissionQuery.builder().permission("user").build(), COMPONENT_ID);
public class GroupWithPermissionDtoTest {
@Test
- public void to_group_with_permission_having_permission() throws Exception {
+ public void to_group_with_permission_having_permission() {
GroupWithPermission group = new GroupWithPermissionDto()
.setName("users")
.setDescription("desc")
}
@Test
- public void to_group_with_permission_not_having_permission() throws Exception {
+ public void to_group_with_permission_not_having_permission() {
GroupWithPermission group = new GroupWithPermissionDto()
.setName("users")
.setPermission(null)
}
@Test
- public void select_groups() throws Exception {
+ public void select_groups() {
setupData("groups_with_permissions");
PermissionQuery query = PermissionQuery.builder().permission("user").build();
}
@Test
- public void anyone_group_is_not_returned_when_it_has_no_permission() throws Exception {
+ public void anyone_group_is_not_returned_when_it_has_no_permission() {
setupData("groups_with_permissions");
// Anyone group has not the permission 'admin', so it's not returned
}
@Test
- public void search_by_groups_name() throws Exception {
+ public void search_by_groups_name() {
setupData("groups_with_permissions");
List<GroupWithPermissionDto> result = dao.selectGroups(PermissionQuery.builder().permission("user").search("aDMini").build(), TEMPLATE_ID);
}
@Test
- public void search_groups_should_be_sorted_by_group_name() throws Exception {
+ public void search_groups_should_be_sorted_by_group_name() {
setupData("groups_with_permissions_should_be_sorted_by_group_name");
List<GroupWithPermissionDto> result = dao.selectGroups(PermissionQuery.builder().permission("user").build(), TEMPLATE_ID);
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void should_apply_permission_template() throws Exception {
+ public void should_apply_permission_template() {
setupData("should_apply_permission_template");
assertThat(permissionFacade.selectGroupPermissions(session, "sonar-administrators", 123L)).isEmpty();
}
@Test
- public void should_count_component_permissions() throws Exception {
+ public void should_count_component_permissions() {
setupData("should_count_component_permissions");
assertThat(permissionFacade.countComponentPermissions(session, 123L)).isEqualTo(2);
}
@Test
- public void should_add_user_permission() throws Exception {
+ public void should_add_user_permission() {
setupData("should_add_user_permission");
permissionFacade.insertUserPermission(123L, 200L, UserRole.ADMIN, session);
}
@Test
- public void should_delete_user_permission() throws Exception {
+ public void should_delete_user_permission() {
setupData("should_delete_user_permission");
permissionFacade.deleteUserPermission(123L, 200L, UserRole.ADMIN, session);
}
@Test
- public void should_insert_group_permission() throws Exception {
+ public void should_insert_group_permission() {
setupData("should_insert_group_permission");
permissionFacade.insertGroupPermission(123L, 100L, UserRole.USER, session);
}
@Test
- public void should_insert_group_name_permission() throws Exception {
+ public void should_insert_group_name_permission() {
setupData("should_insert_group_permission");
permissionFacade.insertGroupPermission(123L, "devs", UserRole.USER, session);
}
@Test
- public void should_insert_anyone_group_permission() throws Exception {
+ public void should_insert_anyone_group_permission() {
setupData("should_insert_anyone_group_permission");
permissionFacade.insertGroupPermission(123L, "Anyone", UserRole.USER, session);
}
@Test
- public void should_delete_group_permission() throws Exception {
+ public void should_delete_group_permission() {
setupData("should_delete_group_permission");
permissionFacade.deleteGroupPermission(123L, 100L, UserRole.USER, session);
}
@Test
- public void should_delete_group_name_permission() throws Exception {
+ public void should_delete_group_name_permission() {
setupData("should_delete_group_permission");
permissionFacade.deleteGroupPermission(123L, "devs", UserRole.USER, session);
}
@Test
- public void should_retrieve_permission_template() throws Exception {
+ public void should_retrieve_permission_template() {
PermissionTemplateDto permissionTemplateDto = new PermissionTemplateDto().setName("Test template").setKee("test_template");
PermissionTemplateDto templateWithPermissions = new PermissionTemplateDto().setKee("test_template");
permissionTemplateDao = mock(PermissionTemplateDao.class);
}
@Test
- public void should_fail_on_unmatched_template() throws Exception {
+ public void should_fail_on_unmatched_template() {
throwable.expect(IllegalArgumentException.class);
permissionTemplateDao = mock(PermissionTemplateDao.class);
}
@Test
- public void should_remove_all_permissions() throws Exception {
+ public void should_remove_all_permissions() {
setupData("should_remove_all_permissions");
assertThat(permissionFacade.selectGroupPermissions(session, "devs", 123L)).hasSize(1);
}
@Test
- public void should_create_permission_template() throws Exception {
+ public void should_create_permission_template() {
setupData("createPermissionTemplate");
PermissionTemplateDto permissionTemplate = permissionTemplateDao.createPermissionTemplate("my template", "my description", "myregexp");
assertThat(permissionTemplate).isNotNull();
}
@Test
- public void should_normalize_kee_on_template_creation() throws Exception {
+ public void should_normalize_kee_on_template_creation() {
setupData("createNonAsciiPermissionTemplate");
PermissionTemplateDto permissionTemplate = permissionTemplateDao.createPermissionTemplate("Môü Gnô Gnèçà ß", "my description", null);
assertThat(permissionTemplate).isNotNull();
}
@Test
- public void should_skip_key_normalization_on_default_template() throws Exception {
+ public void should_skip_key_normalization_on_default_template() {
PermissionTemplateMapper mapper = mock(PermissionTemplateMapper.class);
}
@Test
- public void should_select_permission_template() throws Exception {
+ public void should_select_permission_template() {
setupData("selectPermissionTemplate");
PermissionTemplateDto permissionTemplate = permissionTemplateDao.selectPermissionTemplate("my_template_20130102_030405");
}
@Test
- public void should_select_empty_permission_template() throws Exception {
+ public void should_select_empty_permission_template() {
setupData("selectEmptyPermissionTemplate");
PermissionTemplateDto permissionTemplate = permissionTemplateDao.selectPermissionTemplate("my_template_20130102_030405");
}
@Test
- public void should_select_permission_template_by_key() throws Exception {
+ public void should_select_permission_template_by_key() {
setupData("selectPermissionTemplate");
PermissionTemplateDto permissionTemplate = permissionTemplateDao.selectTemplateByKey("my_template_20130102_030405");
}
@Test
- public void should_select_all_permission_templates() throws Exception {
+ public void should_select_all_permission_templates() {
setupData("selectAllPermissionTemplates");
List<PermissionTemplateDto> permissionTemplates = permissionTemplateDao.selectAllPermissionTemplates();
}
@Test
- public void should_update_permission_template() throws Exception {
+ public void should_update_permission_template() {
setupData("updatePermissionTemplate");
permissionTemplateDao.updatePermissionTemplate(1L, "new_name", "new_description", "new_regexp");
}
@Test
- public void should_delete_permission_template() throws Exception {
+ public void should_delete_permission_template() {
setupData("deletePermissionTemplate");
permissionTemplateDao.deletePermissionTemplate(1L);
}
@Test
- public void should_add_user_permission_to_template() throws Exception {
+ public void should_add_user_permission_to_template() {
setupData("addUserPermissionToTemplate");
permissionTemplateDao.addUserPermission(1L, 1L, "new_permission");
}
@Test
- public void should_remove_user_permission_from_template() throws Exception {
+ public void should_remove_user_permission_from_template() {
setupData("removeUserPermissionFromTemplate");
permissionTemplateDao.removeUserPermission(1L, 2L, "permission_to_remove");
}
@Test
- public void should_add_group_permission_to_template() throws Exception {
+ public void should_add_group_permission_to_template() {
setupData("addGroupPermissionToTemplate");
permissionTemplateDao.addGroupPermission(1L, 1L, "new_permission");
}
@Test
- public void should_remove_group_permission_from_template() throws Exception {
+ public void should_remove_group_permission_from_template() {
setupData("removeGroupPermissionFromTemplate");
permissionTemplateDao.removeGroupPermission(1L, 2L, "permission_to_remove");
}
@Test
- public void remove_by_group() throws Exception {
+ public void remove_by_group() {
setupData("remove_by_group");
permissionTemplateDao.removeByGroup(2L, session);
session.commit();
}
@Test
- public void should_add_group_permission_with_null_name() throws Exception {
+ public void should_add_group_permission_with_null_name() {
setupData("addNullGroupPermissionToTemplate");
permissionTemplateDao.addGroupPermission(1L, null, "new_permission");
}
@Test
- public void should_remove_group_permission_with_null_name() throws Exception {
+ public void should_remove_group_permission_with_null_name() {
setupData("removeNullGroupPermissionFromTemplate");
permissionTemplateDao.removeGroupPermission(1L, null, "permission_to_remove");
}
@Test
- public void select_all_users_for_project_permission() throws Exception {
+ public void select_all_users_for_project_permission() {
setupData("users_with_permissions");
PermissionQuery query = PermissionQuery.builder().permission("user").build();
}
@Test
- public void select_all_users_for_global_permission() throws Exception {
+ public void select_all_users_for_global_permission() {
setupData("users_with_permissions");
PermissionQuery query = PermissionQuery.builder().permission("admin").build();
}
@Test
- public void select_only_user_with_permission() throws Exception {
+ public void select_only_user_with_permission() {
setupData("users_with_permissions");
// user1 and user2 have permission user
}
@Test
- public void select_only_user_without_permission() throws Exception {
+ public void select_only_user_without_permission() {
setupData("users_with_permissions");
// Only user3 has not the user permission
}
@Test
- public void search_by_user_name() throws Exception {
+ public void search_by_user_name() {
setupData("users_with_permissions");
List<UserWithPermissionDto> result = dao.selectUsers(PermissionQuery.builder().permission("user").search("SEr1").build(), COMPONENT_ID);
}
@Test
- public void select_only_enable_users() throws Exception {
+ public void select_only_enable_users() {
setupData("select_only_enable_users");
PermissionQuery query = PermissionQuery.builder().permission("user").build();
}
@Test
- public void should_be_sorted_by_user_name() throws Exception {
+ public void should_be_sorted_by_user_name() {
setupData("users_with_permissions_should_be_sorted_by_user_name");
List<UserWithPermissionDto> result = dao.selectUsers(PermissionQuery.builder().permission("user").build(), COMPONENT_ID);
}
@Test
- public void should_be_paginated() throws Exception {
+ public void should_be_paginated() {
setupData("users_with_permissions");
List<UserWithPermissionDto> result = dao.selectUsers(PermissionQuery.builder().permission("user").build(), COMPONENT_ID, 0, 2);
public class UserWithPermissionDtoTest {
@Test
- public void to_user_with_permission_having_permission() throws Exception {
+ public void to_user_with_permission_having_permission() {
UserWithPermission user = new UserWithPermissionDto()
.setName("Arthur")
.setLogin("arthur")
}
@Test
- public void to_user_with_permission_not_having_permission() throws Exception {
+ public void to_user_with_permission_not_having_permission() {
UserWithPermission user = new UserWithPermissionDto()
.setName("Arthur")
.setLogin("arthur")
}
@Test
- public void select_all_users() throws Exception {
+ public void select_all_users() {
setupData("users_with_permissions");
PermissionQuery query = PermissionQuery.builder().permission("user").build();
}
@Test
- public void return_nothing_on_unknown_template_key() throws Exception {
+ public void return_nothing_on_unknown_template_key() {
setupData("users_with_permissions");
PermissionQuery query = PermissionQuery.builder().permission("user").build();
}
@Test
- public void select_only_user_with_permission() throws Exception {
+ public void select_only_user_with_permission() {
setupData("users_with_permissions");
// user1 and user2 have permission user
}
@Test
- public void select_only_user_without_permission() throws Exception {
+ public void select_only_user_without_permission() {
setupData("users_with_permissions");
// Only user3 has not the user permission
}
@Test
- public void select_only_enable_users() throws Exception {
+ public void select_only_enable_users() {
setupData("select_only_enable_users");
PermissionQuery query = PermissionQuery.builder().permission("user").build();
}
@Test
- public void search_by_user_name() throws Exception {
+ public void search_by_user_name() {
setupData("users_with_permissions");
List<UserWithPermissionDto> result = dao.selectUsers(PermissionQuery.builder().permission("user").search("SEr1").build(), TEMPLATE_ID);
}
@Test
- public void should_be_sorted_by_user_name() throws Exception {
+ public void should_be_sorted_by_user_name() {
setupData("users_with_permissions_should_be_sorted_by_user_name");
List<UserWithPermissionDto> result = dao.selectUsers(PermissionQuery.builder().permission("user").build(), TEMPLATE_ID);
}
@Test
- public void should_be_paginated() throws Exception {
+ public void should_be_paginated() {
setupData("users_with_permissions");
List<UserWithPermissionDto> result = dao.selectUsers(PermissionQuery.builder().permission("user").build(), TEMPLATE_ID, 0, 2);
}
@Test
- public void repeatCondition() throws Exception {
+ public void repeatCondition() {
assertThat(DaoUtils.repeatCondition("uuid=?", 1, "or")).isEqualTo("uuid=?");
assertThat(DaoUtils.repeatCondition("uuid=?", 3, "or")).isEqualTo("uuid=? or uuid=? or uuid=?");
}
@Test
- public void execute_large_inputs() throws Exception {
+ public void execute_large_inputs() {
List<Integer> inputs = newArrayList();
List<String> expectedOutputs = newArrayList();
for (int i = 0; i < 2010; i++) {
}
@Test
- public void execute_large_inputs_on_empty_list() throws Exception {
+ public void execute_large_inputs_on_empty_list() {
List<String> outputs = DaoUtils.executeLargeInputs(Collections.<Integer>emptyList(), new Function<List<Integer>, List<String>>() {
@Override
public List<String> apply(List<Integer> input) {
}
@Test
- public void create_and_acquire_semaphore() throws Exception {
+ public void create_and_acquire_semaphore() {
Semaphores.Semaphore lock = dao.acquire("foo", 60);
assertThat(lock.isLocked()).isTrue();
assertThat(lock.getDurationSinceLocked()).isNull();
}
@Test
- public void fail_to_update_null_semaphore() throws Exception {
+ public void fail_to_update_null_semaphore() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Semaphore must not be null");
}
@Test
- public void create_and_acquire_semaphore_when_maxage_is_zeo() throws Exception {
+ public void create_and_acquire_semaphore_when_maxage_is_zeo() {
Semaphores.Semaphore lock = dao.acquire("foo", 0);
assertThat(lock.isLocked()).isTrue();
assertThat(lock.getDurationSinceLocked()).isNull();
}
@Test
- public void create_and_acquire_semaphore_when_no_timeout() throws Exception {
+ public void create_and_acquire_semaphore_when_no_timeout() {
Semaphores.Semaphore lock = dao.acquire("foo");
assertThat(lock.isLocked()).isTrue();
assertThat(lock.getDurationSinceLocked()).isNull();
}
@Test
- public void fail_to_acquire_locked_semaphore() throws Exception {
+ public void fail_to_acquire_locked_semaphore() {
setupData("old_semaphore");
Semaphores.Semaphore lock = dao.acquire("foo", Integer.MAX_VALUE);
assertThat(lock.isLocked()).isFalse();
}
@Test
- public void acquire_long_locked_semaphore() throws Exception {
+ public void acquire_long_locked_semaphore() {
setupData("old_semaphore");
Semaphores.Semaphore lock = dao.acquire("foo", 60);
assertThat(lock.isLocked()).isTrue();
}
@Test
- public void acquire_locked_semaphore_when_timeout_is_zero() throws Exception {
+ public void acquire_locked_semaphore_when_timeout_is_zero() {
setupData("old_semaphore");
Semaphores.Semaphore lock = dao.acquire("foo", 0);
assertThat(lock.isLocked()).isTrue();
}
@Test
- public void fail_to_acquire_locked_semaphore_when_no_timeout() throws Exception {
+ public void fail_to_acquire_locked_semaphore_when_no_timeout() {
setupData("old_semaphore");
Semaphores.Semaphore lock = dao.acquire("foo");
assertThat(lock.isLocked()).isFalse();
}
@Test
- public void should_select_semaphore_return_current_semaphore_when_acquiring() throws Exception {
+ public void should_select_semaphore_return_current_semaphore_when_acquiring() {
dao.acquire("foo");
SemaphoreDto semaphore = selectSemaphore("foo");
}
}
- private SemaphoreDto selectSemaphore(String name) throws Exception {
+ private SemaphoreDto selectSemaphore(String name) {
SqlSession session = getMyBatis().openSession();
try {
return dao.selectSemaphore(name, session);
}
@Test
- public void shouldNotFailWhenCancelNotExistingSemaphore() throws Exception {
+ public void shouldNotFailWhenCancelNotExistingSemaphore() {
updater.stopUpdate("foo");
}
}
@Test
- public void h2_does_not_supportMigration() throws Exception {
+ public void h2_does_not_supportMigration() {
assertThat(dialect.supportsMigration()).isFalse();
}
}
}
@Test
- public void msSql_does_supportMigration() throws Exception {
+ public void msSql_does_supportMigration() {
assertThat(msSql.supportsMigration()).isTrue();
}
}
}
@Test
- public void mysql_does_supportMigration() throws Exception {
+ public void mysql_does_supportMigration() {
assertThat(mySql.supportsMigration()).isTrue();
}
}
}
@Test
- public void oracle_does_supportMigration() throws Exception {
+ public void oracle_does_supportMigration() {
assertThat(dialect.supportsMigration()).isTrue();
}
}
}
@Test
- public void postgres_does_supportMigration() throws Exception {
+ public void postgres_does_supportMigration() {
assertThat(dialect.supportsMigration()).isTrue();
}
}
}
@Test
- public void only_static_methods() throws Exception {
+ public void only_static_methods() {
assertThat(TestUtils.hasOnlyPrivateConstructors(InvocationUtils.class)).isTrue();
}
}
@Test
- public void shouldImport() throws Exception {
+ public void shouldImport() {
classloaders.add(DefaultPluginMetadata.create("foo").addDeployedFile(getFile("PluginClassloadersTest/foo.jar")));
classloaders.add(DefaultPluginMetadata.create("bar").addDeployedFile(getFile("PluginClassloadersTest/bar.jar")));
classloaders.done();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
}
@Test
- public void hasNotificationSubscribers() throws Exception {
+ public void hasNotificationSubscribers() {
setupData("findNotificationSubscribers");
// Nobody is subscribed
}
@Test
- public void select_module_properties_tree() throws Exception {
+ public void select_module_properties_tree() {
setupData("select_module_properties_tree");
List<PropertyDto> properties = dao.selectEnabledDescendantModuleProperties("ABCD", session);
public class IdUuidPairsTest {
@Test
- public void extract_ids() throws Exception {
+ public void extract_ids() {
List<IdUuidPair> idUuidPairList = Lists.newArrayList(new IdUuidPair(1L, "ABCD"), new IdUuidPair(2L, "EFGH"));
List<Long> ids = IdUuidPairs.ids(idUuidPairList);
}
@Test
- public void is_non_instantiable() throws Exception {
+ public void is_non_instantiable() {
assertThat(TestUtils.hasOnlyPrivateConstructors(IdUuidPairs.class)).isTrue();
}
public class PurgeConfigurationTest {
@Test
- public void should_delete_all_closed_issues() throws Exception {
+ public void should_delete_all_closed_issues() {
PurgeConfiguration conf = new PurgeConfiguration(new IdUuidPair(1L, "1"), new String[0], 0);
assertThat(conf.maxLiveDateOfClosedIssues()).isNull();
}
@Test
- public void should_delete_only_old_closed_issues() throws Exception {
+ public void should_delete_only_old_closed_issues() {
Date now = DateUtils.parseDate("2013-05-18");
PurgeConfiguration conf = new PurgeConfiguration(new IdUuidPair(1L, "1"), new String[0], 30);
}
@Test
- public void select_all_projects_by_query() throws Exception {
+ public void select_all_projects_by_query() {
setupData("shared");
ProjectQgateAssociationQuery query = ProjectQgateAssociationQuery.builder().gateId("42").build();
}
@Test
- public void select_projects_by_query() throws Exception {
+ public void select_projects_by_query() {
setupData("shared");
assertThat(dao.selectProjects(ProjectQgateAssociationQuery.builder().gateId("42").membership(ProjectQgateAssociationQuery.IN).build(), 42L)).hasSize(3);
}
@Test
- public void search_by_project_name() throws Exception {
+ public void search_by_project_name() {
setupData("shared");
List<ProjectQgateAssociationDto> result = dao.selectProjects(ProjectQgateAssociationQuery.builder().gateId("42").projectSearch("one").build(), 42L);
}
@Test
- public void should_be_sorted_by_project_name() throws Exception {
+ public void should_be_sorted_by_project_name() {
setupData("shared");
List<ProjectQgateAssociationDto> result = dao.selectProjects(ProjectQgateAssociationQuery.builder().gateId("42").build(), 42L);
public class ProjectQgateAssociationDtoTest {
@Test
- public void to_assoc_with_project_having_assoc() throws Exception {
+ public void to_assoc_with_project_having_assoc() {
ProjectQgateAssociation project = new ProjectQgateAssociationDto()
.setId(1L)
.setName("polop")
}
@Test
- public void to_assoc_with_project_not_having_assoc() throws Exception {
+ public void to_assoc_with_project_not_having_assoc() {
ProjectQgateAssociation project = new ProjectQgateAssociationDto()
.setId(1L)
.setName("polop")
public class ProjectQgateAssociationQueryTest {
@Test
- public void fail_on_null_login() throws Exception {
+ public void fail_on_null_login() {
ProjectQgateAssociationQuery.Builder builder = ProjectQgateAssociationQuery.builder();
builder.gateId(null);
}
@Test
- public void fail_on_invalid_membership() throws Exception {
+ public void fail_on_invalid_membership() {
ProjectQgateAssociationQuery.Builder builder = ProjectQgateAssociationQuery.builder();
builder.gateId("nelson");
builder.membership("unknwown");
private static QualityGateConditionDao dao;
@Before
- public void createDao() throws Exception {
+ public void createDao() {
dao = new QualityGateConditionDao(getMyBatis());
}
checkTable("update", "quality_gate_conditions", COLUMNS_WITHOUT_TIMESTAMPS);
}
- public void shouldCleanConditions() throws Exception {
+ public void shouldCleanConditions() {
setupData("shouldCleanConditions");
dao.deleteConditionsWithInvalidMetrics();
checkTables("shouldCleanConditions", "quality_gate_conditions");
private static QualityGateDao dao;
@Before
- public void createDao() throws Exception {
+ public void createDao() {
dao = new QualityGateDao(getMyBatis());
}
public class ActiveRuleKeyTest {
@Test
- public void of() throws Exception {
+ public void of() {
RuleKey ruleKey = RuleKey.of("xoo", "R1");
ActiveRuleKey key = ActiveRuleKey.of("P1", ruleKey);
assertThat(key.qProfile()).isEqualTo("P1");
}
@Test
- public void rule_key_can_contain_colons() throws Exception {
+ public void rule_key_can_contain_colons() {
RuleKey ruleKey = RuleKey.of("squid", "Key:With:Some::Colons");
ActiveRuleKey key = ActiveRuleKey.of("P1", ruleKey);
assertThat(key.qProfile()).isEqualTo("P1");
}
@Test
- public void profile_must_not_be_null() throws Exception {
+ public void profile_must_not_be_null() {
try {
ActiveRuleKey.of(null, RuleKey.of("xoo", "R1"));
fail();
}
@Test
- public void rule_key_must_not_be_null() throws Exception {
+ public void rule_key_must_not_be_null() {
try {
ActiveRuleKey.of("P1", null);
fail();
}
@Test
- public void parse() throws Exception {
+ public void parse() {
ActiveRuleKey key = ActiveRuleKey.parse("P1:xoo:R1");
assertThat(key.qProfile()).isEqualTo("P1");
assertThat(key.ruleKey().repository()).isEqualTo("xoo");
}
@Test
- public void parse_fail_when_less_than_three_colons() throws Exception {
+ public void parse_fail_when_less_than_three_colons() {
try {
ActiveRuleKey.parse("P1:xoo");
fail();
}
@Test
- public void equals_and_hashcode() throws Exception {
+ public void equals_and_hashcode() {
ActiveRuleKey key1 = ActiveRuleKey.parse("P1:xoo:R1");
ActiveRuleKey key1b = ActiveRuleKey.parse("P1:xoo:R1");
ActiveRuleKey key2 = ActiveRuleKey.parse("P1:xoo:R2");
public class ActiveRuleParamDtoTest {
@Test
- public void groupByKey() throws Exception {
+ public void groupByKey() {
assertThat(ActiveRuleParamDto.groupByKey(Collections.<ActiveRuleParamDto>emptyList())).isEmpty();
Collection<ActiveRuleParamDto> dtos = Arrays.asList(
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
}
@Test
- public void should_fail_when_no_default_template_is_defined() throws Exception {
+ public void should_fail_when_no_default_template_is_defined() {
throwable.expect(IllegalStateException.class);
permissions.grantDefaultRoles(project);
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
}
@Test
- public void should_insert_using_existing_session() throws Exception {
+ public void should_insert_using_existing_session() {
setupData("insert");
ResourceDto file1 = new ResourceDto().setUuid("ABCD")
}
@Test
- public void shouldNotUpdateAllSubmodules() throws Exception {
+ public void shouldNotUpdateAllSubmodules() {
setupData("shouldNotUpdateAllSubmodules");
dao.bulkUpdateKey(1, "org.struts", "org.apache.struts");
private static RuleDao dao;
@Before
- public void createDao() throws Exception {
+ public void createDao() {
dao = new RuleDao(getMyBatis());
}
@Test
- public void select_enables_and_non_manual() throws Exception {
+ public void select_enables_and_non_manual() {
setupData("select_enables_and_non_manual");
List<RuleDto> ruleDtos = dao.selectEnablesAndNonManual();
}
@Test
- public void select_parameters() throws Exception {
+ public void select_parameters() {
setupData("selectParameters");
List<RuleParamDto> ruleDtos = dao.selectParameters();
public class FileSourceDtoTest {
@Test
- public void encode_and_decode_test_data() throws Exception {
+ public void encode_and_decode_test_data() {
List<FileSourceDb.Test> tests = Arrays.asList(
FileSourceDb.Test.newBuilder()
.setName("name#1")
private DefaultTechnicalDebtModel sqaleModel;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
DefaultDebtModel debtModel = new DefaultDebtModel();
debtModel.addCharacteristic(
new DefaultDebtCharacteristic().setId(1)
}
@Test
- public void get_characteristics() throws Exception {
+ public void get_characteristics() {
assertThat(sqaleModel.rootCharacteristics()).hasSize(1);
DefaultCharacteristic resultRootCharacteristic = sqaleModel.rootCharacteristics().get(0);
}
@Test
- public void get_characteristic_by_key() throws Exception {
+ public void get_characteristic_by_key() {
assertThat(sqaleModel.characteristicByKey("MEMORY_EFFICIENCY")).isNotNull();
assertThat(sqaleModel.characteristicByKey("EFFICIENCY")).isNotNull();
assertThat(sqaleModel.characteristicByKey("EFFICIENCY").parent()).isNotNull();
}
@Test
- public void characteristic_by_id() throws Exception {
+ public void characteristic_by_id() {
assertThat(sqaleModel.characteristicById(1)).isNotNull();
assertThat(sqaleModel.characteristicById(2)).isNotNull();
assertThat(sqaleModel.characteristicById(123)).isNull();
}
@Test
- public void get_requirement_by_rule_key_always_return_null() throws Exception {
+ public void get_requirement_by_rule_key_always_return_null() {
assertThat(sqaleModel.requirementsByRule(RuleKey.of("checkstyle", "Regexp"))).isNull();
}
@Test
- public void get_requirement_by_id_always_return_null() throws Exception {
+ public void get_requirement_by_id_always_return_null() {
assertThat(sqaleModel.requirementsById(1)).isNull();
}
@Test
- public void get_requirements_always_return_empty_list() throws Exception {
+ public void get_requirements_always_return_empty_list() {
assertThat(sqaleModel.requirements()).isEmpty();
}
}
@Test
- public void insert_characteristic() throws Exception {
+ public void insert_characteristic() {
CharacteristicDto dto = new CharacteristicDto()
.setKey("COMPILER_RELATED_PORTABILITY")
.setName("Compiler related portability")
}
@Test
- public void update_characteristic() throws Exception {
+ public void update_characteristic() {
setupData("update_characteristic");
CharacteristicDto dto = new CharacteristicDto()
public class CharacteristicDtoTest {
@Test
- public void to_dto_from_characteristic() throws Exception {
+ public void to_dto_from_characteristic() {
DefaultCharacteristic rootCharacteristic = new DefaultCharacteristic()
.setId(1)
.setKey("MEMORY_EFFICIENCY")
}
@Test
- public void to_characteristic() throws Exception {
+ public void to_characteristic() {
DefaultCharacteristic rootCharacteristic = new DefaultCharacteristic()
.setId(1)
.setKey("MEMORY_EFFICIENCY")
private LoadedTemplateDao dao;
@Before
- public void createDao() throws Exception {
+ public void createDao() {
dao = new LoadedTemplateDao(getMyBatis());
}
@Test
- public void shouldCountByTypeAndKey() throws Exception {
+ public void shouldCountByTypeAndKey() {
setupData("shouldCountByTypeAndKey");
assertThat(dao.countByTypeAndKey("DASHBOARD", "HOTSPOTS"), is(1));
assertThat(dao.countByTypeAndKey("DASHBOARD", "UNKNOWN"), is(0));
}
@Test
- public void shouldInsert() throws Exception {
+ public void shouldInsert() {
setupData("shouldInsert");
LoadedTemplateDto template = new LoadedTemplateDto("SQALE", "DASHBOARD");
}
@Test
- public void shouldInsertAuthorAndDeveloper() throws Exception {
+ public void shouldInsertAuthorAndDeveloper() {
setupData("shouldInsertAuthorAndDeveloper");
String login = "developer@company.net";
}
@Test
- public void add_missing_module_uuid_path() throws Exception {
+ public void add_missing_module_uuid_path() {
setupData("add_missing_module_uuid_path");
dao.insertAuthorAndDeveloper("developer@company.net", new ResourceDto().setName("developer@company.net").setQualifier("DEV").setUuid("ABCD").setProjectUuid("ABCD")
}
@Test
- public void shouldPreventAuthorsAndDevelopersDuplication() throws Exception {
+ public void shouldPreventAuthorsAndDevelopersDuplication() {
setupData("shouldPreventAuthorsAndDevelopersDuplication");
String login = "developer@company.net";
AuthorizationDao authorization;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
session = getMyBatis().openSession(false);
authorization = new AuthorizationDao(getMyBatis());
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
}
@Test
- public void should_return_global_permissions_for_group_anyone() throws Exception {
+ public void should_return_global_permissions_for_group_anyone() {
setupData("should_return_global_permissions_for_group_anyone");
assertThat(authorization.selectGlobalPermissions("anyone_user")).containsOnly("user", "profileadmin");
DefaultUserFinder finder = new DefaultUserFinder(dao);
@Test
- public void findByLogin() throws Exception {
+ public void findByLogin() {
UserDto dto = new UserDto().setLogin("david").setName("David").setEmail("dav@id.com");
when(dao.selectActiveUserByLogin("david")).thenReturn(dto);
}
@Test
- public void findByLogins() throws Exception {
+ public void findByLogins() {
UserDto david = new UserDto().setLogin("david").setName("David").setEmail("dav@id.com");
UserDto john = new UserDto().setLogin("john").setName("John").setEmail("jo@hn.com");
when(dao.selectUsersByLogins(Arrays.asList("david", "john"))).thenReturn(Arrays.asList(david, john));
}
@Test
- public void findByQuery() throws Exception {
+ public void findByQuery() {
UserQuery query = UserQuery.builder().logins("simon").build();
finder.find(query);
verify(dao).selectUsers(query);
public class GroupDtoTest {
@Test
- public void getter_and_setter() throws Exception {
+ public void getter_and_setter() {
GroupDto dto = new GroupDto()
.setId(1L)
.setName("sonar-users")
}
@Test
- public void select_all_groups_by_query() throws Exception {
+ public void select_all_groups_by_query() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
GroupMembershipQuery query = GroupMembershipQuery.builder().login("arthur").build();
}
@Test
- public void select_user_group() throws Exception {
+ public void select_user_group() {
dbTester.prepareDbUnit(getClass(), "select_user_group.xml");
GroupMembershipQuery query = GroupMembershipQuery.builder().login("arthur").build();
}
@Test
- public void select_user_groups_by_query() throws Exception {
+ public void select_user_groups_by_query() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
// 200 is member of 3 groups
}
@Test
- public void select_groups_not_affected_to_a_user_by_query() throws Exception {
+ public void select_groups_not_affected_to_a_user_by_query() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
// 200 is member of 3 groups
}
@Test
- public void search_by_group_name() throws Exception {
+ public void search_by_group_name() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
List<GroupMembershipDto> result = dao.selectGroups(GroupMembershipQuery.builder().login("arthur").groupSearch("user").build(), 200L);
}
@Test
- public void search_by_group_name_with_capitalization() throws Exception {
+ public void search_by_group_name_with_capitalization() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
List<GroupMembershipDto> result = dao.selectGroups(GroupMembershipQuery.builder().login("arthur").groupSearch("UsER").build(), 200L);
}
@Test
- public void should_be_sorted_by_group_name() throws Exception {
+ public void should_be_sorted_by_group_name() {
dbTester.prepareDbUnit(getClass(), "should_be_sorted_by_group_name.xml");
List<GroupMembershipDto> result = dao.selectGroups(GroupMembershipQuery.builder().login("arthur").build(), 200L);
}
@Test
- public void should_be_paginated() throws Exception {
+ public void should_be_paginated() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
List<GroupMembershipDto> result = dao.selectGroups(GroupMembershipQuery.builder().login("arthur").build(), 200L, 0, 2);
}
@Test
- public void count_groups() throws Exception {
+ public void count_groups() {
dbTester.prepareDbUnit(getClass(), "shared.xml");
DbSession session = dbTester.myBatis().openSession(false);
public class GroupMembershipDtoTest {
@Test
- public void to_group_with_permission_having_permission() throws Exception {
+ public void to_group_with_permission_having_permission() {
GroupMembership group = new GroupMembershipDto()
.setId(1L)
.setName("users")
}
@Test
- public void to_group_with_permission_not_having_permission() throws Exception {
+ public void to_group_with_permission_not_having_permission() {
GroupMembership group = new GroupMembershipDto()
.setId(1L)
.setName("users")
public class GroupMembershipQueryTest {
@Test
- public void fail_on_null_login() throws Exception {
+ public void fail_on_null_login() {
GroupMembershipQuery.Builder builder = GroupMembershipQuery.builder();
builder.login(null);
}
@Test
- public void fail_on_invalid_membership() throws Exception {
+ public void fail_on_invalid_membership() {
GroupMembershipQuery.Builder builder = GroupMembershipQuery.builder();
builder.login("nelson");
builder.membership("unknwown");
RoleDao dao;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
session = getMyBatis().openSession(false);
dao = new RoleDao();
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
@Test
- public void retrieve_global_user_permissions() throws Exception {
+ public void retrieve_global_user_permissions() {
setupData("globalUserPermissions");
assertThat(dao.selectUserPermissions(session, "admin_user", null)).containsOnly(GlobalPermissions.SYSTEM_ADMIN, GlobalPermissions.QUALITY_PROFILE_ADMIN);
}
@Test
- public void retrieve_resource_user_permissions() throws Exception {
+ public void retrieve_resource_user_permissions() {
setupData("resourceUserPermissions");
assertThat(dao.selectUserPermissions(session, "admin_user", 1L)).containsOnly(UserRole.ADMIN, UserRole.USER);
}
@Test
- public void retrieve_global_group_permissions() throws Exception {
+ public void retrieve_global_group_permissions() {
setupData("globalGroupPermissions");
assertThat(dao.selectGroupPermissions(session, "sonar-administrators", null)).containsOnly(GlobalPermissions.SYSTEM_ADMIN, GlobalPermissions.QUALITY_PROFILE_ADMIN,
}
@Test
- public void retrieve_resource_group_permissions() throws Exception {
+ public void retrieve_resource_group_permissions() {
setupData("resourceGroupPermissions");
assertThat(dao.selectGroupPermissions(session, "sonar-administrators", 1L)).containsOnly(UserRole.ADMIN, UserRole.CODEVIEWER);
}
@Test
- public void delete_global_user_permission() throws Exception {
+ public void delete_global_user_permission() {
setupData("globalUserPermissions");
UserRoleDto userRoleToDelete = new UserRoleDto().setUserId(200L).setRole(GlobalPermissions.QUALITY_PROFILE_ADMIN);
}
@Test
- public void delete_resource_user_permission() throws Exception {
+ public void delete_resource_user_permission() {
setupData("resourceUserPermissions");
UserRoleDto userRoleToDelete = new UserRoleDto().setUserId(200L).setRole(UserRole.USER).setResourceId(1L);
}
@Test
- public void delete_global_group_permission() throws Exception {
+ public void delete_global_group_permission() {
setupData("globalGroupPermissions");
GroupRoleDto groupRoleToDelete = new GroupRoleDto().setGroupId(100L).setRole(GlobalPermissions.QUALITY_PROFILE_ADMIN);
}
@Test
- public void delete_resource_group_permission() throws Exception {
+ public void delete_resource_group_permission() {
setupData("resourceGroupPermissions");
GroupRoleDto groupRoleToDelete = new GroupRoleDto().setGroupId(100L).setRole(UserRole.CODEVIEWER).setResourceId(1L);
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
session.close();
}
}
@Test
- public void selectUsersByLogins() throws Exception {
+ public void selectUsersByLogins() {
setupData("selectUsersByLogins");
Collection<UserDto> users = dao.selectUsersByLogins(Arrays.asList("marius", "inactive_user", "other"));
}
@Test
- public void selectUsersByLogins_empty_logins() throws Exception {
+ public void selectUsersByLogins_empty_logins() {
// no need to access db
Collection<UserDto> users = dao.selectUsersByLogins(Collections.<String>emptyList());
assertThat(users).isEmpty();
}
@Test
- public void selectUsersByQuery_all() throws Exception {
+ public void selectUsersByQuery_all() {
setupData("selectUsersByQuery");
UserQuery query = UserQuery.builder().includeDeactivated().build();
}
@Test
- public void selectUsersByQuery_only_actives() throws Exception {
+ public void selectUsersByQuery_only_actives() {
setupData("selectUsersByQuery");
UserQuery query = UserQuery.ALL_ACTIVES;
}
@Test
- public void selectUsersByQuery_filter_by_login() throws Exception {
+ public void selectUsersByQuery_filter_by_login() {
setupData("selectUsersByQuery");
UserQuery query = UserQuery.builder().logins("marius", "john").build();
}
@Test
- public void selectUsersByQuery_search_by_login_text() throws Exception {
+ public void selectUsersByQuery_search_by_login_text() {
setupData("selectUsersByText");
UserQuery query = UserQuery.builder().searchText("sbr").build();
}
@Test
- public void selectUsersByQuery_search_by_name_text() throws Exception {
+ public void selectUsersByQuery_search_by_name_text() {
setupData("selectUsersByText");
UserQuery query = UserQuery.builder().searchText("Simon").build();
}
@Test
- public void selectUsersByQuery_escape_special_characters_in_like() throws Exception {
+ public void selectUsersByQuery_escape_special_characters_in_like() {
setupData("selectUsersByText");
UserQuery query = UserQuery.builder().searchText("%s%").build();
public class UserDtoTest {
@Test
- public void encode_scm_accounts() throws Exception {
+ public void encode_scm_accounts() {
assertThat(UserDto.encodeScmAccounts(null)).isNull();
assertThat(UserDto.encodeScmAccounts(Collections.<String>emptyList())).isNull();
assertThat(UserDto.encodeScmAccounts(Arrays.asList("foo"))).isEqualTo("\nfoo\n");
}
@Test
- public void decode_scm_accounts() throws Exception {
+ public void decode_scm_accounts() {
assertThat(UserDto.decodeScmAccounts(null)).isEmpty();
assertThat(UserDto.decodeScmAccounts("\nfoo\n")).containsOnly("foo");
assertThat(UserDto.decodeScmAccounts("\nfoo\nbar\n")).containsOnly("foo", "bar");
public class MultiSetsTest {
@Test
- public void order_with_highest_count_first() throws Exception {
+ public void order_with_highest_count_first() {
Multiset<String> multiset = HashMultiset.create();
add(multiset, "seneca", 10);
add(multiset, "plato", 5);
NonNullInputFunction<String, Integer> sut = new TestFunction();
@Test
- public void fail_if_null_input() throws Exception {
+ public void fail_if_null_input() {
try {
sut.apply(null);
fail();
}
@Test
- public void apply() throws Exception {
+ public void apply() {
assertThat(sut.apply("foo")).isEqualTo(3);
}
private ResourceModel project;
@Before
- public void before() throws Exception {
+ public void before() {
service = new MeasuresDao(getSession());
project = new ResourceModel(ResourceModel.SCOPE_PROJECT, "foo:bar", ResourceModel.QUALIFIER_PROJECT_TRUNK, null, "Foo");
project.setName("project name");
}
@Test
- public void performanceTestOnBatchInserts() throws Exception {
+ public void performanceTestOnBatchInserts() {
getSession().save(project1);
Snapshot snapshot = new Snapshot(project1, true, "", new Date(1));
getSession().save(snapshot);
}
@Test
- public void should_accept_violations_from_no_sonar_rules() throws Exception {
+ public void should_accept_violations_from_no_sonar_rules() {
// The "No Sonar" rule logs violations on the lines that are flagged with "NOSONAR" !!
Set<Integer> noSonarLines = new HashSet<Integer>();
}
@Test
- public void user_home_property_can_be_null() throws Exception {
+ public void user_home_property_can_be_null() {
FileCache cache = new FileCacheBuilder().setUserHome((String) null).build();
// does not fail. It uses default path or env variable
}
@Test
- public void use_default_path_or_env_variable() throws Exception {
+ public void use_default_path_or_env_variable() {
FileCache cache = new FileCacheBuilder().build();
assertThat(cache.getDir()).isDirectory().exists();
}
@Test
- public void unzip_from_cache() throws IOException, URISyntaxException, InterruptedException, ExecutionException {
+ public void unzip_from_cache() throws IOException, URISyntaxException {
final File samplePlugin = new File(this.getClass().getResource("/sonar-checkstyle-plugin-2.8.jar").toURI());
FileHashes hashes = mock(FileHashes.class);
final FileCache cache = new FileCache(tempFolder.newFolder(), log, hashes);
public class DebtRemediationFunctionTest {
@Test
- public void create_linear() throws Exception {
+ public void create_linear() {
DebtRemediationFunction function = DebtRemediationFunction.createLinear(Duration.create(10));
assertThat(function.type()).isEqualTo(DebtRemediationFunction.Type.LINEAR);
assertThat(function.coefficient()).isEqualTo(Duration.create(10));
}
@Test
- public void create_linear_with_offset() throws Exception {
+ public void create_linear_with_offset() {
DebtRemediationFunction function = DebtRemediationFunction.createLinearWithOffset(Duration.create(10), Duration.create(5));
assertThat(function.type()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET);
assertThat(function.coefficient()).isEqualTo(Duration.create(10));
}
@Test
- public void create_constant_per_issue() throws Exception {
+ public void create_constant_per_issue() {
DebtRemediationFunction function = DebtRemediationFunction.createConstantPerIssue(Duration.create(10));
assertThat(function.type()).isEqualTo(DebtRemediationFunction.Type.CONSTANT_ISSUE);
assertThat(function.coefficient()).isNull();
public class DefaultDebtCharacteristicTest {
@Test
- public void setter_and_getter_on_characteristic() throws Exception {
+ public void setter_and_getter_on_characteristic() {
DefaultDebtCharacteristic debtCharacteristic = new DefaultDebtCharacteristic()
.setId(1)
.setKey("PORTABILITY")
}
@Test
- public void setter_and_getter_on_sub_characteristic() throws Exception {
+ public void setter_and_getter_on_sub_characteristic() {
DefaultDebtCharacteristic debtCharacteristic = new DefaultDebtCharacteristic()
.setId(1)
.setKey("COMPILER")
}
@Test
- public void to_string() throws Exception {
+ public void to_string() {
assertThat(new DefaultDebtCharacteristic()
.setId(1)
.setKey("PORTABILITY")
private DefaultDebtModel debtModel;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
debtModel = new DefaultDebtModel()
.addCharacteristic(
new DefaultDebtCharacteristic().setId(1)
}
@Test
- public void all_characteristics() throws Exception {
+ public void all_characteristics() {
assertThat(debtModel.allCharacteristics()).hasSize(2);
}
@Test
- public void characteristics() throws Exception {
+ public void characteristics() {
assertThat(debtModel.characteristics()).hasSize(1);
}
@Test
- public void sub_characteristics() throws Exception {
+ public void sub_characteristics() {
assertThat(debtModel.subCharacteristics("MEMORY_EFFICIENCY")).hasSize(1);
}
@Test
- public void characteristic_by_id() throws Exception {
+ public void characteristic_by_id() {
DefaultDebtCharacteristic debtCharacteristic = (DefaultDebtCharacteristic) debtModel.characteristicById(1);
assertThat(debtCharacteristic).isNotNull();
assertThat(debtCharacteristic.id()).isEqualTo(1);
}
@Test
- public void characteristic_by_key() throws Exception {
+ public void characteristic_by_key() {
DefaultDebtCharacteristic debtCharacteristic = (DefaultDebtCharacteristic) debtModel.characteristicByKey("EFFICIENCY");
assertThat(debtCharacteristic).isNotNull();
assertThat(debtCharacteristic.id()).isEqualTo(2);
}
@Test
- public void all() throws Exception {
+ public void all() {
Assertions.assertThat(predicates.all().apply(javaFile)).isTrue();
}
@Test
- public void none() throws Exception {
+ public void none() {
assertThat(predicates.none().apply(javaFile)).isFalse();
}
@Test
- public void matches_inclusion_pattern() throws Exception {
+ public void matches_inclusion_pattern() {
assertThat(predicates.matchesPathPattern("src/main/**/Action.java").apply(javaFile)).isTrue();
assertThat(predicates.matchesPathPattern("Action.java").apply(javaFile)).isFalse();
assertThat(predicates.matchesPathPattern("src/**/*.php").apply(javaFile)).isFalse();
}
@Test
- public void matches_inclusion_patterns() throws Exception {
+ public void matches_inclusion_patterns() {
assertThat(predicates.matchesPathPatterns(new String[] {"src/other/**.java", "src/main/**/Action.java"}).apply(javaFile)).isTrue();
assertThat(predicates.matchesPathPatterns(new String[] {}).apply(javaFile)).isTrue();
assertThat(predicates.matchesPathPatterns(new String[] {"src/other/**.java", "src/**/*.php"}).apply(javaFile)).isFalse();
}
@Test
- public void does_not_match_exclusion_pattern() throws Exception {
+ public void does_not_match_exclusion_pattern() {
assertThat(predicates.doesNotMatchPathPattern("src/main/**/Action.java").apply(javaFile)).isFalse();
assertThat(predicates.doesNotMatchPathPattern("Action.java").apply(javaFile)).isTrue();
assertThat(predicates.doesNotMatchPathPattern("src/**/*.php").apply(javaFile)).isTrue();
}
@Test
- public void does_not_match_exclusion_patterns() throws Exception {
+ public void does_not_match_exclusion_patterns() {
assertThat(predicates.doesNotMatchPathPatterns(new String[] {}).apply(javaFile)).isTrue();
assertThat(predicates.doesNotMatchPathPatterns(new String[] {"src/other/**.java", "src/**/*.php"}).apply(javaFile)).isTrue();
assertThat(predicates.doesNotMatchPathPatterns(new String[] {"src/other/**.java", "src/main/**/Action.java"}).apply(javaFile)).isFalse();
}
@Test
- public void has_relative_path() throws Exception {
+ public void has_relative_path() {
assertThat(predicates.hasRelativePath("src/main/java/struts/Action.java").apply(javaFile)).isTrue();
assertThat(predicates.hasRelativePath("src/main/java/struts/Other.java").apply(javaFile)).isFalse();
}
@Test
- public void has_language() throws Exception {
+ public void has_language() {
assertThat(predicates.hasLanguage("java").apply(javaFile)).isTrue();
assertThat(predicates.hasLanguage("php").apply(javaFile)).isFalse();
}
@Test
- public void has_languages() throws Exception {
+ public void has_languages() {
assertThat(predicates.hasLanguages(Arrays.asList("java", "php")).apply(javaFile)).isTrue();
assertThat(predicates.hasLanguages(Arrays.asList("cobol", "php")).apply(javaFile)).isFalse();
assertThat(predicates.hasLanguages(Collections.<String>emptyList()).apply(javaFile)).isTrue();
}
@Test
- public void has_status() throws Exception {
+ public void has_status() {
assertThat(predicates.hasStatus(InputFile.Status.ADDED).apply(javaFile)).isTrue();
assertThat(predicates.hasStatus(InputFile.Status.CHANGED).apply(javaFile)).isFalse();
}
@Test
- public void has_type() throws Exception {
+ public void has_type() {
assertThat(predicates.hasType(InputFile.Type.MAIN).apply(javaFile)).isTrue();
assertThat(predicates.hasType(InputFile.Type.TEST).apply(javaFile)).isFalse();
}
@Test
- public void not() throws Exception {
+ public void not() {
assertThat(predicates.not(predicates.hasType(InputFile.Type.MAIN)).apply(javaFile)).isFalse();
assertThat(predicates.not(predicates.hasType(InputFile.Type.TEST)).apply(javaFile)).isTrue();
}
@Test
- public void and() throws Exception {
+ public void and() {
// empty
assertThat(predicates.and().apply(javaFile)).isTrue();
assertThat(predicates.and(new FilePredicate[0]).apply(javaFile)).isTrue();
}
@Test
- public void or() throws Exception {
+ public void or() {
// empty
assertThat(predicates.or().apply(javaFile)).isTrue();
assertThat(predicates.or(new FilePredicate[0]).apply(javaFile)).isTrue();
}
@Test
- public void add_languages() throws Exception {
+ public void add_languages() {
assertThat(fs.languages()).isEmpty();
fs.addLanguages("java", "php", "cobol");
}
@Test
- public void files() throws Exception {
+ public void files() {
assertThat(fs.inputFiles(fs.predicates().all())).isEmpty();
fs.add(new DefaultInputFile("foo", "src/Foo.php").setLanguage("php"));
}
@Test
- public void input_file_returns_null_if_file_not_found() throws Exception {
+ public void input_file_returns_null_if_file_not_found() {
assertThat(fs.inputFile(fs.predicates().hasRelativePath("src/Bar.java"))).isNull();
assertThat(fs.inputFile(fs.predicates().hasLanguage("cobol"))).isNull();
}
@Test
- public void input_file_fails_if_too_many_results() throws Exception {
+ public void input_file_fails_if_too_many_results() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("expected one element");
}
@Test
- public void input_file_supports_non_indexed_predicates() throws Exception {
+ public void input_file_supports_non_indexed_predicates() {
fs.add(new DefaultInputFile("foo", "src/Bar.java").setLanguage("java"));
// it would fail if more than one java file
public TemporaryFolder temp = new TemporaryFolder();
@Test
- public void match_relative_path() throws Exception {
+ public void match_relative_path() {
PathPattern pattern = PathPattern.create("**/*Foo.java");
assertThat(pattern.toString()).isEqualTo("**/*Foo.java");
}
@Test
- public void create_array_of_patterns() throws Exception {
+ public void create_array_of_patterns() {
PathPattern[] patterns = PathPattern.create(new String[] {
"**/src/main/**Foo.java",
"file:**/src/main/**Bar.java"
public class ActiveRulesBuilderTest {
@Test
- public void no_rules() throws Exception {
+ public void no_rules() {
ActiveRulesBuilder builder = new ActiveRulesBuilder();
ActiveRules rules = builder.build();
assertThat(rules.findAll()).isEmpty();
}
@Test
- public void build_rules() throws Exception {
+ public void build_rules() {
ActiveRules activeRules = new ActiveRulesBuilder()
.create(RuleKey.of("squid", "S0001"))
.setName("My Rule")
}
@Test
- public void fail_to_add_twice_the_same_rule() throws Exception {
+ public void fail_to_add_twice_the_same_rule() {
ActiveRulesBuilder builder = new ActiveRulesBuilder();
builder.create(RuleKey.of("squid", "S0001")).activate();
try {
public class RulesBuilderTest {
@Test
- public void no_rules() throws Exception {
+ public void no_rules() {
RulesBuilder builder = new RulesBuilder();
Rules rules = builder.build();
assertThat(rules.findAll()).isEmpty();
}
@Test
- public void build_rules() throws Exception {
+ public void build_rules() {
RulesBuilder builder = new RulesBuilder();
NewRule newSquid1 = builder.add(RuleKey.of("squid", "S0001"));
newSquid1.setName("Detect bug");
}
@Test
- public void fail_to_add_twice_the_same_rule() throws Exception {
+ public void fail_to_add_twice_the_same_rule() {
RulesBuilder builder = new RulesBuilder();
builder.add(RuleKey.of("squid", "S0001"));
try {
}
@Test
- public void fail_to_add_twice_the_same_param() throws Exception {
+ public void fail_to_add_twice_the_same_param() {
RulesBuilder builder = new RulesBuilder();
NewRule newRule = builder.add(RuleKey.of("squid", "S0001"));
newRule.addParam("min");
}
@Test
- public void should_register_highlighting_rule() throws Exception {
+ public void should_register_highlighting_rule() {
assertThat(highlightingRules).hasSize(6);
}
}
@Test
- public void should_order_by_start_then_end_offset() throws Exception {
+ public void should_order_by_start_then_end_offset() {
assertThat(highlightingRules).extracting("range", TextRange.class).containsExactly(rangeOf(1, 0, 1, 10),
rangeOf(1, 10, 1, 12),
rangeOf(1, 12, 1, 20),
}
@Test
- public void should_suport_overlapping() throws Exception {
+ public void should_suport_overlapping() {
new DefaultHighlighting(mock(SensorStorage.class))
.onFile(INPUT_FILE)
.highlight(0, 15, KEYWORD)
}
@Test
- public void should_prevent_boudaries_overlapping() throws Exception {
+ public void should_prevent_boudaries_overlapping() {
throwable.expect(IllegalStateException.class);
throwable
.expectMessage("Cannot register highlighting rule for characters at Range[from [line=1, lineOffset=8] to [line=1, lineOffset=15]] as it overlaps at least one existing rule");
}
@Test
- public void doesNotHaveSecretKey() throws Exception {
+ public void doesNotHaveSecretKey() {
AesCipher cipher = new AesCipher("/my/twitter/id/is/SimonBrandhof");
assertThat(cipher.hasSecretKey(), Matchers.is(false));
}
@Test
- public void should_normalize_key() throws Exception {
+ public void should_normalize_key() {
assertThat(new Category("Licenses").key()).isEqualTo("licenses");
}
@Test
- public void should_use_original_key() throws Exception {
+ public void should_use_original_key() {
assertThat(new Category("Licenses").toString()).isEqualTo("Licenses");
}
}
@Test
- public void setProperty_date() throws Exception {
+ public void setProperty_date() {
Settings settings = new Settings();
Date date = DateUtils.parseDateTime("2010-05-18T15:50:45+0100");
settings.setProperty("aDate", date);
public class MeasureModelTest {
@Test
- public void text_is_utf8() throws UnsupportedEncodingException {
+ public void text_is_utf8() {
String s = "accents éà and special characters ç€";
MeasureModel measure = new MeasureModel();
}
@Test
- public void should_accept_issues_on_no_sonar_rules() throws Exception {
+ public void should_accept_issues_on_no_sonar_rules() {
// The "No Sonar" rule logs violations on the lines that are flagged with "NOSONAR" !!
Issue issue = mock(Issue.class);
when(issue.componentKey()).thenReturn("struts:org.apache.Action");
}
@Test
- public void key_should_be_set() throws Exception {
+ public void key_should_be_set() {
try {
new Action("");
fail();
}
@Test
- public void should_verify_conditions() throws Exception {
+ public void should_verify_conditions() {
DefaultIssue issue = new DefaultIssue();
Action action = new Action("link-to-jira")
.setConditions(condition1, condition2);
public class ActionsTest {
@Test
- public void add_action() throws Exception {
+ public void add_action() {
Actions actions = new Actions();
actions.add("plan");
DefaultIssue issue = new DefaultIssue();
@Test
- public void should_match() throws Exception {
+ public void should_match() {
HasResolution condition = new HasResolution(Issue.RESOLUTION_FIXED, Issue.RESOLUTION_FALSE_POSITIVE);
assertThat(condition.matches(issue.setResolution("FIXED"))).isTrue();
DefaultIssue issue = new DefaultIssue();
@Test
- public void should_match() throws Exception {
+ public void should_match() {
HasStatus condition = new HasStatus("OPEN", "REOPENED", "CONFIRMED");
assertThat(condition.matches(issue.setStatus("OPEN"))).isTrue();
DefaultIssue issue = new DefaultIssue();
@Test
- public void should_match() throws Exception {
+ public void should_match() {
IsUnResolved condition = new IsUnResolved();
assertThat(condition.matches(issue)).isTrue();
Condition target = Mockito.mock(Condition.class);
@Test
- public void should_match_opposite() throws Exception {
+ public void should_match_opposite() {
NotCondition condition = new NotCondition(target);
when(target.matches(any(Issue.class))).thenReturn(true);
}
@Test
- public void set_empty_dates() throws Exception {
+ public void set_empty_dates() {
issue
.setCreationDate(null)
.setUpdateDate(null)
}
@Test
- public void setAttributes_should_not_clear_existing_values() throws Exception {
+ public void setAttributes_should_not_clear_existing_values() {
issue.setAttributes(ImmutableMap.of("1", "one"));
assertThat(issue.attribute("1")).isEqualTo("one");
}
@Test
- public void comments_should_not_be_modifiable() throws Exception {
+ public void comments_should_not_be_modifiable() {
DefaultIssue issue = new DefaultIssue().setKey("AAA");
List<IssueComment> comments = issue.comments();
}
@Test
- public void all_changes_contain_current_change() throws Exception {
+ public void all_changes_contain_current_change() {
IssueChangeContext issueChangeContext = mock(IssueChangeContext.class);
DefaultIssue issue = new DefaultIssue().setKey("AAA").setFieldChange(issueChangeContext, "actionPlan", "1.0", "1.1");
FieldDiffs diffs = new FieldDiffs();
@Test
- public void diffs_should_be_empty_by_default() throws Exception {
+ public void diffs_should_be_empty_by_default() {
assertThat(diffs.diffs()).isEmpty();
}
}
@Test
- public void diff_with_long_values() throws Exception {
+ public void diff_with_long_values() {
diffs.setDiff("technicalDebt", 50l, "100");
FieldDiffs.Diff diff = diffs.diffs().get("technicalDebt");
}
@Test
- public void diff_with_empty_long_values() throws Exception {
+ public void diff_with_empty_long_values() {
diffs.setDiff("technicalDebt", null, "");
FieldDiffs.Diff diff = diffs.diffs().get("technicalDebt");
}
@Test
- public void should_keep_old_value() throws Exception {
+ public void should_keep_old_value() {
diffs.setDiff("severity", "BLOCKER", "INFO");
diffs.setDiff("severity", null, "MAJOR");
FieldDiffs.Diff diff = diffs.diffs().get("severity");
}
@Test
- public void shouldSumOnVariation() throws Exception {
+ public void shouldSumOnVariation() {
Measure measure1 = new Measure(CoreMetrics.NEW_VIOLATIONS).setVariation1(1.0).setVariation2(1.0).setVariation3(3.0);
Measure measure2 = new Measure(CoreMetrics.NEW_VIOLATIONS).setVariation1(1.0).setVariation2(2.0).setVariation3(3.0);
List<Measure> children = Arrays.asList(measure1, measure2);
}
@Test
- public void shouldNotPersistWhenScopeLowerThanMinimun() throws Exception {
+ public void shouldNotPersistWhenScopeLowerThanMinimun() {
when(context.getResource()).thenReturn(File.create("org/Foo.java"));
initContextWithChildren();
}
@Test
- public void shouldPersistWhenScopeEqualsMinimun() throws Exception {
+ public void shouldPersistWhenScopeEqualsMinimun() {
when(context.getResource()).thenReturn(File.create("org/Foo.java"));
initContextWithChildren();
}
@Test
- public void shouldPersistWhenScopeHigherThanMinimun() throws Exception {
+ public void shouldPersistWhenScopeHigherThanMinimun() {
when(context.getResource()).thenReturn(Directory.create("org/foo"));
initContextWithChildren();
* are not defined.
*/
@Test
- public void should_close_components_without_lifecycle() throws Exception {
+ public void should_close_components_without_lifecycle() {
ComponentContainer container = new ComponentContainer();
CloseableComponent component = new CloseableComponent();
container.add(component);
* Method close() must be executed after stop()
*/
@Test
- public void should_close_components_with_lifecycle() throws Exception {
+ public void should_close_components_with_lifecycle() {
ComponentContainer container = new ComponentContainer();
StartableCloseableComponent component = new StartableCloseableComponent();
container.add(component);
ComponentKeys keys = new ComponentKeys();
@Test
- public void generate_key_of_class() throws Exception {
+ public void generate_key_of_class() {
assertThat(keys.of(FakeComponent.class)).isEqualTo(FakeComponent.class);
}
@Test
- public void generate_key_of_object() throws Exception {
+ public void generate_key_of_object() {
assertThat(keys.of(new FakeComponent())).isEqualTo("org.sonar.api.platform.ComponentKeysTest.FakeComponent-fake");
}
@Test
- public void should_log_warning_if_toString_is_not_overridden() throws Exception {
+ public void should_log_warning_if_toString_is_not_overridden() {
Logger log = mock(Logger.class);
keys.of(new Object(), log);
verifyZeroInteractions(log);
}
@Test
- public void should_generate_unique_key_when_toString_is_not_overridden() throws Exception {
+ public void should_generate_unique_key_when_toString_is_not_overridden() {
Object key = keys.of(new WrongToStringImpl());
assertThat(key).isNotEqualTo(WrongToStringImpl.KEY);
}
@Test
- public void key_can_contain_colons() throws Exception {
+ public void key_can_contain_colons() {
RuleKey key = RuleKey.of("squid", "Key:With:Some::Colons");
assertThat(key.repository()).isEqualTo("squid");
assertThat(key.rule()).isEqualTo("Key:With:Some::Colons");
}
@Test
- public void repository_must_not_be_null() throws Exception {
+ public void repository_must_not_be_null() {
try {
RuleKey.of(null, "NullDeref");
fail();
}
@Test
- public void repository_must_not_be_empty() throws Exception {
+ public void repository_must_not_be_empty() {
try {
RuleKey.of("", "NullDeref");
fail();
}
@Test
- public void rule_must_not_be_null() throws Exception {
+ public void rule_must_not_be_null() {
try {
RuleKey.of("squid", null);
fail();
}
@Test
- public void rule_must_not_be_empty() throws Exception {
+ public void rule_must_not_be_empty() {
try {
RuleKey.of("squid", "");
fail();
}
@Test
- public void encode_and_decode_string() throws Exception {
+ public void encode_and_decode_string() {
RuleKey key = RuleKey.of("squid", "NullDeref");
String serialized = key.toString();
assertThat(serialized).isEqualTo("squid:NullDeref");
}
@Test
- public void parse_key_with_colons() throws Exception {
+ public void parse_key_with_colons() {
RuleKey key = RuleKey.parse("squid:Key:With:Some::Colons");
assertThat(key.repository()).isEqualTo("squid");
assertThat(key.rule()).isEqualTo("Key:With:Some::Colons");
}
@Test
- public void not_accept_bad_format() throws Exception {
+ public void not_accept_bad_format() {
try {
RuleKey.parse("foo");
fail();
public class RuleStatusTest {
@Test
- public void default_is_ready() throws Exception {
+ public void default_is_ready() {
assertThat(RuleStatus.defaultStatus()).isEqualTo(RuleStatus.READY);
}
}
}
@Test
- public void default_is_major() throws Exception {
+ public void default_is_major() {
assertThat(Severity.defaultSeverity()).isEqualTo(Severity.MAJOR);
}
}
public class DefaultDebtCharacteristicTest {
@Test
- public void setter_and_getter_on_characteristic() throws Exception {
+ public void setter_and_getter_on_characteristic() {
DefaultDebtCharacteristic debtCharacteristic = new DefaultDebtCharacteristic()
.setId(1)
.setKey("PORTABILITY")
}
@Test
- public void setter_and_getter_on_sub_characteristic() throws Exception {
+ public void setter_and_getter_on_sub_characteristic() {
DefaultDebtCharacteristic debtCharacteristic = new DefaultDebtCharacteristic()
.setId(1)
.setKey("COMPILER")
}
@Test
- public void to_string() throws Exception {
+ public void to_string() {
assertThat(new DefaultDebtCharacteristic()
.setId(1)
.setKey("PORTABILITY")
}
@Test
- public void support_deprecated_formats() throws Exception {
+ public void support_deprecated_formats() {
assertThat(RuleParamType.parse("b")).isEqualTo(RuleParamType.BOOLEAN);
assertThat(RuleParamType.parse("i")).isEqualTo(RuleParamType.INTEGER);
assertThat(RuleParamType.parse("i{}")).isEqualTo(RuleParamType.INTEGER);
RulesDefinitionI18nLoader loader = new RulesDefinitionI18nLoader(i18n);
@Test
- public void complete_rule_name_and_description() throws Exception {
+ public void complete_rule_name_and_description() {
when(i18n.getName("squid", "S0001")).thenReturn("SOne");
when(i18n.getDescription("squid", "S0001")).thenReturn("S One");
}
@Test
- public void do_not_override_if_no_bundle() throws Exception {
+ public void do_not_override_if_no_bundle() {
// i18n returns null values
RulesDefinition.Context context = new RulesDefinition.Context();
}
@Test
- public void override_existing() throws Exception {
+ public void override_existing() {
when(i18n.getName("squid", "S0001")).thenReturn("SOne");
when(i18n.getDescription("squid", "S0001")).thenReturn("S One");
}
@Test
- public void complete_param_description() throws Exception {
+ public void complete_param_description() {
when(i18n.getParamDescription("squid", "S0001", "max")).thenReturn("Maximum");
RulesDefinition.Context context = new RulesDefinition.Context();
RulesDefinition.Context context = new RulesDefinition.Context();
@Test
- public void define_repositories() throws Exception {
+ public void define_repositories() {
assertThat(context.repositories()).isEmpty();
context.createRepository("findbugs", "java").setName("Findbugs").done();
}
@Test
- public void cant_set_blank_repository_name() throws Exception {
+ public void cant_set_blank_repository_name() {
context.createRepository("findbugs", "java").setName(null).done();
assertThat(context.repository("findbugs").name()).isEqualTo("findbugs");
}
@Test
- public void parse_xml() throws Exception {
+ public void parse_xml() {
InputStream input = getClass().getResourceAsStream("/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/rules.xml");
RulesDefinition.Repository repository = load(input, Charsets.UTF_8.name());
assertThat(repository.rules()).hasSize(2);
}
@Test
- public void fail_if_invalid_xml() throws UnsupportedEncodingException {
+ public void fail_if_invalid_xml() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("XML is not valid");
}
@Test
- public void support_deprecated_format() throws UnsupportedEncodingException {
+ public void support_deprecated_format() {
// the deprecated format uses some attributes instead of nodes
InputStream input = getClass().getResourceAsStream("/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/deprecated.xml");
RulesDefinition.Repository repository = load(input, Charsets.UTF_8.name());
SimpleRequest request = new SimpleRequest();
@Before
- public void before() throws Exception {
+ public void before() {
WebService.Context context = new WebService.Context();
new SimpleWebService().define(context);
request.setAction(context.controller("my_controller").action("my_action"));
}
@Test
- public void has_param() throws Exception {
+ public void has_param() {
request.setParam("a_required_string", "foo");
assertThat(request.hasParam("a_required_string")).isTrue();
}
@Test
- public void required_param_is_missing() throws Exception {
+ public void required_param_is_missing() {
try {
request.mandatoryParam("required_param");
fail();
}
@Test
- public void required_param() throws Exception {
+ public void required_param() {
request.setParam("a_required_string", "foo");
request.setParam("a_required_number", "42");
request.setParam("a_required_boolean", "true");
}
@Test
- public void required_param_as_strings() throws Exception {
+ public void required_param_as_strings() {
try {
request.mandatoryParamAsStrings("a_required_string");
} catch (IllegalArgumentException e) {
}
@Test
- public void default_value_of_optional_param() throws Exception {
+ public void default_value_of_optional_param() {
assertThat(request.param("has_default_string")).isEqualTo("the_default_string");
}
@Test
- public void param_as_string() throws Exception {
+ public void param_as_string() {
assertThat(request.setParam("a_string", "foo").param("a_string")).isEqualTo("foo");
}
@Test
- public void null_param() throws Exception {
+ public void null_param() {
assertThat(request.param("a_string")).isNull();
assertThat(request.paramAsBoolean("a_boolean")).isNull();
assertThat(request.paramAsInt("a_number")).isNull();
}
@Test
- public void param_as_int() throws Exception {
+ public void param_as_int() {
assertThat(request.setParam("a_number", "123").paramAsInt("a_number")).isEqualTo(123);
}
@Test
- public void param_as_long() throws Exception {
+ public void param_as_long() {
assertThat(request.setParam("a_number", "123").paramAsLong("a_number")).isEqualTo(123L);
assertThat(request.setParam("a_number", "123").paramAsLong("a_number", 42L)).isEqualTo(123L);
assertThat(request.setParam("a_number", null).paramAsLong("a_number", 42L)).isEqualTo(123L);
}
@Test
- public void param_as_boolean() throws Exception {
+ public void param_as_boolean() {
assertThat(request.setParam("a_boolean", "true").paramAsBoolean("a_boolean")).isTrue();
assertThat(request.setParam("a_boolean", "yes").paramAsBoolean("a_boolean")).isTrue();
assertThat(request.setParam("a_boolean", "false").paramAsBoolean("a_boolean")).isFalse();
}
@Test
- public void param_as_enum() throws Exception {
+ public void param_as_enum() {
assertThat(request.setParam("a_enum", "BETA").paramAsEnum("a_enum", RuleStatus.class)).isEqualTo(RuleStatus.BETA);
}
@Test
- public void param_as_enums() throws Exception {
+ public void param_as_enums() {
assertThat(request.setParam("a_enum", "BETA,READY").paramAsEnums("a_enum", RuleStatus.class)).containsOnly(
RuleStatus.BETA, RuleStatus.READY);
}
@Test
- public void param_as_date() throws Exception {
+ public void param_as_date() {
assertThat(request.setParam("a_date", "2014-05-27").paramAsDate("a_date")).isEqualTo(DateUtils.parseDate("2014-05-27"));
}
@Test
- public void param_as_datetime() throws Exception {
+ public void param_as_datetime() {
assertThat(request.setParam("a_datetime", "2014-05-27T15:50:45+0100").paramAsDateTime("a_datetime")).isEqualTo(DateUtils.parseDateTime("2014-05-27T15:50:45+0100"));
assertThat(request.setParam("a_datetime", "2014-05-27").paramAsDateTime("a_datetime")).isEqualTo(DateUtils.parseDate("2014-05-27"));
try {
}
@Test
- public void param_as_strings() throws Exception {
+ public void param_as_strings() {
assertThat(request.paramAsStrings("a_string")).isNull();
assertThat(request.setParam("a_string", "").paramAsStrings("a_string")).isEmpty();
assertThat(request.setParam("a_string", "bar").paramAsStrings("a_string")).containsExactly("bar");
}
@Test
- public void deprecated_key() throws Exception {
+ public void deprecated_key() {
assertThat(request.setParam("deprecated_param", "bar").param("new_param")).isEqualTo("bar");
}
@Test
- public void fail_if_param_is_not_defined() throws Exception {
+ public void fail_if_param_is_not_defined() {
try {
request.param("unknown");
} catch (IllegalArgumentException e) {
}
@Test
- public void verify_possible_values() throws Exception {
+ public void verify_possible_values() {
request.setParam("has_possible_values", "foo");
assertThat(request.param("has_possible_values")).isEqualTo("foo");
public class SimpleGetRequestTest {
@Test
- public void method() throws Exception {
+ public void method() {
SimpleGetRequest request = new SimpleGetRequest();
assertThat(request.method()).isEqualTo("GET");
}
@Test
- public void has_param() throws Exception {
+ public void has_param() {
SimpleGetRequest request = new SimpleGetRequest();
assertThat(request.method()).isEqualTo("GET");
}
@Test
- public void set_name_as_key() throws Exception {
+ public void set_name_as_key() {
DefaultCharacteristic characteristic = new DefaultCharacteristic()
.setId(1)
.setName("Compiler related portability", true);
}
@Test
- public void add_requirement() throws Exception {
+ public void add_requirement() {
DefaultRequirement requirement = new DefaultRequirement().setRuleKey(RuleKey.of("repo", "rule"));
DefaultCharacteristic characteristic = new DefaultCharacteristic()
}
@Test
- public void add_child() throws Exception {
+ public void add_child() {
DefaultCharacteristic root = new DefaultCharacteristic()
.setId(1)
.setKey("REUSABILITY");
@Test
- public void is_root() throws Exception {
+ public void is_root() {
DefaultCharacteristic characteristic = new DefaultCharacteristic()
.setId(1)
.setKey("NETWORK_USE")
}
@Test
- public void is_root() throws Exception {
+ public void is_root() {
DefaultCharacteristic characteristic = new DefaultCharacteristic()
.setId(1)
.setKey("NETWORK_USE")
}
@Test
- public void is_requirement() throws Exception {
+ public void is_requirement() {
DefaultCharacteristic requirement = new DefaultCharacteristic()
.setId(1)
.setRuleKey(RuleKey.of("repo", "rule"))
}
@Test
- public void should_limit_number_of_logins() throws Exception {
+ public void should_limit_number_of_logins() {
List<String> logins = new ArrayList<String>();
for (int i = 0; i < 1010; i++) {
logins.add(String.valueOf(i));
}
@Test
- public void searchText() throws Exception {
+ public void searchText() {
UserQuery query = UserQuery.builder().searchText("sim").build();
assertThat(query.searchText()).isEqualTo("sim");
assertThat(query.searchTextSql).isEqualTo("%sim%");
}
@Test
- public void searchText_escape_special_characters_in_like() throws Exception {
+ public void searchText_escape_special_characters_in_like() {
UserQuery query = UserQuery.builder().searchText("%sim_").build();
assertThat(query.searchText()).isEqualTo("%sim_");
assertThat(query.searchTextSql).isEqualTo("%/%sim/_%");
}
@Test
- public void format_date_time_null_safe() throws Exception {
+ public void format_date_time_null_safe() {
Assertions.assertThat(DateUtils.formatDateTimeNullSafe(new Date())).startsWith("20");
Assertions.assertThat(DateUtils.formatDateTimeNullSafe(new Date()).length()).isGreaterThan(20);
Assertions.assertThat(DateUtils.formatDateTimeNullSafe(null)).isEmpty();
}
@Test
- public void long_to_date() throws Exception {
+ public void long_to_date() {
Date date = new Date();
Assertions.assertThat(DateUtils.longToDate(date.getTime())).isEqualTo(date);
Assertions.assertThat(DateUtils.longToDate(null)).isNull();
}
@Test
- public void date_to_long() throws Exception {
+ public void date_to_long() {
Date date = new Date();
Assertions.assertThat(DateUtils.dateToLong(date)).isEqualTo(date.getTime());
Assertions.assertThat(DateUtils.dateToLong(null)).isEqualTo(null);
static final Long ONE_DAY_IN_MINUTES = ONE_HOUR_IN_MINUTES * HOURS_IN_DAY;
@Test
- public void create_from_duration_in_minutes() throws Exception {
+ public void create_from_duration_in_minutes() {
Duration duration = Duration.create(ONE_DAY_IN_MINUTES + ONE_HOUR_IN_MINUTES + ONE_MINUTE);
assertThat(duration.toMinutes()).isEqualTo(ONE_DAY_IN_MINUTES + ONE_HOUR_IN_MINUTES + ONE_MINUTE);
}
@Test
- public void encode() throws Exception {
+ public void encode() {
assertThat(Duration.create(2 * ONE_DAY_IN_MINUTES + 5 * ONE_HOUR_IN_MINUTES + 46 * ONE_MINUTE).encode(HOURS_IN_DAY)).isEqualTo("2d5h46min");
assertThat(Duration.create(ONE_DAY_IN_MINUTES).encode(HOURS_IN_DAY)).isEqualTo("1d");
assertThat(Duration.create(ONE_HOUR_IN_MINUTES).encode(HOURS_IN_DAY)).isEqualTo("1h");
}
@Test
- public void decode() throws Exception {
+ public void decode() {
assertThat(Duration.decode(" 15 d 23 h 42min ", HOURS_IN_DAY)).isEqualTo(Duration.create(15 * ONE_DAY_IN_MINUTES + 23 * ONE_HOUR_IN_MINUTES + 42 * ONE_MINUTE));
assertThat(Duration.decode("15d23h42min", HOURS_IN_DAY)).isEqualTo(Duration.create(15 * ONE_DAY_IN_MINUTES + 23 * ONE_HOUR_IN_MINUTES + 42 * ONE_MINUTE));
assertThat(Duration.decode("23h", HOURS_IN_DAY)).isEqualTo(Duration.create(23 * ONE_HOUR_IN_MINUTES));
}
@Test
- public void fail_to_decode_if_unit_with_invalid_number() throws Exception {
+ public void fail_to_decode_if_unit_with_invalid_number() {
try {
Duration.decode("Xd", HOURS_IN_DAY);
fail();
}
@Test
- public void fail_to_decode_if_no_valid_duration() throws Exception {
+ public void fail_to_decode_if_no_valid_duration() {
try {
Duration.decode("foo", HOURS_IN_DAY);
fail();
}
@Test
- public void fail_to_decode_if_only_number() throws Exception {
+ public void fail_to_decode_if_only_number() {
try {
Duration.decode("15", HOURS_IN_DAY);
fail();
}
@Test
- public void fail_to_decode_if_valid_unit_with_invalid_duration() throws Exception {
+ public void fail_to_decode_if_valid_unit_with_invalid_duration() {
try {
Duration.decode("15min foo", HOURS_IN_DAY);
fail();
}
@Test
- public void is_greater_than() throws Exception {
+ public void is_greater_than() {
assertThat(Duration.decode("1h", HOURS_IN_DAY).isGreaterThan(Duration.decode("1min", HOURS_IN_DAY))).isTrue();
assertThat(Duration.decode("1min", HOURS_IN_DAY).isGreaterThan(Duration.decode("1d", HOURS_IN_DAY))).isFalse();
assertThat(Duration.decode("1d", HOURS_IN_DAY).isGreaterThan(Duration.decode("1d", HOURS_IN_DAY))).isFalse();
}
@Test
- public void add() throws Exception {
+ public void add() {
assertThat(Duration.decode("1h", HOURS_IN_DAY).add(Duration.decode("1min", HOURS_IN_DAY))).isEqualTo(Duration.decode("1h1min", HOURS_IN_DAY));
}
@Test
- public void subtract() throws Exception {
+ public void subtract() {
assertThat(Duration.decode("1h", HOURS_IN_DAY).subtract(Duration.decode("1min", HOURS_IN_DAY))).isEqualTo(Duration.decode("59min", HOURS_IN_DAY));
}
@Test
- public void multiply() throws Exception {
+ public void multiply() {
assertThat(Duration.decode("1h", HOURS_IN_DAY).multiply(2)).isEqualTo(Duration.decode("2h", HOURS_IN_DAY));
}
Durations durations;
@Before
- public void setUp() throws Exception {
+ public void setUp() {
settings = new Settings();
settings.setProperty(CoreProperties.HOURS_IN_DAY, HOURS_IN_DAY);
durations = new Durations(settings, i18n);
}
@Test
- public void create_from_minutes() throws Exception {
+ public void create_from_minutes() {
assertThat(durations.create(10L).toMinutes()).isEqualTo(10L);
}
@Test
- public void decode() throws Exception {
+ public void decode() {
// 1 working day -> 8 hours
assertThat(durations.decode("1d").toMinutes()).isEqualTo(8L * ONE_HOUR);
// 8 hours
}
@Test
- public void helper_parse_methods() throws Exception {
+ public void helper_parse_methods() {
assertThat(KeyValueFormat.parseIntDate("1=2014-01-15")).hasSize(1);
assertThat(KeyValueFormat.parseIntDateTime("1=2014-01-15T15:50:45+0100")).hasSize(1);
assertThat(KeyValueFormat.parseIntDouble("1=3.14")).hasSize(1);
}
@Test
- public void helper_format_methods() throws Exception {
+ public void helper_format_methods() {
assertThat(KeyValueFormat.formatIntDateTime(ImmutableMap.of(1, new Date()))).startsWith("1=");
assertThat(KeyValueFormat.formatIntDate(ImmutableMap.of(1, new Date()))).startsWith("1=");
assertThat(KeyValueFormat.formatIntDouble(ImmutableMap.of(1, 3.14))).startsWith("1=");
}
@Test
- public void escape_strings() throws Exception {
+ public void escape_strings() {
Map<String, String> input = Maps.newLinkedHashMap();
input.put("foo", "a=b=c");
input.put("bar", "a;b;c");
}
@Test
- public void not_instantiable() throws Exception {
+ public void not_instantiable() {
// only static methods. Bad pattern, should be improved.
TestUtils.hasOnlyPrivateConstructors(KeyValueFormat.class);
}
public class MessageExceptionTest {
@Test
- public void should_create_exception() throws Exception {
+ public void should_create_exception() {
String message = "the message";
MessageException exception = MessageException.of(message);
assertThat(exception.getMessage()).isEqualTo(message);
}
@Test
- public void page_size_should_be_strictly_positive() throws Exception {
+ public void page_size_should_be_strictly_positive() {
try {
Paging.create(0, 5, 5);
fail();
}
@Test
- public void page_index_should_be_strictly_positive() throws Exception {
+ public void page_index_should_be_strictly_positive() {
try {
Paging.create(5, 0, 5);
fail();
}
@Test
- public void total_items_should_be_positive() throws Exception {
+ public void total_items_should_be_positive() {
try {
Paging.create(5, 5, -1);
fail();
}
@Test
- public void haveFunGetCoverage() throws Exception {
+ public void haveFunGetCoverage() {
// does not fail
new PathUtils();
}
}
@Test
- public void close() throws Exception {
+ public void close() {
class MyCloseable implements Closeable {
boolean isClosed = false;
@Override
}
@Test
- public void close_throws_exception_on_error() throws Exception {
+ public void close_throws_exception_on_error() {
Closeable closeable = new Closeable() {
@Override
public void close() throws IOException {
}
@Test
- public void getDefaultTimezone() throws Exception {
+ public void getDefaultTimezone() {
assertThat(System2.INSTANCE.getDefaultTimeZone().getID()).isEqualTo(TimeZone.getDefault().getID());
}
public class TimeUtilsTest {
@Test
- public void formatDuration() throws Exception {
+ public void formatDuration() {
assertThat(TimeUtils.formatDuration(0)).isEqualTo("0ms");
assertThat(TimeUtils.formatDuration(100)).isEqualTo("100ms");
assertThat(TimeUtils.formatDuration(1000)).isEqualTo("1s");
}
@Test
- public void file_readString() throws Exception {
+ public void file_readString() {
UriReader uriReader = new UriReader(new UriReader.SchemeProcessor[0]);
assertThat(uriReader.readString(testFile, Charsets.UTF_8)).isEqualTo("in foo");
}
@Test
- public void file_readBytes() throws Exception {
+ public void file_readBytes() {
UriReader uriReader = new UriReader(new UriReader.SchemeProcessor[0]);
assertThat(new String(uriReader.readBytes(testFile))).isEqualTo("in foo");
}
public class WorkUnitTest {
@Test
- public void create() throws Exception {
+ public void create() {
WorkUnit workUnit = WorkUnit.create(2.0, "mn");
assertThat(workUnit.getUnit()).isEqualTo("mn");
assertThat(workUnit.getValue()).isEqualTo(2.0);
}
@Test
- public void create_default() throws Exception {
+ public void create_default() {
WorkUnit workUnit = WorkUnit.create();
assertThat(workUnit.getUnit()).isEqualTo("d");
assertThat(workUnit.getValue()).isEqualTo(0.0);
}
@Test
- public void fail_with_bad_unit() throws Exception {
+ public void fail_with_bad_unit() {
try {
WorkUnit.create(2.0, "z");
} catch (Exception e) {
}
@Test
- public void fail_with_bad_value() throws Exception {
+ public void fail_with_bad_value() {
try {
WorkUnit.create(-2.0, "mn");
} catch (Exception e) {
public class UuidsTest {
@Test
- public void create_unique() throws Exception {
+ public void create_unique() {
Set<String> all = Sets.newHashSet();
for (int i = 0; i < 50; i++) {
String uuid = Uuids.create();
}
@Test
- public void constructor_is_private() throws Exception {
+ public void constructor_is_private() {
TestUtils.hasOnlyPrivateConstructors(Uuids.class);
}
}
static final Long ONE_DAY_IN_MINUTES = ONE_HOUR_IN_MINUTES * HOURS_IN_DAY;
@Test
- public void create_from_days_hours_minutes() throws Exception {
+ public void create_from_days_hours_minutes() {
WorkDuration workDuration = WorkDuration.create(1, 1, 1, HOURS_IN_DAY);
assertThat(workDuration.days()).isEqualTo(1);
assertThat(workDuration.hours()).isEqualTo(1);
}
@Test
- public void create_from_value_and_unit() throws Exception {
+ public void create_from_value_and_unit() {
WorkDuration result = WorkDuration.createFromValueAndUnit(1, WorkDuration.UNIT.DAYS, HOURS_IN_DAY);
assertThat(result.days()).isEqualTo(1);
assertThat(result.hours()).isEqualTo(0);
}
@Test
- public void create_from_minutes() throws Exception {
+ public void create_from_minutes() {
WorkDuration workDuration = WorkDuration.createFromMinutes(ONE_MINUTE, HOURS_IN_DAY);
assertThat(workDuration.days()).isEqualTo(0);
assertThat(workDuration.hours()).isEqualTo(0);
}
@Test
- public void create_from_working_long() throws Exception {
+ public void create_from_working_long() {
// 1 minute
WorkDuration workDuration = WorkDuration.createFromLong(1L, HOURS_IN_DAY);
assertThat(workDuration.days()).isEqualTo(0);
}
@Test
- public void convert_to_seconds() throws Exception {
+ public void convert_to_seconds() {
assertThat(WorkDuration.createFromValueAndUnit(2, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).toMinutes()).isEqualTo(2L * ONE_MINUTE);
assertThat(WorkDuration.createFromValueAndUnit(2, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).toMinutes()).isEqualTo(2L * ONE_HOUR_IN_MINUTES);
assertThat(WorkDuration.createFromValueAndUnit(2, WorkDuration.UNIT.DAYS, HOURS_IN_DAY).toMinutes()).isEqualTo(2L * ONE_DAY_IN_MINUTES);
}
@Test
- public void convert_to_working_days() throws Exception {
+ public void convert_to_working_days() {
assertThat(WorkDuration.createFromValueAndUnit(2, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).toWorkingDays()).isEqualTo(2d / 60d / 8d);
assertThat(WorkDuration.createFromValueAndUnit(240, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).toWorkingDays()).isEqualTo(0.5);
assertThat(WorkDuration.createFromValueAndUnit(4, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).toWorkingDays()).isEqualTo(0.5);
}
@Test
- public void convert_to_working_long() throws Exception {
+ public void convert_to_working_long() {
assertThat(WorkDuration.createFromValueAndUnit(2, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).toLong()).isEqualTo(2l);
assertThat(WorkDuration.createFromValueAndUnit(4, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).toLong()).isEqualTo(400l);
assertThat(WorkDuration.createFromValueAndUnit(10, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).toLong()).isEqualTo(10200l);
}
@Test
- public void add() throws Exception {
+ public void add() {
// 4h + 5h = 1d 1h
WorkDuration result = WorkDuration.createFromValueAndUnit(4, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).add(WorkDuration.createFromValueAndUnit(5, WorkDuration.UNIT.HOURS, HOURS_IN_DAY));
assertThat(result.days()).isEqualTo(1);
}
@Test
- public void subtract() throws Exception {
+ public void subtract() {
// 1d 1h - 5h = 4h
WorkDuration result = WorkDuration.create(1, 1, 0, HOURS_IN_DAY).subtract(WorkDuration.createFromValueAndUnit(5, WorkDuration.UNIT.HOURS, HOURS_IN_DAY));
assertThat(result.days()).isEqualTo(0);
}
@Test
- public void multiply() throws Exception {
+ public void multiply() {
// 5h * 2 = 1d 2h
WorkDuration result = WorkDuration.createFromValueAndUnit(5, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).multiply(2);
assertThat(result.days()).isEqualTo(1);
ConsoleLogger sut = new ConsoleLogger();
@Test
- public void log() throws Exception {
+ public void log() {
sut.log(LoggerLevel.WARN, "message");
}
}
public class ConsoleFormatterTest {
@Test
- public void format() throws Exception {
+ public void format() {
assertThat(ConsoleFormatter.format("foo")).isEqualTo("foo");
assertThat(ConsoleFormatter.format("arg: {}", "foo")).isEqualTo("arg: foo");
assertThat(ConsoleFormatter.format("two args: {} and {}", "foo", 42)).isEqualTo("two args: foo and 42");
}
@Test
- public void only_static_methods() throws Exception {
+ public void only_static_methods() {
assertThat(TestUtils.hasOnlyPrivateConstructors(ConsoleFormatter.class)).isTrue();
}
}
public LogTester tester = new LogTester();
@Test
- public void debug_enabled() throws Exception {
+ public void debug_enabled() {
tester.setLevel(LoggerLevel.DEBUG);
assertThat(sut.isDebugEnabled()).isTrue();
assertThat(sut.isTraceEnabled()).isFalse();
}
@Test
- public void debug_disabled() throws Exception {
+ public void debug_disabled() {
tester.setLevel(LoggerLevel.INFO);
assertThat(sut.isDebugEnabled()).isFalse();
assertThat(sut.isTraceEnabled()).isFalse();
}
@Test
- public void trace_enabled() throws Exception {
+ public void trace_enabled() {
tester.setLevel(LoggerLevel.TRACE);
assertThat(sut.isDebugEnabled()).isTrue();
assertThat(sut.isTraceEnabled()).isTrue();
}
@Test
- public void trace_disabled() throws Exception {
+ public void trace_disabled() {
tester.setLevel(LoggerLevel.DEBUG);
assertThat(sut.isTraceEnabled()).isFalse();
sut.trace("message");
}
@Test
- public void log() throws Exception {
+ public void log() {
sut.info("message");
sut.info("message {}", "foo");
sut.info("message {} {}", "foo", "bar");
}
@Test
- public void level_change_not_implemented_yet() throws Exception {
+ public void level_change_not_implemented_yet() {
assertThat(sut.setLevel(LoggerLevel.DEBUG)).isFalse();
}
}
ConsoleLoggers sut = new ConsoleLoggers();
@Test
- public void newInstance() throws Exception {
+ public void newInstance() {
Logger logger = sut.newInstance("foo");
assertThat(logger).isInstanceOf(ConsoleLogger.class);
}
@Test
- public void level() throws Exception {
+ public void level() {
// INFO by default
assertThat(sut.getLevel()).isEqualTo(LoggerLevel.INFO);
}
@Test
- public void stop_reuses_start_message() throws Exception {
+ public void stop_reuses_start_message() {
tester.setLevel(LoggerLevel.TRACE);
// trace
}
@Test
- public void different_start_and_stop_messages() throws Exception {
+ public void different_start_and_stop_messages() {
tester.setLevel(LoggerLevel.TRACE);
// start TRACE and stop DEBUG
}
@Test
- public void log_on_at_stop() throws Exception {
+ public void log_on_at_stop() {
tester.setLevel(LoggerLevel.TRACE);
// trace
}
@Test
- public void add_context() throws Exception {
+ public void add_context() {
Profiler profiler = Profiler.create(Loggers.get("DefaultProfilerTest"));
profiler.addContext("a_string", "bar");
profiler.addContext("null_value", null);
}
@Test
- public void empty_message() throws Exception {
+ public void empty_message() {
sut.addContext("foo", "bar");
sut.startInfo("");
assertThat(tester.logs()).containsOnly("foo=bar");
}
@Test
- public void fail_if_stop_without_message() throws Exception {
+ public void fail_if_stop_without_message() {
sut.start();
try {
sut.stopInfo();
}
@Test
- public void fail_if_stop_without_start() throws Exception {
+ public void fail_if_stop_without_start() {
try {
sut.stopDebug("foo");
fail();
public class LogInterceptorsTest {
@Test
- public void default_is_null_interceptor() throws Exception {
+ public void default_is_null_interceptor() {
// production-ready
assertThat(LogInterceptors.get()).isInstanceOf(NullInterceptor.class);
}
@Test(expected = IllegalArgumentException.class)
- public void instance_cant_be_null() throws Exception {
+ public void instance_cant_be_null() {
LogInterceptors.set(null);
}
@Test
- public void private_constructor() throws Exception {
+ public void private_constructor() {
assertThat(TestUtils.hasOnlyPrivateConstructors(LogInterceptors.class));
}
}
public LogTester tester = new LogTester();
@Test
- public void log() throws Exception {
+ public void log() {
// no assertions. Simply verify that calls do not fail.
sut.trace("message");
sut.trace("message {}", "foo");
}
@Test
- public void change_level() throws Exception {
+ public void change_level() {
assertThat(sut.setLevel(LoggerLevel.INFO)).isTrue();
assertThat(sut.logbackLogger().getLevel()).isEqualTo(Level.INFO);
assertThat(sut.isDebugEnabled()).isFalse();
}
@Test
- public void info_level_can_not_be_disabled() throws Exception {
+ public void info_level_can_not_be_disabled() {
try {
sut.setLevel(LoggerLevel.ERROR);
fail();
public class LoggersTest {
@Test
- public void factory() throws Exception {
+ public void factory() {
// logback is used by sonar-plugin-api
assertThat(Loggers.getFactory()).isInstanceOf(LogbackLoggers.class);
public class NullInterceptorTest {
@Test
- public void do_not_throws_exception() throws Exception {
+ public void do_not_throws_exception() {
// verify that... it does nothing
NullInterceptor.NULL_INSTANCE.log(LoggerLevel.INFO, "foo");
NullInterceptor.NULL_INSTANCE.log(LoggerLevel.INFO, "foo {}", 42);
NullProfiler sut = NullProfiler.NULL_INSTANCE;
@Test
- public void do_not_fail() throws Exception {
+ public void do_not_fail() {
assertThat(sut.start()).isSameAs(sut);
assertThat(sut.startTrace("")).isSameAs(sut);
assertThat(sut.startDebug("")).isSameAs(sut);
public LogTester tester = new LogTester();
@Test
- public void create() throws Exception {
+ public void create() {
Profiler profiler = Profiler.create(Loggers.get("foo"));
assertThat(profiler).isInstanceOf(DefaultProfiler.class);
}
@Test
- public void create_null_profiler_if_trace_level_is_disabled() throws Exception {
+ public void create_null_profiler_if_trace_level_is_disabled() {
tester.setLevel(LoggerLevel.TRACE);
Profiler profiler = Profiler.createIfTrace(Loggers.get("foo"));
assertThat(profiler).isInstanceOf(DefaultProfiler.class);
}
@Test
- public void create_null_profiler_if_debug_level_is_disabled() throws Exception {
+ public void create_null_profiler_if_debug_level_is_disabled() {
tester.setLevel(LoggerLevel.TRACE);
Profiler profiler = Profiler.createIfDebug(Loggers.get("foo"));
assertThat(profiler).isInstanceOf(DefaultProfiler.class);
}
@Test
- public void empty_object() throws Exception {
+ public void empty_object() {
writer.beginObject().endObject().close();
expect("{}");
}
@Test
- public void empty_array() throws Exception {
+ public void empty_array() {
writer.beginArray().endArray().close();
expect("[]");
}
@Test
- public void stop_while_streaming() throws Exception {
+ public void stop_while_streaming() {
writer.beginObject().name("foo").value("bar");
// endObject() and close() are missing
expect("{\"foo\":\"bar\"");
}
@Test
- public void objects_and_arrays() throws Exception {
+ public void objects_and_arrays() {
writer.beginObject().name("issues")
.beginArray()
.beginObject().prop("key", "ABC").endObject()
}
@Test
- public void array_values() throws Exception {
+ public void array_values() {
writer.beginArray().values(Arrays.asList("foo", "bar", "baz")).endArray().close();
expect("[\"foo\",\"bar\",\"baz\"]");
}
@Test
- public void type_of_values() throws Exception {
+ public void type_of_values() {
Date date = DateUtils.parseDateTime("2010-05-18T15:50:45+0100");
writer.beginObject()
.prop("aBoolean", true)
}
@Test
- public void ignore_null_values_by_default() throws Exception {
+ public void ignore_null_values_by_default() {
writer.beginObject()
.prop("nullNumber", (Number) null)
.prop("nullString", (String) null)
}
@Test
- public void serialize_null_values() throws Exception {
+ public void serialize_null_values() {
writer.setSerializeNulls(true);
writer.beginObject()
.prop("nullNumber", (Number) null)
}
@Test
- public void serialize_empty_strings_by_default() throws Exception {
+ public void serialize_empty_strings_by_default() {
writer.beginObject()
.prop("emptyString", EMPTY_STRING)
.name("emptyStringAsObject").valueObject(EMPTY_STRING)
}
@Test
- public void ignore_empty_strings_when_requested() throws Exception {
+ public void ignore_empty_strings_when_requested() {
writer.setSerializeEmptys(false)
.beginObject()
.prop("emptyString", EMPTY_STRING)
}
@Test
- public void escape_values() throws Exception {
+ public void escape_values() {
writer.beginObject()
.prop("foo", "<hello \"world\">")
.endObject().close();
}
@Test
- public void valueObject() throws Exception {
+ public void valueObject() {
writer.beginObject()
.name("aString").valueObject("stringValue")
.name("aBoolean").valueObject(true)
}
@Test
- public void valueObject_recursive() throws Exception {
+ public void valueObject_recursive() {
Map map = ImmutableMap.of("a", ImmutableMap.of("b", "c"));
writer.valueObject(map).close();
expect("{\"a\":{\"b\":\"c\"}}");
}
@Test
- public void valueObject_unsupported_type() throws Exception {
+ public void valueObject_unsupported_type() {
try {
writer.beginObject().valueObject(new StringWriter()).endObject().close();
fail();
}
@Test
- public void fail_on_NaN_value() throws Exception {
+ public void fail_on_NaN_value() {
thrown.expect(WriterException.class);
writer.beginObject().prop("foo", Double.NaN).endObject().close();
}
@Test
- public void fail_if_not_valid() throws Exception {
+ public void fail_if_not_valid() {
thrown.expect(WriterException.class);
writer.beginObject().endArray().close();
}
}
@Test
- public void only_root() throws Exception {
+ public void only_root() {
writer.begin("foo").end().close();
expect("<foo/>");
}
@Test
- public void escape_value() throws Exception {
+ public void escape_value() {
writer.prop("foo", "1<2 & 2>=2").close();
expect("<foo>1<2 & 2>=2</foo>");
}
@Test
- public void only_root_with_value() throws Exception {
+ public void only_root_with_value() {
writer.prop("foo", "bar").close();
expect("<foo>bar</foo>");
}
@Test
- public void ignore_null_values() throws Exception {
+ public void ignore_null_values() {
writer.begin("root")
.prop("nullNumber", (Number) null)
.prop("nullString", (String) null)
}
@Test
- public void fail_on_NaN_value() throws Exception {
+ public void fail_on_NaN_value() {
thrown.expect(WriterException.class);
thrown.expectMessage("Fail to write XML. Double value is not valid: NaN");
writer.begin("root").prop("foo", Double.NaN).end().close();
public class JsonAssertTest {
@Test
- public void isSimilarAs_strings() throws Exception {
+ public void isSimilarAs_strings() {
assertJson("{}").isSimilarTo("{}");
try {
}
@Test
- public void isSimilarAs_urls() throws Exception {
+ public void isSimilarAs_urls() {
URL url1 = getClass().getResource("JsonAssertTest/sample1.json");
URL url2 = getClass().getResource("JsonAssertTest/sample2.json");
assertJson(url1).isSimilarTo(url1);
}
@Test
- public void actual_can_be_superset_of_expected() throws Exception {
+ public void actual_can_be_superset_of_expected() {
assertJson("{\"foo\": \"bar\"}").isSimilarTo("{}");
try {
assertJson("{}").isSimilarTo("{\"foo\": \"bar\"}");
}
@Test
- public void enable_strict_order_of_arrays() throws Exception {
+ public void enable_strict_order_of_arrays() {
try {
assertJson("[1,2]").setStrictArrayOrder(true).isSimilarTo("[2, 1]");
fail();
}
@Test
- public void enable_strict_timezone() throws Exception {
+ public void enable_strict_timezone() {
try {
assertJson("[\"2010-05-18T15:50:45+0100\"]").setStrictTimezone(true).isSimilarTo("[\"2010-05-18T16:50:45+0200\"]");
fail();
}
@Test
- public void syntax_agnostic() throws Exception {
+ public void syntax_agnostic() {
assertThat(areSimilar("{}", " { } ")).isTrue();
assertThat(areSimilar("{\"foo\":\"bar\"}", "{\"foo\": \"bar\" \n }")).isTrue();
}
@Test
- public void object() throws Exception {
+ public void object() {
assertThat(areSimilar("{}", "{}")).isTrue();
// exactly the same
}
@Test
- public void strict_order_of_array() throws Exception {
+ public void strict_order_of_array() {
assertThat(isSimilar_strict_array_order("[]", "[]")).isTrue();
assertThat(isSimilar_strict_array_order("[1, 2]", "[1, 2]")).isTrue();
}
@Test
- public void lenient_order_of_array() throws Exception {
+ public void lenient_order_of_array() {
assertThat(areSimilar("[]", "[]")).isTrue();
assertThat(areSimilar("[1, 2]", "[1, 2]")).isTrue();
assertThat(areSimilar("[1, 2]", "[1]")).isFalse();
}
@Test
- public void lenient_order_of_arrays_by_default() throws Exception {
+ public void lenient_order_of_arrays_by_default() {
assertThat(new JsonComparison().isStrictArrayOrder()).isFalse();
}
@Test
- public void null_value() throws Exception {
+ public void null_value() {
assertThat(areSimilar("[null]", "[null]")).isTrue();
assertThat(areSimilar("[null]", "[]")).isFalse();
}
@Test
- public void maps_and_arrays() throws Exception {
+ public void maps_and_arrays() {
assertThat(areSimilar("[]", "{}")).isFalse();
assertThat(areSimilar("{}", "[]")).isFalse();
}
@Test
- public void lenient_timezone() throws Exception {
+ public void lenient_timezone() {
// lenient mode by default
assertThat(new JsonComparison().isStrictTimezone()).isFalse();
}
@Test
- public void strict_timezone() throws Exception {
+ public void strict_timezone() {
assertThat(new JsonComparison().setStrictTimezone(true).isStrictTimezone()).isTrue();
// same instant, same timezone
}
@Test
- public void compare_doubles() throws Exception {
+ public void compare_doubles() {
assertThat(areSimilar("{\"foo\": true}", "{\"foo\": false}")).isFalse();
assertThat(areSimilar("{\"foo\": true}", "{\"foo\": true}")).isTrue();
assertThat(areSimilar("{\"foo\": true}", "{\"foo\": \"true\"}")).isFalse();
}
@Test
- public void compare_booleans() throws Exception {
+ public void compare_booleans() {
assertThat(areSimilar("{\"foo\": 3.14}", "{\"foo\": 3.14000000}")).isTrue();
assertThat(areSimilar("{\"foo\": 3.14}", "{\"foo\": 3.1400001}")).isTrue();
}