Exemplo n.º 1
0
 @Test
 public void test2() {
   List<Integer> input = new ArrayList<>(Arrays.asList(1, 2, 3));
   List<Integer> output = new ArrayList<>(Arrays.asList(3, 2, 1));
   WithList.reverse(input);
   for (int i = 0; i < input.size(); i++) assertEquals(output.get(i), input.get(i));
 }
Exemplo n.º 2
0
 /** Reads a custom schema. */
 @Test
 public void testCustomSchema() throws IOException {
   final ObjectMapper mapper = mapper();
   JsonRoot root =
       mapper.readValue(
           "{\n"
               + "  version: '1.0',\n"
               + "   schemas: [\n"
               + "     {\n"
               + "       type: 'custom',\n"
               + "       name: 'My Custom Schema',\n"
               + "       factory: 'com.acme.MySchemaFactory',\n"
               + "       operand: {a: 'foo', b: [1, 3.5] }\n"
               + "     }\n"
               + "   ]\n"
               + "}",
           JsonRoot.class);
   assertEquals("1.0", root.version);
   assertEquals(1, root.schemas.size());
   final JsonCustomSchema schema = (JsonCustomSchema) root.schemas.get(0);
   assertEquals("My Custom Schema", schema.name);
   assertEquals("com.acme.MySchemaFactory", schema.factory);
   assertEquals("foo", schema.operand.get("a"));
   assertNull(schema.operand.get("c"));
   assertTrue(schema.operand.get("b") instanceof List);
   final List list = (List) schema.operand.get("b");
   assertEquals(2, list.size());
   assertEquals(1, list.get(0));
   assertEquals(3.5, list.get(1));
 }
Exemplo n.º 3
0
  @Test
  public void canFollowLogfile() throws IOException {
    File tempFile =
        File.createTempFile("commons-io", "", new File(System.getProperty("java.io.tmpdir")));
    tempFile.deleteOnExit();
    System.out.println("Temp file = " + tempFile.getAbsolutePath());
    PrintStream log = new PrintStream(tempFile);
    LogfileFollower follower = new LogfileFollower(tempFile);
    List<String> lines;

    // Empty file:
    lines = follower.newLines();
    assertEquals(0, lines.size());

    // Write two lines:
    log.println("Line 1");
    log.println("Line 2");
    lines = follower.newLines();
    assertEquals(2, lines.size());
    assertEquals("Line 2", lines.get(1));

    // Write one more line:
    log.println("Line 3");
    lines = follower.newLines();
    assertEquals(1, lines.size());
    assertEquals("Line 3", lines.get(0));

    // Write one and a half line and finish later:
    log.println("Line 4");
    log.print("Line 5 begin");
    lines = follower.newLines();
    assertEquals(1, lines.size());

    // End last line and start a new one:
    log.println(" end");
    log.print("Line 6 begin");
    lines = follower.newLines();
    assertEquals(1, lines.size());
    assertEquals("Line 5 begin end", lines.get(0));

    // End last line:
    log.println(" end");
    lines = follower.newLines();
    assertEquals(1, lines.size());
    assertEquals("Line 6 begin end", lines.get(0));

    // A line only missing a newline:
    log.print("Line 7");
    lines = follower.newLines();
    assertEquals(0, lines.size());
    log.println();
    lines = follower.newLines();
    assertEquals(1, lines.size());
    assertEquals("Line 7", lines.get(0));

    // Delete:
    log.close();
    lines = follower.newLines();
    assertEquals(0, lines.size());
  }
Exemplo n.º 4
0
  /**
   * Test importing of Clinical Data File.
   *
   * @throws DaoException Database Access Error.
   * @throws IOException IO Error.
   */
  @Test
  @Ignore("To be fixed")
  public void testImportClinicalDataSurvival() throws Exception {

    // TBD: change this to use getResourceAsStream()
    File clinicalFile = new File("target/test-classes/clinical_data.txt");
    ImportClinicalData importClinicalData = new ImportClinicalData(study, clinicalFile);
    importClinicalData.importData();

    LinkedHashSet<String> caseSet = new LinkedHashSet<String>();
    caseSet.add("TCGA-A1-A0SB");
    caseSet.add("TCGA-A1-A0SI");
    caseSet.add("TCGA-A1-A0SE");

    List<Patient> clinicalCaseList =
        DaoClinicalData.getSurvivalData(study.getInternalId(), caseSet);
    assertEquals(3, clinicalCaseList.size());

    Patient clinical0 = clinicalCaseList.get(0);
    assertEquals(new Double(79.04), clinical0.getAgeAtDiagnosis());
    assertEquals("DECEASED", clinical0.getOverallSurvivalStatus());
    assertEquals("Recurred/Progressed", clinical0.getDiseaseFreeSurvivalStatus());
    assertEquals(new Double(43.8), clinical0.getOverallSurvivalMonths());
    assertEquals(new Double(15.05), clinical0.getDiseaseFreeSurvivalMonths());

    Patient clinical1 = clinicalCaseList.get(1);
    assertEquals(new Double(55.53), clinical1.getAgeAtDiagnosis());
    assertEquals("LIVING", clinical1.getOverallSurvivalStatus());
    assertEquals("DiseaseFree", clinical1.getDiseaseFreeSurvivalStatus());
    assertEquals(new Double(49.02), clinical1.getOverallSurvivalMonths());
    assertEquals(new Double(49.02), clinical1.getDiseaseFreeSurvivalMonths());

    Patient clinical2 = clinicalCaseList.get(2);
    assertEquals(null, clinical2.getDiseaseFreeSurvivalMonths());
  }
Exemplo n.º 5
0
  @Test
  public void testEnums() {
    sql2o
        .createQuery(
            "create table EnumTest(id int identity primary key, enum_val varchar(10), enum_val2 int) ")
        .executeUpdate();

    sql2o
        .createQuery("insert into EnumTest(enum_val, enum_val2) values (:val, :val2)")
        .addParameter("val", TestEnum.HELLO)
        .addParameter("val2", TestEnum.HELLO.ordinal())
        .addToBatch()
        .addParameter("val", TestEnum.WORLD)
        .addParameter("val2", TestEnum.WORLD.ordinal())
        .addToBatch()
        .executeBatch();

    List<EntityWithEnum> list =
        sql2o
            .createQuery("select id, enum_val val, enum_val2 val2 from EnumTest")
            .executeAndFetch(EntityWithEnum.class);

    assertThat(list.get(0).val, is(TestEnum.HELLO));
    assertThat(list.get(0).val2, is(TestEnum.HELLO));
    assertThat(list.get(1).val, is(TestEnum.WORLD));
    assertThat(list.get(1).val2, is(TestEnum.WORLD));

    TestEnum testEnum =
        sql2o.createQuery("select 'HELLO' from (values(0))").executeScalar(TestEnum.class);
    assertThat(testEnum, is(TestEnum.HELLO));

    TestEnum testEnum2 =
        sql2o.createQuery("select NULL from (values(0))").executeScalar(TestEnum.class);
    assertThat(testEnum2, is(nullValue()));
  }
  /**
   * Tests that the system.peers table is not updated after a node has been removed. (See
   * CASSANDRA-6053)
   */
  @Test
  public void testStateChangeOnRemovedNode() throws UnknownHostException {
    StorageService ss = StorageService.instance;
    VersionedValue.VersionedValueFactory valueFactory =
        new VersionedValue.VersionedValueFactory(partitioner);

    // create a ring of 2 nodes
    ArrayList<Token> endpointTokens = new ArrayList<>();
    List<InetAddress> hosts = new ArrayList<>();
    Util.createInitialRing(
        ss, partitioner, endpointTokens, new ArrayList<Token>(), hosts, new ArrayList<UUID>(), 2);

    InetAddress toRemove = hosts.get(1);
    SystemKeyspace.updatePeerInfo(toRemove, "data_center", "dc42");
    SystemKeyspace.updatePeerInfo(toRemove, "rack", "rack42");
    assertEquals("rack42", SystemKeyspace.loadDcRackInfo().get(toRemove).get("rack"));

    // mark the node as removed
    Gossiper.instance.injectApplicationState(
        toRemove,
        ApplicationState.STATUS,
        valueFactory.left(
            Collections.singleton(endpointTokens.get(1)), Gossiper.computeExpireTime()));
    assertTrue(
        Gossiper.instance.isDeadState(Gossiper.instance.getEndpointStateForEndpoint(hosts.get(1))));

    // state changes made after the endpoint has left should be ignored
    ss.onChange(hosts.get(1), ApplicationState.RACK, valueFactory.rack("rack9999"));
    assertEquals("rack42", SystemKeyspace.loadDcRackInfo().get(toRemove).get("rack"));
  }
Exemplo n.º 7
0
  @Test
  public void testCreateOrganizationAndAdminWithConfirmationAndActivation() throws Exception {
    setup.set(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS, "true");
    setup.set(PROPERTIES_NOTIFY_ADMIN_OF_ACTIVATION, "true");
    setup.set(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS, "false");
    setup.set(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION, "true");

    final String orgName = uniqueOrg();
    final String userName = uniqueUsername();
    final String email = uniqueEmail();

    OrganizationOwnerInfo org_owner =
        createOwnerAndOrganization(
            orgName, userName, "Test User", email, "testpassword", false, false);

    assertNotNull(org_owner);

    List<Message> user_inbox = Mailbox.get(email);

    assertFalse(user_inbox.isEmpty());

    Message confirmation = user_inbox.get(0);
    assertEquals("User Account Confirmation: " + email, confirmation.getSubject());

    String token = getTokenFromMessage(confirmation);
    logger.info(token);

    ActivationState state =
        setup.getMgmtSvc().handleConfirmationTokenForAdminUser(org_owner.owner.getUuid(), token);
    assertEquals(ActivationState.CONFIRMED_AWAITING_ACTIVATION, state);

    confirmation = user_inbox.get(1);
    String body =
        ((MimeMultipart) confirmation.getContent()).getBodyPart(0).getContent().toString();
    Boolean subbedEmailed = StringUtils.contains(body, "$");

    assertFalse(subbedEmailed);

    assertEquals("User Account Confirmed", confirmation.getSubject());

    List<Message> sysadmin_inbox = Mailbox.get("*****@*****.**");
    assertFalse(sysadmin_inbox.isEmpty());

    Message activation = sysadmin_inbox.get(0);
    assertEquals("Request For Admin User Account Activation " + email, activation.getSubject());

    token = getTokenFromMessage(activation);
    logger.info(token);

    state = setup.getMgmtSvc().handleActivationTokenForAdminUser(org_owner.owner.getUuid(), token);
    assertEquals(ActivationState.ACTIVATED, state);

    Message activated = user_inbox.get(2);
    assertEquals("User Account Activated", activated.getSubject());

    MockImapClient client = new MockImapClient("mockserver.com", "test-user-2", "somepassword");
    client.processMail();
  }
  private void doControlTask() throws IOException, ClassNotFoundException {
    BlockingTaskSummaryResponseHandler handler = new BlockingTaskSummaryResponseHandler();
    client.getTasksAssignedAsPotentialOwner("control", "en-UK", handler);
    List<TaskSummary> sums = handler.getResults();
    assertNotNull(sums);
    assertEquals(1, sums.size());

    BlockingTaskOperationResponseHandler startTaskOperationHandler =
        new BlockingTaskOperationResponseHandler();
    client.start(sums.get(0).getId(), "control", startTaskOperationHandler);

    BlockingGetTaskResponseHandler getTaskHandler = new BlockingGetTaskResponseHandler();
    client.getTask(sums.get(0).getId(), getTaskHandler);
    Task controlTask = getTaskHandler.getTask();

    BlockingGetContentResponseHandler getContentHandler = new BlockingGetContentResponseHandler();
    client.getContent(controlTask.getTaskData().getDocumentContentId(), getContentHandler);
    Content content = getContentHandler.getContent();

    assertNotNull(content);

    ByteArrayInputStream bais = new ByteArrayInputStream(content.getContent());
    ObjectInputStream ois = new ObjectInputStream(bais);
    Map<String, Object> deserializedContent = (Map<String, Object>) ois.readObject();
    Emergency retrivedEmergency = (Emergency) deserializedContent.get("emergency");
    assertNotNull(retrivedEmergency);
    ActivePatients retrivedActivePatients =
        (ActivePatients) deserializedContent.get("activePatients");
    assertNotNull(retrivedActivePatients);
    assertEquals(1, retrivedActivePatients.size());
    SuggestedProcedures retrivedSuggestedProcedures =
        (SuggestedProcedures) deserializedContent.get("suggestedProcedures");
    assertNotNull(retrivedSuggestedProcedures);
    assertEquals(
        "[DefaultHeartAttackProcedure: ]",
        retrivedSuggestedProcedures.getSuggestedProceduresString());

    Map<String, Object> info = new HashMap<String, Object>();
    SelectedProcedures selectedProcedures = new SelectedProcedures(retrivedEmergency.getId());

    selectedProcedures.addSelectedProcedureName("DefaultHeartAttackProcedure");
    info.put("selectedProcedures", selectedProcedures);

    ContentData result = new ContentData();
    result.setAccessType(AccessType.Inline);
    result.setType("java.util.Map");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bos);
    out.writeObject(info);
    out.close();
    result.setContent(bos.toByteArray());

    BlockingTaskOperationResponseHandler completeTaskOperationHandler =
        new BlockingTaskOperationResponseHandler();
    client.complete(sums.get(0).getId(), "control", result, completeTaskOperationHandler);
  }
 private void assertResultFromTextFileParsing(List<String[]> result) {
   assertEquals(2, result.size());
   String[] line1 = result.get(0);
   assertEquals(1, line1.length);
   assertEquals("line1", line1[0]);
   String[] line2 = result.get(1);
   assertEquals(2, line2.length);
   assertEquals("another", line2[0]);
   assertEquals("line", line2[1]);
 }
  @Test
  public void testStateJumpToLeft() throws UnknownHostException {
    StorageService ss = StorageService.instance;
    TokenMetadata tmd = ss.getTokenMetadata();
    tmd.clearUnsafe();
    IPartitioner partitioner = RandomPartitioner.instance;
    VersionedValue.VersionedValueFactory valueFactory =
        new VersionedValue.VersionedValueFactory(partitioner);

    ArrayList<Token> endpointTokens = new ArrayList<Token>();
    ArrayList<Token> keyTokens = new ArrayList<Token>();
    List<InetAddress> hosts = new ArrayList<InetAddress>();
    List<UUID> hostIds = new ArrayList<UUID>();

    // create a ring of 6 nodes
    Util.createInitialRing(ss, partitioner, endpointTokens, keyTokens, hosts, hostIds, 7);

    // node hosts.get(2) goes jumps to left
    ss.onChange(
        hosts.get(2),
        ApplicationState.STATUS,
        valueFactory.left(
            Collections.singleton(endpointTokens.get(2)), Gossiper.computeExpireTime()));

    assertFalse(tmd.isMember(hosts.get(2)));

    // node hosts.get(4) goes to bootstrap
    Gossiper.instance.injectApplicationState(
        hosts.get(3),
        ApplicationState.TOKENS,
        valueFactory.tokens(Collections.singleton(keyTokens.get(1))));
    ss.onChange(
        hosts.get(3),
        ApplicationState.STATUS,
        valueFactory.bootstrapping(Collections.<Token>singleton(keyTokens.get(1))));

    assertFalse(tmd.isMember(hosts.get(3)));
    assertEquals(1, tmd.getBootstrapTokens().size());
    assertEquals(hosts.get(3), tmd.getBootstrapTokens().get(keyTokens.get(1)));

    // and then directly to 'left'
    Gossiper.instance.injectApplicationState(
        hosts.get(2),
        ApplicationState.TOKENS,
        valueFactory.tokens(Collections.singleton(keyTokens.get(1))));
    ss.onChange(
        hosts.get(2),
        ApplicationState.STATUS,
        valueFactory.left(Collections.singleton(keyTokens.get(1)), Gossiper.computeExpireTime()));

    assertTrue(tmd.getBootstrapTokens().size() == 0);
    assertFalse(tmd.isMember(hosts.get(2)));
    assertFalse(tmd.isLeaving(hosts.get(2)));
  }
 @Test
 public void testFileExtensions() {
   final String[] fileExtensions = plugIn.getDefaultFileExtensions();
   assertNotNull(fileExtensions);
   final List<String> extensionList = Arrays.asList(fileExtensions);
   assertEquals(4, extensionList.size());
   assertEquals(".xml", extensionList.get(0));
   assertEquals(".XML", extensionList.get(1));
   assertEquals(".tgz", extensionList.get(2));
   assertEquals(".TGZ", extensionList.get(3));
 }
Exemplo n.º 12
0
  @Test
  public void testGetElementsWithAttribute() {
    Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>");
    List<Element> els = doc.getElementsByAttribute("style");
    assertEquals(2, els.size());
    assertEquals("div", els.get(0).tagName());
    assertEquals("b", els.get(1).tagName());

    List<Element> none = doc.getElementsByAttribute("class");
    assertEquals(0, none.size());
  }
  private void doOperatorTask() throws ClassNotFoundException, IOException {
    BlockingTaskSummaryResponseHandler handler = new BlockingTaskSummaryResponseHandler();
    client.getTasksAssignedAsPotentialOwner("operator", "en-UK", handler);
    List<TaskSummary> sums = handler.getResults();
    assertNotNull(sums);
    assertEquals(1, sums.size());

    BlockingTaskOperationResponseHandler startTaskOperationHandler =
        new BlockingTaskOperationResponseHandler();
    client.start(sums.get(0).getId(), "operator", startTaskOperationHandler);

    BlockingGetTaskResponseHandler getTaskHandler = new BlockingGetTaskResponseHandler();
    client.getTask(sums.get(0).getId(), getTaskHandler);
    Task operatorTask = getTaskHandler.getTask();

    BlockingGetContentResponseHandler getContentHandler = new BlockingGetContentResponseHandler();
    client.getContent(operatorTask.getTaskData().getDocumentContentId(), getContentHandler);
    Content content = getContentHandler.getContent();

    assertNotNull(content);

    ByteArrayInputStream bais = new ByteArrayInputStream(content.getContent());
    ObjectInputStream ois = new ObjectInputStream(bais);
    Map<String, Object> deserializedContent = (Map<String, Object>) ois.readObject();
    Call restoredCall = (Call) deserializedContent.get("call");
    persistenceService.storeCall(restoredCall);

    Emergency emergency = new Emergency();

    emergency.setCall(restoredCall);

    emergency.setLocation(new Location(1, 2));
    emergency.setType(Emergency.EmergencyType.HEART_ATTACK);
    emergency.setNroOfPeople(1);
    persistenceService.storeEmergency(emergency);

    trackingService.attachEmergency(restoredCall.getId(), emergency.getId());

    Map<String, Object> info = new HashMap<String, Object>();
    info.put("emergency", emergency);

    ContentData result = new ContentData();
    result.setAccessType(AccessType.Inline);
    result.setType("java.util.Map");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bos);
    out.writeObject(info);
    out.close();
    result.setContent(bos.toByteArray());

    BlockingTaskOperationResponseHandler completeTaskOperationHandler =
        new BlockingTaskOperationResponseHandler();
    client.complete(sums.get(0).getId(), "operator", result, completeTaskOperationHandler);
  }
Exemplo n.º 14
0
  @Test
  public void testGetTextNodes() {
    Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>");
    List<TextNode> textNodes = doc.select("p").first().textNodes();

    assertEquals(3, textNodes.size());
    assertEquals("One ", textNodes.get(0).text());
    assertEquals(" Three ", textNodes.get(1).text());
    assertEquals(" Four", textNodes.get(2).text());

    assertEquals(0, doc.select("br").first().textNodes().size());
  }
Exemplo n.º 15
0
  @Test
  public void testExecuteAndFetchResultSet() throws SQLException {
    List<Integer> list =
        sql2o
            .createQuery(
                "select 1 val from (values(0)) union select 2 from (values(0)) union select 3 from (values(0))")
            .executeScalarList();

    assertEquals((int) list.get(0), 1);
    assertEquals((int) list.get(1), 2);
    assertEquals((int) list.get(2), 3);
  }
 @Test
 public void testGetAllPartitionKeys() throws Exception {
   CloudTableClient tableClient = createTableClient();
   assumeNotNull(tableClient);
   t = createTable(tableClient);
   insertRow(t, "p1", "r1");
   insertRow(t, "p1", "r2");
   insertRow(t, "p2", "r1");
   insertRow(t, "p3", "r1");
   List<String> partitionKeys = DefaultTablePartitioner.getAllPartitionKeys(t);
   assertEquals(3, partitionKeys.size());
   assertEquals("p1", partitionKeys.get(0));
   assertEquals("p2", partitionKeys.get(1));
   assertEquals("p3", partitionKeys.get(2));
 }
  @Test
  public void cacheShouldRememberInsertionOrder() {
    Map<String, Set<String>> graph1 = Collections.singletonMap("a", Collections.singleton("b"));
    Map<String, Set<String>> graph2 = Collections.singletonMap("b", Collections.singleton("c"));
    Map<String, Set<String>> graph3 = Collections.singletonMap("c", Collections.singleton("d"));
    cache.putGraph("x", 1, graph1);
    cache.putGraph("z", 2, graph2);
    cache.putGraph("y", 3, graph3);

    List<Object[]> recent = cache.getRecent();

    assertTuple(recent.get(0), "x", 1);
    assertTuple(recent.get(1), "z", 2);
    assertTuple(recent.get(2), "y", 3);
  }
  @Test
  public void testCompareByName() throws Exception {

    final Category cat1 = context.mock(Category.class, "cat1");
    final Category cat2 = context.mock(Category.class, "cat2");

    context.checking(
        new Expectations() {
          {
            allowing(cat1).getRank();
            will(returnValue(0));
            allowing(cat1).getName();
            will(returnValue("name 2"));
            allowing(cat1).getCategoryId();
            will(returnValue(1L));
            allowing(cat2).getRank();
            will(returnValue(0));
            allowing(cat2).getName();
            will(returnValue("name 1"));
          }
        });

    final SortedSet<Category> set = new TreeSet<Category>(new CategoryRankNameComparator());
    set.addAll(Arrays.asList(cat1, cat2));

    final List<Category> list = new ArrayList<Category>(set);
    assertTrue(cat2 == list.get(0));
    assertTrue(cat1 == list.get(1));
  }
Exemplo n.º 19
0
 @Override
 public void verify() throws TransformException {
   ItemList targets = mod.nearest(NodeTarget.class).targets();
   List<Node> references = mod.references();
   ItemList records = mod.supplementQuery().all("sort-proxy");
   assert targets.size() == references.size();
   assert records.size() == references.size();
   for (int i = 0; i < targets.size(); i++) {
     Node target = targets.get(i).node();
     Node restoredProxy = references.get(i);
     ItemList items = query.runOn(mod.scope(target.query()));
     if (items.size() != 1)
       throw new TransformException(
           "sort by corresponding node must select one node per target, but instead selected "
               + items.size()
               + ": "
               + items);
     Node proxy = items.get(0).node();
     if (!restoredProxy.equals(proxy)) throw new TransformException("computed proxy changed");
     if (!proxy
         .query()
         .single(
             "(count(preceding::*) + count(ancestor::*)) eq xs:integer($_1/@position)",
             records.get(i))
         .booleanValue()) throw new SortingException("computed proxy moved");
   }
 }
 @Test
 public void testNetworkConfig() {
   NetworkConfig networkConfig = config.getNetworkConfig();
   assertNotNull(networkConfig);
   assertEquals(5700, networkConfig.getPort());
   assertFalse(networkConfig.isPortAutoIncrement());
   final Collection<String> allowedPorts = networkConfig.getOutboundPortDefinitions();
   assertEquals(2, allowedPorts.size());
   Iterator portIter = allowedPorts.iterator();
   assertEquals("35000-35100", portIter.next());
   assertEquals("36000,36100", portIter.next());
   assertFalse(networkConfig.getJoin().getMulticastConfig().isEnabled());
   assertEquals(networkConfig.getJoin().getMulticastConfig().getMulticastTimeoutSeconds(), 8);
   assertEquals(networkConfig.getJoin().getMulticastConfig().getMulticastTimeToLive(), 16);
   assertFalse(networkConfig.getInterfaces().isEnabled());
   assertEquals(1, networkConfig.getInterfaces().getInterfaces().size());
   assertEquals("10.10.1.*", networkConfig.getInterfaces().getInterfaces().iterator().next());
   TcpIpConfig tcp = networkConfig.getJoin().getTcpIpConfig();
   assertNotNull(tcp);
   assertTrue(tcp.isEnabled());
   assertTrue(networkConfig.getSymmetricEncryptionConfig().isEnabled());
   final List<String> members = tcp.getMembers();
   assertEquals(members.toString(), 2, members.size());
   assertEquals("127.0.0.1:5700", members.get(0));
   assertEquals("127.0.0.1:5701", members.get(1));
   assertEquals("127.0.0.1:5700", tcp.getRequiredMember());
   AwsConfig aws = networkConfig.getJoin().getAwsConfig();
   assertFalse(aws.isEnabled());
   assertEquals("sample-access-key", aws.getAccessKey());
   assertEquals("sample-secret-key", aws.getSecretKey());
   assertEquals("sample-region", aws.getRegion());
   assertEquals("sample-group", aws.getSecurityGroupName());
   assertEquals("sample-tag-key", aws.getTagKey());
   assertEquals("sample-tag-value", aws.getTagValue());
 }
Exemplo n.º 21
0
  @Test
  public void testParameterToPairsWhenValueIsCollection() throws Exception {
    Map<String, String> collectionFormatMap = new HashMap<String, String>();
    collectionFormatMap.put("csv", ",");
    collectionFormatMap.put("tsv", "\t");
    collectionFormatMap.put("ssv", " ");
    collectionFormatMap.put("pipes", "\\|");
    collectionFormatMap.put("", ","); // no format, must default to csv
    collectionFormatMap.put("unknown", ","); // all other formats, must default to csv

    String name = "param-a";

    List<Object> values = new ArrayList<Object>();
    values.add("value-a");
    values.add(123);
    values.add(new Date());

    // check for multi separately
    List<Pair> multiPairs = apiClient.parameterToPairs("multi", name, values);
    assertEquals(values.size(), multiPairs.size());

    // all other formats
    for (String collectionFormat : collectionFormatMap.keySet()) {
      List<Pair> pairs = apiClient.parameterToPairs(collectionFormat, name, values);

      assertEquals(1, pairs.size());

      String delimiter = collectionFormatMap.get(collectionFormat);
      String[] pairValueSplit = pairs.get(0).getValue().split(delimiter);

      // must equal input values
      assertEquals(values.size(), pairValueSplit.length);
    }
  }
  @Test // Uses of JMockit API: 8
  public void useArgumentMatchers() {
    new Expectations() {
      {
        // Using built-in matchers:
        mockedList.get(anyInt);
        result = "element";

        // Using Hamcrest matchers:
        mockedList.get(withArgThat(is(equalTo(5))));
        result = new IllegalArgumentException();
        minTimes = 0;
        mockedList.contains(withArgThat(hasProperty("bytes")));
        result = true;
        mockedList.containsAll(withArgThat(hasSize(2)));
        result = true;
      }
    };

    assertEquals("element", mockedList.get(999));
    assertTrue(mockedList.contains("abc"));
    assertTrue(mockedList.containsAll(asList("a", "b")));

    new Verifications() {
      {
        mockedList.get(anyInt);
      }
    };
  }
Exemplo n.º 23
0
  @Test
  public void getSliceRespectsAllBoundsInclusionArguments() throws Exception {
    // Test case where endColumn=startColumn+1
    ByteBuffer key = KeyColumnValueStoreUtil.longToByteBuffer(0);
    ByteBuffer columnBeforeStart = KeyColumnValueStoreUtil.longToByteBuffer(776);
    ByteBuffer columnStart = KeyColumnValueStoreUtil.longToByteBuffer(777);
    ByteBuffer columnEnd = KeyColumnValueStoreUtil.longToByteBuffer(778);
    ByteBuffer columnAfterEnd = KeyColumnValueStoreUtil.longToByteBuffer(779);

    // First insert four test Entries
    TransactionHandle txn = manager.beginTransaction();
    List<Entry> entries =
        Arrays.asList(
            new Entry(columnBeforeStart, columnBeforeStart),
            new Entry(columnStart, columnStart),
            new Entry(columnEnd, columnEnd),
            new Entry(columnAfterEnd, columnAfterEnd));
    store.mutate(key, entries, null, txn);
    txn.commit();

    // getSlice() with only start inclusive
    txn = manager.beginTransaction();
    List<Entry> result = store.getSlice(key, columnStart, columnEnd, txn);
    assertEquals(1, result.size());
    assertEquals(777, result.get(0).getColumn().getLong());
    txn.commit();
  }
  @Test // Uses of JMockit API: 3
  public void returningElementsFromAList() {
    final List<String> list = asList("a", "b", "c");

    new Expectations() {
      {
        mockedList.get(anyInt);
        result = list;
      }
    };

    assertEquals("a", mockedList.get(0));
    assertEquals("b", mockedList.get(1));
    assertEquals("c", mockedList.get(2));
    assertEquals("c", mockedList.get(3));
  }
Exemplo n.º 25
0
  public void checkSlice(
      String[][] values, Set<KeyColumn> removed, int key, int start, int end, int limit) {
    List<Entry> entries;
    if (limit <= 0)
      entries =
          store.getSlice(
              KeyValueStoreUtil.getBuffer(key),
              KeyValueStoreUtil.getBuffer(start),
              KeyValueStoreUtil.getBuffer(end),
              tx);
    else
      entries =
          store.getSlice(
              KeyValueStoreUtil.getBuffer(key),
              KeyValueStoreUtil.getBuffer(start),
              KeyValueStoreUtil.getBuffer(end),
              limit,
              tx);

    int pos = 0;
    for (int i = start; i < end; i++) {
      if (removed.contains(new KeyColumn(key, i))) continue;
      if (limit <= 0 || pos < limit) {
        Entry entry = entries.get(pos);
        int col = KeyValueStoreUtil.getID(entry.getColumn());
        String str = KeyValueStoreUtil.getString(entry.getValue());
        assertEquals(i, col);
        assertEquals(values[key][i], str);
      }
      pos++;
    }
    assertNotNull(entries);
    if (limit > 0 && pos > limit) assertEquals(limit, entries.size());
    else assertEquals(pos, entries.size());
  }
Exemplo n.º 26
0
  @Test
  public void testJodaTime() {

    sql2o
        .createQuery("create table testjoda(id int primary key, joda1 datetime, joda2 datetime)")
        .executeUpdate();

    sql2o
        .createQuery("insert into testjoda(id, joda1, joda2) values(:id, :joda1, :joda2)")
        .addParameter("id", 1)
        .addParameter("joda1", new DateTime())
        .addParameter("joda2", new DateTime().plusDays(-1))
        .addToBatch()
        .addParameter("id", 2)
        .addParameter("joda1", new DateTime().plusYears(1))
        .addParameter("joda2", new DateTime().plusDays(-2))
        .addToBatch()
        .addParameter("id", 3)
        .addParameter("joda1", new DateTime().plusYears(2))
        .addParameter("joda2", new DateTime().plusDays(-3))
        .addToBatch()
        .executeBatch();

    List<JodaEntity> list =
        sql2o.createQuery("select * from testjoda").executeAndFetch(JodaEntity.class);

    assertTrue(list.size() == 3);
    assertTrue(list.get(0).getJoda2().isBeforeNow());
  }
Exemplo n.º 27
0
  @Test
  public void testGetDataNodes() {
    Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>");
    Element script = doc.select("script").first();
    Element style = doc.select("style").first();
    Element p = doc.select("p").first();

    List<DataNode> scriptData = script.dataNodes();
    assertEquals(1, scriptData.size());
    assertEquals("One Two", scriptData.get(0).getWholeData());

    List<DataNode> styleData = style.dataNodes();
    assertEquals(1, styleData.size());
    assertEquals("Three Four", styleData.get(0).getWholeData());

    List<DataNode> pData = p.dataNodes();
    assertEquals(0, pData.size());
  }
Exemplo n.º 28
0
 @Test
 public void testGetRandomPreference() throws Exception {
   int seed = 123;
   int num = 1;
   List<Project> expected = TheRNG().TestRandomPreferenceUtility(preped_s, seed, num);
   TheRNG().setSeed(seed);
   Project got = preped_s.getRandomPreference();
   assertEquals("should equal", expected.get(0), got);
 }
Exemplo n.º 29
0
 @Override
 public void restore() throws TransformException {
   List<Node> references = mod.references();
   ItemList targets = mod.nearest(NodeTarget.class).targets();
   proxies = new ArrayList<Pair<String, Node>>(references.size());
   for (int i = 0; i < references.size(); i++) {
     proxies.add(Pair.of(targets.get(i).query().single("@xml:id").value(), references.get(i)));
   }
 }
Exemplo n.º 30
0
  @Test
  public void testNewResultSet_Contains() throws Exception {

    // Mocks
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connectionContains = mock(Connection.class);
    Connection connectionDoNotContain = mock(Connection.class);
    PreparedStatement preparedStatementContains = mock(PreparedStatement.class);
    PreparedStatement preparedStatementDoNotContains = mock(PreparedStatement.class);
    java.sql.ResultSet resultSetContains = mock(java.sql.ResultSet.class);
    java.sql.ResultSet resultSetDoNotContain = mock(java.sql.ResultSet.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class)))
        .thenReturn(connectionContains)
        .thenReturn(connectionDoNotContain);
    when(connectionContains.prepareStatement(
            "SELECT COUNT(objectKey) FROM " + TABLE_NAME + " WHERE value = ? AND objectKey = ?;"))
        .thenReturn(preparedStatementContains);
    when(connectionDoNotContain.prepareStatement(
            "SELECT COUNT(objectKey) FROM " + TABLE_NAME + " WHERE value = ? AND objectKey = ?;"))
        .thenReturn(preparedStatementDoNotContains);
    when(preparedStatementContains.executeQuery()).thenReturn(resultSetContains);
    when(preparedStatementDoNotContains.executeQuery()).thenReturn(resultSetDoNotContain);
    when(resultSetContains.next()).thenReturn(true).thenReturn(false);
    when(resultSetContains.getInt(1)).thenReturn(1);
    when(resultSetDoNotContain.next()).thenReturn(true).thenReturn(false);
    when(resultSetDoNotContain.getInt(1)).thenReturn(0);

    // Iterator
    ResultSet<Car> carsWithAbs =
        new SQLiteIndex<String, Car, Integer>(
                Car.FEATURES, OBJECT_TO_ID, ID_TO_OBJECT, connectionManager)
            .retrieve(equal(Car.FEATURES, "abs"), new QueryOptions());

    Assert.assertNotNull(carsWithAbs);
    boolean resultContains = carsWithAbs.contains(data.get(0));
    assertTrue(resultContains);
    verify(connectionContains, times(1)).close();

    boolean resultDoNotContain = carsWithAbs.contains(data.get(1));
    assertFalse(resultDoNotContain);
    verify(connectionDoNotContain, times(1)).close();
  }