org.junit.jupiter.api.function.Executable Java Examples

The following examples show how to use org.junit.jupiter.api.function.Executable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TaskJobLauncherCommandLineRunnerTests.java    From spring-cloud-task with Apache License 2.0 7 votes vote down vote up
@Test
public void testCommandLineRunnerSetToFalse() {
	String[] enabledArgs = new String[] {};
	this.applicationContext = SpringApplication.run(
			new Class[] {
					TaskJobLauncherCommandLineRunnerTests.JobConfiguration.class },
			enabledArgs);
	validateContext();
	assertThat(this.applicationContext.getBean(JobLauncherApplicationRunner.class))
			.isNotNull();

	Executable executable = () -> this.applicationContext
			.getBean(TaskJobLauncherCommandLineRunner.class);

	assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
			.isThrownBy(executable::execute).withMessage("No qualifying bean of type "
					+ "'org.springframework.cloud.task.batch.handler.TaskJobLauncherCommandLineRunner' available");
	validateContext();
}
 
Example #2
Source File: TriplestoreResourceTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
static Stream<Executable> checkResource(final Resource res, final IRI identifier, final IRI ldpType,
        final boolean hasBinary, final boolean hasAcl, final boolean hasParent) {
    return Stream.of(
            () -> assertEquals(identifier, res.getIdentifier(), "Incorrect identifier!"),
            () -> assertEquals(ldpType, res.getInteractionModel(), "Incorrect interaction model!"),
            () -> assertEquals(parse(time), res.getModified(), "Incorrect modified date!"),
            () -> assertNotNull(res.getRevision(), "Revision is null!"),
            () -> assertEquals(hasBinary, res.getBinaryMetadata().isPresent(), "Unexpected binary presence!"),
            () -> assertEquals(hasParent, res.getContainer().isPresent(), "Unexpected parent resource!"),
            () -> assertEquals(res.stream(barGraph).findAny().isPresent(), res.hasMetadata(barGraph),
                               "Unexpected metadata"),
            () -> assertEquals(res.stream(fooGraph).findAny().isPresent(), res.hasMetadata(fooGraph),
                               "Unexpected metadata"),
            () -> assertEquals(res.getMetadataGraphNames().contains(Trellis.PreferAudit),
                               res.hasMetadata(Trellis.PreferAudit), "Unexpected Audit quads"),
            () -> assertEquals(res.stream(Trellis.PreferAudit).findAny().isPresent(),
                               res.hasMetadata(Trellis.PreferAudit), "Missing audit quads"),
            () -> assertEquals(res.getMetadataGraphNames().contains(Trellis.PreferAccessControl),
                               res.hasMetadata(Trellis.PreferAccessControl), "Unexpected ACL presence!"),
            () -> assertEquals(hasAcl, res.hasMetadata(Trellis.PreferAccessControl), "Unexpected ACL presence!"));
}
 
Example #3
Source File: TriplestoreResourceTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
static Stream<Executable> checkRdfStream(final Resource res, final long userManaged,
        final long serverManaged, final long acl, final long audit, final long membership, final long containment) {
    final long total = userManaged + acl + audit + membership + containment + serverManaged;
    return Stream.of(
            () -> assertEquals(serverManaged, res.stream(singleton(Trellis.PreferServerManaged)).count(),
                               "Incorrect server managed triple count!"),
            () -> assertEquals(userManaged, res.stream(singleton(Trellis.PreferUserManaged)).count(),
                               "Incorrect user managed triple count!"),
            () -> assertEquals(acl, res.stream(singleton(Trellis.PreferAccessControl)).count(),
                               "Incorrect acl triple count!"),
            () -> assertEquals(audit, res.stream(singleton(Trellis.PreferAudit)).count(),
                               "Incorrect audit triple count!"),
            () -> assertEquals(membership, res.stream(singleton(LDP.PreferMembership)).count(),
                               "Incorrect member triple count!"),
            () -> assertEquals(containment, res.stream(singleton(LDP.PreferContainment)).count(),
                               "Incorrect containment triple count!"),
            () -> assertEquals(total, res.stream().count(), "Incorrect total triple count!"));
}
 
Example #4
Source File: DefaultRdfaWriterServiceTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
static Stream<Executable> checkHtmlWithoutNamespaces(final String html) {
    return of(
        () -> assertTrue(html.contains("<title>http://example.com/</title>"), "Title not in HTML!"),
        () -> assertTrue(html.contains("_:B"), "bnode value not in HTML!"),
        () -> assertTrue(
                html.contains("<a href=\"http://sws.geonames.org/4929022/\">http://sws.geonames.org/4929022/</a>"),
                "Geonames object IRI not in HTML!"),
        () -> assertTrue(
                html.contains("<a href=\"http://purl.org/dc/terms/spatial\">http://purl.org/dc/terms/spatial</a>"),
                "dc:spatial predicate not in HTML!"),
        () -> assertTrue(
                html.contains("<a href=\"http://purl.org/dc/dcmitype/Text\">http://purl.org/dc/dcmitype/Text</a>"),
                "dcmi type not in HTML output!"),
        () -> assertTrue(html.contains("<a href=\"mailto:[email protected]\">mailto:[email protected]</a>"),
                "email IRI not in output!"),
        () -> assertTrue(html.contains("<h1>http://example.com/</h1>"), "Default title not in output!"));
}
 
Example #5
Source File: FetchParamsTest.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Environment must have a parent type")
void environment_must_have_parent_type() {

    String uri = "abc123";

    HGQLSchema schema = mock(HGQLSchema.class);
    DataFetchingEnvironment environment = mock(DataFetchingEnvironment.class);

    Field field1 = mock(Field.class);

    List<Field> fields = Collections.singletonList(field1);
    when(environment.getFields()).thenReturn(fields);
    when(field1.getName()).thenReturn("field1");

    FieldConfig fieldConfig = mock(FieldConfig.class);
    Map<String, FieldConfig> schemaFields = Collections.singletonMap("field1", fieldConfig);
    when(schema.getFields()).thenReturn(schemaFields);

    when(fieldConfig.getId()).thenReturn(uri);

    Executable executable = () -> new FetchParams(environment, schema);
    assertThrows(NullPointerException.class, executable);
}
 
Example #6
Source File: ParameterTypeRegistryTest.java    From cucumber with MIT License 6 votes vote down vote up
@Test
public void does_not_allow_more_than_one_preferential_parameter_type_for_each_regexp() {

    registry.defineParameterType(new ParameterType<>("name", CAPITALISED_WORD, Name.class, Name::new, false, true));
    registry.defineParameterType(new ParameterType<>("person", CAPITALISED_WORD, Person.class, Person::new, false, false));

    final Executable testMethod = () -> registry.defineParameterType(new ParameterType<>(
            "place",
            CAPITALISED_WORD,
            Place.class,
            Place::new,
            false,
            true
    ));

    final CucumberExpressionException thrownException = assertThrows(CucumberExpressionException.class, testMethod);
    assertThat("Unexpected message", thrownException.getMessage(), is(equalTo("There can only be one preferential parameter type per regexp. The regexp /[A-Z]+\\w+/ is used for two preferential parameter types, {name} and {place}")));
}
 
Example #7
Source File: ResourceServiceTests.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * Check a Trellis Resource.
 * @param res the Resource
 * @param identifier the identifier
 * @param ldpType the LDP type
 * @param time an instant before which the resource shouldn't exist
 * @param dataset a dataset to compare against
 * @return a stream of testable assertions
 */
default Stream<Executable> checkResource(final Resource res, final IRI identifier, final IRI ldpType,
        final Instant time, final Dataset dataset) {
    return Stream.of(
            () -> assertEquals(ldpType, res.getInteractionModel(), "Check the interaction model"),
            () -> assertEquals(identifier, res.getIdentifier(), "Check the identifier"),
            () -> assertFalse(res.getModified().isBefore(time), "Check the modification time (1)"),
            () -> assertFalse(res.getModified().isAfter(now()), "Check the modification time (2)"),
            () -> assertFalse(res.hasMetadata(Trellis.PreferAccessControl), "Check for an ACL"),
            () -> assertEquals(LDP.NonRDFSource.equals(ldpType), res.getBinaryMetadata().isPresent(),
                               "Check Binary"),
            () -> assertEquals(asList(LDP.DirectContainer, LDP.IndirectContainer).contains(ldpType),
                   res.getMembershipResource().isPresent(), "Check ldp:membershipResource"),
            () -> assertEquals(asList(LDP.DirectContainer, LDP.IndirectContainer).contains(ldpType),
                   res.getMemberRelation().isPresent() || res.getMemberOfRelation().isPresent(),
                   "Check ldp:hasMemberRelation or ldp:isMemberOfRelation"),
            () -> assertEquals(asList(LDP.DirectContainer, LDP.IndirectContainer).contains(ldpType),
                   res.getInsertedContentRelation().isPresent(), "Check ldp:insertedContentRelation"),
            () -> res.stream(Trellis.PreferUserManaged).filter(q -> !q.getPredicate().equals(type)).forEach(q ->
                    assertTrue(dataset.contains(q))));
}
 
Example #8
Source File: CustomParameterTypeTest.java    From cucumber with MIT License 5 votes vote down vote up
@Test
public void throws_exception_for_illegal_character_in_parameter_name() {

    final Executable testMethod = () -> new ParameterType<>(
            "[string]",
            ".*",
            String.class,
            (Transformer<String>) s -> s,
            false,
            false
    );

    final CucumberExpressionException thrownException = assertThrows(CucumberExpressionException.class, testMethod);
    assertThat("Unexpected message", thrownException.getMessage(), is(equalTo("Illegal character '[' in parameter name {[string]}.")));
}
 
Example #9
Source File: ViewsTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
/**
 * Validate that an IllegalStateException is thrown if an attempt is made to build a multi
 * request without calling add() before build() with a single request with no view request
 * parameter calls.
 */
@Test
public void multiRequestBuildOnlyAfterAddNoParams() {
    assertThrows(IllegalStateException.class,
            new Executable() {
                @Override
                public void execute() throws Throwable {
                    ViewMultipleRequest<String, Object> multi = db.getViewRequestBuilder
                            ("example", "foo")
                            .newMultipleRequest(Key.Type.STRING, Object.class)
                            .build();
                }
            });
}
 
Example #10
Source File: DatabaseTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
/**
 * Test that when called against a DB that is not a Cloudant service
 * an UnsupportedOperationException is thrown
 */
@RequiresCouch
@RequiresCloudantLocal
public void testPermissionsException() {
    assertThrows(UnsupportedOperationException.class, new Executable() {
        @Override
        public void execute() throws Throwable {
            Map<String, EnumSet<Permissions>> userPerms = db.getPermissions();
        }
    });
}
 
Example #11
Source File: JenaIOServiceTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
static Stream<Executable> checkFlattenedSerialization(final String serialized, final Graph graph) {
    return of(
            () -> assertTrue(serialized.contains("\"title\":\"A title\""), "missing/invalid dc:title value!"),
            () -> assertTrue(serialized.contains("\"@context\":"), "missing @context!"),
            () -> assertTrue(serialized.contains("\"@graph\":"), "unexpected @graph!"),
            () -> assertTrue(validateGraph(graph), "Not all triples present in output graph!"));
}
 
Example #12
Source File: UnleashConfigTest.java    From unleash-client-java with Apache License 2.0 5 votes vote down vote up
@Test
public void should_require_instanceId() {
    Executable ex = () -> UnleashConfig.builder()
            .appName("my-app")
            .instanceId(null)
            .unleashAPI("http://unleash.org")
            .build();

    assertThrows(IllegalStateException.class, ex);
}
 
Example #13
Source File: OAuthFilterTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
private static Stream<Executable> checkSecurityContext(final SecurityContext ctx, final String webid) {
    return of(
            () -> assertEquals(webid, ctx.getUserPrincipal().getName(), "Unexpected agent IRI!"),
            () -> assertEquals(OAuthFilter.SCHEME, ctx.getAuthenticationScheme(), "Unexpected scheme!"),
            () -> assertFalse(ctx.isSecure(), "Unexpected secure flag!"),
            () -> assertFalse(ctx.isUserInRole("some role"), "Unexpectedly in user role!"));
}
 
Example #14
Source File: DiscussionTopicMapperTest.java    From voj with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 测试用例: 测试createDiscussionTopic(DiscussionTopic)方法
 * 测试数据: 使用合法的数据集, 但是该别名存在相应的记录
 * 预期结果: 抛出DuplicateKeyException异常
 */
@Test
public void testCreateDiscussionTopicWithDupliateSlug() {
	DiscussionTopic topic = new DiscussionTopic("general", "New Topic", 0);
	Executable e = () -> {
		discussionTopicMapper.createDiscussionTopic(topic);
	};
	Assertions.assertThrows(org.springframework.dao.DuplicateKeyException.class, e);
}
 
Example #15
Source File: AuthAnonymousTests.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * Run the tests.
 * @return the tests
 */
default Stream<Executable> runTests() {
    return Stream.of(this::testCanReadPublicResource,
            this::testCanReadPublicResourceChild,
            this::testUserCanAppendPublicResource,
            this::testCanWritePublicResource,
            this::testCanWritePublicResourceChild,
            this::testCanControlPublicResource,
            this::testCanControlPublicResourceChild,
            this::testCanReadProtectedResource,
            this::testCanReadProtectedResourceChild,
            this::testUserCanAppendProtectedResource,
            this::testCanWriteProtectedResource,
            this::testCanWriteProtectedResourceChild,
            this::testCanControlProtectedResource,
            this::testCanControlProtectedResourceChild,
            this::testCanReadPrivateResource,
            this::testCanReadPrivateResourceChild,
            this::testUserCanAppendPrivateResource,
            this::testCanWritePrivateResource,
            this::testCanWritePrivateResourceChild,
            this::testCanControlPrivateResource,
            this::testCanControlPrivateResourceChild,
            this::testCanReadGroupResource,
            this::testCanReadGroupResourceChild,
            this::testUserCanAppendGroupResource,
            this::testCanWriteGroupResource,
            this::testCanWriteGroupResourceChild,
            this::testCanControlGroupResource,
            this::testCanControlGroupResourceChild,
            this::testCanReadDefaultAclResource,
            this::testCanReadDefaultAclResourceChild,
            this::testUserCanAppendDefaultAclResource,
            this::testCanWriteDefaultAclResource,
            this::testCanWriteDefaultAclResourceChild,
            this::testCanControlDefaultAclResource,
            this::testCanControlDefaultAclResourceChild);
}
 
Example #16
Source File: DocumentsCRUDTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@Test
public void updateWithInvalidRev_throwsDocumentConflictException() {
    assertThrows(DocumentConflictException.class, new Executable() {
        @Override
        public void execute() throws Throwable {
            Response response = db.save(new Foo());
            Foo foo = db.find(Foo.class, response.getId());
            db.update(foo);
            db.update(foo);
        }
    });
}
 
Example #17
Source File: MementoTimeMapTests.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * Run the tests.
 * @return the tests
 */
default Stream<Executable> runTests() {
    setUp();
    return Stream.of(this::testTimeMapLinkHeader,
            this::testTimeMapResponseHasTimeMapLink,
            this::testTimeMapIsLDPResource,
            this::testTimeMapMediaType,
            this::testTimeMapConnegTurtle,
            this::testTimeMapConnegJsonLd,
            this::testTimeMapConnegNTriples,
            this::testTimeMapAllowedMethods);
}
 
Example #18
Source File: LdpIndirectContainerTests.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * Run the tests.
 * @return the tests
 * @throws Exception in the case of an error
 */
default Stream<Executable> runTests() throws Exception {
    setUp();
    return Stream.of(this::testAddResourceWithMemberSubject,
            this::testCreateIndirectContainerViaPut,
            this::testUpdateIndirectContainerTooManyMemberProps,
            this::testUpdateIndirectContainerMultipleMemberResources,
            this::testUpdateIndirectContainerMissingMemberResource,
            this::testGetInverseEmptyMember);
}
 
Example #19
Source File: TestScopeName.java    From toothpick with Apache License 2.0 5 votes vote down vote up
@Test
void testSetScopeName_shouldFail_whenScopeNameWasAlreadySet() {
  assertThrows(
      IllegalStateException.class,
      new Executable() {
        @Override
        public void execute() {
          toothPickExtension.setScopeName("Bar");
        }
      });
}
 
Example #20
Source File: TitleTests.java    From roboslack with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource(value = "invalidConstructors")
void testConstructionConstraints(Executable executable) {
    Throwable thrown = assertThrows(IllegalArgumentException.class, executable);
    assertThat(thrown.getMessage(),
            either(containsString("cannot contain markdown"))
                    .or(containsString("cannot be null or empty")));
}
 
Example #21
Source File: CloudFoundryServiceTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@Test
public void vcapInvalidJSON() {
    Assertions.assertThrows(IllegalArgumentException.class, new Executable() {
        @Override
        public void execute() throws Throwable {
            ClientBuilder.bluemix("{\"cloudantNoSQLDB\":[]"); // invalid JSON
        }
    });
}
 
Example #22
Source File: LdpBasicContainerTests.java    From trellis with Apache License 2.0 5 votes vote down vote up
default Stream<Executable> runTests() throws Exception {
    setUp();
    return Stream.of(this::testGetEmptyContainer,
            this::testGetInverseEmptyContainer,
            this::testGetEmptyContainerMembership,
            this::testGetContainer,
            this::testPatchNewRDF,
            this::testCreateContainerViaPost,
            this::testCreateContainerViaPut,
            this::testCreateContainerWithSlug,
            this::testDeleteContainer);
}
 
Example #23
Source File: AttachmentsTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@Test
public void attachmentStandaloneDocIdEmptyRev() {
    assertThrows(IllegalArgumentException.class, new Executable() {
        @Override
        public void execute() throws Throwable {
            String docId = Utils.generateUUID();
            byte[] bytesToDB = "binary data".getBytes();
            ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesToDB);
            Response response = db.saveAttachment(bytesIn, "foo.txt", "text/plain", docId, "");
        }
    });
}
 
Example #24
Source File: ServiceSentEventLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSSEEndpointIsCalled_thenEventStreamingBegins() {

    Executable sseStreamingCall = () -> client.get()
        .uri("/stream-sse")
        .exchange()
        .expectStatus()
        .isOk()
        .expectHeader()
        .contentTypeCompatibleWith(MediaType.TEXT_EVENT_STREAM)
        .expectBody(String.class);

    Assertions.assertThrows(IllegalStateException.class, sseStreamingCall, "Expected test to timeout and throw IllegalStateException, but it didn't");
}
 
Example #25
Source File: AbstractTrellisHttpResourceTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
private Stream<Executable> checkBinaryResponse(final Response res) {
    return Stream.of(
            () -> assertTrue(res.getMediaType().isCompatible(TEXT_PLAIN_TYPE), "Incompatible content-type!"),
            () -> assertNotNull(res.getHeaderString(ACCEPT_RANGES), "Missing Accept-Ranges header!"),
            () -> assertNull(res.getHeaderString(MEMENTO_DATETIME), ERR_MEMENTO_DATETIME),
            () -> assertAll(CHECK_VARY_HEADERS, checkVary(res, asList(RANGE, ACCEPT_DATETIME))),
            () -> assertAll(CHECK_ALLOWED_METHODS,
                            checkAllowedMethods(res, asList(PUT, DELETE, GET, HEAD, OPTIONS))),
            () -> assertAll(CHECK_LDP_LINKS, checkLdpTypeHeaders(res, LDP.NonRDFSource)));
}
 
Example #26
Source File: IndexTests.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidFieldThrowsJsonParseException() {
    assertThrows(JsonParseException.class, new Executable() {
        @Override
        public void execute() throws Throwable {
            FindByIndexOptions findByIndexOptions = new FindByIndexOptions();
            findByIndexOptions.fields("\"");
            db.findByIndex("{\"type\":\"subscription\"}", Movie.class, findByIndexOptions);
        }
    });
}
 
Example #27
Source File: AuthorizationExtensionTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void authenticateUser_shouldErrorOutInAbsenceOfSecurityAuthConfigs() {
    Executable codeThatShouldThrowError = () -> {
        authorizationExtension.authenticateUser(PLUGIN_ID, "bob", "secret", null, null);
    };

    MissingAuthConfigsException exception = assertThrows(MissingAuthConfigsException.class, codeThatShouldThrowError);

    assertThat(exception.getMessage()).isEqualTo("No AuthConfigs configured for plugin: plugin-id, Plugin would need at-least one auth_config to authenticate user.");
    verifyNoMoreInteractions(pluginManager);
}
 
Example #28
Source File: ProblemCategoryMapperTest.java    From voj with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 测试用例: 测试createProblemCategoryRelationship(long, ProblemCategory)方法
 * 测试数据: 使用存在的存在试题ID和存在的试题分类对象
 * 预期结果: 抛出DuplicateKeyException异常
 */
@Test
public void testCreateProblemCategoryRelationshipUsingExistingProblemIdAndExistingProblemCategory() {
	ProblemCategory problemCategory = problemCategoryMapper.getProblemCategoryUsingCategoryId(1);
	Executable e = () -> {
		problemCategoryMapper.createProblemCategoryRelationship(1000, problemCategory);
	};
	Assertions.assertThrows(org.springframework.dao.DuplicateKeyException.class, e);
}
 
Example #29
Source File: CommonTests.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * Check an RDF graph.
 * @param graph the graph
 * @param identifier the identifier
 * @return a stream of testable assertions
 */
default Stream<Executable> checkRdfGraph(final Graph graph, final IRI identifier) {
    return Stream.of(
            () -> assertTrue(graph.contains(identifier, SKOS.prefLabel,
                                            RDFFactory.getInstance().createLiteral(BASIC_CONTAINER_LABEL, ENG)),
                             "Check for the presence of a skos:prefLabel triple"),
            () -> assertTrue(graph.contains(identifier, DC.description, null),
                             "Check for the presence fo a dc:description triple"));
}
 
Example #30
Source File: MementoCommonTests.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * Check a response for expected LDP Link headers.
 * @param res the Response object
 * @param ldpType the LDP Resource type
 * @return a Stream of executable assertions
 */
default Stream<Executable> checkMementoLdpHeaders(final Response res, final IRI ldpType) {
    return of(
            () -> assertEquals(SUCCESSFUL, res.getStatusInfo().getFamily(), "Check for a successful response"),
            () -> assertTrue(getLinks(res).stream().anyMatch(hasType(LDP.Resource)),
                             "Check that the response is an LDP Resource"),
            () -> assertTrue(getLinks(res).stream().anyMatch(hasType(ldpType)),
                             "Check that the response is an " + ldpType));
}