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 File: DetectorMapperTest.java    From adaptive-alerting with 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 File: ConsulClientTest.java    From consul-api with 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 #3
Source File: VirtualPoolsControllerTest.java    From uyuni with 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 #4
Source File: VirtualPoolsControllerTest.java    From uyuni with 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 #5
Source File: HtCookiesTest.java    From cactoos-http with 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 File: HtHeadersTest.java    From cactoos-http with 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 File: NetworkParameterAdderTest.java    From cloudbreak with 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 File: PropertySourceTest.java    From ratelimiter4j with 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 File: HtCookiesTest.java    From cactoos-http with 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 #10
Source File: GatewayHomepageControllerTest.java    From api-layer with 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 #11
Source File: GatewayHomepageControllerTest.java    From api-layer with 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 #12
Source File: ApiDocV2ServiceTest.java    From api-layer with 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 #13
Source File: MapOfTest.java    From cactoos with 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 #14
Source File: MapOfTest.java    From cactoos with 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 #15
Source File: MapOfTest.java    From cactoos with 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 File: GroupedTest.java    From cactoos with 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 File: StickyTest.java    From cactoos with 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 File: StickyTest.java    From cactoos with 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 File: StickyTest.java    From cactoos with 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 File: NoNullsTest.java    From cactoos with 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 File: MainTest.java    From batfish with 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 File: MultiGettingStarted.java    From ehcache3 with 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 File: MultiGettingStarted.java    From ehcache3 with 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 File: MultiGettingStarted.java    From ehcache3 with 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 File: MainTest.java    From batfish with 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 File: OneInputStreamTaskTest.java    From flink with 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 File: MultipleInputStreamTaskTest.java    From flink with 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 File: MainTest.java    From batfish with 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 #29
Source File: JWTConfigurationTest.java    From auth0-java with MIT License 5 votes vote down vote up
@Test
public void shouldDeserialize() throws Exception {
    JWTConfiguration config = fromJSON(json, JWTConfiguration.class);

    assertThat(config, is(notNullValue()));

    assertThat(config.getAlgorithm(), is("alg"));
    assertThat(config.getLifetimeInSeconds(), is(123));
    assertThat(config.getScopes(), is(notNullValue()));
    assertThat((Map<String, String>) config.getScopes(), IsMapContaining.hasEntry("key", "value"));
}
 
Example #30
Source File: ClaimsHolderTest.java    From java-jwt with MIT License 5 votes vote down vote up
@SuppressWarnings("RedundantCast")
@Test
public void shouldGetClaims() throws Exception {
    HashMap<String, Object> claims = new HashMap<>();
    claims.put("iss", "auth0");
    ClaimsHolder holder = new ClaimsHolder(claims);
    assertThat(holder, is(notNullValue()));
    assertThat(holder.getClaims(), is(notNullValue()));
    assertThat(holder.getClaims(), is(instanceOf(Map.class)));
    assertThat(holder.getClaims(), is(IsMapContaining.hasEntry("iss", (Object) "auth0")));
}