Test framework library for Elasticsearch providing comprehensive testing utilities, base test classes, cluster management, and assertion helpers for unit and integration testing of Elasticsearch plugins and applications
—
The Elasticsearch test framework provides comprehensive mock implementations for transport, storage, security, and other core systems. These mocks enable controlled testing environments, failure simulation, and isolation of specific components during testing.
The core mock transport service that enables network failure simulation and transport behavior testing.
package org.elasticsearch.test.transport;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.component.Lifecycle;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.transport.*;
/**
* Mock implementation of TransportService that allows injection of transport rules
* for simulating network failures, delays, and other transport-level behaviors.
*/
public class MockTransportService extends TransportService {
/**
* Creates a new MockTransportService with the specified transport.
*
* @param settings service configuration
* @param transport underlying transport implementation
* @param threadPool thread pool for async operations
* @param interceptor transport interceptor for request/response handling
* @param localNodeFactory factory for creating local node representation
* @param clusterSettings cluster-level settings
* @param taskHeaders task header registry
*/
public MockTransportService(Settings settings,
Transport transport,
ThreadPool threadPool,
TransportInterceptor interceptor,
Function<BoundTransportAddress, DiscoveryNode> localNodeFactory,
ClusterSettings clusterSettings,
Set<String> taskHeaders);
/**
* Adds a rule that causes connections to fail when sending to specified nodes.
*
* @param targetNode node to target for failures
* @param action action pattern to match (can use wildcards)
*/
public void addFailToSendNoConnectRule(DiscoveryNode targetNode, String action);
/**
* Adds a rule that causes connections to fail for all actions to a node.
*
* @param targetNode target node for connection failures
*/
public void addFailToSendNoConnectRule(DiscoveryNode targetNode);
/**
* Adds a rule that introduces delays when sending to specified nodes.
*
* @param targetNode node to introduce delays for
* @param action action pattern to match
* @param delay time delay to introduce
*/
public void addSendBehaviorRule(DiscoveryNode targetNode, String action, TimeValue delay);
/**
* Adds a rule that randomly fails requests to simulate unreliable networks.
*
* @param targetNode target node
* @param action action pattern
* @param failureRate probability of failure (0.0 to 1.0)
*/
public void addRandomFailureRule(DiscoveryNode targetNode, String action, double failureRate);
/**
* Adds a rule that blocks requests indefinitely to simulate network partitions.
*
* @param targetNode node to block requests to
* @param action action pattern to block
*/
public void addUnresponsiveRule(DiscoveryNode targetNode, String action);
/**
* Removes all transport rules and returns to normal operation.
*/
public void clearAllRules();
/**
* Removes rules targeting a specific node.
*
* @param targetNode node to clear rules for
*/
public void clearRules(DiscoveryNode targetNode);
/**
* Gets the transport instance used by this service.
*
* @return underlying Transport
*/
public MockTransport transport();
/**
* Interface for defining transport behavior rules.
*/
public static interface TransportRule {
/**
* Applies the rule to an outgoing request.
*
* @param request transport request
* @param connection target connection
* @param requestId request identifier
* @param action action being performed
* @param listener response listener
* @return true if rule was applied, false to continue processing
*/
boolean apply(TransportRequest request,
Connection connection,
long requestId,
String action,
TransportResponseHandler<?> listener);
}
}Transport implementation that captures requests for analysis and verification.
package org.elasticsearch.test.transport;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportRequest;
/**
* Transport implementation that captures all requests and responses for test verification.
* Useful for verifying that specific transport operations occur during testing.
*/
public class CapturingTransport implements Transport {
/**
* Represents a captured transport request.
*/
public static class CapturedRequest {
/** The target node for this request */
public final DiscoveryNode node;
/** The request identifier */
public final long requestId;
/** The action being performed */
public final String action;
/** The request object */
public final TransportRequest request;
public CapturedRequest(DiscoveryNode node, long requestId, String action, TransportRequest request);
}
/**
* Returns all captured requests.
*
* @return list of captured requests
*/
public List<CapturedRequest> getCapturedRequests();
/**
* Returns captured requests for a specific action.
*
* @param action action name to filter by
* @return filtered list of captured requests
*/
public List<CapturedRequest> getCapturedRequestsAndClear(String action);
/**
* Clears all captured requests.
*/
public void clear();
/**
* Sets a response handler for specific actions.
*
* @param action action to handle
* @param response response to return
*/
public void setResponseHandler(String action, TransportResponse response);
/**
* Sets an exception handler for specific actions.
*
* @param action action to handle
* @param exception exception to throw
*/
public void setExceptionHandler(String action, Exception exception);
}Transport with advanced stubbing capabilities for complex test scenarios.
package org.elasticsearch.test.transport;
/**
* Transport implementation with sophisticated stubbing capabilities for complex testing scenarios.
* Allows detailed control over request/response patterns and behavior simulation.
*/
public class StubbableTransport implements Transport {
/**
* Represents a request pattern for stubbing.
*/
public static class RequestPattern {
private final String action;
private final Predicate<TransportRequest> requestMatcher;
public static RequestPattern forAction(String action);
public static RequestPattern matching(String action, Predicate<TransportRequest> matcher);
}
/**
* Stubs responses for requests matching the specified pattern.
*
* @param pattern request pattern to match
* @param response response to return
*/
public StubbableTransport stub(RequestPattern pattern, TransportResponse response);
/**
* Stubs exceptions for requests matching the specified pattern.
*
* @param pattern request pattern to match
* @param exception exception to throw
*/
public StubbableTransport stub(RequestPattern pattern, Exception exception);
/**
* Stubs delayed responses.
*
* @param pattern request pattern to match
* @param response response to return after delay
* @param delay time to wait before responding
*/
public StubbableTransport stubWithDelay(RequestPattern pattern,
TransportResponse response,
TimeValue delay);
/**
* Removes all stubs and returns to pass-through behavior.
*/
public void clearStubs();
}import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.transport.MockTransportService;
public class TransportMockTest extends ESIntegTestCase {
public void testNetworkPartition() {
InternalTestCluster cluster = internalCluster();
cluster.ensureAtLeastNumDataNodes(3);
// Get transport service for a specific node
MockTransportService transportService =
(MockTransportService) cluster.getInstance(TransportService.class, "node1");
// Simulate network partition - block all communication to node2
DiscoveryNode node2 = cluster.clusterService("node2").localNode();
transportService.addUnresponsiveRule(node2);
// Test that operations handle the partition gracefully
try {
createIndex("partition-test");
// Operations should still succeed on available nodes
ensureYellow("partition-test");
} finally {
// Clear rules to restore connectivity
transportService.clearAllRules();
ensureGreen("partition-test");
}
}
public void testTransportFailures() {
InternalTestCluster cluster = internalCluster();
MockTransportService transportService =
(MockTransportService) cluster.getInstance(TransportService.class);
DiscoveryNode targetNode = cluster.clusterService().state().nodes().getDataNodes().values().iterator().next();
// Simulate 50% failure rate for search actions
transportService.addRandomFailureRule(targetNode, "indices:data/read/search", 0.5);
// Test search resilience
createIndex("failure-test");
client().prepareIndex("failure-test")
.setSource("field", "value")
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.get();
// Some searches may fail, but retries should succeed
int successCount = 0;
for (int i = 0; i < 10; i++) {
try {
client().prepareSearch("failure-test").get();
successCount++;
} catch (Exception e) {
// Expected occasional failures
}
}
assertThat("Some searches should succeed", successCount, greaterThan(0));
transportService.clearAllRules();
}
}Mock implementation for secure settings testing.
package org.elasticsearch.common.settings;
import java.io.InputStream;
/**
* Mock implementation of SecureSettings for testing secure configuration handling.
* Allows controlled testing of secure settings without requiring actual keystore files.
*/
public class MockSecureSettings implements SecureSettings {
/**
* Creates a new empty MockSecureSettings instance.
*/
public MockSecureSettings();
/**
* Creates a MockSecureSettings with the specified settings.
*
* @param settings map of setting names to values
*/
public MockSecureSettings(Map<String, String> settings);
/**
* Sets a string value for the specified setting.
*
* @param setting setting name
* @param value string value to set
* @return this MockSecureSettings for fluent chaining
*/
public MockSecureSettings setString(String setting, String value);
/**
* Sets a file content value for the specified setting.
*
* @param setting setting name
* @param bytes file content as byte array
* @return this MockSecureSettings for fluent chaining
*/
public MockSecureSettings setFile(String setting, byte[] bytes);
/**
* Sets a file content value from an InputStream.
*
* @param setting setting name
* @param input stream containing file content
* @return this MockSecureSettings for fluent chaining
*/
public MockSecureSettings setFile(String setting, InputStream input);
/**
* Removes a setting from the mock secure settings.
*
* @param setting setting name to remove
* @return this MockSecureSettings for fluent chaining
*/
public MockSecureSettings remove(String setting);
/**
* Checks if the specified setting exists.
*
* @param setting setting name to check
* @return true if setting exists, false otherwise
*/
@Override
public boolean isLoaded();
/**
* Returns all setting names.
*
* @return set of setting names
*/
@Override
public Set<String> getSettingNames();
/**
* Gets a secure string value.
*
* @param setting setting name
* @return SecureString containing the value
*/
@Override
public SecureString getString(String setting);
/**
* Gets a secure file input stream.
*
* @param setting setting name
* @return InputStream for the file content
*/
@Override
public InputStream getFile(String setting);
/**
* Gets the SHA-256 digest of a file setting.
*
* @param setting setting name
* @return byte array containing SHA-256 hash
*/
@Override
public byte[] getSHA256Digest(String setting);
}Mock repository implementation for testing backup and restore operations.
package org.elasticsearch.repositories;
import org.elasticsearch.cluster.metadata.RepositoryMetadata;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.blobstore.BlobStore;
/**
* Mock repository implementation for testing snapshot and restore operations
* without requiring actual storage backends.
*/
public class MockRepository extends BlobStoreRepository {
/**
* Creates a MockRepository with the specified configuration.
*
* @param metadata repository metadata
* @param clusterService cluster service instance
*/
public MockRepository(RepositoryMetadata metadata, ClusterService clusterService);
/**
* Sets the failure mode for repository operations.
*
* @param failureMode type of failures to simulate
*/
public void setFailureMode(FailureMode failureMode);
/**
* Sets a specific failure for the next operation.
*
* @param operation operation to fail
* @param exception exception to throw
*/
public void setNextFailure(String operation, Exception exception);
/**
* Gets the underlying mock blob store.
*
* @return MockBlobStore instance
*/
public MockBlobStore getMockBlobStore();
/**
* Enumeration of failure modes for repository operations.
*/
public enum FailureMode {
/** No failures */
NONE,
/** Random failures */
RANDOM,
/** All operations fail */
ALL,
/** Only write operations fail */
WRITE_ONLY,
/** Only read operations fail */
READ_ONLY
}
}Mock blob store for testing blob storage operations.
package org.elasticsearch.common.blobstore;
/**
* Mock implementation of BlobStore for testing blob storage operations
* without requiring actual storage infrastructure.
*/
public class MockBlobStore implements BlobStore {
/**
* Creates a new MockBlobStore.
*/
public MockBlobStore();
/**
* Sets the failure probability for blob operations.
*
* @param probability failure probability (0.0 to 1.0)
*/
public void setFailureProbability(double probability);
/**
* Enables or disables atomic move operations.
*
* @param atomic true to enable atomic moves
*/
public void setAtomicMoveSupported(boolean atomic);
/**
* Gets statistics about blob operations performed.
*
* @return BlobStoreStats with operation counts
*/
public BlobStoreStats getStats();
/**
* Resets all statistics counters.
*/
public void resetStats();
/**
* Statistics tracking for mock blob store operations.
*/
public static class BlobStoreStats {
public long readOperations;
public long writeOperations;
public long deleteOperations;
public long listOperations;
public long bytesRead;
public long bytesWritten;
}
}Mock implementation for large array management testing.
package org.elasticsearch.common.util;
import org.elasticsearch.common.breaker.CircuitBreaker;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
/**
* Mock implementation of BigArrays for testing memory management and circuit breaker behavior.
*/
public class MockBigArrays extends BigArrays {
/**
* Creates MockBigArrays with the specified page cache and circuit breaker.
*
* @param pageCacheRecycler page cache for memory reuse
* @param circuitBreakerService circuit breaker for memory tracking
* @param name identifier for this BigArrays instance
*/
public MockBigArrays(PageCacheRecycler pageCacheRecycler,
CircuitBreakerService circuitBreakerService,
String name);
/**
* Sets whether array allocation should be tracked by circuit breakers.
*
* @param track true to enable tracking
*/
public void setTrackAllocations(boolean track);
/**
* Gets the total number of bytes allocated by this instance.
*
* @return bytes allocated
*/
public long getAllocatedBytes();
/**
* Gets the number of active array allocations.
*
* @return active allocation count
*/
public long getActiveAllocations();
}Mock page cache recycler for memory management testing.
package org.elasticsearch.common.util;
/**
* Mock implementation of PageCacheRecycler for testing page-based memory management.
*/
public class MockPageCacheRecycler extends PageCacheRecycler {
/**
* Creates a MockPageCacheRecycler with specified settings.
*
* @param settings configuration settings
*/
public MockPageCacheRecycler(Settings settings);
/**
* Sets the maximum number of pages to cache.
*
* @param maxPages maximum cached page count
*/
public void setMaxCachedPages(int maxPages);
/**
* Gets statistics about page recycling operations.
*
* @return RecyclerStats with operation counts
*/
public RecyclerStats getStats();
/**
* Forces garbage collection of cached pages.
*/
public void forceRecycle();
/**
* Statistics for page recycler operations.
*/
public static class RecyclerStats {
public long pagesAllocated;
public long pagesRecycled;
public long pagesCached;
public long cacheHits;
public long cacheMisses;
}
}import org.elasticsearch.common.settings.MockSecureSettings;
import org.elasticsearch.repositories.MockRepository;
public class MockStorageTest extends ESIntegTestCase {
public void testSecureSettings() {
MockSecureSettings secureSettings = new MockSecureSettings()
.setString("xpack.security.authc.api_key.hashing.algorithm", "pbkdf2")
.setFile("xpack.ssl.keystore.path", keystoreBytes);
Settings settings = Settings.builder()
.setSecureSettings(secureSettings)
.build();
// Test that secure settings are properly loaded
assertTrue(settings.getSecureSettings().isLoaded());
assertThat(settings.getSecureSettings().getSettingNames(),
hasItems("xpack.security.authc.api_key.hashing.algorithm",
"xpack.ssl.keystore.path"));
}
public void testRepositoryFailures() {
// Create a mock repository with failure simulation
MockRepository mockRepo = new MockRepository(
new RepositoryMetadata("test-repo", "mock", Settings.EMPTY),
clusterService()
);
// Configure to fail write operations randomly
mockRepo.setFailureMode(MockRepository.FailureMode.WRITE_ONLY);
// Test snapshot creation with failures
try {
client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snapshot")
.setWaitForCompletion(true)
.get();
fail("Expected snapshot to fail");
} catch (SnapshotException e) {
// Expected failure due to mock repository configuration
}
// Reset to normal operation
mockRepo.setFailureMode(MockRepository.FailureMode.NONE);
}
}The mock implementations provide comprehensive testing capabilities while maintaining isolation and enabling controlled failure simulation for robust test coverage.
Install with Tessl CLI
npx tessl i tessl/maven-org-elasticsearch--elasticsearch-test-framework