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

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

Example 1
Project: Red-master  File: TagsCompositeTest.java View source code
private static Condition<? super TagsComposite> tagControls(final String... tags) {
    return new Condition<TagsComposite>() {

        @Override
        public boolean matches(final TagsComposite composite) {
            final Iterable<Composite> tagComposites = filter(newArrayList(composite.getChildren()), Composite.class);
            final Set<String> tagLabels = new HashSet<>();
            for (final Composite tagComposite : tagComposites) {
                final Iterable<CLabel> labels = filter(newArrayList(tagComposite.getChildren()), CLabel.class);
                final CLabel label = getFirst(labels, null);
                tagLabels.add(label.getText());
            }
            return newHashSet(tags).equals(tagLabels);
        }
    };
}
Example 2
Project: ArchUnit-master  File: JavaClassTest.java View source code
private Condition<JavaCodeUnit> equivalentCodeUnit(final Class<?> owner, final String methodName, final Class<?> paramType) {
    return new Condition<JavaCodeUnit>() {

        @Override
        public boolean matches(JavaCodeUnit value) {
            return value.getOwner().isEquivalentTo(owner) && value.getName().equals(methodName) && value.getParameters().getNames().equals(ImmutableList.of(paramType.getName()));
        }
    };
}
Example 3
Project: jdeps-maven-plugin-master  File: XmlRuleTest.java View source code
@Test
public void toXmlLines_validIndent_indentIsUsed() throws Exception {
    List<String> lines = rule.toXmlLines("\t").collect(toList());
    Condition<String> startingWithIndentUnlessOuterTagLines = new Condition<>( line -> line.startsWith("\t") || line.equals("<xmlRule>") || line.equals("</xmlRule>"), "Start with indent.");
    assertThat(lines).are(startingWithIndentUnlessOuterTagLines);
}
Example 4
Project: assertj-core-master  File: Iterables.java View source code
/**
   * Assert that each element of given {@code Iterable} satisfies the given condition.
   *
   * @param info contains information about the assertion.
   * @param actual the given {@code Iterable}.
   * @param condition the given {@code Condition}.
   * @throws NullPointerException if the given condition is {@code null}.
   * @throws AssertionError if an element cannot be cast to T.
   * @throws AssertionError if one or more elements do not satisfy the given condition.
   */
public <T> void assertAre(AssertionInfo info, Iterable<? extends T> actual, Condition<? super T> condition) {
    assertNotNull(info, actual);
    conditions.assertIsNotNull(condition);
    try {
        List<T> notSatisfiesCondition = notSatisfyingCondition(actual, condition);
        if (!notSatisfiesCondition.isEmpty())
            throw failures.failure(info, elementsShouldBe(actual, notSatisfiesCondition, condition));
    } catch (ClassCastException e) {
        throw failures.failure(info, shouldBeSameGenericBetweenIterableAndCondition(actual, condition));
    }
}
Example 5
Project: fabric8-devops-master  File: TaigaKubernetesTest.java View source code
@Test
public void testtaiga() throws Exception {
    assertThat(client).replicationControllers().haveAtLeast(1, new Condition<ReplicationController>() {

        @Override
        public boolean matches(ReplicationController replicationController) {
            return getName(replicationController).startsWith("taiga");
        }
    });
    assertThat(client).pods().runningStatus().filterNamespace(session.getNamespace()).hasSize(1);
}
Example 6
Project: java-assertjext-master  File: Conditions.java View source code
public static <T> Condition<T> matchedBy(final Matcher<T> matcher) {
    return new Condition<T>() {

        @Override
        public boolean matches(final T t) {
            final boolean matches = matcher.matches(t);
            if (!(matches)) {
                String value = valueOf(t);
                final String reason = reason();
                as(String.format("not matched as %s is not %s", value, reason));
            }
            return matches;
        }

        private String reason() {
            final StringDescription reasonDescription = new StringDescription();
            matcher.describeTo(reasonDescription);
            return reasonDescription.toString();
        }

        private String valueOf(final T t) {
            String value = null;
            if (matcher instanceof TypeSafeMatcher) {
                final TypeSafeMatcher typeSafeMatcher = (TypeSafeMatcher) matcher;
                final StringDescription valueDescription = new StringDescription();
                typeSafeMatcher.describeMismatch(t, valueDescription);
                final String valueDescr = valueDescription.toString();
                if (valueDescr.startsWith("was ")) {
                    // most seem to
                    value = valueDescr.substring(4);
                }
            }
            if (value == null) {
                value = "<" + t + ">";
            }
            return value;
        }
    };
}
Example 7
Project: spring-boot-master  File: WebMvcAutoConfigurationTests.java View source code
private void testLogResolvedExceptionCustomization(final boolean expected) {
    HandlerExceptionResolver exceptionResolver = this.context.getBean(HandlerExceptionResolver.class);
    assertThat(exceptionResolver).isInstanceOf(HandlerExceptionResolverComposite.class);
    List<HandlerExceptionResolver> delegates = ((HandlerExceptionResolverComposite) exceptionResolver).getExceptionResolvers();
    for (HandlerExceptionResolver delegate : delegates) {
        if (delegate instanceof AbstractHandlerMethodAdapter) {
            assertThat(new DirectFieldAccessor(delegate).getPropertyValue("warnLogger")).is(new Condition<Object>() {

                @Override
                public boolean matches(Object value) {
                    return (expected ? value != null : value == null);
                }
            });
        }
    }
}
Example 8
Project: typedbundle-master  File: SparseArrayAssert.java View source code
@Override
public SparseArrayAssert<E> isEqualTo(Object expected) {
    Objects.instance().assertHasSameClassAs(info, actual, expected);
    final SparseArray<E> expectedSparseArray = (SparseArray<E>) expected;
    assertThat(actual).is(new Condition<SparseArray<E>>() {

        @Override
        public boolean matches(SparseArray<E> eSparseArray) {
            return isEqualTo(eSparseArray, expectedSparseArray);
        }
    });
    return this;
}
Example 9
Project: armeria-master  File: HBaseClientCompatibilityTest.java View source code
/**
     * Ensure Armeria's dependencies do not cause a trouble with hbase-shaded-client.
     *
     * @see <a href="https://issues.apache.org/jira/browse/HBASE-14963">HBASE-14963</a>
     */
@Test(expected = NotAllMetaRegionsOnlineException.class)
public void testGuavaConflict() throws Exception {
    // Make sure Armeria is available in the class path.
    assertThat(Version.identify(Server.class.getClassLoader())).isNotNull();
    // Make sure newer Guava is available in the class path.
    assertThat(Stopwatch.class.getDeclaredConstructor().getModifiers()).is(new Condition<>( value -> !Modifier.isPublic(value), "Recent Guava Stopwatch should have non-public default constructor."));
    final MetaTableLocator locator = new MetaTableLocator();
    final ZooKeeperWatcher zkw = mock(ZooKeeperWatcher.class);
    final RecoverableZooKeeper zk = mock(RecoverableZooKeeper.class);
    when(zkw.getRecoverableZooKeeper()).thenReturn(zk);
    when(zk.exists(any(), any())).thenReturn(new Stat(0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0));
    locator.waitMetaRegionLocation(zkw, 100);
}
Example 10
Project: arquillian-extension-drone-master  File: GitHubLastUpdateCacheTest.java View source code
@Test
public void should_create_release_cache_folder() throws Exception {
    // given
    final File customCacheFolder = new File(tmpFolder, "custom-cache-folder");
    final ExternalBinary externalBinary = new ExternalBinary("1.0.0.Final", "https://api.github.com/repos/MatousJobanek/my-test-repository/releases/assets/2857399");
    final String releasesId = "4968399";
    gitHubLastUpdateCache = new GitHubLastUpdateCache(customCacheFolder);
    // when
    gitHubLastUpdateCache.store(externalBinary, releasesId, ZonedDateTime.now());
    // then
    final SoftAssertions softly = new SoftAssertions();
    softly.assertThat(customCacheFolder).exists().isDirectory();
    softly.assertThat(new File(customCacheFolder, "gh.cache.4968399.json")).isFile().has(new Condition<File>() {

        @Override
        public boolean matches(File value) {
            return value.length() > 0;
        }
    });
    softly.assertAll();
}
Example 11
Project: constellio-master  File: TaxonomiesSearchServices_LinkableTreesAcceptTest.java View source code
private Condition<? super LinkableTaxonomySearchResponse> numFoundAndListSize(final int expectedCount) {
    return new Condition<LinkableTaxonomySearchResponse>() {

        @Override
        public boolean matches(LinkableTaxonomySearchResponse value) {
            assertThat(value.getNumFound()).describedAs("NumFound").isEqualTo(expectedCount);
            assertThat(value.getRecords().size()).describedAs("records list size").isEqualTo(expectedCount);
            return true;
        }
    };
}
Example 12
Project: fabric8-master  File: Conditions.java View source code
public static <T extends HasMetadata> Condition<T> hasLabel(final String key, final String value) {
    return new Condition<T>() {

        @Override
        public String toString() {
            return "hasLabel(" + key + " = " + value + ")";
        }

        @Override
        public boolean matches(T resource) {
            return matchesLabel(resource.getMetadata().getLabels(), key, value);
        }
    };
}
Example 13
Project: javaee7-samples-master  File: MyResourceTest.java View source code
@BeforeClass
public static void generateSampleFile() throws IOException {
    tempFile = File.createTempFile("javaee7samples", ".png");
    // fill the file with 1KB of content
    try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
        for (int i = 0; i < 1000; i++) {
            outputStream.write(0);
        }
    }
    assertThat(tempFile).canRead().has(new Condition<File>() {

        @Override
        public boolean matches(File tempFile) {
            return tempFile.length() == 1000;
        }
    });
}
Example 14
Project: lambdamatic-project-master  File: MongoQueryTest.java View source code
@Test
@UsingDataSet(loadStrategy = LoadStrategyEnum.CLEAN_INSERT)
public void shouldFindOneFoo() throws IOException {
    // when
    final BlogEntry blogEntry = blogEntryCollection.filter( e -> e.id.equals("1") && e.authorName.equals("jdoe")).first();
    // then
    assertThat(blogEntry).isNotNull().has(new Condition<BlogEntry>() {

        @Override
        public boolean matches(final BlogEntry blogEntry) {
            return blogEntry.getAuthorName().equals("jdoe");
        }
    });
}
Example 15
Project: mockito-master  File: VerificationListenerCallBackTest.java View source code
private static Condition<RememberingListener> notifiedFor(final Object mock, final VerificationMode mode, final Method wantedMethod) {
    return new Condition<RememberingListener>() {

        public boolean matches(RememberingListener listener) {
            assertThat(listener.mock).isEqualTo(mock);
            assertThat(listener.mode).isEqualTo(mode);
            assertThat(listener.data.getTarget().getInvocation().getMethod()).isEqualTo(wantedMethod);
            return true;
        }
    };
}
Example 16
Project: rxassertions-master  File: BlockingObservableAssertTests.java View source code
@Test
public void withConditionsMatchingEachItem_ShoulPass() {
    List<String> expected = Arrays.asList("These", "are", "Expected", "Values");
    BlockingObservable<String> obs = Observable.from(expected).toBlocking();
    Condition<String> atLeastTwoChars = new Condition<String>() {

        @Override
        public boolean matches(String value) {
            return value.length() >= 2;
        }
    };
    Condition<String> noMoreThanTenChars = new Condition<String>() {

        @Override
        public boolean matches(String value) {
            return value.length() <= 10;
        }
    };
    new BlockingObservableAssert<>(obs).eachItemMatches(atLeastTwoChars).eachItemMatches(noMoreThanTenChars);
}
Example 17
Project: sonarqube-master  File: IssueModeAndReportsMediumTest.java View source code
@Test
public void testIssueTracking() throws Exception {
    File projectDir = copyProject("/mediumtest/xoo/sample");
    TaskResult result = tester.newScanTask(new File(projectDir, "sonar-project.properties")).start();
    int newIssues = 0;
    int openIssues = 0;
    int resolvedIssue = 0;
    for (TrackedIssue issue : result.trackedIssues()) {
        System.out.println(issue.getMessage() + " " + issue.key() + " " + issue.getRuleKey() + " " + issue.isNew() + " " + issue.resolution() + " " + issue.componentKey() + " " + issue.startLine());
        if (issue.isNew()) {
            newIssues++;
        } else if (issue.resolution() != null) {
            resolvedIssue++;
        } else {
            openIssues++;
        }
    }
    System.out.println("new: " + newIssues + " open: " + openIssues + " resolved " + resolvedIssue);
    assertThat(newIssues).isEqualTo(16);
    assertThat(openIssues).isEqualTo(2);
    assertThat(resolvedIssue).isEqualTo(1);
    // progress report
    String logs = StringUtils.join(logTester.logs(LoggerLevel.INFO), "\n");
    assertThat(logs).contains("Performing issue tracking");
    assertThat(logs).contains("6/6 components tracked");
    // assert that original fields of a matched issue are kept
    assertThat(result.trackedIssues()).haveExactly(1, new Condition<TrackedIssue>() {

        @Override
        public boolean matches(TrackedIssue value) {
            return value.isNew() == false && "resolved-on-project".equals(value.key()) && "OPEN".equals(value.status()) && new Date(date("14/03/2004")).equals(value.creationDate());
        }
    });
}
Example 18
Project: TeamCity.SonarQubePlugin-master  File: SQSManagerProjectFeaturesTest.java View source code
public void test_single_child() {
    final List<SProjectFeatureDescriptor> features = Collections.singletonList(mockProjectFeature("id", BaseSQSInfo.NAME, "InChild"));
    when(myProject.getOwnFeaturesOfType(SQSManagerProjectFeatures.PROJECT_FEATURE_TYPE)).thenReturn(features);
    when(myProject.getOwnFeatures()).thenReturn(features);
    when(myProject.getAvailableFeatures()).thenReturn(features);
    when(myProject.getAvailableFeaturesOfType(SQSManagerProjectFeatures.PROJECT_FEATURE_TYPE)).thenReturn(features);
    then(mySqsManagerProjectFeatures.getAvailableServers(myProject)).hasSize(1);
    then(mySqsManagerProjectFeatures.getAvailableServers(myRoot)).isEmpty();
    then(mySqsManagerProjectFeatures.getOwnAvailableServers(myProject)).hasSize(1);
    then(mySqsManagerProjectFeatures.getOwnAvailableServers(myRoot)).isEmpty();
    then(mySqsManagerProjectFeatures.getServer(myProject, "id")).isNotNull().is(new Condition<>( sqsInfo -> "InChild".equals(sqsInfo.getName()), "having InChild name"));
    then(mySqsManagerProjectFeatures.getOwnServer(myProject, "id")).isNotNull().is(new Condition<>( sqsInfo -> "InChild".equals(sqsInfo.getName()), "having InChild name"));
}
Example 19
Project: wisdom-master  File: BundleModelTest.java View source code
@Test
public void testBundles() throws Exception {
    final Bundle bundle1 = mock(Bundle.class);
    when(bundle1.getBundleId()).thenReturn(1l);
    final Bundle bundle2 = mock(Bundle.class);
    when(bundle2.getBundleId()).thenReturn(2l);
    BundleContext bc = mock(BundleContext.class);
    when(bc.getBundles()).thenReturn(new Bundle[] { bundle1, bundle2 });
    assertThat(BundleModel.bundles(bc)).have(new Condition<BundleModel>() {

        @Override
        public boolean matches(BundleModel model) {
            return model.getId() == bundle1.getBundleId() || model.getId() == bundle2.getBundleId();
        }
    }).hasSize(2);
}
Example 20
Project: cassandra-mesos-master  File: AbstractSchedulerTest.java View source code
static Condition<? super CassandraFrameworkProtos.HealthCheckDetails> operationMode(final String operationMode) {
    return new Condition<CassandraFrameworkProtos.HealthCheckDetails>() {

        @Override
        public boolean matches(final CassandraFrameworkProtos.HealthCheckDetails healthCheckDetails) {
            return healthCheckDetails != null && healthCheckDetails.getInfo().getOperationMode().equals(operationMode);
        }
    };
}
Example 21
Project: jongo-master  File: CommandTest.java View source code
@Test
public void canRunAGeoNearCommand() throws Exception {
    MongoCollection safeCollection = collection.withWriteConcern(WriteConcern.SAFE);
    safeCollection.insert("{loc:{lat:48.690833,lng:9.140556}, name:'Paris'}");
    safeCollection.ensureIndex("{loc:'2d'}");
    List<Location> locations = jongo.runCommand("{ geoNear : 'friends', near : [48.690,9.140], spherical: true}").throwOnError().field("results").as(Location.class);
    assertThat(locations.size()).isEqualTo(1);
    assertThat(locations.get(0).dis).has(new Condition<Double>() {

        @Override
        public boolean matches(Double value) {
            return value instanceof Double && value > 1.7E-5 && value < 1.8E-5;
        }
    });
    assertThat(locations.get(0).getName()).isEqualTo("Paris");
}
Example 22
Project: reactor-core-master  File: WorkQueueProcessorTest.java View source code
@Test
public void testDefaultRequestTaskThreadName() {
    String mainName = "workQueueProcessorRequestTask";
    String expectedName = mainName + "[request-task]";
    WorkQueueProcessor<Object> processor = WorkQueueProcessor.create(mainName, 8);
    processor.requestTask(Operators.cancelledSubscription());
    Thread[] threads = new Thread[Thread.activeCount()];
    Thread.enumerate(threads);
    //cleanup to avoid visibility in other tests
    processor.forceShutdown();
    Condition<Thread> defaultRequestTaskThread = new Condition<>( thread -> expectedName.equals(thread.getName()), "a thread named \"%s\"", expectedName);
    Assertions.assertThat(threads).haveExactly(1, defaultRequestTaskThread);
}
Example 23
Project: bonita-web-master  File: AuthenticationFilterTest.java View source code
@Test
public void testCompileSimplePattern() throws Exception {
    final String patternToCompile = "test";
    assertThat(authenticationFilter.compilePattern(patternToCompile)).isNotNull().has(new Condition<Pattern>() {

        @Override
        public boolean matches(final Pattern pattern) {
            return pattern.pattern().equalsIgnoreCase(patternToCompile);
        }
    });
}
Example 24
Project: brainslug-master  File: TaskNodeExecutorTest.java View source code
@Test
public void shouldPropagateException() {
    FlowDefinition serviceCallFlow = new FlowBuilder() {

        @Override
        public void define() {
            start(event(id(START))).execute(task(id(TASK), new SimpleTask() {

                @Override
                public void execute(ExecutionContext context) {
                    throw new RuntimeException("error");
                }
            })).end(event(id(END)));
        }
    }.getDefinition();
    TaskNodeExecutor taskNodeExecutor = createTaskNodeExecutor();
    BrainslugExecutionContext context = new BrainslugExecutionContext(instanceMock(serviceCallFlow.getId()), new Trigger().definitionId(serviceCallFlow.getId()).nodeId(id(TASK)).instanceId(id("instance")), registryWithServiceMock());
    FlowNodeExecutionResult result = taskNodeExecutor.execute(serviceCallFlow.getNode(id(TASK), TaskDefinition.class), context);
    assertThat(result.isFailed()).isTrue();
    assertThat(result.getException()).isNotNull().has(new Condition<Option<Exception>>() {

        @Override
        public boolean matches(Option<Exception> exceptionOption) {
            return exceptionOption.get().getMessage().equals("error");
        }
    });
}
Example 25
Project: emfjson-jackson-master  File: ModelTest.java View source code
@Test
public void testLoadDynamicEnums() {
    Resource model = resourceSet.getResource(URI.createURI("http://emfjson/dynamic/model"), true);
    EPackage p = (EPackage) model.getContents().get(0);
    EClassifier kind = p.getEClassifier("Kind");
    assertThat(kind).isInstanceOf(EEnum.class);
    EEnum kindEnum = (EEnum) kind;
    EList<EEnumLiteral> literals = kindEnum.getELiterals();
    assertThat(literals).doesNotContainNull().hasSize(2).have(new Condition<EEnumLiteral>() {

        @Override
        public boolean matches(EEnumLiteral value) {
            return value.getName() != null;
        }
    });
    assertThat(extractProperty("name").from(literals)).containsExactly("e1", "e2");
    assertThat(extractProperty("literal").from(literals)).containsExactly("e1", "E2");
}
Example 26
Project: konik-master  File: RowToInvoiceConverterTest.java View source code
private Condition<TradeParty> equalToRowTradeParty(final Row.TradeParty rowTradeParty) {
    return new Condition<TradeParty>() {

        @Override
        public boolean matches(TradeParty tradeParty) {
            return tradeParty.getName().equals(rowTradeParty.getName()) && tradeParty.getContact().getName().equals(rowTradeParty.getContactName()) && tradeParty.getContact().getEmail().equals(rowTradeParty.getEmail()) && tradeParty.getAddress().getLineOne().equals(rowTradeParty.getAddressLine1()) && tradeParty.getAddress().getLineTwo().equals(rowTradeParty.getAddressLine2()) && tradeParty.getAddress().getCity().equals(rowTradeParty.getCity()) && tradeParty.getAddress().getPostcode().equals(rowTradeParty.getPostcode()) && tradeParty.getAddress().getCountry().equals(rowTradeParty.getCountryCode());
        }
    };
}
Example 27
Project: testory-master  File: TestMatchersAsMatcher.java View source code
@Test
public void supports_fest_matcher() {
    matcher = new org.fest.assertions.Condition<Object>() {

        public boolean matches(Object value) {
            return value == object;
        }
    };
    assertTrue(isMatcher(matcher));
    assertTrue(asMatcher(matcher).matches(object));
    assertFalse(asMatcher(matcher).matches(otherObject));
}
Example 28
Project: sonar-xml-master  File: XmlSensorTest.java View source code
private void assertLog(String expected, boolean isRegexp) {
    if (isRegexp) {
        Condition<String> regexpMatches = new Condition<String>( log -> Pattern.compile(expected).matcher(log).matches(), "");
        assertThat(logTester.logs()).filteredOn(regexpMatches).as("None of the lines in " + logTester.logs() + " matches regexp [" + expected + "], but one line was expected to match").isNotEmpty();
    } else {
        assertThat(logTester.logs()).contains(expected);
    }
}
Example 29
Project: spring-cloud-stream-master  File: PartitionCapableBinderTests.java View source code
@Test
public void testPartitionedModuleSpEL() throws Exception {
    B binder = getBinder();
    CP consumerProperties = createConsumerProperties();
    consumerProperties.setConcurrency(2);
    consumerProperties.setInstanceIndex(0);
    consumerProperties.setInstanceCount(3);
    consumerProperties.setPartitioned(true);
    QueueChannel input0 = new QueueChannel();
    input0.setBeanName("test.input0S");
    Binding<MessageChannel> input0Binding = binder.bindConsumer("part.0", "test", input0, consumerProperties);
    consumerProperties.setInstanceIndex(1);
    QueueChannel input1 = new QueueChannel();
    input1.setBeanName("test.input1S");
    Binding<MessageChannel> input1Binding = binder.bindConsumer("part.0", "test", input1, consumerProperties);
    consumerProperties.setInstanceIndex(2);
    QueueChannel input2 = new QueueChannel();
    input2.setBeanName("test.input2S");
    Binding<MessageChannel> input2Binding = binder.bindConsumer("part.0", "test", input2, consumerProperties);
    PP producerProperties = createProducerProperties();
    producerProperties.setPartitionKeyExpression(spelExpressionParser.parseExpression("payload"));
    producerProperties.setPartitionSelectorExpression(spelExpressionParser.parseExpression("hashCode()"));
    producerProperties.setPartitionCount(3);
    DirectChannel output = createBindableChannel("output", createProducerBindingProperties(producerProperties));
    output.setBeanName("test.output");
    Binding<MessageChannel> outputBinding = binder.bindProducer("part.0", output, producerProperties);
    try {
        Object endpoint = extractEndpoint(outputBinding);
        checkRkExpressionForPartitionedModuleSpEL(endpoint);
    } catch (UnsupportedOperationException ignored) {
    }
    Message<Integer> message2 = MessageBuilder.withPayload(2).setHeader(IntegrationMessageHeaderAccessor.CORRELATION_ID, "foo").setHeader(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, 42).setHeader(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE, 43).build();
    output.send(message2);
    output.send(new GenericMessage<>(1));
    output.send(new GenericMessage<>(0));
    Message<?> receive0 = receive(input0);
    assertThat(receive0).isNotNull();
    Message<?> receive1 = receive(input1);
    assertThat(receive1).isNotNull();
    Message<?> receive2 = receive(input2);
    assertThat(receive2).isNotNull();
    Condition<Message<?>> correlationHeadersForPayload2 = new Condition<Message<?>>() {

        @Override
        public boolean matches(Message<?> value) {
            IntegrationMessageHeaderAccessor accessor = new IntegrationMessageHeaderAccessor(value);
            return "foo".equals(accessor.getCorrelationId()) && 42 == accessor.getSequenceNumber() && 43 == accessor.getSequenceSize();
        }
    };
    if (usesExplicitRouting()) {
        assertThat(receive0.getPayload()).isEqualTo(0);
        assertThat(receive1.getPayload()).isEqualTo(1);
        assertThat(receive2.getPayload()).isEqualTo(2);
        assertThat(receive2).has(correlationHeadersForPayload2);
    } else {
        List<Message<?>> receivedMessages = Arrays.asList(receive0, receive1, receive2);
        assertThat(receivedMessages).extracting("payload").containsExactlyInAnyOrder(0, 1, 2);
        Condition<Message<?>> payloadIs2 = new Condition<Message<?>>() {

            @Override
            public boolean matches(Message<?> value) {
                return value.getPayload().equals(2);
            }
        };
        assertThat(receivedMessages).filteredOn(payloadIs2).areExactly(1, correlationHeadersForPayload2);
    }
    input0Binding.unbind();
    input1Binding.unbind();
    input2Binding.unbind();
    outputBinding.unbind();
}
Example 30
Project: junit5-master  File: TestTemplateInvocationTests.java View source code
@SuppressWarnings({ "unchecked", "varargs", "rawtypes" })
@SafeVarargs
private final Condition<? super ExecutionEvent>[] wrappedInContainerEvents(Class<MyTestTemplateTestCase> clazz, Condition<? super ExecutionEvent>... wrappedConditions) {
    List<Condition<? super ExecutionEvent>> conditions = new ArrayList<>();
    conditions.add(event(engine(), started()));
    conditions.add(event(container(clazz), started()));
    conditions.addAll(asList(wrappedConditions));
    conditions.add(event(container(clazz), finishedSuccessfully()));
    conditions.add(event(engine(), finishedSuccessfully()));
    return conditions.toArray(new Condition[0]);
}
Example 31
Project: softwaremill-common-master  File: OptionalConditions.java View source code
public static Condition<Object> present() {
    return PRESENT_CONDITION;
}
Example 32
Project: beacon-of-beacons-master  File: BasicDaoTest.java View source code
public Condition getNullCondition() {
    return new Condition("null") {

        @Override
        public boolean matches(Object value) {
            return value == null;
        }
    };
}
Example 33
Project: frisbee-master  File: IntentFilterTest.java View source code
@NonNull
private static Condition<ResolveInfo> ofType(final Class<? extends Activity> activityClass) {
    return new Condition<ResolveInfo>() {

        @Override
        public boolean matches(final ResolveInfo value) {
            return activityClass.getName().equals(value.activityInfo.name);
        }
    };
}
Example 34
Project: spring-data-commons-master  File: SpringDataWebConfigurationIntegrationTests.java View source code
/**
	 * Creates a {@link Condition} that checks if an object is an instance of a class with the same name as the provided
	 * class. This is necessary since we are dealing with multiple classloaders which would make a simple instanceof fail
	 * all the time
	 *
	 * @param expectedClass the class that is expected (possibly loaded by a different classloader).
	 * @return a {@link Condition}
	 */
private static Condition<Object> instanceWithClassName(Class<?> expectedClass) {
    return new //
    Condition<>(//
     it -> it.getClass().getName().equals(expectedClass.getName()), "with class name %s!", expectedClass.getName());
}
Example 35
Project: termsuite-core-master  File: OccurrenceBufferSpec.java View source code
private Condition<RegexOccurrence> cat(final String category) {
    return new Condition<RegexOccurrence>() {

        @Override
        public boolean matches(RegexOccurrence occurrence) {
            return occurrence.getCategory().equals(category);
        }
    };
}
Example 36
Project: flags-master  File: PropertyFeatureProviderTest.java View source code
private Condition<FeatureGroup> groupNamed(final String name) {
    return new Condition<FeatureGroup>() {

        @Override
        public boolean matches(FeatureGroup value) {
            return value != null && value.getLabel().equals(name);
        }
    };
}
Example 37
Project: keywhiz-master  File: MembershipResourceIntegrationTest.java View source code
/** @return condition where group has given id. */
private static Condition<Group> groupId(final long id) {
    return new Condition<Group>() {

        @Override
        public boolean matches(Group group) {
            return group.getId() == id;
        }
    };
}
Example 38
Project: togglz-master  File: PropertyFeatureProviderTest.java View source code
private Condition<FeatureGroup> groupNamed(final String name) {
    return new Condition<FeatureGroup>() {

        @Override
        public boolean matches(FeatureGroup value) {
            return value != null && value.getLabel().equals(name);
        }
    };
}
Example 39
Project: spring-data-rest-master  File: MongoWebTests.java View source code
// DATAREST-471
@Test
public void auditableResourceHasLastModifiedHeaderSet() throws Exception {
    Profile profile = repository.findAll().iterator().next();
    String header = mvc.perform(get("/profiles/{id}", //
    profile.getId())).andReturn().getResponse().getHeader("Last-Modified");
    assertThat(header).isNot(new Condition<String>( it -> it == null || it.isEmpty(), "Foo"));
}