private static void validateAnalyzerMessage( Map<IssueAttribute, String> attrs, AnalyzerMessage analyzerMessage) { Double effortToFix = analyzerMessage.getCost(); if (effortToFix != null) { assertEquals(Integer.toString(effortToFix.intValue()), attrs, IssueAttribute.EFFORT_TO_FIX); } AnalyzerMessage.TextSpan textSpan = analyzerMessage.primaryLocation(); assertEquals(normalizeColumn(textSpan.startCharacter), attrs, IssueAttribute.START_COLUMN); assertEquals(Integer.toString(textSpan.endLine), attrs, IssueAttribute.END_LINE); assertEquals(normalizeColumn(textSpan.endCharacter), attrs, IssueAttribute.END_COLUMN); if (attrs.containsKey(IssueAttribute.SECONDARY_LOCATIONS)) { List<AnalyzerMessage> secondaryLocations = analyzerMessage.secondaryLocations; Multiset<String> actualLines = HashMultiset.create(); for (AnalyzerMessage secondaryLocation : secondaryLocations) { actualLines.add(Integer.toString(secondaryLocation.getLine())); } List<String> expected = Lists.newArrayList( Splitter.on(",") .omitEmptyStrings() .trimResults() .split(attrs.get(IssueAttribute.SECONDARY_LOCATIONS))); List<String> unexpected = new ArrayList<>(); for (String actualLine : actualLines) { if (expected.contains(actualLine)) { expected.remove(actualLine); } else { unexpected.add(actualLine); } } if (!expected.isEmpty() || !unexpected.isEmpty()) { Fail.fail("Secondary locations: expected: " + expected + " unexpected:" + unexpected); } } }
@Test @Ignore("Deactivated awaiting resolution of http://jira.sonarsource.com/browse/JC-145") public void should_run_lint_after_export_and_import_results() throws Exception { assumeTrue(AndroidTestSuite.isAtLeastPlugin1_1()); String response = exportProfile("it-profile"); File baseDir = new File("projects/SonarAndroidSample/app"); FileUtils.write(new File(baseDir, "lint.xml"), response, Charsets.UTF_8); ProcessBuilder pb = new ProcessBuilder("CMD", "/C", "gradle lint"); pb.directory(baseDir); pb.inheritIO(); Process gradleProcess = pb.start(); int exitStatus = gradleProcess.waitFor(); if (exitStatus != 0) { fail("Failed to execute gradle lint."); } SonarRunner analysis = SonarRunner.create() .setProfile("it-profile") .setProjectName("SonarAndroidSample2") .setProjectKey("SonarAndroidSample2") .setProjectVersion("1.0") .setSourceDirs("src/main") .setProjectDir(baseDir) .setProperty("sonar.android.lint.report", "lint-report-build.xml") .setProperty("sonar.import_unknown_files", "true"); orchestrator.executeBuild(analysis); Resource project = sonar.find(ResourceQuery.createForMetrics("SonarAndroidSample2", "violations")); assertThat(project.getMeasureIntValue("violations")).isEqualTo(2); }
@Test public void fail_to_recreate_built_in_profile_when_rule_not_found() throws Exception { String name = "Default"; String language = "java"; RulesProfile profile = RulesProfile.create(name, language); Rule rule = Rule.create("pmd", "rule"); profile.activateRule(rule, null); ProfileDefinition profileDefinition = mock(ProfileDefinition.class); when(profileDefinition.createProfile(any(ValidationMessages.class))).thenReturn(profile); definitions.add(profileDefinition); when(ruleDao.getNullableByKey(session, RuleKey.of("pmd", "rule"))).thenReturn(null); when(qProfileOperations.newProfile( eq(name), eq(language), eq(true), any(UserSession.class), eq(session))) .thenReturn(new QProfile().setId(1)); try { backup.recreateBuiltInProfilesByLanguage(language); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(NotFoundException.class); } verifyZeroInteractions(qProfileActiveRuleOperations); }
@Test(description = "OPENDJ-1197") public void testClientSideConnectTimeout() throws Exception { // Use an non-local unreachable network address. final ConnectionFactory factory = new LDAPConnectionFactory( "10.20.30.40", 1389, new LDAPOptions().setConnectTimeout(1, TimeUnit.MILLISECONDS)); try { for (int i = 0; i < ITERATIONS; i++) { final PromiseImpl<LdapException, NeverThrowsException> promise = PromiseImpl.create(); final Promise<? extends Connection, LdapException> connectionPromise = factory.getConnectionAsync(); connectionPromise.onFailure(getFailureHandler(promise)); ConnectionException e = (ConnectionException) promise.getOrThrow(TEST_TIMEOUT, TimeUnit.SECONDS); assertThat(e.getResult().getResultCode()).isEqualTo(ResultCode.CLIENT_SIDE_CONNECT_ERROR); // Wait for the connect to timeout. try { connectionPromise.getOrThrow(TEST_TIMEOUT, TimeUnit.SECONDS); fail("The connect request succeeded unexpectedly"); } catch (ConnectionException ce) { assertThat(ce.getResult().getResultCode()) .isEqualTo(ResultCode.CLIENT_SIDE_CONNECT_ERROR); } } } finally { factory.close(); } }
private void verifyConstraint(String username, String email, String password, String expected) { try { userService.create(new DomainUser(username, email, password)); fail(); } catch (ConstraintViolationException e) { checkConstraint(expected, e); } }
public void assertNotFound(String path) throws Exception { try { fetch(DEFAULT_URL + path); fail("FileNotFoundException expected but content found for path " + path); } catch (Exception ex) { assertThat(ex).isInstanceOf(FileNotFoundException.class); } }
private void checkConstraint(String expected, ConstraintViolationException e) { for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) { String actual = constraintViolation.getPropertyPath().toString(); if (actual.equals(expected)) { return; } } fail(); }
@Test public void shouldFindFirst() { Stream<Fruit> fruits = asList(new Fruit(APPLE), new Fruit(GRAPE)).stream(); Optional<Fruit> first = fruits.findFirst(); if (first.isPresent()) { Fruit firstFruit = first.get(); assertThat(firstFruit.getName()).isEqualTo(APPLE); } else fail("should've find apple."); }
@Test public void key_should_be_set() throws Exception { try { new State("", new Transition[0]); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("State key must be set"); } }
@Test public void key_should_be_upper_case() throws Exception { try { new State("close", new Transition[0]); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("State key must be upper-case"); } }
@Test public void fail_sort_by_language() throws InterruptedException { try { // Sorting on a field not tagged as sortable new RuleQuery().setSortField(RuleNormalizer.RuleField.LANGUAGE); fail(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Field 'lang' is not sortable!"); } }
@Test(expected = NullPointerException.class) public void shouldNotAcceptNullValues() { // given SmallMap<String, Integer> newSmallMap = SmallMap.newSmallMap(); // when newSmallMap.put("abc", null); // then Fail.fail("NullPointerException expected"); }
@Test public void fail_if_class_not_found() throws Exception { try { new JdapiAvailability().check("does.not.Exist"); fail(); } catch (IllegalStateException e) { assertThat(e) .hasMessage( "Oracle JDAPI file (usually named frmjdapi.jar) is not available in classpath"); } }
private static void updateEndLine(int expectedLine, EnumMap<IssueAttribute, String> attr) { if (attr.containsKey(IssueAttribute.END_LINE)) { String endLineStr = attr.get(IssueAttribute.END_LINE); if (endLineStr.charAt(0) == '+') { int endLine = Integer.parseInt(endLineStr); attr.put(IssueAttribute.END_LINE, Integer.toString(expectedLine + endLine)); } else { Fail.fail("endLine attribute should be relative to the line and must be +N with N integer"); } } }
@Test public void no_duplicated_out_transitions() throws Exception { try { new State("CLOSE", new Transition[] {t1, t1}); fail(); } catch (IllegalArgumentException e) { assertThat(e) .hasMessage( "Transition 'close' is declared several times from the originating state 'CLOSE'"); } }
@Test public void number_of_threads_should_not_be_negative() throws Exception { try { Settings settings = new Settings(); settings.setProperty(ViolationConverters.THREADS_PROPERTY, -2); new ViolationConverters(settings).numberOfThreads(); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()) .isEqualTo("Bad value of " + ViolationConverters.THREADS_PROPERTY + ": -2"); } }
@Test public void shouldThrowAnExceptionWhenUnableToSendTestEmail() throws Exception { configure(); server.stop(); try { channel.sendTestEmail( "user@nowhere", "Test Message from SonarQube", "This is a test message from SonarQube."); fail(); } catch (EmailException e) { // expected } }
@Test public void canBootstrapHibernateOrmWithOgmBeingPresent() { try { new MetadataSources().buildMetadata().buildSessionFactory(); fail("Expected exception was not raised"); } // Failure is expected as we didn't configure a JDBC connection nor a Dialect // (and this would fail only if effectively loading Hibernate ORM without OGM superpowers) catch (Exception pe) { assertThat(Throwables.getRootCause(pe).getMessage()).contains("hibernate.dialect"); } }
@Test public void propagate_converter_failure() throws Exception { Callable<Object> callable = mock(Callable.class); when(callable.call()).thenThrow(new IllegalStateException("Need to cry")); List<Callable<Object>> callables = Lists.newArrayList(callable); try { new ViolationConverters(new Settings()).doExecute(new FakeTimerTask(), callables); fail(); } catch (Exception e) { assertThat(ExceptionUtils.getRootCause(e).getMessage()).isEqualTo("Need to cry"); } }
protected static void assertQueryPromiseFailedWithCodes( Promise<QueryResponse, ResourceException> promise, int resourceErrorCode, int entitlementErrorCode) { try { promise.getOrThrowUninterruptibly(); fail("Should throw ResourceException"); } catch (ResourceException e) { Assertions.assertThat(e.getCode()).isEqualTo(resourceErrorCode); Assertions.assertThat(e.getCause()).isInstanceOf(EntitlementException.class); Assertions.assertThat(((EntitlementException) e.getCause()).getErrorCode()) .isEqualTo(entitlementErrorCode); } }
@Test public void should_fail_to_find_issues() { HttpRequestFactory requestFactory = new HttpRequestFactory(httpServer.url()); httpServer.stubStatusCode(500); IssueClient client = new DefaultIssueClient(requestFactory); try { client.find(IssueQuery.create()); fail(); } catch (HttpException e) { assertThat(e.status()).isEqualTo(500); assertThat(e.url()).startsWith("http://localhost"); assertThat(e.url()).endsWith("/api/issues/search"); } }
@Test public void shouldNotAcceptInvalidLastCheck() { // given Agent underTest = null; int invalidValue = -1; // when try { underTest = new Agent(1, "", "", invalidValue, ""); Fail.fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { // then assertThat(underTest).isNull(); } }
@Test public void shouldNotAcceptnInvalidGroup() { // given Agent underTest = null; String invalidValue = null; // when try { underTest = new Agent(1, "", "", 1, invalidValue); Fail.fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { // then assertThat(underTest).isNull(); } }
private static String extractAttributes(String comment, Map<IssueAttribute, String> attr) { String attributesSubstr = StringUtils.substringBetween(comment, "[[", "]]"); if (!StringUtils.isEmpty(attributesSubstr)) { Iterable<String> attributes = Splitter.on(";").split(attributesSubstr); for (String attribute : attributes) { String[] split = StringUtils.split(attribute, '='); if (split.length == 2 && CheckVerifier.ATTRIBUTE_MAP.containsKey(split[0])) { attr.put(CheckVerifier.ATTRIBUTE_MAP.get(split[0]), split[1]); } else { Fail.fail("// Noncompliant attributes not valid: " + attributesSubstr); } } } return attributesSubstr; }
@Test public void loadInto_FromNonClassPath() { // prepare Load01 cfg = new Load01(); // execute TestConfigurationBuilder sut = TestConfigurationBuilder.buildTestConfig().sourcePath("/other/path"); try { sut.loadInto(cfg); Fail.fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("currently only classpath: is a supported location"); } }
@Test public void should_fail_to_load_project_id_if_unknown_component() throws Exception { SnapshotCache snapshotCache = mock(SnapshotCache.class); when(snapshotCache.get("struts:Action.java")).thenReturn(null); ScanIssueStorage storage = new ScanIssueStorage( getMyBatis(), new FakeRuleFinder(), snapshotCache, new ResourceDao(getMyBatis())); try { storage.projectId(new DefaultIssue().setComponentKey("struts:Action.java")); fail(); } catch (Exception e) { assertThat(e).hasMessage("Project id not found for: struts:Action.java"); } }
@Test public void fail_when_rule_is_linked_on_root_characteristic() throws Exception { verifyRulesInDb(); rulesDefinition.includeRuleLinkedToRootCharacteristic = true; try { // Re-execute startup tasks tester.get(Platform.class).executeStartupTasks(); fail(); } catch (Exception e) { assertThat(e) .isInstanceOf(MessageException.class) .hasMessage( "Rule 'xoo:RuleLinkedToRootCharacteristic' cannot be linked on the root characteristic 'REUSABILITY'"); } }
/** * Unit test for OPENDJ-1247: as per previous test, except this time verify that the connection * failure removes the connection from a connection pool. */ @Test public void testClientSideTimeoutForBindRequestInConnectionPool() throws Exception { resetState(); registerBindEvent(); registerCloseEvent(); for (int i = 0; i < ITERATIONS; i++) { final Connection connection = pool.getConnection(); try { waitForConnect(); final MockConnectionEventListener listener = new MockConnectionEventListener(); connection.addConnectionEventListener(listener); // Now bind with timeout. final PromiseImpl<LdapException, NeverThrowsException> promise = PromiseImpl.create(); final LdapPromise<BindResult> bindPromise = connection.bindAsync(newSimpleBindRequest()); bindPromise.onFailure(getFailureHandler(promise)); waitForBind(); // Wait for the request to timeout and check the handler was invoked. TimeoutResultException e = (TimeoutResultException) promise.getOrThrow(5, TimeUnit.SECONDS); verifyResultCodeIsClientSideTimeout(e); // Now check the promise was completed as expected. try { bindPromise.getOrThrow(5, TimeUnit.SECONDS); fail("The bind request succeeded unexpectedly"); } catch (TimeoutResultException te) { verifyResultCodeIsClientSideTimeout(te); } /* * The connection should no longer be valid, the event listener * should have been notified, but no abandon should have been * sent. */ listener.awaitError(TEST_TIMEOUT, TimeUnit.SECONDS); assertThat(connection.isValid()).isFalse(); verifyResultCodeIsClientSideTimeout(listener.getError()); connection.close(); waitForClose(); verifyNoAbandonSent(); } finally { connection.close(); } } }
private void assertMultipleIssue(Set<AnalyzerMessage> issues) throws AssertionError { Preconditions.checkState(!issues.isEmpty(), "At least one issue expected"); List<Integer> unexpectedLines = Lists.newLinkedList(); boolean isLinear = isLinear(issues.iterator().next()); for (AnalyzerMessage issue : issues) { validateIssue(expected, unexpectedLines, issue, isLinear); } if (!expected.isEmpty() || !unexpectedLines.isEmpty()) { Collections.sort(unexpectedLines); String expectedMsg = !expected.isEmpty() ? ("Expected " + expected) : ""; String unexpectedMsg = !unexpectedLines.isEmpty() ? ((expectedMsg.isEmpty() ? "" : ", ") + "Unexpected at " + unexpectedLines) : ""; Fail.fail(expectedMsg + unexpectedMsg); } }
private LDAPListener createServer() { try { return new LDAPListener( findFreeSocketAddress(), new ServerConnectionFactory<LDAPClientContext, Integer>() { @Override public ServerConnection<Integer> handleAccept(final LDAPClientContext clientContext) throws LdapException { context.set(clientContext); connectLatch.release(); return serverConnection; } }); } catch (IOException e) { fail("Unable to create LDAP listener", e); return null; } }