diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 3258ab7..01a9d2a 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,6 +11,11 @@ updates: patterns: ["*"] multi-ecosystem-group: "monthly-dependencies" + - package-ecosystem: "docker-compose" + directory: "/" + patterns: ["*"] + multi-ecosystem-group: "monthly-dependencies" + - package-ecosystem: "github-actions" directory: "/" patterns: ["*"] diff --git a/.github/release.yml b/.github/release.yml index 58d0ba6..92dcb94 100644 --- a/.github/release.yml +++ b/.github/release.yml @@ -1,11 +1,26 @@ changelog: + exclude: + labels: + - ignore-for-release categories: - - title: Changes + - title: Breaking changes labels: - - "*" - exclude: - labels: - - dependencies + - breaking-change + - title: New features + labels: + - enhancement + - title: Bug fixes + labels: + - bug + - title: Documentation + labels: + - documentation + - title: Build and pipeline + labels: + - build - title: Dependencies labels: - dependencies + - title: Other changes + labels: + - "*" diff --git a/.github/workflows/build-pipeline.yml b/.github/workflows/build-pipeline.yml index a7a6f50..97e9b4d 100644 --- a/.github/workflows/build-pipeline.yml +++ b/.github/workflows/build-pipeline.yml @@ -92,6 +92,10 @@ jobs: with: dotnet-version: '10.0.x' + - name: Format + id: format + run: dotnet format --verify-no-changes --verbosity diagnostic + - name: Pack id: pack run: | @@ -290,7 +294,7 @@ jobs: name: Publish runs-on: ubuntu-latest needs: [build, coverage, scan, analysis] - if: ${{ github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }} + if: ${{ github.repository == 'stphnwlsh/CleanModelContextProtocol' && github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }} permissions: contents: write id-token: write diff --git a/.gitignore b/.gitignore index 702fd02..9f74819 100644 --- a/.gitignore +++ b/.gitignore @@ -366,3 +366,9 @@ out/ .Trashes ehthumbs.db Thumbs.db + +# SQLite databases and coverage reports +*.db +*.db-shm +*.db-wal +coverage.cobertura.xml diff --git a/Directory.Build.props b/Directory.Build.props index 8db3048..c56dd90 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -5,8 +5,19 @@ CleanModelContextProtocol.$(AssemblyName) AnyCPU enable + enable true latest + + + latest-recommended + true + true + + true + $(NoWarn);1591 + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..8f24354 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,33 @@ + + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Dockerfile b/Dockerfile index ce0023f..2095687 100644 --- a/Dockerfile +++ b/Dockerfile @@ -19,7 +19,7 @@ ENV DOTNET_ENVIRONMENT=${ENVIRONMENT} WORKDIR /sln # Dotnet Restore -COPY ./*.sln ./NuGet.config ./Directory.Build.props ./ +COPY ./*.sln ./NuGet.config ./Directory.Build.props ./Directory.Packages.props ./ COPY src/*/*.csproj ./ RUN for file in $(ls *.csproj); do mkdir -p src/${file%.*}/ && mv $file src/${file%.*}/; done COPY tests/*/*.csproj ./ @@ -35,7 +35,7 @@ RUN dotnet build --no-restore -c Release -v minimal -p:VersionPrefix=${VERSION_P # Dotnet Test FROM build AS test -RUN dotnet test --no-restore --no-build -c Release -v minimal -p:CollectCoverage=true -p:CoverletOutput=../results/ -p:MergeWith="../results/coverage.json" -p:CoverletOutputFormat=opencover%2cjson -m:1 -p:ExcludeByFile="**/Program.cs" +RUN dotnet test --no-restore --no-build -c Release -v minimal -p:CollectCoverage=true -p:CoverletOutput=../results/ -p:MergeWith="../results/coverage.json" -p:CoverletOutputFormat=opencover%2cjson -m:1 -p:ExcludeByFile="**/Program.cs%2c**/Migrations/*.cs" FROM scratch AS coverage COPY --from=test /sln/tests/results/*.xml . @@ -48,7 +48,15 @@ RUN dotnet publish ./src/**/Presentation.csproj --no-restore -c Release -v quiet # Runtime Image FROM ${BASE_IMAGE_REPO}/${BASE_IMAGE_RUNTIME}:${BASE_IMAGE_RUNTIME_TAG} AS run -WORKDIR / +WORKDIR /app EXPOSE 8080 COPY --from=publish /sln/app . + +# The database lives in /app/data, the only folder the non-root app user can write to. +RUN mkdir -p /app/data && chown $APP_UID /app/data +USER $APP_UID + +HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \ + CMD wget -qO- http://localhost:8080/health/live || exit 1 + ENTRYPOINT ["dotnet", "Presentation.dll"] diff --git a/README.md b/README.md index 9434071..400b979 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ The one deliberate break from Clean Architecture is that the Presentation projec - Six task-shaped tools (`movies_search`, `movies_get`, `authors_search`, `reviews_list`, `reviews_write`, `reviews_delete`) with titles, read-only, destructive and idempotent hints, and descriptions written for agents - Resources for each movie, author and review (`movies://{movieId}`, `authors://{authorId}`, `reviews://{reviewId}`) and the server version (`server://version`) - Prompts for common jobs (`summarise_movie_reception`, `compare_movies`, `review_movie`) that embed the movies they're about, with completions that suggest movie titles and author names as you type -- Search with paging and small results by default: every list returns 10 items, a total count and a cursor, with names and average ratings next to ids +- Search with paging and small results by default: every list returns 10 items, a total count and the offset of the next page, with names and average ratings next to ids - Optional OAuth protection for `/mcp`: JWT bearer tokens plus MCP protected resource metadata, turned on by setting an authority - Logging using [Serilog](https://github.com/serilog/serilog), with [Seq](https://datalust.co/seq) when running in Docker - Mediator pattern using [Mediator](https://github.com/martinothamar/Mediator) @@ -95,10 +95,13 @@ The one deliberate break from Clean Architecture is that the Presentation projec - Typed tool results published with an output schema and returned as structured content as well as JSON text - Errors mapped from Application exceptions by request filters: tool errors tell the agent how to recover, and resources and prompts return MCP protocol errors such as resource not found - Object mapping using [Mapperly](https://mapperly.riok.app) -- In-memory data using [Entity Framework Core](https://learn.microsoft.com/ef/core/providers/in-memory/) seeded with [Bogus](https://github.com/bchavez/Bogus) +- Data stored in [SQLite](https://learn.microsoft.com/ef/core/providers/sqlite/) using [Entity Framework Core](https://learn.microsoft.com/ef/core) migrations, seeded with [Bogus](https://github.com/bchavez/Bogus) only when `Database:SeedSampleData` is on. Each test uses its own throwaway in-memory SQLite database, so tests never touch a real one or each other's data - Testing using [xUnit](https://xunit.net), [Shouldly](https://github.com/shouldly/shouldly) and [NSubstitute](https://github.com/nsubstitute/NSubstitute), with coverage from [Coverlet](https://github.com/coverlet-coverage/coverlet) -- CI with GitHub Actions: build and test, 95% coverage gate, [Trivy](https://trivy.dev) container scan, [CodeQL](https://codeql.github.com) static analysis, then NuGet publishing and a GitHub release from `main` using [trusted publishing](https://learn.microsoft.com/nuget/nuget-org/trusted-publishing) -- Monthly grouped dependency updates using [Dependabot](https://docs.github.com/code-security/dependabot) +- Build rules in `Directory.Build.props`: code style and the recommended analyzers are checked on every build, warnings fail it, and package versions live in one place with [Central Package Management](https://learn.microsoft.com/nuget/consume-packages/central-package-management) +- CI with GitHub Actions: build and test, a `dotnet format` check, 95% coverage gate, [Trivy](https://trivy.dev) container scan, [CodeQL](https://codeql.github.com) static analysis, then NuGet publishing and a GitHub release from `main` using [trusted publishing](https://learn.microsoft.com/nuget/nuget-org/trusted-publishing) +- Health checks at `/health/live` and `/health/ready`, using [ASP.NET Core health checks](https://learn.microsoft.com/aspnet/core/host-and-deploy/health-checks) +- Monthly grouped dependency updates using [Dependabot](https://docs.github.com/code-security/dependabot), including the pinned Seq image +- A Docker image that runs as a non-root user with a health check ## Related templates diff --git a/docker-compose.yml b/docker-compose.yml index 7f5267a..051a3b7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -10,6 +10,8 @@ services: - "8080:8080" environment: DOTNET_ENVIRONMENT: docker + volumes: + - movie-reviews-data:/app/data networks: - cleanmodelcontextprotocol_network depends_on: @@ -24,7 +26,7 @@ services: depends_on: - api seq: - image: datalust/seq:latest + image: datalust/seq:2026.1.17473 ports: - "5341:80" environment: @@ -32,6 +34,8 @@ services: SEQ_FIRSTRUN_NOAUTHENTICATION: "true" networks: - cleanmodelcontextprotocol_network +volumes: + movie-reviews-data: networks: cleanmodelcontextprotocol_network: driver: bridge diff --git a/docs/RUN.md b/docs/RUN.md index 9ee7f48..4db89c6 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -2,6 +2,17 @@ There are two pre-configured environments, `local` and `docker`. The matching `appsettings.*.json` files decide where logs go: the console when running locally, and a [Seq](https://datalust.co/seq) container when running in Docker. +## Database + +The app stores its data in a SQLite file, `movie-reviews.db`, next to the app. In Docker the file is `/app/data/movie-reviews.db`, on the `movie-reviews-data` volume, so it survives a restart. On startup the app applies any pending Entity Framework Core migrations. When `Database:SeedSampleData` is `true`, it also seeds the same sample data into an empty database. It's on in `appsettings.local.json` and `appsettings.docker.json` and off everywhere else, so a deployed copy never starts with fake data. Delete the file, or run `docker compose down -v`, to start again. Change `ConnectionStrings:MovieReviews` to point somewhere else, or to `Data Source=MovieReviews;Mode=Memory;Cache=Shared` to keep everything in memory. + +To add a migration after changing the data model: + +``` bash +dotnet tool install --global dotnet-ef +dotnet ef migrations add --project ./src/Infrastructure --output-dir Databases/MovieReviews/Migrations +``` + ## .NET CLI `launchSettings.json` sets the ports, environment and logging, so one command is enough. @@ -21,6 +32,9 @@ docker compose up -d --build - App: (MCP endpoint, Streamable HTTP) - MCP Inspector: . Flip the switch on the server card to connect, then open **Tools** to see every tool with its description and input schema and run it. - Seq: +- Health checks: (the process is up) and (the database can be reached). Both answer without a token. The image's `HEALTHCHECK` uses the live one. + +The container runs as the image's non-root `app` user. To shut the containers down: @@ -28,8 +42,14 @@ To shut the containers down: docker compose down ``` +## HTTPS + +Outside the `local` and `Development` environments the app sends an HSTS header and redirects HTTP to HTTPS. The container only listens on HTTP, so in production put it behind a proxy or load balancer that ends TLS, and set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` so the app knows the original request was HTTPS. + ## Tests ``` bash dotnet test ``` + +The tests never touch `movie-reviews.db`. Each test builds its own in-memory SQLite database from the migrations and the same fixed seed, so no test can change what another one sees and the results are the same every time. diff --git a/src/Application/Application.csproj b/src/Application/Application.csproj index b16faf7..354c1cd 100644 --- a/src/Application/Application.csproj +++ b/src/Application/Application.csproj @@ -2,13 +2,11 @@ false - true - $(NoWarn);1591 - - + + diff --git a/src/Application/Authors/Entities/Author.cs b/src/Application/Authors/Entities/Author.cs index c3d93e4..a7ada1e 100644 --- a/src/Application/Authors/Entities/Author.cs +++ b/src/Application/Authors/Entities/Author.cs @@ -9,4 +9,4 @@ namespace CleanModelContextProtocol.Application.Authors.Entities; /// The author's first name. /// The author's last name. /// The reviews the author has written. -public record Author(Guid Id, string FirstName, string LastName, ICollection Reviews = null); +public record Author(Guid Id, string FirstName, string LastName, ICollection Reviews); diff --git a/src/Application/Authors/Entities/AuthorSummary.cs b/src/Application/Authors/Entities/AuthorSummary.cs new file mode 100644 index 0000000..7110532 --- /dev/null +++ b/src/Application/Authors/Entities/AuthorSummary.cs @@ -0,0 +1,11 @@ +namespace CleanModelContextProtocol.Application.Authors.Entities; + +/// +/// An author in a list, with how many reviews they have written and their average star rating instead of the reviews themselves. +/// +/// The unique identifier of the author. +/// The author's first name. +/// The author's last name. +/// The number of reviews the author has written. +/// The average star rating the author gives to one decimal place, or null when they have no reviews. +public record AuthorSummary(Guid Id, string FirstName, string LastName, int ReviewCount, double? AverageStars); diff --git a/src/Application/Authors/IAuthorsRepository.cs b/src/Application/Authors/IAuthorsRepository.cs index b1ae1e7..6225772 100644 --- a/src/Application/Authors/IAuthorsRepository.cs +++ b/src/Application/Authors/IAuthorsRepository.cs @@ -1,19 +1,16 @@ namespace CleanModelContextProtocol.Application.Authors; -using System.Threading.Tasks; using Entities; public interface IAuthorsRepository { - public Task> GetAuthors(CancellationToken cancellationToken); - - public Task GetAuthorById(Guid id, CancellationToken cancellationToken); - - public Task AuthorExists(Guid id, CancellationToken cancellationToken); - - public Task<(List Items, int TotalCount)> SearchAuthors( - string query, + public Task<(List Items, int TotalCount)> GetAuthors( + string? query, int offset, int limit, CancellationToken cancellationToken); + + public Task GetAuthorById(Guid id, CancellationToken cancellationToken); + + public Task AuthorExists(Guid id, CancellationToken cancellationToken); } diff --git a/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs b/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs index 00af4f7..27add67 100644 --- a/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs +++ b/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs @@ -1,14 +1,15 @@ namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthors; -using System.Threading; -using System.Threading.Tasks; +using Common.Paging; using Entities; using Mediator; -public class GetAuthorsHandler(IAuthorsRepository repository) : IRequestHandler> +public class GetAuthorsHandler(IAuthorsRepository repository) : IRequestHandler> { - public async ValueTask> Handle(GetAuthorsQuery request, CancellationToken cancellationToken) + public async ValueTask> Handle(GetAuthorsQuery request, CancellationToken cancellationToken) { - return await repository.GetAuthors(cancellationToken); + var (items, totalCount) = await repository.GetAuthors(request.Query, request.Offset, request.Limit, cancellationToken); + + return new Page(items, request.Offset, request.Limit, totalCount); } } diff --git a/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs b/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs index fa23471..3953b11 100644 --- a/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs +++ b/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs @@ -1,8 +1,21 @@ namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthors; +using Common.Paging; using Entities; using Mediator; -public class GetAuthorsQuery : IRequest> +/// +/// Lists authors one page at a time, optionally only those whose name contains a search term. Each author comes with +/// their review count and average stars rather than their reviews, which returns. +/// +public class GetAuthorsQuery : IRequest> { + /// The words to look for in the first, last or full name, ignoring case. Leave empty to list every author. + public string? Query { get; init; } + + /// The number of results to skip, 0 for the first page. + public int Offset { get; init; } + + /// The largest number of results to return, from 1 to 50. + public int Limit { get; init; } = Paging.DefaultLimit; } diff --git a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsValidator.cs b/src/Application/Authors/Queries/GetAuthors/GetAuthorsValidator.cs similarity index 56% rename from src/Application/Authors/Queries/SearchAuthors/SearchAuthorsValidator.cs rename to src/Application/Authors/Queries/GetAuthors/GetAuthorsValidator.cs index 0d258c2..5509117 100644 --- a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsValidator.cs +++ b/src/Application/Authors/Queries/GetAuthors/GetAuthorsValidator.cs @@ -1,14 +1,14 @@ -namespace CleanModelContextProtocol.Application.Authors.Queries.SearchAuthors; +namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthors; using Common.Paging; using FluentValidation; -public class SearchAuthorsValidator : AbstractValidator +public class GetAuthorsValidator : AbstractValidator { - public SearchAuthorsValidator() + public GetAuthorsValidator() { _ = this.RuleFor(r => r.Query).ValidSearchTerm(); + _ = this.RuleFor(r => r.Offset).ValidOffset(); _ = this.RuleFor(r => r.Limit).ValidLimit(); - _ = this.RuleFor(r => r.Cursor).ValidCursor(); } } diff --git a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs b/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs deleted file mode 100644 index 8af794c..0000000 --- a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace CleanModelContextProtocol.Application.Authors.Queries.SearchAuthors; - -using System.Threading; -using System.Threading.Tasks; -using Common.Paging; -using Entities; -using Mediator; - -public class SearchAuthorsHandler(IAuthorsRepository repository) : IRequestHandler> -{ - public async ValueTask> Handle(SearchAuthorsQuery request, CancellationToken cancellationToken) - { - _ = Paging.TryDecode(request.Cursor, out var offset); - - var (items, totalCount) = await repository.SearchAuthors(request.Query, offset, request.Limit, cancellationToken); - - return Paging.ToPage(items, totalCount, offset); - } -} diff --git a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsQuery.cs b/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsQuery.cs deleted file mode 100644 index a3c12f7..0000000 --- a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsQuery.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace CleanModelContextProtocol.Application.Authors.Queries.SearchAuthors; - -using Common.Paging; -using Entities; -using Mediator; - -/// -/// Finds authors whose the first or last name contains a search term, one page at a time. -/// -public class SearchAuthorsQuery : IRequest> -{ - /// The words to look for, ignoring case. Leave empty to list every one. - public string Query { get; init; } - - /// The largest number of results to return, from 1 to 50. - public int Limit { get; init; } = Paging.DefaultLimit; - - /// The cursor from a previous page, or empty for the first page. - public string Cursor { get; init; } -} diff --git a/src/Application/Common/Exceptions/NotFoundException.cs b/src/Application/Common/Exceptions/NotFoundException.cs index 196ccec..57cbe7d 100644 --- a/src/Application/Common/Exceptions/NotFoundException.cs +++ b/src/Application/Common/Exceptions/NotFoundException.cs @@ -1,6 +1,7 @@ namespace CleanModelContextProtocol.Application.Common.Exceptions; using System; +using System.Diagnostics.CodeAnalysis; using Enums; public class NotFoundException(string message) : Exception(message) @@ -8,7 +9,7 @@ public class NotFoundException(string message) : Exception(message) /// Throws a if is null. /// The reference type argument to validate as non-null. /// The entity type of the parameter. - public static void ThrowIfNull(object argument, EntityType entityType) + public static void ThrowIfNull([NotNull] object? argument, EntityType entityType) { if (argument is null) { @@ -18,6 +19,7 @@ public static void ThrowIfNull(object argument, EntityType entityType) /// Throws a /// The entity type that was not found. + [DoesNotReturn] public static void Throw(EntityType entityType) { throw new NotFoundException($"The {entityType} with the supplied id was not found."); diff --git a/src/Application/Common/Paging/Page.cs b/src/Application/Common/Paging/Page.cs index 776cc83..e01132a 100644 --- a/src/Application/Common/Paging/Page.cs +++ b/src/Application/Common/Paging/Page.cs @@ -1,10 +1,11 @@ namespace CleanModelContextProtocol.Application.Common.Paging; /// -/// One page of results from a search. +/// One page of results from a list. /// /// The type of the results. /// The results on this page. +/// The number of results skipped before this page. +/// The largest number of results this page could hold. /// The number of results across every page. -/// The cursor that fetches the next page, or null when this is the last page. -public record Page(List Items, int TotalCount, string NextCursor = null); +public record Page(List Items, int Offset, int Limit, int TotalCount); diff --git a/src/Application/Common/Paging/Paging.cs b/src/Application/Common/Paging/Paging.cs index 440b9e2..e6aa4bc 100644 --- a/src/Application/Common/Paging/Paging.cs +++ b/src/Application/Common/Paging/Paging.cs @@ -1,10 +1,7 @@ namespace CleanModelContextProtocol.Application.Common.Paging; -using System.Globalization; -using System.Text; - /// -/// Limits and opaque cursors shared by every search. +/// The limits shared by every paged list. /// public static class Paging { @@ -13,53 +10,4 @@ public static class Paging /// The largest number of results a single page can return. public const int MaxLimit = 50; - - private const string Prefix = "offset:"; - - /// Creates the cursor for the page that starts at . - /// The number of results to skip. - /// An opaque cursor. - public static string Encode(int offset) - { - return Convert.ToBase64String(Encoding.UTF8.GetBytes(Prefix + offset.ToString(CultureInfo.InvariantCulture))); - } - - /// Reads the offset from a cursor. An empty cursor is the first page. - /// The cursor from a previous page, or null for the first page. - /// The number of results to skip. - /// True when the cursor is empty or valid. - public static bool TryDecode(string cursor, out int offset) - { - offset = 0; - - if (string.IsNullOrEmpty(cursor)) - { - return true; - } - - try - { - var value = Encoding.UTF8.GetString(Convert.FromBase64String(cursor)); - - return value.StartsWith(Prefix, StringComparison.Ordinal) - && int.TryParse(value.AsSpan(Prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out offset); - } - catch (FormatException) - { - return false; - } - } - - /// Creates the page for a set of results, with a cursor when more results remain. - /// The type of the results. - /// The results on this page. - /// The number of results across every page. - /// The number of results skipped before this page. - /// The page. - public static Page ToPage(List items, int totalCount, int offset) - { - var next = offset + items.Count; - - return new Page(items, totalCount, next < totalCount ? Encode(next) : null); - } } diff --git a/src/Application/Common/Paging/PagingValidatorExtensions.cs b/src/Application/Common/Paging/PagingValidatorExtensions.cs index 940bb27..040ba78 100644 --- a/src/Application/Common/Paging/PagingValidatorExtensions.cs +++ b/src/Application/Common/Paging/PagingValidatorExtensions.cs @@ -3,34 +3,33 @@ namespace CleanModelContextProtocol.Application.Common.Paging; using FluentValidation; /// -/// Validation rules shared by every search. +/// Validation rules shared by every paged list. /// public static class PagingValidatorExtensions { - /// Checks that a limit is between 1 and . + /// Checks that an offset is zero or more. /// The type being validated. - /// The rule for the limit. + /// The rule for the offset. /// The rule. - public static IRuleBuilderOptions ValidLimit(this IRuleBuilder rule) + public static IRuleBuilderOptions ValidOffset(this IRuleBuilder rule) { - return rule.InclusiveBetween(1, Paging.MaxLimit).WithMessage($"A limit must be between 1 and {Paging.MaxLimit}."); + return rule.GreaterThanOrEqualTo(0).WithMessage("An offset can't be negative. Use 0 for the first page."); } - /// Checks that a cursor is empty or came from a previous page. + /// Checks that a limit is between 1 and . /// The type being validated. - /// The rule for the cursor. + /// The rule for the limit. /// The rule. - public static IRuleBuilderOptions ValidCursor(this IRuleBuilder rule) + public static IRuleBuilderOptions ValidLimit(this IRuleBuilder rule) { - return rule.Must(cursor => Paging.TryDecode(cursor, out _)) - .WithMessage("The cursor is not valid. Use the nextCursor from a previous page, or leave it empty for the first page."); + return rule.InclusiveBetween(1, Paging.MaxLimit).WithMessage($"A limit must be between 1 and {Paging.MaxLimit}."); } /// Checks that a search term is no longer than 100 characters. /// The type being validated. /// The rule for the search term. /// The rule. - public static IRuleBuilderOptions ValidSearchTerm(this IRuleBuilder rule) + public static IRuleBuilderOptions ValidSearchTerm(this IRuleBuilder rule) { return rule.MaximumLength(100).WithMessage("A search term can't be longer than 100 characters."); } diff --git a/src/Application/Movies/Entities/Movie.cs b/src/Application/Movies/Entities/Movie.cs index a664863..1f3ee83 100644 --- a/src/Application/Movies/Entities/Movie.cs +++ b/src/Application/Movies/Entities/Movie.cs @@ -8,4 +8,4 @@ namespace CleanModelContextProtocol.Application.Movies.Entities; /// The unique identifier of the movie. /// The title of the movie. /// The reviews written about the movie. -public record Movie(Guid Id, string Title, ICollection Reviews = null); +public record Movie(Guid Id, string Title, ICollection Reviews); diff --git a/src/Application/Movies/Entities/MovieSummary.cs b/src/Application/Movies/Entities/MovieSummary.cs new file mode 100644 index 0000000..cc7f8cf --- /dev/null +++ b/src/Application/Movies/Entities/MovieSummary.cs @@ -0,0 +1,10 @@ +namespace CleanModelContextProtocol.Application.Movies.Entities; + +/// +/// A movie in a list, with how many reviews it has and their average star rating instead of the reviews themselves. +/// +/// The unique identifier of the movie. +/// The title of the movie. +/// The number of reviews written about the movie. +/// The average star rating to one decimal place, or null when the movie has no reviews. +public record MovieSummary(Guid Id, string Title, int ReviewCount, double? AverageStars); diff --git a/src/Application/Movies/IMoviesRepository.cs b/src/Application/Movies/IMoviesRepository.cs index eb55f94..46a5ac1 100644 --- a/src/Application/Movies/IMoviesRepository.cs +++ b/src/Application/Movies/IMoviesRepository.cs @@ -1,19 +1,16 @@ namespace CleanModelContextProtocol.Application.Movies; -using System.Threading.Tasks; using Entities; public interface IMoviesRepository { - public Task> GetMovies(CancellationToken cancellationToken); - - public Task GetMovieById(Guid id, CancellationToken cancellationToken); - - public Task MovieExists(Guid id, CancellationToken cancellationToken); - - public Task<(List Items, int TotalCount)> SearchMovies( - string query, + public Task<(List Items, int TotalCount)> GetMovies( + string? query, int offset, int limit, CancellationToken cancellationToken); + + public Task GetMovieById(Guid id, CancellationToken cancellationToken); + + public Task MovieExists(Guid id, CancellationToken cancellationToken); } diff --git a/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs b/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs index 81488e2..46a47e9 100644 --- a/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs +++ b/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs @@ -1,14 +1,15 @@ namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovies; -using System.Threading; -using System.Threading.Tasks; +using Common.Paging; using Entities; using Mediator; -public class GetMoviesHandler(IMoviesRepository repository) : IRequestHandler> +public class GetMoviesHandler(IMoviesRepository repository) : IRequestHandler> { - public async ValueTask> Handle(GetMoviesQuery request, CancellationToken cancellationToken) + public async ValueTask> Handle(GetMoviesQuery request, CancellationToken cancellationToken) { - return await repository.GetMovies(cancellationToken); + var (items, totalCount) = await repository.GetMovies(request.Query, request.Offset, request.Limit, cancellationToken); + + return new Page(items, request.Offset, request.Limit, totalCount); } } diff --git a/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs b/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs index 03a644c..2d4b460 100644 --- a/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs +++ b/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs @@ -1,8 +1,21 @@ namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovies; +using Common.Paging; using Entities; using Mediator; -public class GetMoviesQuery : IRequest> +/// +/// Lists movies one page at a time, optionally only those whose title contains a search term. Each movie comes with its +/// review count and average stars rather than its reviews, which returns. +/// +public class GetMoviesQuery : IRequest> { + /// The words to look for in the title, ignoring case. Leave empty to list every movie. + public string? Query { get; init; } + + /// The number of results to skip, 0 for the first page. + public int Offset { get; init; } + + /// The largest number of results to return, from 1 to 50. + public int Limit { get; init; } = Paging.DefaultLimit; } diff --git a/src/Application/Movies/Queries/GetMovies/GetMoviesValidator.cs b/src/Application/Movies/Queries/GetMovies/GetMoviesValidator.cs new file mode 100644 index 0000000..883d8f7 --- /dev/null +++ b/src/Application/Movies/Queries/GetMovies/GetMoviesValidator.cs @@ -0,0 +1,14 @@ +namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovies; + +using Common.Paging; +using FluentValidation; + +public class GetMoviesValidator : AbstractValidator +{ + public GetMoviesValidator() + { + _ = this.RuleFor(r => r.Query).ValidSearchTerm(); + _ = this.RuleFor(r => r.Offset).ValidOffset(); + _ = this.RuleFor(r => r.Limit).ValidLimit(); + } +} diff --git a/src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs b/src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs deleted file mode 100644 index 2486af7..0000000 --- a/src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace CleanModelContextProtocol.Application.Movies.Queries.SearchMovies; - -using System.Threading; -using System.Threading.Tasks; -using Common.Paging; -using Entities; -using Mediator; - -public class SearchMoviesHandler(IMoviesRepository repository) : IRequestHandler> -{ - public async ValueTask> Handle(SearchMoviesQuery request, CancellationToken cancellationToken) - { - _ = Paging.TryDecode(request.Cursor, out var offset); - - var (items, totalCount) = await repository.SearchMovies(request.Query, offset, request.Limit, cancellationToken); - - return Paging.ToPage(items, totalCount, offset); - } -} diff --git a/src/Application/Movies/Queries/SearchMovies/SearchMoviesQuery.cs b/src/Application/Movies/Queries/SearchMovies/SearchMoviesQuery.cs deleted file mode 100644 index 39be8fa..0000000 --- a/src/Application/Movies/Queries/SearchMovies/SearchMoviesQuery.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace CleanModelContextProtocol.Application.Movies.Queries.SearchMovies; - -using Common.Paging; -using Entities; -using Mediator; - -/// -/// Finds movies whose the title contains a search term, one page at a time. -/// -public class SearchMoviesQuery : IRequest> -{ - /// The words to look for, ignoring case. Leave empty to list every one. - public string Query { get; init; } - - /// The largest number of results to return, from 1 to 50. - public int Limit { get; init; } = Paging.DefaultLimit; - - /// The cursor from a previous page, or empty for the first page. - public string Cursor { get; init; } -} diff --git a/src/Application/Movies/Queries/SearchMovies/SearchMoviesValidator.cs b/src/Application/Movies/Queries/SearchMovies/SearchMoviesValidator.cs deleted file mode 100644 index d45bca5..0000000 --- a/src/Application/Movies/Queries/SearchMovies/SearchMoviesValidator.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace CleanModelContextProtocol.Application.Movies.Queries.SearchMovies; - -using Common.Paging; -using FluentValidation; - -public class SearchMoviesValidator : AbstractValidator -{ - public SearchMoviesValidator() - { - _ = this.RuleFor(r => r.Query).ValidSearchTerm(); - _ = this.RuleFor(r => r.Limit).ValidLimit(); - _ = this.RuleFor(r => r.Cursor).ValidCursor(); - } -} diff --git a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs index 0f11c5d..2ba0410 100644 --- a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs +++ b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs @@ -2,13 +2,14 @@ namespace CleanModelContextProtocol.Application.Reviews.Commands.UpdateReview; using Mediator; +/// +/// Changes the star rating of a review. The author and the movie of a review can't change. +/// public class UpdateReviewCommand : IRequest { - public Guid Id { get; set; } - - public Guid AuthorId { get; init; } - - public Guid MovieId { get; init; } + /// The unique identifier of the review. + public Guid Id { get; init; } + /// The new star rating, from 1 to 5. public int Stars { get; init; } } diff --git a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs index 90b07f3..7e9dedc 100644 --- a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs +++ b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs @@ -1,17 +1,10 @@ namespace CleanModelContextProtocol.Application.Reviews.Commands.UpdateReview; -using System.Threading; -using System.Threading.Tasks; -using CleanModelContextProtocol.Application.Authors; -using CleanModelContextProtocol.Application.Movies; using Common.Enums; using Common.Exceptions; using Mediator; -public class UpdateReviewHandler( - IAuthorsRepository authorsRepository, - IMoviesRepository moviesRepository, - IReviewsRepository reviewsRepository) : IRequestHandler +public class UpdateReviewHandler(IReviewsRepository reviewsRepository) : IRequestHandler { public async ValueTask Handle(UpdateReviewCommand request, CancellationToken cancellationToken) { @@ -20,17 +13,6 @@ public async ValueTask Handle(UpdateReviewCommand request, CancellationTok NotFoundException.Throw(EntityType.Review); } - if (!await authorsRepository.AuthorExists(request.AuthorId, cancellationToken)) - { - NotFoundException.Throw(EntityType.Author); - } - - if (!await moviesRepository.MovieExists(request.MovieId, cancellationToken)) - { - NotFoundException.Throw(EntityType.Movie); - } - - return await reviewsRepository - .UpdateReview(request.Id, request.AuthorId, request.MovieId, request.Stars, cancellationToken); + return await reviewsRepository.UpdateReview(request.Id, request.Stars, cancellationToken); } } diff --git a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs index d95b20f..a1bb7b1 100644 --- a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs +++ b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs @@ -7,8 +7,6 @@ public class UpdateReviewValidator : AbstractValidator public UpdateReviewValidator() { _ = this.RuleFor(r => r.Id).NotEqual(Guid.Empty).WithMessage("A review id was not supplied to Update the review."); - _ = this.RuleFor(r => r.AuthorId).NotEqual(Guid.Empty).WithMessage("An author id was not supplied to Update the review."); - _ = this.RuleFor(r => r.MovieId).NotEqual(Guid.Empty).WithMessage("A movie id was not supplied to Update the review."); _ = this.RuleFor(r => r.Stars).InclusiveBetween(1, 5).WithMessage("A star rating must be between 1 and 5."); } } diff --git a/src/Application/Reviews/Entities/Review.cs b/src/Application/Reviews/Entities/Review.cs index 580814e..da115ce 100644 --- a/src/Application/Reviews/Entities/Review.cs +++ b/src/Application/Reviews/Entities/Review.cs @@ -13,5 +13,5 @@ namespace CleanModelContextProtocol.Application.Reviews.Entities; public record Review( Guid Id, int Stars, - ReviewedMovie ReviewedMovie = null, - ReviewAuthor ReviewAuthor = null); + ReviewedMovie? ReviewedMovie = null, + ReviewAuthor? ReviewAuthor = null); diff --git a/src/Application/Reviews/IReviewsRepository.cs b/src/Application/Reviews/IReviewsRepository.cs index 1e59e60..cf1781e 100644 --- a/src/Application/Reviews/IReviewsRepository.cs +++ b/src/Application/Reviews/IReviewsRepository.cs @@ -1,6 +1,5 @@ namespace CleanModelContextProtocol.Application.Reviews; -using System.Threading.Tasks; using Entities; public interface IReviewsRepository @@ -13,23 +12,20 @@ public Task CreateReview( public Task DeleteReview(Guid id, CancellationToken cancellationToken); - public Task> GetReviews(CancellationToken cancellationToken); - - public Task GetReviewById(Guid id, CancellationToken cancellationToken); - - public Task ReviewExists(Guid id, CancellationToken cancellationToken); - - public Task<(List Items, int TotalCount)> SearchReviews( + public Task<(List Items, int TotalCount)> GetReviews( Guid? movieId, Guid? authorId, int offset, int limit, CancellationToken cancellationToken); - public Task UpdateReview( - Guid id, - Guid authorId, - Guid movieId, - int stars, - CancellationToken cancellationToken); + public Task> GetReviewsForMovies(IReadOnlyCollection movieIds, CancellationToken cancellationToken); + + public Task> GetReviewsForAuthors(IReadOnlyCollection authorIds, CancellationToken cancellationToken); + + public Task GetReviewById(Guid id, CancellationToken cancellationToken); + + public Task ReviewExists(Guid id, CancellationToken cancellationToken); + + public Task UpdateReview(Guid id, int stars, CancellationToken cancellationToken); } diff --git a/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs b/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs index fc0c1a9..e46086e 100644 --- a/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs +++ b/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs @@ -1,14 +1,15 @@ namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviews; -using System.Threading; -using System.Threading.Tasks; +using Common.Paging; using Entities; using Mediator; -public class GetReviewsHandler(IReviewsRepository repository) : IRequestHandler> +public class GetReviewsHandler(IReviewsRepository repository) : IRequestHandler> { - public async ValueTask> Handle(GetReviewsQuery request, CancellationToken cancellationToken) + public async ValueTask> Handle(GetReviewsQuery request, CancellationToken cancellationToken) { - return await repository.GetReviews(cancellationToken); + var (items, totalCount) = await repository.GetReviews(request.MovieId, request.AuthorId, request.Offset, request.Limit, cancellationToken); + + return new Page(items, request.Offset, request.Limit, totalCount); } } diff --git a/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs b/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs index 23c80bc..6e735bd 100644 --- a/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs +++ b/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs @@ -1,8 +1,23 @@ namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviews; +using Common.Paging; using Entities; using Mediator; -public class GetReviewsQuery : IRequest> +/// +/// Lists reviews one page at a time, optionally only those of one movie, by one author, or both. +/// +public class GetReviewsQuery : IRequest> { + /// Only return reviews of this movie. Leave empty for every movie. + public Guid? MovieId { get; init; } + + /// Only return reviews by this author. Leave empty for every author. + public Guid? AuthorId { get; init; } + + /// The number of results to skip, 0 for the first page. + public int Offset { get; init; } + + /// The largest number of results to return, from 1 to 50. + public int Limit { get; init; } = Paging.DefaultLimit; } diff --git a/src/Application/Reviews/Queries/GetReviews/GetReviewsValidator.cs b/src/Application/Reviews/Queries/GetReviews/GetReviewsValidator.cs new file mode 100644 index 0000000..e917878 --- /dev/null +++ b/src/Application/Reviews/Queries/GetReviews/GetReviewsValidator.cs @@ -0,0 +1,15 @@ +namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviews; + +using Common.Paging; +using FluentValidation; + +public class GetReviewsValidator : AbstractValidator +{ + public GetReviewsValidator() + { + _ = this.RuleFor(r => r.MovieId).NotEqual(Guid.Empty).WithMessage("A Movie Id can't be empty. Leave it out to list every movie."); + _ = this.RuleFor(r => r.AuthorId).NotEqual(Guid.Empty).WithMessage("An Author Id can't be empty. Leave it out to list every author."); + _ = this.RuleFor(r => r.Offset).ValidOffset(); + _ = this.RuleFor(r => r.Limit).ValidLimit(); + } +} diff --git a/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsHandler.cs b/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsHandler.cs new file mode 100644 index 0000000..4fcf1a9 --- /dev/null +++ b/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsHandler.cs @@ -0,0 +1,18 @@ +namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewsForAuthors; + +using Entities; +using Mediator; + +public class GetReviewsForAuthorsHandler(IReviewsRepository repository) : IRequestHandler>> +{ + public async ValueTask>> Handle(GetReviewsForAuthorsQuery request, CancellationToken cancellationToken) + { + var reviews = (await repository.GetReviewsForAuthors(request.AuthorIds, cancellationToken)) + .ToLookup(r => r.ReviewAuthor?.Id); + + // Every id gets an entry, so a author with no reviews has an empty list rather than no entry. + return request.AuthorIds + .Distinct() + .ToDictionary(id => id, id => reviews[id].ToList()); + } +} diff --git a/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsQuery.cs b/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsQuery.cs new file mode 100644 index 0000000..d11cb46 --- /dev/null +++ b/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsQuery.cs @@ -0,0 +1,14 @@ +namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewsForAuthors; + +using Entities; +using Mediator; + +/// +/// Gets every review of several authors in one call, grouped by author. Presentation layers use it to load reviews for a +/// whole page of authors at once instead of one query per author. +/// +public class GetReviewsForAuthorsQuery : IRequest>> +{ + /// The authors to get the reviews of. + public required IReadOnlyCollection AuthorIds { get; init; } +} diff --git a/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsValidator.cs b/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsValidator.cs new file mode 100644 index 0000000..ccad488 --- /dev/null +++ b/src/Application/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsValidator.cs @@ -0,0 +1,15 @@ +namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewsForAuthors; + +using Common.Paging; +using FluentValidation; + +public class GetReviewsForAuthorsValidator : AbstractValidator +{ + public GetReviewsForAuthorsValidator() + { + _ = this.RuleFor(r => r.AuthorIds) + .NotEmpty().WithMessage("At least one Author Id is needed.") + .Must(ids => ids.Count <= Paging.MaxLimit).WithMessage($"Reviews can be fetched for at most {Paging.MaxLimit} authors at a time."); + _ = this.RuleForEach(r => r.AuthorIds).NotEqual(Guid.Empty).WithMessage("An Author Id can't be empty."); + } +} diff --git a/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesHandler.cs b/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesHandler.cs new file mode 100644 index 0000000..63fda46 --- /dev/null +++ b/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesHandler.cs @@ -0,0 +1,18 @@ +namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewsForMovies; + +using Entities; +using Mediator; + +public class GetReviewsForMoviesHandler(IReviewsRepository repository) : IRequestHandler>> +{ + public async ValueTask>> Handle(GetReviewsForMoviesQuery request, CancellationToken cancellationToken) + { + var reviews = (await repository.GetReviewsForMovies(request.MovieIds, cancellationToken)) + .ToLookup(r => r.ReviewedMovie?.Id); + + // Every id gets an entry, so a movie with no reviews has an empty list rather than no entry. + return request.MovieIds + .Distinct() + .ToDictionary(id => id, id => reviews[id].ToList()); + } +} diff --git a/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesQuery.cs b/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesQuery.cs new file mode 100644 index 0000000..62a0d22 --- /dev/null +++ b/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesQuery.cs @@ -0,0 +1,14 @@ +namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewsForMovies; + +using Entities; +using Mediator; + +/// +/// Gets every review of several movies in one call, grouped by movie. Presentation layers use it to load reviews for a +/// whole page of movies at once instead of one query per movie. +/// +public class GetReviewsForMoviesQuery : IRequest>> +{ + /// The movies to get the reviews of. + public required IReadOnlyCollection MovieIds { get; init; } +} diff --git a/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesValidator.cs b/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesValidator.cs new file mode 100644 index 0000000..f7040a6 --- /dev/null +++ b/src/Application/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesValidator.cs @@ -0,0 +1,15 @@ +namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewsForMovies; + +using Common.Paging; +using FluentValidation; + +public class GetReviewsForMoviesValidator : AbstractValidator +{ + public GetReviewsForMoviesValidator() + { + _ = this.RuleFor(r => r.MovieIds) + .NotEmpty().WithMessage("At least one Movie Id is needed.") + .Must(ids => ids.Count <= Paging.MaxLimit).WithMessage($"Reviews can be fetched for at most {Paging.MaxLimit} movies at a time."); + _ = this.RuleForEach(r => r.MovieIds).NotEqual(Guid.Empty).WithMessage("A Movie Id can't be empty."); + } +} diff --git a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs b/src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs deleted file mode 100644 index df733e3..0000000 --- a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace CleanModelContextProtocol.Application.Reviews.Queries.SearchReviews; - -using System.Threading; -using System.Threading.Tasks; -using Common.Paging; -using Entities; -using Mediator; - -public class SearchReviewsHandler(IReviewsRepository repository) : IRequestHandler> -{ - public async ValueTask> Handle(SearchReviewsQuery request, CancellationToken cancellationToken) - { - _ = Paging.TryDecode(request.Cursor, out var offset); - - var (items, totalCount) = await repository.SearchReviews(request.MovieId, request.AuthorId, offset, request.Limit, cancellationToken); - - return Paging.ToPage(items, totalCount, offset); - } -} diff --git a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsQuery.cs b/src/Application/Reviews/Queries/SearchReviews/SearchReviewsQuery.cs deleted file mode 100644 index 2080520..0000000 --- a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsQuery.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace CleanModelContextProtocol.Application.Reviews.Queries.SearchReviews; - -using Common.Paging; -using Entities; -using Mediator; - -/// -/// Finds reviews, optionally only those for one movie or by one author, one page at a time. -/// -public class SearchReviewsQuery : IRequest> -{ - /// Only return reviews of this movie. Leave empty for every movie. - public Guid? MovieId { get; init; } - - /// Only return reviews by this author. Leave empty for every author. - public Guid? AuthorId { get; init; } - - /// The largest number of results to return, from 1 to 50. - public int Limit { get; init; } = Paging.DefaultLimit; - - /// The cursor from a previous page, or empty for the first page. - public string Cursor { get; init; } -} diff --git a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsValidator.cs b/src/Application/Reviews/Queries/SearchReviews/SearchReviewsValidator.cs deleted file mode 100644 index f37375b..0000000 --- a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsValidator.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace CleanModelContextProtocol.Application.Reviews.Queries.SearchReviews; - -using Common.Paging; -using FluentValidation; - -public class SearchReviewsValidator : AbstractValidator -{ - public SearchReviewsValidator() - { - _ = this.RuleFor(r => r.MovieId).NotEqual(Guid.Empty).WithMessage("A Movie Id can't be empty. Leave it out to search every movie."); - _ = this.RuleFor(r => r.AuthorId).NotEqual(Guid.Empty).WithMessage("An Author Id can't be empty. Leave it out to search every author."); - _ = this.RuleFor(r => r.Limit).ValidLimit(); - _ = this.RuleFor(r => r.Cursor).ValidCursor(); - } -} diff --git a/src/Application/Versions/Entities/Version.cs b/src/Application/Versions/Entities/Version.cs index 1c064ee..9eaf65d 100644 --- a/src/Application/Versions/Entities/Version.cs +++ b/src/Application/Versions/Entities/Version.cs @@ -9,11 +9,11 @@ public class Version /// The assembly file version. /// /// 1.1.0.0 - public string FileVersion { get; init; } + public required string FileVersion { get; init; } /// /// The informational version, which can include a pre-release label or commit hash. /// /// 1.1.0+e30eba8 - public string InformationalVersion { get; init; } + public required string InformationalVersion { get; init; } } diff --git a/src/Infrastructure/Databases/MovieReviews/Configuration/EntityConfiguration.cs b/src/Infrastructure/Databases/MovieReviews/Configuration/EntityConfiguration.cs index bf6ec2a..fb4ce72 100644 --- a/src/Infrastructure/Databases/MovieReviews/Configuration/EntityConfiguration.cs +++ b/src/Infrastructure/Databases/MovieReviews/Configuration/EntityConfiguration.cs @@ -11,7 +11,7 @@ public virtual void Configure(EntityTypeBuilder builder) { _ = builder.HasKey(e => e.Id); _ = builder.Property(m => m.Id).ValueGeneratedOnAdd().IsRequired(); - _ = builder.Property(m => m.DateCreated).ValueGeneratedOnAdd().IsRequired(); - _ = builder.Property(m => m.DateModified).ValueGeneratedOnAdd().IsRequired(); + _ = builder.Property(m => m.DateCreated).IsRequired(); + _ = builder.Property(m => m.DateModified).IsRequired(); } } diff --git a/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs b/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs index 8dc950b..3c15542 100644 --- a/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs +++ b/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs @@ -2,16 +2,15 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews; using System; using Application.Authors; -using Application.Common.Enums; -using Application.Common.Exceptions; using Application.Movies; using Application.Reviews; -using Extensions; using Mapping; using Microsoft.EntityFrameworkCore; using Models; using ApplicationAuthor = Application.Authors.Entities.Author; +using ApplicationAuthorSummary = Application.Authors.Entities.AuthorSummary; using ApplicationMovie = Application.Movies.Entities.Movie; +using ApplicationMovieSummary = Application.Movies.Entities.MovieSummary; using ApplicationReview = Application.Reviews.Entities.Review; internal class EntityFrameworkMovieReviewsRepository : IAuthorsRepository, IMoviesRepository, IReviewsRepository @@ -32,43 +31,12 @@ public EntityFrameworkMovieReviewsRepository( this.context = context; this.timeProvider = timeProvider; this.mapper = mapper; - - _ = this.context.Database.EnsureDeleted(); - _ = this.context.Database.EnsureCreated(); - _ = this.context.AddData(); } #region Authors - public virtual async Task> GetAuthors(CancellationToken cancellationToken) - { - var authors = await this.context.Authors - .Include(a => a.Reviews) - .ThenInclude(r => r.ReviewedMovie) - .AsNoTracking() - .ToListAsync(cancellationToken); - - return [.. authors.Select(this.mapper.ToDomain)]; - } - - public virtual async Task GetAuthorById(Guid id, CancellationToken cancellationToken) - { - var author = await this.context.Authors - .Where(r => r.Id == id).Include(a => a.Reviews) - .ThenInclude(r => r.ReviewedMovie) - .AsNoTracking() - .FirstOrDefaultAsync(cancellationToken); - - return this.mapper.ToDomain(author); - } - - public virtual async Task AuthorExists(Guid id, CancellationToken cancellationToken) - { - return await this.context.Authors.AsNoTracking().AnyAsync(a => a.Id == id, cancellationToken); - } - - public virtual async Task<(List Items, int TotalCount)> SearchAuthors( - string query, + public virtual async Task<(List Items, int TotalCount)> GetAuthors( + string? query, int offset, int limit, CancellationToken cancellationToken) @@ -77,60 +45,55 @@ public virtual async Task AuthorExists(Guid id, CancellationToken cancella if (!string.IsNullOrWhiteSpace(query)) { - var term = query.Trim(); + var pattern = ContainsPattern(query); - authors = authors.Where(a => (a.FirstName + " " + a.LastName).Contains(term, StringComparison.OrdinalIgnoreCase)); + authors = authors.Where(a => EF.Functions.Like(a.FirstName + " " + a.LastName, pattern, EscapeCharacter)); } var totalCount = await authors.CountAsync(cancellationToken); + // The review count and average are worked out by the database, so the reviews themselves are never loaded. var result = await authors .OrderBy(a => a.LastName) .ThenBy(a => a.FirstName) .ThenBy(a => a.Id) .Skip(offset) .Take(limit) - .Include(a => a.Reviews) - .ThenInclude(r => r.ReviewedMovie) + .Select(a => new + { + a.Id, + a.FirstName, + a.LastName, + ReviewCount = a.Reviews.Count, + AverageStars = a.Reviews.Average(r => (double?)r.Stars) + }) .ToListAsync(cancellationToken); - return ([.. result.Select(this.mapper.ToDomain)], totalCount); + return ([.. result.Select(a => new ApplicationAuthorSummary(a.Id, a.FirstName, a.LastName, a.ReviewCount, RoundStars(a.AverageStars)))], totalCount); } - #endregion Authors - - #region Movies - - public virtual async Task> GetMovies(CancellationToken cancellationToken) + public virtual async Task GetAuthorById(Guid id, CancellationToken cancellationToken) { - var result = await this.context.Movies - .Include(m => m.Reviews) - .ThenInclude(r => r.ReviewAuthor) - .AsNoTracking() - .ToListAsync(cancellationToken); - - return [.. result.Select(this.mapper.ToDomain)]; - } - - public virtual async Task GetMovieById(Guid id, CancellationToken cancellationToken) - { - var result = await this.context.Movies - .Where(r => r.Id == id) - .Include(m => m.Reviews) - .ThenInclude(r => r.ReviewAuthor) + var author = await this.context.Authors + .Where(r => r.Id == id).Include(a => a.Reviews) + .ThenInclude(r => r.ReviewedMovie) .AsNoTracking() .FirstOrDefaultAsync(cancellationToken); - return this.mapper.ToDomain(result); + return author is null ? null : this.mapper.ToDomain(author); } - public virtual async Task MovieExists(Guid id, CancellationToken cancellationToken) + public virtual async Task AuthorExists(Guid id, CancellationToken cancellationToken) { - return await this.context.Movies.AsNoTracking().AnyAsync(m => m.Id == id, cancellationToken); + return await this.context.Authors.AsNoTracking().AnyAsync(a => a.Id == id, cancellationToken); } - public virtual async Task<(List Items, int TotalCount)> SearchMovies( - string query, + #endregion Authors + + #region Movies + + public virtual async Task<(List Items, int TotalCount)> GetMovies( + string? query, int offset, int limit, CancellationToken cancellationToken) @@ -139,23 +102,46 @@ public virtual async Task MovieExists(Guid id, CancellationToken cancellat if (!string.IsNullOrWhiteSpace(query)) { - var term = query.Trim(); + var pattern = ContainsPattern(query); - movies = movies.Where(m => m.Title.Contains(term, StringComparison.OrdinalIgnoreCase)); + movies = movies.Where(m => EF.Functions.Like(m.Title, pattern, EscapeCharacter)); } var totalCount = await movies.CountAsync(cancellationToken); + // The review count and average are worked out by the database, so the reviews themselves are never loaded. var result = await movies .OrderBy(m => m.Title) .ThenBy(m => m.Id) .Skip(offset) .Take(limit) + .Select(m => new + { + m.Id, + m.Title, + ReviewCount = m.Reviews.Count, + AverageStars = m.Reviews.Average(r => (double?)r.Stars) + }) + .ToListAsync(cancellationToken); + + return ([.. result.Select(m => new ApplicationMovieSummary(m.Id, m.Title, m.ReviewCount, RoundStars(m.AverageStars)))], totalCount); + } + + public virtual async Task GetMovieById(Guid id, CancellationToken cancellationToken) + { + var result = await this.context.Movies + .Where(r => r.Id == id) .Include(m => m.Reviews) .ThenInclude(r => r.ReviewAuthor) - .ToListAsync(cancellationToken); + .AsNoTracking() + .FirstOrDefaultAsync(cancellationToken); - return ([.. result.Select(this.mapper.ToDomain)], totalCount); + return result is null ? null : this.mapper.ToDomain(result); + } + + public virtual async Task MovieExists(Guid id, CancellationToken cancellationToken) + { + return await this.context.Movies.AsNoTracking().AnyAsync(m => m.Id == id, cancellationToken); } #endregion Movies @@ -168,13 +154,15 @@ public async Task CreateReview( int stars, CancellationToken cancellationToken) { + var now = this.timeProvider.GetUtcNow().UtcDateTime; + var review = new Review { ReviewAuthorId = authorId, ReviewedMovieId = movieId, Stars = stars, - DateCreated = this.timeProvider.GetUtcNow().UtcDateTime, - DateModified = this.timeProvider.GetUtcNow().UtcDateTime + DateCreated = now, + DateModified = now }; var id = this.context.Add(review).Entity.Id; @@ -193,31 +181,77 @@ public async Task CreateReview( public async Task DeleteReview(Guid id, CancellationToken cancellationToken) { - try + var deleted = await this.context.Reviews + .Where(r => r.Id == id) + .ExecuteDeleteAsync(cancellationToken); + + return deleted > 0; + } + + public async Task<(List Items, int TotalCount)> GetReviews( + Guid? movieId, + Guid? authorId, + int offset, + int limit, + CancellationToken cancellationToken) + { + var reviews = this.context.Reviews.AsNoTracking(); + + if (movieId is Guid reviewedMovieId) { - _ = this.context.Remove(this.context.Reviews.Single(r => r.Id == id)); - _ = await this.context.SaveChangesAsync(cancellationToken); + reviews = reviews.Where(r => r.ReviewedMovieId == reviewedMovieId); } - catch (Exception) + + if (authorId is Guid reviewAuthorId) { - return false; + reviews = reviews.Where(r => r.ReviewAuthorId == reviewAuthorId); } - return true; + var totalCount = await reviews.CountAsync(cancellationToken); + + var result = await reviews + .Include(r => r.ReviewAuthor) + .Include(r => r.ReviewedMovie) + .OrderBy(r => r.ReviewedMovie.Title) + .ThenBy(r => r.ReviewAuthor.LastName) + .ThenBy(r => r.Id) + .Skip(offset) + .Take(limit) + .ToListAsync(cancellationToken); + + return ([.. result.Select(this.mapper.ToDomain)], totalCount); } - public async Task> GetReviews(CancellationToken cancellationToken) + public async Task> GetReviewsForMovies(IReadOnlyCollection movieIds, CancellationToken cancellationToken) { var result = await this.context.Reviews + .AsNoTracking() + .Where(r => movieIds.Contains(r.ReviewedMovieId)) .Include(r => r.ReviewAuthor) .Include(r => r.ReviewedMovie) + .OrderBy(r => r.ReviewAuthor.LastName) + .ThenBy(r => r.ReviewAuthor.FirstName) + .ThenBy(r => r.Id) + .ToListAsync(cancellationToken); + + return [.. result.Select(this.mapper.ToDomain)]; + } + + public async Task> GetReviewsForAuthors(IReadOnlyCollection authorIds, CancellationToken cancellationToken) + { + var result = await this.context.Reviews .AsNoTracking() + .Where(r => authorIds.Contains(r.ReviewAuthorId)) + .Include(r => r.ReviewAuthor) + .Include(r => r.ReviewedMovie) + .OrderBy(r => r.ReviewedMovie.Title) + .ThenBy(r => r.Id) .ToListAsync(cancellationToken); return [.. result.Select(this.mapper.ToDomain)]; } - public async Task GetReviewById(Guid id, CancellationToken cancellationToken) + public async Task GetReviewById(Guid id, CancellationToken cancellationToken) { var result = await this.context.Reviews .Where(r => r.Id == id) @@ -226,7 +260,7 @@ public async Task GetReviewById(Guid id, CancellationToken ca .AsNoTracking() .FirstOrDefaultAsync(cancellationToken); - return this.mapper.ToDomain(result); + return result is null ? null : this.mapper.ToDomain(result); } public async Task ReviewExists(Guid id, CancellationToken cancellationToken) @@ -234,68 +268,49 @@ public async Task ReviewExists(Guid id, CancellationToken cancellationToke return await this.context.Reviews.AnyAsync(r => r.Id == id, cancellationToken); } - public async Task<(List Items, int TotalCount)> SearchReviews( - Guid? movieId, - Guid? authorId, - int offset, - int limit, - CancellationToken cancellationToken) + public async Task UpdateReview(Guid id, int stars, CancellationToken cancellationToken) { - var reviews = this.context.Reviews.AsNoTracking(); + var now = this.timeProvider.GetUtcNow().UtcDateTime; - if (movieId is Guid reviewedMovieId) - { - reviews = reviews.Where(r => r.ReviewedMovieId == reviewedMovieId); - } + var updated = await this.context.Reviews + .Where(r => r.Id == id) + .ExecuteUpdateAsync( + setters => setters + .SetProperty(r => r.Stars, stars) + .SetProperty(r => r.DateModified, now), + cancellationToken); - if (authorId is Guid reviewAuthorId) - { - reviews = reviews.Where(r => r.ReviewAuthorId == reviewAuthorId); - } + return updated > 0; + } - var totalCount = await reviews.CountAsync(cancellationToken); + #endregion Reviews - var result = await reviews - .Include(r => r.ReviewAuthor) - .Include(r => r.ReviewedMovie) - .OrderBy(r => r.ReviewedMovie.Title) - .ThenBy(r => r.ReviewAuthor.LastName) - .ThenBy(r => r.Id) - .Skip(offset) - .Take(limit) - .ToListAsync(cancellationToken); + #region Helpers - return ([.. result.Select(this.mapper.ToDomain)], totalCount); + private static double? RoundStars(double? averageStars) + { + return averageStars is null ? null : Math.Round(averageStars.Value, 1, MidpointRounding.AwayFromZero); } - public async Task UpdateReview( - Guid id, - Guid authorId, - Guid movieId, - int stars, - CancellationToken cancellationToken) - { - try - { - var review = this.context.Reviews.FirstOrDefault(r => r.Id == id); + #endregion Helpers - NotFoundException.ThrowIfNull(review, EntityType.Review); + #region Search - review.Stars = stars; - review.ReviewAuthorId = authorId; - review.ReviewedMovieId = movieId; - review.DateModified = this.timeProvider.GetUtcNow().UtcDateTime; + private const string EscapeCharacter = "\\"; - _ = this.context.Update(review); - _ = await this.context.SaveChangesAsync(cancellationToken); - } - catch (Exception) - { - return false; - } + /// + /// Builds a LIKE pattern that matches any text containing the search term. LIKE ignores case for + /// ASCII text in SQLite and SQL Server, and the term's own wildcards are escaped so they match literally. + /// + private static string ContainsPattern(string query) + { + var term = query.Trim() + .Replace(EscapeCharacter, EscapeCharacter + EscapeCharacter, StringComparison.Ordinal) + .Replace("%", EscapeCharacter + "%", StringComparison.Ordinal) + .Replace("_", EscapeCharacter + "_", StringComparison.Ordinal); - return true; + return $"%{term}%"; } - #endregion Reviews + #endregion Search } diff --git a/src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs b/src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs index f1333df..6aef8c3 100644 --- a/src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs +++ b/src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs @@ -6,34 +6,46 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Extens internal static class MovieReviewsDbContextExtensions { + // A fixed seed and reference date give the same sample data on every run. + private const int Seed = 20211014; + private static readonly DateTime ReferenceDate = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + public static MovieReviewsDbContext AddData(this MovieReviewsDbContext context) { + if (context.Authors.Any()) + { + return context; + } + var authors = new Faker() - .RuleFor(a => a.Id, _ => Guid.NewGuid()) + .UseSeed(Seed) + .RuleFor(a => a.Id, f => f.Random.Guid()) .RuleFor(a => a.FirstName, f => f.Person.FirstName) .RuleFor(a => a.LastName, f => f.Person.LastName) - .RuleFor(a => a.DateCreated, f => f.Date.Past()) - .RuleFor(a => a.DateModified, f => f.Date.Past()) + .RuleFor(a => a.DateCreated, f => f.Date.Past(refDate: ReferenceDate)) + .RuleFor(a => a.DateModified, f => f.Date.Past(refDate: ReferenceDate)) .Generate(15); context.AddRange(authors); var movies = new Faker() - .RuleFor(m => m.Id, _ => Guid.NewGuid()) + .UseSeed(Seed) + .RuleFor(m => m.Id, f => f.Random.Guid()) .RuleFor(m => m.Title, f => f.Company.CatchPhrase()) - .RuleFor(m => m.DateCreated, f => f.Date.Past()) - .RuleFor(m => m.DateModified, f => f.Date.Past()) + .RuleFor(m => m.DateCreated, f => f.Date.Past(refDate: ReferenceDate)) + .RuleFor(m => m.DateModified, f => f.Date.Past(refDate: ReferenceDate)) .Generate(50); context.AddRange(movies); var reviews = new Faker() - .RuleFor(r => r.Id, _ => Guid.NewGuid()) + .UseSeed(Seed) + .RuleFor(r => r.Id, f => f.Random.Guid()) .RuleFor(r => r.ReviewedMovieId, f => f.PickRandom(movies).Id) .RuleFor(r => r.ReviewAuthorId, f => f.PickRandom(authors).Id) .RuleFor(r => r.Stars, f => f.Random.Number(1, 5)) - .RuleFor(r => r.DateCreated, f => f.Date.Past()) - .RuleFor(r => r.DateModified, f => f.Date.Past()) + .RuleFor(r => r.DateCreated, f => f.Date.Past(refDate: ReferenceDate)) + .RuleFor(r => r.DateModified, f => f.Date.Past(refDate: ReferenceDate)) .Generate(150); context.AddRange(reviews); diff --git a/src/Infrastructure/Databases/MovieReviews/Mapping/MovieReviewsMapper.cs b/src/Infrastructure/Databases/MovieReviews/Mapping/MovieReviewsMapper.cs index f5dfcd2..da1f566 100644 --- a/src/Infrastructure/Databases/MovieReviews/Mapping/MovieReviewsMapper.cs +++ b/src/Infrastructure/Databases/MovieReviews/Mapping/MovieReviewsMapper.cs @@ -2,10 +2,10 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Mappin using Riok.Mapperly.Abstractions; using AppAuthor = Application.Authors.Entities.Author; -using AppReviewAuthor = Application.Authors.Entities.ReviewAuthor; using AppMovie = Application.Movies.Entities.Movie; -using AppReviewedMovie = Application.Movies.Entities.ReviewedMovie; using AppReview = Application.Reviews.Entities.Review; +using AppReviewAuthor = Application.Authors.Entities.ReviewAuthor; +using AppReviewedMovie = Application.Movies.Entities.ReviewedMovie; using InfraAuthor = Models.Author; using InfraMovie = Models.Movie; using InfraReview = Models.Review; @@ -15,6 +15,8 @@ internal partial class MovieReviewsMapper { // Infrastructure → Domain + [MapperIgnoreSource(nameof(InfraAuthor.DateCreated))] + [MapperIgnoreSource(nameof(InfraAuthor.DateModified))] public partial AppAuthor ToDomain(InfraAuthor author); [MapperIgnoreSource(nameof(InfraAuthor.Reviews))] @@ -22,6 +24,8 @@ internal partial class MovieReviewsMapper [MapperIgnoreSource(nameof(InfraAuthor.DateModified))] public partial AppReviewAuthor ToReviewAuthor(InfraAuthor author); + [MapperIgnoreSource(nameof(InfraMovie.DateCreated))] + [MapperIgnoreSource(nameof(InfraMovie.DateModified))] public partial AppMovie ToDomain(InfraMovie movie); [MapperIgnoreSource(nameof(InfraMovie.Reviews))] diff --git a/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.Designer.cs b/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.Designer.cs new file mode 100644 index 0000000..daa9732 --- /dev/null +++ b/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.Designer.cs @@ -0,0 +1,130 @@ +// +using System; +using CleanModelContextProtocol.Infrastructure.Databases.MovieReviews; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Migrations +{ + [DbContext(typeof(MovieReviewsDbContext))] + [Migration("20261028000000_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.14"); + + modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("DateCreated") + .HasColumnType("TEXT"); + + b.Property("DateModified") + .HasColumnType("TEXT"); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Authors"); + }); + + modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("DateCreated") + .HasColumnType("TEXT"); + + b.Property("DateModified") + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Movies"); + }); + + modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Review", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("DateCreated") + .HasColumnType("TEXT"); + + b.Property("DateModified") + .HasColumnType("TEXT"); + + b.Property("ReviewAuthorId") + .HasColumnType("TEXT"); + + b.Property("ReviewedMovieId") + .HasColumnType("TEXT"); + + b.Property("Stars") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("ReviewAuthorId"); + + b.HasIndex("ReviewedMovieId"); + + b.ToTable("Reviews"); + }); + + modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Review", b => + { + b.HasOne("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", "ReviewAuthor") + .WithMany("Reviews") + .HasForeignKey("ReviewAuthorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", "ReviewedMovie") + .WithMany("Reviews") + .HasForeignKey("ReviewedMovieId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ReviewAuthor"); + + b.Navigation("ReviewedMovie"); + }); + + modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", b => + { + b.Navigation("Reviews"); + }); + + modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", b => + { + b.Navigation("Reviews"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.cs b/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.cs new file mode 100644 index 0000000..3356e0d --- /dev/null +++ b/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.cs @@ -0,0 +1,96 @@ +// +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Migrations +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Authors", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + FirstName = table.Column(type: "TEXT", nullable: false), + LastName = table.Column(type: "TEXT", nullable: false), + DateCreated = table.Column(type: "TEXT", nullable: false), + DateModified = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Authors", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Movies", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Title = table.Column(type: "TEXT", nullable: false), + DateCreated = table.Column(type: "TEXT", nullable: false), + DateModified = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Movies", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Reviews", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Stars = table.Column(type: "INTEGER", nullable: false), + ReviewedMovieId = table.Column(type: "TEXT", nullable: false), + ReviewAuthorId = table.Column(type: "TEXT", nullable: false), + DateCreated = table.Column(type: "TEXT", nullable: false), + DateModified = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Reviews", x => x.Id); + table.ForeignKey( + name: "FK_Reviews_Authors_ReviewAuthorId", + column: x => x.ReviewAuthorId, + principalTable: "Authors", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Reviews_Movies_ReviewedMovieId", + column: x => x.ReviewedMovieId, + principalTable: "Movies", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Reviews_ReviewAuthorId", + table: "Reviews", + column: "ReviewAuthorId"); + + migrationBuilder.CreateIndex( + name: "IX_Reviews_ReviewedMovieId", + table: "Reviews", + column: "ReviewedMovieId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Reviews"); + + migrationBuilder.DropTable( + name: "Authors"); + + migrationBuilder.DropTable( + name: "Movies"); + } + } +} diff --git a/src/Infrastructure/Databases/MovieReviews/Migrations/MovieReviewsDbContextModelSnapshot.cs b/src/Infrastructure/Databases/MovieReviews/Migrations/MovieReviewsDbContextModelSnapshot.cs new file mode 100644 index 0000000..3552e71 --- /dev/null +++ b/src/Infrastructure/Databases/MovieReviews/Migrations/MovieReviewsDbContextModelSnapshot.cs @@ -0,0 +1,127 @@ +// +using System; +using CleanModelContextProtocol.Infrastructure.Databases.MovieReviews; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Migrations +{ + [DbContext(typeof(MovieReviewsDbContext))] + partial class MovieReviewsDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.14"); + + modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("DateCreated") + .HasColumnType("TEXT"); + + b.Property("DateModified") + .HasColumnType("TEXT"); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Authors"); + }); + + modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("DateCreated") + .HasColumnType("TEXT"); + + b.Property("DateModified") + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Movies"); + }); + + modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Review", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("DateCreated") + .HasColumnType("TEXT"); + + b.Property("DateModified") + .HasColumnType("TEXT"); + + b.Property("ReviewAuthorId") + .HasColumnType("TEXT"); + + b.Property("ReviewedMovieId") + .HasColumnType("TEXT"); + + b.Property("Stars") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("ReviewAuthorId"); + + b.HasIndex("ReviewedMovieId"); + + b.ToTable("Reviews"); + }); + + modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Review", b => + { + b.HasOne("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", "ReviewAuthor") + .WithMany("Reviews") + .HasForeignKey("ReviewAuthorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", "ReviewedMovie") + .WithMany("Reviews") + .HasForeignKey("ReviewedMovieId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ReviewAuthor"); + + b.Navigation("ReviewedMovie"); + }); + + modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", b => + { + b.Navigation("Reviews"); + }); + + modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", b => + { + b.Navigation("Reviews"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Infrastructure/Databases/MovieReviews/Models/Author.cs b/src/Infrastructure/Databases/MovieReviews/Models/Author.cs index f1dda04..8d8ef9d 100644 --- a/src/Infrastructure/Databases/MovieReviews/Models/Author.cs +++ b/src/Infrastructure/Databases/MovieReviews/Models/Author.cs @@ -5,9 +5,9 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models [ExcludeFromCodeCoverage] internal record Author : Entity { - public string FirstName { get; init; } + public required string FirstName { get; init; } - public string LastName { get; init; } + public required string LastName { get; init; } - public ICollection Reviews { get; init; } + public ICollection Reviews { get; init; } = []; } diff --git a/src/Infrastructure/Databases/MovieReviews/Models/Movie.cs b/src/Infrastructure/Databases/MovieReviews/Models/Movie.cs index fdd298c..0daf229 100644 --- a/src/Infrastructure/Databases/MovieReviews/Models/Movie.cs +++ b/src/Infrastructure/Databases/MovieReviews/Models/Movie.cs @@ -5,7 +5,7 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models [ExcludeFromCodeCoverage] internal record Movie : Entity { - public string Title { get; init; } + public required string Title { get; init; } - public ICollection Reviews { get; init; } + public ICollection Reviews { get; init; } = []; } diff --git a/src/Infrastructure/Databases/MovieReviews/Models/Review.cs b/src/Infrastructure/Databases/MovieReviews/Models/Review.cs index 6e415a5..9aa944f 100644 --- a/src/Infrastructure/Databases/MovieReviews/Models/Review.cs +++ b/src/Infrastructure/Databases/MovieReviews/Models/Review.cs @@ -11,10 +11,10 @@ internal record Review : Entity [ForeignKey("ReviewedMovie")] public Guid ReviewedMovieId { get; set; } - public Movie ReviewedMovie { get; init; } + public Movie ReviewedMovie { get; init; } = null!; [ForeignKey("ReviewAuthor")] public Guid ReviewAuthorId { get; set; } - public Author ReviewAuthor { get; init; } + public Author ReviewAuthor { get; init; } = null!; } diff --git a/src/Infrastructure/Databases/MovieReviews/MovieReviewsDatabase.cs b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDatabase.cs new file mode 100644 index 0000000..14f6ba4 --- /dev/null +++ b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDatabase.cs @@ -0,0 +1,34 @@ +namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews; + +using Microsoft.Data.Sqlite; + +/// +/// The connection details of the movie reviews database. +/// +/// +/// A shared in-memory SQLite database, such as Data Source=Movies;Mode=Memory;Cache=Shared, only lives while a +/// connection to it is open, so this keeps one open for as long as the application runs. +/// +internal sealed class MovieReviewsDatabase(string connectionString) : IDisposable +{ + private SqliteConnection? keepAlive; + + public string ConnectionString { get; } = connectionString; + + public bool IsInMemory => new SqliteConnectionStringBuilder(this.ConnectionString).Mode == SqliteOpenMode.Memory; + + public void KeepAlive() + { + if (this.IsInMemory && this.keepAlive is null) + { + this.keepAlive = new SqliteConnection(this.ConnectionString); + this.keepAlive.Open(); + } + } + + public void Dispose() + { + this.keepAlive?.Dispose(); + this.keepAlive = null; + } +} diff --git a/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContext.cs b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContext.cs index 4e2d69c..24cce2e 100644 --- a/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContext.cs +++ b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContext.cs @@ -6,9 +6,9 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews; internal class MovieReviewsDbContext(DbContextOptions options) : DbContext(options) { - public DbSet Authors { get; set; } - public DbSet Movies { get; set; } - public DbSet Reviews { get; set; } + public DbSet Authors => this.Set(); + public DbSet Movies => this.Set(); + public DbSet Reviews => this.Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContextFactory.cs b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContextFactory.cs new file mode 100644 index 0000000..c8a8f47 --- /dev/null +++ b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContextFactory.cs @@ -0,0 +1,22 @@ +namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews; + +using System.Diagnostics.CodeAnalysis; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +/// +/// Lets the EF Core tools create the context, for example to add a migration: +/// dotnet ef migrations add Name --project src/Infrastructure --output-dir Databases/MovieReviews/Migrations. +/// +[ExcludeFromCodeCoverage] +internal class MovieReviewsDbContextFactory : IDesignTimeDbContextFactory +{ + public MovieReviewsDbContext CreateDbContext(string[] args) + { + var options = new DbContextOptionsBuilder() + .UseSqlite(DependencyInjection.DefaultConnectionString) + .Options; + + return new MovieReviewsDbContext(options); + } +} diff --git a/src/Infrastructure/DependencyInjection.cs b/src/Infrastructure/DependencyInjection.cs index 211ee9b..851d917 100644 --- a/src/Infrastructure/DependencyInjection.cs +++ b/src/Infrastructure/DependencyInjection.cs @@ -5,29 +5,72 @@ namespace CleanModelContextProtocol.Infrastructure; using Application.Movies; using Application.Reviews; using Databases.MovieReviews; +using Databases.MovieReviews.Extensions; using Databases.MovieReviews.Mapping; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; public static class DependencyInjection { - public static IServiceCollection AddInfrastructure(this IServiceCollection services) + /// The connection string used when none is configured. + public const string DefaultConnectionString = "Data Source=movie-reviews.db"; + + public static IServiceCollection AddInfrastructure(this IServiceCollection services, string? connectionString = null) { - _ = services.AddDbContext(options => - options.UseInMemoryDatabase($"Movies-{Guid.NewGuid()}"), ServiceLifetime.Singleton); + var database = new MovieReviewsDatabase(string.IsNullOrWhiteSpace(connectionString) ? DefaultConnectionString : connectionString); + + _ = services.AddSingleton(database); + _ = services.AddDbContext(options => options.UseSqlite(database.ConnectionString)); _ = services.AddSingleton(); - _ = services.AddSingleton(); + _ = services.AddScoped(); - _ = services.AddSingleton(p => + _ = services.AddScoped(p => p.GetRequiredService()); - _ = services.AddSingleton(x => + _ = services.AddScoped(x => x.GetRequiredService()); - _ = services.AddSingleton(x => + _ = services.AddScoped(x => x.GetRequiredService()); _ = services.AddSingleton(TimeProvider.System); return services; } + + /// + /// Adds a readiness check that the movie reviews database can be reached. + /// + /// The health checks builder. + /// The tags to give the check, so endpoints can choose which checks they run. + public static IHealthChecksBuilder AddInfrastructureHealthChecks(this IHealthChecksBuilder builder, params string[] tags) + { + return builder.AddDbContextCheck("MovieReviewsDatabase", HealthStatus.Unhealthy, tags); + } + + /// + /// Creates or upgrades the database with the migrations. Call it once at startup, before the first request. + /// + /// The application's services. + /// + /// Adds the sample authors, movies and reviews when the database is empty. Turn it on for local runs and demos, + /// and leave it off anywhere real data lives. + /// + public static IServiceProvider InitialiseInfrastructure(this IServiceProvider services, bool seedSampleData) + { + services.GetRequiredService().KeepAlive(); + + using var scope = services.CreateScope(); + + var context = scope.ServiceProvider.GetRequiredService(); + + context.Database.Migrate(); + + if (seedSampleData) + { + _ = context.AddData(); + } + + return services; + } } diff --git a/src/Infrastructure/Infrastructure.csproj b/src/Infrastructure/Infrastructure.csproj index ada2a82..6855f1e 100644 --- a/src/Infrastructure/Infrastructure.csproj +++ b/src/Infrastructure/Infrastructure.csproj @@ -5,9 +5,14 @@ - - - + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + diff --git a/src/Presentation/Authentication/AuthenticationSettings.cs b/src/Presentation/Authentication/AuthenticationSettings.cs index e3eecd7..426fdb6 100644 --- a/src/Presentation/Authentication/AuthenticationSettings.cs +++ b/src/Presentation/Authentication/AuthenticationSettings.cs @@ -10,10 +10,10 @@ public class AuthenticationSettings public const string SectionName = "Authentication"; /// The OAuth authorization server that issues access tokens, such as https://login.example.com. - public string Authority { get; init; } + public string? Authority { get; init; } /// The audience access tokens must be issued for. This is usually the server's own URL. - public string Audience { get; init; } + public string? Audience { get; init; } /// The scopes clients should ask for, published in the protected resource metadata. public List Scopes { get; init; } = []; diff --git a/src/Presentation/Completions/CompletionHandler.cs b/src/Presentation/Completions/CompletionHandler.cs index 7d690ec..0bd0ec0 100644 --- a/src/Presentation/Completions/CompletionHandler.cs +++ b/src/Presentation/Completions/CompletionHandler.cs @@ -17,10 +17,10 @@ public static class CompletionHandler public static async ValueTask Handle(RequestContext context, CancellationToken cancellationToken) { - return await Complete(context.Services.GetRequiredService(), context.Params, cancellationToken); + return await Complete(context.Services!.GetRequiredService(), context.Params, cancellationToken); } - public static async Task Complete(ISender sender, CompleteRequestParams request, CancellationToken cancellationToken) + public static async Task Complete(ISender sender, CompleteRequestParams? request, CancellationToken cancellationToken) { var argument = request?.Argument; @@ -33,7 +33,7 @@ public static async Task Complete(ISender sender, CompleteReques { case "movieTitle" or "firstMovieTitle" or "secondMovieTitle": { - var page = await sender.Send(new MovieQueries.SearchMovies.SearchMoviesQuery + var page = await sender.Send(new MovieQueries.GetMovies.GetMoviesQuery { Query = argument.Value, Limit = Paging.MaxLimit @@ -44,7 +44,7 @@ public static async Task Complete(ISender sender, CompleteReques case "authorName": { - var page = await sender.Send(new AuthorQueries.SearchAuthors.SearchAuthorsQuery + var page = await sender.Send(new AuthorQueries.GetAuthors.GetAuthorsQuery { Query = argument.Value, Limit = Paging.MaxLimit diff --git a/src/Presentation/Errors/ProtocolErrorFilter.cs b/src/Presentation/Errors/ProtocolErrorFilter.cs index 98b6ebd..f5675b7 100644 --- a/src/Presentation/Errors/ProtocolErrorFilter.cs +++ b/src/Presentation/Errors/ProtocolErrorFilter.cs @@ -25,7 +25,7 @@ public static McpRequestHandler Filter(McpRe }; } - public static McpProtocolException ToProtocolException(Exception exception) + public static McpProtocolException? ToProtocolException(Exception exception) { return exception switch { diff --git a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs index f745d2c..796acb2 100644 --- a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs @@ -36,8 +36,9 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat #region Project Dependencies _ = builder.Services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped); - _ = builder.Services.AddInfrastructure(); + _ = builder.Services.AddInfrastructure(builder.Configuration.GetConnectionString("MovieReviews")); _ = builder.Services.AddApplication(); + _ = builder.Services.AddHealthChecks().AddInfrastructureHealthChecks("ready"); #endregion Project Dependencies @@ -62,7 +63,7 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat .AddMcp(options => options.ResourceMetadata = new() { Resource = authentication.Audience, - AuthorizationServers = [authentication.Authority], + AuthorizationServers = [authentication.Authority!], ScopesSupported = authentication.Scopes, ResourceName = "Clean Model Context Protocol" }); @@ -97,8 +98,8 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat A review links one author to one movie with a star rating from 1 (worst) to 5 (best). Find things by name first: movies_search and authors_search return ids, review counts and average stars, and reviews_list filters reviews by movie or author. Every search returns one page at a time, - so pass nextCursor back to continue rather than raising the limit. - reviews_write creates a review, or replaces one when you pass its reviewId. + so pass nextOffset back as the offset to continue rather than raising the limit. + reviews_write creates a review, or changes the stars of one when you pass its reviewId. A review's movie and author can't change. reviews_delete can't be undone, so confirm with the user before calling it. Each movie, author and review can also be read as a resource at movies://{id}, authors://{id} or reviews://{id}, and server://version gives this server's version. diff --git a/src/Presentation/Extensions/WebApplicationExtensions.cs b/src/Presentation/Extensions/WebApplicationExtensions.cs index 0fe8b1f..589bd2e 100644 --- a/src/Presentation/Extensions/WebApplicationExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationExtensions.cs @@ -2,7 +2,11 @@ namespace CleanModelContextProtocol.Presentation.Extensions; using System.Diagnostics.CodeAnalysis; using CleanModelContextProtocol.Presentation.Authentication; +using Infrastructure; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Serilog; [ExcludeFromCodeCoverage] @@ -10,12 +14,39 @@ public static class WebApplicationExtensions { public static WebApplication ConfigureApplication(this WebApplication app) { + #region Database + + _ = app.Services.InitialiseInfrastructure(app.Configuration.GetValue("Database:SeedSampleData")); + + #endregion Database + + #region Security + + // HSTS tells browsers to only use HTTPS from then on, so it's left off for local runs. + if (!app.Environment.IsDevelopment() && !app.Environment.IsEnvironment("local")) + { + _ = app.UseHsts(); + } + + _ = app.UseHttpsRedirection(); + + #endregion Security + #region Logging _ = app.UseSerilogRequestLogging(); #endregion Logging + #region Health + + // Liveness runs no checks, so it only fails when the process can't answer. Readiness checks the database. + // They aren't behind authorization, so they answer without a token. + _ = app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false }); + _ = app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = check => check.Tags.Contains("ready") }); + + #endregion Health + #region Model Context Protocol var mcp = app.MapMcp("/mcp"); diff --git a/src/Presentation/Models/AuthorResult.cs b/src/Presentation/Models/AuthorResult.cs index b675d1c..f940891 100644 --- a/src/Presentation/Models/AuthorResult.cs +++ b/src/Presentation/Models/AuthorResult.cs @@ -15,4 +15,4 @@ public record AuthorResult( [property: Description("The author's full name.")] string Name, [property: Description("How many reviews the author has written.")] int ReviewCount, [property: Description("The average star rating the author gives, from 1 to 5, or null when they have no reviews.")] double? AverageStars, - [property: Description("Every review the author has written, when they were asked for.")] List Reviews = null); + [property: Description("Every review the author has written, when they were asked for.")] List? Reviews = null); diff --git a/src/Presentation/Models/MovieResult.cs b/src/Presentation/Models/MovieResult.cs index c857ba1..59f4dfb 100644 --- a/src/Presentation/Models/MovieResult.cs +++ b/src/Presentation/Models/MovieResult.cs @@ -15,4 +15,4 @@ public record MovieResult( [property: Description("The movie's title.")] string Title, [property: Description("How many reviews the movie has.")] int ReviewCount, [property: Description("The average star rating, from 1 to 5, or null when there are no reviews.")] double? AverageStars, - [property: Description("Every review of the movie, when they were asked for.")] List Reviews = null); + [property: Description("Every review of the movie, when they were asked for.")] List? Reviews = null); diff --git a/src/Presentation/Models/ResultMapper.cs b/src/Presentation/Models/ResultMapper.cs index cd7c3dd..0a01620 100644 --- a/src/Presentation/Models/ResultMapper.cs +++ b/src/Presentation/Models/ResultMapper.cs @@ -12,7 +12,7 @@ public static class ResultMapper { public static MovieResult ToResult(this Movie movie, bool includeReviews) { - var reviews = movie.Reviews ?? []; + var reviews = movie.Reviews; return new MovieResult( movie.Id, @@ -22,9 +22,19 @@ public static MovieResult ToResult(this Movie movie, bool includeReviews) includeReviews ? [.. reviews.Select(r => r.ToResult(movie: new ReviewedMovie(movie.Id, movie.Title)))] : null); } + public static MovieResult ToResult(this MovieSummary movie, IEnumerable? reviews = null) + { + return new MovieResult( + movie.Id, + movie.Title, + movie.ReviewCount, + movie.AverageStars, + reviews is null ? null : [.. reviews.Select(r => r.ToResult(movie: new ReviewedMovie(movie.Id, movie.Title)))]); + } + public static AuthorResult ToResult(this Author author, bool includeReviews) { - var reviews = author.Reviews ?? []; + var reviews = author.Reviews; return new AuthorResult( author.Id, @@ -34,7 +44,17 @@ public static AuthorResult ToResult(this Author author, bool includeReviews) includeReviews ? [.. reviews.Select(r => r.ToResult(author: new ReviewAuthor(author.Id, author.FirstName, author.LastName)))] : null); } - public static ReviewResult ToResult(this Review review, ReviewedMovie movie = null, ReviewAuthor author = null) + public static AuthorResult ToResult(this AuthorSummary author, IEnumerable? reviews = null) + { + return new AuthorResult( + author.Id, + FullName(author.FirstName, author.LastName), + author.ReviewCount, + author.AverageStars, + reviews is null ? null : [.. reviews.Select(r => r.ToResult(author: new ReviewAuthor(author.Id, author.FirstName, author.LastName)))]); + } + + public static ReviewResult ToResult(this Review review, ReviewedMovie? movie = null, ReviewAuthor? author = null) { movie = review.ReviewedMovie ?? movie; author = review.ReviewAuthor ?? author; @@ -50,7 +70,9 @@ public static ReviewResult ToResult(this Review review, ReviewedMovie movie = nu public static ResultPage ToResult(this Page page, Func map) { - return new ResultPage([.. page.Items.Select(map)], page.TotalCount, page.NextCursor); + var nextOffset = page.Offset + page.Items.Count; + + return new ResultPage([.. page.Items.Select(map)], page.TotalCount, nextOffset < page.TotalCount ? nextOffset : null); } private static string FullName(string firstName, string lastName) @@ -60,6 +82,6 @@ private static string FullName(string firstName, string lastName) private static double? Average(ICollection reviews) { - return reviews.Count == 0 ? null : Math.Round(reviews.Average(r => r.Stars), 1); + return reviews.Count == 0 ? null : Math.Round(reviews.Average(r => r.Stars), 1, MidpointRounding.AwayFromZero); } } diff --git a/src/Presentation/Models/ResultPage.cs b/src/Presentation/Models/ResultPage.cs index 1fddd91..5d09266 100644 --- a/src/Presentation/Models/ResultPage.cs +++ b/src/Presentation/Models/ResultPage.cs @@ -3,13 +3,13 @@ namespace CleanModelContextProtocol.Presentation.Models; using System.ComponentModel; /// -/// One page of results from a search tool. +/// One page of results from a list or search tool. /// /// The type of the results. /// The results on this page. /// The number of results across every page. -/// Pass this as the cursor to get the next page. Null when this is the last page. +/// Pass this as the offset to get the next page. Null when this is the last page. public record ResultPage( [property: Description("The results on this page.")] List Items, [property: Description("The number of results across every page.")] int TotalCount, - [property: Description("Pass this as the cursor to get the next page. Null when this is the last page.")] string NextCursor); + [property: Description("Pass this as the offset to get the next page. Null when this is the last page.")] int? NextOffset); diff --git a/src/Presentation/Models/ReviewResult.cs b/src/Presentation/Models/ReviewResult.cs index 8864490..9f89c8c 100644 --- a/src/Presentation/Models/ReviewResult.cs +++ b/src/Presentation/Models/ReviewResult.cs @@ -15,6 +15,6 @@ public record ReviewResult( [property: Description("The review's id.")] Guid Id, [property: Description("The star rating, from 1 (worst) to 5 (best).")] int Stars, [property: Description("The id of the movie that was reviewed.")] Guid? MovieId, - [property: Description("The title of the movie that was reviewed.")] string MovieTitle, + [property: Description("The title of the movie that was reviewed.")] string? MovieTitle, [property: Description("The id of the author who wrote the review.")] Guid? AuthorId, - [property: Description("The full name of the author who wrote the review.")] string AuthorName); + [property: Description("The full name of the author who wrote the review.")] string? AuthorName); diff --git a/src/Presentation/Presentation.csproj b/src/Presentation/Presentation.csproj index 757d109..15d27f1 100644 --- a/src/Presentation/Presentation.csproj +++ b/src/Presentation/Presentation.csproj @@ -7,23 +7,21 @@ true true - true Linux - $(NoWarn);1591 - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - + + + + + + + diff --git a/src/Presentation/Prompts/MoviePrompts.cs b/src/Presentation/Prompts/MoviePrompts.cs index 9a3864f..63c9647 100644 --- a/src/Presentation/Prompts/MoviePrompts.cs +++ b/src/Presentation/Prompts/MoviePrompts.cs @@ -15,9 +15,10 @@ public static class MoviePrompts [Description("Summarise how reviewers have received a movie: its average stars, how the ratings spread, and who liked it most and least.")] public static async Task SummariseMovieReception( ISender sender, - [Description("The movie's title, or part of it.")] string movieTitle) + [Description("The movie's title, or part of it.")] string movieTitle, + CancellationToken cancellationToken) { - var movie = await FindMovie(sender, movieTitle); + var movie = await FindMovie(sender, movieTitle, cancellationToken); var messages = new List { @@ -45,10 +46,11 @@ public static async Task SummariseMovieReception( public static async Task CompareMovies( ISender sender, [Description("The first movie's title, or part of it.")] string firstMovieTitle, - [Description("The second movie's title, or part of it.")] string secondMovieTitle) + [Description("The second movie's title, or part of it.")] string secondMovieTitle, + CancellationToken cancellationToken) { - var first = await FindMovie(sender, firstMovieTitle); - var second = await FindMovie(sender, secondMovieTitle); + var first = await FindMovie(sender, firstMovieTitle, cancellationToken); + var second = await FindMovie(sender, secondMovieTitle, cancellationToken); var messages = new List { @@ -88,18 +90,26 @@ public static GetPromptResult ReviewMovie( }; } - private static async Task FindMovie(ISender sender, string title) + private static async Task FindMovie(ISender sender, string? title, CancellationToken cancellationToken) { - var page = await sender.Send(new Queries.SearchMovies.SearchMoviesQuery + var page = await sender.Send(new Queries.GetMovies.GetMoviesQuery { Query = title, Limit = 5 - }); + }, cancellationToken); var movie = page.Items.FirstOrDefault(m => string.Equals(m.Title, title?.Trim(), StringComparison.OrdinalIgnoreCase)) ?? (page.TotalCount == 1 ? page.Items[0] : null); - return movie?.ToResult(includeReviews: true); + if (movie is null) + { + return null; + } + + // The search only has the review count and average, so get the movie again for its reviews. + var withReviews = await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery { Id = movie.Id }, cancellationToken); + + return withReviews.ToResult(includeReviews: true); } private static PromptMessage Text(string text) diff --git a/src/Presentation/Resources/AuthorResources.cs b/src/Presentation/Resources/AuthorResources.cs index 6cca893..45a9f5d 100644 --- a/src/Presentation/Resources/AuthorResources.cs +++ b/src/Presentation/Resources/AuthorResources.cs @@ -14,12 +14,13 @@ public static class AuthorResources [Description("An author with their review count, average stars and every review they have written, including each movie's title.")] public static async Task GetAuthor( ISender sender, - [Description("The author's id (a GUID).")] Guid authorId) + [Description("The author's id (a GUID).")] Guid authorId, + CancellationToken cancellationToken) { var author = await sender.Send(new Queries.GetAuthorById.GetAuthorByIdQuery { Id = authorId - }); + }, cancellationToken); return McpSerializer.Serialize(author.ToResult(includeReviews: true)); } diff --git a/src/Presentation/Resources/MovieResources.cs b/src/Presentation/Resources/MovieResources.cs index d4887cf..1e843c2 100644 --- a/src/Presentation/Resources/MovieResources.cs +++ b/src/Presentation/Resources/MovieResources.cs @@ -14,12 +14,13 @@ public static class MovieResources [Description("A movie with its review count, average stars and every review, including each author's name.")] public static async Task GetMovie( ISender sender, - [Description("The movie's id (a GUID).")] Guid movieId) + [Description("The movie's id (a GUID).")] Guid movieId, + CancellationToken cancellationToken) { var movie = await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery { Id = movieId - }); + }, cancellationToken); return McpSerializer.Serialize(movie.ToResult(includeReviews: true)); } diff --git a/src/Presentation/Resources/ReviewResources.cs b/src/Presentation/Resources/ReviewResources.cs index aa14e9c..4ce2055 100644 --- a/src/Presentation/Resources/ReviewResources.cs +++ b/src/Presentation/Resources/ReviewResources.cs @@ -14,12 +14,13 @@ public static class ReviewResources [Description("A review with its star rating, the movie's title and the author's name.")] public static async Task GetReview( ISender sender, - [Description("The review's id (a GUID).")] Guid reviewId) + [Description("The review's id (a GUID).")] Guid reviewId, + CancellationToken cancellationToken) { var review = await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery { Id = reviewId - }); + }, cancellationToken); return McpSerializer.Serialize(review.ToResult()); } diff --git a/src/Presentation/Resources/VersionResources.cs b/src/Presentation/Resources/VersionResources.cs index 37fb428..6dcf6fd 100644 --- a/src/Presentation/Resources/VersionResources.cs +++ b/src/Presentation/Resources/VersionResources.cs @@ -11,8 +11,8 @@ public static class VersionResources { [McpServerResource(UriTemplate = "server://version", Name = "server_version", Title = "Server version", MimeType = "application/json")] [Description("The version of this server: the file version and the informational version, which includes the commit it was built from.")] - public static async Task GetVersion(ISender sender) + public static async Task GetVersion(ISender sender, CancellationToken cancellationToken) { - return McpSerializer.Serialize(await sender.Send(new Queries.GetVersion.GetVersionQuery())); + return McpSerializer.Serialize(await sender.Send(new Queries.GetVersion.GetVersionQuery(), cancellationToken)); } } diff --git a/src/Presentation/Tools/AuthorTools.cs b/src/Presentation/Tools/AuthorTools.cs index 5865514..2a5debc 100644 --- a/src/Presentation/Tools/AuthorTools.cs +++ b/src/Presentation/Tools/AuthorTools.cs @@ -5,6 +5,7 @@ namespace CleanModelContextProtocol.Presentation.Tools; using Mediator; using ModelContextProtocol.Server; using Queries = Application.Authors.Queries; +using Reviews = Application.Reviews.Queries; [McpServerToolType] public static class AuthorTools @@ -15,18 +16,30 @@ public static class AuthorTools "every author a page at a time. Use this to find an author's id before calling reviews_list or reviews_write.")] public static async Task> SearchAuthors( ISender sender, - [Description("Part of the author's name, such as 'marie' or 'marie hirthe'. Leave empty to list every author.")] string query = null, + CancellationToken cancellationToken, + [Description("Part of the author's name, such as 'marie' or 'marie hirthe'. Leave empty to list every author.")] string? query = null, + [Description("The number of results to skip, 0 for the first page. Pass the nextOffset from a previous call to get the next page.")] int offset = 0, [Description("The most results to return, from 1 to 50.")] int limit = 10, - [Description("The nextCursor from a previous call, to get the next page. Leave empty for the first page.")] string cursor = null, [Description("Also return every review each author has written. Leave false unless you need the individual reviews.")] bool includeReviews = false) { - var page = await sender.Send(new Queries.SearchAuthors.SearchAuthorsQuery + var page = await sender.Send(new Queries.GetAuthors.GetAuthorsQuery { Query = query, - Limit = limit, - Cursor = cursor - }); + Offset = offset, + Limit = limit + }, cancellationToken); - return page.ToResult(a => a.ToResult(includeReviews)); + if (!includeReviews || page.Items.Count == 0) + { + return page.ToResult(a => a.ToResult()); + } + + // One query gets the reviews of the whole page. + var reviews = await sender.Send(new Reviews.GetReviewsForAuthors.GetReviewsForAuthorsQuery + { + AuthorIds = [.. page.Items.Select(a => a.Id)] + }, cancellationToken); + + return page.ToResult(a => a.ToResult(reviews[a.Id])); } } diff --git a/src/Presentation/Tools/MovieTools.cs b/src/Presentation/Tools/MovieTools.cs index fd53d54..a5fe2b9 100644 --- a/src/Presentation/Tools/MovieTools.cs +++ b/src/Presentation/Tools/MovieTools.cs @@ -5,6 +5,7 @@ namespace CleanModelContextProtocol.Presentation.Tools; using Mediator; using ModelContextProtocol.Server; using Queries = Application.Movies.Queries; +using Reviews = Application.Reviews.Queries; [McpServerToolType] public static class MovieTools @@ -15,31 +16,44 @@ public static class MovieTools "Use this to find a movie's id before calling movies_get, reviews_list or reviews_write.")] public static async Task> SearchMovies( ISender sender, - [Description("Words to look for in the title, such as 'matrix'. Leave empty to list every movie.")] string query = null, + CancellationToken cancellationToken, + [Description("Words to look for in the title, such as 'matrix'. Leave empty to list every movie.")] string? query = null, + [Description("The number of results to skip, 0 for the first page. Pass the nextOffset from a previous call to get the next page.")] int offset = 0, [Description("The most results to return, from 1 to 50.")] int limit = 10, - [Description("The nextCursor from a previous call, to get the next page. Leave empty for the first page.")] string cursor = null, [Description("Also return every review of each movie. Leave false unless you need the individual reviews.")] bool includeReviews = false) { - var page = await sender.Send(new Queries.SearchMovies.SearchMoviesQuery + var page = await sender.Send(new Queries.GetMovies.GetMoviesQuery { Query = query, - Limit = limit, - Cursor = cursor - }); + Offset = offset, + Limit = limit + }, cancellationToken); - return page.ToResult(m => m.ToResult(includeReviews)); + if (!includeReviews || page.Items.Count == 0) + { + return page.ToResult(m => m.ToResult()); + } + + // One query gets the reviews of the whole page. + var reviews = await sender.Send(new Reviews.GetReviewsForMovies.GetReviewsForMoviesQuery + { + MovieIds = [.. page.Items.Select(m => m.Id)] + }, cancellationToken); + + return page.ToResult(m => m.ToResult(reviews[m.Id])); } [McpServerTool(Name = "movies_get", Title = "Get movie", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] [Description("Get one movie with its review count, average stars and every review, including each author's name.")] public static async Task GetMovie( ISender sender, - [Description("The movie's id (a GUID). Use movies_search to find it.")] Guid movieId) + [Description("The movie's id (a GUID). Use movies_search to find it.")] Guid movieId, + CancellationToken cancellationToken) { var movie = await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery { Id = movieId - }); + }, cancellationToken); return movie.ToResult(includeReviews: true); } diff --git a/src/Presentation/Tools/ReviewTools.cs b/src/Presentation/Tools/ReviewTools.cs index 6c931b1..5b24f2c 100644 --- a/src/Presentation/Tools/ReviewTools.cs +++ b/src/Presentation/Tools/ReviewTools.cs @@ -15,52 +15,54 @@ public static class ReviewTools "by author or both, or pass a reviewId to get exactly one review. With no filters it pages through every review.")] public static async Task> ListReviews( ISender sender, + CancellationToken cancellationToken, [Description("Only reviews of this movie. Use movies_search to find the id.")] Guid? movieId = null, [Description("Only reviews by this author. Use authors_search to find the id.")] Guid? authorId = null, [Description("Get this one review instead of searching. The other filters are ignored.")] Guid? reviewId = null, - [Description("The most results to return, from 1 to 50.")] int limit = 10, - [Description("The nextCursor from a previous call, to get the next page. Leave empty for the first page.")] string cursor = null) + [Description("The number of results to skip, 0 for the first page. Pass the nextOffset from a previous call to get the next page.")] int offset = 0, + [Description("The most results to return, from 1 to 50.")] int limit = 10) { if (reviewId.HasValue) { var review = await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery { Id = reviewId.Value - }); + }, cancellationToken); return new ResultPage([review.ToResult()], 1, null); } - var page = await sender.Send(new Queries.SearchReviews.SearchReviewsQuery + var page = await sender.Send(new Queries.GetReviews.GetReviewsQuery { MovieId = movieId, AuthorId = authorId, - Limit = limit, - Cursor = cursor - }); + Offset = offset, + Limit = limit + }, cancellationToken); return page.ToResult(r => r.ToResult()); } [McpServerTool(Name = "reviews_write", Title = "Write review", ReadOnly = false, Destructive = true, Idempotent = false, OpenWorld = false, UseStructuredContent = true)] - [Description("Create a review of a movie by an author with a star rating from 1 to 5, or pass a reviewId to replace that " + - "review's movie, author and stars. Returns the saved review. Without a reviewId every call creates another review, " + - "so don't retry a call that succeeded.")] + [Description("Create a review of a movie by an author with a star rating from 1 to 5, or pass a reviewId to change that " + + "review's stars. The movie and author of a review can't change. Returns the saved review. Without a reviewId every " + + "call creates another review, so don't retry a call that succeeded.")] public static async Task WriteReview( ISender sender, - [Description("The id of the movie being reviewed. Use movies_search to find it.")] Guid movieId, - [Description("The id of the author writing the review. Use authors_search to find it.")] Guid authorId, [Description("The star rating, a whole number from 1 (worst) to 5 (best).")] int stars, - [Description("The id of an existing review to replace. Leave empty to create a new review.")] Guid? reviewId = null) + CancellationToken cancellationToken, + [Description("The id of the movie being reviewed, needed to create a review. Use movies_search to find it.")] Guid? movieId = null, + [Description("The id of the author writing the review, needed to create a review. Use authors_search to find it.")] Guid? authorId = null, + [Description("The id of an existing review to change the stars of. Leave empty to create a new review.")] Guid? reviewId = null) { if (!reviewId.HasValue) { var created = await sender.Send(new Commands.CreateReview.CreateReviewCommand { - AuthorId = authorId, - MovieId = movieId, + AuthorId = authorId ?? Guid.Empty, + MovieId = movieId ?? Guid.Empty, Stars = stars - }); + }, cancellationToken); return created.ToResult(); } @@ -68,15 +70,13 @@ public static async Task WriteReview( _ = await sender.Send(new Commands.UpdateReview.UpdateReviewCommand { Id = reviewId.Value, - AuthorId = authorId, - MovieId = movieId, Stars = stars - }); + }, cancellationToken); var updated = await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery { Id = reviewId.Value - }); + }, cancellationToken); return updated.ToResult(); } @@ -85,12 +85,13 @@ public static async Task WriteReview( [Description("Permanently delete a review. This can't be undone, so confirm with the user first.")] public static async Task DeleteReview( ISender sender, - [Description("The id of the review to delete. Use reviews_list to find it.")] Guid reviewId) + [Description("The id of the review to delete. Use reviews_list to find it.")] Guid reviewId, + CancellationToken cancellationToken) { var deleted = await sender.Send(new Commands.DeleteReview.DeleteReviewCommand { Id = reviewId - }); + }, cancellationToken); return new DeletedReview(reviewId, deleted); } diff --git a/src/Presentation/appsettings.docker.json b/src/Presentation/appsettings.docker.json index 0087bf4..96a9391 100644 --- a/src/Presentation/appsettings.docker.json +++ b/src/Presentation/appsettings.docker.json @@ -11,5 +11,11 @@ "Properties": { "ApplicationName": "CleanModelContextProtocol-Docker" } + }, + "ConnectionStrings": { + "MovieReviews": "Data Source=/app/data/movie-reviews.db" + }, + "Database": { + "SeedSampleData": true } -} \ No newline at end of file +} diff --git a/src/Presentation/appsettings.json b/src/Presentation/appsettings.json index 842e129..fd102b5 100644 --- a/src/Presentation/appsettings.json +++ b/src/Presentation/appsettings.json @@ -19,10 +19,16 @@ "Default": "None" } }, + "ConnectionStrings": { + "MovieReviews": "Data Source=movie-reviews.db" + }, "Authentication": { "Authority": "", "Audience": "", "Scopes": [] }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "Database": { + "SeedSampleData": false + } } diff --git a/src/Presentation/appsettings.local.json b/src/Presentation/appsettings.local.json index 8f5db2a..a071bf7 100644 --- a/src/Presentation/appsettings.local.json +++ b/src/Presentation/appsettings.local.json @@ -11,5 +11,8 @@ "Properties": { "ApplicationName": "CleanModelContextProtocol-Local" } + }, + "Database": { + "SeedSampleData": true } -} \ No newline at end of file +} diff --git a/template/template.csproj b/template/template.csproj index 32da234..5f6be92 100644 --- a/template/template.csproj +++ b/template/template.csproj @@ -31,7 +31,7 @@ - + diff --git a/tests/Application.Tests.Unit/Application.Tests.Unit.csproj b/tests/Application.Tests.Unit/Application.Tests.Unit.csproj index 49c2e99..ce4e323 100644 --- a/tests/Application.Tests.Unit/Application.Tests.Unit.csproj +++ b/tests/Application.Tests.Unit/Application.Tests.Unit.csproj @@ -13,15 +13,15 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/tests/Application.Tests.Unit/Authors/Queries/GetAuthorById/GetAuthorByIdHandlerTests.cs b/tests/Application.Tests.Unit/Authors/Queries/GetAuthorById/GetAuthorByIdHandlerTests.cs index a76e098..25d354c 100644 --- a/tests/Application.Tests.Unit/Authors/Queries/GetAuthorById/GetAuthorByIdHandlerTests.cs +++ b/tests/Application.Tests.Unit/Authors/Queries/GetAuthorById/GetAuthorByIdHandlerTests.cs @@ -26,7 +26,7 @@ public async Task Handle_ShouldPassThrough_Query() using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; - _ = context.GetAuthorById(Arg.Any(), token).Returns(new Author(Guid.Empty, "FirstName", "LastName")); + _ = context.GetAuthorById(Arg.Any(), token).Returns(new Author(Guid.Empty, "FirstName", "LastName", [])); // Act var result = await handler.Handle(query, token); @@ -40,7 +40,7 @@ public async Task Handle_ShouldPassThrough_Query() result.Id.ShouldBe(Guid.Empty); result.FirstName.ShouldBe("FirstName"); result.LastName.ShouldBe("LastName"); - result.Reviews.ShouldBeNull(); + result.Reviews.ShouldBeEmpty(); } diff --git a/tests/Application.Tests.Unit/Authors/Queries/GetAuthors/GetAuthorsHandlerTests.cs b/tests/Application.Tests.Unit/Authors/Queries/GetAuthors/GetAuthorsHandlerTests.cs index ead445e..d161ecd 100644 --- a/tests/Application.Tests.Unit/Authors/Queries/GetAuthors/GetAuthorsHandlerTests.cs +++ b/tests/Application.Tests.Unit/Authors/Queries/GetAuthors/GetAuthorsHandlerTests.cs @@ -5,6 +5,7 @@ namespace CleanModelContextProtocol.Application.Tests.Unit.Authors.Queries.GetAu using Application.Authors; using Application.Authors.Entities; using Application.Authors.Queries.GetAuthors; +using Application.Common.Paging; using NSubstitute; using Shouldly; using Xunit; @@ -12,32 +13,53 @@ namespace CleanModelContextProtocol.Application.Tests.Unit.Authors.Queries.GetAu public class GetAuthorsHandlerTests { [Fact] - public async Task Handle_ShouldPassThrough_Query() + public async Task Handle_ShouldReturn_Page() { // Arrange - var query = new GetAuthorsQuery(); + var query = new GetAuthorsQuery { Query = "Lorem", Offset = 20, Limit = 5 }; - var context = Substitute.For(); - var handler = new GetAuthorsHandler(context); + var repository = Substitute.For(); + var handler = new GetAuthorsHandler(repository); using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; - _ = context.GetAuthors(token).Returns([new Author(Guid.Empty, "FirstName", "LastName")]); + _ = repository.GetAuthors("Lorem", 20, 5, token).Returns(([new AuthorSummary(Guid.Empty, "First", "Last", 0, null)], 21)); // Act var result = await handler.Handle(query, token); // Assert - _ = await context.Received(1).GetAuthors(token); + _ = await repository.Received(1).GetAuthors("Lorem", 20, 5, token); _ = result.ShouldNotBeNull(); - _ = result.ShouldBeOfType>(); + result.Items.Count.ShouldBe(1); + result.Items[0].FirstName.ShouldBe("First"); + result.Offset.ShouldBe(20); + result.Limit.ShouldBe(5); + result.TotalCount.ShouldBe(21); + } + + [Fact] + public async Task Handle_ShouldStartAt_FirstPage() + { + // Arrange + var query = new GetAuthorsQuery(); - result.ShouldNotBeEmpty(); - result.Count.ShouldBe(1); + var repository = Substitute.For(); + var handler = new GetAuthorsHandler(repository); + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + _ = repository.GetAuthors(null, 0, Paging.DefaultLimit, token).Returns(([new AuthorSummary(Guid.Empty, "First", "Last", 0, null)], 1)); + + // Act + var result = await handler.Handle(query, token); + + // Assert + _ = await repository.Received(1).GetAuthors(null, 0, Paging.DefaultLimit, token); - result[0].Id.ShouldBe(Guid.Empty); - result[0].FirstName.ShouldBe("FirstName"); - result[0].LastName.ShouldBe("LastName"); + result.Offset.ShouldBe(0); + result.Limit.ShouldBe(Paging.DefaultLimit); + result.TotalCount.ShouldBe(1); } } diff --git a/tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsValidatorTests.cs b/tests/Application.Tests.Unit/Authors/Queries/GetAuthors/GetAuthorsValidatorTests.cs similarity index 55% rename from tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsValidatorTests.cs rename to tests/Application.Tests.Unit/Authors/Queries/GetAuthors/GetAuthorsValidatorTests.cs index af9375d..f97753d 100644 --- a/tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsValidatorTests.cs +++ b/tests/Application.Tests.Unit/Authors/Queries/GetAuthors/GetAuthorsValidatorTests.cs @@ -1,12 +1,12 @@ -namespace CleanModelContextProtocol.Application.Tests.Unit.Authors.Queries.SearchAuthors; +namespace CleanModelContextProtocol.Application.Tests.Unit.Authors.Queries.GetAuthors; -using Application.Authors.Queries.SearchAuthors; +using Application.Authors.Queries.GetAuthors; using FluentValidation.TestHelper; using Xunit; -public class SearchAuthorsValidatorTests +public class GetAuthorsValidatorTests { - private static readonly SearchAuthorsValidator Validator = new(); + private static readonly GetAuthorsValidator Validator = new(); [Theory] [InlineData(0)] @@ -14,7 +14,7 @@ public class SearchAuthorsValidatorTests public void Validator_ShouldHaveValidationErrorFor_Limit(int limit) { // Arrange - var query = new SearchAuthorsQuery { Limit = limit }; + var query = new GetAuthorsQuery { Limit = limit }; // Act var result = Validator.TestValidate(query); @@ -24,23 +24,23 @@ public void Validator_ShouldHaveValidationErrorFor_Limit(int limit) } [Fact] - public void Validator_ShouldHaveValidationErrorFor_Cursor() + public void Validator_ShouldHaveValidationErrorFor_Offset() { // Arrange - var query = new SearchAuthorsQuery { Cursor = "not a cursor" }; + var query = new GetAuthorsQuery { Offset = -1 }; // Act var result = Validator.TestValidate(query); // Assert - _ = result.ShouldHaveValidationErrorFor(query => query.Cursor); + _ = result.ShouldHaveValidationErrorFor(query => query.Offset); } [Fact] public void Validator_ShouldHaveValidationErrorFor_Query() { // Arrange - var query = new SearchAuthorsQuery { Query = new string('a', 101) }; + var query = new GetAuthorsQuery { Query = new string('a', 101) }; // Act var result = Validator.TestValidate(query); @@ -50,12 +50,12 @@ public void Validator_ShouldHaveValidationErrorFor_Query() } [Theory] - [InlineData(null, 1, null)] - [InlineData("Lorem", 50, "b2Zmc2V0OjEw")] - public void Validator_ShouldNotHaveValidationErrors(string search, int limit, string cursor) + [InlineData(null, 0, 1)] + [InlineData("Lorem", 100, 50)] + public void Validator_ShouldNotHaveValidationErrors(string? search, int offset, int limit) { // Arrange - var query = new SearchAuthorsQuery { Query = search, Limit = limit, Cursor = cursor }; + var query = new GetAuthorsQuery { Query = search, Offset = offset, Limit = limit }; // Act var result = Validator.TestValidate(query); diff --git a/tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsHandlerTests.cs b/tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsHandlerTests.cs deleted file mode 100644 index fef0143..0000000 --- a/tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsHandlerTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -namespace CleanModelContextProtocol.Application.Tests.Unit.Authors.Queries.SearchAuthors; - -using System.Threading; -using System.Threading.Tasks; -using Application.Authors; -using Application.Authors.Entities; -using Application.Authors.Queries.SearchAuthors; -using Application.Common.Paging; -using NSubstitute; -using Shouldly; -using Xunit; - -public class SearchAuthorsHandlerTests -{ - [Fact] - public async Task Handle_ShouldPassThrough_Query() - { - // Arrange - var query = new SearchAuthorsQuery { Query = "Lorem", Limit = 1, Cursor = Paging.Encode(2) }; - - var repository = Substitute.For(); - var handler = new SearchAuthorsHandler(repository); - using var tokenSource = new CancellationTokenSource(); - var token = tokenSource.Token; - - _ = repository.SearchAuthors("Lorem", 2, 1, token).Returns(([new Author(Guid.Empty, "First", "Last")], 5)); - - // Act - var result = await handler.Handle(query, token); - - // Assert - _ = await repository.Received(1).SearchAuthors("Lorem", 2, 1, token); - - _ = result.ShouldNotBeNull(); - result.Items.Count.ShouldBe(1); - result.Items[0].FirstName.ShouldBe("First"); - result.TotalCount.ShouldBe(5); - result.NextCursor.ShouldBe(Paging.Encode(3)); - } - - [Fact] - public async Task Handle_ShouldStartAt_FirstPage() - { - // Arrange - var query = new SearchAuthorsQuery(); - - var repository = Substitute.For(); - var handler = new SearchAuthorsHandler(repository); - using var tokenSource = new CancellationTokenSource(); - var token = tokenSource.Token; - - _ = repository.SearchAuthors(null, 0, Paging.DefaultLimit, token).Returns(([new Author(Guid.Empty, "First", "Last")], 1)); - - // Act - var result = await handler.Handle(query, token); - - // Assert - _ = await repository.Received(1).SearchAuthors(null, 0, Paging.DefaultLimit, token); - - result.TotalCount.ShouldBe(1); - result.NextCursor.ShouldBeNull(); - } -} diff --git a/tests/Application.Tests.Unit/Common/Behaviours/ValidationBehaviourTests.cs b/tests/Application.Tests.Unit/Common/Behaviours/ValidationBehaviourTests.cs index c31c1eb..2286ed0 100644 --- a/tests/Application.Tests.Unit/Common/Behaviours/ValidationBehaviourTests.cs +++ b/tests/Application.Tests.Unit/Common/Behaviours/ValidationBehaviourTests.cs @@ -26,7 +26,7 @@ public async Task Handle_ShouldValidate_NoErrors() var token = tokenSource.Token; var next = Substitute.For>(); - _ = next(query, token).Returns(new Author(Guid.Empty, "Test", "Test")); + _ = next(query, token).Returns(new Author(Guid.Empty, "Test", "Test", [])); // Act var result = await handler.Handle(query, next, token); diff --git a/tests/Application.Tests.Unit/Common/Exceptions/NotFoundExceptionTests.cs b/tests/Application.Tests.Unit/Common/Exceptions/NotFoundExceptionTests.cs index f2fb207..04016db 100644 --- a/tests/Application.Tests.Unit/Common/Exceptions/NotFoundExceptionTests.cs +++ b/tests/Application.Tests.Unit/Common/Exceptions/NotFoundExceptionTests.cs @@ -13,7 +13,7 @@ public void ThrowIfNull_ShouldNotThrow_NotFoundException() { // Arrange var entityType = EntityType.Author; - var argument = new Author(Guid.NewGuid(), "FirstName", "LastName"); + var argument = new Author(Guid.NewGuid(), "FirstName", "LastName", []); // Act var result = Should.NotThrow(() => @@ -32,7 +32,7 @@ public void ThrowIfNull_ShouldThrow_NotFoundException() { // Arrange var entityType = EntityType.Author; - Author argument = null; + Author? argument = null; // Act var result = Should.Throw(() => diff --git a/tests/Application.Tests.Unit/Common/Paging/PagingTests.cs b/tests/Application.Tests.Unit/Common/Paging/PagingTests.cs deleted file mode 100644 index 3876ab9..0000000 --- a/tests/Application.Tests.Unit/Common/Paging/PagingTests.cs +++ /dev/null @@ -1,73 +0,0 @@ -namespace CleanModelContextProtocol.Application.Tests.Unit.Common.Paging; - -using Application.Common.Paging; -using Shouldly; -using Xunit; - -public class PagingTests -{ - [Theory] - [InlineData(0)] - [InlineData(10)] - [InlineData(12345)] - public void Encode_ShouldRoundTrip_Offset(int offset) - { - // Act - var cursor = Paging.Encode(offset); - var result = Paging.TryDecode(cursor, out var decoded); - - // Assert - result.ShouldBeTrue(); - decoded.ShouldBe(offset); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void TryDecode_ShouldReturn_FirstPage(string cursor) - { - // Act - var result = Paging.TryDecode(cursor, out var offset); - - // Assert - result.ShouldBeTrue(); - offset.ShouldBe(0); - } - - [Theory] - [InlineData("not a cursor")] - [InlineData("b2Zmc2V0Og==")] - [InlineData("b2Zmc2V0Oi0x")] - [InlineData("cGFnZToy")] - public void TryDecode_ShouldReturn_False(string cursor) - { - // Act - var result = Paging.TryDecode(cursor, out _); - - // Assert - result.ShouldBeFalse(); - } - - [Fact] - public void ToPage_ShouldReturn_NextCursor() - { - // Act - var result = Paging.ToPage([1, 2], 5, 2); - - // Assert - result.Items.ShouldBe([1, 2]); - result.TotalCount.ShouldBe(5); - _ = Paging.TryDecode(result.NextCursor, out var next); - next.ShouldBe(4); - } - - [Fact] - public void ToPage_ShouldReturn_NoCursorOnLastPage() - { - // Act - var result = Paging.ToPage([5], 5, 4); - - // Assert - result.NextCursor.ShouldBeNull(); - } -} diff --git a/tests/Application.Tests.Unit/Movies/Queries/GetMovieById/GetReviewByIdHandlerTests.cs b/tests/Application.Tests.Unit/Movies/Queries/GetMovieById/GetReviewByIdHandlerTests.cs index ddbd47d..c4bf168 100644 --- a/tests/Application.Tests.Unit/Movies/Queries/GetMovieById/GetReviewByIdHandlerTests.cs +++ b/tests/Application.Tests.Unit/Movies/Queries/GetMovieById/GetReviewByIdHandlerTests.cs @@ -26,7 +26,7 @@ public async Task Handle_ShouldPassThrough_Query() using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; - _ = context.GetMovieById(Arg.Any(), token).Returns(new Movie(Guid.Empty, "Title")); + _ = context.GetMovieById(Arg.Any(), token).Returns(new Movie(Guid.Empty, "Title", [])); // Act var result = await handler.Handle(query, token); @@ -39,7 +39,7 @@ public async Task Handle_ShouldPassThrough_Query() result.Id.ShouldBe(Guid.Empty); result.Title.ShouldBe("Title"); - result.Reviews.ShouldBeNull(); + result.Reviews.ShouldBeEmpty(); } [Fact] diff --git a/tests/Application.Tests.Unit/Movies/Queries/GetMovies/GetMoviesHandlerTests.cs b/tests/Application.Tests.Unit/Movies/Queries/GetMovies/GetMoviesHandlerTests.cs index 5a88846..68f135e 100644 --- a/tests/Application.Tests.Unit/Movies/Queries/GetMovies/GetMoviesHandlerTests.cs +++ b/tests/Application.Tests.Unit/Movies/Queries/GetMovies/GetMoviesHandlerTests.cs @@ -2,6 +2,7 @@ namespace CleanModelContextProtocol.Application.Tests.Unit.Movies.Queries.GetMov using System.Threading; using System.Threading.Tasks; +using Application.Common.Paging; using Application.Movies; using Application.Movies.Entities; using Application.Movies.Queries.GetMovies; @@ -12,31 +13,53 @@ namespace CleanModelContextProtocol.Application.Tests.Unit.Movies.Queries.GetMov public class GetMoviesHandlerTests { [Fact] - public async Task Handle_ShouldPassThrough_Query() + public async Task Handle_ShouldReturn_Page() { // Arrange - var query = new GetMoviesQuery(); + var query = new GetMoviesQuery { Query = "Lorem", Offset = 20, Limit = 5 }; - var context = Substitute.For(); - var handler = new GetMoviesHandler(context); + var repository = Substitute.For(); + var handler = new GetMoviesHandler(repository); using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; - _ = context.GetMovies(token).Returns([new Movie(Guid.Empty, "Title")]); + _ = repository.GetMovies("Lorem", 20, 5, token).Returns(([new MovieSummary(Guid.Empty, "Title", 0, null)], 21)); // Act var result = await handler.Handle(query, token); // Assert - _ = await context.Received(1).GetMovies(token); + _ = await repository.Received(1).GetMovies("Lorem", 20, 5, token); _ = result.ShouldNotBeNull(); - _ = result.ShouldBeOfType>(); + result.Items.Count.ShouldBe(1); + result.Items[0].Title.ShouldBe("Title"); + result.Offset.ShouldBe(20); + result.Limit.ShouldBe(5); + result.TotalCount.ShouldBe(21); + } + + [Fact] + public async Task Handle_ShouldStartAt_FirstPage() + { + // Arrange + var query = new GetMoviesQuery(); - result.ShouldNotBeEmpty(); - result.Count.ShouldBe(1); + var repository = Substitute.For(); + var handler = new GetMoviesHandler(repository); + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + _ = repository.GetMovies(null, 0, Paging.DefaultLimit, token).Returns(([new MovieSummary(Guid.Empty, "Title", 0, null)], 1)); + + // Act + var result = await handler.Handle(query, token); + + // Assert + _ = await repository.Received(1).GetMovies(null, 0, Paging.DefaultLimit, token); - result[0].Id.ShouldBe(Guid.Empty); - result[0].Title.ShouldBe("Title"); + result.Offset.ShouldBe(0); + result.Limit.ShouldBe(Paging.DefaultLimit); + result.TotalCount.ShouldBe(1); } } diff --git a/tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesValidatorTests.cs b/tests/Application.Tests.Unit/Movies/Queries/GetMovies/GetMoviesValidatorTests.cs similarity index 56% rename from tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesValidatorTests.cs rename to tests/Application.Tests.Unit/Movies/Queries/GetMovies/GetMoviesValidatorTests.cs index 15bebdb..84bc8e0 100644 --- a/tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesValidatorTests.cs +++ b/tests/Application.Tests.Unit/Movies/Queries/GetMovies/GetMoviesValidatorTests.cs @@ -1,12 +1,12 @@ -namespace CleanModelContextProtocol.Application.Tests.Unit.Movies.Queries.SearchMovies; +namespace CleanModelContextProtocol.Application.Tests.Unit.Movies.Queries.GetMovies; -using Application.Movies.Queries.SearchMovies; +using Application.Movies.Queries.GetMovies; using FluentValidation.TestHelper; using Xunit; -public class SearchMoviesValidatorTests +public class GetMoviesValidatorTests { - private static readonly SearchMoviesValidator Validator = new(); + private static readonly GetMoviesValidator Validator = new(); [Theory] [InlineData(0)] @@ -14,7 +14,7 @@ public class SearchMoviesValidatorTests public void Validator_ShouldHaveValidationErrorFor_Limit(int limit) { // Arrange - var query = new SearchMoviesQuery { Limit = limit }; + var query = new GetMoviesQuery { Limit = limit }; // Act var result = Validator.TestValidate(query); @@ -24,23 +24,23 @@ public void Validator_ShouldHaveValidationErrorFor_Limit(int limit) } [Fact] - public void Validator_ShouldHaveValidationErrorFor_Cursor() + public void Validator_ShouldHaveValidationErrorFor_Offset() { // Arrange - var query = new SearchMoviesQuery { Cursor = "not a cursor" }; + var query = new GetMoviesQuery { Offset = -1 }; // Act var result = Validator.TestValidate(query); // Assert - _ = result.ShouldHaveValidationErrorFor(query => query.Cursor); + _ = result.ShouldHaveValidationErrorFor(query => query.Offset); } [Fact] public void Validator_ShouldHaveValidationErrorFor_Query() { // Arrange - var query = new SearchMoviesQuery { Query = new string('a', 101) }; + var query = new GetMoviesQuery { Query = new string('a', 101) }; // Act var result = Validator.TestValidate(query); @@ -50,12 +50,12 @@ public void Validator_ShouldHaveValidationErrorFor_Query() } [Theory] - [InlineData(null, 1, null)] - [InlineData("Lorem", 50, "b2Zmc2V0OjEw")] - public void Validator_ShouldNotHaveValidationErrors(string search, int limit, string cursor) + [InlineData(null, 0, 1)] + [InlineData("Lorem", 100, 50)] + public void Validator_ShouldNotHaveValidationErrors(string? search, int offset, int limit) { // Arrange - var query = new SearchMoviesQuery { Query = search, Limit = limit, Cursor = cursor }; + var query = new GetMoviesQuery { Query = search, Offset = offset, Limit = limit }; // Act var result = Validator.TestValidate(query); diff --git a/tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesHandlerTests.cs b/tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesHandlerTests.cs deleted file mode 100644 index e412875..0000000 --- a/tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesHandlerTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -namespace CleanModelContextProtocol.Application.Tests.Unit.Movies.Queries.SearchMovies; - -using System.Threading; -using System.Threading.Tasks; -using Application.Movies; -using Application.Movies.Entities; -using Application.Movies.Queries.SearchMovies; -using Application.Common.Paging; -using NSubstitute; -using Shouldly; -using Xunit; - -public class SearchMoviesHandlerTests -{ - [Fact] - public async Task Handle_ShouldPassThrough_Query() - { - // Arrange - var query = new SearchMoviesQuery { Query = "Lorem", Limit = 1, Cursor = Paging.Encode(2) }; - - var repository = Substitute.For(); - var handler = new SearchMoviesHandler(repository); - using var tokenSource = new CancellationTokenSource(); - var token = tokenSource.Token; - - _ = repository.SearchMovies("Lorem", 2, 1, token).Returns(([new Movie(Guid.Empty, "Title")], 5)); - - // Act - var result = await handler.Handle(query, token); - - // Assert - _ = await repository.Received(1).SearchMovies("Lorem", 2, 1, token); - - _ = result.ShouldNotBeNull(); - result.Items.Count.ShouldBe(1); - result.Items[0].Title.ShouldBe("Title"); - result.TotalCount.ShouldBe(5); - result.NextCursor.ShouldBe(Paging.Encode(3)); - } - - [Fact] - public async Task Handle_ShouldStartAt_FirstPage() - { - // Arrange - var query = new SearchMoviesQuery(); - - var repository = Substitute.For(); - var handler = new SearchMoviesHandler(repository); - using var tokenSource = new CancellationTokenSource(); - var token = tokenSource.Token; - - _ = repository.SearchMovies(null, 0, Paging.DefaultLimit, token).Returns(([new Movie(Guid.Empty, "Title")], 1)); - - // Act - var result = await handler.Handle(query, token); - - // Assert - _ = await repository.Received(1).SearchMovies(null, 0, Paging.DefaultLimit, token); - - result.TotalCount.ShouldBe(1); - result.NextCursor.ShouldBeNull(); - } -} diff --git a/tests/Application.Tests.Unit/Reviews/Commands/UpdateReview/UpdateReviewHandlerTests.cs b/tests/Application.Tests.Unit/Reviews/Commands/UpdateReview/UpdateReviewHandlerTests.cs index bfdba8f..0968c3d 100644 --- a/tests/Application.Tests.Unit/Reviews/Commands/UpdateReview/UpdateReviewHandlerTests.cs +++ b/tests/Application.Tests.Unit/Reviews/Commands/UpdateReview/UpdateReviewHandlerTests.cs @@ -5,8 +5,6 @@ namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Commands.Upda using Application.Common.Exceptions; using Application.Reviews; using Application.Reviews.Commands.UpdateReview; -using CleanModelContextProtocol.Application.Authors; -using CleanModelContextProtocol.Application.Movies; using NSubstitute; using Shouldly; using Xunit; @@ -19,32 +17,27 @@ public async Task Handle_ShouldPassThrough_Command() // Arrange var command = new UpdateReviewCommand { - Id = Guid.Empty, - AuthorId = Guid.Empty, - MovieId = Guid.Empty, + Id = Guid.NewGuid(), Stars = 1 }; - var authorsRepository = Substitute.For(); - var moviesRepository = Substitute.For(); var reviewsRepository = Substitute.For(); _ = reviewsRepository.ReviewExists(default, default).ReturnsForAnyArgs(true); - _ = authorsRepository.AuthorExists(default, default).ReturnsForAnyArgs(true); - _ = moviesRepository.MovieExists(default, default).ReturnsForAnyArgs(true); + _ = reviewsRepository.UpdateReview(default, default, default).ReturnsForAnyArgs(true); - var handler = new UpdateReviewHandler(authorsRepository, moviesRepository, reviewsRepository); + var handler = new UpdateReviewHandler(reviewsRepository); using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; // Act - _ = await handler.Handle(command, token); + var result = await handler.Handle(command, token); // Assert + result.ShouldBeTrue(); + _ = await reviewsRepository.Received(1).ReviewExists(command.Id, token); - _ = await authorsRepository.Received(1).AuthorExists(command.AuthorId, token); - _ = await moviesRepository.Received(1).MovieExists(command.MovieId, token); - _ = await reviewsRepository.Received(1).UpdateReview(command.Id, command.AuthorId, command.MovieId, command.Stars, token); + _ = await reviewsRepository.Received(1).UpdateReview(command.Id, command.Stars, token); } [Fact] @@ -53,105 +46,25 @@ public async Task Handle_ShouldThrowException_ReviewDoesNotExist() // Arrange var command = new UpdateReviewCommand { - Id = Guid.Empty, - AuthorId = Guid.Empty, - MovieId = Guid.Empty, + Id = Guid.NewGuid(), Stars = 5 }; - var authorsRepository = Substitute.For(); - var moviesRepository = Substitute.For(); var reviewsRepository = Substitute.For(); _ = reviewsRepository.ReviewExists(default, default).ReturnsForAnyArgs(false); - _ = authorsRepository.AuthorExists(default, default).ReturnsForAnyArgs(true); - _ = moviesRepository.MovieExists(default, default).ReturnsForAnyArgs(true); - var handler = new UpdateReviewHandler(authorsRepository, moviesRepository, reviewsRepository); + var handler = new UpdateReviewHandler(reviewsRepository); using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; // Act - var exception = Should.Throw(async () => await handler.Handle(command, token)); + var exception = await Should.ThrowAsync(async () => await handler.Handle(command, token)); // Assert exception.Message.ShouldBe("The Review with the supplied id was not found."); _ = await reviewsRepository.Received(1).ReviewExists(command.Id, token); - _ = await authorsRepository.DidNotReceive().AuthorExists(command.AuthorId, token); - _ = await moviesRepository.DidNotReceive().MovieExists(command.MovieId, token); - _ = await reviewsRepository.DidNotReceive().UpdateReview(command.Id, command.AuthorId, command.MovieId, command.Stars, token); - } - - [Fact] - public async Task Handle_ShouldThrowException_AuthorDoesNotExist() - { - // Arrange - var command = new UpdateReviewCommand - { - Id = Guid.Empty, - AuthorId = Guid.Empty, - MovieId = Guid.Empty, - Stars = 5 - }; - - var authorsRepository = Substitute.For(); - var moviesRepository = Substitute.For(); - var reviewsRepository = Substitute.For(); - - _ = reviewsRepository.ReviewExists(default, default).ReturnsForAnyArgs(true); - _ = authorsRepository.AuthorExists(default, default).ReturnsForAnyArgs(false); - _ = moviesRepository.MovieExists(default, default).ReturnsForAnyArgs(true); - - var handler = new UpdateReviewHandler(authorsRepository, moviesRepository, reviewsRepository); - using var tokenSource = new CancellationTokenSource(); - var token = tokenSource.Token; - - // Act - var exception = Should.Throw(async () => await handler.Handle(command, token)); - - // Assert - exception.Message.ShouldBe("The Author with the supplied id was not found."); - - _ = await reviewsRepository.Received(1).ReviewExists(command.Id, token); - _ = await authorsRepository.Received(1).AuthorExists(command.AuthorId, token); - _ = await moviesRepository.DidNotReceive().MovieExists(command.MovieId, token); - _ = await reviewsRepository.DidNotReceive().CreateReview(command.AuthorId, command.MovieId, command.Stars, token); - } - - [Fact] - public async Task Handle_ShouldThrowException_MovieDoesNotExist() - { - // Arrange - var command = new UpdateReviewCommand - { - Id = Guid.Empty, - AuthorId = Guid.Empty, - MovieId = Guid.Empty, - Stars = 5 - }; - - var authorsRepository = Substitute.For(); - var moviesRepository = Substitute.For(); - var reviewsRepository = Substitute.For(); - - _ = reviewsRepository.ReviewExists(default, default).ReturnsForAnyArgs(true); - _ = authorsRepository.AuthorExists(default, default).ReturnsForAnyArgs(true); - _ = moviesRepository.MovieExists(default, default).ReturnsForAnyArgs(false); - - var handler = new UpdateReviewHandler(authorsRepository, moviesRepository, reviewsRepository); - using var tokenSource = new CancellationTokenSource(); - var token = tokenSource.Token; - - // Act - var exception = Should.Throw(async () => await handler.Handle(command, token)); - - // Assert - exception.Message.ShouldBe("The Movie with the supplied id was not found."); - - _ = await reviewsRepository.Received(1).ReviewExists(command.Id, token); - _ = await authorsRepository.Received(1).AuthorExists(command.AuthorId, token); - _ = await moviesRepository.Received(1).MovieExists(command.MovieId, token); - _ = await reviewsRepository.DidNotReceive().CreateReview(command.AuthorId, command.MovieId, command.Stars, token); + _ = await reviewsRepository.DidNotReceiveWithAnyArgs().UpdateReview(default, default, default); } } diff --git a/tests/Application.Tests.Unit/Reviews/Commands/UpdateReview/UpdateReviewValidatorTests.cs b/tests/Application.Tests.Unit/Reviews/Commands/UpdateReview/UpdateReviewValidatorTests.cs index a20e674..32c209e 100644 --- a/tests/Application.Tests.Unit/Reviews/Commands/UpdateReview/UpdateReviewValidatorTests.cs +++ b/tests/Application.Tests.Unit/Reviews/Commands/UpdateReview/UpdateReviewValidatorTests.cs @@ -9,14 +9,12 @@ public class UpdateReviewValidatorTests private static readonly UpdateReviewValidator Validator = new(); [Fact] - public void Validator_ShouldNotHaveValidationErrorFor_Id() + public void Validator_ShouldNotHaveValidationErrors() { // Arrange var command = new UpdateReviewCommand { Id = Guid.NewGuid(), - AuthorId = Guid.NewGuid(), - MovieId = Guid.NewGuid(), Stars = 5 }; @@ -24,7 +22,7 @@ public void Validator_ShouldNotHaveValidationErrorFor_Id() var result = Validator.TestValidate(command); // Assert - result.ShouldNotHaveValidationErrorFor(command => command.Id); + result.ShouldNotHaveAnyValidationErrors(); } [Fact] @@ -34,8 +32,6 @@ public void Validator_ShouldHaveValidationErrorFor_Id() var command = new UpdateReviewCommand { Id = Guid.Empty, - AuthorId = Guid.NewGuid(), - MovieId = Guid.NewGuid(), Stars = 5 }; @@ -43,124 +39,18 @@ public void Validator_ShouldHaveValidationErrorFor_Id() var result = Validator.TestValidate(command); // Assert - _ = result.ShouldHaveValidationErrorFor(command => command.Id).WithErrorMessage("A review id was not supplied to Update the review."); - } - - [Fact] - public void Validator_ShouldNotHaveValidationErrorFor_ReviewAuthorId() - { - // Arrange - var command = new UpdateReviewCommand - { - Id = Guid.NewGuid(), - AuthorId = Guid.NewGuid(), - MovieId = Guid.NewGuid(), - Stars = 5 - }; - - // Act - var result = Validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationErrorFor(command => command.AuthorId); - } - - [Fact] - public void Validator_ShouldHaveValidationErrorFor_ReviewAuthorId() - { - // Arrange - var command = new UpdateReviewCommand - { - Id = Guid.NewGuid(), - AuthorId = Guid.Empty, - MovieId = Guid.NewGuid(), - Stars = 5 - }; - - // Act - var result = Validator.TestValidate(command); - - // Assert - _ = result.ShouldHaveValidationErrorFor(command => command.AuthorId).WithErrorMessage("An author id was not supplied to Update the review."); - } - - [Fact] - public void Validator_ShouldNotHaveValidationErrorFor_ReviewedMovieId() - { - // Arrange - var command = new UpdateReviewCommand - { - Id = Guid.NewGuid(), - AuthorId = Guid.NewGuid(), - MovieId = Guid.NewGuid(), - Stars = 5 - }; - - // Act - var result = Validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationErrorFor(command => command.MovieId); - } - - [Fact] - public void Validator_ShouldHaveValidationErrorFor_ReviewedMovieId() - { - // Arrange - var command = new UpdateReviewCommand - { - Id = Guid.NewGuid(), - AuthorId = Guid.NewGuid(), - MovieId = Guid.Empty, - Stars = 5 - }; - - // Act - var result = Validator.TestValidate(command); - - // Assert - _ = result.ShouldHaveValidationErrorFor(command => command.MovieId).WithErrorMessage("A movie id was not supplied to Update the review."); - } - - - [Theory] - [InlineData(1)] - [InlineData(2)] - [InlineData(3)] - [InlineData(4)] - [InlineData(5)] - public void Validator_ShouldNotHaveValidationErrorFor_Stars(int stars) - { - // Arrange - var command = new UpdateReviewCommand - { - Id = Guid.NewGuid(), - AuthorId = Guid.NewGuid(), - MovieId = Guid.NewGuid(), - Stars = stars - }; - - // Act - var result = Validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationErrorFor(command => command.Stars); + _ = result.ShouldHaveValidationErrorFor(command => command.Id); } [Theory] - [InlineData(-1)] [InlineData(0)] [InlineData(6)] - [InlineData(100)] - [InlineData(-100)] public void Validator_ShouldHaveValidationErrorFor_Stars(int stars) { // Arrange var command = new UpdateReviewCommand { Id = Guid.NewGuid(), - AuthorId = Guid.NewGuid(), - MovieId = Guid.NewGuid(), Stars = stars }; @@ -168,6 +58,6 @@ public void Validator_ShouldHaveValidationErrorFor_Stars(int stars) var result = Validator.TestValidate(command); // Assert - _ = result.ShouldHaveValidationErrorFor(command => command.Stars).WithErrorMessage("A star rating must be between 1 and 5."); + _ = result.ShouldHaveValidationErrorFor(command => command.Stars); } } diff --git a/tests/Application.Tests.Unit/Reviews/Queries/GetReviews/GetReviewsHandlerTests.cs b/tests/Application.Tests.Unit/Reviews/Queries/GetReviews/GetReviewsHandlerTests.cs index 0407eac..1eca187 100644 --- a/tests/Application.Tests.Unit/Reviews/Queries/GetReviews/GetReviewsHandlerTests.cs +++ b/tests/Application.Tests.Unit/Reviews/Queries/GetReviews/GetReviewsHandlerTests.cs @@ -2,6 +2,7 @@ namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Queries.GetRe using System.Threading; using System.Threading.Tasks; +using Application.Common.Paging; using Application.Reviews; using Application.Reviews.Entities; using Application.Reviews.Queries.GetReviews; @@ -11,32 +12,57 @@ namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Queries.GetRe public class GetReviewsHandlerTests { + private static readonly Guid MovieId = Guid.NewGuid(); + private static readonly Guid AuthorId = Guid.NewGuid(); + [Fact] - public async Task Handle_ShouldPassThrough_Query() + public async Task Handle_ShouldReturn_Page() { // Arrange - var query = new GetReviewsQuery(); + var query = new GetReviewsQuery { MovieId = MovieId, AuthorId = AuthorId, Offset = 20, Limit = 5 }; - var context = Substitute.For(); - var handler = new GetReviewsHandler(context); + var repository = Substitute.For(); + var handler = new GetReviewsHandler(repository); using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; - _ = context.GetReviews(token).Returns([new Review(Guid.Empty, 5)]); + _ = repository.GetReviews(MovieId, AuthorId, 20, 5, token).Returns(([new Review(Guid.Empty, 5)], 21)); // Act var result = await handler.Handle(query, token); // Assert - _ = await context.Received(1).GetReviews(token); + _ = await repository.Received(1).GetReviews(MovieId, AuthorId, 20, 5, token); _ = result.ShouldNotBeNull(); - _ = result.ShouldBeOfType>(); + result.Items.Count.ShouldBe(1); + result.Items[0].Stars.ShouldBe(5); + result.Offset.ShouldBe(20); + result.Limit.ShouldBe(5); + result.TotalCount.ShouldBe(21); + } + + [Fact] + public async Task Handle_ShouldStartAt_FirstPage() + { + // Arrange + var query = new GetReviewsQuery(); - result.ShouldNotBeEmpty(); - result.Count.ShouldBe(1); + var repository = Substitute.For(); + var handler = new GetReviewsHandler(repository); + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + _ = repository.GetReviews(null, null, 0, Paging.DefaultLimit, token).Returns(([new Review(Guid.Empty, 5)], 1)); + + // Act + var result = await handler.Handle(query, token); + + // Assert + _ = await repository.Received(1).GetReviews(null, null, 0, Paging.DefaultLimit, token); - result[0].Id.ShouldBe(Guid.Empty); - result[0].Stars.ShouldBe(5); + result.Offset.ShouldBe(0); + result.Limit.ShouldBe(Paging.DefaultLimit); + result.TotalCount.ShouldBe(1); } } diff --git a/tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsValidatorTests.cs b/tests/Application.Tests.Unit/Reviews/Queries/GetReviews/GetReviewsValidatorTests.cs similarity index 51% rename from tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsValidatorTests.cs rename to tests/Application.Tests.Unit/Reviews/Queries/GetReviews/GetReviewsValidatorTests.cs index a4bc567..4293e1a 100644 --- a/tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsValidatorTests.cs +++ b/tests/Application.Tests.Unit/Reviews/Queries/GetReviews/GetReviewsValidatorTests.cs @@ -1,85 +1,72 @@ -namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Queries.SearchReviews; +namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Queries.GetReviews; -using Application.Reviews.Queries.SearchReviews; +using Application.Reviews.Queries.GetReviews; using FluentValidation.TestHelper; using Xunit; -public class SearchReviewsValidatorTests +public class GetReviewsValidatorTests { - private static readonly SearchReviewsValidator Validator = new(); + private static readonly GetReviewsValidator Validator = new(); - [Fact] - public void Validator_ShouldHaveValidationErrorFor_MovieIdEmpty() + [Theory] + [InlineData(0)] + [InlineData(51)] + public void Validator_ShouldHaveValidationErrorFor_Limit(int limit) { // Arrange - var query = new SearchReviewsQuery { MovieId = Guid.Empty }; + var query = new GetReviewsQuery { Limit = limit }; // Act var result = Validator.TestValidate(query); // Assert - _ = result.ShouldHaveValidationErrorFor(query => query.MovieId); + _ = result.ShouldHaveValidationErrorFor(query => query.Limit); } [Fact] - public void Validator_ShouldHaveValidationErrorFor_AuthorIdEmpty() + public void Validator_ShouldHaveValidationErrorFor_Offset() { // Arrange - var query = new SearchReviewsQuery { AuthorId = Guid.Empty }; + var query = new GetReviewsQuery { Offset = -1 }; // Act var result = Validator.TestValidate(query); // Assert - _ = result.ShouldHaveValidationErrorFor(query => query.AuthorId); - } - - [Theory] - [InlineData(0)] - [InlineData(51)] - public void Validator_ShouldHaveValidationErrorFor_Limit(int limit) - { - // Arrange - var query = new SearchReviewsQuery { Limit = limit }; - - // Act - var result = Validator.TestValidate(query); - - // Assert - _ = result.ShouldHaveValidationErrorFor(query => query.Limit); + _ = result.ShouldHaveValidationErrorFor(query => query.Offset); } [Fact] - public void Validator_ShouldHaveValidationErrorFor_Cursor() + public void Validator_ShouldHaveValidationErrorFor_MovieId() { // Arrange - var query = new SearchReviewsQuery { Cursor = "not a cursor" }; + var query = new GetReviewsQuery { MovieId = Guid.Empty }; // Act var result = Validator.TestValidate(query); // Assert - _ = result.ShouldHaveValidationErrorFor(query => query.Cursor); + _ = result.ShouldHaveValidationErrorFor(query => query.MovieId); } [Fact] - public void Validator_ShouldNotHaveValidationErrors() + public void Validator_ShouldHaveValidationErrorFor_AuthorId() { // Arrange - var query = new SearchReviewsQuery { MovieId = Guid.NewGuid(), AuthorId = Guid.NewGuid(), Limit = 50 }; + var query = new GetReviewsQuery { AuthorId = Guid.Empty }; // Act var result = Validator.TestValidate(query); // Assert - result.ShouldNotHaveAnyValidationErrors(); + _ = result.ShouldHaveValidationErrorFor(query => query.AuthorId); } [Fact] - public void Validator_ShouldNotHaveValidationErrors_WithoutFilters() + public void Validator_ShouldNotHaveValidationErrors() { // Arrange - var query = new SearchReviewsQuery(); + var query = new GetReviewsQuery { MovieId = Guid.NewGuid(), AuthorId = Guid.NewGuid(), Offset = 100, Limit = 50 }; // Act var result = Validator.TestValidate(query); diff --git a/tests/Application.Tests.Unit/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsHandlerTests.cs b/tests/Application.Tests.Unit/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsHandlerTests.cs new file mode 100644 index 0000000..0d1f352 --- /dev/null +++ b/tests/Application.Tests.Unit/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsHandlerTests.cs @@ -0,0 +1,44 @@ +namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Queries.GetReviewsForAuthors; + +using System.Threading; +using System.Threading.Tasks; +using Application.Authors.Entities; +using Application.Reviews; +using Application.Reviews.Entities; +using Application.Reviews.Queries.GetReviewsForAuthors; +using NSubstitute; +using Shouldly; +using Xunit; + +public class GetReviewsForAuthorsHandlerTests +{ + [Fact] + public async Task Handle_ShouldReturn_ReviewsGroupedByAuthor() + { + // Arrange + var reviewer = Guid.NewGuid(); + var nonReviewer = Guid.NewGuid(); + var query = new GetReviewsForAuthorsQuery { AuthorIds = [reviewer, nonReviewer, reviewer] }; + + var repository = Substitute.For(); + var handler = new GetReviewsForAuthorsHandler(repository); + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + _ = repository.GetReviewsForAuthors(query.AuthorIds, token).Returns( + [ + new Review(Guid.NewGuid(), 5, ReviewAuthor: new ReviewAuthor(reviewer, "First", "Last")), + new Review(Guid.NewGuid(), 3, ReviewAuthor: new ReviewAuthor(reviewer, "First", "Last")) + ]); + + // Act + var result = await handler.Handle(query, token); + + // Assert + _ = await repository.Received(1).GetReviewsForAuthors(query.AuthorIds, token); + + result.Count.ShouldBe(2); + result[reviewer].Select(r => r.Stars).ShouldBe([5, 3]); + result[nonReviewer].ShouldBeEmpty(); + } +} diff --git a/tests/Application.Tests.Unit/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsValidatorTests.cs b/tests/Application.Tests.Unit/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsValidatorTests.cs new file mode 100644 index 0000000..236cd3d --- /dev/null +++ b/tests/Application.Tests.Unit/Reviews/Queries/GetReviewsForAuthors/GetReviewsForAuthorsValidatorTests.cs @@ -0,0 +1,63 @@ +namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Queries.GetReviewsForAuthors; + +using Application.Common.Paging; +using Application.Reviews.Queries.GetReviewsForAuthors; +using FluentValidation.TestHelper; +using Xunit; + +public class GetReviewsForAuthorsValidatorTests +{ + private static readonly GetReviewsForAuthorsValidator Validator = new(); + + [Fact] + public void Validator_ShouldHaveValidationErrorFor_NoIds() + { + // Arrange + var query = new GetReviewsForAuthorsQuery { AuthorIds = [] }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.AuthorIds); + } + + [Fact] + public void Validator_ShouldHaveValidationErrorFor_TooManyIds() + { + // Arrange + var query = new GetReviewsForAuthorsQuery { AuthorIds = [.. Enumerable.Range(0, Paging.MaxLimit + 1).Select(_ => Guid.NewGuid())] }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.AuthorIds); + } + + [Fact] + public void Validator_ShouldHaveValidationErrorFor_EmptyId() + { + // Arrange + var query = new GetReviewsForAuthorsQuery { AuthorIds = [Guid.NewGuid(), Guid.Empty] }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor("AuthorIds[1]"); + } + + [Fact] + public void Validator_ShouldNotHaveValidationErrors() + { + // Arrange + var query = new GetReviewsForAuthorsQuery { AuthorIds = [Guid.NewGuid()] }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/Application.Tests.Unit/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesHandlerTests.cs b/tests/Application.Tests.Unit/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesHandlerTests.cs new file mode 100644 index 0000000..c0cb561 --- /dev/null +++ b/tests/Application.Tests.Unit/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesHandlerTests.cs @@ -0,0 +1,44 @@ +namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Queries.GetReviewsForMovies; + +using System.Threading; +using System.Threading.Tasks; +using Application.Movies.Entities; +using Application.Reviews; +using Application.Reviews.Entities; +using Application.Reviews.Queries.GetReviewsForMovies; +using NSubstitute; +using Shouldly; +using Xunit; + +public class GetReviewsForMoviesHandlerTests +{ + [Fact] + public async Task Handle_ShouldReturn_ReviewsGroupedByMovie() + { + // Arrange + var reviewed = Guid.NewGuid(); + var unreviewed = Guid.NewGuid(); + var query = new GetReviewsForMoviesQuery { MovieIds = [reviewed, unreviewed, reviewed] }; + + var repository = Substitute.For(); + var handler = new GetReviewsForMoviesHandler(repository); + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + _ = repository.GetReviewsForMovies(query.MovieIds, token).Returns( + [ + new Review(Guid.NewGuid(), 5, new ReviewedMovie(reviewed, "Title")), + new Review(Guid.NewGuid(), 3, new ReviewedMovie(reviewed, "Title")) + ]); + + // Act + var result = await handler.Handle(query, token); + + // Assert + _ = await repository.Received(1).GetReviewsForMovies(query.MovieIds, token); + + result.Count.ShouldBe(2); + result[reviewed].Select(r => r.Stars).ShouldBe([5, 3]); + result[unreviewed].ShouldBeEmpty(); + } +} diff --git a/tests/Application.Tests.Unit/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesValidatorTests.cs b/tests/Application.Tests.Unit/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesValidatorTests.cs new file mode 100644 index 0000000..e3c1c31 --- /dev/null +++ b/tests/Application.Tests.Unit/Reviews/Queries/GetReviewsForMovies/GetReviewsForMoviesValidatorTests.cs @@ -0,0 +1,63 @@ +namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Queries.GetReviewsForMovies; + +using Application.Common.Paging; +using Application.Reviews.Queries.GetReviewsForMovies; +using FluentValidation.TestHelper; +using Xunit; + +public class GetReviewsForMoviesValidatorTests +{ + private static readonly GetReviewsForMoviesValidator Validator = new(); + + [Fact] + public void Validator_ShouldHaveValidationErrorFor_NoIds() + { + // Arrange + var query = new GetReviewsForMoviesQuery { MovieIds = [] }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.MovieIds); + } + + [Fact] + public void Validator_ShouldHaveValidationErrorFor_TooManyIds() + { + // Arrange + var query = new GetReviewsForMoviesQuery { MovieIds = [.. Enumerable.Range(0, Paging.MaxLimit + 1).Select(_ => Guid.NewGuid())] }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.MovieIds); + } + + [Fact] + public void Validator_ShouldHaveValidationErrorFor_EmptyId() + { + // Arrange + var query = new GetReviewsForMoviesQuery { MovieIds = [Guid.NewGuid(), Guid.Empty] }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor("MovieIds[1]"); + } + + [Fact] + public void Validator_ShouldNotHaveValidationErrors() + { + // Arrange + var query = new GetReviewsForMoviesQuery { MovieIds = [Guid.NewGuid()] }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsHandlerTests.cs b/tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsHandlerTests.cs deleted file mode 100644 index ed0d137..0000000 --- a/tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsHandlerTests.cs +++ /dev/null @@ -1,45 +0,0 @@ -namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Queries.SearchReviews; - -using System.Threading; -using System.Threading.Tasks; -using Application.Authors.Entities; -using Application.Common.Paging; -using Application.Movies.Entities; -using Application.Reviews; -using Application.Reviews.Entities; -using Application.Reviews.Queries.SearchReviews; -using NSubstitute; -using Shouldly; -using Xunit; - -public class SearchReviewsHandlerTests -{ - [Fact] - public async Task Handle_ShouldPassThrough_Query() - { - // Arrange - var movieId = Guid.NewGuid(); - var authorId = Guid.NewGuid(); - var query = new SearchReviewsQuery { MovieId = movieId, AuthorId = authorId, Limit = 1, Cursor = Paging.Encode(1) }; - - var repository = Substitute.For(); - var handler = new SearchReviewsHandler(repository); - using var tokenSource = new CancellationTokenSource(); - var token = tokenSource.Token; - - _ = repository.SearchReviews(movieId, authorId, 1, 1, token) - .Returns(([new Review(Guid.Empty, 5, new ReviewedMovie(movieId, "Title"), new ReviewAuthor(authorId, "First", "Last"))], 2)); - - // Act - var result = await handler.Handle(query, token); - - // Assert - _ = await repository.Received(1).SearchReviews(movieId, authorId, 1, 1, token); - - _ = result.ShouldNotBeNull(); - result.Items.Count.ShouldBe(1); - result.Items[0].Stars.ShouldBe(5); - result.TotalCount.ShouldBe(2); - result.NextCursor.ShouldBeNull(); - } -} diff --git a/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/EntityFrameworkMovieReviewsRepositoryTests.cs b/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/EntityFrameworkMovieReviewsRepositoryTests.cs index bd2230d..851907b 100644 --- a/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/EntityFrameworkMovieReviewsRepositoryTests.cs +++ b/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/EntityFrameworkMovieReviewsRepositoryTests.cs @@ -5,37 +5,25 @@ namespace CleanModelContextProtocol.Infrastructure.Tests.Integration.Databases.M using Shouldly; using Xunit; -[Collection("MovieReviews")] -public class EntityFrameworkMovieReviewsRepositoryTests(MovieReviewsDataFixture fixture) +public sealed class EntityFrameworkMovieReviewsRepositoryTests : IDisposable { + private readonly MovieReviewsTestDatabase database = new(); - #region Authors - - [Fact] - public async Task GetAuthors_ShouldReturn_Authors() + public void Dispose() { - // Arrange - var repository = fixture.Repository; - using var tokenSource = new CancellationTokenSource(); - var token = tokenSource.Token; - - // Act - var result = await repository.GetAuthors(token); - - // Assert - result.ShouldNotBeEmpty(); - result.Count.ShouldBe(3); + this.database.Dispose(); } + #region Authors [Fact] public async Task GetAuthorById_ShouldReturn_Author() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; - var author = fixture.Context.Authors.FirstOrDefault(a => a.FirstName == "One"); + var author = this.database.Context.Authors.First(a => a.FirstName == "One"); // Act var result = await repository.GetAuthorById(author.Id, token); @@ -53,7 +41,7 @@ public async Task GetAuthorById_ShouldReturn_Author() public async Task GetAuthorById_ShouldReturn_Null() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; @@ -68,10 +56,10 @@ public async Task GetAuthorById_ShouldReturn_Null() public async Task AuthorExists_ShouldReturn_True() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; - var author = fixture.Context.Authors.FirstOrDefault(a => a.FirstName == "One"); + var author = this.database.Context.Authors.First(a => a.FirstName == "One"); // Act var result = await repository.AuthorExists(author.Id, token); @@ -84,7 +72,7 @@ public async Task AuthorExists_ShouldReturn_True() public async Task AuthorExists_ShouldReturn_False() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; @@ -100,68 +88,69 @@ public async Task AuthorExists_ShouldReturn_False() [InlineData("one", 1)] [InlineData("TWO TWO", 1)] [InlineData("missing", 0)] - public async Task SearchAuthors_ShouldReturn_Matches(string query, int expected) + [InlineData("%", 0)] + public async Task GetAuthors_ShouldReturn_Matches(string? query, int expected) { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; // Act - var (items, totalCount) = await repository.SearchAuthors(query, 0, 10, token); + var (items, totalCount) = await repository.GetAuthors(query, 0, 10, token); // Assert items.Count.ShouldBe(expected); totalCount.ShouldBe(expected); - items.ShouldAllBe(a => a.Reviews != null); } [Fact] - public async Task SearchAuthors_ShouldReturn_Page() + public async Task GetAuthors_ShouldReturn_ReviewCountAndAverageStars() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; // Act - var (items, totalCount) = await repository.SearchAuthors(null, 1, 1, token); + var (items, _) = await repository.GetAuthors("one", 0, 10, token); // Assert - items.Count.ShouldBe(1); - items[0].LastName.ShouldBe("Three"); - totalCount.ShouldBe(3); + var author = items.ShouldHaveSingleItem(); + author.ReviewCount.ShouldBe(3); + author.AverageStars.ShouldBe(2.0); } - #endregion Authors - - #region Movies - [Fact] - public async Task GetMovies_ShouldReturn_Movies() + public async Task GetAuthors_ShouldReturn_Page() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; // Act - var result = await repository.GetMovies(token); + var (items, totalCount) = await repository.GetAuthors(null, 1, 1, token); // Assert - result.ShouldNotBeEmpty(); - result.Count.ShouldBe(3); + items.Count.ShouldBe(1); + items[0].LastName.ShouldBe("Three"); + totalCount.ShouldBe(3); } + #endregion Authors + + #region Movies + [Fact] public async Task GetMovieById_ShouldReturn_Movie() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; - var movie = fixture.Context.Movies.FirstOrDefault(m => m.Title == "One"); + var movie = this.database.Context.Movies.First(m => m.Title == "One"); // Act var result = await repository.GetMovieById(movie.Id, token); @@ -178,7 +167,7 @@ public async Task GetMovieById_ShouldReturn_Movie() public async Task GetMovieById_ShouldReturn_Null() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; @@ -193,10 +182,10 @@ public async Task GetMovieById_ShouldReturn_Null() public async Task MovieExists_ShouldReturn_True() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; - var movie = fixture.Context.Movies.FirstOrDefault(m => m.Title == "One"); + var movie = this.database.Context.Movies.First(m => m.Title == "One"); // Act var result = await repository.MovieExists(movie.Id, token); @@ -209,7 +198,7 @@ public async Task MovieExists_ShouldReturn_True() public async Task MovieExists_ShouldReturn_False() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; @@ -225,33 +214,66 @@ public async Task MovieExists_ShouldReturn_False() [InlineData("t", 2)] [InlineData("ONE", 1)] [InlineData("missing", 0)] - public async Task SearchMovies_ShouldReturn_Matches(string query, int expected) + public async Task GetMovies_ShouldReturn_Matches(string? query, int expected) { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; // Act - var (items, totalCount) = await repository.SearchMovies(query, 0, 10, token); + var (items, totalCount) = await repository.GetMovies(query, 0, 10, token); // Assert items.Count.ShouldBe(expected); totalCount.ShouldBe(expected); - items.ShouldAllBe(m => m.Reviews != null); } [Fact] - public async Task SearchMovies_ShouldReturn_PagesInTitleOrder() + public async Task GetMovies_ShouldReturn_ReviewCountAndAverageStars() + { + // Arrange + var repository = this.database.Repository; + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + // Act + var (items, _) = await repository.GetMovies("one", 0, 10, token); + + // Assert + var movie = items.ShouldHaveSingleItem(); + movie.ReviewCount.ShouldBe(3); + movie.AverageStars.ShouldBe(2.7); + } + + [Fact] + public async Task GetMovies_ShouldReturn_NullAverageStars_WhenNoReviews() + { + // Arrange + var repository = this.database.Repository; + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + this.database.Context.Reviews.RemoveRange(this.database.Context.Reviews); + _ = await this.database.Context.SaveChangesAsync(token); + + // Act + var (items, _) = await repository.GetMovies(null, 0, 10, token); + + // Assert + items.ShouldAllBe(m => m.ReviewCount == 0 && m.AverageStars == null); + } + + [Fact] + public async Task GetMovies_ShouldReturn_PagesInTitleOrder() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; // Act - var (first, firstTotal) = await repository.SearchMovies(null, 0, 2, token); - var (second, secondTotal) = await repository.SearchMovies(null, 2, 2, token); + var (first, firstTotal) = await repository.GetMovies(null, 0, 2, token); + var (second, secondTotal) = await repository.GetMovies(null, 2, 2, token); // Assert first.Select(m => m.Title).ShouldBe(["One", "Three"]); @@ -270,45 +292,38 @@ public async Task CreateReview_ShouldReturn_NewReviews() // Arrange var review = new CreateReviewCommand { - AuthorId = fixture.Context.Authors.FirstOrDefault(a => a.FirstName == "One").Id, - MovieId = fixture.Context.Movies.FirstOrDefault(m => m.Title == "One").Id, + AuthorId = this.database.Context.Authors.First(a => a.FirstName == "One").Id, + MovieId = this.database.Context.Movies.First(m => m.Title == "One").Id, Stars = 5 }; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; // Act - var result = await fixture.Repository.CreateReview(review.AuthorId, review.MovieId, review.Stars, token); + var result = await this.database.Repository.CreateReview(review.AuthorId, review.MovieId, review.Stars, token); // Assert _ = result.ShouldNotBeNull(); result.Id.ShouldNotBe(Guid.Empty); - result.ReviewAuthor.Id.ShouldBe(review.AuthorId); - result.ReviewedMovie.Id.ShouldBe(review.MovieId); + result.ReviewAuthor.ShouldNotBeNull().Id.ShouldBe(review.AuthorId); + result.ReviewedMovie.ShouldNotBeNull().Id.ShouldBe(review.MovieId); result.Stars.ShouldBe(review.Stars); - - // Cleanup - _ = await fixture.Repository.DeleteReview(result.Id, token); } [Fact] public async Task DeleteReview_ShouldReturn_True() { // Arrange - var id = fixture.Context.Reviews.FirstOrDefault(r => r.Stars == 1).Id; + var id = this.database.Context.Reviews.First(r => r.Stars == 1).Id; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; // Act - var result = await fixture.Repository.DeleteReview(id, token); + var result = await this.database.Repository.DeleteReview(id, token); // Assert result.ShouldBeTrue(); - - // Cleanup - var authorId = fixture.Context.Authors.FirstOrDefault(a => a.FirstName == "Three").Id; - var movieId = fixture.Context.Movies.FirstOrDefault(m => m.Title == "Three").Id; - _ = await fixture.Repository.CreateReview(authorId, movieId, 1, token); + this.database.Context.Reviews.Any(r => r.Id == id).ShouldBeFalse(); } [Fact] @@ -319,37 +334,21 @@ public async Task DeleteReview_ShouldReturn_False() var token = tokenSource.Token; // Act - var result = await fixture.Repository.DeleteReview(Guid.Empty, token); + var result = await this.database.Repository.DeleteReview(Guid.Empty, token); // Assert result.ShouldBeFalse(); } - [Fact] - public async Task GetReviews_ShouldReturn_Reviews() - { - // Arrange - var repository = fixture.Repository; - using var tokenSource = new CancellationTokenSource(); - var token = tokenSource.Token; - - // Act - var result = await repository.GetReviews(token); - - // Assert - result.ShouldNotBeEmpty(); - result.Count.ShouldBe(9); - } - [Fact] public async Task GetReviewById_ShouldReturn_Review() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; - var review = fixture.Context.Reviews.FirstOrDefault(m => m.Stars == 5); + var review = this.database.Context.Reviews.First(m => m.Stars == 5); // Act var result = await repository.GetReviewById(review.Id, token); @@ -371,7 +370,7 @@ public async Task GetReviewById_ShouldReturn_Review() public async Task GetReviewById_ShouldReturn_Null() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; @@ -386,10 +385,10 @@ public async Task GetReviewById_ShouldReturn_Null() public async Task ReviewExists_ShouldReturn_True() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; - var review = fixture.Context.Reviews.FirstOrDefault(m => m.Stars == 5); + var review = this.database.Context.Reviews.First(m => m.Stars == 5); // Act var result = await repository.ReviewExists(review.Id, token); @@ -402,7 +401,7 @@ public async Task ReviewExists_ShouldReturn_True() public async Task ReviewExists_ShouldReturn_False() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; @@ -417,29 +416,28 @@ public async Task ReviewExists_ShouldReturn_False() public async Task UpdateReview_ShouldReturn_True() { // Arrange + var original = this.database.Context.Reviews.First(a => a.Stars == 2); var review = new UpdateReviewCommand { - Id = fixture.Context.Reviews.FirstOrDefault(a => a.Stars == 2).Id, - AuthorId = fixture.Context.Authors.FirstOrDefault(a => a.FirstName == "Two").Id, - MovieId = fixture.Context.Movies.FirstOrDefault(m => m.Title == "Two").Id, + Id = original.Id, Stars = 4 }; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; // Act - var result = await fixture.Repository.UpdateReview(review.Id, review.AuthorId, review.MovieId, review.Stars, token); + var result = await this.database.Repository.UpdateReview(review.Id, review.Stars, token); // Assert result.ShouldBeTrue(); - var updatedReview = fixture.Context.Reviews.FirstOrDefault(a => a.Id == review.Id); + var updatedReview = this.database.Context.Reviews.First(a => a.Id == review.Id); updatedReview.Id.ShouldBe(review.Id); - updatedReview.ReviewAuthorId.ShouldBe(review.AuthorId); - updatedReview.ReviewedMovieId.ShouldBe(review.MovieId); + updatedReview.ReviewAuthorId.ShouldBe(original.ReviewAuthorId); + updatedReview.ReviewedMovieId.ShouldBe(original.ReviewedMovieId); updatedReview.Stars.ShouldBe(review.Stars); - updatedReview.DateModified.ShouldBe(fixture.TimeProvider.GetUtcNow().UtcDateTime); + updatedReview.DateModified.ShouldBe(this.database.TimeProvider.GetUtcNow().UtcDateTime); } [Fact] @@ -449,71 +447,120 @@ public async Task UpdateReview_ShouldReturn_False() var review = new UpdateReviewCommand { Id = Guid.Empty, - AuthorId = fixture.Context.Authors.FirstOrDefault(a => a.FirstName == "One").Id, - MovieId = fixture.Context.Movies.FirstOrDefault(m => m.Title == "One").Id, Stars = 5 }; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; // Act - var result = await fixture.Repository.UpdateReview(review.Id, review.AuthorId, review.MovieId, review.Stars, token); + var result = await this.database.Repository.UpdateReview(review.Id, review.Stars, token); // Assert result.ShouldBeFalse(); } [Fact] - public async Task SearchReviews_ShouldReturn_ReviewsForMovie() + public async Task GetReviews_ShouldReturn_ReviewsForMovie() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; - var movieId = fixture.Context.Movies.First(m => m.Title == "Two").Id; + var movieId = this.database.Context.Movies.First(m => m.Title == "Two").Id; // Act - var (items, totalCount) = await repository.SearchReviews(movieId, null, 0, 50, token); + var (items, totalCount) = await repository.GetReviews(movieId, null, 0, 50, token); // Assert items.ShouldNotBeEmpty(); items.Count.ShouldBe(totalCount); - items.ShouldAllBe(r => r.ReviewedMovie.Id == movieId && r.ReviewedMovie.Title == "Two"); + items.ShouldAllBe(r => r.ReviewedMovie!.Id == movieId && r.ReviewedMovie.Title == "Two"); items.ShouldAllBe(r => r.ReviewAuthor != null); } [Fact] - public async Task SearchReviews_ShouldReturn_ReviewsForAuthorAndMovie() + public async Task GetReviews_ShouldReturn_ReviewsForAuthorAndMovie() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; - var movieId = fixture.Context.Movies.First(m => m.Title == "Three").Id; - var authorId = fixture.Context.Authors.First(a => a.FirstName == "Two").Id; + var movieId = this.database.Context.Movies.First(m => m.Title == "Three").Id; + var authorId = this.database.Context.Authors.First(a => a.FirstName == "Two").Id; // Act - var (items, _) = await repository.SearchReviews(movieId, authorId, 0, 50, token); + var (items, _) = await repository.GetReviews(movieId, authorId, 0, 50, token); // Assert - items.ShouldAllBe(r => r.ReviewedMovie.Id == movieId && r.ReviewAuthor.Id == authorId); + items.ShouldAllBe(r => r.ReviewedMovie!.Id == movieId && r.ReviewAuthor!.Id == authorId); } [Fact] - public async Task SearchReviews_ShouldReturn_Page() + public async Task GetReviews_ShouldReturn_Page() { // Arrange - var repository = fixture.Repository; + var repository = this.database.Repository; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; // Act - var (items, totalCount) = await repository.SearchReviews(null, null, 0, 2, token); + var (items, totalCount) = await repository.GetReviews(null, null, 0, 2, token); // Assert items.Count.ShouldBe(2); totalCount.ShouldBeGreaterThan(2); } + [Fact] + public async Task GetReviewsForMovies_ShouldReturn_ReviewsForEachMovie() + { + // Arrange + var repository = this.database.Repository; + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + var movieIds = this.database.Context.Movies.Where(m => m.Title != "Three").Select(m => m.Id).ToList(); + + // Act + var result = await repository.GetReviewsForMovies(movieIds, token); + + // Assert + result.Count.ShouldBe(6); + result.ShouldAllBe(r => movieIds.Contains(r.ReviewedMovie!.Id) && r.ReviewAuthor != null); + result.Select(r => r.ReviewAuthor!.LastName).ShouldBeInOrder(); + } + + [Fact] + public async Task GetReviewsForMovies_ShouldReturn_Empty_WhenNoMatches() + { + // Arrange + var repository = this.database.Repository; + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + // Act + var result = await repository.GetReviewsForMovies([Guid.NewGuid()], token); + + // Assert + result.ShouldBeEmpty(); + } + + [Fact] + public async Task GetReviewsForAuthors_ShouldReturn_ReviewsForEachAuthor() + { + // Arrange + var repository = this.database.Repository; + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + var authorIds = this.database.Context.Authors.Where(a => a.FirstName == "One").Select(a => a.Id).ToList(); + + // Act + var result = await repository.GetReviewsForAuthors(authorIds, token); + + // Assert + result.Count.ShouldBe(3); + result.ShouldAllBe(r => authorIds.Contains(r.ReviewAuthor!.Id) && r.ReviewedMovie != null); + result.Select(r => r.ReviewedMovie!.Title).ShouldBe(["One", "Three", "Two"]); + } + #endregion Reviews } diff --git a/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsConfigurationTests.cs b/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsConfigurationTests.cs index 817e685..8d26b6b 100644 --- a/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsConfigurationTests.cs +++ b/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsConfigurationTests.cs @@ -5,14 +5,20 @@ namespace CleanModelContextProtocol.Infrastructure.Tests.Integration.Databases.M using Shouldly; using Xunit; -[Collection("MovieReviews")] -public class MovieReviewsConfigurationTests(MovieReviewsDataFixture fixture) +public sealed class MovieReviewsConfigurationTests : IDisposable { + private readonly MovieReviewsTestDatabase database = new(); + + public void Dispose() + { + this.database.Dispose(); + } + [Fact] public async Task Database_ShouldBe_Configured() { // Arrange - var context = fixture.Context; + var context = this.database.Context; using var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; @@ -29,18 +35,18 @@ public async Task Database_ShouldBe_Configured() .FirstOrDefaultAsync(m => m.Stars == 5, token); // Assert - context.Database.IsInMemory().ShouldBeTrue(); + context.Database.IsSqlite().ShouldBeTrue(); _ = author.ShouldNotBeNull(); _ = author.Id.ShouldBeOfType(); _ = author.FirstName.ShouldBeOfType(); _ = author.LastName.ShouldBeOfType(); - _ = author.Reviews.ShouldBeOfType>(); + author.Reviews.ShouldNotBeEmpty(); _ = movie.ShouldNotBeNull(); _ = movie.Id.ShouldBeOfType(); _ = movie.Title.ShouldBeOfType(); - _ = movie.Reviews.ShouldBeOfType>(); + movie.Reviews.ShouldNotBeEmpty(); _ = review.ShouldNotBeNull(); _ = review.Id.ShouldBeOfType(); diff --git a/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsDatabaseTests.cs b/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsDatabaseTests.cs new file mode 100644 index 0000000..5fc1633 --- /dev/null +++ b/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsDatabaseTests.cs @@ -0,0 +1,50 @@ +namespace CleanModelContextProtocol.Infrastructure.Tests.Integration.Databases.MovieReviews; + +using Infrastructure.Databases.MovieReviews; +using Shouldly; +using Xunit; + +public class MovieReviewsDatabaseTests +{ + [Theory] + [InlineData("Data Source=movie-reviews.db", false)] + [InlineData("Data Source=Movies;Mode=Memory;Cache=Shared", true)] + public void IsInMemory_ShouldMatch_TheConnectionString(string connectionString, bool expected) + { + // Arrange + using var database = new MovieReviewsDatabase(connectionString); + + // Act + var result = database.IsInMemory; + + // Assert + result.ShouldBe(expected); + } + + [Fact] + public void KeepAlive_ShouldOnlyOpen_OneConnection() + { + // Arrange + using var database = new MovieReviewsDatabase($"Data Source=Tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + + // Act + database.KeepAlive(); + database.KeepAlive(); + + // Assert + database.IsInMemory.ShouldBeTrue(); + } + + [Fact] + public void KeepAlive_ShouldDoNothing_ForAFile() + { + // Arrange + using var database = new MovieReviewsDatabase("Data Source=never-created.db"); + + // Act + database.KeepAlive(); + + // Assert + File.Exists("never-created.db").ShouldBeFalse(); + } +} diff --git a/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsCollectionFixture.cs b/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsTestDatabase.cs similarity index 50% rename from tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsCollectionFixture.cs rename to tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsTestDatabase.cs index 27c747d..5940667 100644 --- a/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsCollectionFixture.cs +++ b/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsTestDatabase.cs @@ -4,54 +4,50 @@ namespace CleanModelContextProtocol.Infrastructure.Tests.Integration.Databases.M using Extensions; using Infrastructure.Databases.MovieReviews; using Infrastructure.Databases.MovieReviews.Mapping; +using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Time.Testing; -using Xunit; -[CollectionDefinition("MovieReviews")] -public class MovieReviewsCollectionFixture : ICollectionFixture +/// +/// A private in-memory database with the test data. Each test creates its own, so a test that changes the data +/// can't change what another test sees. +/// +public sealed class MovieReviewsTestDatabase : IDisposable { - // This class has no code, and is never created. Its purpose is simply - // to be the place to apply [CollectionDefinition] and all the - // ICollectionFixture<> interfaces. -} + private SqliteConnection? connection; -public class MovieReviewsDataFixture : IDisposable -{ internal MovieReviewsDbContext Context { get; set; } internal FakeTimeProvider TimeProvider { get; set; } internal EntityFrameworkMovieReviewsRepository Repository { get; set; } - public MovieReviewsDataFixture() + public MovieReviewsTestDatabase() { + // A private in-memory SQLite database that lives as long as this connection is open, + // so every test starts from the same data and nothing is written to disk. + this.connection = new SqliteConnection("Data Source=:memory:"); + this.connection.Open(); + var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase($"TestMovies-{Guid.NewGuid()}") + .UseSqlite(this.connection) + .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking) .Options; this.Context = new MovieReviewsDbContext(options); this.TimeProvider = new FakeTimeProvider(); - this.TimeProvider.SetUtcNow(new DateTime(2009, 12, 31, 23, 51, 01)); + this.TimeProvider.SetUtcNow(new DateTime(2009, 12, 31, 23, 51, 01, DateTimeKind.Utc)); this.Repository = new EntityFrameworkMovieReviewsRepository(this.Context, this.TimeProvider, new MovieReviewsMapper()); - _ = this.Context.Database.EnsureDeleted(); - _ = this.Context.Database.EnsureCreated(); + this.Context.Database.Migrate(); _ = this.Context.AddTestData(); + this.Context.ChangeTracker.Clear(); } public void Dispose() { - this.Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - if (disposing) - { - this.Context?.Dispose(); - this.Context = null; - } + this.Context.Dispose(); + this.connection?.Dispose(); + this.connection = null; } } diff --git a/tests/Infrastructure.Tests.Integration/DependencyInjectionTests.cs b/tests/Infrastructure.Tests.Integration/DependencyInjectionTests.cs new file mode 100644 index 0000000..0d1d528 --- /dev/null +++ b/tests/Infrastructure.Tests.Integration/DependencyInjectionTests.cs @@ -0,0 +1,166 @@ +namespace CleanModelContextProtocol.Infrastructure.Tests.Integration; + +using Application.Authors; +using Application.Movies; +using Application.Reviews; +using Infrastructure.Databases.MovieReviews; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Shouldly; +using Xunit; + +public class DependencyInjectionTests +{ + [Fact] + public void AddInfrastructure_ShouldRegister_ScopedRepositories() + { + // Arrange + var services = new ServiceCollection(); + + // Act + _ = services.AddInfrastructure(InMemoryConnectionString()); + + // Assert + services.Single(s => s.ServiceType == typeof(MovieReviewsDbContext)).Lifetime.ShouldBe(ServiceLifetime.Scoped); + services.Single(s => s.ServiceType == typeof(IAuthorsRepository)).Lifetime.ShouldBe(ServiceLifetime.Scoped); + services.Single(s => s.ServiceType == typeof(IMoviesRepository)).Lifetime.ShouldBe(ServiceLifetime.Scoped); + services.Single(s => s.ServiceType == typeof(IReviewsRepository)).Lifetime.ShouldBe(ServiceLifetime.Scoped); + } + + [Fact] + public void AddInfrastructure_ShouldUse_DefaultConnectionString() + { + // Arrange + var services = new ServiceCollection(); + + // Act + _ = services.AddInfrastructure(); + + using var provider = services.BuildServiceProvider(); + + // Assert + provider.GetRequiredService().ConnectionString.ShouldBe(DependencyInjection.DefaultConnectionString); + } + + [Fact] + public async Task InitialiseInfrastructure_ShouldCreate_SampleDataOnce() + { + // Arrange + var services = new ServiceCollection(); + _ = services.AddInfrastructure(InMemoryConnectionString()); + + using var provider = services.BuildServiceProvider(validateScopes: true); + + // Act + _ = provider.InitialiseInfrastructure(true); + _ = provider.InitialiseInfrastructure(true); + + // Assert + using var scope = provider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); + + (await context.Authors.CountAsync()).ShouldBe(15); + (await context.Movies.CountAsync()).ShouldBe(50); + (await context.Reviews.CountAsync()).ShouldBe(150); + } + + [Fact] + public async Task InitialiseInfrastructure_ShouldNotSeed_WhenSampleDataIsOff() + { + // Arrange + var services = new ServiceCollection(); + _ = services.AddInfrastructure(InMemoryConnectionString()); + + using var provider = services.BuildServiceProvider(validateScopes: true); + + // Act + _ = provider.InitialiseInfrastructure(false); + + // Assert + using var scope = provider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); + + (await context.Authors.CountAsync()).ShouldBe(0); + (await context.Movies.CountAsync()).ShouldBe(0); + (await context.Reviews.CountAsync()).ShouldBe(0); + } + + [Fact] + public async Task AddInfrastructureHealthChecks_ShouldReport_Healthy() + { + // Arrange + var services = new ServiceCollection(); + _ = services.AddLogging(); + _ = services.AddInfrastructure(InMemoryConnectionString()); + _ = services.AddHealthChecks().AddInfrastructureHealthChecks("ready"); + + using var provider = services.BuildServiceProvider(validateScopes: true); + _ = provider.InitialiseInfrastructure(false); + + // Act + var report = await provider.GetRequiredService().CheckHealthAsync(); + + // Assert + report.Status.ShouldBe(HealthStatus.Healthy); + report.Entries["MovieReviewsDatabase"].Tags.ShouldContain("ready"); + } + + [Fact] + public async Task InitialiseInfrastructure_ShouldCreate_TheSameSampleData() + { + // Arrange + var first = await SampleTitles(); + + // Act + var second = await SampleTitles(); + + // Assert + second.ShouldBe(first); + } + + [Fact] + public async Task Repositories_ShouldHandle_ConcurrentRequests() + { + // Arrange + var services = new ServiceCollection(); + _ = services.AddInfrastructure(InMemoryConnectionString()); + + using var provider = services.BuildServiceProvider(validateScopes: true); + _ = provider.InitialiseInfrastructure(true); + + // Act + var requests = Enumerable.Range(0, 20).Select(async _ => + { + using var scope = provider.CreateScope(); + var repository = scope.ServiceProvider.GetRequiredService(); + + return await repository.GetMovies(null, 0, 50, CancellationToken.None); + }); + + var results = await Task.WhenAll(requests); + + // Assert + results.ShouldAllBe(r => r.TotalCount == 50); + } + + private static async Task> SampleTitles() + { + var services = new ServiceCollection(); + _ = services.AddInfrastructure(InMemoryConnectionString()); + + using var provider = services.BuildServiceProvider(); + _ = provider.InitialiseInfrastructure(true); + + var (items, _) = await provider.GetRequiredService().CreateScope() + .ServiceProvider.GetRequiredService() + .GetMovies(null, 0, 50, CancellationToken.None); + + return [.. items.Select(m => m.Title)]; + } + + private static string InMemoryConnectionString() + { + return $"Data Source=Tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared"; + } +} diff --git a/tests/Infrastructure.Tests.Integration/Infrastructure.Tests.Integration.csproj b/tests/Infrastructure.Tests.Integration/Infrastructure.Tests.Integration.csproj index e84b8f1..fbbfd3f 100644 --- a/tests/Infrastructure.Tests.Integration/Infrastructure.Tests.Integration.csproj +++ b/tests/Infrastructure.Tests.Integration/Infrastructure.Tests.Integration.csproj @@ -6,15 +6,15 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs b/tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs index 0d97ccd..b2cb903 100644 --- a/tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs +++ b/tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs @@ -23,7 +23,7 @@ public class AuthenticationTests : IDisposable private static readonly SymmetricSecurityKey SigningKey = new(Encoding.UTF8.GetBytes("a-test-signing-key-that-is-long-enough-for-hs256")); private readonly ModelContextProtocolApplication application = new( - settings: new Dictionary + settings: new Dictionary { ["Authentication:Authority"] = Authority, ["Authentication:Audience"] = Audience, @@ -64,9 +64,9 @@ public async Task ResourceMetadata_ShouldReturn_AuthorizationServer() response.StatusCode.ShouldBe(HttpStatusCode.OK); using var metadata = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); - metadata.RootElement.GetProperty("resource").GetString().ShouldBe(Audience); - metadata.RootElement.GetProperty("authorization_servers")[0].GetString().ShouldBe(Authority); - metadata.RootElement.GetProperty("scopes_supported")[0].GetString().ShouldBe("mcp:tools"); + metadata.RootElement.GetProperty("resource").GetString()!.ShouldBe(Audience); + metadata.RootElement.GetProperty("authorization_servers")[0].GetString()!.ShouldBe(Authority); + metadata.RootElement.GetProperty("scopes_supported")[0].GetString()!.ShouldBe("mcp:tools"); } [Fact] diff --git a/tests/Presentation.Tests.Integration/Extensions/JsonSerializerExtensions.cs b/tests/Presentation.Tests.Integration/Extensions/JsonSerializerExtensions.cs index fb97988..8b7e991 100644 --- a/tests/Presentation.Tests.Integration/Extensions/JsonSerializerExtensions.cs +++ b/tests/Presentation.Tests.Integration/Extensions/JsonSerializerExtensions.cs @@ -19,6 +19,6 @@ public static class JsonSerializerExtensions public static T Deserialize(this string input) { - return JsonSerializer.Deserialize(input, Options); + return JsonSerializer.Deserialize(input, Options)!; } } diff --git a/tests/Presentation.Tests.Integration/Health/HealthEndpointTests.cs b/tests/Presentation.Tests.Integration/Health/HealthEndpointTests.cs new file mode 100644 index 0000000..ac2d6f9 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Health/HealthEndpointTests.cs @@ -0,0 +1,46 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Integration.Health; + +using System.Net; +using System.Threading.Tasks; +using Shouldly; +using Xunit; + +public class HealthEndpointTests : IDisposable +{ + private readonly ModelContextProtocolApplication application = new(settings: new Dictionary + { + // Health checks have to answer without a token, so they're tested with authentication on. + ["Authentication:Authority"] = "https://login.example.com", + ["Authentication:Audience"] = "https://mcp.example.com" + }); + + [Theory] + [InlineData("/health/live")] + [InlineData("/health/ready")] + public async Task GetHealth_ShouldReturn_Healthy(string path) + { + // Arrange + using var client = this.application.CreateClient(); + + // Act + using var response = await client.GetAsync(path); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).ShouldBe("Healthy"); + } + + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + this.application.Dispose(); + } + } +} diff --git a/tests/Presentation.Tests.Integration/ModelContextProtocolApplication.cs b/tests/Presentation.Tests.Integration/ModelContextProtocolApplication.cs index c64e1b8..cbcb6dd 100644 --- a/tests/Presentation.Tests.Integration/ModelContextProtocolApplication.cs +++ b/tests/Presentation.Tests.Integration/ModelContextProtocolApplication.cs @@ -7,18 +7,27 @@ namespace CleanModelContextProtocol.Presentation.Tests.Integration; internal sealed class ModelContextProtocolApplication( string environment = "local", - Dictionary settings = null, - Action configureServices = null) : WebApplicationFactory + Dictionary? settings = null, + Action? configureServices = null) : WebApplicationFactory { protected override IHost CreateHost(IHostBuilder builder) { _ = builder.UseEnvironment(environment); - if (settings is not null) + // Every application gets its own in-memory database, so tests never share or keep data. + var testSettings = new Dictionary { - _ = builder.ConfigureHostConfiguration(configuration => configuration.AddInMemoryCollection(settings)); + ["ConnectionStrings:MovieReviews"] = $"Data Source=Tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared", + ["Database:SeedSampleData"] = "true" + }; + + foreach (var setting in settings ?? []) + { + testSettings[setting.Key] = setting.Value; } + _ = builder.ConfigureHostConfiguration(configuration => configuration.AddInMemoryCollection(testSettings)); + if (configureServices is not null) { _ = builder.ConfigureServices(configureServices); diff --git a/tests/Presentation.Tests.Integration/Presentation.Tests.Integration.csproj b/tests/Presentation.Tests.Integration/Presentation.Tests.Integration.csproj index 58b1e5b..ac88b57 100644 --- a/tests/Presentation.Tests.Integration/Presentation.Tests.Integration.csproj +++ b/tests/Presentation.Tests.Integration/Presentation.Tests.Integration.csproj @@ -6,15 +6,15 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/tests/Presentation.Tests.Integration/Prompts/PromptTests.cs b/tests/Presentation.Tests.Integration/Prompts/PromptTests.cs index 2de0db4..7754b60 100644 --- a/tests/Presentation.Tests.Integration/Prompts/PromptTests.cs +++ b/tests/Presentation.Tests.Integration/Prompts/PromptTests.cs @@ -35,7 +35,7 @@ public async Task SummariseMovieReception_ShouldEmbed_Movie() // Act var result = await this.Client.GetPromptAsync("summarise_movie_reception", - new Dictionary { ["movieTitle"] = movie.Title.ToUpperInvariant() }); + new Dictionary { ["movieTitle"] = movie.Title.ToUpperInvariant() }); // Assert result.Messages.Count.ShouldBe(2); @@ -49,7 +49,7 @@ public async Task SummariseMovieReception_WithUnknownTitle_ShouldAsk_ToSearch() { // Act var result = await this.Client.GetPromptAsync("summarise_movie_reception", - new Dictionary { ["movieTitle"] = "No Such Movie" }); + new Dictionary { ["movieTitle"] = "No Such Movie" }); // Assert var message = result.Messages.ShouldHaveSingleItem(); @@ -61,7 +61,7 @@ public async Task SummariseMovieReception_WithLongTitle_ShouldThrow_InvalidParam { // Act var exception = await Should.ThrowAsync(() => this.Client.GetPromptAsync("summarise_movie_reception", - new Dictionary { ["movieTitle"] = new string('a', 101) }).AsTask()); + new Dictionary { ["movieTitle"] = new string('a', 101) }).AsTask()); // Assert exception.ErrorCode.ShouldBe(McpErrorCode.InvalidParams); @@ -72,10 +72,10 @@ public async Task CompareMovies_ShouldEmbed_BothMovies() { // Arrange var movies = (await this.CallAsync>("movies_search", - new Dictionary { ["limit"] = 2 })).Items; + new Dictionary { ["limit"] = 2 })).Items; // Act - var result = await this.Client.GetPromptAsync("compare_movies", new Dictionary + var result = await this.Client.GetPromptAsync("compare_movies", new Dictionary { ["firstMovieTitle"] = movies[0].Title, ["secondMovieTitle"] = movies[1].Title @@ -91,7 +91,7 @@ public async Task CompareMovies_ShouldEmbed_BothMovies() public async Task ReviewMovie_ShouldReturn_Instructions() { // Act - var result = await this.Client.GetPromptAsync("review_movie", new Dictionary + var result = await this.Client.GetPromptAsync("review_movie", new Dictionary { ["movieTitle"] = "Some Movie", ["authorName"] = "Some Author" @@ -106,7 +106,7 @@ public async Task ReviewMovie_ShouldReturn_Instructions() private async Task FirstMovieAsync() { - return (await this.CallAsync>("movies_search", new Dictionary { ["limit"] = 50 })) + return (await this.CallAsync>("movies_search", new Dictionary { ["limit"] = 50 })) .Items.First(m => m.ReviewCount > 0); } @@ -118,6 +118,6 @@ private static void ShouldEmbed(PromptMessage message, MovieResult movie) var embedded = resource.Text.Deserialize(); embedded.Id.ShouldBe(movie.Id); - embedded.Reviews.Count.ShouldBe(movie.ReviewCount); + embedded.Reviews.ShouldNotBeNull().Count.ShouldBe(movie.ReviewCount); } } diff --git a/tests/Presentation.Tests.Integration/Resources/ResourceTests.cs b/tests/Presentation.Tests.Integration/Resources/ResourceTests.cs index ceb1a5d..c057fb3 100644 --- a/tests/Presentation.Tests.Integration/Resources/ResourceTests.cs +++ b/tests/Presentation.Tests.Integration/Resources/ResourceTests.cs @@ -49,7 +49,7 @@ public async Task ReadMovie_ShouldReturn_MovieWithReviews() { // Arrange var first = (await this.CallAsync>("movies_search", - new Dictionary { ["limit"] = 50 })).Items.First(m => m.ReviewCount > 0); + new Dictionary { ["limit"] = 50 })).Items.First(m => m.ReviewCount > 0); // Act var movie = await this.ReadAsync($"movies://{first.Id}"); @@ -57,7 +57,7 @@ public async Task ReadMovie_ShouldReturn_MovieWithReviews() // Assert movie.Id.ShouldBe(first.Id); movie.Title.ShouldBe(first.Title); - movie.Reviews.Count.ShouldBe(first.ReviewCount); + movie.Reviews.ShouldNotBeNull().Count.ShouldBe(first.ReviewCount); } [Fact] @@ -72,7 +72,7 @@ public async Task ReadAuthor_ShouldReturn_AuthorWithReviews() // Assert author.Id.ShouldBe(first.Id); author.Name.ShouldBe(first.Name); - author.Reviews.Count.ShouldBe(first.ReviewCount); + author.Reviews.ShouldNotBeNull().Count.ShouldBe(first.ReviewCount); } [Fact] diff --git a/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs b/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs index cd08e11..b72012f 100644 --- a/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs @@ -10,12 +10,12 @@ public class AuthorToolTests : BaseToolTests public async Task SearchAuthors_ShouldReturn_EveryAuthor() { // Act - var page = await this.CallAsync>("authors_search", new Dictionary { ["limit"] = 50 }); + var page = await this.CallAsync>("authors_search", new Dictionary { ["limit"] = 50 }); // Assert page.TotalCount.ShouldBe(15); page.Items.Count.ShouldBe(15); - page.NextCursor.ShouldBeNull(); + page.NextOffset.ShouldBeNull(); foreach (var author in page.Items) { @@ -33,12 +33,12 @@ public async Task SearchAuthors_ShouldFind_AuthorByFullName() // Act var page = await this.CallAsync>("authors_search", - new Dictionary { ["query"] = first.Name.ToLowerInvariant(), ["includeReviews"] = true }); + new Dictionary { ["query"] = first.Name.ToLowerInvariant(), ["includeReviews"] = true }); // Assert var author = page.Items.ShouldHaveSingleItem(); author.Id.ShouldBe(first.Id); - author.Reviews.Count.ShouldBe(author.ReviewCount); + author.Reviews.ShouldNotBeNull().Count.ShouldBe(author.ReviewCount); author.Reviews.ShouldAllBe(r => r.AuthorId == author.Id && r.AuthorName == author.Name && r.MovieTitle != null); } @@ -46,7 +46,7 @@ public async Task SearchAuthors_ShouldFind_AuthorByFullName() public async Task SearchAuthors_WithLongQuery_ShouldReturn_ValidationError() { // Act - var text = await this.CallForErrorAsync("authors_search", new Dictionary { ["query"] = new string('a', 101) }); + var text = await this.CallForErrorAsync("authors_search", new Dictionary { ["query"] = new string('a', 101) }); // Assert text.ShouldBe("Validation Failed: Query: A search term can't be longer than 100 characters. Correct the arguments and call the tool again."); diff --git a/tests/Presentation.Tests.Integration/Tools/BaseToolTests.cs b/tests/Presentation.Tests.Integration/Tools/BaseToolTests.cs index 7b14bce..38b270b 100644 --- a/tests/Presentation.Tests.Integration/Tools/BaseToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/BaseToolTests.cs @@ -15,7 +15,7 @@ public abstract class BaseToolTests : IAsyncLifetime, IAsyncDisposable protected McpClient Client { get; private set; } #pragma warning restore CS8618 - protected async Task CallAsync(string name, Dictionary arguments = null) + protected async Task CallAsync(string name, Dictionary? arguments = null) { var result = await this.Client.CallToolAsync(name, arguments); @@ -24,7 +24,7 @@ protected async Task CallAsync(string name, Dictionary arg return result.Content.OfType().First().Text.Deserialize(); } - protected async Task CallForErrorAsync(string name, Dictionary arguments) + protected async Task CallForErrorAsync(string name, Dictionary arguments) { var result = await this.Client.CallToolAsync(name, arguments); diff --git a/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs b/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs index 6ee1f8f..01db14b 100644 --- a/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs @@ -16,7 +16,7 @@ public async Task SearchMovies_ShouldReturn_FirstPage() // Assert page.TotalCount.ShouldBe(50); page.Items.Count.ShouldBe(10); - page.NextCursor.ShouldNotBeNullOrWhiteSpace(); + page.NextOffset.ShouldBe(10); page.Items.Select(m => m.Title).ShouldBeInOrder(SortDirection.Ascending, StringComparer.CurrentCulture); foreach (var movie in page.Items) @@ -37,24 +37,19 @@ public async Task SearchMovies_ShouldPage_ThroughEveryMovie() { // Arrange var titles = new List(); - string cursor = null; + int? offset = 0; // Act do { - var arguments = new Dictionary { ["limit"] = 20 }; - - if (cursor is not null) - { - arguments["cursor"] = cursor; - } + var arguments = new Dictionary { ["limit"] = 20, ["offset"] = offset }; var page = await this.CallAsync>("movies_search", arguments); titles.AddRange(page.Items.Select(m => m.Title)); - cursor = page.NextCursor; + offset = page.NextOffset; } - while (cursor is not null); + while (offset is not null); // Assert titles.Count.ShouldBe(50); @@ -68,32 +63,32 @@ public async Task SearchMovies_ShouldFind_MovieByTitle() // Act var page = await this.CallAsync>("movies_search", - new Dictionary { ["query"] = first.Title.ToUpperInvariant(), ["includeReviews"] = true }); + new Dictionary { ["query"] = first.Title.ToUpperInvariant(), ["includeReviews"] = true }); // Assert page.Items.ShouldContain(m => m.Id == first.Id); page.Items.ShouldAllBe(m => m.Title.Contains(first.Title, StringComparison.OrdinalIgnoreCase)); - page.Items.ShouldAllBe(m => m.Reviews != null && m.Reviews.Count == m.ReviewCount); + page.Items.ShouldAllBe(m => m.Reviews != null && m.Reviews!.Count == m.ReviewCount); } [Fact] public async Task SearchMovies_WithInvalidLimit_ShouldReturn_ValidationError() { // Act - var text = await this.CallForErrorAsync("movies_search", new Dictionary { ["limit"] = 500 }); + var text = await this.CallForErrorAsync("movies_search", new Dictionary { ["limit"] = 500 }); // Assert text.ShouldBe("Validation Failed: Limit: A limit must be between 1 and 50. Correct the arguments and call the tool again."); } [Fact] - public async Task SearchMovies_WithInvalidCursor_ShouldReturn_ValidationError() + public async Task SearchMovies_WithNegativeOffset_ShouldReturn_ValidationError() { // Act - var text = await this.CallForErrorAsync("movies_search", new Dictionary { ["cursor"] = "nope" }); + var text = await this.CallForErrorAsync("movies_search", new Dictionary { ["offset"] = -1 }); // Assert - text.ShouldStartWith("Validation Failed: Cursor: The cursor is not valid."); + text.ShouldStartWith("Validation Failed: Offset: An offset can't be negative."); } [Fact] @@ -101,19 +96,19 @@ public async Task GetMovie_ShouldReturn_MovieWithReviews() { // Arrange var first = (await this.CallAsync>("movies_search", - new Dictionary { ["limit"] = 50 })).Items.First(m => m.ReviewCount > 0); + new Dictionary { ["limit"] = 50 })).Items.First(m => m.ReviewCount > 0); // Act - var movie = await this.CallAsync("movies_get", new Dictionary { ["movieId"] = first.Id }); + var movie = await this.CallAsync("movies_get", new Dictionary { ["movieId"] = first.Id }); // Assert movie.Id.ShouldBe(first.Id); movie.Title.ShouldBe(first.Title); movie.ReviewCount.ShouldBe(first.ReviewCount); movie.AverageStars.ShouldBe(first.AverageStars); - movie.Reviews.Count.ShouldBe(movie.ReviewCount); + movie.Reviews.ShouldNotBeNull().Count.ShouldBe(movie.ReviewCount); - foreach (var review in movie.Reviews) + foreach (var review in movie.Reviews.ShouldNotBeNull()) { review.Stars.ShouldBeInRange(1, 5); review.MovieId.ShouldBe(movie.Id); @@ -127,7 +122,7 @@ public async Task GetMovie_ShouldReturn_MovieWithReviews() public async Task GetMovie_WithEmptyId_ShouldReturn_ValidationError() { // Act - var text = await this.CallForErrorAsync("movies_get", new Dictionary { ["movieId"] = Guid.Empty }); + var text = await this.CallForErrorAsync("movies_get", new Dictionary { ["movieId"] = Guid.Empty }); // Assert text.ShouldBe("Validation Failed: Id: A Movie Id was not supplied. Correct the arguments and call the tool again."); @@ -137,7 +132,7 @@ public async Task GetMovie_WithEmptyId_ShouldReturn_ValidationError() public async Task GetMovie_WithUnknownId_ShouldReturn_NotFoundError() { // Act - var text = await this.CallForErrorAsync("movies_get", new Dictionary { ["movieId"] = Guid.NewGuid() }); + var text = await this.CallForErrorAsync("movies_get", new Dictionary { ["movieId"] = Guid.NewGuid() }); // Assert text.ShouldBe("Not Found: The Movie with the supplied id was not found. Check the ids: movies_search, authors_search and reviews_list return valid ones."); @@ -152,7 +147,7 @@ public async Task GetMovie_WithInvalidId_ShouldReturn_Error(string input) { // Act var result = await this.Client.CallToolAsync("movies_get", - new Dictionary { ["movieId"] = input }); + new Dictionary { ["movieId"] = input }); // Assert result.IsError.ShouldBe(true); diff --git a/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs b/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs index cd3b7f9..e0d45d6 100644 --- a/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs @@ -23,7 +23,7 @@ public async Task ListReviews_ShouldReturn_FirstPage() // Assert page.TotalCount.ShouldBe(150); page.Items.Count.ShouldBe(10); - page.NextCursor.ShouldNotBeNull(); + page.NextOffset.ShouldNotBeNull(); foreach (var review in page.Items) { @@ -38,14 +38,14 @@ public async Task ListReviews_ShouldFilter_ByMovieAndAuthor() { // Arrange var movie = (await this.CallAsync>("movies_search", - new Dictionary { ["limit"] = 50 })).Items.First(m => m.ReviewCount > 0); - var review = (await this.CallAsync("movies_get", new Dictionary { ["movieId"] = movie.Id })).Reviews[0]; + new Dictionary { ["limit"] = 50 })).Items.First(m => m.ReviewCount > 0); + var review = (await this.CallAsync("movies_get", new Dictionary { ["movieId"] = movie.Id })).Reviews.ShouldNotBeNull()[0]; // Act var byMovie = await this.CallAsync>("reviews_list", - new Dictionary { ["movieId"] = movie.Id, ["limit"] = 50 }); + new Dictionary { ["movieId"] = movie.Id, ["limit"] = 50 }); var byBoth = await this.CallAsync>("reviews_list", - new Dictionary { ["movieId"] = movie.Id, ["authorId"] = review.AuthorId }); + new Dictionary { ["movieId"] = movie.Id, ["authorId"] = review.AuthorId }); // Assert byMovie.TotalCount.ShouldBe(movie.ReviewCount); @@ -61,7 +61,7 @@ public async Task ListReviews_ShouldReturn_OneReview() var first = (await this.CallAsync>("reviews_list")).Items[0]; // Act - var page = await this.CallAsync>("reviews_list", new Dictionary { ["reviewId"] = first.Id }); + var page = await this.CallAsync>("reviews_list", new Dictionary { ["reviewId"] = first.Id }); // Assert page.TotalCount.ShouldBe(1); @@ -72,7 +72,7 @@ public async Task ListReviews_ShouldReturn_OneReview() public async Task ListReviews_WithUnknownReviewId_ShouldReturn_NotFoundError() { // Act - var text = await this.CallForErrorAsync("reviews_list", new Dictionary { ["reviewId"] = Guid.NewGuid() }); + var text = await this.CallForErrorAsync("reviews_list", new Dictionary { ["reviewId"] = Guid.NewGuid() }); // Assert text.ShouldBe("Not Found: The Review with the supplied id was not found. Check the ids: movies_search, authors_search and reviews_list return valid ones."); @@ -82,7 +82,7 @@ public async Task ListReviews_WithUnknownReviewId_ShouldReturn_NotFoundError() public async Task ListReviews_WithEmptyMovieId_ShouldReturn_ValidationError() { // Act - var text = await this.CallForErrorAsync("reviews_list", new Dictionary { ["movieId"] = Guid.Empty }); + var text = await this.CallForErrorAsync("reviews_list", new Dictionary { ["movieId"] = Guid.Empty }); // Assert text.ShouldStartWith("Validation Failed: MovieId: A Movie Id can't be empty."); @@ -96,7 +96,7 @@ public async Task WriteReview_ShouldCreate_Review() // Act var review = await this.CallAsync("reviews_write", - new Dictionary { ["movieId"] = movie.Id, ["authorId"] = author.Id, ["stars"] = 5 }); + new Dictionary { ["movieId"] = movie.Id, ["authorId"] = author.Id, ["stars"] = 5 }); // Assert review.Id.ShouldNotBe(Guid.Empty); @@ -106,26 +106,39 @@ public async Task WriteReview_ShouldCreate_Review() review.AuthorId.ShouldBe(author.Id); review.AuthorName.ShouldBe(author.Name); - var after = await this.CallAsync("movies_get", new Dictionary { ["movieId"] = movie.Id }); + var after = await this.CallAsync("movies_get", new Dictionary { ["movieId"] = movie.Id }); after.ReviewCount.ShouldBe(movie.ReviewCount + 1); } [Fact] - public async Task WriteReview_ShouldUpdate_Review() + public async Task WriteReview_ShouldUpdate_OnlyTheStars() { // Arrange var (movie, author) = await this.FirstMovieAndAuthor(); var existing = (await this.CallAsync>("reviews_list")).Items[0]; + var stars = existing.Stars == 5 ? 1 : existing.Stars + 1; // Act var review = await this.CallAsync("reviews_write", - new Dictionary { ["reviewId"] = existing.Id, ["movieId"] = movie.Id, ["authorId"] = author.Id, ["stars"] = 1 }); + new Dictionary { ["reviewId"] = existing.Id, ["movieId"] = movie.Id, ["authorId"] = author.Id, ["stars"] = stars }); // Assert review.Id.ShouldBe(existing.Id); - review.Stars.ShouldBe(1); - review.MovieId.ShouldBe(movie.Id); - review.AuthorId.ShouldBe(author.Id); + review.Stars.ShouldBe(stars); + review.MovieId.ShouldBe(existing.MovieId); + review.AuthorId.ShouldBe(existing.AuthorId); + } + + [Fact] + public async Task WriteReview_WithoutMovieOrAuthor_ShouldReturn_ValidationError() + { + // Act + var text = await this.CallForErrorAsync("reviews_write", new Dictionary { ["stars"] = 3 }); + + // Assert + text.ShouldStartWith("Validation Failed:"); + text.ShouldContain("AuthorId"); + text.ShouldContain("MovieId"); } [Fact] @@ -136,7 +149,7 @@ public async Task WriteReview_WithInvalidStars_ShouldReturn_ValidationError() // Act var text = await this.CallForErrorAsync("reviews_write", - new Dictionary { ["movieId"] = movie.Id, ["authorId"] = author.Id, ["stars"] = 9 }); + new Dictionary { ["movieId"] = movie.Id, ["authorId"] = author.Id, ["stars"] = 9 }); // Assert text.ShouldBe("Validation Failed: Stars: A star rating must be between 1 and 5. Correct the arguments and call the tool again."); @@ -150,7 +163,7 @@ public async Task WriteReview_WithUnknownReviewId_ShouldReturn_NotFoundError() // Act var text = await this.CallForErrorAsync("reviews_write", - new Dictionary { ["reviewId"] = Guid.NewGuid(), ["movieId"] = movie.Id, ["authorId"] = author.Id, ["stars"] = 3 }); + new Dictionary { ["reviewId"] = Guid.NewGuid(), ["movieId"] = movie.Id, ["authorId"] = author.Id, ["stars"] = 3 }); // Assert text.ShouldStartWith("Not Found:"); @@ -163,13 +176,13 @@ public async Task DeleteReview_ShouldDelete_Review() var existing = (await this.CallAsync>("reviews_list")).Items[0]; // Act - var result = await this.CallAsync("reviews_delete", new Dictionary { ["reviewId"] = existing.Id }); + var result = await this.CallAsync("reviews_delete", new Dictionary { ["reviewId"] = existing.Id }); // Assert result.ReviewId.ShouldBe(existing.Id); result.Deleted.ShouldBeTrue(); - var text = await this.CallForErrorAsync("reviews_list", new Dictionary { ["reviewId"] = existing.Id }); + var text = await this.CallForErrorAsync("reviews_list", new Dictionary { ["reviewId"] = existing.Id }); text.ShouldStartWith("Not Found:"); } @@ -177,7 +190,7 @@ public async Task DeleteReview_ShouldDelete_Review() public async Task DeleteReview_WithUnknownId_ShouldReturn_NotFoundError() { // Act - var text = await this.CallForErrorAsync("reviews_delete", new Dictionary { ["reviewId"] = Guid.NewGuid() }); + var text = await this.CallForErrorAsync("reviews_delete", new Dictionary { ["reviewId"] = Guid.NewGuid() }); // Assert text.ShouldStartWith("Not Found: The Review with the supplied id was not found."); diff --git a/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs b/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs index 8db359b..1c86ba8 100644 --- a/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs @@ -60,7 +60,7 @@ public async Task ServerInfo_ShouldDescribe_Server() // Assert var serverInfo = this.Client.ServerInfo; - serverInfo.Name.ShouldBe("clean-model-context-protocol"); + serverInfo.ShouldNotBeNull().Name.ShouldBe("clean-model-context-protocol"); serverInfo.Title.ShouldBe("Clean Model Context Protocol"); this.Client.ServerInstructions.ShouldNotBeNullOrWhiteSpace(); diff --git a/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs b/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs index 321813b..214d00e 100644 --- a/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs +++ b/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs @@ -26,7 +26,7 @@ public void FromConfiguration_ShouldReturn_EnabledSettings_WhenAuthorityIsSet() { // Arrange var configuration = new ConfigurationBuilder() - .AddInMemoryCollection(new Dictionary + .AddInMemoryCollection(new Dictionary { ["Authentication:Authority"] = "https://login.example.com", ["Authentication:Audience"] = "https://localhost:5001", diff --git a/tests/Presentation.Tests.Unit/Presentation.Tests.Unit.csproj b/tests/Presentation.Tests.Unit/Presentation.Tests.Unit.csproj index 3a4cdc7..d998f2e 100644 --- a/tests/Presentation.Tests.Unit/Presentation.Tests.Unit.csproj +++ b/tests/Presentation.Tests.Unit/Presentation.Tests.Unit.csproj @@ -6,15 +6,15 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs b/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs index 39dd438..73352c5 100644 --- a/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs +++ b/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs @@ -18,18 +18,18 @@ public async Task SearchAuthors_ShouldReturn_ConcisePage() { // Arrange var sender = Substitute.For(); - var author = new Entities.Author(Guid.Empty, "Lorem", "Ipsum", [new Review(Guid.Empty, 4, new ReviewedMovie(Guid.Empty, "Dolor"))]); + var author = new Entities.AuthorSummary(Guid.Empty, "Lorem", "Ipsum", 1, 4); _ = sender - .Send(Arg.Is(q => q.Query == "lorem" && q.Limit == 10 && q.Cursor == null)) - .Returns(new Page([author], 1)); + .Send(Arg.Is(q => q.Query == "lorem" && q.Offset == 0 && q.Limit == 10)) + .Returns(new Page([author], 0, 10, 1)); // Act - var response = await AuthorTools.SearchAuthors(sender, "lorem"); + var response = await AuthorTools.SearchAuthors(sender, CancellationToken.None, "lorem"); // Assert response.TotalCount.ShouldBe(1); - response.NextCursor.ShouldBeNull(); + response.NextOffset.ShouldBeNull(); response.Items[0].Name.ShouldBe("Lorem Ipsum"); response.Items[0].ReviewCount.ShouldBe(1); response.Items[0].AverageStars.ShouldBe(4); @@ -41,18 +41,39 @@ public async Task SearchAuthors_ShouldReturn_Reviews() { // Arrange var sender = Substitute.For(); - var author = new Entities.Author(Guid.Empty, "Lorem", "Ipsum", [new Review(Guid.Empty, 4, new ReviewedMovie(Guid.Empty, "Dolor"))]); + var author = new Entities.AuthorSummary(Guid.Empty, "Lorem", "Ipsum", 1, 4); _ = sender - .Send(Arg.Any()) - .ReturnsForAnyArgs(new Page([author], 1)); + .Send(Arg.Any()) + .ReturnsForAnyArgs(new Page([author], 0, 10, 1)); + _ = sender + .Send(Arg.Is(q => q.AuthorIds.Single() == Guid.Empty)) + .Returns(new Dictionary> { [Guid.Empty] = [new Review(Guid.Empty, 4, new ReviewedMovie(Guid.Empty, "Dolor"))] }); + + // Act + var response = await AuthorTools.SearchAuthors(sender, CancellationToken.None, includeReviews: true); + + // Assert + response.Items[0].Reviews.ShouldNotBeNull().Count.ShouldBe(1); + response.Items[0].Reviews![0].MovieTitle.ShouldBe("Dolor"); + response.Items[0].Reviews![0].AuthorName.ShouldBe("Lorem Ipsum"); + } + + [Fact] + public async Task SearchAuthors_ShouldSkip_Reviews_WhenPageIsEmpty() + { + // Arrange + var sender = Substitute.For(); + + _ = sender + .Send(Arg.Any()) + .ReturnsForAnyArgs(new Page([], 0, 10, 0)); // Act - var response = await AuthorTools.SearchAuthors(sender, includeReviews: true); + var response = await AuthorTools.SearchAuthors(sender, CancellationToken.None, "missing", includeReviews: true); // Assert - response.Items[0].Reviews.Count.ShouldBe(1); - response.Items[0].Reviews[0].MovieTitle.ShouldBe("Dolor"); - response.Items[0].Reviews[0].AuthorName.ShouldBe("Lorem Ipsum"); + response.Items.ShouldBeEmpty(); + _ = await sender.DidNotReceive().Send(Arg.Any(), Arg.Any()); } } diff --git a/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs b/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs index e286179..f261a45 100644 --- a/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs +++ b/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs @@ -31,21 +31,22 @@ public async Task SearchMovies_ShouldReturn_ConcisePage() var sender = Substitute.For(); _ = sender - .Send(Arg.Is(q => q.Query == "lorem" && q.Limit == 5 && q.Cursor == "abc")) - .Returns(new Page([SampleMovie()], 7, "next")); + .Send(Arg.Is(q => q.Query == "lorem" && q.Offset == 5 && q.Limit == 1)) + .Returns(new Page([new Entities.MovieSummary(MovieId, "Lorem Ipsum", 2, 3.5)], 5, 1, 7)); // Act - var response = await MovieTools.SearchMovies(sender, "lorem", 5, "abc"); + var response = await MovieTools.SearchMovies(sender, CancellationToken.None, "lorem", 5, 1); // Assert response.TotalCount.ShouldBe(7); - response.NextCursor.ShouldBe("next"); + response.NextOffset.ShouldBe(6); response.Items.Count.ShouldBe(1); response.Items[0].Id.ShouldBe(MovieId); response.Items[0].Title.ShouldBe("Lorem Ipsum"); response.Items[0].ReviewCount.ShouldBe(2); response.Items[0].AverageStars.ShouldBe(3.5); response.Items[0].Reviews.ShouldBeNull(); + _ = await sender.DidNotReceive().Send(Arg.Any(), Arg.Any()); } [Fact] @@ -55,21 +56,43 @@ public async Task SearchMovies_ShouldReturn_Reviews() var sender = Substitute.For(); _ = sender - .Send(Arg.Any()) - .ReturnsForAnyArgs(new Page([SampleMovie(), new Entities.Movie(Guid.Empty, "Empty")], 2)); + .Send(Arg.Any()) + .ReturnsForAnyArgs(new Page( + [new Entities.MovieSummary(MovieId, "Lorem Ipsum", 2, 3.5), new Entities.MovieSummary(Guid.Empty, "Empty", 0, null)], 0, 10, 2)); + _ = sender + .Send(Arg.Is(q => q.MovieIds.SequenceEqual(new[] { MovieId, Guid.Empty }))) + .Returns(new Dictionary> { [MovieId] = [.. SampleMovie().Reviews], [Guid.Empty] = [] }); // Act - var response = await MovieTools.SearchMovies(sender, includeReviews: true); + var response = await MovieTools.SearchMovies(sender, CancellationToken.None, includeReviews: true); // Assert - response.Items[0].Reviews.Count.ShouldBe(2); - response.Items[0].Reviews[0].MovieTitle.ShouldBe("Lorem Ipsum"); - response.Items[0].Reviews[0].AuthorName.ShouldBe("Dolor Sit"); + response.Items[0].Reviews.ShouldNotBeNull().Count.ShouldBe(2); + response.Items[0].Reviews![0].MovieTitle.ShouldBe("Lorem Ipsum"); + response.Items[0].Reviews![0].AuthorName.ShouldBe("Dolor Sit"); response.Items[1].ReviewCount.ShouldBe(0); response.Items[1].AverageStars.ShouldBeNull(); response.Items[1].Reviews.ShouldBeEmpty(); } + [Fact] + public async Task SearchMovies_ShouldSkip_Reviews_WhenPageIsEmpty() + { + // Arrange + var sender = Substitute.For(); + + _ = sender + .Send(Arg.Any()) + .ReturnsForAnyArgs(new Page([], 0, 10, 0)); + + // Act + var response = await MovieTools.SearchMovies(sender, CancellationToken.None, "missing", includeReviews: true); + + // Assert + response.Items.ShouldBeEmpty(); + _ = await sender.DidNotReceive().Send(Arg.Any(), Arg.Any()); + } + [Fact] public async Task GetMovie_ShouldReturn_MovieWithReviews() { @@ -81,14 +104,14 @@ public async Task GetMovie_ShouldReturn_MovieWithReviews() .Returns(SampleMovie()); // Act - var response = await MovieTools.GetMovie(sender, MovieId); + var response = await MovieTools.GetMovie(sender, MovieId, CancellationToken.None); // Assert response.Id.ShouldBe(MovieId); response.AverageStars.ShouldBe(3.5); - response.Reviews.Count.ShouldBe(2); - response.Reviews[1].Stars.ShouldBe(2); - response.Reviews[1].MovieId.ShouldBe(MovieId); - response.Reviews[1].AuthorName.ShouldBe("Amet Elit"); + response.Reviews.ShouldNotBeNull().Count.ShouldBe(2); + response.Reviews![1].Stars.ShouldBe(2); + response.Reviews![1].MovieId.ShouldBe(MovieId); + response.Reviews![1].AuthorName.ShouldBe("Amet Elit"); } } diff --git a/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs b/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs index 7a94c5b..f1603a7 100644 --- a/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs +++ b/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs @@ -30,15 +30,15 @@ public async Task ListReviews_ShouldReturn_Page() var sender = Substitute.For(); _ = sender - .Send(Arg.Is(q => q.MovieId == MovieId && q.AuthorId == AuthorId && q.Limit == 2 && q.Cursor == "abc")) - .Returns(new Page([SampleReview()], 3, "next")); + .Send(Arg.Is(q => q.MovieId == MovieId && q.AuthorId == AuthorId && q.Offset == 2 && q.Limit == 1)) + .Returns(new Page([SampleReview()], 2, 1, 3)); // Act - var response = await ReviewTools.ListReviews(sender, MovieId, AuthorId, null, 2, "abc"); + var response = await ReviewTools.ListReviews(sender, CancellationToken.None, MovieId, AuthorId, null, 2, 1); // Assert response.TotalCount.ShouldBe(3); - response.NextCursor.ShouldBe("next"); + response.NextOffset.ShouldBeNull(); response.Items[0].Id.ShouldBe(ReviewId); response.Items[0].Stars.ShouldBe(5); response.Items[0].MovieId.ShouldBe(MovieId); @@ -58,13 +58,13 @@ public async Task ListReviews_ShouldReturn_OneReview() .Returns(SampleReview()); // Act - var response = await ReviewTools.ListReviews(sender, reviewId: ReviewId); + var response = await ReviewTools.ListReviews(sender, CancellationToken.None, reviewId: ReviewId); // Assert response.TotalCount.ShouldBe(1); - response.NextCursor.ShouldBeNull(); + response.NextOffset.ShouldBeNull(); response.Items.Single().Id.ShouldBe(ReviewId); - _ = await sender.DidNotReceive().Send(Arg.Any()); + _ = await sender.DidNotReceive().Send(Arg.Any()); } [Fact] @@ -78,7 +78,7 @@ public async Task WriteReview_ShouldCreate_Review() .Returns(SampleReview(4)); // Act - var response = await ReviewTools.WriteReview(sender, MovieId, AuthorId, 4); + var response = await ReviewTools.WriteReview(sender, 4, CancellationToken.None, MovieId, AuthorId); // Assert response.Id.ShouldBe(ReviewId); @@ -87,13 +87,31 @@ public async Task WriteReview_ShouldCreate_Review() } [Fact] - public async Task WriteReview_ShouldUpdate_Review() + public async Task WriteReview_ShouldSend_EmptyIds_WhenMovieAndAuthorAreMissing() { // Arrange var sender = Substitute.For(); _ = sender - .Send(Arg.Is(c => c.Id == ReviewId && c.MovieId == MovieId && c.AuthorId == AuthorId && c.Stars == 2)) + .Send(Arg.Is(c => c.MovieId == Guid.Empty && c.AuthorId == Guid.Empty && c.Stars == 4)) + .Returns(SampleReview(4)); + + // Act + var response = await ReviewTools.WriteReview(sender, 4, CancellationToken.None); + + // Assert + response.Stars.ShouldBe(4); + _ = await sender.Received(1).Send(Arg.Any()); + } + + [Fact] + public async Task WriteReview_ShouldUpdate_OnlyTheStars() + { + // Arrange + var sender = Substitute.For(); + + _ = sender + .Send(Arg.Is(c => c.Id == ReviewId && c.Stars == 2)) .Returns(true); _ = sender @@ -101,7 +119,7 @@ public async Task WriteReview_ShouldUpdate_Review() .Returns(SampleReview(2)); // Act - var response = await ReviewTools.WriteReview(sender, MovieId, AuthorId, 2, ReviewId); + var response = await ReviewTools.WriteReview(sender, 2, CancellationToken.None, reviewId: ReviewId); // Assert response.Id.ShouldBe(ReviewId); @@ -120,7 +138,7 @@ public async Task DeleteReview_ShouldReturn_Result() .Returns(true); // Act - var response = await ReviewTools.DeleteReview(sender, ReviewId); + var response = await ReviewTools.DeleteReview(sender, ReviewId, CancellationToken.None); // Assert response.ReviewId.ShouldBe(ReviewId);