org.assertj.core.api.AssertionsForClassTypes Java Examples

The following examples show how to use org.assertj.core.api.AssertionsForClassTypes. 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: BytesValueRLPInputTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ReturnValueIgnored")
@Test
public void decodeValueWithLeadingZerosAsScalar() {
  String value = "0x8200D0";

  List<Function<RLPInput, Object>> invalidDecoders =
      Arrays.asList(
          RLPInput::readBigIntegerScalar,
          RLPInput::readIntScalar,
          RLPInput::readLongScalar,
          RLPInput::readUInt256Scalar);

  for (Function<RLPInput, Object> decoder : invalidDecoders) {
    RLPInput in = RLP.input(h(value));
    AssertionsForClassTypes.assertThatThrownBy(() -> decoder.apply(in))
        .isInstanceOf(MalformedRLPInputException.class)
        .hasMessageContaining("Invalid scalar");
  }
}
 
Example #2
Source File: InMemoryRateLimiterRegistryTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateRateLimiterRegistryWithRegistryStore() {
    RegistryEventConsumer<RateLimiter> registryEventConsumer = getNoOpsRegistryEventConsumer();
    List<RegistryEventConsumer<RateLimiter>> registryEventConsumers = new ArrayList<>();
    registryEventConsumers.add(registryEventConsumer);
    Map<String, RateLimiterConfig> configs = new HashMap<>();
    final RateLimiterConfig defaultConfig = RateLimiterConfig.ofDefaults();
    configs.put("default", defaultConfig);
    final InMemoryRateLimiterRegistry inMemoryRateLimiterRegistry =
        new InMemoryRateLimiterRegistry(configs, registryEventConsumers,
            io.vavr.collection.HashMap.of("Tag1", "Tag1Value"), new InMemoryRegistryStore());

    AssertionsForClassTypes.assertThat(inMemoryRateLimiterRegistry).isNotNull();
    AssertionsForClassTypes.assertThat(inMemoryRateLimiterRegistry.getDefaultConfig()).isEqualTo(defaultConfig);
    AssertionsForClassTypes.assertThat(inMemoryRateLimiterRegistry.getConfiguration("testNotFound")).isEmpty();
    inMemoryRateLimiterRegistry.addConfiguration("testConfig", defaultConfig);
    AssertionsForClassTypes.assertThat(inMemoryRateLimiterRegistry.getConfiguration("testConfig")).isNotNull();
}
 
Example #3
Source File: FixedThreadPoolBulkheadTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateThreadPoolBulkheadRegistryWithRegistryStore() {
    RegistryEventConsumer<ThreadPoolBulkhead> registryEventConsumer = getNoOpsRegistryEventConsumer();
    List<RegistryEventConsumer<ThreadPoolBulkhead>> registryEventConsumers = new ArrayList<>();
    registryEventConsumers.add(registryEventConsumer);
    Map<String, ThreadPoolBulkheadConfig> configs = new HashMap<>();
    final ThreadPoolBulkheadConfig defaultConfig = ThreadPoolBulkheadConfig.ofDefaults();
    configs.put("default", defaultConfig);
    final InMemoryThreadPoolBulkheadRegistry inMemoryThreadPoolBulkheadRegistry =
        new InMemoryThreadPoolBulkheadRegistry(configs, registryEventConsumers,
            io.vavr.collection.HashMap.of("Tag1", "Tag1Value"), new InMemoryRegistryStore());

    AssertionsForClassTypes.assertThat(inMemoryThreadPoolBulkheadRegistry).isNotNull();
    AssertionsForClassTypes.assertThat(inMemoryThreadPoolBulkheadRegistry.getDefaultConfig()).isEqualTo(defaultConfig);
    AssertionsForClassTypes.assertThat(inMemoryThreadPoolBulkheadRegistry.getConfiguration("testNotFound")).isEmpty();
    inMemoryThreadPoolBulkheadRegistry.addConfiguration("testConfig", defaultConfig);
    AssertionsForClassTypes.assertThat(inMemoryThreadPoolBulkheadRegistry.getConfiguration("testConfig")).isNotNull();
}
 
Example #4
Source File: SemaphoreBulkheadTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateBulkheadRegistryWithRegistryStore() {
    RegistryEventConsumer<Bulkhead> registryEventConsumer = getNoOpsRegistryEventConsumer();
    List<RegistryEventConsumer<Bulkhead>> registryEventConsumers = new ArrayList<>();
    registryEventConsumers.add(registryEventConsumer);
    Map<String, BulkheadConfig> configs = new HashMap<>();
    final BulkheadConfig defaultConfig = BulkheadConfig.ofDefaults();
    configs.put("default", defaultConfig);
    final InMemoryBulkheadRegistry inMemoryBulkheadRegistry =
        new InMemoryBulkheadRegistry(configs, registryEventConsumers,
            io.vavr.collection.HashMap.of("Tag1", "Tag1Value"), new InMemoryRegistryStore());

    AssertionsForClassTypes.assertThat(inMemoryBulkheadRegistry).isNotNull();
    AssertionsForClassTypes.assertThat(inMemoryBulkheadRegistry.getDefaultConfig()).isEqualTo(defaultConfig);
    AssertionsForClassTypes.assertThat(inMemoryBulkheadRegistry.getConfiguration("testNotFound")).isEmpty();
    inMemoryBulkheadRegistry.addConfiguration("testConfig", defaultConfig);
    AssertionsForClassTypes.assertThat(inMemoryBulkheadRegistry.getConfiguration("testConfig")).isNotNull();
}
 
Example #5
Source File: BytesValueRLPInputTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void rlpItemSizeOverflowsSignedInt() {
  // Size value encoded in 4 bytes but exceeds max positive int value
  AssertionsForClassTypes.assertThatThrownBy(() -> RLP.input(h("0xBB80000000")))
      .isInstanceOf(RLPException.class)
      .hasMessageContaining(
          "RLP item at offset 1 with size value consuming 4 bytes exceeds max supported size of 2147483647");
}
 
Example #6
Source File: ArtifactTest.java    From kork with Apache License 2.0 5 votes vote down vote up
@Test
void serializeComplexMetadata() throws IOException {
  Artifact artifact =
      Artifact.builder().putMetadata("test", ImmutableMap.of("nested", "abc")).build();
  JsonNode expectedNode =
      jsonFactory.objectNode().set("test", jsonFactory.objectNode().put("nested", "abc"));

  String result = objectMapper.writeValueAsString(artifact);
  JsonNode resultNode = objectMapper.readTree(result).at("/metadata");
  AssertionsForClassTypes.assertThat(resultNode).isEqualTo(expectedNode);
}
 
Example #7
Source File: ArtifactTest.java    From kork with Apache License 2.0 5 votes vote down vote up
@Test
void serializeAllFieldsSnake() throws IOException {
  String result = snakeObjectMapper.writeValueAsString(fullArtifact());
  String expected = fullArtifactJson();

  // Compare the parsed trees of the two results, which is agnostic to key order
  AssertionsForClassTypes.assertThat(objectMapper.readTree(result))
      .isEqualTo(objectMapper.readTree(expected));
}
 
Example #8
Source File: ArtifactTest.java    From kork with Apache License 2.0 5 votes vote down vote up
@Test
void serializeAllFields() throws IOException {
  String result = objectMapper.writeValueAsString(fullArtifact());
  String expected = fullArtifactJson();

  // Compare the parsed trees of the two results, which is agnostic to key order
  AssertionsForClassTypes.assertThat(objectMapper.readTree(result))
      .isEqualTo(objectMapper.readTree(expected));
}
 
Example #9
Source File: ExpectedArtifactTest.java    From kork with Apache License 2.0 5 votes vote down vote up
@Test
void serializeAllFields() throws IOException {
  String result = objectMapper.writeValueAsString(fullExpectedArtifact());
  String expected = fullExpectedArtifactJson();

  // Compare the parsed trees of the two results, which is agnostic to key order
  AssertionsForClassTypes.assertThat(objectMapper.readTree(result))
      .isEqualTo(objectMapper.readTree(expected));
}
 
Example #10
Source File: ResultMatchers.java    From coderadar with MIT License 5 votes vote down vote up
/**
 * Tests if the response contains the JSON representation of an object of the given type.
 *
 * @param typeReference the type of the expected object.
 * @param <T> the type of the expected object.
 * @return ResultMatcher that performs the test described above.
 */
public static <T> ResultMatcher containsResource(TypeReference<T> typeReference) {
  return result -> {
    String json = result.getResponse().getContentAsString();
    try {
      T object = JsonHelper.fromJson(json, typeReference);
      AssertionsForClassTypes.assertThat(object).isNotNull();
    } catch (Exception e) {
      throw new RuntimeException(
          String.format(
              "expected JSON representation of class %s but found '%s'", typeReference, json),
          e);
    }
  };
}
 
Example #11
Source File: ResultMatchers.java    From coderadar with MIT License 5 votes vote down vote up
/**
 * Tests if the response contains the JSON representation of an object of the given type.
 *
 * @param clazz the class of the expected object.
 * @param <T> the type of the expected object.
 * @return ResultMatcher that performs the test described above.
 */
public static <T> ResultMatcher containsResource(Class<T> clazz) {
  return result -> {
    String json = result.getResponse().getContentAsString();
    try {
      T object = fromJson(json, clazz);
      AssertionsForClassTypes.assertThat(object).isNotNull();
    } catch (Exception e) {
      throw new RuntimeException(
          String.format("expected JSON representation of class %s but found '%s'", clazz, json),
          e);
    }
  };
}
 
Example #12
Source File: CarManufacturerTest.java    From Architecting-Modern-Java-EE-Applications with MIT License 5 votes vote down vote up
@Test
public void test() {
    Specification spec = new Specification();
    Car expected = new Car(spec);
    AssertionsForClassTypes.assertThat(carManufacture.manufactureCar(spec)).isEqualTo(expected);

    carManufacture.verifyManufacture(expected);
    carFactory.verifyCarCreation(spec);
}
 
Example #13
Source File: CliqueGetSignersAtHashTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void failsWhenNoParam() {
  final JsonRpcRequestContext request =
      new JsonRpcRequestContext(
          new JsonRpcRequest("2.0", "clique_getSignersAtHash", new Object[] {}));

  final Throwable thrown = AssertionsForClassTypes.catchThrowable(() -> method.response(request));

  assertThat(thrown)
      .isInstanceOf(InvalidJsonRpcParameters.class)
      .hasMessage("Missing required json rpc parameter at index 0");
}
 
Example #14
Source File: BytesValueRLPInputTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void rlpListSizeOverflowsInt() {
  // Size value is encoded with 5 bytes - overflowing int
  AssertionsForClassTypes.assertThatThrownBy(() -> RLP.input(h("0xFC0100000000")))
      .isInstanceOf(RLPException.class)
      .hasMessageContaining(
          "RLP item at offset 1 with size value consuming 5 bytes exceeds max supported size of 2147483647");
}
 
Example #15
Source File: BytesValueRLPInputTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void rlpListSizeOverflowsSignedInt() {
  // Size value encoded in 4 bytes but exceeds max positive int value
  AssertionsForClassTypes.assertThatThrownBy(() -> RLP.input(h("0xFB80000000")))
      .isInstanceOf(RLPException.class)
      .hasMessageContaining(
          "RLP item at offset 1 with size value consuming 4 bytes exceeds max supported size of 2147483647");
}
 
Example #16
Source File: BytesValueRLPInputTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void rlpListSizeHoldsMaxValue() {
  // Size value encode max positive int.  So, size is decoded, but
  // RLP is malformed because the actual payload is not present
  AssertionsForClassTypes.assertThatThrownBy(() -> RLP.input(h("0xFB7FFFFFFF")).readBytes())
      .isInstanceOf(CorruptedRLPInputException.class)
      .hasMessageContaining(
          "Input doesn't have enough data for RLP encoding: encoding advertise a payload ending at byte 2147483652 but input has size 5");
}
 
Example #17
Source File: BytesValueRLPInputTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void rlpItemSizeOverflowsInt() {
  // Size value is encoded with 5 bytes - overflowing int
  AssertionsForClassTypes.assertThatThrownBy(() -> RLP.input(h("0xBC0100000000")))
      .isInstanceOf(RLPException.class)
      .hasMessageContaining(
          "RLP item at offset 1 with size value consuming 5 bytes exceeds max supported size of 2147483647");
}
 
Example #18
Source File: BytesValueRLPInputTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void rlpItemSizeHoldsMaxValue() {
  // Size value encode max positive int.  So, size is decoded, but
  // RLP is malformed because the actual payload is not present
  AssertionsForClassTypes.assertThatThrownBy(() -> RLP.input(h("0xBB7FFFFFFF")).readBytes())
      .isInstanceOf(CorruptedRLPInputException.class)
      .hasMessageContaining("payload should start at offset 5 but input has only 5 bytes");
}
 
Example #19
Source File: PreAuthenticatedAuthenticationProviderTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void getType() {
    final AuthorizationContextType type = underTest.getType(mockRequestContext(DUMMY_AUTH_HEADER, DUMMY_AUTH_QUERY));

    AssertionsForClassTypes.assertThat(type).isEqualTo(DittoAuthorizationContextType.PRE_AUTHENTICATED_HTTP);
}
 
Example #20
Source File: JwtAuthenticationProviderTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void getType() {
    AssertionsForClassTypes.assertThat(underTest.getType(mockRequestContext(VALID_AUTHORIZATION_HEADER)))
            .isEqualTo(DittoAuthorizationContextType.JWT);
}
 
Example #21
Source File: SupportUtilTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void createSupportZipFileTest() throws IOException {
    final NamespacedOpenShiftClient client = mock(NamespacedOpenShiftClient.class);

    final MixedOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> pods = mock(mixedOperationType());
    when(pods.list()).thenReturn(new PodList());

    when(client.pods()).thenReturn(pods);

    final MixedOperation<BuildConfig, BuildConfigList, DoneableBuildConfig, BuildConfigResource<BuildConfig, DoneableBuildConfig, Void, Build>> bcs = mock(
        mixedOperationType());
    when(bcs.list()).thenReturn(new BuildConfigList());

    when(client.buildConfigs()).thenReturn(bcs);

    final MixedOperation<DeploymentConfig, DeploymentConfigList, DoneableDeploymentConfig, DeployableScalableResource<DeploymentConfig, DoneableDeploymentConfig>> dcs = mock(
        mixedOperationType());
    when(dcs.list()).thenReturn(new DeploymentConfigList());

    when(client.deploymentConfigs()).thenReturn(dcs);

    final MixedOperation<ConfigMap, ConfigMapList, DoneableConfigMap, Resource<ConfigMap, DoneableConfigMap>> cm = mock(mixedOperationType());
    when(cm.list()).thenReturn(new ConfigMapList());

    when(client.configMaps()).thenReturn(cm);

    final MixedOperation<ImageStreamTag, ImageStreamTagList, DoneableImageStreamTag, Resource<ImageStreamTag, DoneableImageStreamTag>> ist = mock(
        mixedOperationType());
    final ImageStreamTagList istl = new ImageStreamTagList();
    final List<ImageStreamTag> istList = new ArrayList<>();
    final ImageStreamTag imageStreamTag = new ImageStreamTag();
    imageStreamTag.setKind("ImageStreamTag");
    final ObjectMeta objectMeta = new ObjectMeta();
    objectMeta.setName("ImageStreamTag1");
    imageStreamTag.setMetadata(objectMeta);
    istList.add(imageStreamTag);
    istl.setItems(istList);

    when(ist.list()).thenReturn(istl);

    when(client.imageStreamTags()).thenReturn(ist);

    final IntegrationHandler integrationHandler = mock(IntegrationHandler.class);
    when(integrationHandler.list(anyInt(), anyInt())).thenReturn(new EmptyListResult<IntegrationOverview>());
    final IntegrationSupportHandler integrationSupportHandler = mock(IntegrationSupportHandler.class);

    final Logger log = mock(Logger.class);
    final SupportUtil supportUtil = new SupportUtil(client, integrationHandler, integrationSupportHandler, log);

    final Map<String, Boolean> configurationMap = new HashMap<>(ImmutableMap.of("int1", true, "int2", true));

    final File output = supportUtil.createSupportZipFile(configurationMap, 1, 20);

    try (final ZipFile zip = new ZipFile(output)) {
        final ZipEntry imageStreamTag1 = zip.getEntry("descriptors/ImageStreamTag/ImageStreamTag1.YAML");
        assertThat(imageStreamTag1).isNotNull();
        AssertionsForClassTypes.assertThat(zip.getInputStream(imageStreamTag1)).hasContent(SupportUtil.YAML.dump(imageStreamTag));
    }

    verify(log).info("Created Support file: {}", output);
    // tests that we haven't logged any error messages
    verifyZeroInteractions(log);
}
 
Example #22
Source File: StoreReaderTest.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
/**
 * Tests for {@link StoreReader}
 */
@Test(groups = "unit")
public void startBackgroundAddressRefresh() throws Exception {
    TransportClient transportClient = Mockito.mock(TransportClient.class);
    AddressSelector addressSelector = Mockito.mock(AddressSelector.class);
    ISessionContainer sessionContainer = Mockito.mock(ISessionContainer.class);

    StoreReader storeReader = new StoreReader(transportClient, addressSelector, sessionContainer);

    CyclicBarrier b = new CyclicBarrier(2);
    PublishSubject<List<Uri>> subject = PublishSubject.create();
    CountDownLatch c = new CountDownLatch(1);

    List<Uri> uris = ImmutableList.of(Uri.create("https://localhost:5050"), Uri.create("https://localhost:5051"),
                                      Uri.create("https://localhost:50502"), Uri.create("https://localhost:5053"));

    Mockito.doAnswer(new Answer() {
        @Override
        public Single<List<Uri>> answer(InvocationOnMock invocationOnMock) throws Throwable {

            return subject.toSingle().doOnSuccess(x -> c.countDown()).doAfterTerminate(() -> {
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            b.await();
                        } catch (Exception e) {

                        }
                    }
                }.start();
            });
        }
    }).when(addressSelector).resolveAllUriAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.eq(true), Mockito.eq(true));
    RxDocumentServiceRequest request = Mockito.mock(RxDocumentServiceRequest.class);
    storeReader.startBackgroundAddressRefresh(request);

    subject.onNext(uris);
    subject.onCompleted();

    TimeUnit.MILLISECONDS.sleep(100);
    AssertionsForClassTypes.assertThat(c.getCount()).isEqualTo(0);
    AssertionsForClassTypes.assertThat(b.getNumberWaiting()).isEqualTo(1);
    b.await(1000, TimeUnit.MILLISECONDS);
}