Java Code Examples for org.assertj.core.api.Assertions#assertThat()

The following examples show how to use org.assertj.core.api.Assertions#assertThat() . 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: PoliciesValidatorTest.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
@Test
public void assertValidQueryPolicy() {
    Set<Query> queries = new HashSet<>();
    Query query =
        Query
            .builder()
                .name("docker-images")
                .description("Find all running docker images")
                .sql("select * from application_detail where running_instances > 0 and requested_state = 'started' and image is not null")
            .build();
    queries.add(query);
    EmailNotificationTemplate template =
        EmailNotificationTemplate
            .builder()
                .to(List.of("[email protected]"))
                .from("[email protected]")
                .subject("Contemplating K8s")
                .body("Here's a boatload of containers")
            .build();
    QueryPolicy policy =
        QueryPolicy
            .builder()
                .queries(queries)
                .emailNotificationTemplate(template)
            .build();
    Assertions.assertThat(policiesValidator.validate(policy) == true);
}
 
Example 2
Source File: PoliciesValidatorTest.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
@Test
public void assertInvalidQueryPolicy() {
    Set<Query> queries = new HashSet<>();
    Query query =
        Query
            .builder()
                .name("malicious-query")
                .description("Delete the cache of applicatin detail")
                .sql("delete from application_detail")
            .build();
    queries.add(query);
    EmailNotificationTemplate template =
        EmailNotificationTemplate
            .builder()
                .to(List.of("[email protected]"))
                .from("[email protected]")
                .subject("Ha ha")
                .body("You got nothing")
            .build();
    QueryPolicy policy =
        QueryPolicy
            .builder()
                .queries(queries)
                .emailNotificationTemplate(template)
            .build();
    Assertions.assertThat(policiesValidator.validate(policy) == false);
}
 
Example 3
Source File: JsonPathAssert.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
public AbstractObjectAssert<?, Object> hasPath(String path) {
	try {
		return Assertions.assertThat(this.actual.read(path, Object.class));
	}
	catch (PathNotFoundException ex) {
		failWithMessage("The JSON " + this.actual.jsonString() + " does not contain the path '" + path + "'");
		return null;
	}
}
 
Example 4
Source File: SecretsHandlerTest.java    From tokens with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthorizationHandler() {
    FilesystemReader<?> reader = new SecretsHandler(secrets).getFilesystemReader();
    reader.run();
    Assertions.assertThat(secrets).isNotEmpty();
    Assertions.assertThat(secrets).containsKeys("mybasic", "myfirst");

    Secret mybasicSecret = secrets.get("mybasic");
    Assertions.assertThat(mybasicSecret.getType()).isEqualTo("Basic");
    Assertions.assertThat(mybasicSecret.getValue());

}
 
Example 5
Source File: ArchivaIndexingTaskExecutorTest.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Test
public void testPackagedIndex()
    throws Exception
{

    Path basePath = repo.getRoot().getFilePath();
    IndexCreationFeature icf = repo.getFeature( IndexCreationFeature.class ).get();
    StorageAsset packedIndexDirectory = icf.getLocalPackedIndexPath();
    StorageAsset indexerDirectory = icf.getLocalIndexPath();

    for (StorageAsset dir : new StorageAsset[] { packedIndexDirectory, indexerDirectory }) {
        if (dir.getFilePath()!=null)
        {
            Path localDirPath = dir.getFilePath();
            Files.list( localDirPath ).filter( path -> path.getFileName( ).toString( ).startsWith( "nexus-maven-repository-index" ) )
                .forEach( path ->
                {
                    try
                    {
                        System.err.println( "Deleting " + path );
                        Files.delete( path );
                    }
                    catch ( IOException e )
                    {
                        e.printStackTrace( );
                    }
                } );
        }
    }




    Path artifactFile = basePath.resolve(
                                  "org/apache/archiva/archiva-index-methods-jar-test/1.0/archiva-index-methods-jar-test-1.0.jar" );
    ArtifactIndexingTask task =
        new ArtifactIndexingTask( repo, artifactFile, ArtifactIndexingTask.Action.ADD,
                                  repo.getIndexingContext() );
    task.setExecuteOnEntireRepo( false );

    indexingExecutor.executeTask( task );

    task = new ArtifactIndexingTask( repo, null, ArtifactIndexingTask.Action.FINISH,
                                     repo.getIndexingContext() );

    task.setExecuteOnEntireRepo( false );

    indexingExecutor.executeTask( task );

    assertTrue( Files.exists(packedIndexDirectory.getFilePath()) );
    assertTrue( Files.exists(indexerDirectory.getFilePath()) );

    // test packed index file creation
    //no more zip
    //Assertions.assertThat(new File( indexerDirectory, "nexus-maven-repository-index.zip" )).exists();
    Assertions.assertThat( Files.exists(packedIndexDirectory.getFilePath().resolve("nexus-maven-repository-index.properties" ) ));
    Assertions.assertThat( Files.exists(packedIndexDirectory.getFilePath().resolve("nexus-maven-repository-index.gz" ) ));
    assertFalse( Files.exists(packedIndexDirectory.getFilePath().resolve("nexus-maven-repository-index.1.gz" )  ));

    // unpack .zip index
    //unzipIndex( indexerDirectory.getPath(), destDir.getPath() );

    DefaultIndexUpdater.FileFetcher fetcher = new DefaultIndexUpdater.FileFetcher( packedIndexDirectory.getFilePath().toFile() );
    IndexUpdateRequest updateRequest = new IndexUpdateRequest( getIndexingContext(), fetcher );
    //updateRequest.setLocalIndexCacheDir( indexerDirectory );
    indexUpdater.fetchAndUpdateIndex( updateRequest );

    BooleanQuery.Builder qb = new BooleanQuery.Builder();
    qb.add( indexer.constructQuery( MAVEN.GROUP_ID, new StringSearchExpression( "org.apache.archiva" ) ),
           BooleanClause.Occur.SHOULD );
    qb.add(
        indexer.constructQuery( MAVEN.ARTIFACT_ID, new StringSearchExpression( "archiva-index-methods-jar-test" ) ),
        BooleanClause.Occur.SHOULD );

    FlatSearchRequest request = new FlatSearchRequest( qb.build(), getIndexingContext() );
    FlatSearchResponse response = indexer.searchFlat( request );

    assertEquals( 1, response.getTotalHitsCount() );
    Set<ArtifactInfo> results = response.getResults();

    ArtifactInfo artifactInfo = results.iterator().next();
    assertEquals( "org.apache.archiva", artifactInfo.getGroupId() );
    assertEquals( "archiva-index-methods-jar-test", artifactInfo.getArtifactId() );
    assertEquals( "test-repo", artifactInfo.getRepository() );


}
 
Example 6
Source File: FileSpec.java    From bdt with Apache License 2.0 4 votes vote down vote up
/**
 * Create a JSON in resources directory with given name, so for using it you've to reference it as:
 * $(pwd)/target/test-classes/fileName
 *
 * @param fileName      name of the JSON file to be created
 * @param baseData      path to file containing the schema to be used
 * @param type          element to read from file (element should contain a json)
 * @param modifications DataTable containing the modifications to be done to the base schema element
 *                      <p>
 *                      - Syntax will be:
 *                      {@code
 *                      | <key path> | <type of modification> | <new value> |
 *                      }
 *                      for DELETE/ADD/UPDATE/APPEND/PREPEND
 *                      where:
 *                      key path: path to the key to be modified
 *                      type of modification: DELETE/ADD/UPDATE/APPEND/PREPEND
 *                      new value: new value to be used
 *                      <p>
 *                      - Or:
 *                      {@code
 *                      | <key path> | <type of modification> | <new value> | <new value type> |
 *                      }
 *                      for REPLACE
 *                      where:
 *                      key path: path to the key to be modified
 *                      type of modification: REPLACE
 *                      new value: new value to be used
 *                      json value type: type of the json property (array|object|number|boolean|null|n/a (for string))
 *                      <p>
 *                      <p>
 *                      For example:
 *                      <p>
 *                      (1)
 *                      If the element read is {"key1": "value1", "key2": {"key3": "value3"}}
 *                      and we want to modify the value in "key3" with "new value3"
 *                      the modification will be:
 *                      | key2.key3 | UPDATE | "new value3" |
 *                      being the result of the modification: {"key1": "value1", "key2": {"key3": "new value3"}}
 *                      <p>
 *                      (2)
 *                      If the element read is {"key1": "value1", "key2": {"key3": "value3"}}
 *                      and we want to replace the value in "key2" with {"key4": "value4"}
 *                      the modification will be:
 *                      | key2 | REPLACE | {"key4": "value4"} | object |
 *                      being the result of the modification: {"key1": "value1", "key2": {"key4": "value4"}}
 * @throws Exception
 */
@When("^I create file '(.+?)' based on '(.+?)' as '(.+?)' with:$")
public void createFile(String fileName, String baseData, String type, DataTable modifications) throws Exception {
    // Retrieve data
    String retrievedData = commonspec.retrieveData(baseData, type);

    // Modify data
    commonspec.getLogger().debug("Modifying data {} as {}", retrievedData, type);
    String modifiedData = commonspec.modifyData(retrievedData, type, modifications).toString();

    // Create file (temporary) and set path to be accessible within test
    File tempDirectory = new File(String.valueOf(System.getProperty("user.dir") + "/target/test-classes/"));
    String absolutePathFile = tempDirectory.getAbsolutePath() + "/" + fileName;
    commonspec.getLogger().debug("Creating file {} in 'target/test-classes'", absolutePathFile);
    // Note that this Writer will delete the file if it exists
    Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(absolutePathFile), "UTF-8"));
    try {
        out.write(modifiedData);
    } catch (Exception e) {
        commonspec.getLogger().error("Custom file {} hasn't been created:\n{}", absolutePathFile, e.toString());
    } finally {
        out.close();
    }

    Assertions.assertThat(new File(absolutePathFile).isFile());
}
 
Example 7
Source File: JsonPathAssert.java    From spring-cloud-open-service-broker with Apache License 2.0 4 votes vote down vote up
public <K, V> MapAssert<K, V> hasMapAtPath(String path) {
	TypeRef<Map<K, V>> mapTypeRef = new TypeRef<Map<K, V>>() {
	};
	return Assertions.assertThat(actual.read(path, mapTypeRef));
}
 
Example 8
Source File: JsonPathAssert.java    From spring-cloud-open-service-broker with Apache License 2.0 4 votes vote down vote up
public AbstractIntegerAssert<?> hasIntegerAtPath(String path) {
	return Assertions.assertThat(actual.read(path, Integer.class));
}
 
Example 9
Source File: JsonPathAssert.java    From spring-cloud-open-service-broker with Apache License 2.0 4 votes vote down vote up
public AbstractCharSequenceAssert<?, String> hasStringAtPath(String path) {
	return Assertions.assertThat(actual.read(path, String.class));
}
 
Example 10
Source File: JsonPathAssert.java    From spring-cloud-open-service-broker with Apache License 2.0 4 votes vote down vote up
public AbstractObjectAssert<?, Object> hasPath(String path) {
	return Assertions.assertThat(actual.read(path, Object.class));
}
 
Example 11
Source File: TokenRefresherThreadFactoryTest.java    From tokens with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    Assertions.assertThat(Thread.currentThread().getName().startsWith(expected.prefix));
    Assertions.assertThat(Thread.currentThread().isDaemon()).isEqualTo(expected.daemon);
    latch.countDown();
}
 
Example 12
Source File: EventsAssert.java    From ddd-wro-warehouse with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> AbstractObjectAssert<?, T> assertAt(int index, Class<T> type) {
    AbstractObjectAssert<?, ?> anAssert = Assertions.assertThat(events.get(index));
    anAssert.isInstanceOf(type);
    return (AbstractObjectAssert<?, T>) anAssert;
}
 
Example 13
Source File: PoliciesValidatorTest.java    From cf-butler with Apache License 2.0 4 votes vote down vote up
@Test
public void assertValidApplicationPolicy() {
    Map<String, Object> options = new HashMap<>();
    options.put("from-duration", "PT30S");
    ApplicationPolicy durationPolicy =
        ApplicationPolicy
            .builder()
            .description("Delete applications in stopped state that were pushed more than 30s ago.")
            .operation(ApplicationOperation.DELETE.getName())
            .organizationWhiteList(Set.of("zoo-labs"))
            .options(options)
            .state(ApplicationState.STOPPED.getName())
            .pk(100L)
            .id(null)
            .build();
    Assertions.assertThat(policiesValidator.validate(durationPolicy) == true);

    ApplicationPolicy noTimeframePolicy =
        ApplicationPolicy
            .builder()
            .description("Delete all applications in stopped state.")
            .operation(ApplicationOperation.DELETE.getName())
            .organizationWhiteList(Set.of("zoo-labs"))
            .state(ApplicationState.STOPPED.getName())
            .pk(100L)
            .id(null)
            .build();
    Assertions.assertThat(policiesValidator.validate(noTimeframePolicy) == true);

    Map<String, Object> options2 = new HashMap<>();
    options.put("from-datetime", LocalDateTime.now().minusDays(2));
    ApplicationPolicy dateTimePolicy =
        ApplicationPolicy
            .builder()
            .description("Delete all applications in stopped state that were pushed after date/time.")
            .operation(ApplicationOperation.DELETE.getName())
            .options(options2)
            .organizationWhiteList(Set.of("zoo-labs"))
            .state(ApplicationState.STOPPED.getName())
            .pk(100L)
            .id(null)
            .build();
    Assertions.assertThat(policiesValidator.validate(dateTimePolicy) == true);

    Map<String, Object> options3 = new HashMap<>();
    options.put("instances-from", 1);
    options.put("instances-to", 2);
    ApplicationPolicy scalingPolicy =
        ApplicationPolicy
            .builder()
            .description("Scale all applications ")
            .operation(ApplicationOperation.SCALE_INSTANCES.getName())
            .options(options3)
            .organizationWhiteList(Set.of("zoo-labs"))
            .state(ApplicationState.STOPPED.getName())
            .pk(100L)
            .id(null)
            .build();
    Assertions.assertThat(policiesValidator.validate(scalingPolicy) == true);
}
 
Example 14
Source File: AbstractCommandResultsAssert.java    From ts-reaktive with MIT License 4 votes vote down vote up
/**
 * Asserts there is a validation error, and allows further assertions on it.
 */
public AbstractObjectAssert<?,?> validationError() {
    return Assertions.assertThat(validationError(Object.class));
}
 
Example 15
Source File: TestListResolverAssert.java    From smart-testing with Apache License 2.0 4 votes vote down vote up
public IterableAssert<ResolvedTest> excludedPatterns() {
    isNotNull();

    return Assertions.assertThat(actual.getExcludedPatterns());
}
 
Example 16
Source File: TurnoverReportingConfig_Test.java    From estatio with Apache License 2.0 4 votes vote down vote up
@Test
public void isActiveOnDate_works(){

    // given
    final LocalDate inspectionDateBeforeStartDate = new LocalDate(2019,1,1);
    final LocalDate configStartDate = new LocalDate(2019,1,15);
    Occupancy occupancy = new Occupancy();
    Lease lease = new LeaseForTesting();
    occupancy.setLease(lease);
    occupancy.setEndDate(configStartDate.plusDays(1));

    TurnoverReportingConfig config = new TurnoverReportingConfig();
    config.setOccupancy(occupancy);
    config.setStartDate(configStartDate);

    // when
    config.setFrequency(Frequency.DAILY);
    // then
    Assertions.assertThat(config.isActiveOnDate(inspectionDateBeforeStartDate)).isFalse();

    // when
    config.setFrequency(Frequency.MONTHLY);
    // then
    Assertions.assertThat(config.isActiveOnDate(inspectionDateBeforeStartDate)).isTrue();

    // when
    config.setFrequency(Frequency.YEARLY);
    // then
    Assertions.assertThat(config.isActiveOnDate(inspectionDateBeforeStartDate)).isTrue();

    // given
    final LocalDate inspectionDateAfterDerivedEndDate = new LocalDate(2019,1,17);
    Assertions.assertThat(config.getEndDate().isBefore(inspectionDateAfterDerivedEndDate));

    // when
    config.setFrequency(Frequency.DAILY);
    // then
    Assertions.assertThat(config.isActiveOnDate(inspectionDateAfterDerivedEndDate)).isFalse();

    // when
    config.setFrequency(Frequency.MONTHLY);
    // then
    Assertions.assertThat(config.isActiveOnDate(inspectionDateAfterDerivedEndDate)).isFalse();

    // when
    config.setFrequency(Frequency.YEARLY);
    // then
    Assertions.assertThat(config.isActiveOnDate(inspectionDateAfterDerivedEndDate)).isFalse();

}
 
Example 17
Source File: DependencyAssertion.java    From smart-testing with Apache License 2.0 4 votes vote down vote up
public ListAssert<Exclusion> exclusions() {
    isNotNull();
    return Assertions.assertThat(actual.getExclusions());
}
 
Example 18
Source File: BuildRecordProviderTest.java    From pnc with Apache License 2.0 4 votes vote down vote up
@Test
public void graphShouldContainRunningDependent() {
    // given
    MockitoAnnotations.initMocks(this);
    List<BuildTask> submittedTasks = new ArrayList<>();

    BuildTask runningTask = Mockito.mock(BuildTask.class); // id = 1
    BuildTask runningDependency = Mockito.mock(BuildTask.class); // id = 2
    BuildRecord completedDependencyDependency = Mockito.mock(BuildRecord.class); // id = 3

    when(runningTask.getSubmitTime()).thenReturn(new Date());
    mockMethods(null, runningTask, 1);
    when(runningTask.getDependencies()).thenReturn(asSet(runningDependency));

    mockMethods(null, runningDependency, 2);
    when(runningDependency.getDependants()).thenReturn(asSet(runningTask));

    when(completedDependencyDependency.getId()).thenReturn(3);
    when(completedDependencyDependency.getDependentBuildRecordIds()).thenReturn(new Integer[] { 2 });
    when(completedDependencyDependency.getDependencyBuildRecordIds()).thenReturn(new Integer[] {});

    BuildConfiguration buildConfiguration = BuildConfiguration.Builder.newBuilder().build();
    BuildConfigurationAudited buildConfigurationAudited = BuildConfigurationAudited.Builder.newBuilder()
            .buildConfiguration(buildConfiguration)
            .build();

    when(buildConfigurationAuditedRepository.queryById(any(IdRev.class))).thenReturn(buildConfigurationAudited);

    when(buildRecordRepository.findByIdFetchProperties(3)).thenReturn(completedDependencyDependency);
    when(buildRecordRepository.queryById(3)).thenReturn(completedDependencyDependency);
    when(buildRecordRepository.getDependencyGraph(anyInt())).thenCallRealMethod();

    submittedTasks.add(runningTask);
    submittedTasks.add(runningDependency);
    when(buildCoordinator.getSubmittedBuildTasks()).thenReturn(submittedTasks);

    // bad dependency, it should be refactored
    BuildExecutionConfiguration buildExecutionConfiguration = new DefaultBuildExecutionConfiguration(
            2,
            "",
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            true,
            null,
            null,
            null,
            null,
            false,
            null,
            null,
            true,
            null);
    BuildExecutionSessionMock executionSession = new BuildExecutionSessionMock(
            buildExecutionConfiguration,
            (v) -> {});
    executionSession.setStatus(BuildExecutionStatus.REPO_SETTING_UP);
    when(buildExecutor.getRunningExecution(anyInt())).thenReturn(executionSession);

    // when
    GraphWithMetadata<BuildRecordRest, Integer> graph = buildRecordProvider.getDependencyGraph(3);

    // then
    Assertions.assertThat(graph.getGraph().getVerticies().size()).isEqualTo(3);
    Assertions
            .assertThat(graph.getGraph().getVerticies().stream().map(Vertex::getName).collect(Collectors.toList()))
            .containsExactlyInAnyOrder("1", "2", "3");
    Assertions.assertThat(graph.getMissingNodeIds().isEmpty());

    Assertions.assertThat(graph.getGraph().getEdges().size()).isEqualTo(2);
}
 
Example 19
Source File: AbstractCommandResultsAssert.java    From ts-reaktive with MIT License 2 votes vote down vote up
/**
 * Asserts the Results are not already applied, and performs further assertions on the emitted events.
 * Useful for subclasses for concrete Results implementations that have a fixed message type.
 */
public AbstractIterableAssert<?, ? extends Iterable<? extends E>, E> events() {
    return Assertions.assertThat(getEvents());
}
 
Example 20
Source File: AbstractCommandResultsAssert.java    From ts-reaktive with MIT License 2 votes vote down vote up
/**
 * Asserts the results are valid and already applied, and performs further assertions on the reply message.
 *
 * It is recommended that subclasses declare a more specific overload of this method, e.g.
 * <pre>
 *    public AbstractObjectAssert<?, MyResponseType> idempotentReply() {
 *      return Assertions.assertThat(idempotentReply(MyResponseType.class));
 *    }
 * </pre>
 */
public AbstractObjectAssert<?,?> idempotentReply() {
    return Assertions.assertThat(idempotentReply(Object.class));
}