CodeGo.net>使用InMemoryConnection测试ElasticSearch

我正在尝试对我们使用ElasticSearch进行测试(在使用Nest 1.4.2的C#中使用C#),并想使用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接收任何响应.在连接设置(或NEST 2.x中的.OnRequestCompleted())上与.SetConnectionStatusHandler()结合使用,这是查看请求的序列化形式的便捷方法.

当不使用InMemoryConnection而是仍设置.SetConnectionStatusHandler()或.OnRequestCompleted()时(取决于NEST版本),当还在NEST 1.x或.DisableDirectStreaming中还设置了.ExposeRawResponse(true)时,这也是查看响应的一种便捷方法. ()分别在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并取决于客户端接口IElasticClient(如果您要采用的是这条路由),尽管断言请求的序列化形式符合您在SUT中的期望就足够了.

上一篇:c#-通过在Nest Elastic Search中降序获得不同的术语


下一篇:使用NEST 6.0 for Elasticsearch枚举动态匹配结果