Skip to content

Commit

Permalink
adding tests for middleware
Browse files Browse the repository at this point in the history
adding update method for multiple content items
  • Loading branch information
ssinno28 committed Nov 21, 2023
1 parent a0d199c commit 9fda556
Show file tree
Hide file tree
Showing 6 changed files with 141 additions and 2 deletions.
26 changes: 26 additions & 0 deletions Lucene.Net.IndexProvider.Tests/Controllers/BlogPostController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Lucene.Net.IndexProvider.Interfaces;
using Lucene.Net.IndexProvider.Tests.Models;
using Microsoft.AspNetCore.Mvc;

namespace Lucene.Net.IndexProvider.Tests.Controllers;

[ApiController]
[Route("[controller]")]
public class BlogPostController : ControllerBase
{
private readonly IIndexProvider _indexProvider;

public BlogPostController(IIndexProvider indexProvider)
{
_indexProvider = indexProvider;
}

[HttpPost]
public async Task<BlogPost> Post(BlogPost dto)
{
await _indexProvider.Store(new List<object>() { dto }, nameof(BlogPost));
return dto;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="Moq" Version="4.18.4" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="AutoFixture" Version="4.18.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand All @@ -21,6 +22,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="7.0.5" />
</ItemGroup>

<ItemGroup>
Expand Down
92 changes: 92 additions & 0 deletions Lucene.Net.IndexProvider.Tests/MiddlewareTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using AutoFixture;
using Lucene.Net.DocumentMapper.Helpers;
using Lucene.Net.IndexProvider.Helpers;
using Lucene.Net.IndexProvider.Interfaces;
using Lucene.Net.IndexProvider.Middleware;
using Lucene.Net.IndexProvider.Models;
using Lucene.Net.IndexProvider.Tests.Models;
using Lucene.Net.Util;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;

namespace Lucene.Net.IndexProvider.Tests;

public class MiddlewareTests
{
private readonly TestServer _testServer;
private readonly IFixture _fixture = new Fixture();
private string _settingsPath;
private string _indexPath;
private Mock<ILocalIndexPathFactory> _mockLocalIndexPathFactory;
private IIndexProvider _indexProvider;

public MiddlewareTests()
{
_settingsPath = Path.GetFullPath(Path.Combine($"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}", @"..\..\..\settings"));
_indexPath = $"{_settingsPath}\\PersonalBlog\\index";
_mockLocalIndexPathFactory = new Mock<ILocalIndexPathFactory>();
_mockLocalIndexPathFactory.Setup(x => x.GetLocalIndexPath())
.Returns(_indexPath);

var host = new WebHostBuilder()
.ConfigureServices(services =>
{
services
.AddLuceneDocumentMapper()
.AddLuceneProvider()
.AddRouting()
.AddLogging(x => x.AddConsole())
.AddHttpContextAccessor()
.AddControllers();

services.Add(new ServiceDescriptor(typeof(ILocalIndexPathFactory), _mockLocalIndexPathFactory.Object));
})
.Configure(app =>
{
var configManager = app.ApplicationServices.GetService<IIndexConfigurationManager>();
configManager.AddConfiguration(new LuceneConfig()
{
Indexes = new[] { nameof(BlogPost) },
BatchSize = 50000,
LuceneVersion = LuceneVersion.LUCENE_48
});

_indexProvider = app.ApplicationServices.GetService<IIndexProvider>();

app.UseMiddleware<CloseIndexSessionMiddleware>();
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
});

_testServer = new TestServer(host);
}

[Fact]
public async Task BlogPostApi_Post_ProperlyClosesSession()
{
var blogPostDto = _fixture.Create<BlogPost>();

var payload = JsonSerializer.Serialize(blogPostDto);
var testClient = _testServer.CreateClient();
var response =
await testClient.PostAsync("/blogpost", new StringContent(payload, Encoding.UTF8, "application/json"));

var sessionManager = _testServer.Services.GetService<IIndexSessionManager>();
Assert.Equal(0, sessionManager.ContextSessions.Count);

var blogPost = _indexProvider.GetDocumentById(typeof(BlogPost), blogPostDto.Id);
Assert.NotNull(blogPost.Hit);
}
}
1 change: 1 addition & 0 deletions Lucene.Net.IndexProvider/Interfaces/IIndexProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public interface IIndexProvider
Task Delete(Type contentType, string documentId);
Task Delete<T>(string documentId);
Task<bool> Update(object contentItem, string id);
Task<bool> Update(IList<object> contentItems);
IndexResult<object> GetDocumentById(Type contentType, string id);
IndexResult<T> GetDocumentById<T>(string id);
Task<bool> CheckHealth<T>();
Expand Down
2 changes: 1 addition & 1 deletion Lucene.Net.IndexProvider/Lucene.Net.IndexProvider.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
</ItemGroup>

<PropertyGroup>
<Version>1.0.25</Version>
<Version>1.0.26</Version>
<RepositoryUrl>https://github.com/ssinno28/Lucene.Net.IndexProvider</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<Description>A simple service that helps to abstract common operations when interacting with lucene.net indexes.</Description>
Expand Down
20 changes: 19 additions & 1 deletion Lucene.Net.IndexProvider/LuceneIndexProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public LuceneIndexProvider(
IDocumentMapper mapper,
ILoggerFactory loggerFactory,
ILocalIndexPathFactory localIndexPathFactory,
IIndexSessionManager sessionManager,
IIndexSessionManager sessionManager,
IIndexConfigurationManager configurationManager)
{
_mapper = mapper;
Expand Down Expand Up @@ -313,6 +313,24 @@ public async Task<IndexListResult> GetByFilters(IList<IndexFilter> filters, ILis
});
}

public async Task<bool> Update(IList<object> contentItems)
{
foreach (var contentItem in contentItems)
{
var key = GetKeyName(contentItem.GetType());
var idPropInfo = contentItem.GetType().GetProperties().First(x => x.Name.Equals(key));
var id = idPropInfo.GetValue(contentItem).ToString();

var result = await Update(contentItem, id);
if (!result)
{
return false;
}
}

return true;
}

/// <summary>
/// Updates a single document based on the key supplied
/// </summary>
Expand Down

0 comments on commit 9fda556

Please sign in to comment.