弹性搜索内存中用于测试

2022-09-02 10:51:11

我想写一些与ElasticSearch的集成。对于测试,我想运行内存中的ES。

我在文档中找到了一些信息,但没有示例如何编写此类测试。Elasticsearch Reference [1.6] » Testing » Java Testing Framework » 集成测试 « 单元测试

我也找到了下面的文章,但它没有数据。使用弹性搜索轻松进行 JUnit 测试

我正在看示例如何在内存中启动和运行ES,并通过REST API访问它。


答案 1

基于您提供的第二个链接,我创建了这个抽象测试类:

@RunWith(SpringJUnit4ClassRunner.class)
public abstract class AbstractElasticsearchTest {

    private static final String HTTP_PORT = "9205";
    private static final String HTTP_TRANSPORT_PORT = "9305";
    private static final String ES_WORKING_DIR = "target/es";

    private static Node node;

    @BeforeClass
    public static void startElasticsearch() throws Exception {    
        removeOldDataDir(ES_WORKING_DIR + "/" + clusterName);

        Settings settings = Settings.builder()
                .put("path.home", ES_WORKING_DIR)
                .put("path.conf", ES_WORKING_DIR)
                .put("path.data", ES_WORKING_DIR)
                .put("path.work", ES_WORKING_DIR)
                .put("path.logs", ES_WORKING_DIR)
                .put("http.port", HTTP_PORT)
                .put("transport.tcp.port", HTTP_TRANSPORT_PORT)
                .put("index.number_of_shards", "1")
                .put("index.number_of_replicas", "0")
                .put("discovery.zen.ping.multicast.enabled", "false")
                .build();
        node = nodeBuilder().settings(settings).clusterName("monkeys.elasticsearch").client(false).node();
        node.start();
    }

    @AfterClass
    public static void stopElasticsearch() {
        node.close();
    }

    private static void removeOldDataDir(String datadir) throws Exception {
        File dataDir = new File(datadir);
        if (dataDir.exists()) {
            FileSystemUtils.deleteRecursively(dataDir);
        }
    }    
}

在生产代码中,我配置了一个 Elasticsearch 客户端,如下所示。集成测试扩展了上述定义的抽象类,并将属性配置为 和 。elasticsearch.port9305elasticsearch.hostlocalhost

@Configuration
public class ElasticsearchConfiguration {    
    @Bean(destroyMethod = "close")
    public Client elasticsearchClient(@Value("${elasticsearch.clusterName}") String clusterName,
                                      @Value("${elasticsearch.host}") String elasticsearchClusterHost,
                                      @Value("${elasticsearch.port}") Integer elasticsearchClusterPort) throws UnknownHostException {
        Settings settings = Settings.settingsBuilder().put("cluster.name", clusterName).build();
        InetSocketTransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName(elasticsearchClusterHost), elasticsearchClusterPort);
        return TransportClient.builder().settings(settings).build().addTransportAddress(transportAddress);
    }
}

就是这样。集成测试将运行生产代码,该代码配置为连接到 在 中启动的节点。AbstractElasticsearchTest.startElasticsearch()

如果要使用 elasticsearch REST API,请使用端口 9205。例如,使用Apache HttpComponents:

HttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut("http://localhost:9205/_template/" + templateName);
httpPut.setEntity(new FileEntity(new File("template.json")));
httpClient.execute(httpPut);

答案 2

这是我的实现

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;

/**
 *
 * @author Raghu Nair
 */
public final class ElasticSearchInMemory {

    private static Client client = null;
    private static File tempDir = null;
    private static Node elasticSearchNode = null;

    public static Client getClient() {
        return client;
    }

    public static void setUp() throws Exception {
        tempDir = File.createTempFile("elasticsearch-temp", Long.toString(System.nanoTime()));
        tempDir.delete();
        tempDir.mkdir();
        System.out.println("writing to: " + tempDir);

        String clusterName = UUID.randomUUID().toString();
        elasticSearchNode = NodeBuilder
                .nodeBuilder()
                .local(false)
                .clusterName(clusterName)
                .settings(
                        ImmutableSettings.settingsBuilder()
                        .put("script.disable_dynamic", "false")
                        .put("gateway.type", "local")
                        .put("index.number_of_shards", "1")
                        .put("index.number_of_replicas", "0")
                        .put("path.data", new File(tempDir, "data").getAbsolutePath())
                        .put("path.logs", new File(tempDir, "logs").getAbsolutePath())
                        .put("path.work", new File(tempDir, "work").getAbsolutePath())
                ).node();
        elasticSearchNode.start();
        client = elasticSearchNode.client();
    }

    public static void tearDown() throws Exception {
        if (client != null) {
            client.close();
        }
        if (elasticSearchNode != null) {
            elasticSearchNode.stop();
            elasticSearchNode.close();
        }
        if (tempDir != null) {
            removeDirectory(tempDir);
        }
    }

    public static void removeDirectory(File dir) throws IOException {
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files != null && files.length > 0) {
                for (File aFile : files) {
                    removeDirectory(aFile);
                }
            }
        } 
        Files.delete(dir.toPath());        
    }
}

推荐