org.hamcrest.collection.IsMapContaining Java Examples

The following examples show how to use org.hamcrest.collection.IsMapContaining. 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 Project: adaptive-alerting   Author: ExpediaDotCom   File: DetectorMapperTest.java    License: Apache License 2.0 7 votes vote down vote up
@Test
public void testGetDetectorsFromCache() throws IOException {

    //testing detector Mapper with actual cache
    this.detectorMapper = new DetectorMapper(detectorSource, config, new MetricRegistry());

    this.initTagsFromFile();
    //populate cache
    detectorMapper.isSuccessfulDetectorMappingLookup(listOfMetricTags);

    Map<String, List<Detector>> detectorResults = new HashMap<>();

    listOfMetricTags.forEach(tags -> {
        MetricData metricData = new MetricData(new MetricDefinition(new TagCollection(tags)), 0.0, 1L);

        List<Detector> detector = detectorMapper.getDetectorsFromCache(metricData.getMetricDefinition());
        if (!detector.isEmpty())
            detectorResults.put(CacheUtil.getKey(tags), detector);
    });

    assertThat(detectorResults.size(), is(3));
    assertThat(detectorResults, IsMapContaining.hasEntry("key->RHZGV1VodjI1aA==,name->NjFFS0JDcnd2SQ==", Collections.singletonList(buildDetector("cid", "2c49ba26-1a7d-43f4-b70c-c6644a2c1689"))));
    assertThat(detectorResults, IsMapContaining.hasEntry("key->ZEFxYlpaVlBaOA==,name->ZmJXVGlSbHhrdA==", Collections.singletonList(buildDetector("ad-manager", "5eaa54e9-7406-4a1d-bd9b-e055eca1a423"))));
    assertThat(detectorResults, IsMapContaining.hasEntry("name->aGl3,region->dXMtd2VzdC0y", Collections.singletonList(buildDetector("", "d86b798c-cfee-4a2c-a17a-aa2ba79ccf51"))));
}
 
Example #2
Source Project: uyuni   Author: uyuni-project   File: VirtualPoolsControllerTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void testStop() throws Exception {
    VirtualPoolsController virtualPoolsController = new VirtualPoolsController(virtManager);
    String json = virtualPoolsController.poolStop(
            getPostRequestWithCsrfAndBody("/manager/api/systems/details/virtualization/pools/:sid/stop",
                                          "{poolNames: [\"pool0\"]}",
                                          host.getId()),
            response, user);

    // Ensure the start action is queued
    DataResult<ScheduledAction> actions = ActionManager.pendingActions(user, null);
    assertEquals(1, actions.size());
    assertEquals(ActionFactory.TYPE_VIRTUALIZATION_POOL_STOP.getName(), actions.get(0).getTypeName());

    Action action = ActionManager.lookupAction(user, actions.get(0).getId());
    VirtualizationPoolStopAction virtAction = (VirtualizationPoolStopAction)action;
    assertEquals("pool0", virtAction.getPoolName());

    // Check the returned message
    Map<String, Long> model = GSON.fromJson(json, new TypeToken<Map<String, Long>>() {}.getType());
    assertTrue(IsMapContaining.hasEntry("pool0", action.getId()).matches(model));
}
 
Example #3
Source Project: uyuni   Author: uyuni-project   File: VirtualPoolsControllerTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void testDelete() throws Exception {
    VirtualPoolsController virtualPoolsController = new VirtualPoolsController(virtManager);
    String json = virtualPoolsController.poolDelete(
            getPostRequestWithCsrfAndBody("/manager/api/systems/details/virtualization/pools/:sid/delete",
                                          "{poolNames: [\"pool0\"], purge: true}",
                                          host.getId()),
            response, user);

    // Ensure the start action is queued
    DataResult<ScheduledAction> actions = ActionManager.pendingActions(user, null);
    assertEquals(1, actions.size());
    assertEquals(ActionFactory.TYPE_VIRTUALIZATION_POOL_DELETE.getName(), actions.get(0).getTypeName());

    Action action = ActionManager.lookupAction(user, actions.get(0).getId());
    VirtualizationPoolDeleteAction virtAction = (VirtualizationPoolDeleteAction)action;
    assertEquals("pool0", virtAction.getPoolName());
    assertTrue(virtAction.isPurge());

    // Check the returned message
    Map<String, Long> model = GSON.fromJson(json, new TypeToken<Map<String, Long>>() {}.getType());
    assertTrue(IsMapContaining.hasEntry("pool0", action.getId()).matches(model));
}
 
Example #4
Source Project: cactoos-http   Author: yegor256   File: HtCookiesTest.java    License: MIT License 6 votes vote down vote up
@Test
public void takesCookiesOfHttpResponse() {
    MatcherAssert.assertThat(
        new HtCookies(
            new HtHead(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "HTTP/1.1 200 OK",
                        "Content-type: text/plain",
                        "Set-Cookie: path=/; domain=.google.com",
                        "",
                        "Hello, dude!",
                        "How are you?"
                    )
                )
            )
        ),
        new IsMapContaining<>(
            new IsEqual<>("domain"),
            new IsEqual<>(new ListOf<>(".google.com"))
        )
    );
}
 
Example #5
Source Project: cactoos-http   Author: yegor256   File: HtCookiesTest.java    License: MIT License 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void incorrectHttpResponseCookie() {
    MatcherAssert.assertThat(
        new HtCookies(
            new HtHead(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "HTTP/1.1 200 OK",
                        "Content-type: text/plain",
                        "Set-Cookie: path=/; 123; domain=.google.com",
                        "",
                        "Hello, dude!",
                        "How are you?"
                    )
                )
            )
        ),
        new IsMapContaining<>(
            new IsEqual<>("domain"),
            new IsEqual<>(".google.com")
        )
    );
}
 
Example #6
Source Project: cactoos-http   Author: yegor256   File: HtHeadersTest.java    License: MIT License 6 votes vote down vote up
@Test
public void takesHeadersOutOfHttpResponse() throws IOException {
    MatcherAssert.assertThat(
        new HtHeaders(
            new HtHead(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "HTTP/1.1 200 OK",
                        "Content-type: text/plain",
                        "",
                        "Hello, dude!",
                        "How are you?"
                    )
                )
            )
        ),
        new IsMapContaining<>(
            new IsEqual<>("content-type"),
            new IsEqual<>(new ListOf<>("text/plain"))
        )
    );
}
 
Example #7
Source Project: cloudbreak   Author: hortonworks   File: NetworkParameterAdderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddParametersWhenAws() {
    Map<String, Object> parameters = new HashMap<>();
    DetailedEnvironmentResponse environment = DetailedEnvironmentResponse.Builder.builder()
            .withCloudPlatform(CloudPlatform.AWS.name())
            .withNetwork(EnvironmentNetworkResponseBuilder.anEnvironmentNetworkResponse()
                    .withAws(EnvironmentNetworkAwsParamsBuilder.anEnvironmentNetworkAwsParams().withVpcId(TEST_VPC_ID).build())
                    .withNetworkCidr(TEST_VPC_CIDR)
                    .build())
            .build();

    parameters = underTest.addParameters(parameters, environment, CloudPlatform.AWS);

    assertThat(parameters, IsMapContaining.hasEntry(NetworkParameterAdder.VPC_ID, TEST_VPC_ID));
    assertThat(parameters, IsMapContaining.hasEntry(NetworkParameterAdder.VPC_CIDR, TEST_VPC_CIDR));
}
 
Example #8
Source Project: ratelimiter4j   Author: wangzheng0822   File: PropertySourceTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testCombinePropertySource() {
  PropertySource propertySource = new PropertySource();
  Map<String, Object> m1 = new HashMap<>();
  m1.put("k1", "v1");
  m1.put("k2", "v2");
  propertySource.addProperties(m1);

  PropertySource propertySource2 = new PropertySource();
  Map<String, Object> m2 = new HashMap<>();
  m2.put("k1", "v1-1");
  m2.put("k3", "v3");
  propertySource2.addProperties(m2);

  propertySource.combinePropertySource(propertySource2);
  Map<String, Object> result = propertySource.getProperties();
  assertEquals(result.size(), 3);

  assertThat(result, IsMapContaining.hasEntry("k1", "v1-1"));
  assertThat(result, IsMapContaining.hasEntry("k2", "v2"));
  assertThat(result, IsMapContaining.hasEntry("k3", "v3"));
}
 
Example #9
Source Project: api-layer   Author: zowe   File: GatewayHomepageControllerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void givenSpecificBuildVersion_whenHomePageCalled_thenBuildInfoShouldBeGivenVersionAndNumber() {
    BuildInfo buildInfo = mock(BuildInfo.class);

    Properties buildProperties = new Properties();
    buildProperties.setProperty("build.version", "test-version");
    buildProperties.setProperty("build.number", "test-number");
    BuildInfoDetails buildInfoDetails = new BuildInfoDetails(buildProperties, new Properties());
    when(buildInfo.getBuildInfoDetails()).thenReturn(buildInfoDetails);

    GatewayHomepageController gatewayHomepageController = new GatewayHomepageController(
        discoveryClient, authConfigurationProperties, buildInfo);

    Model model = new ConcurrentModel();
    gatewayHomepageController.home(model);

    Map<String, Object> actualModelMap = model.asMap();

    assertThat(actualModelMap, IsMapContaining.hasEntry("buildInfoText", "Version test-version build # test-number"));
}
 
Example #10
Source Project: api-layer   Author: zowe   File: GatewayHomepageControllerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void givenZOSMFProviderWithOneInstance_whenHomePageCalled_thenHomePageModelShouldContain() {
    ServiceInstance serviceInstance = new DefaultServiceInstance("instanceId", "serviceId",
        "host", 10000, true);
    when(discoveryClient.getInstances("zosmf")).thenReturn(
        Arrays.asList(serviceInstance)
    );

    authConfigurationProperties.setProvider("zosmf");
    authConfigurationProperties.setZosmfServiceId("zosmf");

    Model model = new ConcurrentModel();
    gatewayHomepageController.home(model);

    Map<String, Object> actualModelMap = model.asMap();

    assertThat(actualModelMap, IsMapContaining.hasEntry("authIconName", "success"));
    assertThat(actualModelMap, IsMapContaining.hasEntry("authStatusText", "The Authentication service is running"));
}
 
Example #11
Source Project: api-layer   Author: zowe   File: ApiDocV2ServiceTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void givenServiceUrlAsRoot_whenApiDocTransform_thenCheckUpdatedValues() throws IOException {
    Swagger dummySwaggerObject = getDummySwaggerObject("/apicatalog", false);
    String apiDocContent = convertSwaggerToJson(dummySwaggerObject);

    RoutedService routedService = new RoutedService("api_v1", "api/v1", "/");
    RoutedService routedService2 = new RoutedService("ui_v1", "ui/v1", "/apicatalog");

    RoutedServices routedServices = new RoutedServices();
    routedServices.addRoutedService(routedService);
    routedServices.addRoutedService(routedService2);

    ApiInfo apiInfo = new ApiInfo("org.zowe.apicatalog", "api/v1", null, "https://localhost:10014/apicatalog/api-doc", "https://www.zowe.org");
    ApiDocInfo apiDocInfo = new ApiDocInfo(apiInfo, apiDocContent, routedServices);

    String actualContent = apiDocV2Service.transformApiDoc(SERVICE_ID, apiDocInfo);
    Swagger actualSwagger = convertJsonToSwagger(actualContent);
    assertNotNull(actualSwagger);

    assertEquals("/api/v1/" + SERVICE_ID, actualSwagger.getBasePath());

    dummySwaggerObject.getPaths().forEach((k, v) ->
        assertThat(actualSwagger.getPaths(), IsMapContaining.hasKey(dummySwaggerObject.getBasePath() + k))
    );
}
 
Example #12
Source Project: cactoos   Author: yegor256   File: MapOfTest.java    License: MIT License 6 votes vote down vote up
@Test
public void createsMapWithFunctions() {
    MatcherAssert.assertThat(
        "Can't create a map with functions as values",
        new MapOf<Integer, Scalar<Boolean>>(
            new MapEntry<>(0, () -> true),
            new MapEntry<>(
                1,
                () -> {
                    throw new IOException("oops");
                }
            )
        ),
        new IsMapContaining<>(new IsEqual<>(0), new IsAnything<>())
    );
}
 
Example #13
Source Project: cactoos   Author: yegor256   File: MapOfTest.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void createsMapFromMapAndMapEntries() {
    MatcherAssert.assertThat(
        "Can't create a map from map and map entries",
        new MapOf<Integer, Integer>(
            new MapOf<Integer, Integer>(
                new MapEntry<Integer, Integer>(0, 0)
            ),
            new MapEntry<Integer, Integer>(1, 1)
        ),
        new AllOf<>(
            new IterableOf<>(
                new IsMapContaining<>(new IsEqual<>(0), new IsEqual<>(0)),
                new IsMapContaining<>(new IsEqual<>(1), new IsEqual<>(1))
            )
        )
    );
}
 
Example #14
Source Project: batfish   Author: batfish   File: MainTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testReadQuestionTemplates() throws Exception {
  Map<String, String> questionTemplates = Maps.newHashMap();
  questionTemplates.put(DUPLICATE_TEMPLATE_NAME, "template_body");

  JSONObject testQuestion = new JSONObject();
  testQuestion.put(
      "instance",
      new JSONObject()
          .put("instanceName", NEW_TEMPLATE_NAME)
          .put("description", "test question description"));
  Path questionJsonPath = _folder.newFile("testquestion.json").toPath();
  CommonUtil.writeFile(questionJsonPath, testQuestion.toString());

  readQuestionTemplate(questionJsonPath, questionTemplates);

  assertThat(questionTemplates.keySet(), hasSize(2));
  // Both templates should be present
  assertThat(
      questionTemplates,
      allOf(
          IsMapContaining.hasEntry(DUPLICATE_TEMPLATE_NAME, "template_body"),
          IsMapContaining.hasEntry(
              NEW_TEMPLATE_NAME,
              "{\"instance\":{\"instanceName\":\"new_template\",\"description\":\"test question description\"}}")));
}
 
Example #15
Source Project: cactoos   Author: yegor256   File: MapOfTest.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void createsMapFromMapFunctionsAndIterable() {
    MatcherAssert.assertThat(
        "Can't create a map from map, functions and iterable.",
        new MapOf<Integer, Integer>(
            new FuncOf<Integer, Integer>(0),
            new FuncOf<Integer, Integer>(0),
            new MapOf<Integer, Integer>(
                new MapEntry<Integer, Integer>(1, 1)
            ),
            new IterableOf<>(0)
        ),
        new AllOf<>(
            new IterableOf<>(
                new IsMapContaining<>(new IsEqual<>(0), new IsEqual<>(0)),
                new IsMapContaining<>(new IsEqual<>(1), new IsEqual<>(1))
            )
        )
    );
}
 
Example #16
Source Project: cactoos   Author: yegor256   File: GroupedTest.java    License: MIT License 6 votes vote down vote up
@Test
public void groupedByOneHasEntries() throws Exception {
    MatcherAssert.assertThat(
        "Can't group int values",
        new Grouped<>(
            // @checkstyle MagicNumberCheck (1 line)
            new IterableOf<>(1, 1, 1, 4, 5, 6, 7, 8, 9),
            number -> number,
            Object::toString
        ),
        new IsMapContaining<>(
            new IsEqual<>(1),
            new IsEqual<>(new ListOf<>("1", "1", "1"))
        )
    );
}
 
Example #17
Source Project: cactoos   Author: yegor256   File: StickyTest.java    License: MIT License 6 votes vote down vote up
@Test
public void extendsExistingMap() throws Exception {
    MatcherAssert.assertThat(
        "Can't extend an existing map",
        new Sticky<String, String>(
            new Sticky<String, String>(
                new MapEntry<>("make", "Mercedes-Benz"),
                new MapEntry<>("cost", "$95,000")
            ),
            new MapEntry<>("year", "2017"),
            new MapEntry<>("mileage", "12,000")
        ),
        new IsMapContaining<>(
            new IsAnything<>(),
            new StringEndsWith(",000")
        )
    );
}
 
Example #18
Source Project: cactoos   Author: yegor256   File: StickyTest.java    License: MIT License 6 votes vote down vote up
@Test
public void extendsExistingMapWithFunc() throws Exception {
    MatcherAssert.assertThat(
        "Can't transform and decorate a list of entries",
        new Sticky<>(
            color -> new MapEntry<>(
                color, color.toUpperCase(Locale.ENGLISH)
            ),
            new Sticky<String, String>(
                new MapEntry<>("black", "BLACK"),
                new MapEntry<>("white", "WHITE")
            ),
            new IterableOf<>("yellow", "red", "blue")
        ),
        new IsMapContaining<>(
            new IsAnything<>(),
            new IsEqual<>("BLUE")
        )
    );
}
 
Example #19
Source Project: cactoos   Author: yegor256   File: StickyTest.java    License: MIT License 6 votes vote down vote up
@Test
public void extendsExistingMapWithTwoFuncs() throws Exception {
    MatcherAssert.assertThat(
        "Can't transform and decorate a list of entries with two funcs",
        new Sticky<>(
            color -> new FormattedText("[%s]", color).asString(),
            String::toUpperCase,
            new Sticky<String, String>(
                new MapEntry<>("black!", "Black!"),
                new MapEntry<>("white!", "White!")
            ),
            new IterableOf<>("yellow!", "red!", "blue!")
        ),
        new IsMapContaining<>(
            new IsAnything<>(),
            new IsEqual<>("BLUE!")
        )
    );
}
 
Example #20
Source Project: cactoos   Author: yegor256   File: NoNullsTest.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void entrySet() {
    MatcherAssert.assertThat(
        "Can't call #entrySet()",
        new NoNulls<Integer, Integer>(
            new HashMap<Integer, Integer>() {
                {
                    put(1, 1);
                    put(0, 0);
                }
            }
        ),
        new AllOf<>(
            new IterableOf<>(
                new IsMapContaining<>(new IsEqual<>(1), new IsEqual<>(1)),
                new IsMapContaining<>(new IsEqual<>(0), new IsEqual<>(0))
            )
        )
    );
}
 
Example #21
Source Project: batfish   Author: batfish   File: MainTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testReadQuestionTemplateDuplicate() throws Exception {
  Map<String, String> questionTemplates = Maps.newHashMap();
  // already existing question template with key duplicate_template
  questionTemplates.put(DUPLICATE_TEMPLATE_NAME, "template_body");

  JSONObject testQuestion = new JSONObject();
  testQuestion.put(
      "instance",
      new JSONObject()
          .put("instanceName", DUPLICATE_TEMPLATE_NAME)
          .put("description", "test question description"));
  Path questionJsonPath = _folder.newFile("testquestion.json").toPath();
  CommonUtil.writeFile(questionJsonPath, testQuestion.toString());

  readQuestionTemplate(questionJsonPath, questionTemplates);

  assertThat(questionTemplates.keySet(), hasSize(1));
  // the value of the question template with key duplicate_template should be replaced now
  assertThat(
      questionTemplates,
      IsMapContaining.hasEntry(
          DUPLICATE_TEMPLATE_NAME,
          "{\"instance\":{\"instanceName\":\"duplicate_template\",\"description\":\"test question description\"}}"));
}
 
Example #22
Source Project: ehcache3   Author: ehcache   File: MultiGettingStarted.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void multipleConfigurations() {
  //tag::multipleManagers[]
  XmlMultiConfiguration multipleConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-managers.xml")) // <1>
    .build(); // <2>

  Configuration fooConfiguration = multipleConfiguration.configuration("foo-manager"); // <3>
  //end::multipleManagers[]

  Assert.assertThat(resourceMap(multipleConfiguration.identities().stream().collect(
    Collectors.toMap(Function.identity(), multipleConfiguration::configuration)
  )), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP)))
  ));
}
 
Example #23
Source Project: ehcache3   Author: ehcache   File: MultiGettingStarted.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void multipleVariants() {
  //tag::multipleVariants[]
  XmlMultiConfiguration variantConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-variants.xml"))
    .build();

  Configuration fooConfiguration = variantConfiguration.configuration("foo-manager", "offheap"); // <1>
  //end::multipleVariants[]

  Assert.assertThat(resourceMap(variantConfiguration.identities().stream().collect(
    Collectors.toMap(Function.identity(), i -> variantConfiguration.configuration(i, "offheap"))
  )), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP)))
  ));

  Assert.assertThat(resourceMap(variantConfiguration.identities().stream().collect(
    Collectors.toMap(Function.identity(), i -> variantConfiguration.configuration(i, "heap"))
  )), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP)))
  ));
}
 
Example #24
Source Project: ehcache3   Author: ehcache   File: MultiGettingStarted.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void multipleRetrieval() {
  XmlMultiConfiguration multipleConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-managers.xml"))
    .build();
  XmlMultiConfiguration variantConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-variants.xml"))
    .build();

  //tag::multipleRetrieval[]
  Map<String, Configuration> allConfigurations = multipleConfiguration.identities().stream() // <1>
    .collect(Collectors.toMap(i -> i, i -> multipleConfiguration.configuration(i))); // <2>
  Map<String, Configuration> offheapConfigurations = variantConfiguration.identities().stream()
    .collect(Collectors.toMap(i -> i, i -> variantConfiguration.configuration(i, "offheap"))); // <3>
  //end::multipleRetrieval[]

  Assert.assertThat(resourceMap(allConfigurations), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP)))
  ));

  Assert.assertThat(resourceMap(offheapConfigurations), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP)))
  ));
}
 
Example #25
Source Project: batfish   Author: batfish   File: MainTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testReadQuestionTemplatesCaps() throws Exception {
  Map<String, String> questionTemplates = Maps.newHashMap();
  questionTemplates.put(DUPLICATE_TEMPLATE_NAME, "template_body");

  JSONObject testQuestion = new JSONObject();
  testQuestion.put(
      "instance",
      new JSONObject()
          .put("instanceName", DUPLICATE_TEMPLATE_NAME.toUpperCase())
          .put("description", "test question description"));
  Path questionJsonPath = _folder.newFile("testquestion.json").toPath();
  CommonUtil.writeFile(questionJsonPath, testQuestion.toString());

  readQuestionTemplate(questionJsonPath, questionTemplates);

  assertThat(questionTemplates.keySet(), hasSize(1));
  // the value will be replaced with the body of the last template read
  // with (instanceName:DUPLICATE_TEMPLATE), key of the map will be same
  assertThat(
      questionTemplates,
      IsMapContaining.hasEntry(
          DUPLICATE_TEMPLATE_NAME,
          "{\"instance\":{\"instanceName\":\"DUPLICATE_TEMPLATE\",\"description\":\"test question description\"}}"));
}
 
Example #26
Source Project: flink   Author: apache   File: OneInputStreamTaskTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests the checkpoint related metrics are registered into {@link TaskIOMetricGroup}
 * correctly while generating the {@link OneInputStreamTask}.
 */
@Test
public void testCheckpointBarrierMetrics() throws Exception {
	final OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>(
		OneInputStreamTask::new,
		BasicTypeInfo.STRING_TYPE_INFO,
		BasicTypeInfo.STRING_TYPE_INFO);

	testHarness.setupOutputForSingletonOperatorChain();
	StreamConfig streamConfig = testHarness.getStreamConfig();
	streamConfig.setStreamOperator(new TestOperator());

	final Map<String, Metric> metrics = new ConcurrentHashMap<>();
	final TaskMetricGroup taskMetricGroup = new StreamTaskTestHarness.TestTaskMetricGroup(metrics);
	final StreamMockEnvironment environment = testHarness.createEnvironment();
	environment.setTaskMetricGroup(taskMetricGroup);

	testHarness.invoke(environment);
	testHarness.waitForTaskRunning();

	assertThat(metrics, IsMapContaining.hasKey(MetricNames.CHECKPOINT_ALIGNMENT_TIME));
	assertThat(metrics, IsMapContaining.hasKey(MetricNames.CHECKPOINT_START_DELAY_TIME));

	testHarness.endInput();
	testHarness.waitForTaskCompletion();
}
 
Example #27
Source Project: flink   Author: apache   File: MultipleInputStreamTaskTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests the checkpoint related metrics are registered into {@link TaskIOMetricGroup}
 * correctly while generating the {@link TwoInputStreamTask}.
 */
@Test
public void testCheckpointBarrierMetrics() throws Exception {
	final Map<String, Metric> metrics = new ConcurrentHashMap<>();
	final TaskMetricGroup taskMetricGroup = new StreamTaskTestHarness.TestTaskMetricGroup(metrics);

	try (StreamTaskMailboxTestHarness<String> testHarness =
			new MultipleInputStreamTaskTestHarnessBuilder<>(MultipleInputStreamTask::new, BasicTypeInfo.STRING_TYPE_INFO)
				.addInput(BasicTypeInfo.STRING_TYPE_INFO, 2)
				.addInput(BasicTypeInfo.INT_TYPE_INFO, 2)
				.addInput(BasicTypeInfo.DOUBLE_TYPE_INFO, 2)
				.setupOutputForSingletonOperatorChain(new MapToStringMultipleInputOperatorFactory())
				.setTaskMetricGroup(taskMetricGroup)
				.build()) {

		assertThat(metrics, IsMapContaining.hasKey(MetricNames.CHECKPOINT_ALIGNMENT_TIME));
		assertThat(metrics, IsMapContaining.hasKey(MetricNames.CHECKPOINT_START_DELAY_TIME));

		testHarness.endInput();
		testHarness.waitForTaskCompletion();
	}
}
 
Example #28
Source Project: consul-api   Author: Ecwid   File: ConsulClientTest.java    License: Apache License 2.0 6 votes vote down vote up
private void serviceRegisterTest(ConsulClient consulClient) {
    NewService newService = new NewService();
    String serviceName = "abc";
    newService.setName(serviceName);
    consulClient.agentServiceRegister(newService);

    Response<Map<String, Service>> agentServicesResponse = consulClient.getAgentServices();
    Map<String, Service> services = agentServicesResponse.getValue();
    assertThat(services, IsMapContaining.hasKey(serviceName));
}
 
Example #29
Source Project: uyuni   Author: uyuni-project   File: VirtualPoolsControllerTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testVolumeDelete() throws Exception {
    VirtualPoolsController virtualPoolsController = new VirtualPoolsController(virtManager);
    String json = virtualPoolsController.volumeDelete(
            getPostRequestWithCsrfAndBody("/manager/api/systems/details/virtualization/volumes/:sid/delete",
                                          "{volumes: {\"pool0\": [\"vol0\", \"vol1\"], \"pool1\": [\"vol2\"]}}",
                                          host.getId()),
            response, user);

    // Ensure the start action is queued
    List<BaseVirtualizationVolumeAction> actions = ActionManager.pendingActions(user, null).stream()
        .filter(action -> ActionFactory.TYPE_VIRTUALIZATION_VOLUME_DELETE.getName().equals(action.getTypeName()))
        .map(action -> (BaseVirtualizationVolumeAction)ActionManager.lookupAction(user, action.getId()))
        .collect(Collectors.toList());

    assertEquals(3, actions.size());
    Optional<BaseVirtualizationVolumeAction> vol0 = actions.stream()
        .filter(action -> "pool0".equals(action.getPoolName()) && "vol0".equals(action.getVolumeName()))
        .findFirst();
    assertTrue(vol0.isPresent());

    Optional<BaseVirtualizationVolumeAction> vol1 = actions.stream()
            .filter(action -> "pool0".equals(action.getPoolName()) && "vol1".equals(action.getVolumeName()))
            .findFirst();
    assertTrue(vol1.isPresent());

    Optional<BaseVirtualizationVolumeAction> vol2 = actions.stream()
            .filter(action -> "pool1".equals(action.getPoolName()) && "vol2".equals(action.getVolumeName()))
            .findFirst();
    assertTrue(vol2.isPresent());

    // Check the returned message
    Map<String, Long> model = GSON.fromJson(json, new TypeToken<Map<String, Long>>() {}.getType());
    assertTrue(IsMapContaining.hasEntry("pool0/vol1", vol1.get().getId()).matches(model));
}
 
Example #30
Source Project: cactoos-http   Author: yegor256   File: HtCookiesTest.java    License: MIT License 5 votes vote down vote up
@Test
public void takesMultipleCookies() {
    final String first = "first";
    final String second = "second";
    final HtHead head = new HtHead(
        new InputOf(
            new FormattedText(
                new Joined(
                    "\r\n",
                    "HTTP/1.1 200 OK",
                    "Set-Cookie: path=/; session1=%s",
                    "Set-Cookie: path=/; session2=%s",
                    "",
                    "Hello!"
                ), first, second
            )
        )
    );
    MatcherAssert.assertThat(
        new HtCookies(head),
        Matchers.allOf(
            new IsMapContaining<>(
                new IsEqual<>("session1"),
                new IsEqual<>(new ListOf<>(first))
            ),
            new IsMapContaining<>(
                new IsEqual<>("session2"),
                new IsEqual<>(new ListOf<>(second))
            )
        )
    );
}