Java Examples for org.assertj.core.api.Assertions

The following java examples will help you to understand the usage of org.assertj.core.api.Assertions. These source code samples are taken from different open source projects.

Example 1
Project: com.cedarsoft.serialization-master  File: PrimitivesSerializerVersionTest.java View source code
@Override
protected void verifyDeserialized(@NotNull Primitives deserialized, @NotNull com.cedarsoft.version.Version version) {
    org.assertj.core.api.Assertions.assertThat(deserialized.getFoo1()).isNotNull();
    org.assertj.core.api.Assertions.assertThat(deserialized.getFoo2()).isNotNull();
    org.assertj.core.api.Assertions.assertThat(deserialized.getFoo3()).isNotNull();
    org.assertj.core.api.Assertions.assertThat(deserialized.getFoo4()).isNotNull();
    org.assertj.core.api.Assertions.assertThat(deserialized.getFoo5()).isNotNull();
    org.assertj.core.api.Assertions.assertThat(deserialized.getFoo6()).isNotNull();
    org.assertj.core.api.Assertions.assertThat(deserialized.getFoo7()).isNotNull();
    org.assertj.core.api.Assertions.assertThat(deserialized.isFoo8()).isNotNull();
    org.assertj.core.api.Assertions.assertThat(deserialized.getFoo9()).isNotNull();
}
Example 2
Project: sonar-java-master  File: AssertionsCompletenessCheck.java View source code
@Test
public void fest_assertions() {
    // Noncompliant {{Complete the assertion.}}
    org.fest.assertions.Assertions.assertThat(true);
    // Noncompliant
    org.fest.assertions.Assertions.assertThat(true).as("foo");
    // Noncompliant
    org.fest.assertions.Assertions.assertThat(true).describedAs("foo");
    // Noncompliant
    org.fest.assertions.Assertions.assertThat(true).overridingErrorMessage("foo");
    // Compliant
    org.fest.assertions.Assertions.assertThat(true).isTrue();
    // Compliant
    org.fest.assertions.Assertions.assertThat(AssertionsCompletenessCheck.class.toString()).hasSize(0);
    // Compliant
    org.fest.assertions.Assertions.assertThat(AssertionsCompletenessCheck.class.toString()).as("aa").hasSize(0);
}
Example 3
Project: brainslug-master  File: JpaPropertyStoreIT.java View source code
@Test
public void shouldStoreStringProperty() throws Exception {
    jpaPropertyStore.setProperties(instance.getIdentifier(), newProperties().with("stringTest", "value"));
    FlowInstanceProperties loadedProperties = jpaPropertyStore.getProperties(instance.getIdentifier());
    Assertions.assertThat(loadedProperties.value("stringTest", String.class)).isEqualTo("value");
}
Example 4
Project: estatio-master  File: UdoDomainObjectContract_jdoAnnotations_Test.java View source code
@SuppressWarnings("rawtypes")
@Test
public void searchAndTest() {
    Reflections reflections = new Reflections("org.estatio.dom");
    Set<Class<? extends UdoDomainObject>> subtypes = reflections.getSubTypesOf(UdoDomainObject.class);
    for (Class<? extends UdoDomainObject> subtype : subtypes) {
        if (subtype.isAnonymousClass() || subtype.isLocalClass() || subtype.isMemberClass() || subtype.getName().endsWith("ForTesting")) {
            // skip (probably a testing class)
            continue;
        }
        if (UdoDomainObject.class == subtype || UdoDomainObject2.class == subtype) {
            // skip
            continue;
        }
        System.out.println(">>> " + subtype.getName());
        // must have a @PersistenceCapable(identityType=...) annotation
        final PersistenceCapable persistenceCapable = subtype.getAnnotation(PersistenceCapable.class);
        Assertions.assertThat(persistenceCapable).isNotNull();
        IdentityType identityType = persistenceCapable.identityType();
        Assertions.assertThat(identityType).isNotNull();
        if (identityType == IdentityType.DATASTORE) {
            // NOT mandatory to have a @DatastoreIdentity, but if does, then @DatastoreIdentity(..., column="id")
            final DatastoreIdentity datastoreIdentity = subtype.getAnnotation(DatastoreIdentity.class);
            if (datastoreIdentity != null) {
                Assertions.assertThat(datastoreIdentity.column()).isEqualTo("id");
            }
        }
        Inheritance inheritance = subtype.getAnnotation(Inheritance.class);
        if (inheritance != null && inheritance.strategy() == InheritanceStrategy.SUPERCLASS_TABLE) {
            // must NOT have a @Discriminator(..., column="discriminator")
            final Annotation[] declaredAnnotations = subtype.getDeclaredAnnotations();
            for (Annotation declaredAnnotation : declaredAnnotations) {
                if (declaredAnnotation.annotationType() == Discriminator.class) {
                    Assert.fail("Class " + subtype.getName() + " inherits from " + subtype.getSuperclass().getName() + "and has (incorrectly) been annotated with @Discriminator");
                }
            }
            // check if supertype has discriminator
            // must have a @Discriminator(..., column="discriminator") on one of its supertypes
            final Discriminator superDiscriminator = subtype.getSuperclass().getAnnotation(Discriminator.class);
            Assertions.assertThat(superDiscriminator).isNotNull();
            Assertions.assertThat(superDiscriminator.column()).isEqualTo("discriminator");
        }
        if (subtype.getSuperclass().equals(UdoDomainObject.class)) {
            // must have a @Version(..., column="version")
            final Version version = getAnnotationOfTypeOfItsSupertypes(subtype, Version.class);
            Assertions.assertThat(version).isNotNull();
            Assertions.assertThat(version.column()).isEqualTo("version");
        }
    }
}
Example 5
Project: elasticsearch-http-master  File: IndexActionHandlerTest.java View source code
@Test
public void should_not_index_document_when_version_does_not_match() throws IOException, ExecutionException, InterruptedException {
    BytesReference source = source().bytes();
    IndexRequest request = Requests.indexRequest().index(THE_INDEX).type(THE_TYPE).id(THE_ID).version(1).source(source.toBytes());
    transportClient.index(request);
    try {
        httpClient.index(request).get();
        fail();
    } catch (ExecutionException e) {
        Assertions.assertThat(e).hasCauseInstanceOf(ElasticsearchHttpException.class);
        Assertions.assertThat(e.getCause()).hasMessageStartingWith("status code 409");
        Assertions.assertThat(e.getCause()).hasMessageContaining("VersionConflictEngineException");
    }
}
Example 6
Project: FluentLenium-master  File: NoSuchElementMessageTest.java View source code
@Test
public void testListSelector() {
    Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {

        @Override
        public void call() throws Throwable {
            search.$("test").now();
        }
    }).isExactlyInstanceOf(NoSuchElementException.class).hasMessageStartingWith("Elements By.cssSelector: test (Lazy Element List) is not present");
}
Example 7
Project: sphere-sunrise-master  File: RatingDataFactoryTest.java View source code
@Test
public void create() {
    final CmsPage cms = ( messageKey,  args) -> Optional.of(messageKey);
    final RatingData ratingData = RatingDataFactory.of(cms).create();
    Assertions.assertThat(ratingData.getRating()).containsExactly(new SelectableData("5 Stars", "5", "ratingFiveStarText", "", false), new SelectableData("4 Stars", "4", "ratingFourStarText", "", false), new SelectableData("3 Stars", "3", "ratingThreeStarText", "", false), new SelectableData("2 Stars", "2", "ratingTwoStarText", "", false), new SelectableData("1 Stars", "1", "ratingOneStarText", "", false));
}
Example 8
Project: tyrion-master  File: FullAgentIT.java View source code
@Test
public void should_attach_to_java_application_and_profile_synchronized_locks() throws IOException {
    // Given
    // NOTE : if you run the test form an IDE, set the working directory to be the "agent" directory
    String runAgentOnTestClass = String.format("java -javaagent:%s=output-file=%s;enabled-at-startup=true -cp %s %s%n", new File("target/tyrion-agent-jar-with-dependencies.jar").getAbsolutePath(), new File("target/" + getClass().getSimpleName() + ".locks.txt").getAbsolutePath(), new File("target/test-classes/").getAbsolutePath(), TestClassWithSynchronized.class.getName());
    // When
    Process javaProcess = Runtime.getRuntime().exec(runAgentOnTestClass);
    String output = flushStream(javaProcess.getInputStream());
    String error = flushStream(javaProcess.getErrorStream());
    // Then
    //        Assertions.assertThat(error).isEmpty();
    Assertions.assertThat(output).contains("Test completed. Now please check the output file.");
}
Example 9
Project: arquillian-extension-drone-master  File: HtmlUnitDriverTest.java View source code
@Test
public void shouldSetWebClientOptionsForHtmlUnitDriver() throws IOException {
    final HtmlUnitDriverFactory htmlUnitDriverFactory = new HtmlUnitDriverFactory();
    final WebDriverConfiguration configuration = getMockedConfiguration("Timeout=300; JavaScriptEnabled=false");
    final WebDriver driver = htmlUnitDriverFactory.createInstance(configuration);
    final DroneHtmlUnitDriver htmlUnitDriver = (DroneHtmlUnitDriver) driver;
    final WebClient webClient = htmlUnitDriver.getWebClient();
    final WebClientOptions webClientOptions = webClient.getOptions();
    Assertions.assertThat(webClientOptions.isJavaScriptEnabled()).isFalse();
    Assertions.assertThat(webClientOptions.getTimeout()).isEqualTo(300);
}
Example 10
Project: dolphin-master  File: ClassPathScanningProviderTest.java View source code
@Test
public void testScan() throws IOException {
    ClassPathScanningProvider provider = new ClassPathScanningProvider();
    provider.addIncludeFilter(( m,  mf) -> true);
    Set<MetadataReader> components = provider.findCandidateComponents("com.freetmp.common.util");
    components.stream().map(( mr) -> mr.getResource()).forEach(System.out::println);
    Assertions.assertThat(components).isNotEmpty();
}
Example 11
Project: drooms-master  File: CollisionDetectionTest.java View source code
@Test
public void testIntegration() {
    // prepare the scenario
    final PlayerPosition expected = PlayerPosition.build(CollisionDetectionTest.PLAYGROUND, new Player("a", "b", "c", "1.0"), CollisionDetectionTest.PLAYER_UNCOLLIDED);
    final Set<PlayerPosition> players = new HashSet<>();
    players.add(expected);
    players.add(PlayerPosition.build(CollisionDetectionTest.PLAYGROUND, new Player("d", "e", "f", "1.0"), CollisionDetectionTest.PLAYER_HITTING_THE_UNCOLLIDED));
    players.add(PlayerPosition.build(CollisionDetectionTest.PLAYGROUND, new Player("g", "h", "i", "1.0"), CollisionDetectionTest.PLAYER_HEAD_ON_HEAD_1));
    players.add(PlayerPosition.build(CollisionDetectionTest.PLAYGROUND, new Player("j", "k", "l", "1.0"), CollisionDetectionTest.PLAYER_HEAD_ON_HEAD_2));
    players.add(PlayerPosition.build(CollisionDetectionTest.PLAYGROUND, new Player("m", "n", "o", "1.0"), CollisionDetectionTest.PLAYER_COLLIDED_WITH_WALL));
    players.add(PlayerPosition.build(CollisionDetectionTest.PLAYGROUND, new Player("p", "q", "r", "1.0"), CollisionDetectionTest.PLAYER_COLLIDED_WITH_ITSELF));
    // run the scenario
    final Set<PlayerPosition> collided = Detectors.detectCollision(players);
    Assertions.assertThat(collided).doesNotContain(expected);
}
Example 12
Project: fullstop-master  File: SecurityGroupProviderTest.java View source code
@Test
public void testAmazonException() {
    final AmazonServiceException amazonServiceException = new AmazonServiceException("");
    amazonServiceException.setErrorCode("InvalidGroup.NotFound");
    when(clientProviderMock.getClient(any(), anyString(), any(Region.class))).thenReturn(amazonEC2ClientMock);
    when(amazonEC2ClientMock.describeSecurityGroups(any(DescribeSecurityGroupsRequest.class))).thenThrow(amazonServiceException);
    securityGroupProvider = new SecurityGroupProvider(clientProviderMock);
    final String securityGroup = securityGroupProvider.getSecurityGroup(Lists.newArrayList("sg.1234"), REGION, "9876");
    Assertions.assertThat(securityGroup).isEqualTo(null);
    verify(clientProviderMock).getClient(any(), anyString(), any(Region.class));
    verify(amazonEC2ClientMock).describeSecurityGroups(any(DescribeSecurityGroupsRequest.class));
}
Example 13
Project: JRocket-master  File: BookmarkTest.java View source code
/**
     * Simple Unit Test that uses AssertJ Assertions Java library.
     */
@Test
public void create() {
    // Given
    String inputUrl = "http://some-url.fr";
    String inputTitle = "Lorem ipsum";
    String inputDescription = "Lorem ipsum dolor sit amet...";
    // When
    Bookmark bookmark = Bookmark.create(inputUrl, inputTitle, inputDescription);
    // Then
    Assertions.assertThat(bookmark.getUrl()).isEqualTo(inputUrl);
    Assertions.assertThat(bookmark.getTitle()).isEqualTo(inputTitle);
    Assertions.assertThat(bookmark.getDescription()).isEqualTo(inputDescription);
    Assertions.assertThat(bookmark.getCreationDate()).isNull();
    Assertions.assertThat(bookmark.getModificationDate()).isNull();
}
Example 14
Project: JsonPath-master  File: NullHandlingTest.java View source code
@Test
public void the_age_of_all_with_age_defined() {
    //List<Integer> result = JsonPath.read(DOCUMENT, "$.children[*].age");
    List<Integer> result = JsonPath.using(Configuration.defaultConfiguration().setOptions(Option.SUPPRESS_EXCEPTIONS)).parse(DOCUMENT).read("$.children[*].age");
    Assertions.assertThat(result).containsSequence(0, null);
}
Example 15
Project: webmagic-master  File: RegexSelectorTest.java View source code
@Test
public void testRegexWithZeroWidthAssertions() {
    String regex = "^.*(?=\\?)";
    String source = "hello world?xxxx";
    RegexSelector regexSelector = new RegexSelector(regex);
    String select = regexSelector.select(source);
    Assertions.assertThat(select).isEqualTo("hello world");
    regex = "\\d{3}(?!\\d)";
    source = "123456asdf";
    regexSelector = new RegexSelector(regex);
    select = regexSelector.select(source);
    Assertions.assertThat(select).isEqualTo("456");
}
Example 16
Project: beakerx-master  File: ScalaEvaluatorTest.java View source code
@Test
public void evaluatePlot_shouldCreatePlotObject() throws Exception {
    //given
    String code = "import com.twosigma.beaker.chart.xychart.Plot;\n" + "val plot = new Plot();\n" + "plot.setTitle(\"test title\");";
    SimpleEvaluationObject seo = new SimpleEvaluationObject(code, new ExecuteCodeCallbackTest());
    //when
    scalaEvaluator.evaluate(seo, code);
    waitForResult(seo);
    //then
    Assertions.assertThat(seo.getStatus()).isEqualTo(FINISHED);
    Assertions.assertThat(seo.getPayload() instanceof Plot).isTrue();
    Assertions.assertThat(((Plot) seo.getPayload()).getTitle()).isEqualTo("test title");
}
Example 17
Project: luwak-master  File: TestMonitorPersistence.java View source code
@Test
public void testCacheIsRepopulated() throws IOException, UpdateException {
    InputDocument doc = InputDocument.builder("doc1").addField("f", "test", new StandardAnalyzer()).build();
    try (Monitor monitor = new Monitor(new LuceneQueryParser("f"), new TermFilteredPresearcher(), new MMapDirectory(indexDirectory))) {
        monitor.update(new MonitorQuery("1", "test"), new MonitorQuery("2", "test"), new MonitorQuery("3", "test", ImmutableMap.of("language", "en")), new MonitorQuery("4", "test", ImmutableMap.of("language", "en", "wibble", "quack")));
        assertThat(monitor.match(doc, SimpleMatcher.FACTORY)).hasMatchCount("doc1", 4);
    }
    try (Monitor monitor2 = new Monitor(new LuceneQueryParser("f"), new TermFilteredPresearcher(), new MMapDirectory(indexDirectory))) {
        Assertions.assertThat(monitor2.getQueryCount()).isEqualTo(4);
        assertThat(monitor2.match(doc, SimpleMatcher.FACTORY)).hasMatchCount("doc1", 4);
    }
}
Example 18
Project: mockito-master  File: SafeJUnitRuleTest.java View source code
@Test
public void expected_exception_message_did_not_match() throws Throwable {
    //expect
    rule.expectFailure(AssertionError.class, "FOO");
    //when
    try {
        rule.apply(new Statement() {

            public void evaluate() throws Throwable {
                throw new AssertionError("BAR");
            }
        }, mock(FrameworkMethod.class), this).evaluate();
        fail();
    } catch (AssertionError throwable) {
        Assertions.assertThat(throwable).hasMessageContaining("Expecting message");
    }
}
Example 19
Project: robolectric-master  File: ShadowMediaMetadataRetrieverTest.java View source code
@Test
public void reset_clearsStaticValues() {
    addMetadata(path, METADATA_KEY_ARTIST, "The Rolling Stones");
    addFrame(path, 1, bitmap);
    addException(toDataSource(path2), new IllegalArgumentException());
    retriever.setDataSource(path);
    assertThat(retriever.extractMetadata(METADATA_KEY_ARTIST)).isEqualTo("The Rolling Stones");
    assertThat(retriever.getFrameAtTime(1)).isSameAs(bitmap);
    try {
        retriever2.setDataSource(path2);
        Assertions.failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
    } catch (IllegalArgumentException e) {
    }
    ShadowMediaMetadataRetriever.reset();
    assertThat(retriever.extractMetadata(METADATA_KEY_ARTIST)).isNull();
    assertThat(retriever.getFrameAtTime(1)).isNull();
    try {
        retriever2.setDataSource(path2);
    } catch (IllegalArgumentException e) {
        Assertions.fail("Shouldn't throw exception after reset", e);
    }
}
Example 20
Project: smartparam-master  File: ReportingTreeAssert.java View source code
@SuppressWarnings("unchecked")
public ReportingTreeAssert containsValues(Object... leavesValues) {
    List<ReportingTreePath<?>> leaves = (List<ReportingTreePath<?>>) actual.harvestLeavesValues();
    List<Object> rawValues = new ArrayList<Object>();
    for (ReportingTreePath<?> leaf : leaves) {
        rawValues.add(leaf.value());
    }
    Assertions.assertThat(rawValues).containsOnly(leavesValues);
    return this;
}
Example 21
Project: TruckMuncher-Android-master  File: ApiRequestInterceptorTest.java View source code
@Test
public void timeStampHeaderIsAdded() {
    interceptor.intercept(facade);
    assertThat(facade.headers).containsKey(ApiRequestInterceptor.HEADER_TIMESTAMP);
    String value = facade.headers.get(ApiRequestInterceptor.HEADER_TIMESTAMP);
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    try {
        format.parse(value);
    } catch (ParseException e) {
        Assertions.fail("Unable to parse the header timestamp", e);
    }
}
Example 22
Project: activedirectory-master  File: GroupMappingWaffleRealmTests.java View source code
/**
     * Test valid username password.
     */
@Test
public void testValidUsernamePassword() {
    final AuthenticationToken token = new UsernamePasswordToken(this.getCurrentUserName(), "somePassword");
    final AuthenticationInfo authcInfo = this.realm.getAuthenticationInfo(token);
    final PrincipalCollection principals = authcInfo.getPrincipals();
    Assert.assertFalse(principals.isEmpty());
    final Object primaryPrincipal = principals.getPrimaryPrincipal();
    Assert.assertNotNull(primaryPrincipal);
    Assertions.assertThat(primaryPrincipal).isInstanceOf(WaffleFqnPrincipal.class);
    final WaffleFqnPrincipal fqnPrincipal = (WaffleFqnPrincipal) primaryPrincipal;
    Assertions.assertThat(fqnPrincipal.getFqn()).isEqualTo(this.getCurrentUserName());
    Assertions.assertThat(fqnPrincipal.getGroupFqns()).contains("Users", "Everyone");
    final Object credentials = authcInfo.getCredentials();
    Assertions.assertThat(credentials).isInstanceOf(char[].class);
    Assertions.assertThat(credentials).isEqualTo("somePassword".toCharArray());
    Assert.assertTrue(this.realm.hasRole(principals, GroupMappingWaffleRealmTests.ROLE_NAME));
}
Example 23
Project: aws-ec2-start-stop-tools-master  File: ProgramOptionsTest.java View source code
@Test
public void testProgramOptionsGetterTrue() {
    final ProgramOptions programOptions = new ProgramOptions(true, true, true, true, new ArrayList<String>());
    Assertions.assertThat(programOptions.hasCheckOption()).isTrue();
    Assertions.assertThat(programOptions.hasPostCheckOption()).isTrue();
    Assertions.assertThat(programOptions.hasListOption()).isTrue();
    Assertions.assertThat(programOptions.hasExecutionOption()).isTrue();
    Assertions.assertThat(programOptions.hasNoSectionOption()).isTrue();
    Assertions.assertThat(programOptions.getSectionOptions()).isEmpty();
}
Example 24
Project: camunda-bpm-assert-master  File: CaseInstanceAssertTest.java View source code
@Test
@Deployment(resources = { "cmmn/TaskTest.cmmn" })
public void task_should_return_HumanTaskAssert_for_given_activityId() {
    // Given
    CaseInstance caseInstance = aStartedCase();
    CaseExecution pi_taskA = caseService().createCaseExecutionQuery().activityId(TASK_A).singleResult();
    // Then
    assertThat(caseInstance).isActive();
    // When
    HumanTaskAssert caseTaskAssert = assertThat(caseInstance).humanTask(TASK_A);
    // Then
    CaseExecution actual = caseTaskAssert.getActual();
    Assertions.assertThat(actual).overridingErrorMessage("Expected case execution " + toString(actual) + " to be equal to " + toString(pi_taskA)).isEqualToComparingOnlyGivenFields(pi_taskA, "id");
}
Example 25
Project: Fiazard-master  File: FiazardExceptionToJSONMapperTest.java View source code
@Test
public void mapsToErrorR() throws Exception {
    AppErrorCode expectedAppError = AppErrorCode.ILLEGAL_ID;
    String expectedMessage = "exception message";
    int expectedStatus = 400;
    ErrorR expectedErrorR = new ErrorRBuilderForTests().withStatus(expectedStatus).withErrorCode(expectedAppError.getErrorCode()).withMessage(expectedMessage).withFields("aField", "bField").build();
    FiazardExceptionBuilder.DummyFiazardException dummyFiazardException = someFiazardExceptionBuilder().withStatus(expectedStatus).withAppError(expectedAppError).withMessage(expectedMessage).withFields("aField", "bField").build();
    Response actual = mapper.toResponse(dummyFiazardException);
    Assertions.assertThat(actual.getStatus()).isEqualTo(expectedStatus);
    Assertions.assertThat(actual.getEntity()).isEqualTo(expectedErrorR);
}
Example 26
Project: hppc-master  File: HashContainersTest.java View source code
@Test
public void testAddReplacements() {
    ObjectHashSet<Integer> set = new ObjectHashSet<>();
    HashSet<Integer> reference = new HashSet<>();
    Integer i1 = 1;
    Integer i2 = new Integer(i1.intValue());
    assertTrue(set.add(i1));
    assertTrue(reference.add(i1));
    assertFalse(set.add(i2));
    assertFalse(reference.add(i2));
    Assertions.assertThat(reference.iterator().next()).isSameAs(i1);
    Assertions.assertThat(set.iterator().next().value).isSameAs(i1);
}
Example 27
Project: NOVA-Core-master  File: PipelineTest.java View source code
@Test
public void testRenderStream2() throws Exception {
    Model model = new MeshModel();
    RenderPipeline renderPipeline1 = new RenderPipeline().apply(new RenderPipeline( m -> m.addChild(new MeshModel())));
    RenderPipeline renderPipeline = renderPipeline1.apply(new RenderPipeline( m -> m.addChild(new MeshModel())));
    renderPipeline.build().accept(model);
    Assertions.assertThat(model.children).hasSize(2);
}
Example 28
Project: seed-master  File: EncryptionServiceFactoryTest.java View source code
@Test
public void testCreateEncryptionService() throws Exception {
    new Expectations() {

        {
            keyStore.getKey(ALIAS, PASSWORD);
            result = key;
            keyStore.getCertificate(ALIAS);
            result = certificate;
            certificate.getPublicKey();
            result = publicKey;
        }
    };
    KeyPairConfig keyPairConfig = new KeyPairConfig("keyStoreName", ALIAS, "password", null, null);
    EncryptionServiceFactory factory = new EncryptionServiceFactory(configuration, keyStore);
    EncryptionService encryptionService = factory.create(ALIAS, PASSWORD);
    Assertions.assertThat(encryptionService).isNotNull();
    new Verifications() {

        {
            new EncryptionServiceImpl(ALIAS, publicKey, key);
        }
    };
}
Example 29
Project: spotless-master  File: StepHarness.java View source code
/** Asserts that the given elements in the resources directory are transformed as expected. */
public StepHarness testException(String resourceBefore, Consumer<AbstractThrowableAssert<?, ? extends Throwable>> exceptionAssertion) throws Exception {
    String before = ResourceHarness.getTestResource(resourceBefore);
    try {
        formatter.apply(before);
        Assert.fail();
    } catch (Throwable t) {
        AbstractThrowableAssert<?, ? extends Throwable> abstractAssert = Assertions.assertThat(t);
        exceptionAssertion.accept(abstractAssert);
    }
    return this;
}
Example 30
Project: spring-social-examples-master  File: RepositoryUserDetailsServiceTest.java View source code
@Test
public void loadByUsername_UserNotFound_ShouldThrowException() {
    when(repositoryMock.findByEmail(EMAIL)).thenReturn(null);
    catchException(service).loadUserByUsername(EMAIL);
    Assertions.assertThat(caughtException()).isExactlyInstanceOf(UsernameNotFoundException.class).hasMessage("No user found with username: " + EMAIL).hasNoCause();
    verify(repositoryMock, times(1)).findByEmail(EMAIL);
    verifyNoMoreInteractions(repositoryMock);
}
Example 31
Project: waffle-master  File: GroupMappingWaffleRealmTests.java View source code
/**
     * Test valid username password.
     */
@Test
public void testValidUsernamePassword() {
    final AuthenticationToken token = new UsernamePasswordToken(this.getCurrentUserName(), "somePassword");
    final AuthenticationInfo authcInfo = this.realm.getAuthenticationInfo(token);
    final PrincipalCollection principals = authcInfo.getPrincipals();
    Assert.assertFalse(principals.isEmpty());
    final Object primaryPrincipal = principals.getPrimaryPrincipal();
    Assert.assertNotNull(primaryPrincipal);
    Assertions.assertThat(primaryPrincipal).isInstanceOf(WaffleFqnPrincipal.class);
    final WaffleFqnPrincipal fqnPrincipal = (WaffleFqnPrincipal) primaryPrincipal;
    Assertions.assertThat(fqnPrincipal.getFqn()).isEqualTo(this.getCurrentUserName());
    Assertions.assertThat(fqnPrincipal.getGroupFqns()).contains("Users", "Everyone");
    final Object credentials = authcInfo.getCredentials();
    Assertions.assertThat(credentials).isInstanceOf(char[].class);
    Assertions.assertThat(credentials).isEqualTo("somePassword".toCharArray());
    Assert.assertTrue(this.realm.hasRole(principals, GroupMappingWaffleRealmTests.ROLE_NAME));
}
Example 32
Project: assertj-core-master  File: ObjectsBaseTest.java View source code
@Before
public void setUp() {
    failures = spy(new Failures());
    objects = new Objects();
    objects.failures = failures;
    customComparisonStrategy = new ComparatorBasedComparisonStrategy(comparatorForCustomComparisonStrategy());
    objectsWithCustomComparisonStrategy = new Objects(customComparisonStrategy);
    objectsWithCustomComparisonStrategy.failures = failures;
    // reverts to default value
    Assertions.setAllowComparingPrivateFields(true);
}
Example 33
Project: javaslang-master  File: Euler23Test.java View source code
@Test
public void shouldSolveProblem23() {
    List.range(1, SMALLEST_ABUNDANT_NUMBER).forEach( n -> Assertions.assertThat(isAbundant.apply(n)).isFalse());
    Assertions.assertThat(isAbundant.apply(SMALLEST_ABUNDANT_NUMBER)).isTrue();
    Assertions.assertThat(isAbundant.apply(28L)).isFalse();
    assertThat(canBeWrittenAsTheSumOfTwoAbundantNumbers(SMALLEST_NUMBER_WRITTEN_AS_THE_SUM_OF_TO_ABUNDANT_NUMBERS - 1)).isFalse();
    assertThat(canBeWrittenAsTheSumOfTwoAbundantNumbers(SMALLEST_NUMBER_WRITTEN_AS_THE_SUM_OF_TO_ABUNDANT_NUMBERS)).isTrue();
    assertThat(canBeWrittenAsTheSumOfTwoAbundantNumbers(LOWER_LIMIT_FOUND_BY_MATHEMATICAL_ANALYSIS_FOR_NUMBERS_THAT_CAN_BE_WRITTEN_AS_THE_SUM_OF_TO_ABUNDANT_NUMBERS + 1)).isTrue();
    assertThat(sumOfAllPositiveIntegersThatCannotBeWrittenAsTheSumOfTwoAbundantNumbers()).isEqualTo(4179871L);
}
Example 34
Project: liquigraph-master  File: ExecutionContextsTest.java View source code
@Test
public void no_configured_contexts_matches_any_changeset_contexts() {
    Assertions.assertThat(ExecutionContexts.DEFAULT_CONTEXT.matches(Optional.<Collection<String>>absent())).isTrue();
    Assertions.assertThat(ExecutionContexts.DEFAULT_CONTEXT.matches(fromNullable((Collection<String>) Collections.<String>emptyList()))).isTrue();
    Assertions.assertThat(ExecutionContexts.DEFAULT_CONTEXT.matches(fromNullable((Collection<String>) newArrayList("foo")))).isTrue();
}
Example 35
Project: sonarqube-master  File: SetQualityProfileOrganizationUuidToDefaultTest.java View source code
@Test
public void should_keep_existing_organization() throws SQLException {
    String otherOrg = "existing uuid";
    db.executeInsert("RULES_PROFILES", "NAME", "java", "kee", PROFILE_KEY, "organization_uuid", otherOrg);
    underTest.execute();
    Assertions.assertThat(db.selectFirst("SELECT ORGANIZATION_UUID FROM RULES_PROFILES WHERE KEE = '" + PROFILE_KEY + "'")).containsValue(otherOrg);
}
Example 36
Project: Traceur-master  File: TraceurTest.java View source code
@Test
public void callSiteIsShownInStackTrace() throws Exception {
    // Assumption - Call site not shown when Traceur not enabled
    try {
        StreamFactory.createNullPointerExceptionObservable().blockingFirst();
    } catch (Throwable t) {
        final String exceptionAsString = exceptionAsString(t);
        printStackTrace("Default Stacktrace", exceptionAsString);
        assertThat(exceptionAsString).doesNotContain("StreamFactory");
    }
    // Enable Traceur and ensure call site is shown
    Traceur.enableLogging();
    try {
        StreamFactory.createNullPointerExceptionObservable().blockingFirst();
        Assertions.failBecauseExceptionWasNotThrown(Throwable.class);
    } catch (Throwable t) {
        final String exceptionAsString = exceptionAsString(t);
        printStackTrace("Traceur Stacktrace", exceptionAsString);
        assertThat(exceptionAsString).contains("StreamFactory");
    }
}
Example 37
Project: vavr-master  File: Euler23Test.java View source code
@Test
public void shouldSolveProblem23() {
    List.range(1, SMALLEST_ABUNDANT_NUMBER).forEach( n -> Assertions.assertThat(isAbundant.apply(n)).isFalse());
    Assertions.assertThat(isAbundant.apply(SMALLEST_ABUNDANT_NUMBER)).isTrue();
    Assertions.assertThat(isAbundant.apply(28L)).isFalse();
    assertThat(canBeWrittenAsTheSumOfTwoAbundantNumbers(SMALLEST_NUMBER_WRITTEN_AS_THE_SUM_OF_TO_ABUNDANT_NUMBERS - 1)).isFalse();
    assertThat(canBeWrittenAsTheSumOfTwoAbundantNumbers(SMALLEST_NUMBER_WRITTEN_AS_THE_SUM_OF_TO_ABUNDANT_NUMBERS)).isTrue();
    assertThat(canBeWrittenAsTheSumOfTwoAbundantNumbers(LOWER_LIMIT_FOUND_BY_MATHEMATICAL_ANALYSIS_FOR_NUMBERS_THAT_CAN_BE_WRITTEN_AS_THE_SUM_OF_TO_ABUNDANT_NUMBERS + 1)).isTrue();
    assertThat(sumOfAllPositiveIntegersThatCannotBeWrittenAsTheSumOfTwoAbundantNumbers()).isEqualTo(4179871L);
}
Example 38
Project: CorfuDB-master  File: LogUnitServerAssertions.java View source code
public LogUnitServerAssertions matchesDataAtAddress(long address, Object data) {
    isNotNull();
    if (actual.getDataCache().get(new LogAddress(address, null)) == null) {
        failWithMessage("Expected address <%d> to contain data but was empty!", address);
    } else {
        ByteBuf b = Unpooled.buffer();
        Serializers.CORFU.serialize(data, b);
        byte[] expected = new byte[b.readableBytes()];
        b.getBytes(0, expected);
        org.assertj.core.api.Assertions.assertThat(((LogData) actual.getDataCache().get(new LogAddress(address, null))).getData()).isEqualTo(expected);
    }
    return this;
}
Example 39
Project: Achilles-master  File: ManagerCodeGenTest.java View source code
@Test
public void should_generate_manager_class_for_index_dsl() throws Exception {
    setExec( aptUtils -> {
        final GlobalParsingContext globalContext = new GlobalParsingContext(V3_7.INSTANCE, InsertStrategy.ALL_FIELDS, new LowerCaseNaming(), FieldFilter.EXPLICIT_ENTITY_FIELD_FILTER, FieldFilter.EXPLICIT_UDT_FIELD_FILTER, Optional.empty());
        final String className = TestEntityWithSASI.class.getCanonicalName();
        final TypeElement typeElement = aptUtils.elementUtils.getTypeElement(className);
        final EntityParser entityParser = new EntityParser(aptUtils);
        final EntityMetaSignature entityMetaSignature = entityParser.parseEntity(typeElement, globalContext);
        final ManagerAndDSLClasses managerAndDSLClasses = ManagerCodeGen.buildManager(globalContext, aptUtils, entityMetaSignature);
        final StringBuilder builder = new StringBuilder();
        try {
            JavaFile.builder(TypeUtils.GENERATED_PACKAGE, managerAndDSLClasses.managerClass).build().writeTo(builder);
        } catch (IOException e) {
            Assertions.assertThat(false).as("IOException when generating class : %s", e.getMessage()).isTrue();
        }
        assertThat(builder.toString().trim()).isEqualTo(readCodeBlockFromFile("expected_code/manager/should_generate_manager_class_for_index_dsl.txt"));
    });
    launchTest();
}
Example 40
Project: async-retry-master  File: AsyncRetryJobTest.java View source code
@Test
public void shouldRethrowExceptionThatWasThrownFromUserTaskBeforeReturningFuture() throws Exception {
    //given
    final RetryExecutor executor = new AsyncRetryExecutor(schedulerMock).abortOn(IllegalArgumentException.class);
    given(serviceMock.safeAsync()).willThrow(new IllegalArgumentException(DON_T_PANIC));
    //when
    final CompletableFuture<String> future = executor.getFutureWithRetry( ctx -> serviceMock.safeAsync());
    //then
    assertThat(future.isCompletedExceptionally()).isTrue();
    try {
        future.get();
        Assertions.failBecauseExceptionWasNotThrown(ExecutionException.class);
    } catch (ExecutionException e) {
        assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class);
        assertThat(e.getCause()).hasMessage(DON_T_PANIC);
    }
}
Example 41
Project: couch-java-master  File: ClassicAuthenticatorTesst.java View source code
@Test
public void shouldAllowToResetAuthenticator() {
    Authenticator auth1 = cluster.authenticator();
    Authenticator auth2 = new ClassicAuthenticator();
    Assertions.assertThat(cluster.authenticator()).isSameAs(auth1);
    cluster.authenticate(auth2);
    Assertions.assertThat(cluster.authenticator()).isNotSameAs(auth1).isSameAs(auth2);
}
Example 42
Project: couchbase-java-client-master  File: ClassicAuthenticatorTesst.java View source code
@Test
public void shouldAllowToResetAuthenticator() {
    Authenticator auth1 = cluster.authenticator();
    Authenticator auth2 = new ClassicAuthenticator();
    Assertions.assertThat(cluster.authenticator()).isSameAs(auth1);
    cluster.authenticate(auth2);
    Assertions.assertThat(cluster.authenticator()).isNotSameAs(auth1).isSameAs(auth2);
}
Example 43
Project: ebean-master  File: TestHstore.java View source code
void json_parse_format() {
    String asJson = Ebean.json().toJson(bean);
    assertThat(asJson).contains("\"map\":{\"home\":\"123\",\"work\":\"987\"}");
    EBasicHstore fromJson = Ebean.json().toBean(EBasicHstore.class, asJson);
    assertEquals(bean.getId(), fromJson.getId());
    assertEquals(bean.getName(), fromJson.getName());
    Assertions.assertThat(fromJson.getMap().keySet()).containsExactly("home", "work");
}
Example 44
Project: neba-master  File: ResourceModelMetaDataTest.java View source code
private void assertMetadataEqualsMetadataOf(Class<?> otherModel) {
    MappedFieldMetaData[] mappableFields = this.testee.getMappableFields();
    MethodMetaData[] preMappingMethods = this.testee.getPreMappingMethods();
    MethodMetaData[] postMappingMethods = this.testee.getPostMappingMethods();
    ResourceModelMetaData other = new ResourceModelMetaData(otherModel);
    Assertions.assertThat(mappableFields).isEqualTo(other.getMappableFields());
    Assertions.assertThat(postMappingMethods).isEqualTo(other.getPostMappingMethods());
    Assertions.assertThat(preMappingMethods).isEqualTo(other.getPreMappingMethods());
}
Example 45
Project: assertj-guava-master  File: TableAssert_isEmpty_Test.java View source code
@Test
public void should_fail_if_actual_is_not_empty() {
    try {
        assertThat(actual).isEmpty();
    } catch (AssertionError e) {
        Assertions.assertThat(e).hasMessage(String.format("%nExpecting empty but was:<{1={4=Franklin Pierce, 3=Millard Fillmore}, 2={5=Grover Cleveland}}>"));
        return;
    }
    fail("Assertion error expected");
}
Example 46
Project: booties-master  File: UsersTemplatePublicKeyTest.java View source code
@Test
public void getPublicKeys() throws Exception {
    mockServer.expect(requestTo("https://api.github.com/user/keys")).andExpect(method(HttpMethod.GET)).andRespond(// .andExpect(header("Authorization", "Bearer ACCESS_TOKEN"))
    withSuccess(new ClassPathResource("listPublicKeys.json", getClass()), MediaType.APPLICATION_JSON));
    List<ExtPubKey> publicKeyList = usersTemplate.listPublicKeys();
    Assertions.assertThat(publicKeyList).isNotNull();
    Assertions.assertThat(publicKeyList.size()).isEqualTo(1);
    Assertions.assertThat(publicKeyList.get(0).getKey()).isEqualTo("ssh-rsa AAA...");
}
Example 47
Project: Boxer-master  File: BoxerTest.java View source code
@Test
public void obtainDefaultWrappers() {
    Assertions.assertThat(Boxer.from(new Bundle())).isOfAnyClassIn(BundleWrapper.class).isNotNull();
    Assertions.assertThat(Boxer.from(new DataMap())).isOfAnyClassIn(DataMapWrapper.class).isNotNull();
    Assertions.assertThat(Boxer.from(Parcel.obtain())).isOfAnyClassIn(ParcelWrapper.class).isNotNull();
    Assertions.assertThat(Boxer.from(sqLiteHelper.getReadableDatabase())).isOfAnyClassIn(SQLiteWrapper.class).isNotNull();
}
Example 48
Project: CacheIO-master  File: GsonValueMapperTest.java View source code
@Test
public void shouldDeserializeAObject() throws Exception {
    UserTestModel userTestModelToDeserialize = fakeUserTestObject();
    byte[] userDeserialized = fakeUserTestBytes(userTestModelToDeserialize);
    final ByteArrayInputStream bytesIn = new ByteArrayInputStream(userDeserialized);
    final UserTestModel value = valueMapper.read(UserTestModel.class, bytesIn);
    Assertions.assertThat(value).isNotNull();
    Assertions.assertThat(value.getId()).isEqualTo(userTestModelToDeserialize.getId());
    Assertions.assertThat(value.getName()).isEqualTo(userTestModelToDeserialize.getName());
}
Example 49
Project: camunda-bpm-needle-master  File: TestProcessTest.java View source code
@Test
@Deployment(resources = "test-process.bpmn")
public void should_deploy_and_start_process_via_starter_bean() {
    Assert.assertNotNull(processEngineNeedleRule.getDeploymentId());
    Mocks.register("serviceTask", serviceTaskMock);
    final ProcessInstance processInstance = testProcessStarter.startProcessWithUser("foo", UUID.randomUUID().toString());
    ProcessEngineTests.assertThat(processInstance).isActive();
    ProcessEngineTests.assertThat(processInstance).task().isNotAssigned();
    final Task task = ProcessEngineTests.task();
    Assertions.assertThat(task).isNotNull();
    ProcessEngineTests.assertThat(task).hasDefinitionKey("task_wait");
    taskService.complete(task.getId());
    ProcessEngineTests.assertThat(processInstance).isEnded();
}
Example 50
Project: cereebro-master  File: RelationshipHintsTest.java View source code
@Test
public void test() {
    Set<Relationship> result = detector.detect();
    Dependency d1 = Dependency.on(Component.of("d1", "d1"));
    Dependency d2 = Dependency.on(Component.of("d2", "d2"));
    Dependency d3 = Dependency.on(Component.of("d3", "d3"));
    Consumer c1 = Consumer.by(Component.of("c1", "c1"));
    Consumer c2 = Consumer.by(Component.of("c2", "c2"));
    Consumer c3 = Consumer.by(Component.of("c3", "c3"));
    Set<Relationship> expected = new HashSet<>(Arrays.asList(d1, d2, d3, c1, c2, c3));
    Assertions.assertThat(result).isEqualTo(expected);
}
Example 51
Project: circuitbreaker-master  File: EventConsumerTest.java View source code
@Test
public void shouldReturnAfterThreeAttempts() {
    // Given the HelloWorldService throws an exception
    BDDMockito.willThrow(new WebServiceException("BAM!")).given(helloWorldService).sayHelloWorld();
    // Create a Retry with default configuration
    RetryContext retryContext = (RetryContext) Retry.ofDefaults("id");
    TestSubscriber<RetryEvent.Type> testSubscriber = retryContext.getEventStream().map(RetryEvent::getEventType).test();
    // Decorate the invocation of the HelloWorldService
    CheckedRunnable retryableRunnable = Retry.decorateCheckedRunnable(retryContext, helloWorldService::sayHelloWorld);
    // When
    Try<Void> result = Try.run(retryableRunnable);
    // Then the helloWorldService should be invoked 3 times
    BDDMockito.then(helloWorldService).should(Mockito.times(3)).sayHelloWorld();
    // and the result should be a failure
    Assertions.assertThat(result.isFailure()).isTrue();
    // and the returned exception should be of type RuntimeException
    Assertions.assertThat(result.failed().get()).isInstanceOf(WebServiceException.class);
    Assertions.assertThat(sleptTime).isEqualTo(RetryConfig.DEFAULT_WAIT_DURATION * 2);
    testSubscriber.assertValueCount(1).assertValues(RetryEvent.Type.ERROR);
}
Example 52
Project: drools-master  File: UseOfRuleFlowGroupPlusLockOnTest.java View source code
@Test
public void test() {
    final Resource resource = KieServices.Factory.get().getResources().newReaderResource(new StringReader(DRL));
    resource.setTargetPath(TestConstants.DRL_TEST_TARGET_PATH);
    final KieBuilder kbuilder = KieUtil.getKieBuilderFromResources(true, resource);
    final KieBase kbase = KieBaseUtil.getDefaultKieBaseFromKieBuilder(kbuilder);
    final KieSession ksession = kbase.newKieSession();
    ksession.insert(new Person());
    ksession.insert(new Cheese("eidam"));
    ((DefaultAgenda) ksession.getAgenda()).activateRuleFlowGroup("group1");
    Assertions.assertThat(ksession.fireAllRules()).isEqualTo(1);
    ksession.dispose();
}
Example 53
Project: elasticsearch-carrot2-master  File: MultithreadedClusteringIT.java View source code
public void testRequestFlood() throws Exception {
    final Client client = client();
    List<Callable<ClusteringActionResponse>> tasks = new ArrayList<>();
    final int requests = 100;
    final int threads = 10;
    logger.debug("Stress testing: " + client.getClass().getSimpleName() + "| ");
    for (int i = 0; i < requests; i++) {
        tasks.add(() -> {
            logger.debug(">");
            ClusteringActionResponse result = new ClusteringActionRequestBuilder(client).setQueryHint("data mining").addFieldMapping("title", LogicalField.TITLE).addHighlightedFieldMapping("content", LogicalField.CONTENT).setSearchRequest(client.prepareSearch().setIndices(INDEX_NAME).setTypes("test").setSize(100).setQuery(QueryBuilders.termQuery("content", "data")).highlighter(new HighlightBuilder().preTags("").postTags("").field("content")).storedFields("title")).execute().actionGet();
            logger.debug("<");
            checkValid(result);
            checkJsonSerialization(result);
            return result;
        });
    }
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    try {
        for (Future<ClusteringActionResponse> future : executor.invokeAll(tasks)) {
            ClusteringActionResponse response = future.get();
            Assertions.assertThat(response).isNotNull();
            Assertions.assertThat(response.getSearchResponse()).isNotNull();
        }
    } finally {
        executor.shutdown();
        logger.debug("Done.");
    }
}
Example 54
Project: elasticsearch-reindex-tool-master  File: ReindexInvokerWithIndexingErrorsTest.java View source code
@Test
public void shouldWarnWhenIndexingFails() throws Exception {
    //given
    indexWithSampleData();
    embeddedElasticsearchCluster.createIndex(TARGET_INDEX, DATA_TYPE, createStrictMappingDefinition());
    ElasticDataPointer sourceDataPointer = embeddedElasticsearchCluster.createDataPointer(SOURCE_INDEX);
    ElasticDataPointer targetDataPointer = embeddedElasticsearchCluster.createDataPointer(TARGET_INDEX);
    ElasticSearchQuery elasticSearchQuery = embeddedElasticsearchCluster.createInitialQuery("");
    //when
    ReindexingSummary reindexingSummary = ReindexInvoker.invokeReindexing(sourceDataPointer, targetDataPointer, EmptySegmentation.createEmptySegmentation(elasticSearchQuery));
    //then
    Assertions.assertThat(embeddedElasticsearchCluster.count(SOURCE_INDEX)).isEqualTo(8L);
    Assertions.assertThat(embeddedElasticsearchCluster.count(TARGET_INDEX)).isEqualTo(4L);
    ReindexingSummaryAssert.assertThat(reindexingSummary).hasIndexedCount(8L).hasQueriedCount(8L).hasFailedIndexedCount(4L);
}
Example 55
Project: hibernate-validator-master  File: XmlParsingTest.java View source code
@Test
@TestForIssue(jiraKey = "HV-1101")
public void xmlConstraintMappingSupportsTabsWithoutNewLines() {
    Validator validator = getConfiguration().addMapping(XmlParsingTest.class.getResourceAsStream("hv-1101-tabs-mapping.xml")).buildValidatorFactory().getValidator();
    ConstraintDescriptorImpl<?> descriptor = getSingleConstraintDescriptorForClass(validator, Double.class);
    MyConstraint constraint = (MyConstraint) descriptor.getAnnotation();
    Assertions.assertThat(constraint.additionalConstraints()).hasSize(1);
    Assertions.assertThat(constraint.additionalConstraints()[0].constraint()).isEqualTo("AA");
}
Example 56
Project: io-addon-master  File: SuperCSVParserIT.java View source code
@Test
public void parse_csv_with_parsers() {
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(CSV_CONTENT.getBytes());
    Parser parser = parsers.getParserFor("pojo");
    List<CustomerBean> customerBeans = parser.parse(byteArrayInputStream, CustomerBean.class);
    Assertions.assertThat(customerBeans.size()).isEqualTo(2);
}
Example 57
Project: jaxygen-master  File: JsonResponseConverterTest.java View source code
@Test
public void shall_serializeTimeToDefaultFormat() throws Exception {
    // given
    DateContainer dc = new DateContainer();
    dc.setDate(new Date(99, 3, 1, 22, 55, 11));
    OutputStream writter = new ByteArrayOutputStream();
    JsonResponseConverter instance = new JsonResponseConverter();
    // when
    instance.serialize(dc, writter);
    // then
    Assertions.assertThat(writter.toString()).isEqualTo("{\"date\":\"01-04-1999 22:55:11\"}");
}
Example 58
Project: jbpm-master  File: HumanTaskAssignmentTest.java View source code
@Test
@BZ("1103977")
public void testGetTasksAssignedAsPotentialOwnerGroup() {
    createRuntimeManager(GET_TASKS_OWNER_GROUP);
    KieSession ksession = getRuntimeEngine().getKieSession();
    InternalTaskService taskService = (InternalTaskService) getRuntimeEngine().getTaskService();
    long pid = ksession.startProcess(GET_TASKS_OWNER_GROUP_ID).getId();
    // Task is assigned to group HR.
    List<TaskSummary> taskList = taskService.getTasksAssignedAsPotentialOwner(null, Arrays.asList("HR"));
    Assertions.assertThat(taskList).hasSize(1);
    Assertions.assertThat(taskList.get(0).getStatus()).isEqualTo(Status.Ready);
    Long taskId = taskList.get(0).getId();
    taskService.claim(taskId, "mary");
    taskService.start(taskId, "mary");
    taskService.complete(taskId, "mary", null);
    Task task = taskService.getTaskById(taskId);
    Assertions.assertThat(task.getTaskData().getStatus()).isEqualTo(Status.Completed);
    // Next task is assigned to group PM.
    // So task list for HR will be empty.
    taskList = taskService.getTasksAssignedAsPotentialOwner(null, Arrays.asList("HR"));
    Assertions.assertThat(taskList).hasSize(0);
    taskList = taskService.getTasksAssignedAsPotentialOwner(null, Arrays.asList("PM"));
    Assertions.assertThat(taskList).hasSize(1);
    Assertions.assertThat(taskList.get(0).getStatus()).isEqualTo(Status.Ready);
    ksession.abortProcessInstance(pid);
}
Example 59
Project: jbpmmigration-master  File: SingleTaskWithEventTest.java View source code
@Test
public void testJpdl() throws Exception {
    ProcessInstance pi = processDef.createProcessInstance();
    TrackingActionListener listener = new TrackingActionListener();
    // pi.getContextInstance().createVariable("listener", listener);
    DefaultActionHandler.setTrackingListener(listener);
    DefaultActionHandler.setSignalization(false);
    pi.signal();
    JpdlAssert.assertProcessStarted(pi);
    TaskInstance ti = JpdlHelper.getTaskInstance("Test task", pi);
    Assertions.assertThat(ti.getActorId()).isEqualTo("EXPERT");
    ti.end();
    JpdlAssert.assertTaskEnded(ti);
    Assertions.assertThat(listener.wasCalledOnNode("human-task")).isTrue();
    Assertions.assertThat(listener.wasEventAccepted("node-enter")).isTrue();
    Assertions.assertThat(listener.wasEventAccepted("node-leave")).isTrue();
    JpdlAssert.assertProcessCompleted(pi);
}
Example 60
Project: jdeps-maven-plugin-master  File: JdkInternalsExecutionServiceTest.java View source code
@Test
public void execute_internalDependenciesExist_returnsViolations() throws Exception {
    // print this class' name as a header for the following JDeps output
    System.out.println("\n# " + getClass().getSimpleName().toUpperCase() + "\n");
    Result result = JdkInternalsExecutionService.execute(PATH_TO_SCANNED_FOLDER, new DependencyRulesConfiguration(Severity.WARN, PackageInclusion.HIERARCHICAL, Collections.emptyList(), Collections.emptyList()));
    Assertions.assertThat(violations(result, Severity.IGNORE)).isEmpty();
    Assertions.assertThat(violations(result, Severity.SUMMARIZE)).isEmpty();
    Assertions.assertThat(violations(result, Severity.INFORM)).isEmpty();
    Assertions.assertThat(violations(result, Severity.WARN)).containsOnly(onActionsViolation(), onBASE64Violation(), onUnsafeViolation());
    Assertions.assertThat(violations(result, Severity.FAIL)).isEmpty();
}
Example 61
Project: jmx-zabbix-master  File: ZabbixClientProtocolTest.java View source code
@Test
public void should() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ZabbixProtocol.write(out, "salut!".getBytes());
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    byte[] read = ZabbixProtocol.read(in);
    Assertions.assertThat(new String(read)).isEqualTo("salut!");
    Assertions.assertThat(in.available()).isEqualTo(0);
}
Example 62
Project: json2java4idea-master  File: ElementAssert.java View source code
@Nonnull
public ElementAssert hasAttribute(@Nonnull String expectedName, @Nonnull String expectedValue) {
    isNotNull();
    final Attribute actual = this.actual.getAttribute(expectedName);
    Assertions.assertThat(actual).overridingErrorMessage("Expected attribute named <%s> does not exist", expectedName).isNotNull();
    final String actualName = actual.getName();
    Assertions.assertThat(actualName).overridingErrorMessage("Expected attribute name to be <%s> but was <%s>", expectedName, actualName).isEqualTo(expectedName);
    final String actualValue = actual.getValue();
    Assertions.assertThat(actualValue).overridingErrorMessage("Expected attribute value to be <%s> but was <%s>", expectedValue, actualValue).isEqualTo(expectedValue);
    return this;
}
Example 63
Project: linuxtools-master  File: DockerConnectionManagerTest.java View source code
@Test
public void shouldRegisterConnectionOnRefreshContainersManager() {
    // given
    final DockerClient client = MockDockerClientFactory.build();
    final DockerConnection dockerConnection = MockDockerConnectionFactory.from("Test", client).withDefaultTCPConnectionSettings();
    dockerConnectionManager.setConnectionStorageManager(MockDockerConnectionStorageManagerFactory.providing(dockerConnection));
    SWTUtils.syncExec(() -> dockerConnectionManager.reloadConnections());
    // when
    dockerConnection.getContainers();
    // then
    Assertions.assertThat(dockerContainersRefreshManager.getConnections()).contains(dockerConnection);
}
Example 64
Project: nuxeo-master  File: CanStandbyAndResumeTest.java View source code
@Test
public void canCommand() throws InterruptedException {
    MBeanServer server = Framework.getService(ServerLocator.class).lookupServer();
    StandbyMXBean bean = JMX.newMBeanProxy(server, ObjectNameFactory.getObjectName(StandbyCommand.class.getName()), StandbyMXBean.class);
    Assertions.assertThat(bean.isStandby()).isFalse();
    bean.standby(10);
    Assertions.assertThat(bean.isStandby()).isTrue();
    bean.resume();
    Assertions.assertThat(bean.isStandby()).isFalse();
}
Example 65
Project: ovirt-engine-master  File: LabelActionParametersTest.java View source code
private void validateLabelNameLength(Label label, boolean isValidLabelName) {
    LabelActionParameters parameters = new LabelActionParameters(label);
    List<String> validationMessages = ValidationUtils.validateInputs(new ArrayList<>(), parameters);
    if (isValidLabelName) {
        Assertions.assertThat(validationMessages).isEmpty();
    } else {
        Assertions.assertThat(validationMessages).contains(EngineMessage.AFFINITY_LABEL_NAME_SIZE_INVALID.name()).contains("$min 1").contains("$max " + BusinessEntitiesDefinitions.TAG_NAME_SIZE);
    }
}
Example 66
Project: splitlog-master  File: HandingDownTest.java View source code
@Test
public void testDuplicates() {
    final LogWatch watch = this.getLogWatch();
    Assertions.assertThat(watch.startHandingDown(HandingDownTest.MEASURE, HandingDownTest.ID)).isTrue();
    Assertions.assertThat(watch.startHandingDown(HandingDownTest.MEASURE, HandingDownTest.ID2)).isFalse();
    Assertions.assertThat(watch.startHandingDown(HandingDownTest.MEASURE2, HandingDownTest.ID)).isFalse();
}
Example 67
Project: swagger-codegen-tooling-master  File: ConfigurableCodegenConfigTest.java View source code
@Test
public void testConfigurableCodegenConfig() {
    TestConfigurableCodegenConfig codegenConfig = new TestConfigurableCodegenConfig();
    codegenConfig.setApiPackage("org.zalando.stups.api");
    codegenConfig.setModelPackage("org.zalando.stups.model");
    codegenConfig.setOutputDir("/a/path/to/generatedOutput");
    //
    Assertions.assertThat(codegenConfig.apiPackage()).isEqualTo("org.zalando.stups.api");
    Assertions.assertThat(codegenConfig.modelPackage()).isEqualTo("org.zalando.stups.model");
    Assertions.assertThat(codegenConfig.getOutputDir()).isEqualTo("/a/path/to/generatedOutput");
    Assertions.assertThat(codegenConfig.apiFileFolder()).isEqualTo("/a/path/to/generatedOutput/org/zalando/stups/api");
    Assertions.assertThat(codegenConfig.modelFileFolder()).isEqualTo("/a/path/to/generatedOutput/org/zalando/stups/model");
}
Example 68
Project: tokens-master  File: TokenVerifyRunnerTest.java View source code
@Test
public void create() {
    TokenVerifier verifier = Mockito.mock(TokenVerifier.class);
    Mockito.when(configuration.getTokenInfoUri()).thenReturn(tokenInfoUri);
    Mockito.when(configuration.getTokenVerifierMcbConfig()).thenReturn(new MCBConfig.Builder().build());
    Mockito.when(tokenVerifierProvider.create(Mockito.any(URI.class), Mockito.any(), Mockito.any())).thenReturn(verifier);
    Mockito.when(verifier.isTokenValid(Mockito.anyString())).thenReturn(true).thenReturn(false).thenReturn(true);
    TokenVerifyRunner runner = new TokenVerifyRunner(configuration, accessTokens, invalidTokens);
    // execute
    runner.run();
    runner.run();
    runner.run();
    try {
        runner.close();
    } catch (IOException e) {
    }
    Mockito.verify(verifier, Mockito.atLeast(3)).isTokenValid(Mockito.anyString());
    Assertions.assertThat(invalidTokens.size()).isEqualTo(1);
}
Example 69
Project: wisdom-master  File: PeriodParserTest.java View source code
@Test
public void testPredefinedPeriods() {
    Period period;
    period = Job.PERIOD_FORMATTER.parsePeriod(Every.DAY);
    Assertions.assertThat(period.getDays()).isEqualTo(1);
    Assertions.assertThat(period.getHours()).isEqualTo(0);
    Assertions.assertThat(period.getMinutes()).isEqualTo(0);
    period = Job.PERIOD_FORMATTER.parsePeriod(Every.HOUR);
    Assertions.assertThat(period.getDays()).isEqualTo(0);
    Assertions.assertThat(period.getHours()).isEqualTo(1);
    Assertions.assertThat(period.getMinutes()).isEqualTo(0);
    period = Job.PERIOD_FORMATTER.parsePeriod(Every.MINUTE);
    Assertions.assertThat(period.getDays()).isEqualTo(0);
    Assertions.assertThat(period.getHours()).isEqualTo(0);
    Assertions.assertThat(period.getMinutes()).isEqualTo(1);
}
Example 70
Project: WTFDYUM-master  File: SecurityAspectTest.java View source code
@Test
public void aroundSecuredMethodTestAuthorized() throws Throwable {
    final Object expectedResult = new Object();
    when(authenticationService.isAuthenticated()).thenReturn(true);
    when(pjp.proceed()).thenReturn(expectedResult);
    final Object result = sut.aroundSecuredMethod(pjp, new Secured() {

        @Override
        public Class<? extends Annotation> annotationType() {
            return null;
        }
    });
    Assertions.assertThat(result).isSameAs(expectedResult);
    verify(pjp, times(1)).proceed();
}
Example 71
Project: armeria-master  File: ZooKeeperRegistrationTest.java View source code
@Test
public void testServerNodeCreateAndDelete() {
    //all servers start and with zNode created
    sampleEndpoints.forEach( endpoint -> assertExists(zNode + '/' + endpoint.host() + '_' + endpoint.port()));
    try (CloseableZooKeeper zkClient = connection()) {
        try {
            sampleEndpoints.forEach( endpoint -> {
                try {
                    Assertions.assertThat(NodeValueCodec.DEFAULT.decode(zkClient.getData(zNode + '/' + endpoint.host() + '_' + endpoint.port()).get())).isEqualTo(endpoint);
                } catch (Throwable throwable) {
                    fail(throwable.getMessage());
                }
            });
            //stop one server and check its ZooKeeper node
            if (servers.size() > 1) {
                servers.get(0).stop().get();
                servers.remove(0);
                zkConnectors.remove(0);
                ZooKeeperUpdatingListener stoppedServerListener = listeners.remove(0);
                assertNotExists(zNode + '/' + stoppedServerListener.getEndpoint().host() + '_' + stoppedServerListener.getEndpoint().port());
                //the other server will not influenced
                assertExists(zNode + '/' + listeners.get(0).getEndpoint().host() + '_' + listeners.get(0).getEndpoint().port());
            }
        } catch (Throwable throwable) {
            fail(throwable.getMessage());
        }
    }
}
Example 72
Project: invesdwin-util-master  File: ADelegateComparator.java View source code
/**
     * Checks all elements
     */
public <T extends E> void assertOrder(final List<? extends T> list, final boolean ascending) {
    if (list == null || list.size() == 0) {
        return;
    }
    final Comparator<Object> comparator;
    if (ascending) {
        comparator = this;
    } else {
        comparator = asDescending();
    }
    T previousE = null;
    for (final T e : list) {
        if (previousE == null) {
            previousE = e;
        } else {
            final int compareResult = comparator.compare(e, previousE);
            if (compareResult < 0) {
                org.assertj.core.api.Assertions.assertThat(compareResult).as("No %s order: previousE [%s], e [%s]", ascending ? "ascending" : "descending", previousE, e).isGreaterThanOrEqualTo(0);
            }
        }
    }
}
Example 73
Project: NOVA-Microblock-master  File: MicroblockTest.java View source code
@Test
public void testMicroblockPlacement() {
    /**
		 * Microblock placement
		 */
    FakeWorld fakeWorld = new FakeWorld();
    Vector3D testPosition = new Vector3D(5, 5, 5);
    NovaMicroblock.MicroblockInjectFactory injectionFactory = (NovaMicroblock.MicroblockInjectFactory) TestMicroblockMod.singleMicroblock;
    ContainerPlace microblockPlace = new ContainerPlace(fakeWorld, injectionFactory, testPosition, new Block.PlaceEvent(null, null, null, null));
    assertThat(microblockPlace.operate()).isTrue();
    Block block = fakeWorld.getBlock(testPosition).get();
    assertThat(block.getID()).contains(TestMicroblockMod.containerID);
    assertThat(block.components.has(MicroblockContainer.class)).isTrue();
    MicroblockContainer microblockContainer = block.components.get(MicroblockContainer.class);
    Assertions.assertThat(microblockContainer.get(new Vector3D(0, 0, 0)).get().block.getID()).isEqualTo(TestMicroblockMod.singleMicroblockID);
}
Example 74
Project: vertx-stomp-master  File: AbstractClientIT.java View source code
/**
   * The test is the following:
   * 1. Create a client subscribing to the "box" destination
   * 2. Create another client sending messages to the "box" destination
   * 3. Ensure the the client 1 receives the message.
   */
@Test
public void testRegularConnection() {
    AtomicReference<StompClientConnection> receiver = new AtomicReference<>();
    AtomicReference<StompClientConnection> sender = new AtomicReference<>();
    AtomicReference<Frame> frame = new AtomicReference<>();
    // Step 1.
    StompClient client1 = StompClient.create(vertx, getOptions()).connect( connection -> {
        if (connection.failed()) {
            connection.cause().printStackTrace();
        } else {
            receiver.set(connection.result());
            connection.result().subscribe(getDestination(), frame::set);
        }
    });
    clients.add(client1);
    await().atMost(10, TimeUnit.SECONDS).until(() -> receiver.get() != null);
    // Step 2.
    StompClient client2 = StompClient.create(vertx, getOptions()).connect( connection -> {
        if (connection.failed()) {
            connection.cause().printStackTrace();
        } else {
            sender.set(connection.result());
            connection.result().send(getDestination(), Buffer.buffer("hello from vert.x"));
        }
    });
    clients.add(client2);
    await().atMost(10, TimeUnit.SECONDS).until(() -> sender.get() != null);
    // Step 3.
    await().atMost(10, TimeUnit.SECONDS).until(() -> frame.get() != null);
    assertThat(frame.get().getCommand()).isEqualTo(Frame.Command.MESSAGE);
    assertThat(frame.get().getHeaders()).contains(entry("content-length", "17")).containsKeys("destination", "message-id", "subscription");
    Assertions.assertThat(frame.get().getBodyAsString()).isEqualToIgnoringCase("hello from vert.x");
}
Example 75
Project: assertj-db-master  File: EntryPointsComparison_Test.java View source code
@Test
public void assertions_and_bdd_assertions_should_have_the_same_methods() {
    Method[] thenMethods = findMethodsWithName(BDDAssertions.class, "then");
    Method[] assertThatMethods = findMethodsWithName(Assertions.class, "assertThat");
    assertThat(thenMethods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_METHOD_NAME).containsExactlyInAnyOrder(assertThatMethods);
}
Example 76
Project: beam-master  File: RecordFilterTest.java View source code
@Test
public void shouldFilterOutRecordsBeforeOrAtCheckpoint() {
    given(checkpoint.isBeforeOrAt(record1)).willReturn(false);
    given(checkpoint.isBeforeOrAt(record2)).willReturn(true);
    given(checkpoint.isBeforeOrAt(record3)).willReturn(true);
    given(checkpoint.isBeforeOrAt(record4)).willReturn(false);
    given(checkpoint.isBeforeOrAt(record5)).willReturn(true);
    List<KinesisRecord> records = Lists.newArrayList(record1, record2, record3, record4, record5);
    RecordFilter underTest = new RecordFilter();
    List<KinesisRecord> retainedRecords = underTest.apply(records, checkpoint);
    Assertions.assertThat(retainedRecords).containsOnly(record2, record3, record5);
}
Example 77
Project: denominator-master  File: GeoReadOnlyLiveTest.java View source code
@Test
public void testListRRSs() {
    for (Zone zone : manager.api().zones()) {
        for (ResourceRecordSet<?> geoRRS : geoApi(zone)) {
            assertThat(geoRRS).isValidGeo();
            assertThat(manager.provider().profileToRecordTypes().get("geo")).contains(geoRRS.type());
            Assertions.assertThat(geoApi(zone).iterateByNameAndType(geoRRS.name(), geoRRS.type())).overridingErrorMessage("could not list by name and type: " + geoRRS).isNotEmpty();
            ResourceRecordSet<?> byNameTypeAndQualifier = geoApi(zone).getByNameTypeAndQualifier(geoRRS.name(), geoRRS.type(), geoRRS.qualifier());
            assertThat(byNameTypeAndQualifier).overridingErrorMessage("could not lookup by name, type, and qualifier: " + geoRRS).isNotNull().isEqualTo(geoRRS);
        }
    }
}
Example 78
Project: droolsjbpm-integration-master  File: MarshallingRoundTripCustomClassListTest.java View source code
@Test
public void testJSONTypeInfoTopLevelOnly() {
    Marshaller marshaller = MarshallerFactory.getMarshaller(getCustomClasses(), MarshallingFormat.JSON, getClass().getClassLoader());
    String rawContent = "{\"org.kie.server.api.marshalling.objects.PojoA\": " + "{\"name\": \"A\"," + " \"pojoBList\":" + " [{\"name\": \"B1\"," + "   \"pojoCList\":" + "    [" + "      {\"name\": \"C1\"}, " + "      {\"name\": \"C2\"}" + "    ]" + "  }," + "  {\"name\": \"B2\"," + "   \"pojoCList\":" + "    [" + "     {\"name\": \"C3\"}" + "    ]" + "  }" + " ]," + " \"stringList\":" + "  [\"Hello\", \"Bye\"]" + "}}";
    Object unmarshalledObject = marshaller.unmarshall(rawContent, PojoA.class);
    Assertions.assertThat(unmarshalledObject).isEqualTo(createTestObject());
}
Example 79
Project: funktion-connectors-master  File: FunktionTestSupport.java View source code
protected Funktion loadTestYaml() throws IOException {
    String path = getClassNameAsPath() + "-" + getTestMethodName() + ".yml";
    LOG.info("Loading Funktion flows from classpath at: " + path);
    URL resource = getClass().getClassLoader().getResource(path);
    Assertions.assertThat(resource).describedAs("Could not find " + path + " on the classpath!").isNotNull();
    return Funktions.loadFromURL(resource);
}
Example 80
Project: hammock-master  File: FlywayTest.java View source code
@Test
public void shouldApplyMigrations() throws Exception {
    Connection connection = testds.getConnection();
    try (PreparedStatement preparedStatement = connection.prepareStatement("select count(*) from \"schema_version\"");
        ResultSet rs = preparedStatement.executeQuery()) {
        rs.next();
        int anInt = rs.getInt(1);
        Assertions.assertThat(anInt).isEqualTo(1);
    }
}
Example 81
Project: jmxtrans-master  File: LibratoWriterTest.java View source code
@Test
public void httpUserAgentContainsAppropriateInformation() throws MalformedURLException {
    LibratoWriter writer = new LibratoWriter(ImmutableList.<String>of(), false, false, new URL(LibratoWriter.DEFAULT_LIBRATO_API_URL), 1000, "username", "token", null, null, ImmutableMap.<String, Object>of());
    Assertions.assertThat(writer.httpUserAgent).startsWith("jmxtrans-standalone/").contains(System.getProperty("os.name")).contains(System.getProperty("os.arch")).contains(System.getProperty("os.version")).contains(System.getProperty("java.vm.name")).contains(System.getProperty("java.version"));
}
Example 82
Project: kie-wb-distributions-master  File: JobIntegrationTest.java View source code
@Test
public void testDelete() {
    JobRequest jobRequest = cloneRepositoryAsync("deleteJobRepository");
    JobResult jobResult = client.getJob(jobRequest.getJobId());
    Assertions.assertThat(jobResult.getStatus()).isNotEqualTo(JobStatus.GONE);
    jobResult = client.deleteJob(jobRequest.getJobId());
    Assertions.assertThat(jobResult.getStatus()).isEqualTo(JobStatus.GONE);
    jobResult = client.getJob(jobRequest.getJobId());
    Assertions.assertThat(jobResult.getStatus()).isEqualTo(JobStatus.GONE);
}
Example 83
Project: lambdamatic-project-master  File: MongoUpdateTest.java View source code
@Test
@UsingDataSet(loadStrategy = LoadStrategyEnum.CLEAN_INSERT)
@ShouldMatchDataSet()
public void shouldReplaceDocument() {
    // given
    final BlogEntry blogEntry = blogEntryCollection.filter( e -> e.id.equals("1") && e.authorName.equals("jdoe")).first();
    Assertions.assertThat(blogEntry).isNotNull();
    blogEntry.setAuthorName("John Doe");
    blogEntry.setContent("Updating documents...");
    final GregorianCalendar gregorianCalendar = new GregorianCalendar(2015, 05, 07, 16, 40, 0);
    gregorianCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
    final Date publishDate = gregorianCalendar.getTime();
    blogEntry.setPublishDate(publishDate);
    final List<String> tags = Arrays.asList("doc", "update");
    blogEntry.setTags(tags);
    // when
    blogEntryCollection.replace(blogEntry);
// then... let NoSqlUnit perform post-update assertions using the file given in the
// @ShouldMatchDataSet
// annotation
}
Example 84
Project: OpenIDM-master  File: ClusterManagerTest.java View source code
@Test
public void testReadEntry() throws ResourceException, Exception {
    final ReadRequest readRequest = Requests.newReadRequest("test-node");
    final ResourceResponse resource = clusterHandler.handleRead(new RootContext(), readRequest).get();
    // Test basic instance fields
    Assertions.assertThat(resource.getContent().get("state").asString()).isEqualTo("running");
    Assertions.assertThat(resource.getContent().get("instanceId").asString()).isEqualTo("test-node");
    Assertions.assertThat(resource.getContent().get("startup").asString()).isNotNull();
    Assertions.assertThat(resource.getContent().get("shutdown").asString()).isEqualTo("");
}
Example 85
Project: pojobuilder-master  File: JavaProjectAssert.java View source code
public JavaProjectAssert generatedSameSourceAs(Class<?> target) {
    String actualSource = null;
    String expectedSource = null;
    try {
        actualSource = TestBase.getContent(actual.findGeneratedSource(target.getName()));
        expectedSource = base.loadResourceFromFilesystem(TestBase.TESTDATA_DIRECTORY, base.getSourceFilename(target.getName()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    Assertions.assertThat(actualSource).isEqualTo(expectedSource);
    return this;
}
Example 86
Project: rewrite-master  File: ErrorPageFormTest.java View source code
@Test
public void testNavigateWithSimpleString() throws Exception {
    HttpAction<HttpGet> client = get("/missingresource");
    assertThat(client.getCurrentURL(), endsWith("/missingresource"));
    Assert.assertEquals(404, client.getResponse().getStatusLine().getStatusCode());
    String content = client.getResponseContent();
    Assertions.assertThat(content).matches("(?s).*action=\"" + client.getContextPath() + "/faces/error\\.xhtml.*");
}
Example 87
Project: spring-cloud-consul-master  File: ConsulAutoServiceRegistrationDefaultCheckTests.java View source code
@Test
public void contextLoads() {
    assertThat(properties.getHealthCheckCriticalTimeout()).isEqualTo("30m");
    assertThat(properties.getHealthCheckInterval()).isEqualTo("19s");
    assertThat(properties.getHealthCheckTimeout()).isEqualTo("12s");
// I'm unable to find a way to query consul to see the configuration of the health check
// so for now, just sending the new healthCheckCriticalTimeout and having consul accept
// it is going to have to suffice
//final Response<List<com.ecwid.consul.v1.health.model.Check>> checksForService = consul.getHealthChecksForService("myTestServiceDefaultChecks", QueryParams.DEFAULT);
//final List<com.ecwid.consul.v1.health.model.Check> checkList = checksForService.getValue();
//final Response<Map<String, Check>> response2 = consul.getAgentChecks();
//final Map<String, Check> checks = response2.getValue();
//final Check check = checks.get("myTestServiceDefaultChecks");
//Assertions.assertThat(check).isNotNull();
}
Example 88
Project: spring-cloud-stream-master  File: SourceBindingWithGlobalPropertiesTest.java View source code
@SuppressWarnings("unchecked")
@Test
public void testGlobalPropertiesSet() {
    BindingProperties bindingProperties = channelBindingServiceProperties.getBindingProperties(Source.OUTPUT);
    Assertions.assertThat(bindingProperties.getContentType()).isEqualTo("application/json");
    Assertions.assertThat(bindingProperties.getDestination()).isEqualTo("ticktock");
    Assertions.assertThat(bindingProperties.getProducer().getRequiredGroups()).containsExactly("someGroup");
    Assertions.assertThat(bindingProperties.getProducer().getHeaderMode()).isEqualTo(HeaderMode.raw);
}
Example 89
Project: camunda-engine-dmn-master  File: ParseDecisionTest.java View source code
@Test
public void shouldFailIfDecisionKeyIsUnknown() {
    try {
        parseDecisionFromFile("unknownDecision", NO_INPUT_DMN);
        failBecauseExceptionWasNotThrown(DmnTransformException.class);
    } catch (DmnTransformException e) {
        Assertions.assertThat(e).hasMessageStartingWith("DMN-01001").hasMessageContaining("Unable to find decision").hasMessageContaining("unknownDecision");
    }
}
Example 90
Project: parkandrideAPI-master  File: CapacityPricingValidatorTest.java View source code
@Test
public void hours_can_overlap_for_different_usages() {
    Pricing a = pricing(CAR, PARK_AND_RIDE, BUSINESS_DAY, 7, 17);
    Pricing b = pricing(CAR, COMMERCIAL, BUSINESS_DAY, 8, 18);
    List<Violation> violations = new ArrayList<>();
    CapacityPricingValidator.validateAndNormalizeCustomPricing(maxCapacities(a, b), ImmutableList.of(a, b), ImmutableList.of(), violations);
    Assertions.assertThat(violations).isEmpty();
}
Example 91
Project: rdp4j-master  File: AcceptanceTest.java View source code
@Test
public void enableParallelDirectoryPolling() throws Exception {
    // given 
    Mockito.when(directoryMock.listFiles()).thenReturn(list());
    // when
    dp = builder.addPolledDirectory(directoryMock).enableParallelPollingOfDirectories().setPollingInterval(10, TimeUnit.MILLISECONDS).start();
    // then
    Assertions.assertThat(dp.isParallelDirectoryPollingEnabled()).isTrue();
}
Example 92
Project: bonita-web-master  File: ArchivedUserTaskContextResourceTest.java View source code
@Test
public void should_getArchivedTaskIDParameter_throws_an_exception_when_archived_task_id_parameter_is_null() throws Exception {
    //given
    doReturn(null).when(archviedTaskContextResource).getAttribute(ArchivedUserTaskContextResource.ARCHIVED_TASK_ID);
    try {
        //when
        archviedTaskContextResource.getArchivedTaskIdParameter();
    } catch (final Exception e) {
        Assertions.assertThat(e).isInstanceOf(APIException.class);
        Assertions.assertThat(e.getMessage()).isEqualTo("Attribute '" + ArchivedUserTaskContextResource.ARCHIVED_TASK_ID + "' is mandatory in order to get the archived task context");
    }
}
Example 93
Project: catch-exception-master  File: BDDCatchExceptionTest.java View source code
@SuppressWarnings("rawtypes")
@Test
public void testThenFromAssertJ() {
    // given an empty list
    List myList = new ArrayList();
    // when we try to get first element of the list
    when(myList).get(1);
    // then we expect an IndexOutOfBoundsException
    //
    Assertions.assertThat(caughtException()).isInstanceOf(//
    IndexOutOfBoundsException.class).hasMessage(//
    "Index: 1, Size: 0").hasNoCause();
}
Example 94
Project: drools-wb-master  File: PlainTextAssetWithPackagePropertyExporterTest.java View source code
@Test
public // BZ-1319568
void testExportSingleStandaloneRule() {
    String technicalRule = "dialect \"mvel\"\n" + "agenda-group \"RULE GROUP myGroup\"\n" + "when\n" + "    list : ArrayList( )\n" + "then\n" + "    list.add(1)\n" + "    drools.setFocus(\"some-rule-group\");";
    for (String assetType : Arrays.asList("drl", "dslr")) {
        AssetItem assetItem = createAssetItemMock(technicalRule, assetType);
        Module jcrModule = Mockito.mock(Module.class);
        ExportContext exportContext = Mockito.mock(ExportContext.class);
        Mockito.when(exportContext.getJcrAssetItem()).thenReturn(assetItem);
        Mockito.when(exportContext.getJcrModule()).thenReturn(jcrModule);
        PlainTextAsset asset = exporter.export(exportContext);
        String expectedContentAfterMigration = "rule \"dummy-technical-rule\"\n\n" + "dialect \"mvel\"\n" + "agenda-group \"RULE GROUP myGroup\"\n" + "when\n" + "    list : ArrayList( )\n" + "then\n" + "    list.add(1)\n" + "    drools.setFocus(\"some-rule-group\");\n\n" + "end";
        Assertions.assertThat(asset.getContent()).isEqualTo(expectedContentAfterMigration);
    }
}
Example 95
Project: easybatch-framework-master  File: DefaultJobReportFormatterTest.java View source code
@Test
public void testFormatReport() throws Exception {
    String expectedReport = "Job Report:" + LINE_SEPARATOR + "===========" + LINE_SEPARATOR + "Name: job" + LINE_SEPARATOR + "Status: COMPLETED" + LINE_SEPARATOR + "Parameters:" + LINE_SEPARATOR + "\tBatch size = 100" + LINE_SEPARATOR + "\tError threshold = N/A" + LINE_SEPARATOR + "\tJmx monitoring = false" + LINE_SEPARATOR + "Metrics:" + LINE_SEPARATOR + "\tStart time = 2015-01-01 01:00:00" + LINE_SEPARATOR + "\tEnd time = 2015-01-01 01:00:10" + LINE_SEPARATOR + "\tDuration = 0hr 0min 10sec 0ms" + LINE_SEPARATOR + "\tRead count = 0" + LINE_SEPARATOR + "\tWrite count = 0" + LINE_SEPARATOR + "\tFiltered count = 0" + LINE_SEPARATOR + "\tError count = 0" + LINE_SEPARATOR + "\tnbFoos = 1" + LINE_SEPARATOR + "System properties:" + LINE_SEPARATOR + "\tsysprop1 = foo" + LINE_SEPARATOR + "\tsysprop2 = bar";
    String formattedReport = reportFormatter.formatReport(report);
    Assertions.assertThat(formattedReport).isEqualTo(expectedReport);
}
Example 96
Project: fuchsia-master  File: FuchsiaHelper.java View source code
/**
     * Create an instance with the given factory and properties.
     *
     * @param factory
     * @param properties
     * @return
     */
public static ComponentInstance createInstance(final Factory factory, final Dictionary<String, Object> properties) {
    ComponentInstance instance = null;
    // Create an instance
    try {
        instance = factory.createComponentInstance(properties);
    } catch (Exception e) {
        Assertions.fail("Creation of instance failed (" + factory + ", " + properties + ").", e);
    }
    return instance;
}
Example 97
Project: geode-master  File: AbstractRegionEntryTest.java View source code
@Test
public void whenMakeTombstoneHasSetValueThatThrowsExceptionDoesNotChangeValueToTombstone() throws RegionClearedException {
    LocalRegion lr = mock(LocalRegion.class);
    RegionVersionVector<?> rvv = mock(RegionVersionVector.class);
    when(lr.getVersionVector()).thenReturn(rvv);
    VersionTag<?> vt = mock(VersionTag.class);
    Object value = "value";
    AbstractRegionEntry re = new TestableRegionEntry(lr, value);
    assertEquals(value, re.getValueField());
    Assertions.assertThatThrownBy(() -> re.makeTombstone(lr, vt)).isInstanceOf(RuntimeException.class).hasMessage("throw exception on setValue(TOMBSTONE)");
    assertEquals(Token.REMOVED_PHASE2, re.getValueField());
}
Example 98
Project: magenta-master  File: DataDomainAssert.java View source code
public <X> InnerDataSetAssert<X> theDataSet(Class<X> type) {
    DataSet<X> dataset = actual.dataset(type);
    if (dataset != null) {
        // validating coherence
        DataKey<X> key = DataKey.makeDefault(type);
        Assertions.assertThat(actual.datasetKeys()).overridingErrorMessage("The key<%s>  is missing from this data domain dataset keys.", key).contains(key);
        Assertions.assertThat(actual.datasets()).overridingErrorMessage("No dataset found for type <%s> in this domain dataset list", type).contains(dataset);
    }
    return new InnerDataSetAssert<X>(dataset);
}
Example 99
Project: mybatis-3-master  File: XmlMapperTest.java View source code
@Test
public void applyDefaultValueOnXmlMapper() throws IOException {
    Properties props = new Properties();
    props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "true");
    Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/global_variables_defaults/mybatis-config.xml");
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, props);
    Configuration configuration = factory.getConfiguration();
    configuration.addMapper(XmlMapper.class);
    SupportClasses.CustomCache cache = SupportClasses.Utils.unwrap(configuration.getCache(XmlMapper.class.getName()));
    Assertions.assertThat(cache.getName()).isEqualTo("default");
    SqlSession sqlSession = factory.openSession();
    try {
        XmlMapper mapper = sqlSession.getMapper(XmlMapper.class);
        Assertions.assertThat(mapper.ping()).isEqualTo("Hello");
        Assertions.assertThat(mapper.selectOne()).isEqualTo("1");
        Assertions.assertThat(mapper.selectFromVariable()).isEqualTo("9999");
    } finally {
        sqlSession.close();
    }
}
Example 100
Project: smartsprites-master  File: MessageListAssertion.java View source code
/**
     * Asserts that the current message list contains (at least) the specified messages.
     */
public MessageListAssertion contains(Message... messages) {
    final Set<Message> toCheck = Sets.newHashSet(messages);
    for (int i = 0; i < actual.size(); i++) {
        for (Iterator<Message> it = toCheck.iterator(); it.hasNext(); ) {
            final Message message = it.next();
            try {
                org.carrot2.labs.test.Assertions.assertThat(actual.get(i)).as("message[" + i + "]").isEquivalentTo(message);
                it.remove();
            } catch (AssertionError e) {
            }
        }
    }
    if (!toCheck.isEmpty()) {
        Fail.fail("Message list did not contain " + toCheck.size() + " of the required messages");
    }
    return this;
}
Example 101
Project: wb-master  File: PlainTextAssetWithPackagePropertyExporterTest.java View source code
@Test
public // BZ-1319568
void testExportSingleStandaloneRule() {
    String technicalRule = "dialect \"mvel\"\n" + "agenda-group \"RULE GROUP myGroup\"\n" + "when\n" + "    list : ArrayList( )\n" + "then\n" + "    list.add(1)\n" + "    drools.setFocus(\"some-rule-group\");";
    for (String assetType : Arrays.asList("drl", "dslr")) {
        AssetItem assetItem = createAssetItemMock(technicalRule, assetType);
        Module jcrModule = Mockito.mock(Module.class);
        ExportContext exportContext = Mockito.mock(ExportContext.class);
        Mockito.when(exportContext.getJcrAssetItem()).thenReturn(assetItem);
        Mockito.when(exportContext.getJcrModule()).thenReturn(jcrModule);
        PlainTextAsset asset = exporter.export(exportContext);
        String expectedContentAfterMigration = "rule \"dummy-technical-rule\"\n\n" + "dialect \"mvel\"\n" + "agenda-group \"RULE GROUP myGroup\"\n" + "when\n" + "    list : ArrayList( )\n" + "then\n" + "    list.add(1)\n" + "    drools.setFocus(\"some-rule-group\");\n\n" + "end";
        Assertions.assertThat(asset.getContent()).isEqualTo(expectedContentAfterMigration);
    }
}