/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.elasticsearch.search;

import com.google.common.base.Predicate;
import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.junit.Test;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import static org.elasticsearch.common.settings.Settings.settingsBuilder;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;

@ElasticsearchIntegrationTest.ClusterScope(scope = ElasticsearchIntegrationTest.Scope.SUITE)
@LuceneTestCase.Slow
public class SearchWithRejectionsTests extends ElasticsearchIntegrationTest {
    @Override
    public Settings nodeSettings(int nodeOrdinal) {
        return settingsBuilder().put(super.nodeSettings(nodeOrdinal))
                .put("threadpool.search.type", "fixed")
                .put("threadpool.search.size", 1)
                .put("threadpool.search.queue_size", 1)
                .build();
    }

    @Test
    public void testOpenContextsAfterRejections() throws InterruptedException {
        createIndex("test");
        ensureGreen("test");
        final int docs = scaledRandomIntBetween(20, 50);
        for (int i = 0; i < docs; i++) {
            client().prepareIndex("test", "type", Integer.toString(i)).setSource("field", "value").execute().actionGet();
        }
        IndicesStatsResponse indicesStats = client().admin().indices().prepareStats().execute().actionGet();
        assertThat(indicesStats.getTotal().getSearch().getOpenContexts(), equalTo(0l));
        refresh();

        int numSearches = 10;
        Future<SearchResponse>[] responses = new Future[numSearches];
        SearchType searchType = randomFrom(SearchType.DEFAULT, SearchType.QUERY_AND_FETCH, SearchType.QUERY_THEN_FETCH, SearchType.DFS_QUERY_AND_FETCH, SearchType.DFS_QUERY_THEN_FETCH);
        logger.info("search type is {}", searchType);
        for (int i = 0; i < numSearches; i++) {
            responses[i] = client().prepareSearch()
                    .setQuery(matchAllQuery())
                    .setSearchType(searchType)
                    .execute();
        }
        int failures = 0;
        for (int i = 0; i < numSearches; i++) {
            try {
                SearchResponse searchResponse = responses[i].get();
                if (searchResponse.getFailedShards() > 0) {
                    failures++;
                }
            } catch (Throwable t) {
                failures++;
            }
        }
        assertThat(failures, greaterThanOrEqualTo(1));
        awaitBusy(new Predicate<Object>() {
            @Override
            public boolean apply(Object input) {
                // we must wait here because the requests to release search contexts might still be in flight
                // although the search request has already returned
                return client().admin().indices().prepareStats().execute().actionGet().getTotal().getSearch().getOpenContexts() == 0;
            }
        }, 1, TimeUnit.SECONDS);
        indicesStats = client().admin().indices().prepareStats().execute().actionGet();
        assertThat(indicesStats.getTotal().getSearch().getOpenContexts(), equalTo(0l));
    }
}

@@ -3244,34 +3244,8 @@
   %7D%0A
-        int failures = 0;%0A
     
@@ -3326,312 +3326,87 @@
     
-SearchResponse searchResponse = responses%5Bi%5D.get();%0A                if (searchResponse.getFailedShards() %3E 0) %7B%0A                    failures++;%0A                %7D%0A            %7D catch (Throwable t) %7B%0A                failures++;%0A            %7D%0A        %7D%0A        assertThat(failures, greaterThanOrEqualTo(1));
+responses%5Bi%5D.get();%0A            %7D catch (Throwable t) %7B%0A            %7D%0A        %7D
 %0A   

remove check for failure, might rarely not fail at all