org.mockito.internal.util.collections.Sets Java Examples

The following examples show how to use org.mockito.internal.util.collections.Sets. 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: BehaviorSettingsFactoryTest.java    From megamek with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testLoadBehaviorSettings() throws IOException, SAXException, ParserConfigurationException {
    // Test loading a good behavior settings file.
    testFactory.behaviorMap.clear();
    TestCase.assertTrue(testFactory.loadBehaviorSettings(buildTestDocument()));
    TestCase.assertEquals(5, testFactory.behaviorMap.size());
    String[] expectedBehaviors = new String[]
            {BehaviorSettingsFactoryTestConstants.NM_RECKLESS,
                    BehaviorSettingsFactoryTestConstants.NM_COWARDLY,
                    BehaviorSettingsFactoryTestConstants.NM_ESCAPE,
                    BehaviorSettingsFactoryTestConstants.NM_DEFAULT,
                    BehaviorSettingsFactory.BERSERK_BEHAVIOR_DESCRIPTION};
    TestCase.assertEquals(Sets.newSet(expectedBehaviors), Sets.newSet(testFactory.getBehaviorNames()));

    // Test loading a null behavior settings file.
    testFactory.behaviorMap.clear();
    TestCase.assertFalse(testFactory.loadBehaviorSettings(null));
    TestCase.assertEquals(4, testFactory.behaviorMap.size());
    expectedBehaviors = new String[]{BehaviorSettingsFactory.BERSERK_BEHAVIOR_DESCRIPTION,
            BehaviorSettingsFactory.COWARDLY_BEHAVIOR_DESCRIPTION,
            BehaviorSettingsFactory.DEFAULT_BEHAVIOR_DESCRIPTION,
            BehaviorSettingsFactory.ESCAPE_BEHAVIOR_DESCRIPTION};
    Assert.assertArrayEquals(expectedBehaviors, testFactory.getBehaviorNames());
}
 
Example #2
Source File: TestReplaceFiles.java    From iceberg with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteNonExistentFile() {
  Assert.assertEquals("Table should start empty", 0, listManifestFiles().size());

  table.newAppend()
      .appendFile(FILE_A)
      .appendFile(FILE_B)
      .commit();

  TableMetadata base = readMetadata();
  Assert.assertEquals("Should create 1 manifest for initial write",
      1, base.currentSnapshot().manifests().size());

  AssertHelpers.assertThrows("Expected an exception",
      ValidationException.class,
      "Missing required files to delete: /path/to/data-c.parquet",
      () -> table.newRewrite()
          .rewriteFiles(Sets.newSet(FILE_C), Sets.newSet(FILE_D))
          .commit());

  Assert.assertEquals("Only 1 manifests should exist", 1, listManifestFiles().size());
}
 
Example #3
Source File: RpcTest.java    From tx-lcn with Apache License 2.0 6 votes vote down vote up
@Test
public void testLock() throws RpcException {

    // 第一个锁,True
    boolean result0 = messenger.acquireLocks("1", Sets.newSet("1"), DTXLocks.S_LOCK);
    Assert.assertTrue(result0);

    // 共享锁下可以加共享锁, True
    boolean result1 = messenger.acquireLocks("2", Sets.newSet("1"), DTXLocks.S_LOCK);
    Assert.assertTrue(result1);

    // 共享锁下只准加共享锁,False
    boolean result = messenger.acquireLocks("3", Sets.newSet("1", "2"), DTXLocks.X_LOCK);
    Assert.assertFalse(result);

    messenger.releaseLocks(Sets.newSet("1"));

    // 锁被释放,True
    boolean result2 = messenger.acquireLocks("4", Sets.newSet("2", "3"), DTXLocks.X_LOCK);
    Assert.assertTrue(result2);

    // 同一个 DTX 下, True
    boolean result3 = messenger.acquireLocks("4", Sets.newSet("2"), DTXLocks.X_LOCK);
    Assert.assertTrue(result3);
}
 
Example #4
Source File: SessionContainerTest.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
@Test(groups = "unit")
public void setSessionTokenDoesNothingOnEmptySessionTokenHeader() {
    SessionContainer sessionContainer = new SessionContainer("127.0.0.1");
    String documentCollectionId = ResourceId.newDocumentCollectionId(getRandomDbId(), getRandomCollectionId()).getDocumentCollectionId().toString();
    String collectionFullName = "dbs/db1/colls1/collName";

    sessionContainer.setSessionToken(documentCollectionId, collectionFullName + "/docs/doc1",
            ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, "range_0:1#100#4=90#5=1"));
    RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read,
            documentCollectionId, ResourceType.Document, new HashMap<>());
    String sessionToken = sessionContainer.resolveGlobalSessionToken(request);
    Set<String> tokens = Sets.newSet(sessionToken.split(","));
    assertThat(tokens.size()).isEqualTo(1);
    assertThat(tokens.contains("range_0:1#100#4=90#5=1")).isTrue();

    sessionContainer.setSessionToken(documentCollectionId, collectionFullName, new HashMap<>());
    request = RxDocumentServiceRequest.create(OperationType.Read,
            documentCollectionId, ResourceType.Document, new HashMap<>());
    sessionToken = sessionContainer.resolveGlobalSessionToken(request);
    tokens = Sets.newSet(sessionToken.split(","));
    assertThat(tokens.size()).isEqualTo(1);
    assertThat(tokens.contains("range_0:1#100#4=90#5=1")).isTrue();
}
 
Example #5
Source File: SessionContainerTest.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
@Test(groups = "unit")
public void resolveGlobalSessionTokenReturnsTokenMapUsingResourceId() {
    SessionContainer sessionContainer = new SessionContainer("127.0.0.1");
    String documentCollectionId = ResourceId.newDocumentCollectionId(getRandomDbId(), getRandomCollectionId()).getDocumentCollectionId().toString();
    String collectionFullName = "dbs/db1/colls1/collName";
    RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read,
            documentCollectionId, ResourceType.Document, new HashMap<>());

    sessionContainer.setSessionToken(documentCollectionId, collectionFullName,
            ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, "range_0:1#100#1=20#2=5#3=30"));
    sessionContainer.setSessionToken(documentCollectionId, collectionFullName,
            ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, "range_1:1#101#1=20#2=5#3=30"));
    String sessionToken = sessionContainer.resolveGlobalSessionToken(request);

    Set<String> tokens = Sets.newSet(sessionToken.split(","));
    assertThat(tokens.size()).isEqualTo(2);
    assertThat(tokens.contains("range_0:1#100#1=20#2=5#3=30")).isTrue();
    assertThat(tokens.contains("range_1:1#101#1=20#2=5#3=30")).isTrue();
}
 
Example #6
Source File: SessionContainerTest.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
@Test(groups = "unit")
public void resolveGlobalSessionTokenReturnsTokenMapUsingName() {
    SessionContainer sessionContainer = new SessionContainer("127.0.0.1");
    String documentCollectionId = ResourceId.newDocumentCollectionId(getRandomDbId(), getRandomCollectionId()).getDocumentCollectionId().toString();
    String collectionFullName = "dbs/db1/colls1/collName";

    sessionContainer.setSessionToken(documentCollectionId, collectionFullName,
            ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, "range_0:1#100#1=20#2=5#3=30"));
    sessionContainer.setSessionToken(documentCollectionId, collectionFullName,
            ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, "range_1:1#101#1=20#2=5#3=30"));

    RxDocumentServiceRequest request = RxDocumentServiceRequest.createFromName(OperationType.Read,
            collectionFullName + "/docs/doc1", ResourceType.Document);
    String sessionToken = sessionContainer.resolveGlobalSessionToken(request);
    Set<String> tokens = Sets.newSet(sessionToken.split(","));

    assertThat(tokens.size()).isEqualTo(2);
    assertThat(tokens.contains("range_0:1#100#1=20#2=5#3=30")).isTrue();
    assertThat(tokens.contains("range_1:1#101#1=20#2=5#3=30")).isTrue();
}
 
Example #7
Source File: GeoReportHelperTest.java    From mobile-messaging-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void test_should_filter_reports_for_inactive_campaigns() throws Exception {

    // Given
    Area area = createArea("areaId");
    EventReportResponse reportResponse = new EventReportResponse();
    reportResponse.setFinishedCampaignIds(Sets.newSet("campaignId1"));
    reportResponse.setSuspendedCampaignIds(Sets.newSet("campaignId2"));
    createMessage(context, "signalingMessageId1", "campaignId1", true, area);
    createMessage(context, "signalingMessageId2", "campaignId2", true, area);
    createMessage(context, "signalingMessageId3", "campaignId3", true, area);
    GeoReportingResult geoReportingResult = new GeoReportingResult(reportResponse);
    List<GeoReport> reports = Arrays.asList(
            createReport(context, "signalingMessageId1", "campaignId1", "sdkMessageId1", false, area),
            createReport(context, "signalingMessageId2", "campaignId2", "sdkMessageId2", false, area),
            createReport(context, "signalingMessageId3", "campaignId3", "sdkMessageId3", false, area));

    // When
    List<GeoReport> filtered = GeoReportHelper.filterOutNonActiveReports(context, reports, geoReportingResult);

    // Then
    assertJEquals(reports.get(2), filtered.get(0));
}
 
Example #8
Source File: PushableStreamTest.java    From cyclops with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiple() {
	MultipleStreamSource<Integer> multi = StreamSource
											.ofMultiple();
	FutureStream<Integer> pushable = multi
			.futureStream(new LazyReact());
	ReactiveSeq<Integer> seq = multi.reactiveSeq();
	Stream<Integer> stream = multi.stream();
	multi.getInput().offer(100);
	multi.getInput().close();

	Set<Integer> vals = new TreeSet<>();
	pushable.forEach(vals::add);
	seq.forEach(vals::add);
	stream.forEach(vals::add);

	assertThat(Sets.newSet(100),is(vals));
}
 
Example #9
Source File: TestRewriteFiles.java    From iceberg with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteNonExistentFile() {
  Assert.assertEquals("Table should start empty", 0, listManifestFiles().size());

  table.newAppend()
      .appendFile(FILE_A)
      .appendFile(FILE_B)
      .commit();

  TableMetadata base = readMetadata();
  Assert.assertEquals("Should create 1 manifest for initial write",
      1, base.currentSnapshot().allManifests().size());

  AssertHelpers.assertThrows("Expected an exception",
      ValidationException.class,
      "Missing required files to delete: /path/to/data-c.parquet",
      () -> table.newRewrite()
          .rewriteFiles(Sets.newSet(FILE_C), Sets.newSet(FILE_D))
          .commit());

  Assert.assertEquals("Only 1 manifests should exist", 1, listManifestFiles().size());
}
 
Example #10
Source File: TransactionalDatabaseTemplateTest.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFetch_withQueryAndItemClass() throws Exception {
    // Given
    final Query query = mock(Query.class);
    final Set<StubItem> items = Sets.newSet(randomStubItem(), randomStubItem(), randomStubItem());
    when(mockDatabaseTemplate.fetch(any(Query.class), any(Class.class))).thenReturn(items);
    final TransactionalDatabaseTemplate transactionalDatabaseTemplate = new TransactionalDatabaseTemplate(
            mockDatabaseTemplate);

    // When
    final Collection<StubItem> returnedItems = transactionalDatabaseTemplate.fetch(query, StubItem.class);

    // Then
    verify(mockDatabaseTemplate).fetch(query, StubItem.class);
    assertEquals(items, returnedItems);
}
 
Example #11
Source File: ItemHashUtilTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Test
public void testHashBaseForItemMetadataSkipsUnimportantKeys() throws NoSuchAlgorithmException, IOException, ServerOverloadException {
    final ItemData item = new ItemData();
    item.setTypeId(TypeIfc.FILL_IN_BLANK);
    final ItemMetaDataIfc metaData1 = newItemMetaData(item, ItemMetaDataIfc.RANDOMIZE, 0);
    final ItemMetaDataIfc metaData2 = newItemMetaData(item, ItemMetaDataIfc.OBJECTIVE, 1); // this one should be ignored
    final ItemMetaDataIfc metaData3 = newItemMetaData(item, ItemMetaDataIfc.REQUIRE_ALL_OK, 2);
    item.setItemMetaDataSet(Sets.newSet(metaData1, metaData2, metaData3));

    final StringBuilder expectedHashBase = new StringBuilder()
            .append("RANDOMIZE:" + resourceDocTemplate1(fullUrlForContentResource(CONTENT_RESOURCES[0])) +  "::")
            .append("REQUIRE_ALL_OK:" + resourceDocTemplate1(fullUrlForContentResource(CONTENT_RESOURCES[2]))+ "::");

    // nulls for the other 14 "important" keys
    IntStream.rangeClosed(0, 13).forEach(
            i -> expectedHashBase.append("")
    );

    final StringBuilder actualHashBase = new StringBuilder();
    itemHashUtil.hashBaseForItemMetadata(item, actualHashBase);
    assertThat(actualHashBase.toString(), equalTo(expectedHashBase.toString()));
}
 
Example #12
Source File: GeoReportHelperTest.java    From mobile-messaging-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void test_should_find_signaling_messages_and_areas_for_geofencing_request_ids_and_event_type() throws Exception {

    // Given
    Area area = createArea("areaId1");
    Message message = createMessage(context, "messageId1", "campaigId1", true, area);

    // When
    Map<Message, List<Area>> messageAreas = GeoReportHelper.findSignalingMessagesAndAreas(context, geoStore, Sets.newSet("areaId1"), GeoEventType.entry);

    // Then
    // internalData is String, so has to be compared as JSON separately
    assertJEquals(message, messageAreas.keySet().iterator().next(), "internalData");
    JSONAssert.assertEquals(message.getInternalData(), messageAreas.keySet().iterator().next().getInternalData(), true);
    assertJEquals(area, messageAreas.values().iterator().next().get(0));
}
 
Example #13
Source File: AcknowledgementsJsonParserTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void parseJsonRepresentationWithInvalidAcknowledgementJsonRepresentation() {
    final Acknowledgements acknowledgements = Acknowledgements.of(Sets.newSet(knownAcknowledgement), dittoHeaders);
    final JsonFieldDefinition<JsonObject> acknowledgementsFieldDefinition =
            Acknowledgements.JsonFields.ACKNOWLEDGEMENTS;
    final int invalidAcknowledgement = 42;
    final JsonObject invalidAcknowledgements = JsonObject.newBuilder()
            .set(knownAcknowledgement.getLabel(), invalidAcknowledgement)
            .build();
    final JsonObject jsonRepresentation = JsonFactory.newObjectBuilder(acknowledgements.toJson())
            .set(acknowledgementsFieldDefinition, invalidAcknowledgements)
            .build();

    assertThatExceptionOfType(JsonParseException.class)
            .isThrownBy(() -> underTest.apply(jsonRepresentation))
            .withMessage("<%d> is not an Acknowledgement JSON object representation!", invalidAcknowledgement)
            .withNoCause();
}
 
Example #14
Source File: ItemHashUtilTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Test
public void testHashBaseForItemAttachmentsSkipSingleMissingResources() throws IOException, IdUnusedException,
        PermissionException, TypeException, ServerOverloadException, NoSuchAlgorithmException {
    final ItemData item = new ItemData();
    item.setTypeId(TypeIfc.FILL_IN_BLANK);

    final ItemAttachment attachment1 = new ItemAttachment(1L, item, idForContentResource(CONTENT_RESOURCES[0]), CONTENT_RESOURCES[0][CR_NAME_IDX], null, Long.MAX_VALUE - 1, null, null, null, null, null, null, null, null);
    item.setItemAttachmentSet(Sets.newSet(attachment1));

    expectServerUrlLookup();
    failResourceLookup(CONTENT_RESOURCES[0]);

    final StringBuilder actualHashBase = new StringBuilder();
    itemHashUtil.hashBaseForItemAttachments(item, actualHashBase);
    assertThat(actualHashBase.toString(), equalTo(""));
}
 
Example #15
Source File: ApiService_UpdateTest.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUpdateWithExistingAllowedTags() throws TechnicalException {
    prepareUpdate();
    when(existingApi.getTags()).thenReturn(newSet("public", "private"));
    Proxy proxy = new Proxy();
    EndpointGroup endpointGroup = new EndpointGroup();
    Endpoint endpoint = new HttpEndpoint(null, null);
    endpointGroup.setEndpoints(singleton(endpoint));
    proxy.setGroups(singleton(endpointGroup));
    when(existingApi.getProxy()).thenReturn(proxy);
    when(api.getDefinition()).thenReturn("{\"id\": \"" + API_ID + "\",\"name\": \"" + API_NAME + "\",\"proxy\": {\"context_path\": \"/old\"} ,\"tags\": [\"public\"]}");
    when(tagService.findByUser(any())).thenReturn(Sets.newSet("public", "private"));
    final ApiEntity apiEntity = apiService.update(API_ID, existingApi);
    assertNotNull(apiEntity);
    assertEquals(API_NAME, apiEntity.getName());
}
 
Example #16
Source File: FilterTest.java    From flower with Apache License 2.0 6 votes vote down vote up
@Test
public void testAccessLogFilter() throws Exception {
  String flowName = generateFlowName();
  ServiceFlow serviceFlow = serviceFactory.getOrCreateServiceFlow(flowName);
  serviceFlow.buildFlow(UserServiceA.class, UserServiceB.class);
  serviceFlow.buildFlow(UserServiceB.class, UserServiceC1.class);
  serviceFlow.buildFlow(UserServiceC1.class, OpenTracerService.class);
  serviceFlow.setFilters(Sets.newSet("mockOneFilter", "mockTwoFilter", "accessLogFilter"));
  serviceFlow.build();
  final FlowRouter router = serviceFacade.buildFlowRouter(flowName, 2 << 3);

  User user = new User();
  user.setName("响应式编程 ");
  user.setAge(2);
  Object o = router.syncCallService(user);
  System.out.println("响应结果: " + o);
}
 
Example #17
Source File: TestRoutingTableProvider.java    From helix with Apache License 2.0 6 votes vote down vote up
@Test(dependsOnMethods = { "testRoutingTableListener" })
public void testShutdownInstance() throws InterruptedException {
  // shutdown second instance.
  _participants.get(1).syncStop();

  Assert.assertTrue(_clusterVerifier.verifyByPolling());

  Assert.assertEquals(_routingTableProvider_default.getLiveInstances().size(), _instances.size() - 1);
  Assert.assertEquals(_routingTableProvider_default.getInstanceConfigs().size(), _instances.size());

  Assert.assertEquals(_routingTableProvider_ev.getLiveInstances().size(), _instances.size() - 1);
  Assert.assertEquals(_routingTableProvider_ev.getInstanceConfigs().size(), _instances.size());

  Assert.assertEquals(_routingTableProvider_cs.getLiveInstances().size(), _instances.size() - 1);
  Assert.assertEquals(_routingTableProvider_cs.getInstanceConfigs().size(), _instances.size());

  validateRoutingTable(_routingTableProvider_default, Sets.newSet(_instances.get(0)),
      Sets.newSet(_instances.get(2)));
  validateRoutingTable(_routingTableProvider_ev, Sets.newSet(_instances.get(0)),
      Sets.newSet(_instances.get(2)));
  validateRoutingTable(_routingTableProvider_cs, Sets.newSet(_instances.get(0)),
      Sets.newSet(_instances.get(2)));
}
 
Example #18
Source File: ConditionTest.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnDoesNotHaveMissingComparisonValues_withConditionWhichDoesNotRequireComparisonValuesAndNonNullOrEmptyValues() {
    // Given
    final Set<Operators> operatorsWhichDoNotRequireNonNullOrEmptyValues = Sets.newSet(Operators.NOT_NULL,
            Operators.NULL);
    final Operators operatorWhichRequiresNonNullOrEmptyValue = randomEnumInSet(
            operatorsWhichDoNotRequireNonNullOrEmptyValues);
    final String value = randomString();

    final Condition condition = new Condition(operatorWhichRequiresNonNullOrEmptyValue, value);

    // When
    final boolean hasMissingComparisonValues = condition.hasMissingComparisonValues();

    // Then
    assertFalse(hasMissingComparisonValues);
}
 
Example #19
Source File: AbstractUpdateImportsTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void getModuleLines_oneFrontendDependencyDoesntExist_throwExceptionAndlogExplanation() {
    useMockLog = true;
    Mockito.when(logger.isInfoEnabled()).thenReturn(true);

    String fooFileName = "./foo.js";
    assertFileRemoved(fooFileName, frontendDirectory);

    try {
        updater.run();
        Assert.fail("Execute should have failed with missing file");
    } catch (IllegalStateException e) {
        assertThat(e.getMessage(),
                CoreMatchers
                        .containsString(getFormattedFrontendErrorMessage(
                                Sets.newSet(fooFileName))));
    }

}
 
Example #20
Source File: ConditionTest.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnDoesNotHaveMissingComparisonValues_withConditionWhichDoesNotRequireComparisonValuesAndNullOrEmptyValues() {
    // Given
    final Set<Operators> operatorsWhichDoNotRequireNonNullOrEmptyValues = Sets.newSet(Operators.NOT_NULL,
            Operators.NULL);
    final Operators operatorWhichRequiresNonNullOrEmptyValue = randomEnumInSet(
            operatorsWhichDoNotRequireNonNullOrEmptyValues);
    final String value = randomBoolean() ? null : "";

    final Condition condition = new Condition(operatorWhichRequiresNonNullOrEmptyValue, value);

    // When
    final boolean hasMissingComparisonValues = condition.hasMissingComparisonValues();

    // Then
    assertFalse(hasMissingComparisonValues);
}
 
Example #21
Source File: AbstractUpdateImportsTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void getModuleLines_multipleFrontendDependencyDoesntExist_throwExceptionAndlogExplanation() {
    useMockLog = true;
    Mockito.when(logger.isInfoEnabled()).thenReturn(true);

    String localTemplateFileName = "./local-template.js";
    String fooFileName = "./foo.js";

    assertFileRemoved(localTemplateFileName, frontendDirectory);
    assertFileRemoved(fooFileName, frontendDirectory);

    try {
        updater.run();
        Assert.fail("Execute should have failed with missing files");
    } catch (IllegalStateException e) {
        assertThat(e.getMessage(), CoreMatchers
                .containsString(getFormattedFrontendErrorMessage(
                        Sets.newSet(localTemplateFileName, fooFileName))));
    }

}
 
Example #22
Source File: NativeSessionFileGzipperTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testProcessNativeSessions_putsFilesInCorrectLocation() throws IOException {
  String fileBackedSessionName = "file";
  String byteBackedSessionName = "byte";
  FileBackedNativeSessionFile fileSession =
      new FileBackedNativeSessionFile("not_applicable", fileBackedSessionName, testFile);
  BytesBackedNativeSessionFile byteSession =
      new BytesBackedNativeSessionFile("not_applicable", byteBackedSessionName, testContents);
  List<NativeSessionFile> files = Arrays.asList(fileSession, byteSession);
  NativeSessionFileGzipper.processNativeSessions(gzipDir, files);

  assertEquals(
      Sets.newSet(
          new File(gzipDir, fileBackedSessionName), new File(gzipDir, byteBackedSessionName)),
      Sets.newSet(gzipDir.listFiles()));
}
 
Example #23
Source File: DynamoDbTemplateIntegrationTest.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUpdate_withSingleItem() {
    // Given
    final DynamoDbTemplate dynamoDbTemplate = new DynamoDbTemplate(databaseSchemaHolder);
    dynamoDbTemplate.initialize(amazonDynamoDbClient);
    final StubItem createdItem = dataGenerator.createStubItem();
    final Long originalVersion = createdItem.getVersion();
    final String stringProperty = randomString(10);
    final String stringProperty2 = randomString(10);
    final Set<String> newStringSetProperty = Sets.newSet(randomString(10), randomString(10), randomString(10));
    createdItem.setStringProperty(stringProperty);
    createdItem.setStringProperty2(stringProperty2);
    createdItem.setStringSetProperty(newStringSetProperty);
    final Long newVersion = originalVersion + 1;

    // When
    final StubItem updatedItem = dynamoDbTemplate.update(createdItem);

    // Then
    assertEquals(newVersion, updatedItem.getVersion());
    assertEquals(createdItem.getId(), updatedItem.getId());
    assertEquals(stringProperty, updatedItem.getStringProperty());
    assertEquals(stringProperty2, updatedItem.getStringProperty2());
    assertEquals(newStringSetProperty, updatedItem.getStringSetProperty());
}
 
Example #24
Source File: DynamoDbDataGenerator.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
public StubWithRangeItem createStubWithRangeItem() {
    final StubWithRangeItem stubItem = new StubWithRangeItem();
    stubItem.setId(randomId());
    stubItem.setSupportingId(randomId());
    stubItem.setStringProperty(randomString(10));
    stubItem.setBooleanProperty(randomBoolean());
    stubItem.setStringSetProperty(new HashSet<>(Sets.newSet(randomString(10), randomString(10), randomString(10))));
    stubItem.setVersion((long) randomInt(100));
    final Map<String, AttributeValue> itemMap = new HashMap<>();
    itemMap.put("id", new AttributeValue(stubItem.getId()));
    itemMap.put("supportingId", new AttributeValue(stubItem.getSupportingId()));
    if (stubItem.getStringProperty() != null) {
        itemMap.put("stringProperty", new AttributeValue(stubItem.getStringProperty()));
    }
    itemMap.put("booleanProperty", new AttributeValue().withN(stubItem.isBooleanProperty() ? "1" : "0"));
    if (!stubItem.getStringSetProperty().isEmpty()) {
        itemMap.put("stringSetProperty", new AttributeValue().withSS(stubItem.getStringSetProperty()));
    }
    itemMap.put("version", new AttributeValue().withN(String.valueOf(stubItem.getVersion())));
    final PutItemRequest putItemRequest = new PutItemRequest()
            .withTableName(unitTestSchemaName + "." + stubItemWithRangeTableName).withItem(itemMap);
    amazonDynamoDbClient.putItem(putItemRequest);
    logger.debug("Created stub item with id: " + stubItem.getId());
    createdItemIds.add(stubItem.getId());
    return stubItem;
}
 
Example #25
Source File: StatementDocumentAccessTest.java    From Wikidata-Toolkit with Apache License 2.0 6 votes vote down vote up
@Test
public void testHasStatementValue() {
	Statement s1 = StatementBuilder.forSubjectAndProperty(q1, p1)
			.withValue(q1).build();
	Statement s2 = StatementBuilder.forSubjectAndProperty(q1, p1)
			.withValue(q2).build();
	Statement s3 = StatementBuilder.forSubjectAndProperty(q1, p1)
			.withSomeValue().build();

	ItemDocument id = ItemDocumentBuilder.forItemId(q1).withStatement(s1)
			.withStatement(s2).withStatement(s3).build();

	assertTrue(id.hasStatementValue(p1, q2));
	assertTrue(id.hasStatementValue("P1", q2));
	assertTrue(id.hasStatementValue(p1, Sets.newSet(q1, p3)));
	assertFalse(id.hasStatementValue(p1, p3));
	assertFalse(id.hasStatementValue("P2", q2));
}
 
Example #26
Source File: ProgramEndpointCallMockIntegrationShould.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
    BaseMockIntegrationTestEmptyEnqueable.setUpClass();

    ContentValues categoryCombo = CreateCategoryComboUtils.create(1L, "nM3u9s5a52V");
    databaseAdapter.insert(CategoryComboTableInfo.TABLE_INFO.name(), null, categoryCombo);

    ContentValues categoryCombo2 = CreateCategoryComboUtils.create(2L, "x31y45jvIQL");
    databaseAdapter.insert(CategoryComboTableInfo.TABLE_INFO.name(), null, categoryCombo2);

    // inserting tracked entity
    ContentValues trackedEntityType = CreateTrackedEntityUtils.create(1L, "nEenWmSyUEp");
    databaseAdapter.insert(TrackedEntityTypeTableInfo.TABLE_INFO.name(), null, trackedEntityType);

    // inserting tracked entity attributes
    ContentValues trackedEntityAttribute1 = CreateTrackedEntityAttributeUtils.create(1L, "w75KJ2mc4zz", null);
    databaseAdapter.insert(TrackedEntityAttributeTableInfo.TABLE_INFO.name(), null, trackedEntityAttribute1);

    ContentValues trackedEntityAttribute2 = CreateTrackedEntityAttributeUtils.create(2L, "zDhUuAYrxNC", null);
    databaseAdapter.insert(TrackedEntityAttributeTableInfo.TABLE_INFO.name(), null, trackedEntityAttribute2);

    ContentValues trackedEntityAttribute3 = CreateTrackedEntityAttributeUtils.create(3L, "cejWyOfXge6", null);
    databaseAdapter.insert(TrackedEntityAttributeTableInfo.TABLE_INFO.name(), null, trackedEntityAttribute3);

    programEndpointCall = objects.d2DIComponent.programCallFactory().create(Sets.newSet("IpHINAT79UW"));
}
 
Example #27
Source File: DynamoDbTemplateIntegrationTest.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUpdate_withSingleItemWithCompoundPk() {
    // Given
    final DynamoDbTemplate dynamoDbTemplate = new DynamoDbTemplate(databaseSchemaHolder);
    dynamoDbTemplate.initialize(amazonDynamoDbClient);
    final StubWithRangeItem createdItem = dataGenerator.createStubWithRangeItem();
    final Long originalVersion = createdItem.getVersion();
    final String stringProperty = randomString(10);
    final boolean booleanProperty = randomBoolean();
    final Set<String> newStringSetProperty = Sets.newSet(randomString(10), randomString(10), randomString(10));
    createdItem.setStringProperty(stringProperty);
    createdItem.setBooleanProperty(booleanProperty);
    createdItem.setStringSetProperty(newStringSetProperty);
    final Long newVersion = originalVersion + 1;

    // When
    final StubWithRangeItem updatedItem = dynamoDbTemplate.update(createdItem);

    // Then
    assertEquals(newVersion, updatedItem.getVersion());
    assertEquals(createdItem.getId(), updatedItem.getId());
    assertEquals(stringProperty, updatedItem.getStringProperty());
    assertEquals(booleanProperty, updatedItem.isBooleanProperty());
    assertEquals(newStringSetProperty, updatedItem.getStringSetProperty());
}
 
Example #28
Source File: ItemHashUtilTest.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testHashBaseForItemAttachments() throws IOException, NoSuchAlgorithmException,
        IdUnusedException, PermissionException, TypeException, ServerOverloadException {
    final ItemData item = new ItemData();
    item.setTypeId(TypeIfc.FILL_IN_BLANK);

    final ItemAttachment attachment1 = new ItemAttachment(1L, item, idForContentResource(CONTENT_RESOURCES[0]), CONTENT_RESOURCES[0][CR_NAME_IDX], null, Long.MAX_VALUE - 1, null, null, null, null, null, null, null, null);
    final ItemAttachment attachment2 = new ItemAttachment(2L, item, idForContentResource(CONTENT_RESOURCES[1]), CONTENT_RESOURCES[1][CR_NAME_IDX], null, Long.MAX_VALUE, null, null, null, null, null, null, null, null);

    // this assertion and the intentional backward add to the attachment set are *mild* attempt at ensuring
    // they're sorted in lexical order before being added to the hash base
    assertThat(attachment1.getResourceId(), lessThan(attachment2.getResourceId()));
    item.setItemAttachmentSet(Sets.newSet(attachment1, attachment2));

    // for a straight-up attachment (as opposed to an inlined HTML doc containing question or answer text),
    // we hash the attachment contents, not a doc referring to the attachment.
    ArrayList<String[]> contentResourceDefs1 = new ArrayList<>();
    contentResourceDefs1.add(CONTENT_RESOURCES[0]);
    contentResourceDefs1.add(CONTENT_RESOURCES[1]);

    final StringBuilder expectedHashBase = new StringBuilder()
            .append(expectedContentResourceHashAttachments(contentResourceDefs1));

    expectServerUrlLookup();
    expectResourceLookup(CONTENT_RESOURCES[0]);
    expectResourceLookup(CONTENT_RESOURCES[1]);

    final StringBuilder actualHashBase = new StringBuilder();
    itemHashUtil.hashBaseForItemAttachments(item, actualHashBase);
    assertThat(actualHashBase.toString(), equalTo(expectedHashBase.toString()));
}
 
Example #29
Source File: IamPrincipalPermissionsValidatorTest.java    From cerberus with Apache License 2.0 5 votes vote down vote up
@Test
public void set_can_handle_case_sensitivity() {

  IamPrincipalPermission a = new IamPrincipalPermission();
  a.withIamPrincipalArn("arn:aws:iam::123:role/abc");
  IamPrincipalPermission b = new IamPrincipalPermission();
  b.withIamPrincipalArn("arn:aws:iam::123:role/ABC");

  Assert.assertTrue(subject.isValid(Sets.newSet(a, b), mockConstraintValidatorContext));
}
 
Example #30
Source File: SubutaiAppenderTest.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppend() throws Exception
{

    doReturn( SubutaiAppender.MIN_REPORT_LOG_LEVEL ).when( loggingEvent ).getLevel();
    doReturn( throwableInformation ).when( loggingEvent ).getThrowableInformation();
    doReturn( throwable ).when( throwableInformation ).getThrowable();
    subutaiAppender.listeners = Sets.newSet(listener);

    subutaiAppender.append( loggingEvent );

    verify( notifierPool ).execute( isA( Runnable.class ) );
}