@Test
  public void testUnknownFunction() throws Throwable {
    // will be wrapped somewhere above
    expectedException.expect(IllegalArgumentException.class);
    expectedException.expectMessage("Cannot find implementation for function unknown()");

    Symbol unknownFunction =
        new Function(
            new FunctionInfo(
                new FunctionIdent("unknown", ImmutableList.<DataType>of()), DataTypes.BOOLEAN),
            ImmutableList.<Symbol>of());
    CollectPhase collectNode =
        new CollectPhase(
            UUID.randomUUID(),
            0,
            "unknownFunction",
            testRouting,
            Collections.singletonList(unknownFunction),
            EMPTY_PROJECTIONS);
    try {
      getBucket(collectNode);
    } catch (ExecutionException e) {
      throw e.getCause();
    }
  }
  @Test
  public void orderByDescTest()
      throws IOException, SqlParseException, SQLFeatureNotSupportedException {
    SearchHits response =
        query(String.format("SELECT age FROM %s/account ORDER BY age DESC LIMIT 1000", TEST_INDEX));
    SearchHit[] hits = response.getHits();

    ArrayList<Integer> ages = new ArrayList<Integer>();
    for (SearchHit hit : hits) {
      ages.add((int) hit.getSource().get("age"));
    }

    ArrayList<Integer> sortedAges = (ArrayList<Integer>) ages.clone();
    Collections.sort(sortedAges, Collections.reverseOrder());
    Assert.assertTrue("The list is not ordered descending", sortedAges.equals(ages));
  }
  @Test
  public void testCollectUnknownReference() throws Throwable {
    expectedException.expect(UnhandledServerException.class);
    expectedException.expectMessage("Unknown Reference some.table.some_column");

    Reference unknownReference =
        new Reference(
            new ReferenceInfo(
                new ReferenceIdent(new TableIdent("some", "table"), "some_column"),
                RowGranularity.NODE,
                DataTypes.BOOLEAN));
    CollectPhase collectNode =
        new CollectPhase(
            UUID.randomUUID(),
            0,
            "unknown",
            testRouting,
            Collections.<Symbol>singletonList(unknownReference),
            EMPTY_PROJECTIONS);
    collectNode.maxRowGranularity(RowGranularity.NODE);
    try {
      getBucket(collectNode);
    } catch (ExecutionException e) {
      throw e.getCause();
    }
  }
  public void testMultiPercolate() {
    String multiPercolateShardAction = MultiPercolateAction.NAME + "[shard][s]";
    interceptTransportActions(multiPercolateShardAction);

    client().prepareIndex("test-get", "type", "1").setSource("field", "value").get();

    MultiPercolateRequest multiPercolateRequest = new MultiPercolateRequest();
    List<String> indices = new ArrayList<>();
    int numRequests = iterations(1, 30);
    for (int i = 0; i < numRequests; i++) {
      String[] indicesOrAliases = randomIndicesOrAliases();
      Collections.addAll(indices, indicesOrAliases);
      PercolateRequest percolateRequest =
          new PercolateRequest().indices(indicesOrAliases).documentType("type");
      if (randomBoolean()) {
        percolateRequest.getRequest(new GetRequest("test-get", "type", "1"));
      } else {
        percolateRequest.source("\"field\":\"value\"");
      }
      multiPercolateRequest.add(percolateRequest);
    }

    internalCluster().clientNodeClient().multiPercolate(multiPercolateRequest).actionGet();

    clearInterceptedActions();
    assertIndicesSubset(indices, multiPercolateShardAction);
  }
  @Test
  public void testBenchmarkWithErrors() {
    List<SearchRequest> reqList = new ArrayList<>();
    int numQueries = scaledRandomIntBetween(20, 100);
    int numErrors = scaledRandomIntBetween(1, numQueries);
    final boolean containsFatal = randomBoolean();
    if (containsFatal) {
      ScriptScoreFunctionBuilder scriptFunction =
          scriptFunction("DOES NOT COMPILE - fails on any shard");
      SearchRequest searchRequest =
          searchRequest()
              .source(
                  searchSource()
                      .query(functionScoreQuery(FilterBuilders.matchAllFilter(), scriptFunction)));
      reqList.add(searchRequest);
    }
    for (int i = 0; reqList.size() < numErrors; i++) {
      ScriptScoreFunctionBuilder scriptFunction = scriptFunction("throw new RuntimeException();");
      SearchRequest searchRequest =
          searchRequest()
              .source(
                  searchSource()
                      .query(functionScoreQuery(FilterBuilders.matchAllFilter(), scriptFunction)));
      reqList.add(searchRequest);
    }
    logger.info("--> run with [{}] errors ", numErrors);
    for (int i = 0; reqList.size() < numQueries; i++) {

      reqList.add(BenchmarkTestUtil.randomSearch(client(), indices));
    }
    Collections.shuffle(reqList, getRandom());

    final BenchmarkRequest request =
        BenchmarkTestUtil.randomRequest(
            client(),
            indices,
            numExecutorNodes,
            competitionSettingsMap,
            reqList.toArray(new SearchRequest[0]));
    logger.info(
        "--> Submitting benchmark - competitors [{}] iterations [{}]",
        request.competitors().size(),
        request.settings().iterations());
    final BenchmarkResponse response = client().bench(request).actionGet();

    assertThat(response, notNullValue());
    if (response.hasErrors() || containsFatal) {
      assertThat(response.state(), equalTo(BenchmarkResponse.State.FAILED));
    } else {
      assertThat(response.state(), equalTo(BenchmarkResponse.State.COMPLETE));
      for (CompetitionResult result : response.competitionResults().values()) {
        assertThat(result.nodeResults().size(), equalTo(numExecutorNodes));
        validateCompetitionResult(
            result, competitionSettingsMap.get(result.competitionName()), true);
      }
    }
    assertThat(response.benchmarkName(), equalTo(BENCHMARK_NAME));
  }
  @Test
  public void orderByDescTest()
      throws IOException, SqlParseException, SQLFeatureNotSupportedException {
    ArrayList<Long> agesCount = new ArrayList<>();

    Aggregations result =
        query(
            String.format(
                "SELECT COUNT(*) FROM %s/account GROUP BY age ORDER BY COUNT(*) DESC", TEST_INDEX));
    Terms age = result.get("age");

    for (Terms.Bucket bucket : age.getBuckets()) {
      agesCount.add(((ValueCount) bucket.getAggregations().get("COUNT(*)")).getValue());
    }

    ArrayList<Long> sortedAgesCount = (ArrayList<Long>) agesCount.clone();
    Collections.sort(sortedAgesCount, Collections.reverseOrder());
    Assert.assertTrue("The list is not ordered descending", agesCount.equals(agesCount));
  }
  @Test
  public void testCollectExpressions() throws Exception {
    CollectPhase collectNode =
        new CollectPhase(
            UUID.randomUUID(),
            0,
            "collect",
            testRouting,
            Collections.<Symbol>singletonList(testNodeReference),
            EMPTY_PROJECTIONS);
    collectNode.maxRowGranularity(RowGranularity.NODE);

    Bucket result = getBucket(collectNode);

    assertThat(result.size(), equalTo(1));
    assertThat(result, contains(isRow((short) 1)));
  }
  @Test
  public void orderByAscFieldWithSpaceTest()
      throws IOException, SqlParseException, SQLFeatureNotSupportedException {
    SearchHits response =
        query(
            String.format(
                "SELECT * FROM %s/phrase_2 ORDER BY `test field` ASC LIMIT 1000", TEST_INDEX));
    SearchHit[] hits = response.getHits();

    ArrayList<Integer> testFields = new ArrayList<Integer>();
    for (SearchHit hit : hits) {
      testFields.add((int) hit.getSource().get("test field"));
    }

    ArrayList<Integer> sortedTestFields = (ArrayList<Integer>) testFields.clone();
    Collections.sort(sortedTestFields);
    Assert.assertTrue("The list is not ordered ascending", sortedTestFields.equals(testFields));
  }
  @Test
  public void shouldAlsoLookForClassesInClassDirectories() throws Exception {
    newDir = new File("tempClassDir");
    List<File> buildPaths = asList(newDir);
    ClasspathProvider classpath =
        new StandaloneClasspath(
            Collections.<File>emptyList(),
            buildPaths,
            FakeEnvironments.systemClasspath() + pathSeparator + newDir.getAbsolutePath());

    String classname = "org.fakeco.Foobar2";
    createClass(classname);

    builder = new JavaClassBuilder(classpath);
    JavaClass javaClass = builder.createClass(classname);
    assertEquals(classname, javaClass.getName());
    assertFalse(javaClass.isATest());
  }
 synchronized void interceptTransportActions(String... actions) {
   Collections.addAll(this.actions, actions);
 }