@Test public void read() throws IOException { assertThat(IOUtil.toString(ResourceUtil.asStream("test.txt"))).isEqualTo("ABCDEFG\nABC"); assertThat(IOUtil.toLines(ResourceUtil.asStream("test.txt"))).hasSize(2).containsExactly("ABCDEFG", "ABC"); }
@Test public void do_not_fail_nor_log_ERROR_when_sendError_throws_IOException_and_plugin_does_not_exist() throws Exception { system.sendErrorException = new IOException("Simulating sendError throwing IOException"); when(pluginRepository.hasPlugin("myplugin")).thenReturn(false); Response response = call("/static/myplugin/foo.css"); assertThat(response.code()).isEqualTo(200); assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty(); assertThat(logTester.logs(LoggerLevel.TRACE)).contains("Failed to send error code 404: java.io.IOException: Simulating sendError throwing IOException"); }
@Test @SuppressWarnings("unchecked") public void invokeAll() throws Exception { List<Future<Object>> exectedResult = Arrays.asList(expectedFutureObject); List<Callable<Object>> wrappedCallables = Arrays.asList(wrappedCallable); when(delegate.invokeAll(wrappedCallables)).thenReturn(exectedResult); List<Future<Object>> result = executor.invokeAll(Arrays.asList(callable)); verify(delegate).invokeAll(wrappedCallables); assertThat(result).isEqualTo(exectedResult); }
@Test public void shutdownNow() { List<Runnable> result = executor.shutdownNow(); verify(delegate).shutdownNow(); assertThat(result).isEqualTo(delegate.shutdownNow()).isNotNull(); }
@Test public void verify_installed_ClusterHealthChecks_implementations_in_clustering() { when(webServer.isStandalone()).thenReturn(false); ComponentContainer container = new ComponentContainer(); underTest.configure(container); List<Class<?>> checks = classesAddedToContainer(container).stream().filter(ClusterHealthCheck.class::isAssignableFrom).collect(Collectors.toList()); assertThat(checks) .hasSize(2) .contains(EsStatusClusterCheck.class) .contains(AppNodeClusterCheck.class); }
@Test public void guavaBuildList() { List<String> list1 = ListUtil.newArrayList(); List<String> list2 = ListUtil.newArrayList("a", "b"); assertThat(list2).hasSize(2).containsExactly("a", "b"); List<String> list3 = ListUtil.newArrayList(SetUtil.newHashSet("a", "b")); assertThat(list2).hasSize(2).containsExactly("a", "b"); List<String> list4 = ListUtil.newArrayListWithCapacity(10); List<String> list5 = ListUtil.newCopyOnWriteArrayList(); List<String> list6 = ListUtil.newCopyOnWriteArrayList("a", "b"); assertThat(list6).hasSize(2).containsExactly("a", "b"); List<String> list7 = ListUtil.newLinkedList(); }
@Test public void constructor_logs_warning_if_env_variable_ES_JAVA_OPTS_is_set() { System2 system2 = Mockito.mock(System2.class); when(system2.getenv("ES_JAVA_OPTS")).thenReturn("xyz"); attachMemoryAppenderToLoggerOf(CommandFactoryImpl.class); new CommandFactoryImpl(new Props(new Properties()), tempDir, system2); assertThat(listAppender.getLogs()) .extracting(ILoggingEvent::getMessage) .containsOnly( "ES_JAVA_OPTS is defined but will be ignored. " + "Use properties sonar.search.javaOpts and/or sonar.search.javaAdditionalOpts in sonar.properties to change SQ JVM processes options"); }
@Test public void handleWhenNotOAuth2AuthenticatedThenStatus403() { Authentication token = new TestingAuthenticationToken("user", "pass"); ServerWebExchange exchange = mock(ServerWebExchange.class); when(exchange.getPrincipal()).thenReturn(Mono.just(token)); when(exchange.getResponse()).thenReturn(new MockServerHttpResponse()); this.accessDeniedHandler.handle(exchange, null).block(); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(exchange.getResponse().getHeaders().get("WWW-Authenticate")).isEqualTo( Arrays.asList("Bearer")); }
@Test public void Components_of_ReportAnalysisComponentProvider_are_added_to_the_container() { Object object = new Object(); Class<MyClass> clazz = MyClass.class; ReportAnalysisComponentProvider componentProvider = mock(ReportAnalysisComponentProvider.class); when(componentProvider.getComponents()).thenReturn(ImmutableList.of(object, clazz)); underTest = new ProjectAnalysisTaskContainerPopulator(task, new ReportAnalysisComponentProvider[] {componentProvider}); AddedObjectsRecorderTaskContainer container = new AddedObjectsRecorderTaskContainer(); container.add(componentProvider); underTest.populateContainer(container); assertThat(container.added).contains(object, clazz); }
@Test public void testLoadOrderITHardwareCase() throws Exception { KieBase kbase = createKnowledgeBase("CMMN-OrderITHardwareCase.cmmn"); assertThat(kbase).isNotNull(); Process process = kbase.getProcess("itorders.orderhardware"); assertThat(process).isNotNull(); assertThat(process).isInstanceOf(RuleFlowProcess.class); RuleFlowProcess caseProcess = (RuleFlowProcess) process; assertThat(caseProcess.isDynamic()).isTrue(); assertThat(caseProcess.getId()).isEqualTo("itorders.orderhardware"); assertThat(caseProcess.getName()).isEqualTo("Order IT hardware"); Node[] nodes = caseProcess.getNodes(); assertThat(nodes).hasSize(9); List<Variable> variables = caseProcess.getVariableScope().getVariables(); assertThat(variables).hasSize(7); }
@Test public void return_400_on_BadRequestException_with_single_message() { Request request = new TestRequest().setPath("api/foo"); DumbResponse response = run(request, newWs("api/foo", a -> a.setHandler((req, resp) -> { throw BadRequestException.create("Bad request !"); }))); assertThat(response.stream().outputAsString()).isEqualTo( "{\"errors\":[{\"msg\":\"Bad request !\"}]}"); assertThat(response.stream().status()).isEqualTo(400); assertThat(response.stream().mediaType()).isEqualTo(MediaTypes.JSON); assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty(); }
@Test public void return_resource_if_exists_in_requested_plugin() throws Exception { system.pluginStream = IOUtils.toInputStream("bar"); when(pluginRepository.hasPlugin("myplugin")).thenReturn(true); when(pluginRepository.getPluginInfo("myplugin")).thenReturn(new PluginInfo("myplugin")); Response response = call("/static/myplugin/foo.css"); assertThat(response.isSuccessful()).isTrue(); assertThat(response.body().string()).isEqualTo("bar"); assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty(); assertThat(logTester.logs(LoggerLevel.WARN)).isEmpty(); }
@Test public void not_update_sources_when_nothing_has_changed() { dbClient.fileSourceDao().insert(dbTester.getSession(), createDto()); dbTester.getSession().commit(); Changeset changeset = Changeset.newChangesetBuilder().setDate(1L).setRevision("rev-1").build(); setComputedData(DbFileSources.Data.newBuilder().build(), Collections.singletonList("lineHash"), "sourceHash", changeset); underTest.execute(new TestComputationStepContext()); assertThat(dbTester.countRowsOfTable("file_sources")).isEqualTo(1); FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID); assertThat(fileSourceDto.getSrcHash()).isEqualTo("sourceHash"); assertThat(fileSourceDto.getLineHashes()).isEqualTo(Collections.singletonList("lineHash")); assertThat(fileSourceDto.getCreatedAt()).isEqualTo(PAST); assertThat(fileSourceDto.getUpdatedAt()).isEqualTo(PAST); verify(fileSourceDataWarnings).commitWarnings(); }
@Test public void should_persist_without_significant_code_from_cache_if_possible() { List<String> lineHashes = Lists.newArrayList("line1", "line2", "line3"); sourceLinesHashCache.computeIfAbsent(file, c -> lineHashes); when(dbLineHashVersion.hasLineHashesWithSignificantCode(file)).thenReturn(false); when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.empty()); LineHashesComputer hashesComputer = underTest.getLineHashesComputerToPersist(file); assertThat(hashesComputer).isInstanceOf(CachedLineHashesComputer.class); assertThat(hashesComputer.getResult()).isEqualTo(lineHashes); }
@Test public void log_task_characteristics() throws Exception { when(queue.peek(anyString())).thenReturn(Optional.of(createCeTask(null, "pullRequest", "123", "branch", "foo"))); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); underTest.call(); List<String> logs = logTester.logs(LoggerLevel.INFO); assertThat(logs).hasSize(2); for (int i = 0; i < 2; i++) { assertThat(logs.get(i)).contains("pullRequest=123"); assertThat(logs.get(i)).contains("branch=foo"); } }
@Test public void do_not_log_submitter_param_if_anonymous_and_success() throws Exception { when(queue.peek(anyString())).thenReturn(Optional.of(createCeTask(null))); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); underTest.call(); verifyWorkerUuid(); List<String> logs = logTester.logs(LoggerLevel.INFO); assertThat(logs).hasSize(2); for (int i = 0; i < 2; i++) { assertThat(logs.get(i)).doesNotContain("submitter="); } }
@Test public void return_private_project_with_AllowAnyone_false_and_user_id_when_user_is_granted_USER_permission_directly() { dbTester.users().insertProjectPermissionOnUser(user1, USER, privateProject1); List<IndexPermissions> dtos = underTest.selectByUuids(dbClient, dbSession, singletonList(privateProject1.uuid())); Assertions.assertThat(dtos).hasSize(1); IndexPermissions dto = dtos.get(0); assertThat(dto.getGroupIds()).isEmpty(); assertThat(dto.getUserIds()).containsOnly(user1.getId()); assertThat(dto.isAllowAnyone()).isFalse(); assertThat(dto.getProjectUuid()).isEqualTo(privateProject1.uuid()); assertThat(dto.getQualifier()).isEqualTo(privateProject1.qualifier()); }
@Test public void execute_deletes_all_qualitygate_component_properties_when_there_is_no_qualitygate() throws SQLException { insertProperty(PROPERTY_SONAR_QUALITYGATE, 30, "12"); insertProperty(PROPERTY_SONAR_QUALITYGATE, 42, "val1"); insertProperty(PROPERTY_SONAR_QUALITYGATE, null, "val2"); underTest.execute(); assertThat(selectPropertyValues()).containsOnly("val2"); assertThat(db.countRowsOfTable("PROPERTIES")).isEqualTo(1); }
@Test public void filter_projects_on_favorites() { userSession.logIn(); OrganizationDto organization = db.organizations().insert(); ComponentDto javaProject = insertProject(organization); ComponentDto markDownProject = insertProject(organization); ComponentDto sonarQubeProject = insertProject(organization); Stream.of(javaProject, markDownProject).forEach(this::addFavourite); SearchProjectsWsResponse result = call(request.setFilter("isFavorite")); assertThat(result.getComponentsCount()).isEqualTo(2); assertThat(result.getComponentsList()).extracting(Component::getKey).containsExactly(javaProject.getDbKey(), markDownProject.getDbKey()); }
@Test public void selectByNameAndLanguages() { createSharedData(); List<QProfileDto> dtos = underTest.selectByNameAndLanguages(dbSession, organization, "Sonar Way", singletonList("java")); assertThat(dtos).hasSize(1); QProfileDto dto = dtos.iterator().next(); assertThat(dto.getName()).isEqualTo("Sonar Way"); assertThat(dto.getLanguage()).isEqualTo("java"); assertThat(dto.getParentKee()).isNull(); assertThat(underTest.selectByNameAndLanguages(dbSession, organization, "Sonar Way", singletonList("unknown"))).isEmpty(); assertThat(underTest.selectByNameAndLanguages(dbSession, organization, "Sonar Way", of("java", "unknown"))) .extracting(QProfileDto::getKee).containsOnly(dto.getKee()); }