public void UsePrettyResponsesShouldSurviveUrlModififications()
        {
            var settings = new ConnectionSettings(Test.Default.Uri, Test.Default.DefaultIndex)
                .UsePrettyResponses();
            var connection = new InMemoryConnection(settings);
            var client = new ElasticClient(settings, connection);

            var r = client.Health(h=>h.Level(LevelOptions.Cluster));
            var u = new Uri(r.ConnectionStatus.RequestUrl);
            u.AbsolutePath.Should().StartWith("/_cluster/health");
            u.Query.Should().Contain("level=cluster");

            u.Query.Should().Contain("pretty=true");
        }
        public void InMemoryConnectionOverloadedCtor()
        {
            var response = new
            {
                took      = 1,
                timed_out = false,
                _shards   = new
                {
                    total      = 2,
                    successful = 2,
                    failed     = 0
                },
                hits = new
                {
                    total     = new { value = 25 },
                    max_score = 1.0,
                    hits      = Enumerable.Range(1, 25).Select(i => (object)new
                    {
                        _index  = "project",
                        _type   = "project",
                        _id     = $"Project {i}",
                        _score  = 1.0,
                        _source = new { name = $"Project {i}" }
                    }).ToArray()
                }
            };

            var responseBytes  = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response));
            var connection     = new InMemoryConnection(responseBytes, 200);         // <1> `InMemoryConnection` is configured to **always** return `responseBytes` along with a 200 HTTP status code
            var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
            var settings       = new ConnectionSettings(connectionPool, connection).DefaultIndex("project");
            var client         = new ElasticClient(settings);

            var searchResponse = client.Search <Project>(s => s.MatchAll());

            /**
             * We can now assert that the `searchResponse` is valid and contains documents deserialized
             * from our fixed `InMemoryConnection` response
             */
            searchResponse.ShouldBeValid();
            searchResponse.Documents.Count.Should().Be(25);
        }
Exemple #3
0
        public static IElasticClient GetFixedReturnClient(
            object response,
            int statusCode = 200,
            Func <ConnectionSettings, ConnectionSettings> modifySettings = null,
            string contentType  = "application/json",
            Exception exception = null)
        {
            var serializer  = Default.Serializer;
            var fixedResult = contentType == "application/json"
                                ? serializer.SerializeToBytes(response)
                                : Encoding.UTF8.GetBytes(response.ToString());

            var connection      = new InMemoryConnection(fixedResult, statusCode, exception);
            var connectionPool  = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
            var defaultSettings = new ConnectionSettings(connectionPool, connection)
                                  .DefaultIndex("default-index");
            var settings = (modifySettings != null) ? modifySettings(defaultSettings) : defaultSettings;

            return(new ElasticClient(settings));
        }
        protected IElasticClient GetElasticClient(object responseData = null)
        {
            IConnection connection = null;

            if (responseData != null)
            {
                var responseBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(responseData));
                connection = new InMemoryConnection(responseBytes);
            }
            else
            {
                connection = new InMemoryConnection();
            }

            var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
            var settings       = new ConnectionSettings(connectionPool, connection).DefaultIndex(DefaultIndexName);
            var client         = new ElasticClient(settings);

            return(client);
        }
Exemple #5
0
        private IElasticClientProvider CreateClientProvider(object responseMock)
        {
            var providerMock = new Mock <IElasticClientProvider>();

            providerMock.Setup(m =>
                               m.GetElasticClient(It.IsAny <IElasticSettings>(), It.IsAny <ElasticQueryResult <TreeRecord> >())).Returns(
                () =>
            {
                var response       = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(responseMock));
                var connection     = new InMemoryConnection(response);
                var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
                var settings       = new ConnectionSettings(connectionPool, connection,
                                                            (serializer, values) => new JsonNetSerializer(
                                                                serializer, values, null, null,
                                                                new[] { new ExpandoObjectConverter() }));

                return(new ElasticClient(settings));
            });

            return(providerMock.Object);
        }
Exemple #6
0
        private List <DataStorageModel> CreateDataStorageList()
        {
            string connectionSetting = "SQLConnection";
            string inMemorySetting   = "InMemoryRegionName";
            string pathFileSetting   = "PathFile";

            IConnection sqlConnection      = new SqlConnection(new System.Data.SqlClient.SqlConnection(ConfigurationManager.AppSettings[connectionSetting]));
            IConnection inMemoryConnection = new InMemoryConnection(ConfigurationManager.AppSettings[inMemorySetting]);
            IConnection csvConnection      = new CsvFileConnection(ConfigurationManager.AppSettings[pathFileSetting]);
            IConnection jsonConnection     = new JsonFileConnection(ConfigurationManager.AppSettings[pathFileSetting]);
            IConnection xmlConnection      = new XmlFileConnection(ConfigurationManager.AppSettings[pathFileSetting]);

            return(new List <DataStorageModel>()
            {
                new DataStorageModel(1, sqlConnection, new DbCommand(sqlConnection as DbConnection)),
                new DataStorageModel(2, inMemoryConnection, new InMemoryCommand(inMemoryConnection as InMemoryConnection)),
                new DataStorageModel(3, csvConnection, new FileCommand(csvConnection as CsvFileConnection)),
                new DataStorageModel(4, jsonConnection, new FileCommand(jsonConnection as JsonFileConnection)),
                new DataStorageModel(5, xmlConnection, new FileCommand(xmlConnection as XmlFileConnection))
            });
        }
Exemple #7
0
        public IControlledWampConnection <TMessage> CreateClientConnection(IScheduler scheduler)
        {
            Subject <WampMessage <TMessage> > serverInput =
                new Subject <WampMessage <TMessage> >();

            Subject <WampMessage <TMessage> > clientInput =
                new Subject <WampMessage <TMessage> >();

            Subject <Unit> connectionOpen   = new Subject <Unit>();
            Subject <Unit> connectionClosed = new Subject <Unit>();

            InMemoryConnection serverToClient =
                new InMemoryConnection(mBinding, serverInput, clientInput, mServerScheduler, connectionOpen, connectionClosed);

            IWampConnection <TMessage> clientToServer =
                new InMemoryConnection(mBinding, clientInput, serverInput, scheduler, connectionOpen, connectionClosed);

            mSubject.OnNext(clientToServer);

            return(serverToClient);
        }
Exemple #8
0
        public void ConvenienceExtensionShouldGenerateExactBodyAsMethodOnClient()
        {
            var connection = new InMemoryConnection(this._settings)
            {
                RecordRequests = true
            };
            var client = new ElasticClient(this._settings, connection);

            var response  = client.GetMany <ElasticsearchProject>(new[] { "123" });
            var response2 = client.MultiGet(s => s.GetMany <ElasticsearchProject>(new[] { "123" }));

            connection.Requests.Should().NotBeEmpty().And.HaveCount(2);

            var getManyRequest  = connection.Requests[0];
            var multiGetRequest = connection.Requests[1];

            getManyRequest.Item3.Should().NotBeNull()
            .And.BeEquivalentTo(multiGetRequest.Item3);

            getManyRequest.Item3.Utf8String().Should().Contain("_index\":");
            getManyRequest.Item3.Utf8String().Should().Contain("_type\":");
        }
Exemple #9
0
        /// <summary>
        /// Gets an ElasticClient backed by an InMemoryConnection.  This is used to mock the
        /// JSON returned by the elastic search so that we test the Nest mappings to our models.
        /// </summary>
        /// <param name="testFile"></param>
        /// <param name="requestDataCallback"></param>
        /// <returns></returns>
        public static IElasticClient GetInMemoryElasticClient(string testFile)
        {
            // Determine where the output folder is that should be the parent for the TestData
            string assmPath = Path.GetDirectoryName(typeof(ElasticTools).GetTypeInfo().Assembly.Location);

            // Build a path to the test json
            string path = Path.Combine(new string[] { assmPath, "TestData", testFile });

            //While this has a URI, it does not matter, an InMemoryConnection never requests
            //from the server.
            var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

            //Get Response JSON
            byte[] responseBody = File.ReadAllBytes(path);

            // Setup ElasticSearch stuff using the contents of the JSON file as the client response.
            InMemoryConnection conn = new InMemoryConnection(responseBody);

            var connectionSettings = new ConnectionSettings(pool, conn);

            return(new ElasticClient(connectionSettings));
        }
Exemple #10
0
        public void GlobalSetupPlaintext()
        {
            var transportFactory = new InMemoryTransportFactory(connectionsPerEndPoint: 1);

            _host = new WebHostBuilder()
                    // Prevent VS from attaching to hosting startup which could impact results
                    .UseSetting("preventHostingStartup", "true")
                    .UseKestrel()
                    // Bind to a single non-HTTPS endpoint
                    .UseUrls("http://127.0.0.1:5000")
                    .ConfigureServices(services => services.AddSingleton <ITransportFactory>(transportFactory))
                    .Configure(app => app.UseMiddleware <PlaintextMiddleware>())
                    .Build();

            _host.Start();

            // Ensure there is a single endpoint and single connection
            _connection = transportFactory.Connections.Values.Single().Single();

            ValidateResponseAsync(RequestParsingData.PlaintextTechEmpowerRequest, _plaintextExpectedResponse).Wait();
            ValidateResponseAsync(RequestParsingData.PlaintextTechEmpowerPipelinedRequests, _plaintextPipelinedExpectedResponse).Wait();
        }
Exemple #11
0
        public void CanDeserializeNestedError()
        {
            var nestedCausedByError = @"{
				""status"": 400,
				""error"": {
					""type"": ""illegal_argument_exception"",
					""reason"": ""failed to execute script"",
					""caused_by"": {
						""type"": ""script_exception"",
						""reason"": ""failed to run inline script [use(java.lang.Exception) {throw new Exception(\""Customized Exception\"")}] using lang [groovy]"",
						""caused_by"": {
							""type"": ""privileged_action_exception"",
							""reason"": null,
							""caused_by"": {
								""type"": ""exception"",
								""reason"": ""Custom Exception""
							}
						}
					}
				}
			}"            ;

            var bytes      = Encoding.UTF8.GetBytes(nestedCausedByError);
            var connection = new InMemoryConnection(bytes, 400);
            var settings   = new ConnectionSettings(new SingleNodeConnectionPool(new Uri("http://localhost:9200")), connection);
            var client     = new ElasticClient(settings);

            var searchResponse = client.Search <object>(s => s.Index("index"));

            searchResponse.ShouldNotBeValid();
            var se = searchResponse.ServerError;

            se.Status.Should().Be(400);
            se.Should().NotBeNull();
            ShouldDeserialize(se.Error);
            ShouldDeserialize(se.Error.CausedBy);
            ShouldDeserialize(se.Error.CausedBy.CausedBy, nullReason: true);
            ShouldDeserialize(se.Error.CausedBy.CausedBy.CausedBy);
        }
        public InMemoryDataStoreServices(
            [NotNull] InMemoryDataStore store,
            [NotNull] InMemoryDataStoreCreator creator,
            [NotNull] InMemoryConnection connection,
            [NotNull] InMemoryValueGeneratorCache valueGeneratorCache,
            [NotNull] Database database,
            [NotNull] ModelBuilderFactory modelBuilderFactory)
        {
            Check.NotNull(store, "store");
            Check.NotNull(creator, "creator");
            Check.NotNull(connection, "connection");
            Check.NotNull(valueGeneratorCache, "valueGeneratorCache");
            Check.NotNull(database, "database");
            Check.NotNull(modelBuilderFactory, "modelBuilderFactory");

            _store = store;
            _creator = creator;
            _connection = connection;
            _valueGeneratorCache = valueGeneratorCache;
            _database = database;
            _modelBuilderFactory = modelBuilderFactory;
        }
Exemple #13
0
        public static ConnectionSettings CreateConnectionSettings(
            object response,
            int statusCode = 200,
            Func <ConnectionSettings, ConnectionSettings> modifySettings = null,
            string contentType  = RequestData.MimeType,
            Exception exception = null
            )
        {
            var serializer = TestClient.Default.RequestResponseSerializer;

            byte[] responseBytes;
            switch (response)
            {
            case string s:
                responseBytes = Encoding.UTF8.GetBytes(s);
                break;

            case byte[] b:
                responseBytes = b;
                break;

            default:
            {
                responseBytes = contentType == RequestData.MimeType
                                                ? serializer.SerializeToBytes(response, TestClient.Default.ConnectionSettings.MemoryStreamFactory)
                                                : Encoding.UTF8.GetBytes(response.ToString());
                break;
            }
            }

            var connection      = new InMemoryConnection(responseBytes, statusCode, exception, contentType);
            var connectionPool  = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
            var defaultSettings = new ConnectionSettings(connectionPool, connection)
                                  .DefaultIndex("default-index");
            var settings = modifySettings != null?modifySettings(defaultSettings) : defaultSettings;

            return(settings);
        }
        public void FieldsSelectionIsCovariantAsWell()
        {
            var settings = new ConnectionSettings(Test.Default.Uri, "default-index")
                .ExposeRawResponse();
            var file = this.GetFileFromMethod(MethodInfo.GetCurrentMethod(), "FixedCovariantSearchResult");
            var jsonResponse = File.ReadAllText(file);
            var connection = new InMemoryConnection(this._settings, jsonResponse);
            var client = new ElasticClient(settings, connection);

            var results = client.Search<BaseClass>(s => s
                .Types(typeof(ClassA),typeof(ClassB),typeof(ClassC),typeof(ClassD))
                .Fields(p=>p.Lang)
            );

            results.Total.Should().Be(1605);

            results.Hits.Should().NotBeNull().And.HaveCount(10);
            var classAHits = results.Hits.OfType<Hit<ClassA>>();
            classAHits.Should().NotBeNull().And.HaveCount(3);

            var classAHit = classAHits.First();
            classAHit.Fields.Should().NotBeNull();
            var lang = classAHit.Fields.FieldValue<ClassA, string>(p => p.Lang).FirstOrDefault();
        }
        private IRequestPipeline CreatePipeline(
            Func <IEnumerable <Uri>, IConnectionPool> setupPool, Func <ConnectionSettings, ConnectionSettings> settingsSelector = null, IDateTimeProvider dateTimeProvider = null, InMemoryConnection connection = null)
        {
            var pool     = setupPool(new[] { TestClient.CreateUri(), TestClient.CreateUri(9201) });
            var settings = new ConnectionSettings(pool, connection ?? new InMemoryConnection());

            settings = settingsSelector?.Invoke(settings) ?? settings;
            return(new FixedPipelineFactory(settings, dateTimeProvider ?? DateTimeProvider.Default).Pipeline);
        }
Exemple #16
0
 /// <summary>
 /// Cleanup all resources
 /// </summary>
 public virtual void Dispose()
 {
     GC.Collect();
     GC.WaitForPendingFinalizers();
     InMemoryConnection?.Dispose();
 }
Exemple #17
0
 /// <summary>
 ///     Instantiate connection settings using a <see cref="SingleNodePool" /> using the provided
 ///     <see cref="InMemoryConnection" /> that never uses any IO.
 /// </summary>
 public ElasticsearchClientSettings(InMemoryConnection connection)
     : this(new SingleNodePool(new Uri("http://localhost:9200")), connection)
 {
 }
Exemple #18
0
 /// <summary>
 /// Instantiate connection settings using a <see cref="SingleNodeConnectionPool" /> using the provided
 /// <see cref="InMemoryConnection" /> that never uses any IO.
 /// </summary>
 public ConnectionSettings(InMemoryConnection connection)
     : this(new SingleNodeConnectionPool(new Uri("http://localhost:9200")), connection)
 {
 }
Exemple #19
0
        public LowLevelResponseTypes()
        {
            var connection = new InMemoryConnection(Response().Utf8Bytes());

            this.Client = new ElasticClient(new ConnectionSettings(connection).ApplyDomainSettings());
        }
 /// <summary>
 /// Cleanup all resources
 /// </summary>
 public virtual void Dispose()
 {
     InMemoryConnection?.Dispose();
 }
 protected ElasticClient GetFixedReturnClient(MethodBase methodInfo, string fileName)
 {
     var settings = new ConnectionSettings(UnitTestDefaults.Uri, UnitTestDefaults.DefaultIndex)
         .ExposeRawResponse();
     var file = this.GetFileFromMethod(methodInfo, fileName);
     var jsonResponse = File.ReadAllText(file);
     var connection = new InMemoryConnection(this._settings, jsonResponse);
     var client = new ElasticClient(settings, connection);
     return client;
 }