org.assertj.core.api.Condition Java Examples

The following examples show how to use org.assertj.core.api.Condition. 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: MavenBuildAssert.java    From initializr with Apache License 2.0 7 votes vote down vote up
/**
 * Assert {@code pom.xml} defines the specified repository.
 * @param id the id of the repository
 * @param name the name of the repository
 * @param url the url of the repository
 * @param snapshotsEnabled whether snapshot is enabled for the repository
 * @return {@code this} assertion object
 */
public MavenBuildAssert hasRepository(String id, String name, String url, Boolean snapshotsEnabled) {
	this.pom.nodesAtPath("/project/repositories/repository").areExactly(1, new Condition<>((candidate) -> {
		String actualId = ((Element) candidate).getElementsByTagName("id").item(0).getTextContent();
		if (actualId.equals(id)) {
			Repository repository = toRepository(candidate);
			if (name != null) {
				new StringAssert(repository.getName()).isEqualTo(name);
			}
			if (url != null) {
				try {
					new UrlAssert(repository.getUrl()).isEqualTo(new URL(url));
				}
				catch (MalformedURLException ex) {
					throw new IllegalArgumentException("Cannot parse URL", ex);
				}
			}
			if (snapshotsEnabled) {
				new BooleanAssert(repository.isSnapshotsEnabled()).isEqualTo(snapshotsEnabled);
			}
			return true;
		}
		return false;
	}, "matching repository"));
	return this;
}
 
Example #2
Source File: OrderServiceImplTest.java    From pizzeria with MIT License 6 votes vote down vote up
@Test
public void shouldPostOrder() throws Exception {
    // given
    Order order = new Order();
    String trackingNumber = "42";
    Long orderId = 42L;

    when(trackingNumberGenerationStrategy.generatetrackingNumber(order)).thenReturn(trackingNumber);
    when(orderDAO.saveOrUpdate(order)).thenAnswer(invocation -> {
        order.setId(orderId);
        return order;
    });

    // when
    Order result = orderService.postOrder(order);

    // then
    assertThat(result.getId()).isEqualTo(orderId);
    assertThat(result.getTrackingNumber()).isEqualTo(trackingNumber);
    Condition<OrderEvent> purchaseEvent = new Condition<>(orderEvent -> orderEvent.getOrderEventType() == OrderEventType.PURCHASED, "purchase event");
    assertThat(result.getOrderEvents()).first().is(purchaseEvent);
}
 
Example #3
Source File: AddressSelectorWrapper.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
VerifierBuilder resolveAllUriAsync(Condition<RxDocumentServiceRequest> requestMatcher, Condition<Boolean> includePrimaryMatcher, Condition<Boolean> forceRefreshMatcher) {
    methodName(resolveAllUriAsync);
    add(new Verifier() {
        @Override
        public void verify(InvocationOnMock invocation) {
            RxDocumentServiceRequest request = invocation.getArgumentAt(0, RxDocumentServiceRequest.class);
            boolean includePrimary = invocation.getArgumentAt(1, Boolean.class);
            boolean forceRefresh = invocation.getArgumentAt(2, Boolean.class);

            assertThat(request).is(requestMatcher);

            assertThat(includePrimary).is(includePrimaryMatcher);
            assertThat(forceRefresh).is(forceRefreshMatcher);
        }
    });
    return this;
}
 
Example #4
Source File: ArrayOperationsUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenShufflingIntArraySeveralTimes_thenAtLeastOneWithDifferentOrder() {
    int[] output = ArrayOperations.shuffleIntArray(defaultIntArray);
    int[] output2 = ArrayOperations.shuffleIntArray(defaultIntArray);
    int[] output3 = ArrayOperations.shuffleIntArray(defaultIntArray);
    int[] output4 = ArrayOperations.shuffleIntArray(defaultIntArray);
    int[] output5 = ArrayOperations.shuffleIntArray(defaultIntArray);
    int[] output6 = ArrayOperations.shuffleIntArray(defaultIntArray);

    Condition<int[]> atLeastOneArraysIsNotEqual = new Condition<int[]>("at least one output should be different (order-wise)") {
        @Override
        public boolean matches(int[] value) {
            return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3) || !Arrays.equals(value, output4) || !Arrays.equals(value, output5) || !Arrays.equals(value, output6);
        }
    };

    assertThat(defaultIntArray).has(atLeastOneArraysIsNotEqual);
}
 
Example #5
Source File: FluxUsingTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void sourceFactoryAndResourceCleanupThrow() {
	RuntimeException sourceEx = new IllegalStateException("sourceFactory");
	RuntimeException cleanupEx = new IllegalStateException("resourceCleanup");

	Condition<? super Throwable> suppressingFactory = new Condition<>(
			e -> {
				Throwable[] suppressed = e.getSuppressed();
				return suppressed != null && suppressed.length == 1 && suppressed[0] == sourceEx;
			}, "suppressing <%s>", sourceEx);

	Flux<String> test = new FluxUsing<>(() -> "foo",
			o -> { throw sourceEx; },
			s -> { throw cleanupEx; },
			false);

	StepVerifier.create(test)
	            .verifyErrorSatisfies(e -> assertThat(e)
			            .hasMessage("resourceCleanup")
			            .is(suppressingFactory));

}
 
Example #6
Source File: DistributionSetManagementTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Verifies that multiple DS are of default type if not specified explicitly at creation time.")
public void createMultipleDistributionSetsWithImplicitType() {

    final List<DistributionSetCreate> creates = Lists.newArrayListWithExpectedSize(10);
    for (int i = 0; i < 10; i++) {
        creates.add(entityFactory.distributionSet().create().name("newtypesoft" + i).version("1" + i));
    }

    final List<DistributionSet> sets = distributionSetManagement.create(creates);

    assertThat(sets).as("Type should be equal to default type of tenant").are(new Condition<DistributionSet>() {
        @Override
        public boolean matches(final DistributionSet value) {
            return value.getType().equals(systemManagement.getTenantMetadata().getDefaultDsType());
        }
    });

}
 
Example #7
Source File: FeedItemCardSpecTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeepSubComponents() {
  final ComponentContext c = mComponentsRule.getContext();

  // N.B. This manual way of testing is not recommended and will be replaced by more high-level
  // matchers, but illustrates how it can be used in case more fine-grained assertions are
  // required.
  assertThat(c, mComponent)
      .extractingSubComponentAt(0)
      .extractingSubComponentsDeeply(c)
      .hasSize(22) // TODO: T53372437 Remove or rewrite test.
      .has(
          new Condition<InspectableComponent>() {
            @Override
            public boolean matches(InspectableComponent value) {
              describedAs(value.getComponentClass() + " with text " + value.getTextContent());
              return value.getComponentClass() == Text.class
                  && "JavaScript Rockstar".equals(value.getTextContent());
            }
          },
          atIndex(10));
}
 
Example #8
Source File: BuildConfigurationEndpointTest.java    From pnc with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetConflictWhenCreatingNewBuildConfigurationWithTheSameNameAndProjectId() throws ClientException {
    BuildConfigurationClient client = new BuildConfigurationClient(RestClientConfiguration.asUser());

    BuildConfiguration bc = client.getSpecific(configurationId);

    BuildConfiguration duplicate = BuildConfiguration.builder()
            .name(bc.getName())
            .buildScript(bc.getBuildScript())
            .project(bc.getProject())
            .environment(bc.getEnvironment())
            .parameters(bc.getParameters())
            .scmRepository(bc.getScmRepository())
            .buildType(bc.getBuildType())
            .build();

    assertThatThrownBy(() -> client.createNew(duplicate)).hasCauseInstanceOf(ClientErrorException.class)
            .has(
                    new Condition<Throwable>(
                            (e -> ((ClientErrorException) e.getCause()).getResponse().getStatus() == 409),
                            "HTTP 409 Conflict"));
}
 
Example #9
Source File: ArrayOperationsUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenShufflingObjectArraySeveralTimes_thenAtLeastOneWithDifferentOrder() {
    Integer[] output = ArrayOperations.shuffleObjectArray(defaultObjectArray);
    Integer[] output2 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
    Integer[] output3 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
    Integer[] output4 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
    Integer[] output5 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
    Integer[] output6 = ArrayOperations.shuffleObjectArray(defaultObjectArray);

    Condition<Integer[]> atLeastOneArraysIsNotEqual = new Condition<Integer[]>("at least one output should be different (order-wise)") {
        @Override
        public boolean matches(Integer[] value) {
            return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3) || !Arrays.equals(value, output4) || !Arrays.equals(value, output5) || !Arrays.equals(value, output6);
        }
    };

    assertThat(defaultObjectArray).has(atLeastOneArraysIsNotEqual);
}
 
Example #10
Source File: GroupConfigurationProviderTest.java    From pnc with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveConfiguration() {
    // With
    org.jboss.pnc.dto.GroupConfiguration groupConfiguration = provider.getSpecific("1"); //
    BuildConfiguration toRemove = bcs.getBuildConfigurations().stream().findFirst().get();
    when(buildConfigurationRepository.queryById(Integer.valueOf(toRemove.getId()))).thenReturn(toRemove);
    assertThat(groupConfiguration.getBuildConfigs()).containsKey(toRemove.getId().toString());

    // When
    provider.removeConfiguration(groupConfiguration.getId(), toRemove.getId().toString());

    // Then
    org.jboss.pnc.dto.GroupConfiguration refreshed = provider.getSpecific(groupConfiguration.getId());
    assertThat(refreshed.getBuildConfigs().values())
            .doNotHave(new Condition<>(toRemove::equals, "BC is equal to 'toRemove' bc"));
}
 
Example #11
Source File: CamelLanguageServerCompletionPositionTest.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest(name="{6} - Position ({1},{2})")
   @MethodSource("data")
void testProvideCompletionForCamelBlueprintNamespace(
		String textToTest,
		int line,
		int characterCallingCompletion,
		int characterStartCompletion,
		int characterEndCompletion,
		boolean shouldHaveCompletion,
		String testNameQualification) throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer(textToTest);
	
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, new Position(line, characterCallingCompletion));
	
	if(shouldHaveCompletion) {
		assertThat(completions.get().getLeft()).contains(createExpectedAhcCompletionItem(line, characterStartCompletion, line, characterEndCompletion));
	} else {
		Condition<CompletionItem> ahc = new Condition<>(completionItem -> completionItem.getLabel().contains("ahc"), "Found an ahc component");
		assertThat(completions.get().getLeft().stream()).areNot(ahc);
		assertThat(completions.get().getRight()).isNull();
	}
}
 
Example #12
Source File: StepDefinitions.java    From blog with MIT License 6 votes vote down vote up
@Given("^L'entrepôt contient les Personnes suivantes$")
public void l_entrepôt_contient_les_Personnes_suivantes(DataTable expected)
		throws Throwable {
	givenPersonSize = personRepositoryToTest.count();
	// L'entrepôt contient les Personnes suivantes
	List<PersonModel> actual = personRepositoryToTest.readAll();
	for (final PersonModel exp : expected.asList(PersonModel.class)) {
		assertThat(actual).haveExactly(1, new Condition<PersonModel>() {

			@Override
			public boolean matches(PersonModel act) {
				return act.getId().equals(exp.getId()) //
						&& act.getPrenom().equals(exp.getPrenom()) //
						&& act.getNom().equals(exp.getNom()) //
						&& act.getNaissance().equals(exp.getNaissance());
			}
		});
	}
}
 
Example #13
Source File: IntegrationLoggingDisabledTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void testDisabledContextConfiguration() throws Exception {
    DefaultCamelContext context = new DefaultCamelContext();

    Properties properties = new Properties();

    PropertiesComponent pc = new PropertiesComponent();
    pc.setInitialProperties(properties);
    context.setPropertiesComponent(pc);

    RuntimeSupport.configureContextCustomizers(context);

    context.start();

    assertThat(context.getLogListeners()).have(new Condition<LogListener>() {
        @Override
        public boolean matches(LogListener value) {
            return !(value instanceof IntegrationLoggingListener);
        }
    });

    assertThat(context.getUuidGenerator()).isInstanceOf(DefaultUuidGenerator.class);

    context.stop();
}
 
Example #14
Source File: ColumnsParametersParserTest.java    From springlets with Apache License 2.0 5 votes vote down vote up
@Test
public void checkColumnsParametersAreParsed() {
  // Prepare
  parser = createParser(
      new String[] {"columns[0][data]", "columns[0][name]", "columns[0][orderable]",
          "columns[0][searchable]", "columns[0][search][value]", "columns[0][search][regex]",
          "columns[1][data]", "columns[1][name]", "columns[1][orderable]",
          "columns[1][searchable]", "columns[1][search][value]", "columns[1][search][regex]"},
      new String[] {"data0", "name0", "true", "true", "search0", "true", "data1", "name1",
          "false", "false", "search1", "false"});

  // Exercise
  DatatablesColumns columns = parser.getColumns();

  // Validate
  assertThat(columns.getColumns()).areExactly(2, new Condition<Column>() {

    @Override
    public boolean matches(Column value) {
      switch (value.getIndex()) {
        case 0:
          return value.getData().equals("data0") && value.getName().equals("name0")
              && value.isOrderable() && value.isSearchable()
              && value.getSearch().equals("search0") && value.isSearchRegex();
        case 1:
          return value.getData().equals("data1") && value.getName().equals("name1")
              && !value.isOrderable() && !value.isSearchable()
              && value.getSearch().equals("search1") && !value.isSearchRegex();
        default:
          return false;
      }
    }

  });
}
 
Example #15
Source File: AppKubernetesTest.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppProvisionsRunningPods() throws Exception {
    assertThat(client).replicationController("example-java-camel-cdi-controller").isNotNull();
    assertThat(client).pods()
            .runningStatus()
            .filterNamespace(session.getNamespace())
            .haveAtLeast(1, new Condition<Pod>() {
                @Override
                public boolean matches(Pod podSchema) {
                    return true;
                }
            });
}
 
Example #16
Source File: FilteredSortedListTest.java    From clean-architecture with Apache License 2.0 5 votes vote down vote up
private Condition<Item> activeOnly() {
	return new Condition<FilteredSortedListTest.Item>() {
		@Override
		public boolean matches(Item item) {
			return item.isActive();
		}
	};
}
 
Example #17
Source File: Conditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
public static <T> Condition<Iterable<? extends T>> containing(final Condition<T> condition) {
    return new Condition<Iterable<? extends T>>() {
        @Override
        public boolean matches(Iterable<? extends T> value) {
            boolean contains = false;
            for (T t : value) {
                contains = contains || condition.matches(t);
            }
            return contains;
        }
    }.as("containing an element that " + condition.description());
}
 
Example #18
Source File: ImapClientTest.java    From NioImapClient with Apache License 2.0 5 votes vote down vote up
@Test
public void testFetchBodyHeaders_doesParseHeaders() throws Exception {
  FetchResponse response = client.fetch(1, Optional.of(10L), new BodyPeekFetchDataItem("HEADER")).get();
  assertThat(response.getMessages()).have(new Condition<>(m -> {
    try {
      return !Strings.isNullOrEmpty(m.getBody().getHeader().getField("Message-ID").getBody());
    } catch (UnfetchedFieldException e) {
      throw Throwables.propagate(e);
    }
  }, "message id"));

}
 
Example #19
Source File: ExtensionIntegrationTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private static Condition<Object> containingEntry(final String propKey, final String propValue) {
    return new Condition<Object>(String.format("containing entry {%s=%s}", propKey, propValue)) {
        @Override
        public boolean matches(Object value) {
            return Objects.equals(((Map<?, ?>) value).get(propKey), propValue);
        }
    };
}
 
Example #20
Source File: StoreResponseValidator.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
public Builder withRequestChargeGreaterThanOrEqualTo(double value) {
    withHeaderValueCondition(HttpConstants.HttpHeaders.REQUEST_CHARGE, new Condition<>(s -> {
        try {
            double parsed = Double.parseDouble(s);
            return parsed >= value;
        } catch (Exception e) {
            return false;
        }
    }, "request charge should be greater than or equal to " + value));
    return this;
}
 
Example #21
Source File: Assertions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
public Condition<JavaAccess<?>> to(final Class<?> targetClass, final String targetName) {
    return new Condition<JavaAccess<?>>(
            String.format("%s from %s.%s to %s.%s",
                    JavaAccess.class.getSimpleName(),
                    originClass.getName(), originCodeUnitName,
                    targetClass.getSimpleName(), targetName)) {
        @Override
        public boolean matches(JavaAccess<?> access) {
            return access.getOriginOwner().isEquivalentTo(originClass) &&
                    access.getOrigin().getName().equals(originCodeUnitName) &&
                    access.getTargetOwner().isEquivalentTo(targetClass) &&
                    access.getTarget().getName().equals(targetName);
        }
    };
}
 
Example #22
Source File: Assertions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
public AccessesAssertion contain(Condition<? super JavaAccess<?>> condition) {
    for (Iterator<JavaAccess<?>> iterator = actualRemaining.iterator(); iterator.hasNext(); ) {
        if (condition.matches(iterator.next())) {
            iterator.remove();
            return this;
        }
    }
    throw new AssertionError("No access matches " + condition);
}
 
Example #23
Source File: GraphDimacsFileWriterTest.java    From LogicNG with Apache License 2.0 5 votes vote down vote up
private void assertFilesEqual(final File expected, final File actual) throws IOException {
  final BufferedReader expReader = new BufferedReader(new FileReader(expected));
  final BufferedReader actReader = new BufferedReader(new FileReader(actual));
  final List<String> expEdgeLines = new ArrayList<>();
  List<String> actEdgeLines = new ArrayList<>();
  List<String> expNodeLines = new ArrayList<>();
  List<String> actNodeLines = new ArrayList<>();
  for (int lineNumber = 1; expReader.ready() && actReader.ready(); lineNumber++) {
    String exp = expReader.readLine();
    String act = actReader.readLine();
    if (exp.contains("{") || exp.contains("}")) {
      softly.assertThat(act).as("Line " + lineNumber + " not equal").isEqualTo(exp);
    } else {
      if (exp.contains("-")) {
        expEdgeLines.add(exp);
      } else {
        expNodeLines.add(exp);
      }
      if (act.contains("-")) {
        actEdgeLines.add(act);
      } else {
        actNodeLines.add(act);
      }
    }
  }
  for (String actNode : actNodeLines) {
    Assert.assertTrue(expNodeLines.contains(actNode));
  }
  for (String actEdge : actEdgeLines) {
    String[] actEdgeNodes = actEdge.trim().split(" ");

    Condition<? super List<? extends String>> left = new ContainsCondition(actEdge);
    Condition<? super List<? extends String>> right = new ContainsCondition("e " + actEdgeNodes[2] + " " + actEdgeNodes[1]);
    softly.assertThat(expEdgeLines).has(Assertions.anyOf(left, right));
  }
  if (expReader.ready())
    softly.fail("Missing line(s) found, starting with \"" + expReader.readLine() + "\"");
  if (actReader.ready())
    softly.fail("Additional line(s) found, starting with \"" + actReader.readLine() + "\"");
}
 
Example #24
Source File: CustomFiltersLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * This condition will be successful if the event contains a substring, but not another one
 */
private Condition<ILoggingEvent> eventContainsExcept(String substring, String except) {
    return new Condition<ILoggingEvent>(entry -> (substring == null || (entry.getFormattedMessage() != null && entry.getFormattedMessage()
        .contains(substring)
        && !entry.getFormattedMessage()
            .contains(except))),
        String.format("entry with message '%s'", substring));
}
 
Example #25
Source File: BuildConfigProviderTest.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAll() {
    Page<org.jboss.pnc.dto.BuildConfiguration> all = provider.getAll(0, 10, null, null);

    assertThat(all.getContent()).hasSize(5)
            .haveExactly(1, new Condition<>(e -> e.getName().equals(bc.getName()), "BC Present"));
}
 
Example #26
Source File: StoreResponseValidator.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
public Builder withHeaderValueCondition(String headerKey, Condition<String> condition) {

            validators.add(new StoreResponseValidator() {
                @Override
                public void validate(StoreResponse resp) {
                    assertThat(Arrays.asList(resp.getResponseHeaderNames())).asList().contains(headerKey);
                    int index = Arrays.asList(resp.getResponseHeaderNames()).indexOf(headerKey);
                    String value = resp.getResponseHeaderValues()[index];
                    condition.matches(value);
                }
            });
            return this;
        }
 
Example #27
Source File: AddressValidator.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
public Builder withProperty(String propertyName, Condition<Object> validatingCondition) {
    validators.add(new AddressValidator() {

        @Override
        public void validate(Address address) {
            assertThat(address.get(propertyName)).is(validatingCondition);

        }
    });
    return this;
}
 
Example #28
Source File: ResourceResponseValidator.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
public Builder<T> validatePropertyCondition(String key, Condition<Object> condition) {
    validators.add(new ResourceResponseValidator<T>() {

        @Override
        public void validate(ResourceResponse<T> resourceResponse) {
            assertThat(resourceResponse.getResource()).isNotNull();
            assertThat(resourceResponse.getResource().get(key)).is(condition);

        }
    });
    return this;
}
 
Example #29
Source File: RootContractInputGeneratorTest.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private void assertEditMode(List<ContractInput> inputs,EditMode mode) {
    for(ContractInput child : inputs) {
        assertThat(child.isCreateMode()).is(new Condition<Boolean>(value -> mode == EditMode.CREATE ? value : !value, 
                "Invalid create mode"));
        assertEditMode(child.getInputs(), mode);
    }
}
 
Example #30
Source File: Conditions.java    From besu with Apache License 2.0 5 votes vote down vote up
public static Condition<Path> shouldContain(final String content) {
  return new Condition<>(
      path -> {
        try {
          return content.equals(Files.readString(path));
        } catch (IOException e) {
          return false;
        }
      },
      "File should contain specified content.");
}