gpt4 book ai didi

c# - 使用 InMemoryConnection 测试 ElasticSearch

转载 作者:行者123 更新时间:2023-11-30 15:21:09 27 4
gpt4 key购买 nike

我正在尝试围绕我们对 ElasticSearch 的使用添加测试(在 C# 中使用 Nest 1.4.2)并想使用 InMemoryConnection 但我遗漏了一些东西(我假设)并且没有成功。

我已经创建了这个简单的 Nunit 测试用例作为我的问题的归结示例

using System;
using Elasticsearch.Net.Connection;
using FluentAssertions;
using Nest;
using NUnit.Framework;

namespace NestTest
{
public class InMemoryConnections
{
public class TestThing
{
public string Stuff { get; }

public TestThing(string stuff)
{
Stuff = stuff;
}
}

[Test]
public void CanBeQueried()
{
var connectionSettings = new ConnectionSettings(new Uri("http://foo.test"), "default_index");

var c = new ElasticClient(connectionSettings, new InMemoryConnection(connectionSettings));
c.Index(new TestThing("peter rabbit"));

var result = c.Search<TestThing>(sd => sd);

result.ConnectionStatus.Success.Should().BeTrue();
}
}
}

查询成功但没有找到我刚刚索引的文档...

如果我更新到 NEST 版本 2.3.3 和新语法

        [Test]
public void CanBeQueried()
{

var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(connectionPool, new InMemoryConnection());
settings.DefaultIndex("default");

var c = new ElasticClient(settings);

c.Index(new TestThing("peter rabbit"));

var result = c.Search<TestThing>(sd => sd);

result.CallDetails.Success.Should().BeTrue();
result.Documents.Single().Stuff.Should().Be("peter rabbit");
}

它以同样的方式失败...即查询报告为成功但返回 0 个文档

最佳答案

InMemoryConnection 实际上不发送任何请求或从 Elasticsearch 接收任何响应;与连接设置上的 .SetConnectionStatusHandler()(或 NEST 2.x+ 中的 .OnRequestCompleted())结合使用,这是查看请求的序列化形式的便捷方式。

当不使用 InMemoryConnection 但仍设置 .SetConnectionStatusHandler().OnRequestCompleted() 时,根据 NEST 版本,这是一种方便的方法还可以查看响应,当 .ExposeRawResponse(true) 也在 NEST 1.x 中设置时,或者 .DisableDirectStreaming() 分别在 NEST 2.x+ 中设置时。

NEST 1.x 的例子

void Main()
{
var settings = new ConnectionSettings(new Uri("http://localhost:9200"))
.ExposeRawResponse(true)
.PrettyJson()
.SetDefaultIndex("myIndexName")
.MapDefaultTypeNames(d => d.Add(typeof(myPoco), string.Empty))
.SetConnectionStatusHandler(r =>
{
// log out the requests
if (r.Request != null)
{
Console.WriteLine("{0} {1} \n{2}\n", r.RequestMethod.ToUpperInvariant(), r.RequestUrl,
Encoding.UTF8.GetString(r.Request));
}
else
{
Console.WriteLine("{0} {1}\n", r.RequestMethod.ToUpperInvariant(), r.RequestUrl);
}

Console.WriteLine();

if (r.ResponseRaw != null)
{
Console.WriteLine("Status: {0}\n{1}\n\n{2}\n", r.HttpStatusCode, Encoding.UTF8.GetString(r.ResponseRaw), new String('-', 30));
}
else
{
Console.WriteLine("Status: {0}\n\n{1}\n", r.HttpStatusCode, new String('-', 30));
}
});

var client = new ElasticClient(settings, new InMemoryConnection());

int skipCount = 0;
int takeSize = 100;

var searchResults = client.Search<myPoco>(x => x
.Query(q => q
.Bool(b => b
.Must(m =>
m.Match(mt1 => mt1.OnField(f1 => f1.status).Query("New")))))
.Skip(skipCount)
.Take(takeSize)
);
}

public class myPoco
{
public string status { get; set;}
}

产量

POST http://localhost:9200/myIndexName/_search?pretty=true 
{
"from": 0,
"size": 100,
"query": {
"bool": {
"must": [
{
"match": {
"status": {
"query": "New"
}
}
}
]
}
}
}


Status: 0
{ "USING NEST IN MEMORY CONNECTION" : null }

------------------------------

对于 NEST 2.x

void Main()
{
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var defaultIndex = "default-index";
var connectionSettings = new ConnectionSettings(pool, new InMemoryConnection())
.DefaultIndex(defaultIndex)
.PrettyJson()
.DisableDirectStreaming()
.OnRequestCompleted(response =>
{
// log out the request
if (response.RequestBodyInBytes != null)
{
Console.WriteLine(
$"{response.HttpMethod} {response.Uri} \n" +
$"{Encoding.UTF8.GetString(response.RequestBodyInBytes)}");
}
else
{
Console.WriteLine($"{response.HttpMethod} {response.Uri}");
}

Console.WriteLine();

// log out the response
if (response.ResponseBodyInBytes != null)
{
Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
$"{Encoding.UTF8.GetString(response.ResponseBodyInBytes)}\n" +
$"{new string('-', 30)}\n");
}
else
{
Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
$"{new string('-', 30)}\n");
}
});

var client = new ElasticClient(connectionSettings);

int skipCount = 0;
int takeSize = 100;

var searchResults = client.Search<myPoco>(x => x
.Query(q => q
.Bool(b => b
.Must(m =>
m.Match(mt1 => mt1.Field(f1 => f1.status).Query("New")))))
.Skip(skipCount)
.Take(takeSize)
);
}

You can of course mock/stub responses from the client using your favourite mocking framework并且根据客户端接口(interface) IElasticClient,如果这是您想要采用的路线,尽管断言请求的序列化形式符合您在 SUT 中的期望可能就足够了。

关于c# - 使用 InMemoryConnection 测试 ElasticSearch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38207159/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com