@Test
 public void BuildListWith1Item() {
   List<String> documentClassCodeList = new ArrayList<String>();
   documentClassCodeList.add("classcode1");
   String classCodes = DocumentClassCodeParser.buildDocumentClassCodeItem(documentClassCodeList);
   assertEquals("('classcode1')", classCodes);
 }
예제 #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));
 }
예제 #3
0
 public List<TestFile> files(Object... paths) {
   List<TestFile> files = new ArrayList<TestFile>();
   for (Object path : paths) {
     files.add(file(path));
   }
   return files;
 }
예제 #4
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");
   }
 }
예제 #5
0
  @Test
  public void rejectAllStorageOperationsBeingInInappropriateState() throws Exception {

    // -- generate list of "inappropriate" states
    final List<String> states = new LinkedList<>();
    final EnumSet<StorageNode.StorageState> allowedStates =
        EnumSet.of(StorageNode.StorageState.RECOVERING, StorageNode.StorageState.RUNNING);

    for (StorageNode.StorageState s : StorageNode.StorageState.values()) {
      if (!allowedStates.contains(s)) {
        states.add(s.name());
      }
    }

    // --
    for (String s : states) {
      if (!node.getState().equals(s)) {
        manageNode(new ControlMessage.Builder().setState(s));
      }

      assertEquals(s, node.getState());

      for (StorageOperation op : allOperations) {
        // TODO: rewrite with Exception Matcher to introduce message checking
        try {
          node.onStorageRequest(op);
          fail();
        } catch (IllegalStateException ex) {
        }
      }
    }
  }
예제 #6
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());
  }
예제 #7
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));
 }
예제 #8
0
  @Test
  public void test_find_children_2() {
    for (boolean left : new boolean[] {true, false}) {
      for (boolean right : new boolean[] {true, false}) {
        List keys = new ArrayList();
        for (int i = 0; i < 100; i += 10) {
          keys.add(i);
        }

        int[] child = new int[keys.size() + (right ? 1 : 0) + (left ? 1 : 0)];
        Arrays.fill(child, 11);
        if (right) child[child.length - 1] = 0;

        BTreeMap.BNode n = new BTreeMap.DirNode(keys.toArray(), left, right, false, mkchild(child));

        for (int i = -10; i < 110; i++) {
          int pos = BTreeKeySerializer.BASIC.findChildren(n, i);
          int expected = (i + (left ? 19 : 9)) / 10;
          expected = Math.max(left ? 1 : 0, expected);
          expected = Math.min(left ? 11 : 10, expected);
          assertEquals("i:" + i + " - l:" + left + " - r:" + right, expected, pos);
        }
      }
    }
  }
  /**
   * Test usage from multiple threads.
   *
   * @throws InterruptedException if interrupted
   */
  public final void testInstancesUsedFromMultipleThreads() throws InterruptedException {
    final Set<Touchable> set = Collections.synchronizedSet(new HashSet<Touchable>());
    final List<Touchable> list = Collections.synchronizedList(new ArrayList<Touchable>());
    final ComponentAdapter componentAdapter =
        new ThreadLocalizing.ThreadLocalized(
            new ConstructorInjection.ConstructorInjector(
                Touchable.class, SimpleTouchable.class, null));
    final Touchable touchable =
        (Touchable) componentAdapter.getComponentInstance(null, ComponentAdapter.NOTHING.class);

    final Thread[] threads = {
      new Thread(new Runner(touchable, list, set), "junit-1"),
      new Thread(new Runner(touchable, list, set), "junit-2"),
      new Thread(new Runner(touchable, list, set), "junit-3"),
    };
    for (int i = threads.length; i-- > 0; ) {
      threads[i].start();
    }
    Thread.sleep(300);
    for (int i = threads.length; i-- > 0; ) {
      synchronized (threads[i]) {
        threads[i].notifyAll();
      }
    }
    Thread.sleep(300);
    for (int i = threads.length; i-- > 0; ) {
      threads[i].interrupt();
    }
    Thread.sleep(300);
    assertEquals(6, list.size());
    assertEquals(3, set.size());
  }
 @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());
 }
  @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);
      }
    };
  }
예제 #12
0
  @Test
  public void insertChildrenAtPosition() {
    Document doc =
        Jsoup.parse(
            "<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>");
    Element div1 = doc.select("div").get(0);
    Elements p1s = div1.select("p");
    Element div2 = doc.select("div").get(1);

    assertEquals(2, div2.childNodeSize());
    div2.insertChildren(-1, p1s);
    assertEquals(2, div1.childNodeSize()); // moved two out
    assertEquals(4, div2.childNodeSize());
    assertEquals(3, p1s.get(1).siblingIndex()); // should be last

    List<Node> els = new ArrayList<Node>();
    Element el1 = new Element(Tag.valueOf("span"), "").text("Span1");
    Element el2 = new Element(Tag.valueOf("span"), "").text("Span2");
    TextNode tn1 = new TextNode("Text4", "");
    els.add(el1);
    els.add(el2);
    els.add(tn1);

    assertNull(el1.parent());
    div2.insertChildren(-2, els);
    assertEquals(div2, el1.parent());
    assertEquals(7, div2.childNodeSize());
    assertEquals(3, el1.siblingIndex());
    assertEquals(4, el2.siblingIndex());
    assertEquals(5, tn1.siblingIndex());
  }
예제 #13
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();
  }
예제 #14
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());
  }
예제 #15
0
  @Test
  public void testAdd() throws DatabaseException {

    Project census = new Project("census", 2, 3, 4, 5);
    Project births = new Project("births", 6, 7, 8, 9);

    dbProjects.add(census);
    dbProjects.add(births);

    List<Project> all = dbProjects.getAll();
    assertEquals(2, all.size());

    boolean foundAge = false;
    boolean foundPlace = false;

    for (Project p : all) {

      assertFalse(p.getId() == -1);

      if (!foundAge) {
        foundAge = areEqual(p, census, false);
      }
      if (!foundPlace) {
        foundPlace = areEqual(p, births, false);
      }
    }

    assertTrue(foundAge && foundPlace);
  }
예제 #16
0
 // #list-validate
 public List<ValidationError> validate() {
   List<ValidationError> errors = new ArrayList<ValidationError>();
   if (User.byEmail(email) != null) {
     errors.add(new ValidationError("email", "This e-mail is already registered."));
   }
   return errors.isEmpty() ? null : errors;
 }
  @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));
  }
예제 #18
0
  @Test
  public void insert_many_reopen_check() throws InterruptedException {
    e = openEngine();
    int max = 1000;
    int size = 100000;
    Random r = new Random(0);
    List<Long> recids = new ArrayList<Long>();
    for (int j = 0; j < max; j++) {
      byte[] b = new byte[r.nextInt(size)];
      r.nextBytes(b);
      long recid = e.put(b, Serializer.BYTE_ARRAY_NOSIZE);
      recids.add(recid);
    }
    e.commit();

    reopen();

    r = new Random(0);
    for (long recid : recids) {
      byte[] b = new byte[r.nextInt(size)];
      r.nextBytes(b);
      byte[] b2 = e.get(recid, Serializer.BYTE_ARRAY_NOSIZE);
      assertTrue("Data were not commited recid=" + recid, Arrays.equals(b, b2));
    }
  }
예제 #19
0
  @Test
  public void testCreateAndDropManyDatabases() throws Exception {
    List<String> createdDatabases = new ArrayList<>();
    InfoSchemaMetadataDictionary dictionary = new InfoSchemaMetadataDictionary();
    String namePrefix = "database_";
    final int NUM = 10;
    for (int i = 0; i < NUM; i++) {
      String databaseName = namePrefix + i;
      assertFalse(catalog.existDatabase(databaseName));
      catalog.createDatabase(databaseName, TajoConstants.DEFAULT_TABLESPACE_NAME);
      assertTrue(catalog.existDatabase(databaseName));
      createdDatabases.add(databaseName);
    }

    Collection<String> allDatabaseNames = catalog.getAllDatabaseNames();
    for (String databaseName : allDatabaseNames) {
      assertTrue(
          databaseName.equals(DEFAULT_DATABASE_NAME)
              || createdDatabases.contains(databaseName)
              || dictionary.isSystemDatabase(databaseName));
    }
    // additional ones are 'default' and 'system' databases.
    assertEquals(NUM + 2, allDatabaseNames.size());

    Collections.shuffle(createdDatabases);
    for (String tobeDropped : createdDatabases) {
      assertTrue(catalog.existDatabase(tobeDropped));
      catalog.dropDatabase(tobeDropped);
      assertFalse(catalog.existDatabase(tobeDropped));
    }
  }
 private List<String> dependenciesOf(Package source) {
   List<String> result = new ArrayList<>();
   if (source.isAnnotationPresent(DependsUpon.class))
     for (Class<?> target : source.getAnnotation(DependsUpon.class).packagesOf())
       result.add(target.getPackage().getName());
   return result;
 }
예제 #21
0
  @Test
  public void testDelTail() {
    System.out.println("\n___ TEST DEL TAIL____\n");
    List<Object> l = new ArrayList<Object>();
    l.add("a");
    l.add("b");
    l.add("c");
    l.add("d");
    l.add("e");
    l.add("f");
    l.add("g");

    DifTree test = DifTreeImpl.create(l);
    System.out.println("Del everything from the Tail");
    System.out.println(test);
    test.delTail();
    System.out.println(test);
    test.delTail();
    System.out.println(test);
    test.delTail();
    System.out.println(test);
    test.delTail();
    System.out.println(test);
    test.delTail();
    System.out.println(test);
    test.delTail();
    System.out.println(test);
    test.delTail();
    System.out.println(test);
    assertTrue(true);
  }
예제 #22
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"));
  }
예제 #24
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());
  }
예제 #25
0
  @Test
  public void testUtilDate() {
    sql2o
        .createQuery("create table testutildate(id int primary key, d1 datetime, d2 timestamp)")
        .executeUpdate();

    sql2o
        .createQuery("insert into testutildate(id, d1, d2) values(:id, :d1, :d2)")
        .addParameter("id", 1)
        .addParameter("d1", new Date())
        .addParameter("d2", new Date())
        .addToBatch()
        .addParameter("id", 2)
        .addParameter("d1", new Date())
        .addParameter("d2", new Date())
        .addToBatch()
        .addParameter("id", 3)
        .addParameter("d1", new Date())
        .addParameter("d2", new Date())
        .addToBatch()
        .executeBatch();

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

    assertTrue(list.size() == 3);
  }
예제 #26
0
  @Test
  public void testCaseInsensitive() {
    sql2o
        .createQuery(
            "create table testCI(id2 int primary key, value2 varchar(20), sometext varchar(20), valwithgetter varchar(20))")
        .executeUpdate();

    Query query =
        sql2o.createQuery(
            "insert into testCI(id2, value2, sometext, valwithgetter) values(:id, :value, :someText, :valwithgetter)");
    for (int i = 0; i < 20; i++) {
      query
          .addParameter("id", i)
          .addParameter("value", "some text " + i)
          .addParameter("someText", "whatever " + i)
          .addParameter("valwithgetter", "spaz" + i)
          .addToBatch();
    }
    query.executeBatch();

    List<CIEntity> ciEntities =
        sql2o
            .createQuery("select * from testCI")
            .setCaseSensitive(false)
            .executeAndFetch(CIEntity.class);

    assertTrue(ciEntities.size() == 20);

    // test defaultCaseSensitive;
    sql2o.setDefaultCaseSensitive(false);
    List<CIEntity> ciEntities2 =
        sql2o.createQuery("select * from testCI").executeAndFetch(CIEntity.class);
    assertTrue(ciEntities2.size() == 20);
  }
예제 #27
0
  private List<String> executeDDL(
      String ddlFileName,
      @Nullable String dataFileName,
      boolean isLocalTable,
      @Nullable String[] args)
      throws Exception {

    Path ddlFilePath = new Path(currentQueryPath, ddlFileName);
    FileSystem fs = ddlFilePath.getFileSystem(conf);
    assertTrue(ddlFilePath + " existence check", fs.exists(ddlFilePath));

    String template = FileUtil.readTextFile(new File(ddlFilePath.toUri()));
    String dataFilePath = null;
    if (dataFileName != null) {
      dataFilePath = getDataSetFile(dataFileName).toString();
    }
    String compiled = compileTemplate(template, dataFilePath, args);

    List<ParsedResult> parsedResults = SimpleParser.parseScript(compiled);
    List<String> createdTableNames = new ArrayList<String>();

    for (ParsedResult parsedResult : parsedResults) {
      // parse a statement
      Expr expr = sqlParser.parse(parsedResult.getStatement());
      assertNotNull(ddlFilePath + " cannot be parsed", expr);

      if (expr.getType() == OpType.CreateTable) {
        CreateTable createTable = (CreateTable) expr;
        String tableName = createTable.getTableName();
        assertTrue("Table creation is failed.", client.updateQuery(parsedResult.getStatement()));
        TableDesc createdTable = client.getTableDesc(tableName);
        String createdTableName = createdTable.getName();

        assertTrue(
            "table '" + createdTableName + "' creation check", client.existTable(createdTableName));
        if (isLocalTable) {
          createdTableGlobalSet.add(createdTableName);
          createdTableNames.add(tableName);
        }
      } else if (expr.getType() == OpType.DropTable) {
        DropTable dropTable = (DropTable) expr;
        String tableName = dropTable.getTableName();
        assertTrue(
            "table '" + tableName + "' existence check",
            client.existTable(CatalogUtil.buildFQName(currentDatabase, tableName)));
        assertTrue("table drop is failed.", client.updateQuery(parsedResult.getStatement()));
        assertFalse(
            "table '" + tableName + "' dropped check",
            client.existTable(CatalogUtil.buildFQName(currentDatabase, tableName)));
        if (isLocalTable) {
          createdTableGlobalSet.remove(tableName);
        }
      } else {
        assertTrue(ddlFilePath + " is not a Create or Drop Table statement", false);
      }
    }

    return createdTableNames;
  }
예제 #28
0
 static ServerMessage doTxRx(ClientMessage... cms) {
   List<ClientMessage> cmArray = new ArrayList<ClientMessage>();
   for (ClientMessage cm : cms) {
     cmArray.add(cm);
   }
   ServerMessage result = doTxRx(cmArray);
   return result;
 }
예제 #29
0
 @Test
 public void testExists() throws Exception {
   List<Integer> list = List.list(1, 2, 3, 4, 5, 6, 7, 8);
   assertTrue(list.exists(x -> x < 4));
   assertFalse(list.exists(x -> x < 1));
   assertTrue(list.exists(x -> x > 0));
   assertTrue(list.exists(x -> x > 4));
 }
예제 #30
0
 @Test
 public void testExistsEmpty() throws Exception {
   List<Integer> list = List.list();
   assertFalse(list.exists(x -> x < 4));
   assertFalse(list.exists(x -> x < 1));
   assertFalse(list.exists(x -> x > 0));
   assertFalse(list.exists(x -> x > 4));
 }