@Test
 public void removeConnection() throws Exception {
   ConnectionFactoryRegistry connectionFactoryLocator = new ConnectionFactoryRegistry();
   ConnectionFactory<TestApi2> connectionFactory =
       new StubOAuth2ConnectionFactory("clientId", "clientSecret", THROW_EXCEPTION);
   connectionFactoryLocator.addConnectionFactory(connectionFactory);
   StubConnectionRepository connectionRepository = new StubConnectionRepository();
   connectionRepository.addConnection(
       connectionFactory.createConnection(
           new ConnectionData(
               "oauth2Provider", "provider1User1", null, null, null, null, null, null, null)));
   connectionRepository.addConnection(
       connectionFactory.createConnection(
           new ConnectionData(
               "oauth2Provider", "provider1User2", null, null, null, null, null, null, null)));
   assertEquals(2, connectionRepository.findConnections("oauth2Provider").size());
   ConnectController connectController =
       new ConnectController(connectionFactoryLocator, connectionRepository);
   List<DisconnectInterceptor<?>> interceptors = getDisconnectInterceptor();
   connectController.setDisconnectInterceptors(interceptors);
   MockMvc mockMvc = standaloneSetup(connectController).build();
   mockMvc
       .perform(delete("/connect/oauth2Provider/provider1User1"))
       .andExpect(redirectedUrl("/connect/oauth2Provider"));
   assertEquals(1, connectionRepository.findConnections("oauth2Provider").size());
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(0))).preDisconnectInvoked);
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(0))).postDisconnectInvoked);
   assertNull(((TestConnectInterceptor<?>) (interceptors.get(0))).connectionFactory);
   assertTrue(((TestConnectInterceptor<?>) (interceptors.get(1))).preDisconnectInvoked);
   assertTrue(((TestConnectInterceptor<?>) (interceptors.get(1))).postDisconnectInvoked);
   assertSame(
       connectionFactory, ((TestConnectInterceptor<?>) (interceptors.get(1))).connectionFactory);
 }
Example #2
1
 public <T extends AbstractTask> T createTask(Class<T> type, Project project, String name) {
   Task task =
       TASK_FACTORY.createTask(
           (ProjectInternal) project, GUtil.map(Task.TASK_TYPE, type, Task.TASK_NAME, name));
   assertTrue(type.isAssignableFrom(task.getClass()));
   return type.cast(task);
 }
  @Test
  public void testDataSourceRepo() throws SQLException, RepositoryException {
    DataSourceWorkflowRepository repo = new DataSourceWorkflowRepository(ds);

    // test id 1
    WorkflowCondition wc = repo.getWorkflowConditionById("1");
    assertEquals(wc.getConditionName(), "CheckCond");
    WorkflowConditionInstance condInst =
        GenericWorkflowObjectFactory.getConditionObjectFromClassName(
            wc.getConditionInstanceClassName());
    Metadata m = new Metadata();
    m.addMetadata("Met1", "Val1");
    m.addMetadata("Met2", "Val2");
    m.addMetadata("Met3", "Val3");
    assertTrue(condInst.evaluate(m, wc.getTaskConfig()));

    // test id 2
    wc = repo.getWorkflowConditionById("2");
    assertEquals(wc.getConditionName(), "FalseCond");
    condInst =
        GenericWorkflowObjectFactory.getConditionObjectFromClassName(
            wc.getConditionInstanceClassName());
    assertFalse(condInst.evaluate(m, wc.getTaskConfig()));

    // test id 3
    wc = repo.getWorkflowConditionById("3");
    assertEquals(wc.getConditionName(), "TrueCond");
    condInst =
        GenericWorkflowObjectFactory.getConditionObjectFromClassName(
            wc.getConditionInstanceClassName());
    assertTrue(condInst.evaluate(m, wc.getTaskConfig()));
  }
  @Test
  public void write_onPatchWithInnerObject_fullyWritesInnerObject() {
    TestData original = new TestData();
    TestData updated = new TestData();
    updated.setInnerData(new InnerTestData());

    Patch<TestData> patch =
        MakePatch.from(original).to(updated).with(new ReflectivePatchCalculator<>());
    JsonObject json = toJson(patch);

    assertTrue(json.has("innerData"));
    assertTrue(json.get("innerData").isJsonObject());

    JsonObject innerJson = json.get("innerData").getAsJsonObject();
    Collection<String[]> fields =
        Collections2.transform(
            innerJson.entrySet(),
            entry -> new String[] {entry.getKey(), entry.getValue().getAsString()});
    assertThat(
        fields,
        containsInAnyOrder(
            new String[] {"json-name-alias", "inner-named-value"},
            new String[] {"name1", "inner-value-1"},
            new String[] {"name2", "inner-value-2"}));
  }
  @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);
      }
    };
  }
  @Test
  public void testRemoveAndWriteAllReentrance() {
    EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
    final PendingWriteQueue queue = new PendingWriteQueue(channel.pipeline().firstContext());

    ChannelPromise promise = channel.newPromise();
    promise.addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            queue.removeAndWriteAll();
          }
        });
    queue.add(1L, promise);

    ChannelPromise promise2 = channel.newPromise();
    queue.add(2L, promise2);
    queue.removeAndWriteAll();
    channel.flush();
    assertTrue(promise.isSuccess());
    assertTrue(promise2.isSuccess());
    assertTrue(channel.finish());

    assertEquals(1L, channel.readOutbound());
    assertEquals(2L, channel.readOutbound());
    assertNull(channel.readOutbound());
    assertNull(channel.readInbound());
  }
Example #7
0
  @Test
  public void testCopyColumnsToDirectory() throws Exception {
    this.setup.groupBySetup();

    String uriTemplate = Paths.get(folder.getRoot().toURI()).toUri().toString();
    SQLResponse response =
        execute(
            "copy characters (name, details['job']) to DIRECTORY ?", new Object[] {uriTemplate});
    assertThat(response.cols().length, is(0));
    assertThat(response.rowCount(), is(7L));
    List<String> lines = new ArrayList<>(7);
    DirectoryStream<Path> stream =
        Files.newDirectoryStream(Paths.get(folder.getRoot().toURI()), "*.json");
    for (Path entry : stream) {
      lines.addAll(Files.readAllLines(entry, StandardCharsets.UTF_8));
    }
    Path path = Paths.get(folder.getRoot().toURI().resolve("characters_0_.json"));
    assertTrue(path.toFile().exists());
    assertThat(lines.size(), is(7));

    boolean foundJob = false;
    boolean foundName = false;
    for (String line : lines) {
      foundName = foundName || line.contains("Arthur Dent");
      foundJob = foundJob || line.contains("Sandwitch Maker");
      assertThat(line.split(",").length, is(2));
      assertThat(line.trim(), startsWith("["));
      assertThat(line.trim(), endsWith("]"));
    }
    assertTrue(foundJob);
    assertTrue(foundName);
  }
Example #8
0
 @Test
 public void testLateRegisterSuccess() throws Exception {
   TestEventLoopGroup group = new TestEventLoopGroup();
   try {
     ServerBootstrap bootstrap = new ServerBootstrap();
     bootstrap.group(group);
     bootstrap.channel(LocalServerChannel.class);
     bootstrap.childHandler(new DummyHandler());
     bootstrap.localAddress(new LocalAddress("1"));
     ChannelFuture future = bootstrap.bind();
     assertFalse(future.isDone());
     group.promise.setSuccess();
     final BlockingQueue<Boolean> queue = new LinkedBlockingQueue<Boolean>();
     future.addListener(
         new ChannelFutureListener() {
           @Override
           public void operationComplete(ChannelFuture future) throws Exception {
             queue.add(future.channel().eventLoop().inEventLoop(Thread.currentThread()));
             queue.add(future.isSuccess());
           }
         });
     assertTrue(queue.take());
     assertTrue(queue.take());
   } finally {
     group.shutdownGracefully();
     group.terminationFuture().sync();
   }
 }
Example #9
0
  @Test
  public void testRefCount() throws IOException {
    final ShardId shardId = new ShardId(new Index("index"), 1);
    DirectoryService directoryService = new LuceneManagedDirectoryService(random());
    Store store =
        new Store(
            shardId,
            ImmutableSettings.EMPTY,
            directoryService,
            randomDistributor(directoryService),
            new DummyShardLock(shardId));
    int incs = randomIntBetween(1, 100);
    for (int i = 0; i < incs; i++) {
      if (randomBoolean()) {
        store.incRef();
      } else {
        assertTrue(store.tryIncRef());
      }
      store.ensureOpen();
    }

    for (int i = 0; i < incs; i++) {
      store.decRef();
      store.ensureOpen();
    }

    store.incRef();
    final AtomicBoolean called = new AtomicBoolean(false);
    store.close();
    for (int i = 0; i < incs; i++) {
      if (randomBoolean()) {
        store.incRef();
      } else {
        assertTrue(store.tryIncRef());
      }
      store.ensureOpen();
    }

    for (int i = 0; i < incs; i++) {
      store.decRef();
      store.ensureOpen();
    }

    store.decRef();
    assertThat(store.refCount(), Matchers.equalTo(0));
    assertFalse(store.tryIncRef());
    try {
      store.incRef();
      fail(" expected exception");
    } catch (AlreadyClosedException ex) {

    }
    try {
      store.ensureOpen();
      fail(" expected exception");
    } catch (AlreadyClosedException ex) {

    }
  }
 @Test // SPR-11970
 public void fromUriStringNoPathWithReservedCharInQuery() {
   UriComponents result =
       UriComponentsBuilder.fromUriString("http://example.com?foo=bar@baz").build();
   assertTrue(StringUtils.isEmpty(result.getUserInfo()));
   assertEquals("example.com", result.getHost());
   assertTrue(result.getQueryParams().containsKey("foo"));
   assertEquals("bar@baz", result.getQueryParams().getFirst("foo"));
 }
 @Test
 public void isAnnotatedOnClassWithMetaDepth2() {
   assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, TX_NAME));
   assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, Component.class.getName()));
   assertTrue(
       isAnnotated(
           ComposedTransactionalComponentClass.class,
           ComposedTransactionalComponent.class.getName()));
 }
 private static void delete(File directory) {
   for (File file : directory.listFiles()) {
     if (file.isDirectory()) {
       delete(file);
     } else {
       assertTrue(file.delete());
     }
   }
   assertTrue(directory.delete());
 }
 @Test
 public void hasMetaAnnotationTypesOnClassWithMetaDepth2() {
   assertTrue(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, TX_NAME));
   assertTrue(
       hasMetaAnnotationTypes(
           ComposedTransactionalComponentClass.class, Component.class.getName()));
   assertFalse(
       hasMetaAnnotationTypes(
           ComposedTransactionalComponentClass.class,
           ComposedTransactionalComponent.class.getName()));
 }
Example #14
0
  @Test
  public void testDirCreations() throws IOException, PluginException {
    FitNesse fitnesse = context.makeFitNesseContext().fitNesse;
    fitnesse.start();

    try {
      assertTrue(new File("testFitnesseRoot").exists());
      assertTrue(new File("testFitnesseRoot/files").exists());
    } finally {
      fitnesse.stop();
    }
  }
Example #15
0
  @Test
  public void testEqualsContract() {
    IBAN x = IBAN.parse(VALID_IBAN);
    IBAN y = IBAN.parse(VALID_IBAN);
    IBAN z = IBAN.parse(VALID_IBAN);

    assertFalse("No object equals null", x.equals(null));
    assertTrue("An object equals itself", x.equals(x));
    assertTrue("Equality is symmetric", x.equals(y) && y.equals(x));
    assertTrue("Equality is transitive", x.equals(y) && y.equals(z) && x.equals(z));
    assertEquals("Equal objects have the same hash code", x.hashCode(), y.hashCode());
  }
 @Test
 public void getMergedAnnotationAttributesFavorsLocalComposedAnnotationOverInheritedAnnotation() {
   Class<?> element = SubClassWithInheritedAnnotation.class;
   String name = TX_NAME;
   AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
   assertNotNull(
       "AnnotationAttributes for @Transactional on SubClassWithInheritedAnnotation", attributes);
   // Verify contracts between utility methods:
   assertTrue(isAnnotated(element, name));
   assertTrue(
       "readOnly flag for SubClassWithInheritedAnnotation.", attributes.getBoolean("readOnly"));
 }
  @Test
  public void testParseConfiguration() throws Exception {
    JmxTransExporterConfiguration config =
        new JmxTransConfigurationXmlLoader("classpath:jmxtrans-agent.xml").loadConfiguration();

    assertThat(config.collectInterval, is(11));
    assertThat(config.collectIntervalTimeUnit, is(TimeUnit.SECONDS));
    assertThat(config.getConfigReloadInterval(), equalTo(-1));

    OutputWriter decoratedOutputWriter = config.outputWriter;
    // CircuitBreaker
    assertTrue(decoratedOutputWriter.getClass().equals(OutputWriterCircuitBreakerDecorator.class));
    OutputWriterCircuitBreakerDecorator circuitBreakerDecorator =
        (OutputWriterCircuitBreakerDecorator) decoratedOutputWriter;
    assertThat(circuitBreakerDecorator.isDisabled(), is(false));

    // Graphite Writer
    assertTrue(
        circuitBreakerDecorator.delegate.getClass().equals(GraphitePlainTextTcpOutputWriter.class));
    GraphitePlainTextTcpOutputWriter graphiteWriter =
        (GraphitePlainTextTcpOutputWriter) circuitBreakerDecorator.delegate;
    assertThat(graphiteWriter.graphiteServerHostAndPort.getPort(), is(2203));
    assertThat(graphiteWriter.graphiteServerHostAndPort.getHost(), is("localhost"));
    assertThat(graphiteWriter.getMetricPathPrefix(), is("app_123456.server.i876543."));

    assertThat(config.queries.size(), is(13));

    Map<String, Query> queriesByResultAlias = indexQueriesByResultAlias(config.queries);

    {
      Query query = queriesByResultAlias.get("os.systemLoadAverage");
      assertThat(query.objectName, is(new ObjectName("java.lang:type=OperatingSystem")));
      assertThat(query.getAttributes(), contains("SystemLoadAverage"));
      assertThat(query.resultAlias, is("os.systemLoadAverage"));
      assertThat(query.key, is((String) null));
    }
    {
      Query query = queriesByResultAlias.get("jvm.heapMemoryUsage.used");
      assertThat(query.objectName, is(new ObjectName("java.lang:type=Memory")));
      assertThat(query.getAttributes(), contains("HeapMemoryUsage"));
      assertThat(query.resultAlias, is("jvm.heapMemoryUsage.used"));
      assertThat(query.key, is("used"));
    }
    Map<String, Invocation> invocationsByResultAlias =
        indexInvocationsByResultAlias(config.invocations);
    {
      Invocation invocation = invocationsByResultAlias.get("jvm.gc");
      assertThat(invocation.objectName, is(new ObjectName("java.lang:type=Memory")));
      assertThat(invocation.operationName, is("gc"));
      assertThat(invocation.resultAlias, is("jvm.gc"));
    }
  }
 @Test
 public void shouldFindChangedFiles() throws IOException {
   Set<File> files = detector.findChangedFiles();
   assertTrue("Should have found changed files on first run", files.size() > 0);
   assertThat(
       "TestFakeProduct should be in changed list",
       files,
       hasItem(getFileForClass(TestFakeProduct.class)));
   assertTrue(
       "FakeProduct should be in changed list",
       files.contains(getFileForClass(FakeProduct.class)));
   assertTrue("Should have no changed files now", detector.findChangedFiles().isEmpty());
 }
Example #19
0
 @Test
 public void testTask() {
   assertTrue(getTask().isEnabled());
   assertEquals(TEST_TASK_NAME, getTask().getName());
   assertNull(getTask().getDescription());
   assertSame(project, getTask().getProject());
   assertEquals(getExpectedStandardOutputCapture(), getTask().getStandardOutputCapture());
   assertEquals(new HashMap(), getTask().getAdditionalProperties());
   assertNotNull(getTask().getInputs());
   assertNotNull(getTask().getOutputs());
   assertNotNull(getTask().getOnlyIf());
   assertTrue(getTask().getOnlyIf().isSatisfiedBy(getTask()));
 }
Example #20
0
 @Test
 public void testExecuteWithExistingWrapperJarParentDirAndExistingWrapperJar() throws IOException {
   File jarDir = new File(getProject().getProjectDir(), "lib");
   jarDir.mkdirs();
   File wrapperJar = new File(getProject().getProjectDir(), targetWrapperJarPath);
   File parentFile = expectedTargetWrapperJar.getParentFile();
   assertTrue(parentFile.isDirectory() || parentFile.mkdirs());
   try {
     assertTrue(expectedTargetWrapperJar.createNewFile());
   } catch (IOException e) {
     throw new RuntimeException(String.format("Could not create %s.", wrapperJar), e);
   }
   checkExecute();
 }
 @Test
 public void oauth2Callback() throws Exception {
   ConnectionFactoryRegistry connectionFactoryLocator = new ConnectionFactoryRegistry();
   ConnectionFactory<TestApi2> connectionFactory =
       new StubOAuth2ConnectionFactory("clientId", "clientSecret");
   connectionFactoryLocator.addConnectionFactory(connectionFactory);
   StubConnectionRepository connectionRepository = new StubConnectionRepository();
   ConnectController connectController =
       new ConnectController(connectionFactoryLocator, connectionRepository);
   List<ConnectInterceptor<?>> interceptors = getConnectInterceptor();
   connectController.setConnectInterceptors(interceptors);
   connectController.afterPropertiesSet();
   MockMvc mockMvc = standaloneSetup(connectController).build();
   assertEquals(0, connectionRepository.findConnections("oauth2Provider").size());
   mockMvc
       .perform(get("/connect/oauth2Provider").param("code", "oauth2Code"))
       .andExpect(redirectedUrl("/connect/oauth2Provider"));
   List<Connection<?>> connections = connectionRepository.findConnections("oauth2Provider");
   assertEquals(1, connections.size());
   assertEquals("oauth2Provider", connections.get(0).getKey().getProviderId());
   // Check for postConnect() only. The preConnect() is only invoked during the initial portion of
   // the flow
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(0))).postConnectInvoked);
   TestConnectInterceptor<?> testInterceptor2 = (TestConnectInterceptor<?>) (interceptors.get(1));
   assertTrue(testInterceptor2.postConnectInvoked);
 }
  @Test
  @LocalData
  @Issue("jenkinsci/docker-plugin/issues/263")
  public void load080Config() {
    final DockerCloud dock = (DockerCloud) j.getInstance().getCloud("someCloud");
    assertThat(dock.getTemplates(), hasSize(6));

    final DockerTemplate template = dock.getTemplate("somedomain.com:5000/dockerbuild");
    assertThat(template, notNullValue());

    assertThat(template.getLabelString(), equalTo("dockerbuild-local"));
    assertThat(template.remoteFs, equalTo("/home/jenkins"));

    final DockerTemplateBase tBase = template.getDockerTemplateBase();
    assertThat(tBase, notNullValue());

    assertThat(tBase.getDockerCommandArray()[0], equalTo("/usr/bin/start-jenkins-slave.sh"));
    assertThat(tBase.getDnsString(), equalTo("8.8.8.8"));

    assertThat(tBase.getVolumesString(), equalTo("/dev/log:/dev/log"));
    assertThat(asList(tBase.getVolumes()), hasSize(1));
    assertThat(tBase.getVolumes()[0], equalTo("/dev/log:/dev/log"));

    assertFalse(tBase.bindAllPorts);
    assertTrue(tBase.privileged);
  }
 @Test
 public void testInvalidOption() {
   Session session = Session.createTestSession();
   session.handleInput("bogus");
   assertEquals(Constants.invalidOptionString, session.history(-2));
   assertTrue(session.lastMessage().startsWith(Constants.mainMenuString));
 }
  @Test
  public void actions_uses_action_factory_to_create_ExamineAnItem_action_for_all_visible_items() {
    final Item visibleItem = mockery.mock(Item.class, "visible item");
    final Item invisibleItem = mockery.mock(Item.class, "invisible item");
    final ActionFactory actionFactory = mockery.mock(ActionFactory.class);
    final Action examineAnItemAction = mockery.mock(Action.class);
    final List<Item> visibleItems = new ArrayList<Item>();
    visibleItems.add(visibleItem);
    mockery.checking(
        new Expectations() {
          {
            allowing(visibleItem).visible();
            will(returnValue(true));
            ignoring(visibleItem);
            allowing(invisibleItem).visible();
            will(returnValue(false));
            ignoring(invisibleItem);
            oneOf(actionFactory).createExamineAnItemAction(with(equal(visibleItems)));
            will(returnValue(examineAnItemAction));
            ignoring(actionFactory);
          }
        });
    Location l = new Location("", "", null, actionFactory);
    l.addItem(visibleItem);
    l.addItem(invisibleItem);

    List<Action> actions = l.actions();
    assertTrue(actions.size() > 0);
    assertThat(actions.get(0), is(examineAnItemAction));
  }
 @Test
 public void connect_OAuth1Provider() throws Exception {
   ConnectionFactoryRegistry connectionFactoryLocator = new ConnectionFactoryRegistry();
   ConnectionFactory<TestApi1> connectionFactory =
       new StubOAuth1ConnectionFactory("clientId", "clientSecret");
   connectionFactoryLocator.addConnectionFactory(connectionFactory);
   ConnectController connectController = new ConnectController(connectionFactoryLocator, null);
   List<ConnectInterceptor<?>> interceptors = getConnectInterceptor();
   connectController.setConnectInterceptors(interceptors);
   connectController.afterPropertiesSet();
   MockMvc mockMvc = standaloneSetup(connectController).build();
   mockMvc
       .perform(post("/connect/oauth1Provider"))
       .andExpect(
           redirectedUrl("https://someprovider.com/oauth/authorize?oauth_token=requestToken"))
       .andExpect(
           request()
               .sessionAttribute(
                   "oauthToken",
                   samePropertyValuesAs(new OAuthToken("requestToken", "requestTokenSecret"))));
   // Check for preConnect() only. The postConnect() won't be invoked until after callback
   TestConnectInterceptor<?> textInterceptor1 = (TestConnectInterceptor<?>) (interceptors.get(0));
   assertTrue(textInterceptor1.preConnectInvoked);
   assertEquals("oauth1Provider", textInterceptor1.connectionFactory.getProviderId());
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(1))).preConnectInvoked);
 }
  @Test
  public void convertsJodaTimeTypesCorrectly() {

    List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
    converters.add(new LocalDateToDateConverter());
    converters.add(new DateToLocalDateConverter());

    List<Class<?>> customSimpleTypes = new ArrayList<Class<?>>();
    customSimpleTypes.add(LocalDate.class);
    mappingContext.setCustomSimpleTypes(customSimpleTypes);

    converter = new MappingMongoConverter(mappingContext);
    converter.setConverters(converters);
    converter.afterPropertiesSet();

    Person person = new Person();
    person.birthDate = new LocalDate();

    DBObject dbObject = new BasicDBObject();
    converter.write(person, dbObject);

    assertTrue(dbObject.get("birthDate") instanceof Date);

    Person result = converter.read(Person.class, dbObject);
    assertThat(result.birthDate, is(notNullValue()));
  }
Example #27
0
  @Test
  public void existReturnsWhetherAnEntityCanBeLoaded() throws Exception {

    flushTestUsers();
    assertTrue(userDao.exists(id));
    assertFalse(userDao.exists(id * 27));
  }
Example #28
0
  @Test
  public void savingEmptyCollectionIsNoOp() throws Exception {

    List<User> result = userDao.save(new ArrayList<User>());
    assertNotNull(result);
    assertTrue(result.isEmpty());
  }
Example #29
0
  @Test
  public void savingNullCollectionIsNoOp() throws Exception {

    List<User> result = userDao.save((Collection<User>) null);
    assertNotNull(result);
    assertTrue(result.isEmpty());
  }
  @Test
  public void testPartitionedBy() throws Exception {
    CreateTableAnalyzedStatement analysis =
        (CreateTableAnalyzedStatement)
            analyze(
                "create table my_table ("
                    + "  id integer,"
                    + "  no_index string index off,"
                    + "  name string,"
                    + "  date timestamp"
                    + ") partitioned by (name)");
    assertThat(analysis.partitionedBy().size(), is(1));
    assertThat(analysis.partitionedBy().get(0), contains("name", "string"));

    // partitioned columns must be not indexed in mapping
    Map<String, Object> nameMapping =
        (Map<String, Object>) analysis.mappingProperties().get("name");
    assertThat(
        mapToSortedString(nameMapping), is("doc_values=false, index=no, store=false, type=string"));

    Map<String, Object> metaMapping = (Map) analysis.mapping().get("_meta");
    assertThat((Map<String, Object>) metaMapping.get("columns"), not(hasKey("name")));
    List<List<String>> partitionedByMeta = (List<List<String>>) metaMapping.get("partitioned_by");
    assertTrue(analysis.isPartitioned());
    assertThat(partitionedByMeta.size(), is(1));
    assertThat(partitionedByMeta.get(0).get(0), is("name"));
    assertThat(partitionedByMeta.get(0).get(1), is("string"));
  }