diff --git a/.editorconfig b/.editorconfig index 06296de..2242bb5 100644 --- a/.editorconfig +++ b/.editorconfig @@ -37,4 +37,65 @@ csharp_style_pattern_matching_over_is_with_cast_check = true csharp_style_pattern_matching_over_as_with_null_check = true csharp_style_inlined_variable_declaration = true csharp_style_var_for_built_in_types = true -csharp_style_var_when_type_is_apparent = true \ No newline at end of file +csharp_style_var_when_type_is_apparent = true +csharp_style_var_elsewhere = true + +# Namespaces & usings +csharp_style_namespace_declarations = file_scoped +csharp_using_directive_placement = outside_namespace + +# Qualification & accessibility +dotnet_style_qualification_for_field = false +dotnet_style_qualification_for_property = false +dotnet_style_qualification_for_method = false +dotnet_style_qualification_for_event = false +dotnet_style_require_accessibility_modifiers = for_non_interface_members +dotnet_style_readonly_field = true + +# Modern expressions & initializers +dotnet_style_coalesce_expression = true +dotnet_style_null_propagation = true +dotnet_style_object_initializer = true +dotnet_style_collection_initializer = true +dotnet_style_prefer_auto_properties = true +csharp_prefer_simple_using_statement = true +csharp_style_prefer_collection_expression = true + +# Naming: private instance fields -> _camelCase +dotnet_naming_rule.private_instance_fields.symbols = private_instance_fields +dotnet_naming_rule.private_instance_fields.style = underscore_camel_case +dotnet_naming_rule.private_instance_fields.severity = suggestion +dotnet_naming_symbols.private_instance_fields.applicable_kinds = field +dotnet_naming_symbols.private_instance_fields.applicable_accessibilities = private + +# Naming: private const fields -> PascalCase +dotnet_naming_rule.private_const_fields.symbols = private_const_fields +dotnet_naming_rule.private_const_fields.style = pascal_case +dotnet_naming_rule.private_const_fields.severity = suggestion +dotnet_naming_symbols.private_const_fields.applicable_kinds = field +dotnet_naming_symbols.private_const_fields.applicable_accessibilities = private +dotnet_naming_symbols.private_const_fields.required_modifiers = const + +# Naming: private static readonly fields -> PascalCase +dotnet_naming_rule.private_static_readonly_fields.symbols = private_static_readonly_fields +dotnet_naming_rule.private_static_readonly_fields.style = pascal_case +dotnet_naming_rule.private_static_readonly_fields.severity = suggestion +dotnet_naming_symbols.private_static_readonly_fields.applicable_kinds = field +dotnet_naming_symbols.private_static_readonly_fields.applicable_accessibilities = private +dotnet_naming_symbols.private_static_readonly_fields.required_modifiers = static, readonly + +# Naming: interfaces -> I-prefixed PascalCase +dotnet_naming_rule.interfaces.symbols = interfaces +dotnet_naming_rule.interfaces.style = i_prefix_pascal_case +dotnet_naming_rule.interfaces.severity = suggestion +dotnet_naming_symbols.interfaces.applicable_kinds = interface +dotnet_naming_style.i_prefix_pascal_case.capitalization = pascal_case +dotnet_naming_style.i_prefix_pascal_case.required_prefix = I + +dotnet_naming_style.underscore_camel_case.capitalization = camel_case +dotnet_naming_style.underscore_camel_case.required_prefix = _ +dotnet_naming_style.pascal_case.capitalization = pascal_case + +# Sample top-level programs require block-scoped namespaces. +[samples/**/Program.cs] +csharp_style_namespace_declarations = block_scoped \ No newline at end of file diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 74f881a..419c0d5 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -27,12 +27,14 @@ jobs: - name: Setup .NET 10 uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6 with: - dotnet-version: '10.0.x' + global-json-file: global.json cache: true cache-dependency-path: '**/packages.lock.json' - name: Restore - run: dotnet restore DotBahn.slnx --locked-mode + run: | + dotnet restore DotBahn.slnx --force-evaluate + git diff --exit-code -- '**/packages.lock.json' - name: Format check run: dotnet format DotBahn.slnx --verify-no-changes --verbosity diagnostic diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f4a1432..4af76a9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -33,12 +33,14 @@ jobs: - name: Setup .NET 10 uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6 with: - dotnet-version: '10.0.x' + global-json-file: global.json cache: true cache-dependency-path: '**/packages.lock.json' - name: Restore - run: dotnet restore DotBahn.slnx --locked-mode + run: | + dotnet restore DotBahn.slnx --force-evaluate + git diff --exit-code -- '**/packages.lock.json' - name: Pack NuGet run: dotnet pack DotBahn.slnx --no-restore --configuration Release --output ./nupkgs @@ -85,13 +87,14 @@ jobs: - name: Setup .NET 10 uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6 with: - dotnet-version: '10.0.x' + global-json-file: global.json cache: true cache-dependency-path: '**/packages.lock.json' - name: Build library (produces XML doc files) run: | - dotnet restore DotBahn.slnx --locked-mode + dotnet restore DotBahn.slnx --force-evaluate + git diff --exit-code -- '**/packages.lock.json' dotnet build DotBahn.slnx --no-restore --configuration Release - name: Build docs @@ -169,12 +172,13 @@ jobs: - name: Setup .NET 10 uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6 with: - dotnet-version: '10.0.x' + global-json-file: global.json - name: Generate dependency SBOM run: | dotnet tool restore - dotnet restore DotBahn.slnx --locked-mode + dotnet restore DotBahn.slnx --force-evaluate + git diff --exit-code -- '**/packages.lock.json' dotnet cyclonedx DotBahn.slnx -o ./build/sbom -F Json - name: Download packages @@ -184,7 +188,7 @@ jobs: path: ./nupkgs - name: Create GitHub Release - uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3 + uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3 with: tag_name: ${{ github.ref_name }} name: Release ${{ github.ref_name }} diff --git a/Directory.Build.props b/Directory.Build.props index 6034e00..1c1b195 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -5,11 +5,11 @@ latest enable true + true enable true true true - true true @@ -36,7 +36,7 @@ https://github.com/rlvelte/dotbahn https://github.com/rlvelte/dotbahn git - db;bahn;client;deutschebahn;deutsche-bahn;api;rest;http;dotnet;net10;stations;facilities;timetables;client-library + db;bahn;client;deutschebahn;deutsche-bahn;api;rest;http;dotnet;net10;stations;facilities;timetables;boards;ai Copyright (c) Robin L. Velte 2026 icon.png README.md @@ -58,16 +58,8 @@ - - - - all - runtime; build; native; contentfiles; analyzers - - - - - + + Exe false false diff --git a/Directory.Packages.props b/Directory.Packages.props index 8a3f20c..067cd0b 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -3,21 +3,36 @@ true - - - - - - - + - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DotBahn.slnx b/DotBahn.slnx index 5e9b14e..447f9d4 100644 --- a/DotBahn.slnx +++ b/DotBahn.slnx @@ -5,6 +5,11 @@ + + + + + @@ -15,23 +20,26 @@ + + + + - - - - - + - - - - - + + + + + + + + diff --git a/Makefile b/Makefile index 7421061..6253542 100644 --- a/Makefile +++ b/Makefile @@ -6,6 +6,8 @@ NUGET_PACKAGES_DIR ?= # Out RESULTS_DIR := ./build/tests +BENCH_DIR := ./build/benchmarks +MUTATE_DIR := ./build/mutations NUPKG_DIR := ./build/nupkgs PUBLISH_DIR := ./build/publish RPM_DIR := ./build/rpm @@ -29,20 +31,24 @@ export RPM_DIR # Main .DEFAULT_GOAL := build -.PHONY: format restore sbom build test coverage pack publish rpm mutate +.PHONY: format restore vulcheck sbom build test mutate pack publish rpm format: - dotnet format whitespace $(SOLUTION) \ - --verbosity diagnostic dotnet format $(SOLUTION) \ --verbosity diagnostic restore: dotnet restore $(SOLUTION) \ $(if $(NUGET_PACKAGES_DIR),--packages $(NUGET_PACKAGES_DIR),) \ + --force-evaluate \ --verbosity minimal -sbom: restore +vulcheck: + dotnet list $(SOLUTION) package \ + --vulnerable \ + --include-transitive + +sbom: dotnet cyclonedx $(SOLUTION) \ -o $(SBOM_DIR) \ -F Json @@ -54,47 +60,40 @@ build: restore test: build dotnet test --solution $(SOLUTION) \ - --no-build \ --configuration $(CONFIGURATION) \ --results-directory $(RESULTS_DIR) \ - -- --coverage --coverage-output-format cobertura --ignore-exit-code 8 + --no-build \ + -- --coverage --coverage-output-format cobertura -coverage: test - dotnet reportgenerator \ - -reports:$(RESULTS_DIR)/**/*.cobertura.xml \ - -targetdir:$(RESULTS_DIR)/coverage \ - -reporttypes:Html \ - -verbosity:Warning \ - -filefilters:-**/*.g.cs - @echo "file://$(CURDIR)/$(RESULTS_DIR)/coverage/index.html" +mutate: export MinVerVersionOverride = 1.0.0 +mutate: build + mkdir -p $(MUTATE_DIR) + dotnet stryker \ + --output $(MUTATE_DIR) -pack: +pack: build dotnet pack $(SOLUTION) \ --configuration $(CONFIGURATION) \ --output $(NUPKG_DIR) \ + --no-build \ --verbosity minimal publish: $(RUN) scripts/publish$(EXT) -rpm: publish +rpm: ifeq ($(OS),Windows_NT) - @echo "RPM packaging requires 'rpmbuild'." >&2 + @echo "Windows does not support 'rpmbuild'." >&2 else $(RUN) scripts/rpm$(EXT) endif -# Documentation -docs-build: build - dotnet docfx docs/docfx.json - -docs-serve: build - dotnet docfx docs/docfx.json --serve - -# Utility clean: + dotnet clean $(SOLUTION) \ + --configuration $(CONFIGURATION) \ + --verbosity minimal ifeq ($(OS),Windows_NT) - pwsh -NoProfile -Command "Remove-Item -Recurse -Force -ErrorAction SilentlyContinue build, StrykerOutput, docs/_site, docs/api" + powershell -NoProfile -Command "Remove-Item -Recurse -Force -ErrorAction SilentlyContinue build, docs/_site, docs/api" else - rm -rf build StrykerOutput docs/_site docs/api -endif \ No newline at end of file + rm -rf build docs/_site docs/api +endif diff --git a/README.md b/README.md index e8f4661..8048097 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ ![NuGet](https://img.shields.io/nuget/v/DotBahn.Common?label=DotBahn.Common&style=flat) ![NuGet](https://img.shields.io/nuget/v/DotBahn.Telemetry?label=DotBahn.Telemetry&style=flat) +![NuGet](https://img.shields.io/nuget/v/DotBahn.Boards?label=DotBahn.Boards&style=flat) ![NuGet](https://img.shields.io/nuget/v/DotBahn.Timetables?label=DotBahn.Timetables&style=flat) ![NuGet](https://img.shields.io/nuget/v/DotBahn.Stations?label=DotBahn.Stations&style=flat) ![NuGet](https://img.shields.io/nuget/v/DotBahn.Facilities?label=DotBahn.Facilities&style=flat) @@ -11,27 +12,28 @@ DotBahn is a collection of unofficial .NET client packages for accessing Deutsche Bahn (DB) APIs. Query train schedules, station details, and facility status directly in your application. It also provides convenience features like timetable merging, fluent queries and some additional properties. All libraries are AOT compatible and trimmable. -> [!IMPORTANT] -> If you are just here to use the departure monitor as a standalone tool on your system, there is also a packaged RPM on the [Open Build Service](https://build.opensuse.org/package/show/home:rvelte/dbpeek) for that. - | API | Description | |------------------------|-------------| | **Stations (StaDa)** | Station data including parking, accessibility, and opening hours. | | **Facilities (FaSta)** | Real-time operational status of elevators and escalators at stations. | -| **Timetables** | Scheduled departures and arrivals with real-time delay and platform change information. | +| **Boards (OpenBoards)** | Scheduled departures and arrivals with real-time delay and platform change information. | + +> [!CAUTION] +> **Deutsche Bahn is shutting down the Timetables API.** It entered parallel operation in November 2026 and is scheduled for shutdown around mid-2027. There is a replacement package with `DotBahn.Boards` that uses the new OpenBoards API. + ## Table of Contents - [Install](#install) - [Usage](#usage) - [Authorization](#authorization) - [Samples](#samples) -- [API Reference](https://rlvelte.github.io/dotbahn/index.html) +- [Experimental & AI](#experimental--ai) ## Install Install the packages you need from [NuGet](https://www.nuget.org/) or [GitHub Packages](https://docs.github.com/de/packages/working-with-a-github-packages-registry/working-with-the-nuget-registry): ```bash -dotnet add package DotBahn.Timetables +dotnet add package DotBahn.Boards dotnet add package DotBahn.Stations dotnet add package DotBahn.Facilities @@ -42,7 +44,6 @@ dotnet add package DotBahn.Telemetry > [!NOTE] > All client packages depend on **DotBahn.Common**, which provides cross-cutting abstractions such as authorization, base client infrastructure, and shared models. It is installed automatically as a transitive dependency. - ## Usage ### Dependency Injection (Recommended) All packages integrate seamlessly with `IServiceCollection`. Each client comes with a default endpoint, override only for custom proxies: @@ -50,7 +51,7 @@ All packages integrate seamlessly with `IServiceCollection`. Each client comes w ```csharp // Register clients services.AddDotBahnStations(); -services.AddDotBahnTimetables(); +services.AddDotBahnBoards(); services.AddDotBahnFacilities(); // Configure authorization (required for API access) @@ -101,22 +102,27 @@ A Deutsche Bahn API key is required. Register and obtain your credentials at the > These packages only consume the credentials you provide for API authentication. They do not create, register, or manage credentials on your behalf. ## Samples -Both samples take credentials via `--client` / `--secret` or, more conveniently, the `DOTBAHN_CLIENT` / `DOTBAHN_SECRET` environment variables. +All samples take DB credentials via `--client` / `--secret` or, more conveniently, the `DOTBAHN_CLIENT` / `DOTBAHN_SECRET` environment variables. ### TimetablePeek (`dbpeek`) Terminal departures board for DB timetable services. Shows customer-facing train names (service line or trip number), planned and actual times, delays, platforms, destinations, and via stops. Optional category filter, upstream time window and machine-readable JSON output. -```bash -dotnet run --project samples/DotBahn.Samples.TimetablePeek -- [options] -``` +> [!NOTE] +> If you are just here to use the departure monitor as a standalone tool on your system, there is also a packaged RPM on the [Open Build Service](https://build.opensuse.org/package/show/home:rvelte/dbpeek) for that. + ### StationBrowser (`dbstation`) Interactive terminal application for exploring DB station details. Search by name and navigate results with arrow keys. Shows station category, identifiers (EVA/RIL100), address, coordinates, regional area, available services, and real-time elevator/escalator status. -```bash -dotnet run --project samples/DotBahn.Samples.StationBrowser -- [options] -``` - + +## Experimental & AI + +The package `DotBahn.Ai` is an early exploration of integrated AI tool support. It is experimental and has no current development priority. If you have experience with .NET AI integrations, tool calling or related designs, feel free to contribute. + +However, there is a minimal interactive chatbot sample that uses a local Ollama model with these tools. It defaults to `qwen3:4b` at `http://localhost:11434/v1`; override with `--model` and `--endpoint`. + + + diff --git a/docs/docfx.json b/docs/docfx.json index 15c3a2e..f8f5ccb 100644 --- a/docs/docfx.json +++ b/docs/docfx.json @@ -7,6 +7,7 @@ "source/DotBahn.Facilities/bin/Release/net10.0/DotBahn.Facilities.dll", "source/DotBahn.Stations/bin/Release/net10.0/DotBahn.Stations.dll", "source/DotBahn.Timetables/bin/Release/net10.0/DotBahn.Timetables.dll", + "source/DotBahn.Boards/bin/Release/net10.0/DotBahn.Boards.dll", "source/DotBahn.Common/bin/Release/net10.0/DotBahn.Common.dll", "source/DotBahn.Telemetry/bin/Release/net10.0/DotBahn.Telemetry.dll" ], diff --git a/dotnet-tools.json b/dotnet-tools.json index f1ed0aa..b9c5349 100644 --- a/dotnet-tools.json +++ b/dotnet-tools.json @@ -10,21 +10,21 @@ "rollForward": false }, "dotnet-reportgenerator-globaltool": { - "version": "5.5.12", + "version": "5.6.1", "commands": [ "reportgenerator" ], "rollForward": false }, "dotnet-stryker": { - "version": "5.0.0", + "version": "5.1.0", "commands": [ "dotnet-stryker" ], "rollForward": false }, "cyclonedx": { - "version": "6.3.1", + "version": "6.3.2", "commands": [ "dotnet-CycloneDX" ], diff --git a/global.json b/global.json index 3140116..1682134 100644 --- a/global.json +++ b/global.json @@ -1,4 +1,8 @@ { + "sdk": { + "version": "10.0.404", + "rollForward": "disable" + }, "test": { "runner": "Microsoft.Testing.Platform" } diff --git a/samples/DotBahn.Samples.Chatbot/DotBahn.Samples.Chatbot.csproj b/samples/DotBahn.Samples.Chatbot/DotBahn.Samples.Chatbot.csproj new file mode 100644 index 0000000..d57d6cf --- /dev/null +++ b/samples/DotBahn.Samples.Chatbot/DotBahn.Samples.Chatbot.csproj @@ -0,0 +1,21 @@ + + + + Exe + dbchat + false + $(NoWarn);CS1591 + + + + + + + + + + + + + + diff --git a/samples/DotBahn.Samples.Chatbot/Program.cs b/samples/DotBahn.Samples.Chatbot/Program.cs new file mode 100644 index 0000000..1e24a4f --- /dev/null +++ b/samples/DotBahn.Samples.Chatbot/Program.cs @@ -0,0 +1,157 @@ +using System.ClientModel; +using System.CommandLine; +using DotBahn.Ai; +using DotBahn.Boards; +using DotBahn.Common; +using DotBahn.Facilities; +using DotBahn.Samples.Chatbot; +using DotBahn.Stations; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using OpenAI; +using Spectre.Console; + +return await DbChatCli.BuildRootCommand().Parse(args).InvokeAsync(); + +namespace DotBahn.Samples.Chatbot { + internal static class DbChatCli { + private const string SystemPrompt = + "You are a helpful Deutsche Bahn assistant. Use the provided tools to answer questions " + + "about stations, departures, arrivals, and facility status. Keep answers concise. " + + "If a tool returns a structured error, explain the problem and ask for corrected input."; + + private static readonly Option ClientIdOption = new("--client") { + Description = "DB API client id; falls back to the DOTBAHN_CLIENT environment variable" + }; + + private static readonly Option SecretOption = new("--secret") { + Description = "DB API secret; falls back to the DOTBAHN_SECRET environment variable" + }; + + private static readonly Option ApiKeyOption = new("--api-key") { + Description = "Model API key; defaults to OPENAI_API_KEY or 'ollama' for local models", + DefaultValueFactory = _ => Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? "ollama" + }; + + private static readonly Option EndpointOption = new("--endpoint", "-e") { + Description = "OpenAI-compatible endpoint", + DefaultValueFactory = _ => Environment.GetEnvironmentVariable("DOTBAHN_AI_ENDPOINT") ?? "http://localhost:11434/v1" + }; + + private static readonly Option ModelOption = new("--model", "-m") { + Description = "Model name; defaults to DOTBAHN_AI_MODEL or 'qwen3:4b'", + DefaultValueFactory = _ => Environment.GetEnvironmentVariable("DOTBAHN_AI_MODEL") ?? "qwen3:4b" + }; + + internal static RootCommand BuildRootCommand() { + var rootCommand = new RootCommand("Minimal local chatbot for Deutsche Bahn data") { + ClientIdOption, + SecretOption, + ApiKeyOption, + EndpointOption, + ModelOption + }; + + EndpointOption.Validators.Add(result => { + var endpoint = result.GetValue(EndpointOption); + if (!Uri.TryCreate(endpoint, UriKind.Absolute, out _)) { + result.AddError("--endpoint must be an absolute URI."); + } + }); + + ModelOption.Validators.Add(result => { + if (string.IsNullOrWhiteSpace(result.GetValue(ModelOption))) { + result.AddError("--model must not be empty."); + } + }); + + rootCommand.SetAction(async (parseResult, ct) => await RunAsync( + parseResult.GetValue(ClientIdOption), + parseResult.GetValue(SecretOption), + parseResult.GetValue(ApiKeyOption)!, + parseResult.GetValue(EndpointOption)!, + parseResult.GetValue(ModelOption)!, ct)); + + return rootCommand; + } + + private static async Task RunAsync(string? clientId, string? secret, string apiKey, string endpoint, string model, CancellationToken cancellationToken) { + if (!ResolveCredentials(clientId, secret, out var resolvedClientId, out var resolvedSecret)) { + AnsiConsole.MarkupLine("[red]Usage:[/] provide --client/--secret, or set DOTBAHN_CLIENT / DOTBAHN_SECRET via env or CLI args"); + return 1; + } + + var services = new ServiceCollection(); + services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Warning)); + services.AddDotBahnAuthorization(opt => { + opt.ClientId = resolvedClientId; + opt.ApiKey = resolvedSecret; + }); + + services.AddDotBahnStations(); + services.AddDotBahnBoards(); + services.AddDotBahnFacilities(); + services.AddDotBahnAiTools(); + + await using var provider = services.BuildServiceProvider(); + + var openAiOptions = new OpenAIClientOptions { + Endpoint = new Uri(endpoint) + }; + var openAiClient = new OpenAIClient(new ApiKeyCredential(apiKey), openAiOptions); + + IChatClient inner = openAiClient.GetChatClient(model).AsIChatClient(); + IChatClient chat = new ChatClientBuilder(inner).UseDotBahnAiTools(provider.GetService()).Build(); + + var chatOptions = new ChatOptions { + Tools = provider.GetRequiredService>() + .Cast() + .ToList() + }; + + var history = new List { + new(ChatRole.System, SystemPrompt) + }; + + AnsiConsole.MarkupLine($"[grey]Model:[/] {Markup.Escape(model)}"); + while (true) { + var input = AnsiConsole.Ask("[blue]You[/]"); + if (string.Equals(input, "exit", StringComparison.OrdinalIgnoreCase) || + string.Equals(input, "quit", StringComparison.OrdinalIgnoreCase)) { + return 0; + } + + history.Add(new ChatMessage(ChatRole.User, input)); + AnsiConsole.MarkupLine("[grey]Thinking...[/]"); + + ChatResponse response; + try { + response = await chat.GetResponseAsync(history, chatOptions, cancellationToken); + } catch (OperationCanceledException) { + return 130; + } catch (Exception ex) when (IsLocalEndpoint(endpoint)) { + AnsiConsole.MarkupLine($"[red]Local model unavailable:[/] {Markup.Escape(ex.Message)}"); + AnsiConsole.MarkupLine($"[grey]Start Ollama with 'ollama serve' and pull the model with 'ollama pull {Markup.Escape(model)}'.[/]"); + return 1; + } catch (Exception ex) { + AnsiConsole.MarkupLine($"[red]Error:[/] {Markup.Escape(ex.Message)}"); + return 1; + } + + history.AddRange(response.Messages); + AnsiConsole.MarkupLine($"[green]Assistant[/]: {Markup.Escape(response.Text)}"); + } + } + + private static bool IsLocalEndpoint(string endpoint) => + endpoint.Contains("localhost", StringComparison.OrdinalIgnoreCase) || + endpoint.Contains("127.0.0.1", StringComparison.OrdinalIgnoreCase); + + private static bool ResolveCredentials(string? clientId, string? secret, out string resolvedClientId, out string resolvedSecret) { + resolvedClientId = clientId ?? Environment.GetEnvironmentVariable("DOTBAHN_CLIENT") ?? string.Empty; + resolvedSecret = secret ?? Environment.GetEnvironmentVariable("DOTBAHN_SECRET") ?? string.Empty; + return !string.IsNullOrEmpty(resolvedClientId) && !string.IsNullOrEmpty(resolvedSecret); + } + } +} diff --git a/samples/DotBahn.Samples.Chatbot/packages.lock.json b/samples/DotBahn.Samples.Chatbot/packages.lock.json new file mode 100644 index 0000000..007333c --- /dev/null +++ b/samples/DotBahn.Samples.Chatbot/packages.lock.json @@ -0,0 +1,437 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.Extensions.AI.OpenAI": { + "type": "Direct", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "BPyxzh96v26MfAM61x/5hj1Gt3FbUpqqnRFuKa9j+FIPewNq4qL4zmJzUJv6csyv8nMNX8tdZBKba3H3XK/OBg==", + "dependencies": { + "Microsoft.Extensions.AI.Abstractions": "11.0.1", + "OpenAI": "2.15.0" + } + }, + "MinVer": { + "type": "Direct", + "requested": "[8.0.0, )", + "resolved": "8.0.0", + "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" + }, + "Spectre.Console": { + "type": "Direct", + "requested": "[0.57.2, )", + "resolved": "0.57.2", + "contentHash": "wzsB+P9i6F9G+cFOJxRotCiQWNSzZVAMxi8YMiHlGXXU1JLMXGp7zSSqBMmROZS2bzpK5jk+Saa7Evp8HwqhKg==", + "dependencies": { + "Spectre.Console.Ansi": "0.57.2" + } + }, + "System.CommandLine": { + "type": "Direct", + "requested": "[3.0.0, )", + "resolved": "3.0.0", + "contentHash": "swNpSTl0iYJeBuvYYfaY+VxzZ5YC8wklwkqDCNOq2aTQqJzjauJfh/O3Zw93nwxspWrxvZTjT45f8VPR0ParEA==" + }, + "Microsoft.Extensions.AmbientMetadata.Application": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "tm28s2ODWZ6RdysP06NI3B23DUY5OfHG35ihMHxVAO3hywZAczDVjrkYMfBY//J4HQqfDHS5op84BhnF7ROseQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Caching.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "L+eahU5QGaFaCau3Y9qqY7WThUsR18sHASVDD1KuaSx2dy73NOY9U5Qz5eOe6bJOF3wHzkEaCl2LZhgwtlClyw==", + "dependencies": { + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Compliance.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "DUwdXgIxJKH9zBNg/SUBqOX0FpXCq7w80CIzrr0Jcw5tBXS926AtCcidoAsEHq5e/c6KQ8rWhSt7NxFxak8N/Q==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15" + } + }, + "Microsoft.Extensions.Compliance.Redaction": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "2rwe98yZEn4+aXjAg5DdcROMg6m2w3tejf/mRk4/fBCHKM2EWCaFTmbHLtz1BfyBxMY00/08XFoN0wzWYNiSiQ==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Configuration": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", + "dependencies": { + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" + }, + "Microsoft.Extensions.DependencyInjection.AutoActivation": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "OuVIF5TmsfonN2Fqmi2zlUtbFQNqQiflhgo/rh64ptrqYrB4wZLwKbXr/HzrQXMf+h3jIbWrjIdJFspGqcvuuQ==", + "dependencies": { + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mqqpmAFNRLa4cozN3RvT/T81k4aarwMc8xb8VVQgLqUE7AAoN/WWayZAvP+4hy9+KujP3dfn3taU06fZJPIbgA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.FileProviders.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "1RSYAUtJeb76m2T0u5BbvwKY3s+ge9fT3cj1odvo5Bm+frc7pU9RSeXeMIlYHV8GjpqLdv2neeeomz010yYL8A==", + "dependencies": { + "Microsoft.Extensions.Primitives": "10.0.15" + } + }, + "Microsoft.Extensions.Hosting.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "s/JBiwR3F/vKRCbe6WO5b6t6or1ISaZ3rllchcw6/FSWZmK8s2fAzD7elrZo7592FnMD1fhGoG/wuJL1YYtVXw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.Http.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mKHY0oFYL3fkAOhBNi2LqWPuEdUJ+HiF28KKUwBkQG2sgXAUdFDDqvJAfu2PcYgtAwsAtl58zuk4SElpPzbCvA==", + "dependencies": { + "Microsoft.Extensions.Compliance.Redaction": "11.0.1", + "Microsoft.Extensions.Http": "10.0.15", + "Microsoft.Extensions.Telemetry": "11.0.1" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Configuration": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "Km6Ml1/nu0T/f80Btonxf9CWmP/BXI84aJwC5fUbCxRArJ0lH++0ADQrjErZvsSIrKhusTkTSGBChKy2fYAF4w==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Configuration.Binder": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.ObjectPool": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "kvd9eyRRQ+OEu9wik7GKgTS+7XnJ5XoOtSXJqmkJtVYV/S4gsBUrobYRSdNeBcb0ymef4L5Q9pZGiTxJ8jJfyQ==" + }, + "Microsoft.Extensions.Options.ConfigurationExtensions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" + }, + "Microsoft.Extensions.Resilience": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "xgKof6iwAByZNrxWOa7Drk4A953L7U2HleTmx7EXE2Vf6j1crp4RsvNlIVsJMtHKf3ftGKd9gOhR3xES9vxUgg==", + "dependencies": { + "Microsoft.Extensions.Diagnostics": "10.0.15", + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1", + "Polly.Extensions": "8.4.2", + "Polly.RateLimiting": "8.4.2" + } + }, + "Microsoft.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "9uuA8entTC9m00m59h6CACSt4IQh9KknB+hPvCteXUTiG67lqJ8BI65fEUJSPSfT3ZDDi01Zg2aY5kRUvD4HPw==", + "dependencies": { + "Microsoft.Extensions.AmbientMetadata.Application": "11.0.1", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "11.0.1", + "Microsoft.Extensions.Logging.Configuration": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1" + } + }, + "Microsoft.Extensions.Telemetry.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "qINZz4G01Wxumqd0hLr6YdzPa3s7jexQWN28EenaiJQnmKdsR9FnBaKENdRRElLc+A5bJKQ+jYw/WHG4ZpIyAg==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15" + } + }, + "OpenAI": { + "type": "Transitive", + "resolved": "2.15.0", + "contentHash": "04Lvp/guze35OdYsEcQY58SmSCBWCEDCGkiLiTQXDJy5L3d20n7I/zg94ry9hQ5c4dMDF1ASqlxD/IIMy47gFg==", + "dependencies": { + "System.ClientModel": "1.16.0" + } + }, + "Polly.Core": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g==" + }, + "Polly.Extensions": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==", + "dependencies": { + "Microsoft.Extensions.Logging.Abstractions": "8.0.0", + "Microsoft.Extensions.Options": "8.0.0", + "Polly.Core": "8.4.2" + } + }, + "Polly.RateLimiting": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==", + "dependencies": { + "Polly.Core": "8.4.2", + "System.Threading.RateLimiting": "8.0.0" + } + }, + "Spectre.Console.Ansi": { + "type": "Transitive", + "resolved": "0.57.2", + "contentHash": "Y1+u73shwP+JYHmrkdN6bSt2kaGBEAafhi2nrecczbXdFRey+k7J/WF9YPfcB0rqivv2S8fmif6FSBq9m/AFvw==" + }, + "System.ClientModel": { + "type": "Transitive", + "resolved": "1.16.0", + "contentHash": "vLljZON+8lXDUtsPP8uwsPvsBSQaUHhh8NvB+D9TQsXu5n622RLtuLyZAcyIFc98b8ixrwD0AhzUQhtg2NwJnQ==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.10", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.10", + "Microsoft.Extensions.Logging.Abstractions": "10.0.10", + "System.Memory.Data": "10.0.10" + } + }, + "System.Diagnostics.DiagnosticSource": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" + }, + "System.Memory.Data": { + "type": "Transitive", + "resolved": "10.0.10", + "contentHash": "roR+5AeOpflUxJQlqSfsZs/Bvi1uw4KBuTkIgF1e8l0RdalG4AUn84+sjJLclEfOV85gAjc8+Pp540qjDE5UIg==" + }, + "System.Numerics.Tensors": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "thx6y1hMzB6LumB/aLcZoLHWq8wr+dbldk/FiNghyT+4ynxo9u2oCTFfb5iDMDG6hykDXLorXuaf4EPEij2BBg==" + }, + "System.Threading.RateLimiting": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q==" + }, + "dotbahn.ai": { + "type": "Project", + "dependencies": { + "DotBahn.Boards": "[1.0.0, )", + "DotBahn.Facilities": "[1.0.0, )", + "DotBahn.Stations": "[1.0.0, )", + "Microsoft.Extensions.AI": "[11.0.1, )", + "Microsoft.Extensions.AI.Abstractions": "[11.0.1, )" + } + }, + "dotbahn.boards": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )", + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Http.Resilience": "[11.0.1, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.common": { + "type": "Project", + "dependencies": { + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.facilities": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )", + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Http.Resilience": "[11.0.1, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.stations": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )", + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Http.Resilience": "[11.0.1, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "Microsoft.Extensions.AI": { + "type": "CentralTransitive", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "MP6zzZzPseaXu0DtZFCkPCWPXLTu7JY28ciyxqSoeDOP5Raf+wJT8+HapyLfXaI7F1CXpyr5PgiCQEE0CeVCqw==", + "dependencies": { + "Microsoft.Extensions.AI.Abstractions": "11.0.1", + "Microsoft.Extensions.Caching.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "System.Numerics.Tensors": "11.0.0" + } + }, + "Microsoft.Extensions.AI.Abstractions": { + "type": "CentralTransitive", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "pG3n1nHRnVcYuMAiqhDPuKefXTtUGAhAtqhBUKpNsZXYef9Vm51iZhUAVfQ2EzYhechFaA5hCcgQgK18jTzuiw==" + }, + "Microsoft.Extensions.Http": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Http.Resilience": { + "type": "CentralTransitive", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "5VawCrg+VgVT2hNurSSEWUnq0pvNoH+Zt82s5Wpl/8jdnmU8DpRlr+M3DcdtVgeBG7mRyk3GtSRbf8PB/HrL3w==", + "dependencies": { + "Microsoft.Extensions.Http.Diagnostics": "11.0.1", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Resilience": "11.0.1" + } + }, + "Microsoft.Extensions.Options": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + } + } + } +} \ No newline at end of file diff --git a/samples/DotBahn.Samples.StationBrowser/Program.cs b/samples/DotBahn.Samples.StationBrowser/Program.cs index b37447f..6ff61cf 100644 --- a/samples/DotBahn.Samples.StationBrowser/Program.cs +++ b/samples/DotBahn.Samples.StationBrowser/Program.cs @@ -6,6 +6,7 @@ using DotBahn.Facilities; using DotBahn.Facilities.Models; using DotBahn.Facilities.Models.Enumerations; +using DotBahn.Samples.StationBrowser; using DotBahn.Stations; using DotBahn.Stations.Models; using DotBahn.Stations.Models.Enumerations; @@ -16,425 +17,427 @@ return await StationBrowserCli.BuildRootCommand().Parse(args).InvokeAsync(); -internal static class StationBrowserCli { - private static readonly Argument SearchArgument = new("search") { - Description = "Station name to search for (e.g. würzburg)", - Arity = ArgumentArity.ZeroOrOne, - }; - - private static readonly Option ClientIdOption = new("--client") { - Description = "DB API client id; falls back to the DOTBAHN_CLIENT environment variable", - }; - - private static readonly Option SecretOption = new("--secret") { - Description = "DB API secret; falls back to the DOTBAHN_SECRET environment variable", - }; - - private static readonly Option JsonOption = new("--json", "-j") { - Description = "Print the matched stations as JSON instead of starting the interactive browser", - }; - - internal static RootCommand BuildRootCommand() { - var rootCommand = new RootCommand("Interactive browser for Deutsche Bahn stations and their facilities") { - SearchArgument, - ClientIdOption, - SecretOption, - JsonOption, +namespace DotBahn.Samples.StationBrowser { + internal static class StationBrowserCli { + private static readonly Argument SearchArgument = new("search") { + Description = "Station name to search for (e.g. würzburg)", + Arity = ArgumentArity.ZeroOrOne }; - rootCommand.Validators.Add(result => { - var search = result.GetValue(SearchArgument); - if (string.IsNullOrWhiteSpace(search)) { - result.AddError("A search name is required: pass the station name to look up."); - } - }); + private static readonly Option ClientIdOption = new("--client") { + Description = "DB API client id; falls back to the DOTBAHN_CLIENT environment variable" + }; - rootCommand.SetAction(async (parseResult, cancellationToken) => { - var search = parseResult.GetValue(SearchArgument)!; - var clientId = parseResult.GetValue(ClientIdOption); - var secret = parseResult.GetValue(SecretOption); - var json = parseResult.GetValue(JsonOption); + private static readonly Option SecretOption = new("--secret") { + Description = "DB API secret; falls back to the DOTBAHN_SECRET environment variable" + }; - return await RunAsync(search, clientId, secret, json, cancellationToken); - }); + private static readonly Option JsonOption = new("--json", "-j") { + Description = "Print the matched stations as JSON instead of starting the interactive browser" + }; - return rootCommand; - } + internal static RootCommand BuildRootCommand() { + var rootCommand = new RootCommand("Interactive browser for Deutsche Bahn stations and their facilities") { + SearchArgument, + ClientIdOption, + SecretOption, + JsonOption + }; - private static async Task RunAsync(string search, string? clientId, string? secret, bool json, CancellationToken cancellationToken) { - if (!ResolveCredentials(clientId, secret, out var resolvedClientId, out var resolvedSecret)) { - if (json) { - WriteJsonError("missing-credentials", "Provide --client/--secret or set DOTBAHN_CLIENT and DOTBAHN_SECRET."); - } else { - AnsiConsole.MarkupLine("[red]Usage:[/] provide --client/--secret, or set DOTBAHN_CLIENT / DOTBAHN_SECRET via env or CLI args"); - } - return 1; + rootCommand.Validators.Add(result => { + var search = result.GetValue(SearchArgument); + if (string.IsNullOrWhiteSpace(search)) { + result.AddError("A search name is required: pass the station name to look up."); + } + }); + + rootCommand.SetAction(async (parseResult, cancellationToken) => { + var search = parseResult.GetValue(SearchArgument)!; + var clientId = parseResult.GetValue(ClientIdOption); + var secret = parseResult.GetValue(SecretOption); + var json = parseResult.GetValue(JsonOption); + + return await RunAsync(search, clientId, secret, json, cancellationToken); + }); + + return rootCommand; } - List stations; + private static async Task RunAsync(string search, string? clientId, string? secret, bool json, CancellationToken cancellationToken) { + if (!ResolveCredentials(clientId, secret, out var resolvedClientId, out var resolvedSecret)) { + if (json) { + WriteJsonError("missing-credentials", "Provide --client/--secret or set DOTBAHN_CLIENT and DOTBAHN_SECRET."); + } else { + AnsiConsole.MarkupLine("[red]Usage:[/] provide --client/--secret, or set DOTBAHN_CLIENT / DOTBAHN_SECRET via env or CLI args"); + } + return 1; + } - try { - stations = await FindStationsAsync(resolvedClientId, resolvedSecret, search, cancellationToken); - } catch (HttpRequestException ex) { - if (json) { - WriteJsonError("api-error", ex.Message); - } else { - AnsiConsole.MarkupLine($"[red]API request failed:[/] [grey]{Markup.Escape(ex.Message)}[/]"); + List stations; + + try { + stations = await FindStationsAsync(resolvedClientId, resolvedSecret, search, cancellationToken); + } catch (HttpRequestException ex) { + if (json) { + WriteJsonError("api-error", ex.Message); + } else { + AnsiConsole.MarkupLine($"[red]API request failed:[/] [grey]{Markup.Escape(ex.Message)}[/]"); + } + return 1; + } + + if (stations.Count == 0) { + if (json) { + WriteJsonError("station-not-found", $"No stations found matching \"{search}\""); + } else { + AnsiConsole.MarkupLine($"[yellow]No stations found matching '{Markup.Escape(search)}'[/]"); + } + return 1; } - return 1; - } - if (stations.Count == 0) { if (json) { - WriteJsonError("station-not-found", $"No stations found matching \"{search}\""); - } else { - AnsiConsole.MarkupLine($"[yellow]No stations found matching '{Markup.Escape(search)}'[/]"); + Console.WriteLine(JsonSerializer.Serialize(new StationsPayload([.. stations.Select(ToStationDto)]), StationBrowserJsonContext.Default.StationsPayload)); + return 0; } - return 1; - } - if (json) { - Console.WriteLine(JsonSerializer.Serialize(new StationsPayload([.. stations.Select(ToStationDto)]), StationBrowserJsonContext.Default.StationsPayload)); + await BrowseAsync(stations, resolvedClientId, resolvedSecret); return 0; } - await BrowseAsync(stations, resolvedClientId, resolvedSecret); - return 0; - } - - private static bool ResolveCredentials(string? clientId, string? secret, out string resolvedClientId, out string resolvedSecret) { - _ = TryCredentialsFromEnvironment(out var envClient, out var envSecret); - resolvedClientId = clientId ?? envClient; - resolvedSecret = secret ?? envSecret; - return !string.IsNullOrEmpty(resolvedClientId) && !string.IsNullOrEmpty(resolvedSecret); - } - - private static bool TryCredentialsFromEnvironment(out string clientId, out string clientSecret) { - clientId = Environment.GetEnvironmentVariable("DOTBAHN_CLIENT") ?? string.Empty; - clientSecret = Environment.GetEnvironmentVariable("DOTBAHN_SECRET") ?? string.Empty; - return !string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(clientSecret); - } + private static bool ResolveCredentials(string? clientId, string? secret, out string resolvedClientId, out string resolvedSecret) { + _ = TryCredentialsFromEnvironment(out var envClient, out var envSecret); + resolvedClientId = clientId ?? envClient; + resolvedSecret = secret ?? envSecret; + return !string.IsNullOrEmpty(resolvedClientId) && !string.IsNullOrEmpty(resolvedSecret); + } - private static async Task> FindStationsAsync(string clientId, string secret, string search, CancellationToken cancellationToken) { - var services = new ServiceCollection(); - services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Warning)); - services.AddDotBahnAuthorization(opt => { - opt.ClientId = clientId; - opt.ApiKey = secret; - }); - services.AddDotBahnStations(opt => opt.BaseEndpoint = new Uri("https://apis.deutschebahn.com/db-api-marketplace/apis/station-data/v2/")); - services.AddDotBahnFacilities(opt => opt.BaseEndpoint = new Uri("https://apis.deutschebahn.com/db-api-marketplace/apis/fasta/v2/")); + private static bool TryCredentialsFromEnvironment(out string clientId, out string clientSecret) { + clientId = Environment.GetEnvironmentVariable("DOTBAHN_CLIENT") ?? string.Empty; + clientSecret = Environment.GetEnvironmentVariable("DOTBAHN_SECRET") ?? string.Empty; + return !string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(clientSecret); + } - var serviceProvider = services.BuildServiceProvider(); - var stationsClient = serviceProvider.GetRequiredService(); + private static async Task> FindStationsAsync(string clientId, string secret, string search, CancellationToken cancellationToken) { + var services = new ServiceCollection(); + services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Warning)); + services.AddDotBahnAuthorization(opt => { + opt.ClientId = clientId; + opt.ApiKey = secret; + }); + services.AddDotBahnStations(opt => opt.BaseEndpoint = new Uri("https://apis.deutschebahn.com/db-api-marketplace/apis/station-data/v2/")); + services.AddDotBahnFacilities(opt => opt.BaseEndpoint = new Uri("https://apis.deutschebahn.com/db-api-marketplace/apis/fasta/v2/")); - var stations = new List(); - var query = new StationQuery().WithNames(search); + var serviceProvider = services.BuildServiceProvider(); + var stationsClient = serviceProvider.GetRequiredService(); - await AnsiConsole.Status().Spinner(Spinner.Known.Dots).StartAsync($"Searching for stations matching '{search}'...", async _ => { - stations.AddRange(await stationsClient.GetStationsAsync(query, cancellationToken)); - }); + var stations = new List(); + var query = new StationQuery().WithNames(search); - return stations; - } + await AnsiConsole.Status().Spinner(Spinner.Known.Dots).StartAsync($"Searching for stations matching '{search}'...", async _ => { + stations.AddRange(await stationsClient.GetStationsAsync(query, cancellationToken)); + }); - private static StationDto ToStationDto(Station station) => new( - station.Number, - station.Name, - station.PrimaryEva?.Number, - station.Category.ToString(), - station.Coordinates?.Latitude, - station.Coordinates?.Longitude); - - private static void WriteJsonError(string code, string message) { - var payload = new ErrorPayload(new ErrorDto(code, message)); - Console.WriteLine(JsonSerializer.Serialize(payload, StationBrowserJsonContext.Default.ErrorPayload)); - } + return stations; + } - private static async Task BrowseAsync(List stations, string clientId, string secret) { - var services = new ServiceCollection(); - services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Warning)); - services.AddDotBahnAuthorization(opt => { - opt.ClientId = clientId; - opt.ApiKey = secret; - }); - services.AddDotBahnStations(opt => opt.BaseEndpoint = new Uri("https://apis.deutschebahn.com/db-api-marketplace/apis/station-data/v2/")); - services.AddDotBahnFacilities(opt => opt.BaseEndpoint = new Uri("https://apis.deutschebahn.com/db-api-marketplace/apis/fasta/v2/")); - - var serviceProvider = services.BuildServiceProvider(); - var facilitiesClient = serviceProvider.GetRequiredService(); - - AnsiConsole.MarkupLine($"[green]Found {stations.Count} station(s)[/]"); - var facilitiesCache = new Dictionary>(); - - var currentIndex = 0; - while (true) { - var currentStation = stations[currentIndex]; - - if (!facilitiesCache.TryGetValue(currentStation.Number, out var facilities)) { - await AnsiConsole.Status().Spinner(Spinner.Known.Dots).StartAsync( - "Loading facilities...", - async _ => { - var query = new FacilityQuery().AtStation(currentStation.Number); - facilities = (await facilitiesClient.GetFacilitiesAsync(query)).ToList(); - facilitiesCache[currentStation.Number] = facilities; - }); - } + private static StationDto ToStationDto(Station station) => new( + station.Number, + station.Name, + station.PrimaryEva?.Number, + station.Category.ToString(), + station.Coordinates?.Latitude, + station.Coordinates?.Longitude); + + private static void WriteJsonError(string code, string message) { + var payload = new ErrorPayload(new ErrorDto(code, message)); + Console.WriteLine(JsonSerializer.Serialize(payload, StationBrowserJsonContext.Default.ErrorPayload)); + } - AnsiConsole.Clear(); - RenderStation(currentStation, facilities ?? [], currentIndex, stations.Count); - RenderNavigation(); - - switch (Console.ReadKey(true).Key) { - case ConsoleKey.LeftArrow: - if (currentIndex > 0) { - currentIndex--; - } - - break; - case ConsoleKey.RightArrow: - if (currentIndex < stations.Count - 1) { - currentIndex++; - } - - break; - case ConsoleKey.Home: - currentIndex = 0; - break; - case ConsoleKey.End: - currentIndex = stations.Count - 1; - break; - case ConsoleKey.Escape: - case ConsoleKey.Q: - return; + private static async Task BrowseAsync(List stations, string clientId, string secret) { + var services = new ServiceCollection(); + services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Warning)); + services.AddDotBahnAuthorization(opt => { + opt.ClientId = clientId; + opt.ApiKey = secret; + }); + services.AddDotBahnStations(opt => opt.BaseEndpoint = new Uri("https://apis.deutschebahn.com/db-api-marketplace/apis/station-data/v2/")); + services.AddDotBahnFacilities(opt => opt.BaseEndpoint = new Uri("https://apis.deutschebahn.com/db-api-marketplace/apis/fasta/v2/")); + + var serviceProvider = services.BuildServiceProvider(); + var facilitiesClient = serviceProvider.GetRequiredService(); + + AnsiConsole.MarkupLine($"[green]Found {stations.Count} station(s)[/]"); + var facilitiesCache = new Dictionary>(); + + var currentIndex = 0; + while (true) { + var currentStation = stations[currentIndex]; + + if (!facilitiesCache.TryGetValue(currentStation.Number, out var facilities)) { + await AnsiConsole.Status().Spinner(Spinner.Known.Dots).StartAsync( + "Loading facilities...", + async _ => { + var query = new FacilityQuery().AtStation(currentStation.Number); + facilities = (await facilitiesClient.GetFacilitiesAsync(query)).ToList(); + facilitiesCache[currentStation.Number] = facilities; + }); + } + + AnsiConsole.Clear(); + RenderStation(currentStation, facilities ?? [], currentIndex, stations.Count); + RenderNavigation(); + + switch (Console.ReadKey(true).Key) { + case ConsoleKey.LeftArrow: + if (currentIndex > 0) { + currentIndex--; + } + + break; + case ConsoleKey.RightArrow: + if (currentIndex < stations.Count - 1) { + currentIndex++; + } + + break; + case ConsoleKey.Home: + currentIndex = 0; + break; + case ConsoleKey.End: + currentIndex = stations.Count - 1; + break; + case ConsoleKey.Escape: + case ConsoleKey.Q: + return; + } } } - } - private static void RenderStation(Station station, List facilities, int index, int total) { - var rule = new Rule(Markup.Escape(station.Name)) { - Justification = Justify.Center, - }; + private static void RenderStation(Station station, List facilities, int index, int total) { + var rule = new Rule(Markup.Escape(station.Name)) { + Justification = Justify.Center + }; - AnsiConsole.Write(rule); - RenderPositionBar(index, total); - AnsiConsole.WriteLine(); + AnsiConsole.Write(rule); + RenderPositionBar(index, total); + AnsiConsole.WriteLine(); - var leftPanel = BuildStationInfo(station); - var rightPanel = BuildRightPanel(station.Services, facilities); + var leftPanel = BuildStationInfo(station); + var rightPanel = BuildRightPanel(station.Services, facilities); - var layout = new Columns(leftPanel, rightPanel) { - Expand = true - }; + var layout = new Columns(leftPanel, rightPanel) { + Expand = true + }; - AnsiConsole.Write(layout); - } + AnsiConsole.Write(layout); + } - private static IRenderable BuildStationInfo(Station station) { - var rows = new List(); + private static IRenderable BuildStationInfo(Station station) { + var rows = new List(); - var infoGrid = new Grid(); - infoGrid.AddColumn(new GridColumn().Width(18)); - infoGrid.AddColumn(); + var infoGrid = new Grid(); + infoGrid.AddColumn(new GridColumn().Width(18)); + infoGrid.AddColumn(); - infoGrid.AddRow("[grey]Station Number[/]", $"{station.Number}"); - infoGrid.AddRow("[grey]Category[/]", FormatCategory(station.Category)); + infoGrid.AddRow("[grey]Station Number[/]", $"{station.Number}"); + infoGrid.AddRow("[grey]Category[/]", FormatCategory(station.Category)); - if (station.PrimaryEva != null) { - infoGrid.AddRow("[grey]EVA Number[/]", $"{station.PrimaryEva.Number}"); - } + if (station.PrimaryEva != null) { + infoGrid.AddRow("[grey]EVA Number[/]", $"{station.PrimaryEva.Number}"); + } - if (station.PrimaryRil100 != null) { - infoGrid.AddRow("[grey]RIL100[/]", Markup.Escape(station.PrimaryRil100.Identifier)); - } + if (station.PrimaryRil100 != null) { + infoGrid.AddRow("[grey]RIL100[/]", Markup.Escape(station.PrimaryRil100.Identifier)); + } - if (station.Coordinates != null) { - var c = station.Coordinates.Value; - infoGrid.AddRow("[grey]Coordinates[/]", $"{c.Latitude:F6}, {c.Longitude:F6}"); - } + if (station.Coordinates != null) { + var c = station.Coordinates.Value; + infoGrid.AddRow("[grey]Coordinates[/]", $"{c.Latitude:F6}, {c.Longitude:F6}"); + } - if (station.RegionalArea != null) { - infoGrid.AddRow("[grey]Regional Area[/]", Markup.Escape($"{station.RegionalArea.Name} ({station.RegionalArea.ShortName})")); - } + if (station.RegionalArea != null) { + infoGrid.AddRow("[grey]Regional Area[/]", Markup.Escape($"{station.RegionalArea.Name} ({station.RegionalArea.ShortName})")); + } - rows.Add(infoGrid); - rows.Add(new Text("")); - - if (station.Address != null) { - var addressPanel = new Panel( - Markup.Escape($"{station.Address.Street}\n{station.Address.ZipCode} {station.Address.City}") - ) { - Header = new PanelHeader("[blue]Address[/]"), - Border = BoxBorder.Rounded, - BorderStyle = Style.Parse("grey"), - Expand = false - }; - rows.Add(addressPanel); + rows.Add(infoGrid); rows.Add(new Text("")); - } - if (station.EvaNumbers.Count() > 1) { - rows.Add(new Markup("[grey]EVA Numbers:[/]")); - rows.AddRange(station.EvaNumbers.Select(eva => new Text($" {eva.Number}{(eva.IsMain ? " (main)" : "")}")).Cast()); - rows.Add(new Text("")); - } + if (station.Address != null) { + var addressPanel = new Panel( + Markup.Escape($"{station.Address.Street}\n{station.Address.ZipCode} {station.Address.City}") + ) { + Header = new PanelHeader("[blue]Address[/]"), + Border = BoxBorder.Rounded, + BorderStyle = Style.Parse("grey"), + Expand = false + }; + rows.Add(addressPanel); + rows.Add(new Text("")); + } + + if (station.EvaNumbers.Count > 1) { + rows.Add(new Markup("[grey]EVA Numbers:[/]")); + rows.AddRange(station.EvaNumbers.Select(eva => new Text($" {eva.Number}{(eva.IsMain ? " (main)" : "")}"))); + rows.Add(new Text("")); + } + + if (station.Ril100Identifiers.Count <= 1) { + return new Rows(rows); + } + + rows.Add(new Markup("[grey]RIL100 Identifiers:[/]")); + foreach (var ril in station.Ril100Identifiers) { + rows.Add(new Text($" {Markup.Escape(ril.Identifier)}{(ril.IsMain ? " (main)" : "")}")); + } - if (station.Ril100Identifiers.Count() <= 1) { return new Rows(rows); } - rows.Add(new Markup("[grey]RIL100 Identifiers:[/]")); - foreach (var ril in station.Ril100Identifiers) { - rows.Add(new Text($" {Markup.Escape(ril.Identifier)}{(ril.IsMain ? " (main)" : "")}")); - } + private static IRenderable BuildRightPanel(StationServices services, List facilities) { + var rows = new List(); - return new Rows(rows); - } + var servicesTable = new Table { + Border = TableBorder.Rounded, + BorderStyle = Style.Parse("grey") + }; + servicesTable.AddColumn(new TableColumn("[bold blue]Service[/]").LeftAligned()); + servicesTable.AddColumn(new TableColumn("[blue]?[/]").Centered()); + + AddServiceRow(servicesTable, "Parking", services.HasParking); + AddServiceRow(servicesTable, "Bicycle Parking", services.HasBicycleParking); + AddServiceRow(servicesTable, "Public Facilities", services.HasPublicFacilities); + AddServiceRow(servicesTable, "Locker System", services.HasLockerSystem); + AddServiceRow(servicesTable, "Step-Free Access", services.HasStepFreeAccess); + AddServiceRow(servicesTable, "Stepless Access", services.HasSteplessAccess); + AddServiceRow(servicesTable, "Travel Center", services.HasTravelCenter); + AddServiceRow(servicesTable, "Travel Necessities", services.HasTravelNecessities); + AddServiceRow(servicesTable, "Mobility Service", services.HasMobilityService); + AddServiceRow(servicesTable, "WiFi", services.HasWiFi); + + rows.Add(servicesTable); + + if (facilities.Count <= 0) { + return new Rows(rows); + } - private static IRenderable BuildRightPanel(StationServices services, List facilities) { - var rows = new List(); + rows.Add(new Text("")); + rows.Add(BuildFacilitiesPanel(facilities)); - var servicesTable = new Table { - Border = TableBorder.Rounded, - BorderStyle = Style.Parse("grey") - }; - servicesTable.AddColumn(new TableColumn("[bold blue]Service[/]").LeftAligned()); - servicesTable.AddColumn(new TableColumn("[blue]?[/]").Centered()); - - AddServiceRow(servicesTable, "Parking", services.HasParking); - AddServiceRow(servicesTable, "Bicycle Parking", services.HasBicycleParking); - AddServiceRow(servicesTable, "Public Facilities", services.HasPublicFacilities); - AddServiceRow(servicesTable, "Locker System", services.HasLockerSystem); - AddServiceRow(servicesTable, "Step-Free Access", services.HasStepFreeAccess); - AddServiceRow(servicesTable, "Stepless Access", services.HasSteplessAccess); - AddServiceRow(servicesTable, "Travel Center", services.HasTravelCenter); - AddServiceRow(servicesTable, "Travel Necessities", services.HasTravelNecessities); - AddServiceRow(servicesTable, "Mobility Service", services.HasMobilityService); - AddServiceRow(servicesTable, "WiFi", services.HasWiFi); - - rows.Add(servicesTable); - - if (facilities.Count <= 0) { return new Rows(rows); } - rows.Add(new Text("")); - rows.Add(BuildFacilitiesPanel(facilities)); - - return new Rows(rows); - } + private static IRenderable BuildFacilitiesPanel(List facilities) { + var elevators = facilities.Where(f => f.Type == FacilityType.Elevator).ToList(); + var escalators = facilities.Where(f => f.Type == FacilityType.Escalator).ToList(); - private static IRenderable BuildFacilitiesPanel(List facilities) { - var elevators = facilities.Where(f => f.Type == FacilityType.Elevator).ToList(); - var escalators = facilities.Where(f => f.Type == FacilityType.Escalator).ToList(); + var table = new Table { + Border = TableBorder.Rounded, + BorderStyle = Style.Parse("grey") + }; + table.AddColumn(new TableColumn("[bold blue]Facilities[/]").LeftAligned()); + table.AddColumn(new TableColumn("[blue]Status[/]").Centered()); + + var elevatorsActive = elevators.Count(f => f.State == FacilityState.Active); + var escalatorsActive = escalators.Count(f => f.State == FacilityState.Active); + + if (elevators.Count > 0) { + var color = elevatorsActive == elevators.Count ? "green" : + elevatorsActive == 0 ? "red" : "yellow"; + table.AddRow( + "Elevators", + $"[{color}]{elevatorsActive}/{elevators.Count}[/]" + ); + } - var table = new Table { - Border = TableBorder.Rounded, - BorderStyle = Style.Parse("grey") - }; - table.AddColumn(new TableColumn("[bold blue]Facilities[/]").LeftAligned()); - table.AddColumn(new TableColumn("[blue]Status[/]").Centered()); - - var elevatorsActive = elevators.Count(f => f.State == FacilityState.Active); - var escalatorsActive = escalators.Count(f => f.State == FacilityState.Active); - - if (elevators.Count > 0) { - var color = elevatorsActive == elevators.Count ? "green" : - elevatorsActive == 0 ? "red" : "yellow"; - table.AddRow( - "Elevators", - $"[{color}]{elevatorsActive}/{elevators.Count}[/]" - ); - } + if (escalators.Count > 0) { + var color = escalatorsActive == escalators.Count ? "green" : + escalatorsActive == 0 ? "red" : "yellow"; + table.AddRow( + "Escalators", + $"[{color}]{escalatorsActive}/{escalators.Count}[/]" + ); + } - if (escalators.Count > 0) { - var color = escalatorsActive == escalators.Count ? "green" : - escalatorsActive == 0 ? "red" : "yellow"; - table.AddRow( - "Escalators", - $"[{color}]{escalatorsActive}/{escalators.Count}[/]" - ); - } + var inactiveFacilities = facilities.Where(f => f.State != FacilityState.Active).ToList(); + if (inactiveFacilities.Count <= 0) { + return table; + } - var inactiveFacilities = facilities.Where(f => f.State != FacilityState.Active).ToList(); - if (inactiveFacilities.Count <= 0) { - return table; - } + table.AddEmptyRow(); + table.AddRow("[red]Out of service:[/]", ""); + foreach (var facility in inactiveFacilities.Take(5)) { + var typeIcon = facility.Type == FacilityType.Elevator ? "\u21c5" : "\u21f5"; + var desc = facility.Description ?? $"#{facility.EquipmentNumber}"; + if (desc.Length > 25) { + desc = desc[..22] + "..."; + } - table.AddEmptyRow(); - table.AddRow("[red]Out of service:[/]", ""); - foreach (var facility in inactiveFacilities.Take(5)) { - var typeIcon = facility.Type == FacilityType.Elevator ? "\u21c5" : "\u21f5"; - var desc = facility.Description ?? $"#{facility.EquipmentNumber}"; - if (desc.Length > 25) { - desc = desc[..22] + "..."; + table.AddRow($"[grey]{typeIcon} {Markup.Escape(desc)}[/]", ""); + } + if (inactiveFacilities.Count > 5) { + table.AddRow($"[grey]... and {inactiveFacilities.Count - 5} more[/]", ""); } - table.AddRow($"[grey]{typeIcon} {Markup.Escape(desc)}[/]", ""); - } - if (inactiveFacilities.Count > 5) { - table.AddRow($"[grey]... and {inactiveFacilities.Count - 5} more[/]", ""); + return table; } - return table; - } + private static string FormatCategory(StationCategory category) { + var (color, description) = category switch { + StationCategory.Category1 => ("green", "Major Hub"), + StationCategory.Category2 => ("aqua", "Large Station"), + StationCategory.Category3 => ("blue", "Important Regional"), + StationCategory.Category4 => ("default", "Regional Station"), + StationCategory.Category5 => ("grey", "Standard Station"), + StationCategory.Category6 => ("grey", "Small Station"), + StationCategory.Category7 => ("grey", "Minor Stop"), + _ => ("yellow", "Unknown") + }; - private static string FormatCategory(StationCategory category) { - var (color, description) = category switch { - StationCategory.Category1 => ("green", "Major Hub"), - StationCategory.Category2 => ("aqua", "Large Station"), - StationCategory.Category3 => ("blue", "Important Regional"), - StationCategory.Category4 => ("default", "Regional Station"), - StationCategory.Category5 => ("grey", "Standard Station"), - StationCategory.Category6 => ("grey", "Small Station"), - StationCategory.Category7 => ("grey", "Minor Stop"), - _ => ("yellow", "Unknown") - }; + var categoryNum = category switch { + StationCategory.Category1 => "1", + StationCategory.Category2 => "2", + StationCategory.Category3 => "3", + StationCategory.Category4 => "4", + StationCategory.Category5 => "5", + StationCategory.Category6 => "6", + StationCategory.Category7 => "7", + _ => "?" + }; - var categoryNum = category switch { - StationCategory.Category1 => "1", - StationCategory.Category2 => "2", - StationCategory.Category3 => "3", - StationCategory.Category4 => "4", - StationCategory.Category5 => "5", - StationCategory.Category6 => "6", - StationCategory.Category7 => "7", - _ => "?" - }; + return $"[bold {color}]{categoryNum}[/] [grey]({description})[/]"; + } - return $"[bold {color}]{categoryNum}[/] [grey]({description})[/]"; - } + private static void AddServiceRow(Table table, string name, bool available) { + var icon = available ? "[green]Yes[/]" : "[red]No[/]"; + table.AddRow(name, icon); + } - private static void AddServiceRow(Table table, string name, bool available) { - var icon = available ? "[green]Yes[/]" : "[red]No[/]"; - table.AddRow(name, icon); - } + private static void RenderPositionBar(int index, int total) { + var segments = new StringBuilder(); + for (var i = 0; i < total; i++) { + segments.Append(i == index ? "[blue]\u2588[/]" : "[grey]\u2591[/]"); + } - private static void RenderPositionBar(int index, int total) { - var segments = new StringBuilder(); - for (var i = 0; i < total; i++) { - segments.Append(i == index ? "[blue]\u2588[/]" : "[grey]\u2591[/]"); + AnsiConsole.MarkupLine(segments.ToString()); } - AnsiConsole.MarkupLine(segments.ToString()); + private static void RenderNavigation() { + AnsiConsole.WriteLine(); + AnsiConsole.Write(new Rule()); + AnsiConsole.MarkupLine("[grey]Navigation: [/]" + "[default]\u2190[/] Previous | [default]\u2192[/] Next | [default]Home[/] First | [default]End[/] Last | [default]Q/Esc[/] Quit"); + } } - private static void RenderNavigation() { - AnsiConsole.WriteLine(); - AnsiConsole.Write(new Rule()); - AnsiConsole.MarkupLine("[grey]Navigation: [/]" + "[default]\u2190[/] Previous | [default]\u2192[/] Next | [default]Home[/] First | [default]End[/] Last | [default]Q/Esc[/] Quit"); - } -} + [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = true)] + [JsonSerializable(typeof(StationsPayload))] + [JsonSerializable(typeof(ErrorPayload))] + internal sealed partial class StationBrowserJsonContext : JsonSerializerContext; -[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = true)] -[JsonSerializable(typeof(StationsPayload))] -[JsonSerializable(typeof(ErrorPayload))] -internal sealed partial class StationBrowserJsonContext : JsonSerializerContext; + internal sealed record StationsPayload(IEnumerable Stations); -internal sealed record StationsPayload(IEnumerable Stations); + internal sealed record StationDto(int Number, string Name, long? Eva, string? Category, double? Latitude, double? Longitude); -internal sealed record StationDto(int Number, string Name, long? Eva, string? Category, double? Latitude, double? Longitude); + internal sealed record ErrorPayload(ErrorDto Error); -internal sealed record ErrorPayload(ErrorDto Error); - -internal sealed record ErrorDto(string Code, string Message); + internal sealed record ErrorDto(string Code, string Message); +} diff --git a/samples/DotBahn.Samples.StationBrowser/dbstation.spec b/samples/DotBahn.Samples.StationBrowser/dbstation.spec index 3fb7a20..277a235 100644 --- a/samples/DotBahn.Samples.StationBrowser/dbstation.spec +++ b/samples/DotBahn.Samples.StationBrowser/dbstation.spec @@ -19,6 +19,7 @@ built with DotBahn (https://github.com/rlvelte/dotbahn). %install install -Dm755 dbstation %{buildroot}%{_bindir}/dbstation +install -Dm644 bom.json %{buildroot}%{_datadir}/%{name}/bom.json %check : @@ -26,6 +27,7 @@ install -Dm755 dbstation %{buildroot}%{_bindir}/dbstation %files %license LICENSE %{_bindir}/dbstation +%{_datadir}/%{name}/bom.json %changelog * Wed Oct 28 2026 Robin L. Velte - 2.1.1-0 diff --git a/samples/DotBahn.Samples.StationBrowser/packages.lock.json b/samples/DotBahn.Samples.StationBrowser/packages.lock.json index 0e06c31..561ff90 100644 --- a/samples/DotBahn.Samples.StationBrowser/packages.lock.json +++ b/samples/DotBahn.Samples.StationBrowser/packages.lock.json @@ -2,23 +2,6 @@ "version": 2, "dependencies": { "net10.0": { - "Microsoft.NET.ILLink.Tasks": { - "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "YlTamXppEQls6DYWt7RdUuwWDb0lyw/vXCaGeQpLCpsLmfwGuCkOz/vIGgMTV7ECsJcavkCOkxZXv9s8rdAHkQ==" - }, - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[10.0.403, )", - "resolved": "10.0.403", - "contentHash": "T4WYxWydJGNQRe/EgURFlhPZ1cHYgivrCCHSomCcfQzGzhkDYGNn5bUwwjs4/PHuMxsmGaLvPv2puG8lluA1IA==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "10.0.403", - "Microsoft.SourceLink.Common": "10.0.403", - "System.IO.Hashing": "10.0.14" - } - }, "MinVer": { "type": "Direct", "requested": "[8.0.0, )", @@ -36,236 +19,235 @@ }, "System.CommandLine": { "type": "Direct", - "requested": "[2.0.14, )", - "resolved": "2.0.14", - "contentHash": "15fyVO4aG6poR6IKmhM74zf7PUzaU6FZAGm2d3SQSO9yIyGAeo44e6t9qeKjjaqyMEqYdqcb2G1B0gpLoDU2cA==" + "requested": "[3.0.0, )", + "resolved": "3.0.0", + "contentHash": "swNpSTl0iYJeBuvYYfaY+VxzZ5YC8wklwkqDCNOq2aTQqJzjauJfh/O3Zw93nwxspWrxvZTjT45f8VPR0ParEA==" }, - "Microsoft.Build.Tasks.Git": { + "Microsoft.Extensions.AmbientMetadata.Application": { "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "1furteBFeemMmZ4s+ORjQb7YtO+wG63NJahbQbRUi91FV6V87BdV0U3vX1jbMC6iKSELYYoXWssSzLu3mx0i2w==", + "resolved": "11.0.1", + "contentHash": "tm28s2ODWZ6RdysP06NI3B23DUY5OfHG35ihMHxVAO3hywZAczDVjrkYMfBY//J4HQqfDHS5op84BhnF7ROseQ==", "dependencies": { - "System.IO.Hashing": "10.0.14" + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, - "Microsoft.Extensions.AmbientMetadata.Application": { + "Microsoft.Extensions.Compliance.Abstractions": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "aMCm7C6CexZT8W/p8zRp4BoxSnqRs3MmkBF7FvPIXC92b7vqs2SL0J+mVJi5W2Mk9Vb4ZRFWe9sdzFew6zUl1w==", + "resolved": "11.0.1", + "contentHash": "DUwdXgIxJKH9zBNg/SUBqOX0FpXCq7w80CIzrr0Jcw5tBXS926AtCcidoAsEHq5e/c6KQ8rWhSt7NxFxak8N/Q==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15" } }, - "Microsoft.Extensions.Compliance.Abstractions": { + "Microsoft.Extensions.Compliance.Redaction": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2mjAb3Sm5k6uNeI+IyXpggYMpfdDDGgZSwUm9QQsm5QgZboJWbm2eU+6wNMrlfFEao11yq6JS1zXI7SVQQ0NuQ==", + "resolved": "11.0.1", + "contentHash": "2rwe98yZEn4+aXjAg5DdcROMg6m2w3tejf/mRk4/fBCHKM2EWCaFTmbHLtz1BfyBxMY00/08XFoN0wzWYNiSiQ==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13" + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, "Microsoft.Extensions.Configuration": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Binder": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" }, "Microsoft.Extensions.DependencyInjection.AutoActivation": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "h/sovspxVmT2DTIbWORMG0Gi3zVcPQzNl3kbwtpo0LoUXYbe2+66wQqZYwaF2ZWKN8HDdHv5yoc7d0DbDBBlnA==", + "resolved": "11.0.1", + "contentHash": "OuVIF5TmsfonN2Fqmi2zlUtbFQNqQiflhgo/rh64ptrqYrB4wZLwKbXr/HzrQXMf+h3jIbWrjIdJFspGqcvuuQ==", "dependencies": { - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13" + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15" } }, "Microsoft.Extensions.Diagnostics": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "80VqW8eKxQaxBOLDNpLUdxOlxzWn/jqBSxNBCfD8GCjcshNDpFvUgKh8uvvZwvkfBbwmNPWPWHyy9F+RLd1dlQ==", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" } }, "Microsoft.Extensions.Diagnostics.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vm+PPso6vOwGeX52MdOPh6z/R6KHgxQUwqq7k7Jc9jhy2JOxO2KB4xfoJQBBp2Ni8M4zKgJ4r2a1dgrYG7+MKw==", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "Dp/FaAPo3U9h3HsWT1dcdRRV//rm+MQF5iKpY/WxL5swwV+wZNE5eyJZ0kgy9Upl/kHz4ejpiLMloxDIuJaoJQ==", + "resolved": "11.0.1", + "contentHash": "mqqpmAFNRLa4cozN3RvT/T81k4aarwMc8xb8VVQgLqUE7AAoN/WWayZAvP+4hy9+KujP3dfn3taU06fZJPIbgA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13" + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" } }, "Microsoft.Extensions.FileProviders.Abstractions": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "BZDwtN3uoWRghDi5lRRZPDjMMCg2Ds7J6YEYjqka/TLjqnzquEpXyvchrIMeoubwT1ns23ow6PPeAoBHJO81Rw==", + "resolved": "10.0.15", + "contentHash": "1RSYAUtJeb76m2T0u5BbvwKY3s+ge9fT3cj1odvo5Bm+frc7pU9RSeXeMIlYHV8GjpqLdv2neeeomz010yYL8A==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.13" + "Microsoft.Extensions.Primitives": "10.0.15" } }, "Microsoft.Extensions.Hosting.Abstractions": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "zIrbe9vkIFXxW3mOApIOWXw+xMwX7Cgsptr3ZSlglJt4hW2qp4fB/JU1NHgAevteBNH4PicvU9DsFPHxlnnloA==", + "resolved": "10.0.15", + "contentHash": "s/JBiwR3F/vKRCbe6WO5b6t6or1ISaZ3rllchcw6/FSWZmK8s2fAzD7elrZo7592FnMD1fhGoG/wuJL1YYtVXw==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13" + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15" } }, "Microsoft.Extensions.Http.Diagnostics": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "iFcxcuMF/21LO+tDqDyzYVvokJUH03cNalmOJhmjyQSMV3dR4JAgcUBTV1iVH/yruC8wG2RNjvW0xcUgYqmrGg==", + "resolved": "11.0.1", + "contentHash": "mKHY0oFYL3fkAOhBNi2LqWPuEdUJ+HiF28KKUwBkQG2sgXAUdFDDqvJAfu2PcYgtAwsAtl58zuk4SElpPzbCvA==", "dependencies": { - "Microsoft.Extensions.Http": "10.0.13", - "Microsoft.Extensions.Telemetry": "10.11.0" + "Microsoft.Extensions.Compliance.Redaction": "11.0.1", + "Microsoft.Extensions.Http": "10.0.15", + "Microsoft.Extensions.Telemetry": "11.0.1" } }, "Microsoft.Extensions.Logging": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Logging.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Logging.Configuration": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "OyYJOaE9WbBx1Hp+Dd2zrqeFM0JwH5M/x0VL6tNUv3V18vIAVpix8UjhvY9eW/iXpguEHy68JO/Z9YkBOwftIw==", + "resolved": "10.0.15", + "contentHash": "Km6Ml1/nu0T/f80Btonxf9CWmP/BXI84aJwC5fUbCxRArJ0lH++0ADQrjErZvsSIrKhusTkTSGBChKy2fYAF4w==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.Configuration.Binder": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Configuration.Binder": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, "Microsoft.Extensions.ObjectPool": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "NX3bhcc0WitPKAVc9Zfi8jeEPClhfEmobUJM4a4bkWhJcBt5IWg6lCrItUoFy4whLjU+atXktURYCweQlR7wfg==" + "resolved": "10.0.15", + "contentHash": "kvd9eyRRQ+OEu9wik7GKgTS+7XnJ5XoOtSXJqmkJtVYV/S4gsBUrobYRSdNeBcb0ymef4L5Q9pZGiTxJ8jJfyQ==" }, "Microsoft.Extensions.Options.ConfigurationExtensions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4wcIU0rE04ejEfCwHTftu9O8fgH6CRYCe+tseRapikUBn1Kic3QdO7ku22SwFyLrzdWGYPUZMEgv57ZYuuc5gA==", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Primitives": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" }, "Microsoft.Extensions.Resilience": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "GbN7R2BOoZf3F7aK02nz9kWf6ttbvVzpw1orGG30VmrKTmRV6pasQOCfF2fjKXyHIMC/lAiBEYHCKjgf0OiGvQ==", + "resolved": "11.0.1", + "contentHash": "xgKof6iwAByZNrxWOa7Drk4A953L7U2HleTmx7EXE2Vf6j1crp4RsvNlIVsJMtHKf3ftGKd9gOhR3xES9vxUgg==", "dependencies": { - "Microsoft.Extensions.Diagnostics": "10.0.13", - "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "10.11.0", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0", + "Microsoft.Extensions.Diagnostics": "10.0.15", + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1", "Polly.Extensions": "8.4.2", "Polly.RateLimiting": "8.4.2" } }, "Microsoft.Extensions.Telemetry": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2meCfABvkLPtEBBwGzItIGnhrex1AEn2N+dHvxB5UoozeX/xTtBuUz5BRdjNI5oNgd5T31kC69WWw3BHDc9iZA==", + "resolved": "11.0.1", + "contentHash": "9uuA8entTC9m00m59h6CACSt4IQh9KknB+hPvCteXUTiG67lqJ8BI65fEUJSPSfT3ZDDi01Zg2aY5kRUvD4HPw==", "dependencies": { - "Microsoft.Extensions.AmbientMetadata.Application": "10.11.0", - "Microsoft.Extensions.DependencyInjection.AutoActivation": "10.11.0", - "Microsoft.Extensions.Logging.Configuration": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0" + "Microsoft.Extensions.AmbientMetadata.Application": "11.0.1", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "11.0.1", + "Microsoft.Extensions.Logging.Configuration": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1" } }, "Microsoft.Extensions.Telemetry.Abstractions": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "FzcHRan/C2g5X5KD0kPlL4tTROFRpM8sqcXfOIi6FGLsw/d2yoOYMbLJ5hyb8N5QgOVW7e1TdwEN4zVUfcwfdw==", + "resolved": "11.0.1", + "contentHash": "qINZz4G01Wxumqd0hLr6YdzPa3s7jexQWN28EenaiJQnmKdsR9FnBaKENdRRElLc+A5bJKQ+jYw/WHG4ZpIyAg==", "dependencies": { - "Microsoft.Extensions.Compliance.Abstractions": "10.11.0", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13" + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15" } }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "SvzUeqFGrcQxlIgjmcoSGiV5UWcPa0NCTuH69/40uSDsSD/26c6p9cH7XLAxpn+I8+2Zhl1qp+WMugl0oOwBMg==" - }, "Polly.Core": { "type": "Transitive", "resolved": "8.4.2", @@ -295,10 +277,10 @@ "resolved": "0.57.2", "contentHash": "Y1+u73shwP+JYHmrkdN6bSt2kaGBEAafhi2nrecczbXdFRey+k7J/WF9YPfcB0rqivv2S8fmif6FSBq9m/AFvw==" }, - "System.IO.Hashing": { + "System.Diagnostics.DiagnosticSource": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "lVqovhCt3HlZe7ONG5ydaj6BYwYI004gldVfMMkJl/lR5ueeCtWNpW4nejOX75sPmzm8vXCxB69GqwHaYCnyUQ==" + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" }, "System.Threading.RateLimiting": { "type": "Transitive", @@ -308,61 +290,61 @@ "dotbahn.common": { "type": "Project", "dependencies": { - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Options": "[10.0.14, )" + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" } }, "dotbahn.facilities": { "type": "Project", "dependencies": { "DotBahn.Common": "[1.0.0, )", - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Http.Resilience": "[10.11.0, )", - "Microsoft.Extensions.Options": "[10.0.14, )" + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Http.Resilience": "[11.0.1, )", + "Microsoft.Extensions.Options": "[11.0.0, )" } }, "dotbahn.stations": { "type": "Project", "dependencies": { "DotBahn.Common": "[1.0.0, )", - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Http.Resilience": "[10.11.0, )", - "Microsoft.Extensions.Options": "[10.0.14, )" + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Http.Resilience": "[11.0.1, )", + "Microsoft.Extensions.Options": "[11.0.0, )" } }, "Microsoft.Extensions.Http": { "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "IDsXLGGz7nJMsqspWnErsP18WyAVf6V9Ixl4p47/8/95Jak3ZA1YWhQ0iesMVwubVhkVZGoO9m9ADUnK0m6HLw==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Http.Resilience": { "type": "CentralTransitive", - "requested": "[10.11.0, )", - "resolved": "10.11.0", - "contentHash": "6/YEoPCcQLzExm4x4FH5c38JffbhkMaTtXsrDmYNozt9KRtdXK3TsDeuKSBZJno+41oIDGBONb2up0zCsuEERw==", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "5VawCrg+VgVT2hNurSSEWUnq0pvNoH+Zt82s5Wpl/8jdnmU8DpRlr+M3DcdtVgeBG7mRyk3GtSRbf8PB/HrL3w==", "dependencies": { - "Microsoft.Extensions.Http.Diagnostics": "10.11.0", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Resilience": "10.11.0" + "Microsoft.Extensions.Http.Diagnostics": "11.0.1", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Resilience": "11.0.1" } }, "Microsoft.Extensions.Options": { "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } } } diff --git a/samples/DotBahn.Samples.TimetablePeek/DotBahn.Samples.TimetablePeek.csproj b/samples/DotBahn.Samples.TimetablePeek/DotBahn.Samples.TimetablePeek.csproj index 3f18600..bf072ca 100644 --- a/samples/DotBahn.Samples.TimetablePeek/DotBahn.Samples.TimetablePeek.csproj +++ b/samples/DotBahn.Samples.TimetablePeek/DotBahn.Samples.TimetablePeek.csproj @@ -15,6 +15,6 @@ - + diff --git a/samples/DotBahn.Samples.TimetablePeek/Program.cs b/samples/DotBahn.Samples.TimetablePeek/Program.cs index d4dd64c..9551866 100644 --- a/samples/DotBahn.Samples.TimetablePeek/Program.cs +++ b/samples/DotBahn.Samples.TimetablePeek/Program.cs @@ -1,14 +1,15 @@ using System.CommandLine; using System.Diagnostics; +using System.Globalization; using System.Text.Json; using System.Text.Json.Serialization; +using DotBahn.Boards; +using DotBahn.Boards.Models; +using DotBahn.Boards.Models.Entries; using DotBahn.Common.Auth; using DotBahn.Common.Clients; -using DotBahn.Common.Models; +using DotBahn.Samples.TimetablePeek; using DotBahn.Telemetry; -using DotBahn.Timetables; -using DotBahn.Timetables.Models; -using DotBahn.Timetables.Models.Enumerations; using Microsoft.Extensions.DependencyInjection; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; @@ -16,314 +17,312 @@ return await TimetablePeekCli.BuildRootCommand().Parse(args).InvokeAsync(); -internal static class TimetablePeekCli { - private static readonly Uri BaseEndpoint = new("https://apis.deutschebahn.com/db-api-marketplace/apis/timetables/v1/"); - - private static readonly Argument EvaArgument = new("eva") { - Description = "EVA station number (e.g. 8098160)", - Arity = ArgumentArity.ZeroOrOne, - }; - - private static readonly Option CategoryOption = new("--category", "-c") { - Description = "Train category to filter for (e.g. ICE, RB); defaults to all categories", - }; - - private static readonly Option LimitOption = new("--limit", "-n") { - Description = "Maximum number of departures to show (1-100)", - DefaultValueFactory = _ => 20, - }; - - private static readonly Option WindowOption = new("--window", "-w") { - Description = "Look-ahead window for the timetable, in hours (1-24)", - DefaultValueFactory = _ => 24, - }; - - private static readonly Option ClientIdOption = new("--client") { - Description = "DB API client id; falls back to the DOTBAHN_CLIENT environment variable", - }; - - private static readonly Option SecretOption = new("--secret") { - Description = "DB API secret; falls back to the DOTBAHN_SECRET environment variable", - }; - - private static readonly Option JsonOption = new("--json", "-j") { - Description = "Print departures as JSON instead of a table", - }; - - internal static RootCommand BuildRootCommand() { - var rootCommand = new RootCommand("Deutsche Bahn departure monitor showing the next departures at a station") { - EvaArgument, - CategoryOption, - LimitOption, - WindowOption, - ClientIdOption, - SecretOption, - JsonOption, +namespace DotBahn.Samples.TimetablePeek { + internal static class TimetablePeekCli { + private static readonly Uri BaseEndpoint = new("https://apis.deutschebahn.com/db-api-marketplace/apis/open-boards/v1/"); + + private static readonly Argument EvaArgument = new("eva") { + Description = "EVA station number (e.g. 8098160)", + Arity = ArgumentArity.ZeroOrOne }; - rootCommand.Validators.Add(result => { - var eva = result.GetValue(EvaArgument); - if (string.IsNullOrWhiteSpace(eva)) { - result.AddError("An EVA station number must be supplied: pass it as first argument (e.g. 8098160)."); - } else if (!int.TryParse(eva, out _)) { - result.AddError("eva must be a numeric EVA station number (e.g. 8098160)."); - } - }); + private static readonly Option ArrivalsOption = new("--arrivals", "-a") { + Description = "Show arrivals instead of departures" + }; - CategoryOption.Validators.Add(result => { - var category = result.GetValue(CategoryOption); - if (category is { Length: 0 }) { - result.AddError("--category must not be empty."); - } - }); - - LimitOption.Validators.Add(result => { - var limit = result.GetValue(LimitOption); - if (limit < 1) { - result.AddError("--limit must be at least 1."); - } else if (limit > 100) { - result.AddError("--limit must be at most 100."); - } - }); - - WindowOption.Validators.Add(result => { - var window = result.GetValue(WindowOption); - if (window < 1) { - result.AddError("--window must be at least 1."); - } else if (window > 24) { - result.AddError("--window must be at most 24."); - } - }); + private static readonly Option CategoryOption = new("--category", "-c") { + Description = "Train category to filter for (e.g. ICE, RB); defaults to all categories" + }; - rootCommand.SetAction(async (parseResult, cancellationToken) => { - var eva = parseResult.GetValue(EvaArgument); - var category = parseResult.GetValue(CategoryOption); - var limit = parseResult.GetValue(LimitOption); - var window = parseResult.GetValue(WindowOption); - var clientId = parseResult.GetValue(ClientIdOption); - var secret = parseResult.GetValue(SecretOption); - var json = parseResult.GetValue(JsonOption); + private static readonly Option LimitOption = new("--limit", "-n") { + Description = "Maximum number of entries to show (1-100)", + DefaultValueFactory = _ => 20 + }; - return await RunAsync(eva, category, limit, window, clientId, secret, json, cancellationToken); - }); + private static readonly Option WindowOption = new("--window", "-w") { + Description = "Time window for the board, in hours (1-8)", + DefaultValueFactory = _ => 8 + }; - return rootCommand; - } + private static readonly Option ClientIdOption = new("--client") { + Description = "DB API client id; falls back to the DOTBAHN_CLIENT environment variable" + }; - private static async Task RunAsync(string? eva, string? category, int limit, int window, string? clientId, string? secret, bool json, CancellationToken cancellationToken) { - if (!int.TryParse(eva, out var evaNumber)) { - throw new UnreachableException("eva was validated but could not be parsed."); - } + private static readonly Option SecretOption = new("--secret") { + Description = "DB API secret; falls back to the DOTBAHN_SECRET environment variable" + }; - if (!ResolveCredentials(clientId, secret, out var resolvedClientId, out var resolvedSecret)) { - if (json) { - WriteJsonError("missing-credentials", "Provide --client/--secret or set DOTBAHN_CLIENT and DOTBAHN_SECRET."); - } else { - AnsiConsole.MarkupLine("[red]Usage:[/] provide --client/--secret, or set DOTBAHN_CLIENT / DOTBAHN_SECRET via env or CLI args"); - } - return 1; - } + private static readonly Option JsonOption = new("--json", "-j") { + Description = "Print entries as JSON instead of a table" + }; - var services = new ServiceCollection(); - services.AddOpenTelemetry() - .WithTracing(tracing => tracing.AddOtlpExporter()) - .WithMetrics(metrics => metrics.AddOtlpExporter()); - services.AddDotBahnTelemetry(); - await using var telemetry = services.BuildServiceProvider(); - _ = telemetry.GetRequiredService(); - _ = telemetry.GetRequiredService(); - - using var client = new TimetableClient( - new ClientOptions { - BaseEndpoint = BaseEndpoint, - }, - new AuthorizationOptions { - ClientId = resolvedClientId, - ApiKey = resolvedSecret, + internal static RootCommand BuildRootCommand() { + var rootCommand = new RootCommand("Deutsche Bahn arrival/departure board (OpenBoards API)") { + EvaArgument, + ArrivalsOption, + CategoryOption, + LimitOption, + WindowOption, + ClientIdOption, + SecretOption, + JsonOption + }; + + rootCommand.Validators.Add(result => { + var eva = result.GetValue(EvaArgument); + if (string.IsNullOrWhiteSpace(eva)) { + result.AddError("An EVA station number must be supplied: pass it as first argument (e.g. 8098160)."); + } else if (!int.TryParse(eva, out _)) { + result.AddError("eva must be a numeric EVA station number (e.g. 8098160)."); + } }); - try { - var (timetable, departures) = await FetchAsync(client, evaNumber, category, limit, window, cancellationToken); - - if (json) { - var payload = new DeparturePayload(evaNumber, timetable.Station, [.. departures.Select(ToDepartureDto)]); - Console.WriteLine(JsonSerializer.Serialize(payload, TimetablePeekJsonContext.Default.DeparturePayload)); - return departures.Count > 0 ? 0 : 1; - } + CategoryOption.Validators.Add(result => { + var category = result.GetValue(CategoryOption); + if (category is { Length: 0 }) { + result.AddError("--category must not be empty."); + } + }); - AnsiConsole.Clear(); - RenderHeader(timetable.Station, evaNumber); - if (departures.Count == 0) { - AnsiConsole.MarkupLine("[yellow]No departures found.[/]"); - return 1; - } + LimitOption.Validators.Add(result => { + var limit = result.GetValue(LimitOption); + if (limit < 1) { + result.AddError("--limit must be at least 1."); + } else if (limit > 100) { + result.AddError("--limit must be at most 100."); + } + }); - RenderDepartures(departures); - return 0; - } catch (OperationCanceledException) { - return 130; - } catch (HttpRequestException ex) { - if (json) { - WriteJsonError("api-error", ex.Message); - } else { - AnsiConsole.MarkupLine($"[red]Error:[/] {Markup.Escape(ex.Message)}"); - } - return 1; - } - } + WindowOption.Validators.Add(result => { + var window = result.GetValue(WindowOption); + if (window < 1) { + result.AddError("--window must be at least 1."); + } else if (window > 8) { + result.AddError("--window must be at most 8 (API limit)."); + } + }); - private static bool ResolveCredentials(string? clientId, string? secret, out string resolvedClientId, out string resolvedSecret) { - _ = TryCredentialsFromEnvironment(out var envClient, out var envSecret); - resolvedClientId = clientId ?? envClient; - resolvedSecret = secret ?? envSecret; - return !string.IsNullOrEmpty(resolvedClientId) && !string.IsNullOrEmpty(resolvedSecret); - } + rootCommand.SetAction(async (parseResult, cancellationToken) => { + var eva = parseResult.GetValue(EvaArgument); + var arrivals = parseResult.GetValue(ArrivalsOption); + var category = parseResult.GetValue(CategoryOption); + var limit = parseResult.GetValue(LimitOption); + var window = parseResult.GetValue(WindowOption); + var clientId = parseResult.GetValue(ClientIdOption); + var secret = parseResult.GetValue(SecretOption); + var json = parseResult.GetValue(JsonOption); + + return await RunAsync(eva, arrivals, category, limit, window, clientId, secret, json, cancellationToken); + }); - private static bool TryCredentialsFromEnvironment(out string clientId, out string clientSecret) { - clientId = Environment.GetEnvironmentVariable("DOTBAHN_CLIENT") ?? string.Empty; - clientSecret = Environment.GetEnvironmentVariable("DOTBAHN_SECRET") ?? string.Empty; - return !string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(clientSecret); - } + return rootCommand; + } - private static async Task LoadTimetableAsync(TimetableClient client, int eva, int window, CancellationToken cancellationToken) { - var start = DateTime.Now; - var stops = new Dictionary(); - Timetable? first = null; + private static async Task RunAsync(string? eva, bool arrivals, string? category, int limit, int window, string? clientId, string? secret, bool json, CancellationToken cancellationToken) { + if (!int.TryParse(eva, out var evaNumber)) { + throw new UnreachableException("eva was validated but could not be parsed."); + } - for (var h = new DateTime(start.Year, start.Month, start.Day, start.Hour, 0, 0); h < start.AddHours(window); h = h.AddHours(1)) { - var data = await client.GetTimetableAsync(eva, h, cancellationToken); + if (!ResolveCredentials(clientId, secret, out var resolvedClientId, out var resolvedSecret)) { + if (json) { + WriteJsonError("missing-credentials", "Provide --client/--secret or set DOTBAHN_CLIENT and DOTBAHN_SECRET."); + } else { + AnsiConsole.MarkupLine("[red]Usage:[/] provide --client/--secret, or set DOTBAHN_CLIENT / DOTBAHN_SECRET via env or CLI args"); + } + return 1; + } - first ??= data; - foreach (var s in data.Stops) { - stops[s.Id] = s; + var services = new ServiceCollection(); + services.AddOpenTelemetry() + .WithTracing(tracing => tracing.AddOtlpExporter()) + .WithMetrics(metrics => metrics.AddOtlpExporter()); + services.AddDotBahnTelemetry(); + await using var telemetry = services.BuildServiceProvider(); + _ = telemetry.GetRequiredService(); + _ = telemetry.GetRequiredService(); + + using var client = new BoardsClient( + new ClientOptions { + BaseEndpoint = BaseEndpoint + }, + new AuthorizationOptions { + ClientId = resolvedClientId, + ApiKey = resolvedSecret + }); + + try { + var query = new BoardQuery() + .ForEvaNumbers(evaNumber.ToString(CultureInfo.InvariantCulture)) + .StartingAt(DateTime.Now) + .EndingAt(DateTime.Now.AddHours(window)) + .WithPlatformAccessibility(); + + var entries = new List(); + string station; + + if (arrivals) { + var board = await client.GetArrivalsAsync(query, cancellationToken); + station = BoardStation(board.ConsideredStopPlaces, evaNumber); + entries.AddRange(board.Entries + .Where(e => Matches(e.Transport.Category, category)) + .Select(ToArrivalDto)); + } else { + var board = await client.GetDeparturesAsync(query, cancellationToken); + station = BoardStation(board.ConsideredStopPlaces, evaNumber); + entries.AddRange(board.Entries + .Where(e => Matches(e.Transport.Category, category)) + .Select(ToDepartureDto)); + } + + entries = entries + .Where(e => e.Actual >= DateTime.Now) + .OrderBy(e => e.Actual) + .Take(limit) + .ToList(); + + if (json) { + var payload = new BoardPayload(evaNumber, station, arrivals ? "arrivals" : "departures", entries); + Console.WriteLine(JsonSerializer.Serialize(payload, TimetablePeekJsonContext.Default.BoardPayload)); + return entries.Count > 0 ? 0 : 1; + } + + AnsiConsole.Clear(); + RenderHeader(station, evaNumber, arrivals); + if (entries.Count == 0) { + AnsiConsole.MarkupLine($"[yellow]No {(arrivals ? "arrivals" : "departures")} found.[/]"); + return 1; + } + + RenderBoard(entries, arrivals); + return 0; + } catch (OperationCanceledException) { + return 130; + } catch (HttpRequestException ex) { + if (json) { + WriteJsonError("api-error", ex.Message); + } else { + AnsiConsole.MarkupLine($"[red]Error:[/] {Markup.Escape(ex.Message)}"); + } + return 1; } } - return new Timetable { - Station = first?.Station ?? $"EVA {eva}", - Stops = stops.Values, - Messages = [], - }; - } - - private static async Task<(Timetable Timetable, List Departures)> FetchAsync(TimetableClient client, int eva, string? category, int limit, int window, CancellationToken cancellationToken) { - var timetable = await LoadTimetableAsync(client, eva, window, cancellationToken); - timetable = await client.GetFullChangesAsync(eva, timetable, cancellationToken); - return (timetable, SelectDepartures(timetable, category, limit)); - } - - private static List SelectDepartures(Timetable timetable, string? category, int limit) => timetable.Stops - .Where(s => category is null || category.Equals(s.Train.Category, StringComparison.OrdinalIgnoreCase)) - .Where(s => s.Departure is { Status.Actual: not EventStatus.Cancelled }) - .Where(s => s.Departure!.Time.Actual >= DateTime.Now) - .OrderBy(s => s.Departure!.Time.Actual) - .Take(limit) - .ToList(); - - private static DepartureDto ToDepartureDto(TimetableStop stop) { - var dep = stop.Departure!; - return new DepartureDto( - stop.Train.DisplayName, - stop.Train.Category, - dep.Time.Original, - dep.Time.Actual, - (int)(dep.Time.Actual - dep.Time.Original).TotalMinutes, - dep.Platform.HasUpdate ? dep.Platform.Actual : dep.Platform.Original, - dep.Path.Actual.LastOrDefault(), - [.. dep.Path.Actual.SkipLast(1)]); - } - - private static void WriteJsonError(string code, string message) { - var payload = new ErrorPayload(new ErrorDto(code, message)); - Console.WriteLine(JsonSerializer.Serialize(payload, TimetablePeekJsonContext.Default.ErrorPayload)); - } - - private static void RenderHeader(string station, int eva) { - AnsiConsole.Write(new Rule($"Departures \u2013 {Markup.Escape(station)}") { - Justification = Justify.Center, - }); - AnsiConsole.MarkupLine($"[grey]EVA {eva} | {DateTime.Now:HH:mm}[/]\n"); - } - - private static void RenderDepartures(List stops) { - if (stops.Count == 0) { - AnsiConsole.WriteLine("No departures found."); - return; + private static bool Matches(string category, string? filter) => + filter is null || filter.Equals(category, StringComparison.OrdinalIgnoreCase); + + private static string BoardStation(IReadOnlyList stopPlaces, int eva) => + stopPlaces.FirstOrDefault()?.Name ?? $"EVA {eva}"; + + private static BoardEntryDto ToArrivalDto(ArrivalEntry entry) => CreateDto( + entry, entry.Journey.Origin.StopPlace.Name); + + private static BoardEntryDto ToDepartureDto(DepartureEntry entry) => CreateDto( + entry, entry.Journey.Destination.StopPlace.Name); + + private static BoardEntryDto CreateDto(BoardEntry entry, string stationName) { + var time = entry.Time; + return new BoardEntryDto( + Train: $"{entry.Transport.Category} {entry.Transport.Number}", + Category: entry.Transport.Category, + Planned: time.Original, + Actual: time.Actual, + DelayMinutes: (int)(time.Actual - time.Original).TotalMinutes, + Platform: entry.Platform.Actual.Name, + Station: stationName, + Via: entry.Transport.Via + .Take(Math.Max(0, entry.Transport.Via.Count - 1)) + .Select(v => v.StopPlace.Name) + .ToList()); } - var table = new Table() - .Border(TableBorder.Rounded) - .BorderColor(Color.Grey) - .AddColumn("[bold]Train[/]") - .AddColumn("[bold]Departure[/]") - .AddColumn("[bold]Platf.[/]") - .AddColumn("[bold]Destination[/]") - .AddColumn("[bold]Via[/]"); - - foreach (var stop in stops) { - var dep = stop.Departure!; - table.AddRow(FormatTrain(stop.Train.DisplayName), FormatTime(dep.Time), FormatPlatform(dep.Platform), FormatDestination(dep.Path), FormatVia(dep.Path)); + private static bool ResolveCredentials(string? clientId, string? secret, out string resolvedClientId, out string resolvedSecret) { + _ = TryCredentialsFromEnvironment(out var envClient, out var envSecret); + resolvedClientId = clientId ?? envClient; + resolvedSecret = secret ?? envSecret; + return !string.IsNullOrEmpty(resolvedClientId) && !string.IsNullOrEmpty(resolvedSecret); } - AnsiConsole.Write(table); - AnsiConsole.MarkupLine($"[grey]Showing {stops.Count} departure(s)[/]\n"); - } + private static bool TryCredentialsFromEnvironment(out string clientId, out string clientSecret) { + clientId = Environment.GetEnvironmentVariable("DOTBAHN_CLIENT") ?? string.Empty; + clientSecret = Environment.GetEnvironmentVariable("DOTBAHN_SECRET") ?? string.Empty; + return !string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(clientSecret); + } - private static string FormatTrain(string trainName) => $"[bold]{Markup.Escape(trainName)}[/]"; + private static void WriteJsonError(string code, string message) { + var payload = new ErrorPayload(new ErrorDto(code, message)); + Console.WriteLine(JsonSerializer.Serialize(payload, TimetablePeekJsonContext.Default.ErrorPayload)); + } - private static string FormatTime(ChangedValue t) { - var p = t.Original.ToString("HH:mm"); - if (!t.HasUpdate) { - return $"[green]{p}[/]"; + private static void RenderHeader(string station, int eva, bool arrivals) { + var title = arrivals ? "Arrivals" : "Departures"; + AnsiConsole.Write(new Rule($"{title} \u2013 {Markup.Escape(station)}") { + Justification = Justify.Center + }); + AnsiConsole.MarkupLine($"[grey]EVA {eva} | {DateTime.Now:HH:mm}[/]\n"); } - var a = t.Actual.ToString("HH:mm"); - var d = (int)(t.Actual - t.Original).TotalMinutes; - return d <= 0 ? $"[green]{a}[/]" : $"[strikethrough grey]{p}[/] [bold red]{a} (+{d})[/]"; - } + private static void RenderBoard(List entries, bool arrivals) { + var stationHeader = arrivals ? "[bold]Origin[/]" : "[bold]Destination[/]"; + var table = new Table() + .Border(TableBorder.Rounded) + .BorderColor(Color.Grey) + .AddColumn("[bold]Train[/]") + .AddColumn(arrivals ? "[bold]Arrival[/]" : "[bold]Departure[/]") + .AddColumn("[bold]Platf.[/]") + .AddColumn(stationHeader) + .AddColumn("[bold]Via[/]"); + + foreach (var entry in entries) { + table.AddRow( + FormatTrain(entry.Train), + FormatTime(entry.Planned, entry.Actual, entry.DelayMinutes), + Markup.Escape(entry.Platform ?? "-"), + $"[bold]{Markup.Escape(entry.Station)}[/]", + FormatVia(entry.Via)); + } - private static string FormatPlatform(ChangedRef p) { - if (!p.HasUpdate || p.Updated == p.Original) { - return Markup.Escape(p.Original); + AnsiConsole.Write(table); + var label = arrivals ? "arrival(s)" : "departure(s)"; + AnsiConsole.MarkupLine($"[grey]Showing {entries.Count} {label}[/]\n"); } - return $"[strikethrough grey]{Markup.Escape(p.Original)}[/] [bold red]{Markup.Escape(p.Actual)}[/]"; - } + private static string FormatTrain(string trainName) => $"[bold]{Markup.Escape(trainName)}[/]"; + + private static string FormatTime(DateTime planned, DateTime actual, int delay) { + var p = planned.ToString("HH:mm", CultureInfo.InvariantCulture); + if (delay <= 0) { + return $"[green]{p}[/]"; + } - private static string FormatDestination(ChangedRef> p) { - var planned = Markup.Escape(p.Original.LastOrDefault() ?? "-"); - var actual = Markup.Escape(p.Actual.LastOrDefault() ?? "-"); - if (!p.HasUpdate || planned == actual) { - return $"[bold]{planned}[/]"; + var a = actual.ToString("HH:mm", CultureInfo.InvariantCulture); + return $"[strikethrough grey]{p}[/] [bold red]{a} (+{delay})[/]"; } - return $"[strikethrough grey]{planned}[/] [bold red]{actual}[/]"; - } + private static string FormatVia(IEnumerable stops) { + var list = stops.ToList(); + if (list.Count == 0) { + return "[grey]-[/]"; + } - private static string FormatVia(ChangedRef> p) { - var stops = p.Actual.ToList(); - if (stops.Count <= 1) { - return "[grey]-[/]"; - } + var via = string.Join(" \u2013 ", list.Take(3).Select(Markup.Escape)); + if (list.Count > 3) { + via += " \u2026"; + } - var via = string.Join(" \u2013 ", stops.Take(Math.Min(3, stops.Count - 1)).Select(Markup.Escape)); - if (stops.Count > 4) { - via += " \u2026"; + return $"[grey]{via}[/]"; } - - return p.HasUpdate ? $"[orange1]{via}[/]" : $"[grey]{via}[/]"; } -} -[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = true)] -[JsonSerializable(typeof(DeparturePayload))] -[JsonSerializable(typeof(ErrorPayload))] -internal sealed partial class TimetablePeekJsonContext : JsonSerializerContext; + [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = true)] + [JsonSerializable(typeof(BoardPayload))] + [JsonSerializable(typeof(ErrorPayload))] + internal sealed partial class TimetablePeekJsonContext : JsonSerializerContext; -internal sealed record DeparturePayload(int Eva, string Station, IEnumerable Departures); + internal sealed record BoardPayload(int Eva, string Station, string Board, IEnumerable Entries); -internal sealed record DepartureDto(string Train, string Category, DateTime Planned, DateTime Actual, int DelayMinutes, string? Platform, string? Destination, IEnumerable Via); + internal sealed record BoardEntryDto(string Train, string Category, DateTime Planned, DateTime Actual, int DelayMinutes, string? Platform, string Station, IEnumerable Via); -internal sealed record ErrorPayload(ErrorDto Error); + internal sealed record ErrorPayload(ErrorDto Error); -internal sealed record ErrorDto(string Code, string Message); + internal sealed record ErrorDto(string Code, string Message); +} diff --git a/samples/DotBahn.Samples.TimetablePeek/dbpeek.spec b/samples/DotBahn.Samples.TimetablePeek/dbpeek.spec index ce03a6b..2d14934 100644 --- a/samples/DotBahn.Samples.TimetablePeek/dbpeek.spec +++ b/samples/DotBahn.Samples.TimetablePeek/dbpeek.spec @@ -1,7 +1,7 @@ Name: dbpeek Version: %{?pkg_version}%{!?pkg_version:0.0.0} Release: 0 -Summary: German railway departures monitor +Summary: German railway arrival/departure board License: MIT URL: https://github.com/rlvelte/dotbahn Source0: %{name}-%{version}.tar.gz @@ -9,8 +9,8 @@ ExclusiveArch: x86_64 %define debug_package %{nil} %description -One-shot departures board for Deutsche Bahn timetable services, -built with DotBahn (https://github.com/rlvelte/dotbahn). +One-shot arrival and departure board for Deutsche Bahn, built with +DotBahn (https://github.com/rlvelte/dotbahn) using the OpenBoards API. %prep %autosetup -n %{name}-%{version} @@ -19,6 +19,7 @@ built with DotBahn (https://github.com/rlvelte/dotbahn). %install install -Dm755 dbpeek %{buildroot}%{_bindir}/dbpeek +install -Dm644 bom.json %{buildroot}%{_datadir}/%{name}/bom.json %check : @@ -26,7 +27,13 @@ install -Dm755 dbpeek %{buildroot}%{_bindir}/dbpeek %files %license LICENSE %{_bindir}/dbpeek +%{_datadir}/%{name}/bom.json %changelog +* Sun Nov 22 2026 Robin L. Velte - 2.2.0-0 +- Migrate to the new OpenBoards API (DotBahn.Boards) +- Add arrivals mode (--arrivals/-a) +- Support departure/arrival filtering by category, limit and time window +- Cap --window to 8 hours per API limit * Wed Oct 28 2026 Robin L. Velte - 2.1.1-0 - Initial package diff --git a/samples/DotBahn.Samples.TimetablePeek/packages.lock.json b/samples/DotBahn.Samples.TimetablePeek/packages.lock.json index e7ca0cc..e9a58bc 100644 --- a/samples/DotBahn.Samples.TimetablePeek/packages.lock.json +++ b/samples/DotBahn.Samples.TimetablePeek/packages.lock.json @@ -2,23 +2,6 @@ "version": 2, "dependencies": { "net10.0": { - "Microsoft.NET.ILLink.Tasks": { - "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "YlTamXppEQls6DYWt7RdUuwWDb0lyw/vXCaGeQpLCpsLmfwGuCkOz/vIGgMTV7ECsJcavkCOkxZXv9s8rdAHkQ==" - }, - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[10.0.403, )", - "resolved": "10.0.403", - "contentHash": "T4WYxWydJGNQRe/EgURFlhPZ1cHYgivrCCHSomCcfQzGzhkDYGNn5bUwwjs4/PHuMxsmGaLvPv2puG8lluA1IA==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "10.0.403", - "Microsoft.SourceLink.Common": "10.0.403", - "System.IO.Hashing": "10.0.14" - } - }, "MinVer": { "type": "Direct", "requested": "[8.0.0, )", @@ -27,21 +10,21 @@ }, "OpenTelemetry.Exporter.OpenTelemetryProtocol": { "type": "Direct", - "requested": "[1.20.1, )", - "resolved": "1.20.1", - "contentHash": "IlO8F0Y01ki0N5hJaeFJ5j3MVYJdbyNpDF9g7goU8wA3o8r/+ir9WJNnmte7QlUzM3iSV/aIuev1fqwF1CZOqg==", + "requested": "[1.21.0, )", + "resolved": "1.21.0", + "contentHash": "Xo/3lqiZhv+an00t5N9Jxt3U2vIOcY6/bu0wo5LiQrrRIwd/8dv9FdlIVB3k3ypiyG1VkbCXhWH1tiC48HQS4w==", "dependencies": { - "OpenTelemetry": "1.20.1" + "OpenTelemetry": "1.21.0" } }, "OpenTelemetry.Extensions.Hosting": { "type": "Direct", - "requested": "[1.20.1, )", - "resolved": "1.20.1", - "contentHash": "wnoK07COxyQBR47QwP80SIO4cpD2xeF4PrBDYFXDMnhDLmOP4nN0Szy1wCBLo5UABU1I4xwWRGzZM0bFdCbRog==", + "requested": "[1.21.0, )", + "resolved": "1.21.0", + "contentHash": "+cOZFDBLktHT8V/aUb2SXQVFNP5JrcX/F24TgHcbD2kd4SFcKlBMChYeU/K+Tg3nuL+4HAS7dcR7Y2+tcSnFbQ==", "dependencies": { "Microsoft.Extensions.Hosting.Abstractions": "10.0.0", - "OpenTelemetry": "1.20.1" + "OpenTelemetry": "1.21.0" } }, "Spectre.Console": { @@ -55,61 +38,62 @@ }, "System.CommandLine": { "type": "Direct", - "requested": "[2.0.14, )", - "resolved": "2.0.14", - "contentHash": "15fyVO4aG6poR6IKmhM74zf7PUzaU6FZAGm2d3SQSO9yIyGAeo44e6t9qeKjjaqyMEqYdqcb2G1B0gpLoDU2cA==" + "requested": "[3.0.0, )", + "resolved": "3.0.0", + "contentHash": "swNpSTl0iYJeBuvYYfaY+VxzZ5YC8wklwkqDCNOq2aTQqJzjauJfh/O3Zw93nwxspWrxvZTjT45f8VPR0ParEA==" }, - "Microsoft.Build.Tasks.Git": { + "Microsoft.Extensions.AmbientMetadata.Application": { "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "1furteBFeemMmZ4s+ORjQb7YtO+wG63NJahbQbRUi91FV6V87BdV0U3vX1jbMC6iKSELYYoXWssSzLu3mx0i2w==", + "resolved": "11.0.1", + "contentHash": "tm28s2ODWZ6RdysP06NI3B23DUY5OfHG35ihMHxVAO3hywZAczDVjrkYMfBY//J4HQqfDHS5op84BhnF7ROseQ==", "dependencies": { - "System.IO.Hashing": "10.0.14" + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, - "Microsoft.Extensions.AmbientMetadata.Application": { + "Microsoft.Extensions.Compliance.Abstractions": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "aMCm7C6CexZT8W/p8zRp4BoxSnqRs3MmkBF7FvPIXC92b7vqs2SL0J+mVJi5W2Mk9Vb4ZRFWe9sdzFew6zUl1w==", + "resolved": "11.0.1", + "contentHash": "DUwdXgIxJKH9zBNg/SUBqOX0FpXCq7w80CIzrr0Jcw5tBXS926AtCcidoAsEHq5e/c6KQ8rWhSt7NxFxak8N/Q==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15" } }, - "Microsoft.Extensions.Compliance.Abstractions": { + "Microsoft.Extensions.Compliance.Redaction": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2mjAb3Sm5k6uNeI+IyXpggYMpfdDDGgZSwUm9QQsm5QgZboJWbm2eU+6wNMrlfFEao11yq6JS1zXI7SVQQ0NuQ==", + "resolved": "11.0.1", + "contentHash": "2rwe98yZEn4+aXjAg5DdcROMg6m2w3tejf/mRk4/fBCHKM2EWCaFTmbHLtz1BfyBxMY00/08XFoN0wzWYNiSiQ==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13" + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, "Microsoft.Extensions.Configuration": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Binder": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" } }, "Microsoft.Extensions.Configuration.EnvironmentVariables": { @@ -123,181 +107,182 @@ }, "Microsoft.Extensions.DependencyInjection": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" }, "Microsoft.Extensions.DependencyInjection.AutoActivation": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "h/sovspxVmT2DTIbWORMG0Gi3zVcPQzNl3kbwtpo0LoUXYbe2+66wQqZYwaF2ZWKN8HDdHv5yoc7d0DbDBBlnA==", + "resolved": "11.0.1", + "contentHash": "OuVIF5TmsfonN2Fqmi2zlUtbFQNqQiflhgo/rh64ptrqYrB4wZLwKbXr/HzrQXMf+h3jIbWrjIdJFspGqcvuuQ==", "dependencies": { - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13" + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15" } }, "Microsoft.Extensions.Diagnostics": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "80VqW8eKxQaxBOLDNpLUdxOlxzWn/jqBSxNBCfD8GCjcshNDpFvUgKh8uvvZwvkfBbwmNPWPWHyy9F+RLd1dlQ==", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" } }, "Microsoft.Extensions.Diagnostics.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vm+PPso6vOwGeX52MdOPh6z/R6KHgxQUwqq7k7Jc9jhy2JOxO2KB4xfoJQBBp2Ni8M4zKgJ4r2a1dgrYG7+MKw==", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "Dp/FaAPo3U9h3HsWT1dcdRRV//rm+MQF5iKpY/WxL5swwV+wZNE5eyJZ0kgy9Upl/kHz4ejpiLMloxDIuJaoJQ==", + "resolved": "11.0.1", + "contentHash": "mqqpmAFNRLa4cozN3RvT/T81k4aarwMc8xb8VVQgLqUE7AAoN/WWayZAvP+4hy9+KujP3dfn3taU06fZJPIbgA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13" + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" } }, "Microsoft.Extensions.FileProviders.Abstractions": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "BZDwtN3uoWRghDi5lRRZPDjMMCg2Ds7J6YEYjqka/TLjqnzquEpXyvchrIMeoubwT1ns23ow6PPeAoBHJO81Rw==", + "resolved": "10.0.15", + "contentHash": "1RSYAUtJeb76m2T0u5BbvwKY3s+ge9fT3cj1odvo5Bm+frc7pU9RSeXeMIlYHV8GjpqLdv2neeeomz010yYL8A==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.13" + "Microsoft.Extensions.Primitives": "10.0.15" } }, "Microsoft.Extensions.Hosting.Abstractions": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "zIrbe9vkIFXxW3mOApIOWXw+xMwX7Cgsptr3ZSlglJt4hW2qp4fB/JU1NHgAevteBNH4PicvU9DsFPHxlnnloA==", + "resolved": "10.0.15", + "contentHash": "s/JBiwR3F/vKRCbe6WO5b6t6or1ISaZ3rllchcw6/FSWZmK8s2fAzD7elrZo7592FnMD1fhGoG/wuJL1YYtVXw==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13" + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15" } }, "Microsoft.Extensions.Http.Diagnostics": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "iFcxcuMF/21LO+tDqDyzYVvokJUH03cNalmOJhmjyQSMV3dR4JAgcUBTV1iVH/yruC8wG2RNjvW0xcUgYqmrGg==", + "resolved": "11.0.1", + "contentHash": "mKHY0oFYL3fkAOhBNi2LqWPuEdUJ+HiF28KKUwBkQG2sgXAUdFDDqvJAfu2PcYgtAwsAtl58zuk4SElpPzbCvA==", "dependencies": { - "Microsoft.Extensions.Http": "10.0.13", - "Microsoft.Extensions.Telemetry": "10.11.0" + "Microsoft.Extensions.Compliance.Redaction": "11.0.1", + "Microsoft.Extensions.Http": "10.0.15", + "Microsoft.Extensions.Telemetry": "11.0.1" } }, "Microsoft.Extensions.Logging": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Logging.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Logging.Configuration": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "OyYJOaE9WbBx1Hp+Dd2zrqeFM0JwH5M/x0VL6tNUv3V18vIAVpix8UjhvY9eW/iXpguEHy68JO/Z9YkBOwftIw==", + "resolved": "10.0.15", + "contentHash": "Km6Ml1/nu0T/f80Btonxf9CWmP/BXI84aJwC5fUbCxRArJ0lH++0ADQrjErZvsSIrKhusTkTSGBChKy2fYAF4w==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.Configuration.Binder": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Configuration.Binder": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, "Microsoft.Extensions.ObjectPool": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "NX3bhcc0WitPKAVc9Zfi8jeEPClhfEmobUJM4a4bkWhJcBt5IWg6lCrItUoFy4whLjU+atXktURYCweQlR7wfg==" + "resolved": "10.0.15", + "contentHash": "kvd9eyRRQ+OEu9wik7GKgTS+7XnJ5XoOtSXJqmkJtVYV/S4gsBUrobYRSdNeBcb0ymef4L5Q9pZGiTxJ8jJfyQ==" }, "Microsoft.Extensions.Options.ConfigurationExtensions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4wcIU0rE04ejEfCwHTftu9O8fgH6CRYCe+tseRapikUBn1Kic3QdO7ku22SwFyLrzdWGYPUZMEgv57ZYuuc5gA==", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Primitives": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" }, "Microsoft.Extensions.Resilience": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "GbN7R2BOoZf3F7aK02nz9kWf6ttbvVzpw1orGG30VmrKTmRV6pasQOCfF2fjKXyHIMC/lAiBEYHCKjgf0OiGvQ==", + "resolved": "11.0.1", + "contentHash": "xgKof6iwAByZNrxWOa7Drk4A953L7U2HleTmx7EXE2Vf6j1crp4RsvNlIVsJMtHKf3ftGKd9gOhR3xES9vxUgg==", "dependencies": { - "Microsoft.Extensions.Diagnostics": "10.0.13", - "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "10.11.0", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0", + "Microsoft.Extensions.Diagnostics": "10.0.15", + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1", "Polly.Extensions": "8.4.2", "Polly.RateLimiting": "8.4.2" } }, "Microsoft.Extensions.Telemetry": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2meCfABvkLPtEBBwGzItIGnhrex1AEn2N+dHvxB5UoozeX/xTtBuUz5BRdjNI5oNgd5T31kC69WWw3BHDc9iZA==", + "resolved": "11.0.1", + "contentHash": "9uuA8entTC9m00m59h6CACSt4IQh9KknB+hPvCteXUTiG67lqJ8BI65fEUJSPSfT3ZDDi01Zg2aY5kRUvD4HPw==", "dependencies": { - "Microsoft.Extensions.AmbientMetadata.Application": "10.11.0", - "Microsoft.Extensions.DependencyInjection.AutoActivation": "10.11.0", - "Microsoft.Extensions.Logging.Configuration": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0" + "Microsoft.Extensions.AmbientMetadata.Application": "11.0.1", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "11.0.1", + "Microsoft.Extensions.Logging.Configuration": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1" } }, "Microsoft.Extensions.Telemetry.Abstractions": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "FzcHRan/C2g5X5KD0kPlL4tTROFRpM8sqcXfOIi6FGLsw/d2yoOYMbLJ5hyb8N5QgOVW7e1TdwEN4zVUfcwfdw==", + "resolved": "11.0.1", + "contentHash": "qINZz4G01Wxumqd0hLr6YdzPa3s7jexQWN28EenaiJQnmKdsR9FnBaKENdRRElLc+A5bJKQ+jYw/WHG4ZpIyAg==", "dependencies": { - "Microsoft.Extensions.Compliance.Abstractions": "10.11.0", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13" + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15" } }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "SvzUeqFGrcQxlIgjmcoSGiV5UWcPa0NCTuH69/40uSDsSD/26c6p9cH7XLAxpn+I8+2Zhl1qp+WMugl0oOwBMg==" - }, "OpenTelemetry.Api": { "type": "Transitive", - "resolved": "1.20.1", - "contentHash": "QO9hlwadOdJGR4vDpJyDnl9B62v7epIBSTIHUA4C+bCtrRaB4TWmYSnu3QVOIe7caH8dt7NaHRei6zebESJJyw==" + "resolved": "1.21.0", + "contentHash": "KptD6ThegQORUzwot75zW2AUH6IDyKXH1R2yhovJPYfrzqSgHQidMfVfKLjaYEnJa5ySQgQm0RjuM6X+TCJ9yw==", + "dependencies": { + "System.Diagnostics.DiagnosticSource": "11.0.0" + } }, "Polly.Core": { "type": "Transitive", @@ -328,94 +313,94 @@ "resolved": "0.57.2", "contentHash": "Y1+u73shwP+JYHmrkdN6bSt2kaGBEAafhi2nrecczbXdFRey+k7J/WF9YPfcB0rqivv2S8fmif6FSBq9m/AFvw==" }, - "System.IO.Hashing": { + "System.Diagnostics.DiagnosticSource": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "lVqovhCt3HlZe7ONG5ydaj6BYwYI004gldVfMMkJl/lR5ueeCtWNpW4nejOX75sPmzm8vXCxB69GqwHaYCnyUQ==" + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" }, "System.Threading.RateLimiting": { "type": "Transitive", "resolved": "8.0.0", "contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q==" }, - "dotbahn.common": { + "dotbahn.boards": { "type": "Project", "dependencies": { - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Options": "[10.0.14, )" + "DotBahn.Common": "[1.0.0, )", + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Http.Resilience": "[11.0.1, )", + "Microsoft.Extensions.Options": "[11.0.0, )" } }, - "dotbahn.telemetry": { + "dotbahn.common": { "type": "Project", "dependencies": { - "DotBahn.Common": "[1.0.0, )", - "OpenTelemetry.Api.ProviderBuilderExtensions": "[1.20.1, )" + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" } }, - "dotbahn.timetables": { + "dotbahn.telemetry": { "type": "Project", "dependencies": { "DotBahn.Common": "[1.0.0, )", - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Http.Resilience": "[10.11.0, )", - "Microsoft.Extensions.Options": "[10.0.14, )" + "OpenTelemetry.Api.ProviderBuilderExtensions": "[1.21.0, )" } }, "Microsoft.Extensions.Http": { "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "IDsXLGGz7nJMsqspWnErsP18WyAVf6V9Ixl4p47/8/95Jak3ZA1YWhQ0iesMVwubVhkVZGoO9m9ADUnK0m6HLw==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Http.Resilience": { "type": "CentralTransitive", - "requested": "[10.11.0, )", - "resolved": "10.11.0", - "contentHash": "6/YEoPCcQLzExm4x4FH5c38JffbhkMaTtXsrDmYNozt9KRtdXK3TsDeuKSBZJno+41oIDGBONb2up0zCsuEERw==", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "5VawCrg+VgVT2hNurSSEWUnq0pvNoH+Zt82s5Wpl/8jdnmU8DpRlr+M3DcdtVgeBG7mRyk3GtSRbf8PB/HrL3w==", "dependencies": { - "Microsoft.Extensions.Http.Diagnostics": "10.11.0", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Resilience": "10.11.0" + "Microsoft.Extensions.Http.Diagnostics": "11.0.1", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Resilience": "11.0.1" } }, "Microsoft.Extensions.Options": { "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "OpenTelemetry": { "type": "CentralTransitive", - "requested": "[1.20.1, )", - "resolved": "1.20.1", - "contentHash": "+XDw3fYbiv1a40aFnDJSQleeuUJciXuhoIA19XmcGhT47Hy/xZRqk8NCjHUDKrg72Ixjthicecp8ygBDNeH/Jw==", + "requested": "[1.21.0, )", + "resolved": "1.21.0", + "contentHash": "ynAzNO/ebDTPxARbz4z/HgL8azMk/iDk4GXFuIRQ6krr1+a5QMC4eoiXRl+e7COd+3RLyL/yTuE6bevwqbv4Bw==", "dependencies": { "Microsoft.Extensions.Configuration.EnvironmentVariables": "10.0.0", "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.0", "Microsoft.Extensions.Logging.Configuration": "10.0.0", - "OpenTelemetry.Api.ProviderBuilderExtensions": "1.20.1" + "OpenTelemetry.Api.ProviderBuilderExtensions": "1.21.0" } }, "OpenTelemetry.Api.ProviderBuilderExtensions": { "type": "CentralTransitive", - "requested": "[1.20.1, )", - "resolved": "1.20.1", - "contentHash": "eDzDY/jTBqRytkYECmVKF7ZP5sKmCIqv1SSnA5BSWltIIvc3931TOMRyCW1qCGNIgmtldtJhISnsmFNxOCfauQ==", + "requested": "[1.21.0, )", + "resolved": "1.21.0", + "contentHash": "ZcBCBTGbzjj8Y+9UnZKbSjnRyKc2ub2IvvU68fFHKmyKzTS4hU+4/f0PO1GoIf7FTYLKTyw+l/EwLL/PPIDkxg==", "dependencies": { "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0", - "OpenTelemetry.Api": "1.20.1" + "OpenTelemetry.Api": "1.21.0" } } } diff --git a/scripts/publish.ps1 b/scripts/publish.ps1 index 551e9f1..98556f5 100644 --- a/scripts/publish.ps1 +++ b/scripts/publish.ps1 @@ -1,4 +1,6 @@ +# Publishes all CSPROJ marked as executable in the 'SAMPLES_DIR' as binaries. $ErrorActionPreference = 'Stop' + $root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path Set-Location $root @@ -12,7 +14,7 @@ function Get-Rid { } elseif ([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform([System.Runtime.InteropServices.OSPlatform]::Linux)) { 'linux' } else { - throw "unsupported OS" + throw "unsupported os" } $arch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture @@ -21,6 +23,7 @@ function Get-Rid { 'Arm64' { 'arm64' } default { 'x64' } } + return "$os-$archName" } @@ -29,11 +32,16 @@ $rid = Get-Rid foreach ($projectDir in Get-ChildItem (Join-Path $root $samplesDir) -Directory) { $csprojs = Get-ChildItem -Path (Join-Path $projectDir.FullName '*.csproj') -File foreach ($csproj in $csprojs) { - if (-not (Select-String -Path $csproj.FullName -Pattern 'Exe' -Quiet)) { continue } + if (-not (Select-String -Path $csproj.FullName -Pattern 'Exe' -Quiet)) { + continue + } + $name = $csproj.BaseName $projectPath = $csproj.Directory.FullName + $source = Join-Path $projectPath "bin/$configuration/net10.0/$rid/publish" $out = Join-Path $root "$publishDir/$rid/$name" + New-Item -ItemType Directory -Force -Path $out | Out-Null dotnet publish $csproj.FullName ` @@ -42,10 +50,13 @@ foreach ($projectDir in Get-ChildItem (Join-Path $root $samplesDir) -Directory) --self-contained ` -p:PublishAot=true ` -p:StripSymbols=true ` + -p:NuGetLockFilePath=obj/aot.lock.json ` --verbosity minimal - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE + } Copy-Item -Path (Join-Path $source '*') -Destination $out -Force - Write-Host "published: $out" } } diff --git a/scripts/publish.sh b/scripts/publish.sh index ae59c58..dc42a7b 100755 --- a/scripts/publish.sh +++ b/scripts/publish.sh @@ -1,4 +1,4 @@ -#!/usr/bin/env bash +# Publishes all '*.csproj' marked as executable in the 'SAMPLES_DIR' as binaries. set -euo pipefail root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -12,8 +12,8 @@ detect_rid() { local os arch case "$(uname -s)" in Linux*) os=linux ;; - MINGW*|MSYS*|CYGWIN*) os=win ;; - *) echo "unsupported OS: $(uname -s)" >&2; exit 1 ;; + MINGW*|MSYS*|CYGWIN*) os=win ;; # really need this? + *) echo "unsupported os: $(uname -s)" >&2; exit 1 ;; esac case "$(uname -m)" in x86_64|amd64) arch=x64 ;; @@ -28,9 +28,11 @@ rid="$(detect_rid)" for csproj in "$root/$samples_dir"/*/*.csproj; do name="$(basename "$csproj" .csproj)" grep -q 'Exe' "$csproj" || continue + project_dir="$(dirname "$csproj")" source="$project_dir/bin/$configuration/net10.0/$rid/publish" out="$root/$publish_dir/$rid/$name" + mkdir -p "$out" dotnet publish "$csproj" \ @@ -39,8 +41,8 @@ for csproj in "$root/$samples_dir"/*/*.csproj; do --self-contained \ -p:PublishAot=true \ -p:StripSymbols=true \ + -p:NuGetLockFilePath=obj/aot.lock.json \ --verbosity minimal cp -a "$source/." "$out/" - echo "published: $out" done diff --git a/scripts/rpm.sh b/scripts/rpm.sh index 10de46a..dea6021 100755 --- a/scripts/rpm.sh +++ b/scripts/rpm.sh @@ -1,16 +1,13 @@ -#!/usr/bin/env bash -# Package all samples as RPMs from a prior publish (run `make publish` first or use `make rpm`, which chains it). -# Usage: ./scripts/rpm.sh [version] - +# Packages all '*.spec' in the 'SAMPLES_DIR' as rpm. set -euo pipefail root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" cd "$root" -configuration="${CONFIGURATION:-Release}" samples_dir="${SAMPLES_DIR:-./samples}" publish_dir="${PUBLISH_DIR:-./build/publish}" rpm_dir="${RPM_DIR:-./build/rpm}" + version="${1:-$(git describe --tags --abbrev=0 | sed 's/^v//')}" work="$(mktemp -d)" trap 'rm -rf "$work"' EXIT @@ -18,8 +15,8 @@ trap 'rm -rf "$work"' EXIT detect_rid() { local os arch case "$(uname -s)" in - Linux*) os=linux ;; - *) echo "unsupported OS: $(uname -s)" >&2; exit 1 ;; + Linux*) os=linux ;; # really need this? + *) echo "unsupported os: $(uname -s)" >&2; exit 1 ;; esac case "$(uname -m)" in x86_64|amd64) arch=x64 ;; @@ -43,7 +40,7 @@ mkdir -p "$work/SOURCES" for spec in "${specs[@]}"; do name="$(sed -n 's/^Name:[[:space:]]*//p' "$spec" | head -1)" if [ -z "$name" ]; then - echo "Skipping $spec: no 'Name:' field" >&2 + echo "Skipping $spec: no name field" >&2 continue fi @@ -51,22 +48,28 @@ for spec in "${specs[@]}"; do csproj="$(basename "$(ls "$sample_dir"/*.csproj)" .csproj)" binary="$publish_dir/$rid/$csproj/$name" if [ ! -x "$binary" ]; then - echo "Missing published binary: $binary" >&2 + echo "Skipping $spec: missing binaries" >&2 exit 1 fi - echo "Staging tarball for $name" mkdir "$work/$name-$version" cp "$binary" "$work/$name-$version/" cp LICENSE "$work/$name-$version/" + dotnet cyclonedx "$sample_dir/$csproj.csproj" \ + -o "$work/$name-$version" \ + -F Json \ + -fn bom.json \ + -dpr + if [ ! -f "$work/$name-$version/bom.json" ]; then + echo "Skipping $spec: sbom generation failed" >&2 + exit 1 + fi + tar -czf "$work/SOURCES/$name-$version.tar.gz" -C "$work" "$name-$version" - echo "Building RPM for $name" rpmbuild -bb \ --define "_sourcedir $work/SOURCES" \ --define "_rpmdir $rpm_dir" \ --define "pkg_version $version" \ "$spec" done - -find "$rpm_dir" -name '*.rpm' diff --git a/source/DotBahn.Ai/AiJsonContext.cs b/source/DotBahn.Ai/AiJsonContext.cs new file mode 100644 index 0000000..197a2f9 --- /dev/null +++ b/source/DotBahn.Ai/AiJsonContext.cs @@ -0,0 +1,26 @@ +using System.Text.Json.Serialization; +using DotBahn.Ai.Input; +using DotBahn.Boards.Models; +using DotBahn.Boards.Models.Entries; +using DotBahn.Facilities.Models; +using DotBahn.Facilities.Models.Enumerations; +using DotBahn.Stations.Models; + +namespace DotBahn.Ai; + +/// +/// Source-generated JSON metadata for AI tool contracts. +/// +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, GenerationMode = JsonSourceGenerationMode.Metadata)] +[JsonSerializable(typeof(StationSearchInput))] +[JsonSerializable(typeof(BoardToolInput))] +[JsonSerializable(typeof(FacilityStatusInput))] +[JsonSerializable(typeof(StationIdentifierKind))] +[JsonSerializable(typeof(FacilityType))] +[JsonSerializable(typeof(FacilityState))] +[JsonSerializable(typeof(ToolError))] +[JsonSerializable(typeof(ToolResult>))] +[JsonSerializable(typeof(ToolResult>))] +[JsonSerializable(typeof(ToolResult>))] +[JsonSerializable(typeof(ToolResult>))] +internal sealed partial class AiJsonContext : JsonSerializerContext; diff --git a/source/DotBahn.Ai/DotBahn.Ai.csproj b/source/DotBahn.Ai/DotBahn.Ai.csproj new file mode 100644 index 0000000..5874fe5 --- /dev/null +++ b/source/DotBahn.Ai/DotBahn.Ai.csproj @@ -0,0 +1,19 @@ + + + true + DotBahn.Ai + AI tool definitions for DotBahn client packages. + + + + + + + + + + + + + + diff --git a/source/DotBahn.Ai/Input/BoardToolInput.cs b/source/DotBahn.Ai/Input/BoardToolInput.cs new file mode 100644 index 0000000..e039410 --- /dev/null +++ b/source/DotBahn.Ai/Input/BoardToolInput.cs @@ -0,0 +1,51 @@ +using System.ComponentModel; + +namespace DotBahn.Ai.Input; + +/// +/// AI optimized input DTO for the arrivals and departures tools. +/// +public record BoardToolInput { + /// + /// Identifier returned by the station search tool. + /// + [Description("Identifier returned by search_stations, e.g. an EVA number.")] + public required string StationId { get; init; } + + /// + /// Identifier scheme used by . + /// + [Description("Identifier scheme: Eva, Stada, or Dhid.")] + public required StationIdentifierKind StationKind { get; init; } + + /// + /// Optional start of the time window in ISO 8601 format. + /// + [Description("Optional start of the time window in ISO 8601 format. Defaults to now.")] + public DateTime? Start { get; init; } + + /// + /// Maximum number of board entries to return. + /// + [Description("Maximum number of board entries to return (1-25).")] + public int MaxEntries { get; init; } = 10; + + /// + /// Validates that the DTO constraints are respected by the LLM. + /// + /// Thrown when a required value is missing or invalid. + /// Thrown when a value is outside the allowed range. + internal void Validate() { + if (string.IsNullOrWhiteSpace(StationId) || StationId.Length > 64) { + throw new ArgumentException("StationId must contain between 1 and 64 characters.", nameof(StationId)); + } + + if (!Enum.IsDefined(StationKind)) { + throw new ArgumentOutOfRangeException(nameof(StationKind), "StationKind must be Eva, Stada, or Dhid."); + } + + if (MaxEntries is < 1 or > 25) { + throw new ArgumentOutOfRangeException(nameof(MaxEntries), "MaxEntries must be between 1 and 25."); + } + } +} diff --git a/source/DotBahn.Ai/Input/FacilityStatusInput.cs b/source/DotBahn.Ai/Input/FacilityStatusInput.cs new file mode 100644 index 0000000..b744530 --- /dev/null +++ b/source/DotBahn.Ai/Input/FacilityStatusInput.cs @@ -0,0 +1,48 @@ +using System.ComponentModel; +using DotBahn.Facilities.Models.Enumerations; + +namespace DotBahn.Ai.Input; + +/// +/// AI optimized input DTO for the facility status tool. +/// +public sealed record FacilityStatusInput { + /// + /// The station number whose facilities should be queried. + /// + [Description("DB station number returned by search_stations.")] + public required int StationNumber { get; init; } + + /// + /// Only return facilities of this type. + /// + [Description("Only return facilities of this type.")] + public FacilityType? Type { get; init; } + + /// + /// Only return facilities in this state. + /// + [Description("Only return facilities in this state.")] + public FacilityState? State { get; init; } + + /// + /// Maximum number of facilities to return. + /// + [Description("Maximum number of facilities to return (1-25).")] + public int MaxResults { get; init; } = 25; + + /// + /// Validates that the DTO constraints are respected by the LLM. + /// + /// Thrown when a required value is missing or invalid. + /// Thrown when a value is outside the allowed range. + internal void Validate() { + if (StationNumber <= 0) { + throw new ArgumentOutOfRangeException(nameof(StationNumber), "StationNumber must be positive."); + } + + if (MaxResults is < 1 or > 25) { + throw new ArgumentOutOfRangeException(nameof(MaxResults), "MaxResults must be between 1 and 25."); + } + } +} diff --git a/source/DotBahn.Ai/Input/StationIdentifierKind.cs b/source/DotBahn.Ai/Input/StationIdentifierKind.cs new file mode 100644 index 0000000..0cad96b --- /dev/null +++ b/source/DotBahn.Ai/Input/StationIdentifierKind.cs @@ -0,0 +1,21 @@ +namespace DotBahn.Ai.Input; + +/// +/// Identifier scheme used by . +/// +public enum StationIdentifierKind { + /// + /// EVA station number. + /// + Eva, + + /// + /// STADA station identifier. + /// + Stada, + + /// + /// DHID stop-place identifier. + /// + Dhid +} diff --git a/source/DotBahn.Ai/Input/StationSearchInput.cs b/source/DotBahn.Ai/Input/StationSearchInput.cs new file mode 100644 index 0000000..bfefccd --- /dev/null +++ b/source/DotBahn.Ai/Input/StationSearchInput.cs @@ -0,0 +1,35 @@ +using System.ComponentModel; + +namespace DotBahn.Ai.Input; + +/// +/// AI optimized input DTO for the station search tool. +/// +public sealed record StationSearchInput { + /// + /// Station name or fragment to search for. + /// + [Description("Station name or fragment to search for. Supports * and ? wildcards.")] + public required string Query { get; init; } + + /// + /// Maximum number of stations to return. + /// + [Description("Maximum number of stations to return (1-20).")] + public int MaxResults { get; init; } = 20; + + /// + /// Validates that the DTO constraints are respected by the LLM. + /// + /// Thrown when a required value is missing or invalid. + /// Thrown when a value is outside the allowed range. + internal void Validate() { + if (string.IsNullOrWhiteSpace(Query) || Query.Length > 200) { + throw new ArgumentException("Query must contain between 1 and 200 characters.", nameof(Query)); + } + + if (MaxResults is < 1 or > 20) { + throw new ArgumentOutOfRangeException(nameof(MaxResults), "MaxResults must be between 1 and 20."); + } + } +} diff --git a/source/DotBahn.Ai/ServiceCollectionExtensions.cs b/source/DotBahn.Ai/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..a4bf8f8 --- /dev/null +++ b/source/DotBahn.Ai/ServiceCollectionExtensions.cs @@ -0,0 +1,78 @@ +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace DotBahn.Ai; + +/// +/// Extension methods for registering the DotBahn AI tools. +/// +public static class ServiceCollectionExtensions { + private static readonly JsonSerializerOptions FunctionJsonOptions = CreateFunctionJsonOptions(); + + /// + /// Adds function invocation middleware with safe defaults for DotBahn tools. + /// + /// The chat client builder to configure. + /// Optional logger factory for function invocation logging. + /// The chat client builder for chaining. + /// Thrown when is null. + public static ChatClientBuilder UseDotBahnAiTools(this ChatClientBuilder builder, ILoggerFactory? factory = null) { + ArgumentNullException.ThrowIfNull(builder); + return builder.UseFunctionInvocation(factory, configure: client => { + client.MaximumIterationsPerRequest = 5; + client.MaximumConsecutiveErrorsPerRequest = 2; + client.AllowConcurrentInvocation = false; + client.IncludeDetailedErrors = false; + client.TerminateOnUnknownCalls = true; + }); + } + + /// + /// Registers the DotBahn AI tools and their adapters. + /// + /// The service collection to add to. + /// The service collection for chaining. + /// Thrown when is null. + public static IServiceCollection AddDotBahnAiTools(this IServiceCollection services) { + ArgumentNullException.ThrowIfNull(services); + + services.AddSingleton(); + + services.AddSingleton(CreateSearchStationsFunction); + services.AddSingleton(CreateDeparturesFunction); + services.AddSingleton(CreateArrivalsFunction); + services.AddSingleton(CreateFacilityStatusFunction); + + services.AddSingleton>(sp => sp.GetServices().ToList()); + return services; + } + + private static AIFunction CreateSearchStationsFunction(IServiceProvider services) { + var tools = services.GetRequiredService(); + return AIFunctionFactory.Create(tools.SearchStationsAsync, "dotbahn_search_stations", "Search for railway stations by name.", FunctionJsonOptions); + } + + private static AIFunction CreateDeparturesFunction(IServiceProvider services) { + var tools = services.GetRequiredService(); + return AIFunctionFactory.Create(tools.GetDeparturesAsync, "dotbahn_get_departures", "Get scheduled departures for a station.", FunctionJsonOptions); + } + + private static AIFunction CreateArrivalsFunction(IServiceProvider services) { + var tools = services.GetRequiredService(); + return AIFunctionFactory.Create(tools.GetArrivalsAsync, "dotbahn_get_arrivals", "Get scheduled arrivals for a station.", FunctionJsonOptions); + } + + private static AIFunction CreateFacilityStatusFunction(IServiceProvider services) { + var tools = services.GetRequiredService(); + return AIFunctionFactory.Create(tools.GetFacilityStatusAsync, "dotbahn_get_facility_status", "Get operational status for station facilities.", FunctionJsonOptions); + } + + private static JsonSerializerOptions CreateFunctionJsonOptions() { + return new JsonSerializerOptions(AIJsonUtilities.DefaultOptions) { + TypeInfoResolver = AIJsonUtilities.DefaultOptions.TypeInfoResolver is { } resolver ? JsonTypeInfoResolver.Combine(AiJsonContext.Default, resolver) : AiJsonContext.Default + }; + } +} diff --git a/source/DotBahn.Ai/ToolResult.cs b/source/DotBahn.Ai/ToolResult.cs new file mode 100644 index 0000000..18b8cdf --- /dev/null +++ b/source/DotBahn.Ai/ToolResult.cs @@ -0,0 +1,37 @@ +namespace DotBahn.Ai; + +/// +/// Structured error information returned to the model when a tool call fails. +/// +/// Stable machine-readable error code. +/// Sanitized, actionable error message. +/// Optional name of the invalid input field. +/// Whether retrying with corrected input may succeed. +public sealed record ToolError(string Code, string Message, string? Field = null, bool Retryable = false); + +/// +/// Result envelope returned by AI tools, containing either data or a structured error. +/// +/// The type of the successful result. +/// Whether the tool completed successfully. +/// The successful result, or null on failure. +/// The structured error, or null on success. +public sealed record ToolResult(bool Success, T? Data, ToolError? Error) { + /// + /// Creates a successful result. + /// + /// The successful result. + /// A successful . + public static ToolResult Ok(T data) => new(true, data, null); + + /// + /// Creates a failed result. + /// + /// The structured error. + /// A failed . + /// Thrown when is null. + public static ToolResult Fail(ToolError error) { + ArgumentNullException.ThrowIfNull(error); + return new ToolResult(false, default, error); + } +} diff --git a/source/DotBahn.Ai/Tools.cs b/source/DotBahn.Ai/Tools.cs new file mode 100644 index 0000000..930e466 --- /dev/null +++ b/source/DotBahn.Ai/Tools.cs @@ -0,0 +1,138 @@ +using System.Diagnostics; +using DotBahn.Ai.Input; +using DotBahn.Ai.Utilities; +using DotBahn.Boards; +using DotBahn.Boards.Models; +using DotBahn.Boards.Models.Entries; +using DotBahn.Common.Telemetry; +using DotBahn.Facilities; +using DotBahn.Facilities.Models; +using DotBahn.Facilities.Models.Enumerations; +using DotBahn.Stations; +using DotBahn.Stations.Models; + +namespace DotBahn.Ai; + +/// +/// AI tools backed by the DotBahn clients. +/// +/// The client used for station lookups. +/// The client used for arrival and departure boards. +/// The client used for facility status lookups. +public sealed class Tools(IStationClient stations, IBoardsClient boards, IFacilityClient facilities) { + /// + /// Searches for railway stations by name. + /// + /// Station name or fragment to search for. + /// Maximum number of stations to return (1-20). + /// Token to cancel the request. + /// A result containing the matching stations, or an invalid_argument error. + /// Thrown when the operation is canceled. + public Task>> SearchStationsAsync(string query, int maxResults = 20, CancellationToken ct = default) => + ExecuteToolAsync("dotbahn_search_stations", async token => { + var input = new StationSearchInput { Query = query, MaxResults = maxResults }; + input.Validate(); + + return await stations.GetStationsAsync(new StationQuery().WithNames(input.Query).LimitTo(input.MaxResults), token).ConfigureAwait(false); + }, ct); + + /// + /// Gets the operational status of facilities at a station. + /// + /// DB station number returned by search_stations. + /// Optional facility type filter. + /// Optional facility state filter. + /// Maximum number of facilities to return (1-25). + /// Token to cancel the request. + /// A result containing the matching facilities, or an invalid_argument error. + /// Thrown when the operation is canceled. + public Task>> GetFacilityStatusAsync(int stationNumber, FacilityType? type = null, FacilityState? state = null, int maxResults = 25, CancellationToken ct = default) => + ExecuteToolAsync>("dotbahn_get_facility_status", async token => { + var input = new FacilityStatusInput { StationNumber = stationNumber, Type = type, State = state, MaxResults = maxResults }; + input.Validate(); + + var query = new FacilityQuery().AtStation(input.StationNumber); + if (input.Type.HasValue) { + query.WithType(input.Type.Value); + } + + if (input.State.HasValue) { + query.WithState(input.State.Value); + } + + var result = await facilities.GetFacilitiesAsync(query, token).ConfigureAwait(false); + return result.Take(input.MaxResults).ToList(); + }, ct); + + /// + /// Gets the departure board for a station. + /// + /// Identifier returned by search_stations. + /// Identifier scheme used by stationId. + /// Optional start of the time window in ISO 8601 format. + /// Maximum number of board entries to return (1-25). + /// Token to cancel the request. + /// A result containing the departure board, or an invalid_argument error. + /// Thrown when the operation is canceled. + public Task>> GetDeparturesAsync(string stationId, StationIdentifierKind stationKind, DateTime? start = null, int maxEntries = 10, CancellationToken ct = default) => + ExecuteToolAsync("dotbahn_get_departures", async token => { + var input = new BoardToolInput { StationId = stationId, StationKind = stationKind, Start = start, MaxEntries = maxEntries }; + input.Validate(); + + return await boards.GetDeparturesAsync(CreateBoardQuery(input), token).ConfigureAwait(false); + }, ct); + + /// + /// Gets the arrival board for a station. + /// + /// Identifier returned by search_stations. + /// Identifier scheme used by stationId. + /// Optional start of the time window in ISO 8601 format. + /// Maximum number of board entries to return (1-25). + /// Token to cancel the request. + /// A result containing the arrival board, or an invalid_argument error. + /// Thrown when the operation is canceled. + public Task>> GetArrivalsAsync(string stationId, StationIdentifierKind stationKind, DateTime? start = null, int maxEntries = 10, CancellationToken ct = default) => + ExecuteToolAsync("dotbahn_get_arrivals", async token => { + var input = new BoardToolInput { StationId = stationId, StationKind = stationKind, Start = start, MaxEntries = maxEntries }; + input.Validate(); + + return await boards.GetArrivalsAsync(CreateBoardQuery(input), token).ConfigureAwait(false); + }, ct); + + private static async Task> ExecuteToolAsync(string name, Func> operation, CancellationToken ct) { + using var activity = DotBahnTelemetry.StartAiTool(name); + var start = Stopwatch.GetTimestamp(); + + try { + var value = await operation(ct).ConfigureAwait(false); + DotBahnTelemetry.RecordAiTool(Stopwatch.GetElapsedTime(start).TotalSeconds, name); + return ToolResult.Ok(value); + } catch (OperationCanceledException) { + DotBahnTelemetry.RecordAiTool(Stopwatch.GetElapsedTime(start).TotalSeconds, name); + throw; + } catch (Exception ex) { + var error = ToolErrorUtil.FromException(ex); + + activity?.SetStatus(ActivityStatusCode.Error, error.Message); + activity?.SetTag(DotBahnTelemetry.ErrorCodeTag, error.Code); + + DotBahnTelemetry.RecordAiTool(Stopwatch.GetElapsedTime(start).TotalSeconds, name, errorCode: error.Code); + return ToolResult.Fail(error); + } + } + + private static BoardQuery CreateBoardQuery(BoardToolInput input) { + var query = new BoardQuery().ForNext(input.MaxEntries); + if (input.Start.HasValue) { + query = query.StartingAt(input.Start.Value); + } + + return input.StationKind switch { + StationIdentifierKind.Eva => query.ForEvaNumbers(input.StationId), + StationIdentifierKind.Stada => query.ForStada(input.StationId), + StationIdentifierKind.Dhid => query.ForDhids(input.StationId), + _ => throw new ArgumentOutOfRangeException(nameof(input)) + }; + } +} diff --git a/source/DotBahn.Ai/Utilities/ToolErrorUtil.cs b/source/DotBahn.Ai/Utilities/ToolErrorUtil.cs new file mode 100644 index 0000000..279dfaa --- /dev/null +++ b/source/DotBahn.Ai/Utilities/ToolErrorUtil.cs @@ -0,0 +1,33 @@ +using System.Net; + +namespace DotBahn.Ai.Utilities; + +/// +/// Maps exceptions to sanitized, model-facing instances. +/// +public static class ToolErrorUtil { + /// + /// Maps an exception to a structured tool error. + /// + /// The exception to map. + /// The structured tool error. + /// Thrown when is null. + public static ToolError FromException(Exception exception) { + ArgumentNullException.ThrowIfNull(exception); + return exception switch { + ArgumentException argument => FromArgument(argument), + HttpRequestException http => FromHttp(http), + _ => new ToolError("internal_error", "The tool could not complete the request.") + }; + } + + private static ToolError FromHttp(HttpRequestException http) => http.StatusCode switch { + HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden => new ToolError("unauthorized", "DotBahn API credentials are missing or invalid."), + HttpStatusCode.NotFound => new ToolError("not_found", "The requested station or board was not found."), + HttpStatusCode.TooManyRequests => new ToolError("rate_limited", "The DotBahn API rate limit was reached. Retry later.", null, true), + { } value when (int)value >= 500 => new ToolError("upstream_error", "The DotBahn API is temporarily unavailable.", null, true), + _ => new ToolError("upstream_error", "The DotBahn API request failed.", null, true) + }; + + private static ToolError FromArgument(ArgumentException argument) => new("invalid_argument", argument.Message, string.IsNullOrWhiteSpace(argument.ParamName) ? null : argument.ParamName, true); +} diff --git a/source/DotBahn.Ai/packages.lock.json b/source/DotBahn.Ai/packages.lock.json new file mode 100644 index 0000000..55b055a --- /dev/null +++ b/source/DotBahn.Ai/packages.lock.json @@ -0,0 +1,379 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.Extensions.AI": { + "type": "Direct", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "MP6zzZzPseaXu0DtZFCkPCWPXLTu7JY28ciyxqSoeDOP5Raf+wJT8+HapyLfXaI7F1CXpyr5PgiCQEE0CeVCqw==", + "dependencies": { + "Microsoft.Extensions.AI.Abstractions": "11.0.1", + "Microsoft.Extensions.Caching.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "System.Numerics.Tensors": "11.0.0" + } + }, + "Microsoft.Extensions.AI.Abstractions": { + "type": "Direct", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "pG3n1nHRnVcYuMAiqhDPuKefXTtUGAhAtqhBUKpNsZXYef9Vm51iZhUAVfQ2EzYhechFaA5hCcgQgK18jTzuiw==" + }, + "Microsoft.NET.ILLink.Tasks": { + "type": "Direct", + "requested": "[10.0.15, )", + "resolved": "10.0.15", + "contentHash": "u0WnRcZgBZYHlVFpbe/3Adpmb9rmNJ8/fmEwqc/xjB7fFppq+gfaLJd3Sdaw+J02zV0eP/T9dneQ3Dv5jWw6bw==" + }, + "MinVer": { + "type": "Direct", + "requested": "[8.0.0, )", + "resolved": "8.0.0", + "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" + }, + "Microsoft.Extensions.AmbientMetadata.Application": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "tm28s2ODWZ6RdysP06NI3B23DUY5OfHG35ihMHxVAO3hywZAczDVjrkYMfBY//J4HQqfDHS5op84BhnF7ROseQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Caching.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "L+eahU5QGaFaCau3Y9qqY7WThUsR18sHASVDD1KuaSx2dy73NOY9U5Qz5eOe6bJOF3wHzkEaCl2LZhgwtlClyw==", + "dependencies": { + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Compliance.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "DUwdXgIxJKH9zBNg/SUBqOX0FpXCq7w80CIzrr0Jcw5tBXS926AtCcidoAsEHq5e/c6KQ8rWhSt7NxFxak8N/Q==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15" + } + }, + "Microsoft.Extensions.Compliance.Redaction": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "2rwe98yZEn4+aXjAg5DdcROMg6m2w3tejf/mRk4/fBCHKM2EWCaFTmbHLtz1BfyBxMY00/08XFoN0wzWYNiSiQ==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Configuration": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", + "dependencies": { + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" + }, + "Microsoft.Extensions.DependencyInjection.AutoActivation": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "OuVIF5TmsfonN2Fqmi2zlUtbFQNqQiflhgo/rh64ptrqYrB4wZLwKbXr/HzrQXMf+h3jIbWrjIdJFspGqcvuuQ==", + "dependencies": { + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mqqpmAFNRLa4cozN3RvT/T81k4aarwMc8xb8VVQgLqUE7AAoN/WWayZAvP+4hy9+KujP3dfn3taU06fZJPIbgA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.FileProviders.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "1RSYAUtJeb76m2T0u5BbvwKY3s+ge9fT3cj1odvo5Bm+frc7pU9RSeXeMIlYHV8GjpqLdv2neeeomz010yYL8A==", + "dependencies": { + "Microsoft.Extensions.Primitives": "10.0.15" + } + }, + "Microsoft.Extensions.Hosting.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "s/JBiwR3F/vKRCbe6WO5b6t6or1ISaZ3rllchcw6/FSWZmK8s2fAzD7elrZo7592FnMD1fhGoG/wuJL1YYtVXw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.Http.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mKHY0oFYL3fkAOhBNi2LqWPuEdUJ+HiF28KKUwBkQG2sgXAUdFDDqvJAfu2PcYgtAwsAtl58zuk4SElpPzbCvA==", + "dependencies": { + "Microsoft.Extensions.Compliance.Redaction": "11.0.1", + "Microsoft.Extensions.Http": "10.0.15", + "Microsoft.Extensions.Telemetry": "11.0.1" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Configuration": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "Km6Ml1/nu0T/f80Btonxf9CWmP/BXI84aJwC5fUbCxRArJ0lH++0ADQrjErZvsSIrKhusTkTSGBChKy2fYAF4w==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Configuration.Binder": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.ObjectPool": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "kvd9eyRRQ+OEu9wik7GKgTS+7XnJ5XoOtSXJqmkJtVYV/S4gsBUrobYRSdNeBcb0ymef4L5Q9pZGiTxJ8jJfyQ==" + }, + "Microsoft.Extensions.Options.ConfigurationExtensions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" + }, + "Microsoft.Extensions.Resilience": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "xgKof6iwAByZNrxWOa7Drk4A953L7U2HleTmx7EXE2Vf6j1crp4RsvNlIVsJMtHKf3ftGKd9gOhR3xES9vxUgg==", + "dependencies": { + "Microsoft.Extensions.Diagnostics": "10.0.15", + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1", + "Polly.Extensions": "8.4.2", + "Polly.RateLimiting": "8.4.2" + } + }, + "Microsoft.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "9uuA8entTC9m00m59h6CACSt4IQh9KknB+hPvCteXUTiG67lqJ8BI65fEUJSPSfT3ZDDi01Zg2aY5kRUvD4HPw==", + "dependencies": { + "Microsoft.Extensions.AmbientMetadata.Application": "11.0.1", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "11.0.1", + "Microsoft.Extensions.Logging.Configuration": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1" + } + }, + "Microsoft.Extensions.Telemetry.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "qINZz4G01Wxumqd0hLr6YdzPa3s7jexQWN28EenaiJQnmKdsR9FnBaKENdRRElLc+A5bJKQ+jYw/WHG4ZpIyAg==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15" + } + }, + "Polly.Core": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g==" + }, + "Polly.Extensions": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==", + "dependencies": { + "Microsoft.Extensions.Logging.Abstractions": "8.0.0", + "Microsoft.Extensions.Options": "8.0.0", + "Polly.Core": "8.4.2" + } + }, + "Polly.RateLimiting": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==", + "dependencies": { + "Polly.Core": "8.4.2", + "System.Threading.RateLimiting": "8.0.0" + } + }, + "System.Diagnostics.DiagnosticSource": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" + }, + "System.Numerics.Tensors": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "thx6y1hMzB6LumB/aLcZoLHWq8wr+dbldk/FiNghyT+4ynxo9u2oCTFfb5iDMDG6hykDXLorXuaf4EPEij2BBg==" + }, + "System.Threading.RateLimiting": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q==" + }, + "dotbahn.boards": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )", + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Http.Resilience": "[11.0.1, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.common": { + "type": "Project", + "dependencies": { + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.facilities": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )", + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Http.Resilience": "[11.0.1, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.stations": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )", + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Http.Resilience": "[11.0.1, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "Microsoft.Extensions.Http": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Http.Resilience": { + "type": "CentralTransitive", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "5VawCrg+VgVT2hNurSSEWUnq0pvNoH+Zt82s5Wpl/8jdnmU8DpRlr+M3DcdtVgeBG7mRyk3GtSRbf8PB/HrL3w==", + "dependencies": { + "Microsoft.Extensions.Http.Diagnostics": "11.0.1", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Resilience": "11.0.1" + } + }, + "Microsoft.Extensions.Options": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + } + } + } +} \ No newline at end of file diff --git a/source/DotBahn.Boards/BoardQuery.cs b/source/DotBahn.Boards/BoardQuery.cs new file mode 100644 index 0000000..258ef0e --- /dev/null +++ b/source/DotBahn.Boards/BoardQuery.cs @@ -0,0 +1,214 @@ +namespace DotBahn.Boards; + +/// +/// Query for an arrival or departure board. +/// +public sealed record BoardQuery { + /// + /// EVA numbers of stop places. Mutually exclusive with and . + /// + public IReadOnlyList? EvaNumbers { get; init; } + + /// + /// Stada ID of a station. Mutually exclusive with and . + /// + public string? StadaId { get; init; } + + /// + /// DHIDs of stop places. Mutually exclusive with and . + /// + public IReadOnlyList? Dhids { get; init; } + + /// + /// Optional platform names to filter the board. + /// + public IReadOnlyList? Platforms { get; init; } + + /// + /// Board configuration modes to extend the board to nearby stop places. + /// + public IReadOnlyList? BoardConfigurations { get; init; } + + /// + /// Start of the time window. If omitted, the API uses the current time. + /// + public DateTime? Start { get; init; } + + /// + /// End of the time window. Mutually exclusive with . + /// + public DateTime? End { get; init; } + + /// + /// Fixed number of entries to return from . + /// + /// Mutually exclusive with . + /// + /// + public int? EntryCount { get; init; } + + /// + /// Transport types to include. If empty, the API defaults to rail transports. + /// + public IReadOnlyList TransportTypes { get; init; } = []; + + /// + /// Languages to request, as ISO-639-3 codes. + /// + public IReadOnlyList Languages { get; init; } = ["deu", "eng"]; + + /// + /// Maximum number of entries returned per transport type. + /// + public int MaxEntriesPerTransportType { get; init; } = 25; + + /// + /// Maximum number of via stops returned per journey. + /// + public int? MaxViaStops { get; init; } + + /// + /// Whether to include line colors in the response. + /// + public bool IncludeLineColours { get; init; } + + /// + /// Whether to include platform accessibility information in the response. + /// + public bool IncludePlatformAccessibility { get; init; } + + /// + /// Whether to exclude canceled entries. + /// + public bool NoCancellations { get; init; } + + /// + /// Whether to return only replacement transports. + /// + public bool OnlyReplacementTransports { get; init; } + + /// + /// Sorting order, either TIME or TIME_SCHEDULE. + /// + public string SortBy { get; init; } = "TIME"; + + /// + /// Restricts the board to one or more EVA numbers. + /// + /// EVA numbers of stop places. + /// A new query with the selector applied. + public BoardQuery ForEvaNumbers(params string[] evaNumbers) => this with { EvaNumbers = evaNumbers }; + + /// + /// Restricts the board to a Stada station id. + /// + /// Stada identifier. + /// A new query with the selector applied. + public BoardQuery ForStada(string stadaId) => this with { StadaId = stadaId }; + + /// + /// Restricts the board to one or more DHIDs. + /// + /// DHIDs of stop places. + /// A new query with the selector applied. + public BoardQuery ForDhids(params string[] dhids) => this with { Dhids = dhids }; + + /// + /// Filters the board to one or more platforms. + /// + /// Platform names. + /// A new query with the selector applied. + public BoardQuery OnPlatforms(params string[] platforms) => this with { Platforms = platforms }; + + /// + /// Sets the board configuration modes for extending the board to nearby stop places. + /// + /// Configuration modes. + /// A new query with the selector applied. + public BoardQuery WithBoardConfigurations(params string[] configurations) => this with { BoardConfigurations = configurations }; + + /// + /// Sets the start of the time window. + /// + /// Start date and time. + /// A new query with the time window applied. + public BoardQuery StartingAt(DateTime start) => this with { Start = start }; + + /// + /// Sets the end of the time window. + /// + /// End date and time. + /// A new query with the time window applied. + public BoardQuery EndingAt(DateTime end) => this with { End = end }; + + /// + /// Requests a fixed number of entries starting at . + /// + /// Number of entries. + /// A new query with the time window applied. + public BoardQuery ForNext(int entryCount) => this with { EntryCount = entryCount }; + + /// + /// Sets the transport types to include. + /// + /// Transport types. + /// A new query with the transport types applied. + public BoardQuery WithTransportTypes(params string[] transportTypes) => this with { TransportTypes = transportTypes }; + + /// + /// Sets the requested languages. + /// + /// ISO-639-3 language codes. + /// A new query with the languages applied. + public BoardQuery InLanguages(params string[] languages) => this with { Languages = languages }; + + /// + /// Sets the maximum number of entries per transport type. + /// + /// Maximum entries. + /// A new query with the limit applied. + public BoardQuery WithMaxEntriesPerTransportType(int max) => this with { MaxEntriesPerTransportType = max }; + + /// + /// Sets the maximum number of via stops per journey. + /// + /// Maximum via stops. + /// A new query with the limit applied. + public BoardQuery WithMaxViaStops(int max) => this with { MaxViaStops = max }; + + /// + /// Requests line colors in the response. + /// + /// A new query with the flag applied. + public BoardQuery WithLineColours() => this with { IncludeLineColours = true }; + + /// + /// Requests platform accessibility information in the response. + /// + /// A new query with the flag applied. + public BoardQuery WithPlatformAccessibility() => this with { IncludePlatformAccessibility = true }; + + /// + /// Excludes canceled entries from the response. + /// + /// A new query with the flag applied. + public BoardQuery WithoutCancellations() => this with { NoCancellations = true }; + + /// + /// Requests only replacement transports. + /// + /// A new query with the flag applied. + public BoardQuery WithOnlyReplacementTransports() => this with { OnlyReplacementTransports = true }; + + /// + /// Sorts results by best-known time. + /// + /// A new query with the sort order applied. + public BoardQuery SortByTime() => this with { SortBy = "TIME" }; + + /// + /// Sorts results by scheduled time. + /// + /// A new query with the sort order applied. + public BoardQuery SortByTimeSchedule() => this with { SortBy = "TIME_SCHEDULE" }; +} diff --git a/source/DotBahn.Boards/BoardsClient.cs b/source/DotBahn.Boards/BoardsClient.cs new file mode 100644 index 0000000..f5e77e4 --- /dev/null +++ b/source/DotBahn.Boards/BoardsClient.cs @@ -0,0 +1,80 @@ +using DotBahn.Boards.Internal.Contracts; +using DotBahn.Boards.Internal.Json; +using DotBahn.Boards.Internal.Transformers; +using DotBahn.Boards.Internal.Utilities; +using DotBahn.Boards.Models; +using DotBahn.Boards.Models.Entries; +using DotBahn.Common.Auth; +using DotBahn.Common.Clients; +using DotBahn.Common.Parsing; +using DotBahn.Common.Transformer; +using Microsoft.Extensions.DependencyInjection; + +namespace DotBahn.Boards; + +/// +/// Client for accessing the Deutsche Bahn OpenBoards API. +/// +public class BoardsClient : ClientBase, IBoardsClient { + private readonly IParser _arrivalParser; + private readonly IParser _departureParser; + private readonly ITransformer, ArrivalBoardResponseContract> _arrivalTransformer; + private readonly ITransformer, DepartureBoardResponseContract> _departureTransformer; + + /// + protected override string ApiName => "boards"; + + /// + /// Client for accessing the Deutsche Bahn OpenBoards API. + /// + /// The HTTP client used for requests. + /// The provider used for retrieving access tokens. + /// The parser for arrival-board responses. + /// The parser for departure-board responses. + /// The transformer for arrival-board responses. + /// The transformer for departure-board responses. + [ActivatorUtilitiesConstructor] + internal BoardsClient(HttpClient http, IAuthorization authorization, IParser arrivalParser, IParser departureParser, ITransformer, ArrivalBoardResponseContract> arrivalTransformer, ITransformer, DepartureBoardResponseContract> departureTransformer) : base(http, authorization) { + _arrivalParser = arrivalParser; + _departureParser = departureParser; + _arrivalTransformer = arrivalTransformer; + _departureTransformer = departureTransformer; + } + + /// + /// Client for accessing the Deutsche Bahn OpenBoards API. + /// + /// + /// Creates and owns its own . Dispose this instance to release it. + /// Use only when instantiating manually without a DI container. + /// + /// The options for this instance. + /// The auth credentials for the client. + /// Thrown when or is null. + public BoardsClient(ClientOptions options, AuthorizationOptions auth) : base(options, auth) { + _arrivalParser = new JsonParser(BoardsJsonContext.Default.ArrivalBoardResponseContract); + _departureParser = new JsonParser(BoardsJsonContext.Default.DepartureBoardResponseContract); + _arrivalTransformer = new ArrivalBoardTransformer(); + _departureTransformer = new DepartureBoardTransformer(); + } + + /// + public async Task> GetArrivalsAsync(BoardQuery query, CancellationToken ct = default) { + ArgumentNullException.ThrowIfNull(query); + + var request = QueryUtil.ToArrivalContract(query); + var response = await PostAsync("/arrivals", request, BoardsJsonContext.Default.OpenArrivalBoardRequestContract, _arrivalParser, "application/json", ct).ConfigureAwait(false); + + return _arrivalTransformer.Transform(response); + } + + /// + public async Task> GetDeparturesAsync(BoardQuery query, CancellationToken ct = default) { + ArgumentNullException.ThrowIfNull(query); + + var request = QueryUtil.ToDepartureContract(query); + var response = await PostAsync("/departures", request, BoardsJsonContext.Default.OpenDepartureBoardRequestContract, _departureParser, "application/json", ct).ConfigureAwait(false); + + return _departureTransformer.Transform(response); + } +} diff --git a/source/DotBahn.Boards/DotBahn.Boards.csproj b/source/DotBahn.Boards/DotBahn.Boards.csproj new file mode 100644 index 0000000..3ef9abd --- /dev/null +++ b/source/DotBahn.Boards/DotBahn.Boards.csproj @@ -0,0 +1,22 @@ + + + + true + DotBahn.Boards + .NET client for DB OpenBoards API. + + + + + + + + + + + + + + + + diff --git a/source/DotBahn.Boards/IBoardsClient.cs b/source/DotBahn.Boards/IBoardsClient.cs new file mode 100644 index 0000000..1277b88 --- /dev/null +++ b/source/DotBahn.Boards/IBoardsClient.cs @@ -0,0 +1,31 @@ +using DotBahn.Boards.Models; +using DotBahn.Boards.Models.Entries; + +namespace DotBahn.Boards; + +/// +/// Client for accessing the Deutsche Bahn OpenBoards API. +/// +public interface IBoardsClient { + /// + /// Gets an arrival board for the specified query. + /// + /// The board query. + /// Cancellation token. + /// The arrival board. + /// Thrown when is null. + /// Thrown when the API responds with a non-success status code. + /// Thrown when the operation is canceled. + Task> GetArrivalsAsync(BoardQuery query, CancellationToken ct = default); + + /// + /// Gets a departure board for the specified query. + /// + /// The board query. + /// Cancellation token. + /// The departure board. + /// Thrown when is null. + /// Thrown when the API responds with a non-success status code. + /// Thrown when the operation is canceled. + Task> GetDeparturesAsync(BoardQuery query, CancellationToken ct = default); +} diff --git a/source/DotBahn.Boards/Internal/Contracts/AdministrationExtendedMultiLanguageContract.cs b/source/DotBahn.Boards/Internal/Contracts/AdministrationExtendedMultiLanguageContract.cs new file mode 100644 index 0000000..c037a21 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/AdministrationExtendedMultiLanguageContract.cs @@ -0,0 +1,34 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for an extended administration multi-language. +/// +[ExcludeFromCodeCoverage] +internal record AdministrationExtendedMultiLanguageContract { + /// + /// Gets the administration identifier. + /// + [JsonPropertyName("administrationId")] + public string AdministrationId { get; init; } = string.Empty; + + /// + /// Gets the operator code. + /// + [JsonPropertyName("operatorCode")] + public string OperatorCode { get; init; } = string.Empty; + + /// + /// Gets the operator name. + /// + [JsonPropertyName("operatorName")] + public string OperatorName { get; init; } = string.Empty; + + /// + /// Gets the transport companies. + /// + [JsonPropertyName("transportCompanies")] + public List? TransportCompanies { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/ArrivalBoardResponseContract.cs b/source/DotBahn.Boards/Internal/Contracts/ArrivalBoardResponseContract.cs new file mode 100644 index 0000000..c9ae02d --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/ArrivalBoardResponseContract.cs @@ -0,0 +1,52 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for an arrival-board response. +/// +[ExcludeFromCodeCoverage] +internal record ArrivalBoardResponseContract { + /// + /// Gets the administrations. + /// + [JsonPropertyName("administrations")] + public List? Administrations { get; init; } + + /// + /// Gets the arrivals. + /// + [JsonPropertyName("arrivals")] + public List? Arrivals { get; init; } + + /// + /// Gets the disruption communications. + /// + [JsonPropertyName("disruptionCommunications")] + public List? DisruptionCommunications { get; init; } + + /// + /// Gets the messages. + /// + [JsonPropertyName("messages")] + public MessagesMultiLanguageContract? Messages { get; init; } + + /// + /// Gets the meta. + /// + [JsonPropertyName("meta")] + public BoardMetaContract Meta { get; init; } = new(); + + /// + /// Gets the stations. + /// + [JsonPropertyName("stations")] + public List? Stations { get; init; } + + /// + /// Gets the stop places. + /// + [JsonPropertyName("stopPlaces")] + public List? StopPlaces { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/ArrivalContract.cs b/source/DotBahn.Boards/Internal/Contracts/ArrivalContract.cs new file mode 100644 index 0000000..3b0f102 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/ArrivalContract.cs @@ -0,0 +1,167 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using DotBahn.Common.Parsing.Converters; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for an arrival. +/// +[ExcludeFromCodeCoverage] +internal record ArrivalContract { + /// + /// Gets a value indicating whether this is additional. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("additional")] + public bool Additional { get; init; } + + /// + /// Gets the arrival identifier. + /// + [JsonPropertyName("arrivalId")] + public string ArrivalId { get; init; } = string.Empty; + + /// + /// Gets a value indicating whether this is cancelled. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("cancelled")] + public bool Cancelled { get; init; } + + /// + /// Gets the codeshares. + /// + [JsonPropertyName("codeshares")] + public List? Codeshares { get; init; } + + /// + /// Gets the continuation by. + /// + [JsonPropertyName("continuationBy")] + public List? ContinuationBy { get; init; } + + /// + /// Gets the EVA number. + /// + [JsonPropertyName("evaNumber")] + public string EvaNumber { get; init; } = string.Empty; + + /// + /// Gets the journey identifier. + /// + [JsonPropertyName("journeyId")] + public string JourneyId { get; init; } = string.Empty; + + /// + /// Gets the journey information. + /// + [JsonPropertyName("journeyInfo")] + public JourneyInfoContract JourneyInfo { get; init; } = new(); + + /// + /// Gets the messages. + /// + [JsonPropertyName("messages")] + public List? Messages { get; init; } + + /// + /// Gets a value indicating whether there is no passenger change. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("noPassengerChange")] + public bool NoPassengerChange { get; init; } + + /// + /// Gets a value indicating whether this is on demand. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("onDemand")] + public bool OnDemand { get; init; } + + /// + /// Gets a value indicating whether there were past disruptions. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("pastDisruptions")] + public bool? PastDisruptions { get; init; } + + /// + /// Gets the platform. + /// + [JsonPropertyName("platform")] + public PlatformContract? Platform { get; init; } + + /// + /// Gets the platform history. + /// + [JsonPropertyName("platformHistory")] + public List? PlatformHistory { get; init; } + + /// + /// Gets the platform schedule. + /// + [JsonPropertyName("platformSchedule")] + public PlatformContract? PlatformSchedule { get; init; } + + /// + /// Gets the relief by. + /// + [JsonPropertyName("reliefBy")] + public List? ReliefBy { get; init; } + + /// + /// Gets the relief for. + /// + [JsonPropertyName("reliefFor")] + public List? ReliefFor { get; init; } + + /// + /// Gets the replaced by. + /// + [JsonPropertyName("replacedBy")] + public List? ReplacedBy { get; init; } + + /// + /// Gets the replacement for. + /// + [JsonPropertyName("replacementFor")] + public List? ReplacementFor { get; init; } + + /// + /// Gets the time. + /// + [JsonPropertyName("time")] + public string Time { get; init; } = string.Empty; + + /// + /// Gets the time schedule. + /// + [JsonPropertyName("timeSchedule")] + public string TimeSchedule { get; init; } = string.Empty; + + /// + /// Gets the time type. + /// + [JsonPropertyName("timeType")] + public string TimeType { get; init; } = string.Empty; + + /// + /// Gets the transport. + /// + [JsonPropertyName("transport")] + public TransportWithDirectionAndViaContract Transport { get; init; } = new(); + + /// + /// Gets the travels with. + /// + [JsonPropertyName("travelsWith")] + public List? TravelsWith { get; init; } + + /// + /// Gets a value indicating whether the vehicle sequence is available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("vehicleSequenceAvailable")] + public bool? VehicleSequenceAvailable { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/BoardMetaContract.cs b/source/DotBahn.Boards/Internal/Contracts/BoardMetaContract.cs new file mode 100644 index 0000000..1becedc --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/BoardMetaContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a board meta. +/// +[ExcludeFromCodeCoverage] +internal record BoardMetaContract { + /// + /// Gets the considered stop places. + /// + [JsonPropertyName("consideredStopPlaces")] + public List? ConsideredStopPlaces { get; init; } + + /// + /// Gets the truncated transport types. + /// + [JsonPropertyName("truncatedTransportTypes")] + public List? TruncatedTransportTypes { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/CodeShareContract.cs b/source/DotBahn.Boards/Internal/Contracts/CodeShareContract.cs new file mode 100644 index 0000000..7b57f96 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/CodeShareContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a codeshare. +/// +[ExcludeFromCodeCoverage] +internal record CodeShareContract { + /// + /// Gets the airline code. + /// + [JsonPropertyName("airlineCode")] + public string AirlineCode { get; init; } = string.Empty; + + /// + /// Gets the flight number. + /// + [JsonPropertyName("flightnumber")] + public int Flightnumber { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/DepartureBoardResponseContract.cs b/source/DotBahn.Boards/Internal/Contracts/DepartureBoardResponseContract.cs new file mode 100644 index 0000000..0194625 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/DepartureBoardResponseContract.cs @@ -0,0 +1,52 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a departure-board response. +/// +[ExcludeFromCodeCoverage] +internal record DepartureBoardResponseContract { + /// + /// Gets the administrations. + /// + [JsonPropertyName("administrations")] + public List? Administrations { get; init; } + + /// + /// Gets the departures. + /// + [JsonPropertyName("departures")] + public List? Departures { get; init; } + + /// + /// Gets the disruption communications. + /// + [JsonPropertyName("disruptionCommunications")] + public List? DisruptionCommunications { get; init; } + + /// + /// Gets the messages. + /// + [JsonPropertyName("messages")] + public MessagesMultiLanguageContract? Messages { get; init; } + + /// + /// Gets the meta. + /// + [JsonPropertyName("meta")] + public BoardMetaContract Meta { get; init; } = new(); + + /// + /// Gets the stations. + /// + [JsonPropertyName("stations")] + public List? Stations { get; init; } + + /// + /// Gets the stop places. + /// + [JsonPropertyName("stopPlaces")] + public List? StopPlaces { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/DepartureContract.cs b/source/DotBahn.Boards/Internal/Contracts/DepartureContract.cs new file mode 100644 index 0000000..e2444a8 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/DepartureContract.cs @@ -0,0 +1,167 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using DotBahn.Common.Parsing.Converters; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a departure. +/// +[ExcludeFromCodeCoverage] +internal record DepartureContract { + /// + /// Gets a value indicating whether this is additional. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("additional")] + public bool Additional { get; init; } + + /// + /// Gets a value indicating whether this is cancelled. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("cancelled")] + public bool Cancelled { get; init; } + + /// + /// Gets the codeshares. + /// + [JsonPropertyName("codeshares")] + public List? Codeshares { get; init; } + + /// + /// Gets the continuation for. + /// + [JsonPropertyName("continuationFor")] + public List? ContinuationFor { get; init; } + + /// + /// Gets the departure identifier. + /// + [JsonPropertyName("departureId")] + public string DepartureId { get; init; } = string.Empty; + + /// + /// Gets the EVA number. + /// + [JsonPropertyName("evaNumber")] + public string EvaNumber { get; init; } = string.Empty; + + /// + /// Gets a value indicating whether there are future disruptions. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("futureDisruptions")] + public bool? FutureDisruptions { get; init; } + + /// + /// Gets the journey identifier. + /// + [JsonPropertyName("journeyId")] + public string JourneyId { get; init; } = string.Empty; + + /// + /// Gets the journey information. + /// + [JsonPropertyName("journeyInfo")] + public JourneyInfoContract JourneyInfo { get; init; } = new(); + + /// + /// Gets the messages. + /// + [JsonPropertyName("messages")] + public List? Messages { get; init; } + + /// + /// Gets a value indicating whether there is no passenger change. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("noPassengerChange")] + public bool NoPassengerChange { get; init; } + + /// + /// Gets a value indicating whether this is on demand. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("onDemand")] + public bool OnDemand { get; init; } + + /// + /// Gets the platform. + /// + [JsonPropertyName("platform")] + public PlatformContract? Platform { get; init; } + + /// + /// Gets the platform history. + /// + [JsonPropertyName("platformHistory")] + public List? PlatformHistory { get; init; } + + /// + /// Gets the platform schedule. + /// + [JsonPropertyName("platformSchedule")] + public PlatformContract? PlatformSchedule { get; init; } + + /// + /// Gets the relief by. + /// + [JsonPropertyName("reliefBy")] + public List? ReliefBy { get; init; } + + /// + /// Gets the relief for. + /// + [JsonPropertyName("reliefFor")] + public List? ReliefFor { get; init; } + + /// + /// Gets the replaced by. + /// + [JsonPropertyName("replacedBy")] + public List? ReplacedBy { get; init; } + + /// + /// Gets the replacement for. + /// + [JsonPropertyName("replacementFor")] + public List? ReplacementFor { get; init; } + + /// + /// Gets the time. + /// + [JsonPropertyName("time")] + public string Time { get; init; } = string.Empty; + + /// + /// Gets the time schedule. + /// + [JsonPropertyName("timeSchedule")] + public string TimeSchedule { get; init; } = string.Empty; + + /// + /// Gets the time type. + /// + [JsonPropertyName("timeType")] + public string TimeType { get; init; } = string.Empty; + + /// + /// Gets the transport. + /// + [JsonPropertyName("transport")] + public TransportWithDirectionAndViaContract Transport { get; init; } = new(); + + /// + /// Gets the travels with. + /// + [JsonPropertyName("travelsWith")] + public List? TravelsWith { get; init; } + + /// + /// Gets a value indicating whether the vehicle sequence is available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("vehicleSequenceAvailable")] + public bool? VehicleSequenceAvailable { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/DirectionInfoContract.cs b/source/DotBahn.Boards/Internal/Contracts/DirectionInfoContract.cs new file mode 100644 index 0000000..5137dcc --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/DirectionInfoContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a direction information. +/// +[ExcludeFromCodeCoverage] +internal record DirectionInfoContract { + /// + /// Gets the stop places. + /// + [JsonPropertyName("stopPlaces")] + public List? StopPlaces { get; init; } + + /// + /// Gets the texts. + /// + [JsonPropertyName("texts")] + public List? Texts { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/DisruptionCommunicationAttachmentContract.cs b/source/DotBahn.Boards/Internal/Contracts/DisruptionCommunicationAttachmentContract.cs new file mode 100644 index 0000000..780f66f --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/DisruptionCommunicationAttachmentContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a disruption-communication attachment. +/// +[ExcludeFromCodeCoverage] +internal record DisruptionCommunicationAttachmentContract { + /// + /// Gets the label. + /// + [JsonPropertyName("label")] + public string Label { get; init; } = string.Empty; + + /// + /// Gets the URL. + /// + [JsonPropertyName("url")] + public string Url { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/DisruptionCommunicationImageContract.cs b/source/DotBahn.Boards/Internal/Contracts/DisruptionCommunicationImageContract.cs new file mode 100644 index 0000000..b53744f --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/DisruptionCommunicationImageContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a disruption-communication image. +/// +[ExcludeFromCodeCoverage] +internal record DisruptionCommunicationImageContract { + /// + /// Gets the label. + /// + [JsonPropertyName("label")] + public string Label { get; init; } = string.Empty; + + /// + /// Gets the URL. + /// + [JsonPropertyName("url")] + public string Url { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/DisruptionCommunicationLinkContract.cs b/source/DotBahn.Boards/Internal/Contracts/DisruptionCommunicationLinkContract.cs new file mode 100644 index 0000000..1c749dc --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/DisruptionCommunicationLinkContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a disruption-communication link. +/// +[ExcludeFromCodeCoverage] +internal record DisruptionCommunicationLinkContract { + /// + /// Gets the label. + /// + [JsonPropertyName("label")] + public string Label { get; init; } = string.Empty; + + /// + /// Gets the URL. + /// + [JsonPropertyName("url")] + public string Url { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/ErrorDetailContract.cs b/source/DotBahn.Boards/Internal/Contracts/ErrorDetailContract.cs new file mode 100644 index 0000000..fe230fe --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/ErrorDetailContract.cs @@ -0,0 +1,34 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for an error detail. +/// +[ExcludeFromCodeCoverage] +internal record ErrorDetailContract { + /// + /// Gets the detail. + /// + [JsonPropertyName("detail")] + public string Detail { get; init; } = string.Empty; + + /// + /// Gets the error code. + /// + [JsonPropertyName("errorCode")] + public string? ErrorCode { get; init; } + + /// + /// Gets the field. + /// + [JsonPropertyName("field")] + public string Field { get; init; } = string.Empty; + + /// + /// Gets the title. + /// + [JsonPropertyName("title")] + public string Title { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/ErrorResponseContract.cs b/source/DotBahn.Boards/Internal/Contracts/ErrorResponseContract.cs new file mode 100644 index 0000000..5681baa --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/ErrorResponseContract.cs @@ -0,0 +1,46 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for an error response. +/// +[ExcludeFromCodeCoverage] +internal record ErrorResponseContract { + /// + /// Gets the detail. + /// + [JsonPropertyName("detail")] + public string Detail { get; init; } = string.Empty; + + /// + /// Gets the error code. + /// + [JsonPropertyName("errorCode")] + public string? ErrorCode { get; init; } + + /// + /// Gets the errors. + /// + [JsonPropertyName("errors")] + public List? Errors { get; init; } + + /// + /// Gets the instance identifier. + /// + [JsonPropertyName("instanceId")] + public string? InstanceId { get; init; } + + /// + /// Gets the status. + /// + [JsonPropertyName("status")] + public string? Status { get; init; } + + /// + /// Gets the title. + /// + [JsonPropertyName("title")] + public string Title { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/JourneyInfoContract.cs b/source/DotBahn.Boards/Internal/Contracts/JourneyInfoContract.cs new file mode 100644 index 0000000..81d09f7 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/JourneyInfoContract.cs @@ -0,0 +1,72 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using DotBahn.Common.Parsing.Converters; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a journey information. +/// +[ExcludeFromCodeCoverage] +internal record JourneyInfoContract { + /// + /// Gets the destination. + /// + [JsonPropertyName("destination")] + public StopPlaceRefWithCancelContract Destination { get; init; } = new(); + + /// + /// Gets the differing destination. + /// + [JsonPropertyName("differingDestination")] + public StopPlaceRefContract? DifferingDestination { get; init; } + + /// + /// Gets the differing origin. + /// + [JsonPropertyName("differingOrigin")] + public StopPlaceRefContract? DifferingOrigin { get; init; } + + /// + /// Gets the header administration identifier. + /// + [JsonPropertyName("headerAdministrationId")] + public string HeaderAdministrationId { get; init; } = string.Empty; + + /// + /// Gets the header journey number. + /// + [JsonPropertyName("headerJourneyNumber")] + public int HeaderJourneyNumber { get; init; } + + /// + /// Gets a value indicating whether the journey is cancelled. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("journeyCancelled")] + public bool JourneyCancelled { get; init; } + + /// + /// Gets the origin. + /// + [JsonPropertyName("origin")] + public StopPlaceRefWithCancelContract Origin { get; init; } = new(); + + /// + /// Gets the scheduled start time. + /// + [JsonPropertyName("scheduledStartTime")] + public string ScheduledStartTime { get; init; } = string.Empty; + + /// + /// Gets the transport at start. + /// + [JsonPropertyName("transportAtStart")] + public TransportContract TransportAtStart { get; init; } = new(); + + /// + /// Gets the type. + /// + [JsonPropertyName("type")] + public string Type { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/LineChipVisualizationContract.cs b/source/DotBahn.Boards/Internal/Contracts/LineChipVisualizationContract.cs new file mode 100644 index 0000000..b69c15d --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/LineChipVisualizationContract.cs @@ -0,0 +1,34 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a line chip visualization. +/// +[ExcludeFromCodeCoverage] +internal record LineChipVisualizationContract { + /// + /// Gets the differing boundary colour. + /// + [JsonPropertyName("differingBoundaryColour")] + public string? DifferingBoundaryColour { get; init; } + + /// + /// Gets the differing fill colour. + /// + [JsonPropertyName("differingFillColour")] + public string? DifferingFillColour { get; init; } + + /// + /// Gets the differing text colour. + /// + [JsonPropertyName("differingTextColour")] + public string? DifferingTextColour { get; init; } + + /// + /// Gets the secondary fill colour. + /// + [JsonPropertyName("secondaryFillColour")] + public string? SecondaryFillColour { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/LineColourContract.cs b/source/DotBahn.Boards/Internal/Contracts/LineColourContract.cs new file mode 100644 index 0000000..ad022e8 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/LineColourContract.cs @@ -0,0 +1,34 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a line colour. +/// +[ExcludeFromCodeCoverage] +internal record LineColourContract { + /// + /// Gets the chip visualization. + /// + [JsonPropertyName("chipVisualization")] + public LineChipVisualizationContract? ChipVisualization { get; init; } + + /// + /// Gets the primary colour. + /// + [JsonPropertyName("primaryColour")] + public string PrimaryColour { get; init; } = string.Empty; + + /// + /// Gets the primary text colour. + /// + [JsonPropertyName("primaryTextColour")] + public string PrimaryTextColour { get; init; } = string.Empty; + + /// + /// Gets the stroke visualization. + /// + [JsonPropertyName("strokeVisualization")] + public LineStrokeVisualizationContract? StrokeVisualization { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/LineInfoContract.cs b/source/DotBahn.Boards/Internal/Contracts/LineInfoContract.cs new file mode 100644 index 0000000..0f95d2c --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/LineInfoContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a line information. +/// +[ExcludeFromCodeCoverage] +internal record LineInfoContract { + /// + /// Gets the colour. + /// + [JsonPropertyName("colour")] + public LineColourContract? Colour { get; init; } + + /// + /// Gets the name. + /// + [JsonPropertyName("name")] + public string Name { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/LineStrokeVisualizationContract.cs b/source/DotBahn.Boards/Internal/Contracts/LineStrokeVisualizationContract.cs new file mode 100644 index 0000000..b9a9ad5 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/LineStrokeVisualizationContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a line stroke visualization. +/// +[ExcludeFromCodeCoverage] +internal record LineStrokeVisualizationContract { + /// + /// Gets the differing boundary colour. + /// + [JsonPropertyName("differingBoundaryColour")] + public string? DifferingBoundaryColour { get; init; } + + /// + /// Gets the secondary fill colour. + /// + [JsonPropertyName("secondaryFillColour")] + public string? SecondaryFillColour { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/MessageAttributeDescriptionContract.cs b/source/DotBahn.Boards/Internal/Contracts/MessageAttributeDescriptionContract.cs new file mode 100644 index 0000000..2d8b3d2 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/MessageAttributeDescriptionContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a message attribute description. +/// +[ExcludeFromCodeCoverage] +internal record MessageAttributeDescriptionContract { + /// + /// Gets the language. + /// + [JsonPropertyName("language")] + public string Language { get; init; } = string.Empty; + + /// + /// Gets the text. + /// + [JsonPropertyName("text")] + public string Text { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/MessageAttributeMultiLanguageContract.cs b/source/DotBahn.Boards/Internal/Contracts/MessageAttributeMultiLanguageContract.cs new file mode 100644 index 0000000..d4c2619 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/MessageAttributeMultiLanguageContract.cs @@ -0,0 +1,40 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a journey attribute multi-language. +/// +[ExcludeFromCodeCoverage] +internal record MessageAttributeMultiLanguageContract { + /// + /// Gets the code. + /// + [JsonPropertyName("code")] + public string Code { get; init; } = string.Empty; + + /// + /// Gets the descriptions. + /// + [JsonPropertyName("descriptions")] + public List? Descriptions { get; init; } + + /// + /// Gets the display priority. + /// + [JsonPropertyName("displayPriority")] + public int? DisplayPriority { get; init; } + + /// + /// Gets the display priority detail. + /// + [JsonPropertyName("displayPriorityDetail")] + public int? DisplayPriorityDetail { get; init; } + + /// + /// Gets the message identifier. + /// + [JsonPropertyName("messageID")] + public int MessageId { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/MessageDisruptionCommunicationDescriptionContract.cs b/source/DotBahn.Boards/Internal/Contracts/MessageDisruptionCommunicationDescriptionContract.cs new file mode 100644 index 0000000..159d4c5 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/MessageDisruptionCommunicationDescriptionContract.cs @@ -0,0 +1,46 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a disruption-communication description. +/// +[ExcludeFromCodeCoverage] +internal record MessageDisruptionCommunicationDescriptionContract { + /// + /// Gets the attachments. + /// + [JsonPropertyName("attachments")] + public List? Attachments { get; init; } + + /// + /// Gets the images. + /// + [JsonPropertyName("images")] + public List? Images { get; init; } + + /// + /// Gets the language. + /// + [JsonPropertyName("language")] + public string Language { get; init; } = string.Empty; + + /// + /// Gets the links. + /// + [JsonPropertyName("links")] + public List? Links { get; init; } + + /// + /// Gets the text. + /// + [JsonPropertyName("text")] + public string Text { get; init; } = string.Empty; + + /// + /// Gets the short text. + /// + [JsonPropertyName("textShort")] + public string? TextShort { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/MessageDisruptionCommunicationMultiLanguageContract.cs b/source/DotBahn.Boards/Internal/Contracts/MessageDisruptionCommunicationMultiLanguageContract.cs new file mode 100644 index 0000000..3050471 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/MessageDisruptionCommunicationMultiLanguageContract.cs @@ -0,0 +1,60 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using DotBahn.Common.Parsing.Converters; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a disruption-communication multi-language. +/// +[ExcludeFromCodeCoverage] +internal record MessageDisruptionCommunicationMultiLanguageContract { + /// + /// Gets the cause. + /// + [JsonPropertyName("cause")] + public string? Cause { get; init; } + + /// + /// Gets the descriptions. + /// + [JsonPropertyName("descriptions")] + public List? Descriptions { get; init; } + + /// + /// Gets the display priority. + /// + [JsonPropertyName("displayPriority")] + public int? DisplayPriority { get; init; } + + /// + /// Gets the disruption communication identifier. + /// + [JsonPropertyName("disruptionCommunicationID")] + public string DisruptionCommunicationId { get; init; } = string.Empty; + + /// + /// Gets the disruption identifier. + /// + [JsonPropertyName("disruptionID")] + public string DisruptionId { get; init; } = string.Empty; + + /// + /// Gets the effect. + /// + [JsonPropertyName("effect")] + public string Effect { get; init; } = string.Empty; + + /// + /// Gets a value indicating whether alternatives are available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("hasAlternatives")] + public bool? HasAlternatives { get; init; } + + /// + /// Gets the message identifier. + /// + [JsonPropertyName("messageID")] + public int MessageId { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/MessageNoteDescriptionContract.cs b/source/DotBahn.Boards/Internal/Contracts/MessageNoteDescriptionContract.cs new file mode 100644 index 0000000..82369e7 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/MessageNoteDescriptionContract.cs @@ -0,0 +1,46 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a note description. +/// +[ExcludeFromCodeCoverage] +internal record MessageNoteDescriptionContract { + /// + /// Gets the attachments. + /// + [JsonPropertyName("attachments")] + public List? Attachments { get; init; } + + /// + /// Gets the images. + /// + [JsonPropertyName("images")] + public List? Images { get; init; } + + /// + /// Gets the language. + /// + [JsonPropertyName("language")] + public string Language { get; init; } = string.Empty; + + /// + /// Gets the links. + /// + [JsonPropertyName("links")] + public List? Links { get; init; } + + /// + /// Gets the text. + /// + [JsonPropertyName("text")] + public string Text { get; init; } = string.Empty; + + /// + /// Gets the short text. + /// + [JsonPropertyName("textShort")] + public string? TextShort { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/MessageNoteMultiLanguageContract.cs b/source/DotBahn.Boards/Internal/Contracts/MessageNoteMultiLanguageContract.cs new file mode 100644 index 0000000..2f213d9 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/MessageNoteMultiLanguageContract.cs @@ -0,0 +1,52 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a note multi-language. +/// +[ExcludeFromCodeCoverage] +internal record MessageNoteMultiLanguageContract { + /// + /// Gets the category. + /// + [JsonPropertyName("category")] + public string? Category { get; init; } + + /// + /// Gets the code. + /// + [JsonPropertyName("code")] + public string? Code { get; init; } + + /// + /// Gets the descriptions. + /// + [JsonPropertyName("descriptions")] + public List? Descriptions { get; init; } + + /// + /// Gets the display priority. + /// + [JsonPropertyName("displayPriority")] + public int? DisplayPriority { get; init; } + + /// + /// Gets the disruption communication identifier. + /// + [JsonPropertyName("disruptionCommunicationID")] + public string? DisruptionCommunicationId { get; init; } + + /// + /// Gets the disruption identifier. + /// + [JsonPropertyName("disruptionID")] + public string? DisruptionId { get; init; } + + /// + /// Gets the message identifier. + /// + [JsonPropertyName("messageID")] + public int MessageId { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/MessageRisCauseCodeDescriptionContract.cs b/source/DotBahn.Boards/Internal/Contracts/MessageRisCauseCodeDescriptionContract.cs new file mode 100644 index 0000000..540bc2c --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/MessageRisCauseCodeDescriptionContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a RIS cause-code description. +/// +[ExcludeFromCodeCoverage] +internal record MessageRisCauseCodeDescriptionContract { + /// + /// Gets the language. + /// + [JsonPropertyName("language")] + public string Language { get; init; } = string.Empty; + + /// + /// Gets the text. + /// + [JsonPropertyName("text")] + public string Text { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/MessageRisCauseCodeMultiLanguageContract.cs b/source/DotBahn.Boards/Internal/Contracts/MessageRisCauseCodeMultiLanguageContract.cs new file mode 100644 index 0000000..00ff9a4 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/MessageRisCauseCodeMultiLanguageContract.cs @@ -0,0 +1,28 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a RIS cause-code multi-language. +/// +[ExcludeFromCodeCoverage] +internal record MessageRisCauseCodeMultiLanguageContract { + /// + /// Gets the code. + /// + [JsonPropertyName("code")] + public string Code { get; init; } = string.Empty; + + /// + /// Gets the descriptions. + /// + [JsonPropertyName("descriptions")] + public List? Descriptions { get; init; } + + /// + /// Gets the message identifier. + /// + [JsonPropertyName("messageID")] + public int MessageId { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/MessageRisQualityDeviationDescriptionContract.cs b/source/DotBahn.Boards/Internal/Contracts/MessageRisQualityDeviationDescriptionContract.cs new file mode 100644 index 0000000..a22bcc2 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/MessageRisQualityDeviationDescriptionContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a RIS quality-deviation description. +/// +[ExcludeFromCodeCoverage] +internal record MessageRisQualityDeviationDescriptionContract { + /// + /// Gets the language. + /// + [JsonPropertyName("language")] + public string Language { get; init; } = string.Empty; + + /// + /// Gets the text. + /// + [JsonPropertyName("text")] + public string Text { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/MessageRisQualityDeviationMultiLanguageContract.cs b/source/DotBahn.Boards/Internal/Contracts/MessageRisQualityDeviationMultiLanguageContract.cs new file mode 100644 index 0000000..0de3dd7 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/MessageRisQualityDeviationMultiLanguageContract.cs @@ -0,0 +1,28 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a RIS quality-deviation multi-language. +/// +[ExcludeFromCodeCoverage] +internal record MessageRisQualityDeviationMultiLanguageContract { + /// + /// Gets the code. + /// + [JsonPropertyName("code")] + public string Code { get; init; } = string.Empty; + + /// + /// Gets the descriptions. + /// + [JsonPropertyName("descriptions")] + public List? Descriptions { get; init; } + + /// + /// Gets the message identifier. + /// + [JsonPropertyName("messageID")] + public int MessageId { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/MessagesMultiLanguageContract.cs b/source/DotBahn.Boards/Internal/Contracts/MessagesMultiLanguageContract.cs new file mode 100644 index 0000000..8e3df42 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/MessagesMultiLanguageContract.cs @@ -0,0 +1,40 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a messages multi-language. +/// +[ExcludeFromCodeCoverage] +internal record MessagesMultiLanguageContract { + /// + /// Gets the attributes. + /// + [JsonPropertyName("attributes")] + public List? Attributes { get; init; } + + /// + /// Gets the disruptions. + /// + [JsonPropertyName("disruptions")] + public List? Disruptions { get; init; } + + /// + /// Gets the notes. + /// + [JsonPropertyName("notes")] + public List? Notes { get; init; } + + /// + /// Gets the RIS cause codes. + /// + [JsonPropertyName("risCauseCodes")] + public List? RisCauseCodes { get; init; } + + /// + /// Gets the RIS quality deviations. + /// + [JsonPropertyName("risQualityDeviations")] + public List? RisQualityDeviations { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/OpenArrivalBoardRequestContract.cs b/source/DotBahn.Boards/Internal/Contracts/OpenArrivalBoardRequestContract.cs new file mode 100644 index 0000000..06a0cba --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/OpenArrivalBoardRequestContract.cs @@ -0,0 +1,81 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using DotBahn.Common.Parsing.Converters; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for an arrival-board request. +/// +[ExcludeFromCodeCoverage] +internal record OpenArrivalBoardRequestContract { + /// + /// Gets a value indicating whether line colours are included. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("includeLineColours")] + public bool IncludeLineColours { get; init; } + + /// + /// Gets a value indicating whether platform accessibility is included. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("includePlatformAccessibility")] + public bool IncludePlatformAccessibility { get; init; } + + /// + /// Gets the languages. + /// + [JsonPropertyName("languages")] + public List? Languages { get; init; } + + /// + /// Gets the maximum entries per transport type. + /// + [JsonPropertyName("maxEntriesPerTransportType")] + public int MaxEntriesPerTransportType { get; init; } = 25; + + /// + /// Gets the maximum via stops. + /// + [JsonPropertyName("maxViaStops")] + public int MaxViaStops { get; init; } = 3; + + /// + /// Gets a value indicating whether cancellations are excluded. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("noCancellations")] + public bool NoCancellations { get; init; } + + /// + /// Gets a value indicating whether only replacement transports are included. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("onlyReplacementTransports")] + public bool OnlyReplacementTransports { get; init; } + + /// + /// Gets the sort by. + /// + [JsonPropertyName("sortBy")] + public string? SortBy { get; init; } + + /// + /// Gets the stop-place or station. + /// + [JsonPropertyName("stopPlaceOrStation")] + public StopPlaceOrStationRequestContract StopPlaceOrStation { get; init; } = new(); + + /// + /// Gets the time window. + /// + [JsonPropertyName("timeWindow")] + public TimeWindowContract? TimeWindow { get; init; } + + /// + /// Gets the transport types. + /// + [JsonPropertyName("transportTypes")] + public List? TransportTypes { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/OpenDepartureBoardRequestContract.cs b/source/DotBahn.Boards/Internal/Contracts/OpenDepartureBoardRequestContract.cs new file mode 100644 index 0000000..f78359a --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/OpenDepartureBoardRequestContract.cs @@ -0,0 +1,81 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using DotBahn.Common.Parsing.Converters; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a departure-board request. +/// +[ExcludeFromCodeCoverage] +internal record OpenDepartureBoardRequestContract { + /// + /// Gets a value indicating whether line colours are included. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("includeLineColours")] + public bool IncludeLineColours { get; init; } + + /// + /// Gets a value indicating whether platform accessibility is included. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("includePlatformAccessibility")] + public bool IncludePlatformAccessibility { get; init; } + + /// + /// Gets the languages. + /// + [JsonPropertyName("languages")] + public List? Languages { get; init; } + + /// + /// Gets the maximum entries per transport type. + /// + [JsonPropertyName("maxEntriesPerTransportType")] + public int MaxEntriesPerTransportType { get; init; } = 25; + + /// + /// Gets the maximum via stops. + /// + [JsonPropertyName("maxViaStops")] + public int MaxViaStops { get; init; } = 3; + + /// + /// Gets a value indicating whether cancellations are excluded. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("noCancellations")] + public bool NoCancellations { get; init; } + + /// + /// Gets a value indicating whether only replacement transports are included. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("onlyReplacementTransports")] + public bool OnlyReplacementTransports { get; init; } + + /// + /// Gets the sort by. + /// + [JsonPropertyName("sortBy")] + public string? SortBy { get; init; } + + /// + /// Gets the stop-place or station. + /// + [JsonPropertyName("stopPlaceOrStation")] + public StopPlaceOrStationRequestContract StopPlaceOrStation { get; init; } = new(); + + /// + /// Gets the time window. + /// + [JsonPropertyName("timeWindow")] + public TimeWindowContract? TimeWindow { get; init; } + + /// + /// Gets the transport types. + /// + [JsonPropertyName("transportTypes")] + public List? TransportTypes { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/PlatformAccessibilityContract.cs b/source/DotBahn.Boards/Internal/Contracts/PlatformAccessibilityContract.cs new file mode 100644 index 0000000..a1ed60b --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/PlatformAccessibilityContract.cs @@ -0,0 +1,88 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using DotBahn.Common.Parsing.Converters; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a platform accessibility. +/// +[ExcludeFromCodeCoverage] +internal record PlatformAccessibilityContract { + /// + /// Gets a value indicating whether audible signals are available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("audibleSignalsAvailable")] + public bool AudibleSignalsAvailable { get; init; } + + /// + /// Gets a value indicating whether an automatic door is available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("automaticDoor")] + public bool AutomaticDoor { get; init; } + + /// + /// Gets a value indicating whether boarding aid is available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("boardingAid")] + public bool BoardingAid { get; init; } + + /// + /// Gets a value indicating whether a passenger information display is available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("passengerInformationDisplay")] + public bool PassengerInformationDisplay { get; init; } + + /// + /// Gets a value indicating whether a platform sign is available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("platformSign")] + public bool PlatformSign { get; init; } + + /// + /// Gets a value indicating whether stairs marking is available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("stairsMarking")] + public bool StairsMarking { get; init; } + + /// + /// Gets a value indicating whether a standard platform height is available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("standardPlatformHeight")] + public bool StandardPlatformHeight { get; init; } + + /// + /// Gets a value indicating whether step-free access is available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("stepFreeAccess")] + public bool StepFreeAccess { get; init; } + + /// + /// Gets a value indicating whether tactile guiding strips are available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("tactileGuidingStrips")] + public bool TactileGuidingStrips { get; init; } + + /// + /// Gets a value indicating whether a tactile handrail label is available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("tactileHandrailLabel")] + public bool TactileHandrailLabel { get; init; } + + /// + /// Gets a value indicating whether tactile platform access is available. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("tactilePlatformAccess")] + public bool TactilePlatformAccess { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/PlatformContract.cs b/source/DotBahn.Boards/Internal/Contracts/PlatformContract.cs new file mode 100644 index 0000000..5768648 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/PlatformContract.cs @@ -0,0 +1,28 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a platform. +/// +[ExcludeFromCodeCoverage] +internal record PlatformContract { + /// + /// Gets the accessibility. + /// + [JsonPropertyName("accessibility")] + public PlatformAccessibilityContract? Accessibility { get; init; } + + /// + /// Gets the IFOPT. + /// + [JsonPropertyName("ifopt")] + public string? Ifopt { get; init; } + + /// + /// Gets the name. + /// + [JsonPropertyName("name")] + public string Name { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/PlatformHistoryContract.cs b/source/DotBahn.Boards/Internal/Contracts/PlatformHistoryContract.cs new file mode 100644 index 0000000..d42337a --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/PlatformHistoryContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a platform history entry. +/// +[ExcludeFromCodeCoverage] +internal record PlatformHistoryContract { + /// + /// Gets the IFOPT. + /// + [JsonPropertyName("ifopt")] + public string? Ifopt { get; init; } + + /// + /// Gets the name. + /// + [JsonPropertyName("name")] + public string Name { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/ReplacementTransportContract.cs b/source/DotBahn.Boards/Internal/Contracts/ReplacementTransportContract.cs new file mode 100644 index 0000000..c8c1403 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/ReplacementTransportContract.cs @@ -0,0 +1,16 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a replacement transport. +/// +[ExcludeFromCodeCoverage] +internal record ReplacementTransportContract { + /// + /// Gets the real type. + /// + [JsonPropertyName("realType")] + public string RealType { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/StationMultiLanguageContract.cs b/source/DotBahn.Boards/Internal/Contracts/StationMultiLanguageContract.cs new file mode 100644 index 0000000..64f82fa --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/StationMultiLanguageContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a station multi-language. +/// +[ExcludeFromCodeCoverage] +internal record StationMultiLanguageContract { + /// + /// Gets the localized names. + /// + [JsonPropertyName("localizedNames")] + public List? LocalizedNames { get; init; } + + /// + /// Gets the STADA identifier. + /// + [JsonPropertyName("stada")] + public string Stada { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/StationNameMultiLanguageContract.cs b/source/DotBahn.Boards/Internal/Contracts/StationNameMultiLanguageContract.cs new file mode 100644 index 0000000..783c0d5 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/StationNameMultiLanguageContract.cs @@ -0,0 +1,22 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a station name multi-language. +/// +[ExcludeFromCodeCoverage] +internal record StationNameMultiLanguageContract { + /// + /// Gets the language. + /// + [JsonPropertyName("language")] + public string Language { get; init; } = string.Empty; + + /// + /// Gets the name. + /// + [JsonPropertyName("name")] + public string Name { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/StopPlaceMultiLanguageContract.cs b/source/DotBahn.Boards/Internal/Contracts/StopPlaceMultiLanguageContract.cs new file mode 100644 index 0000000..3d71bd4 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/StopPlaceMultiLanguageContract.cs @@ -0,0 +1,34 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a stop-place multi-language. +/// +[ExcludeFromCodeCoverage] +internal record StopPlaceMultiLanguageContract { + /// + /// Gets the EVA number. + /// + [JsonPropertyName("evaNumber")] + public string EvaNumber { get; init; } = string.Empty; + + /// + /// Gets the IFOPT. + /// + [JsonPropertyName("ifopt")] + public string? Ifopt { get; init; } + + /// + /// Gets the localized names. + /// + [JsonPropertyName("localizedNames")] + public List? LocalizedNames { get; init; } + + /// + /// Gets the STADA identifier. + /// + [JsonPropertyName("stada")] + public string? Stada { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/StopPlaceNameMultiLanguageContract.cs b/source/DotBahn.Boards/Internal/Contracts/StopPlaceNameMultiLanguageContract.cs new file mode 100644 index 0000000..021851a --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/StopPlaceNameMultiLanguageContract.cs @@ -0,0 +1,34 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a stop-place name multi-language. +/// +[ExcludeFromCodeCoverage] +internal record StopPlaceNameMultiLanguageContract { + /// + /// Gets the language. + /// + [JsonPropertyName("language")] + public string Language { get; init; } = string.Empty; + + /// + /// Gets the name. + /// + [JsonPropertyName("name")] + public string Name { get; init; } = string.Empty; + + /// + /// Gets the symbol. + /// + [JsonPropertyName("symbol")] + public string? Symbol { get; init; } + + /// + /// Gets the symbol name. + /// + [JsonPropertyName("symbolName")] + public string? SymbolName { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/StopPlaceOrStationRequestContract.cs b/source/DotBahn.Boards/Internal/Contracts/StopPlaceOrStationRequestContract.cs new file mode 100644 index 0000000..29e0c26 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/StopPlaceOrStationRequestContract.cs @@ -0,0 +1,40 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a stop-place or station request. +/// +[ExcludeFromCodeCoverage] +internal record StopPlaceOrStationRequestContract { + /// + /// Gets the board configurations. + /// + [JsonPropertyName("boardConfigurations")] + public List? BoardConfigurations { get; init; } + + /// + /// Gets the DHIDs. + /// + [JsonPropertyName("dhids")] + public List? Dhids { get; init; } + + /// + /// Gets the EVA numbers. + /// + [JsonPropertyName("evaNumbers")] + public List? EvaNumbers { get; init; } + + /// + /// Gets the platforms. + /// + [JsonPropertyName("platforms")] + public List? Platforms { get; init; } + + /// + /// Gets the STADA identifier. + /// + [JsonPropertyName("stada")] + public string? Stada { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/StopPlaceRefContract.cs b/source/DotBahn.Boards/Internal/Contracts/StopPlaceRefContract.cs new file mode 100644 index 0000000..57e634d --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/StopPlaceRefContract.cs @@ -0,0 +1,16 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a stop-place reference. +/// +[ExcludeFromCodeCoverage] +internal record StopPlaceRefContract { + /// + /// Gets the EVA number. + /// + [JsonPropertyName("evaNumber")] + public string EvaNumber { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/StopPlaceRefViaContract.cs b/source/DotBahn.Boards/Internal/Contracts/StopPlaceRefViaContract.cs new file mode 100644 index 0000000..3ae1d4f --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/StopPlaceRefViaContract.cs @@ -0,0 +1,37 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using DotBahn.Common.Parsing.Converters; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a via stop-place reference. +/// +[ExcludeFromCodeCoverage] +internal record StopPlaceRefViaContract { + /// + /// Gets a value indicating whether this is additional. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("additional")] + public bool Additional { get; init; } + + /// + /// Gets a value indicating whether this is cancelled. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("cancelled")] + public bool Cancelled { get; init; } + + /// + /// Gets the display priority. + /// + [JsonPropertyName("displayPriority")] + public int DisplayPriority { get; init; } + + /// + /// Gets the EVA number. + /// + [JsonPropertyName("evaNumber")] + public string EvaNumber { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/StopPlaceRefWithCancelContract.cs b/source/DotBahn.Boards/Internal/Contracts/StopPlaceRefWithCancelContract.cs new file mode 100644 index 0000000..7f78d62 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/StopPlaceRefWithCancelContract.cs @@ -0,0 +1,24 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using DotBahn.Common.Parsing.Converters; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a stop-place reference with cancellation. +/// +[ExcludeFromCodeCoverage] +internal record StopPlaceRefWithCancelContract { + /// + /// Gets a value indicating whether this is cancelled. + /// + [JsonConverter(typeof(BahnDialectJsonConverter))] + [JsonPropertyName("cancelled")] + public bool Cancelled { get; init; } + + /// + /// Gets the EVA number. + /// + [JsonPropertyName("evaNumber")] + public string EvaNumber { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/TimeWindowContract.cs b/source/DotBahn.Boards/Internal/Contracts/TimeWindowContract.cs new file mode 100644 index 0000000..6241bdb --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/TimeWindowContract.cs @@ -0,0 +1,28 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a time window. +/// +[ExcludeFromCodeCoverage] +internal record TimeWindowContract { + /// + /// Gets the entry count. + /// + [JsonPropertyName("entryCount")] + public int? EntryCount { get; init; } + + /// + /// Gets the time end. + /// + [JsonPropertyName("timeEnd")] + public string? TimeEnd { get; init; } + + /// + /// Gets the time start. + /// + [JsonPropertyName("timeStart")] + public string? TimeStart { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/TransportCompanyMultiLanguageContract.cs b/source/DotBahn.Boards/Internal/Contracts/TransportCompanyMultiLanguageContract.cs new file mode 100644 index 0000000..82b9a34 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/TransportCompanyMultiLanguageContract.cs @@ -0,0 +1,58 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a transport-company multi-language. +/// +[ExcludeFromCodeCoverage] +internal record TransportCompanyMultiLanguageContract { + /// + /// Gets the email. + /// + [JsonPropertyName("email")] + public string? Email { get; init; } + + /// + /// Gets the language. + /// + [JsonPropertyName("language")] + public string Language { get; init; } = string.Empty; + + /// + /// Gets the name. + /// + [JsonPropertyName("name")] + public string Name { get; init; } = string.Empty; + + /// + /// Gets the phone number. + /// + [JsonPropertyName("phoneNumber")] + public string? PhoneNumber { get; init; } + + /// + /// Gets the short name. + /// + [JsonPropertyName("shortName")] + public string ShortName { get; init; } = string.Empty; + + /// + /// Gets the website. + /// + [JsonPropertyName("website")] + public string Website { get; init; } = string.Empty; + + /// + /// Gets the website digital assistant. + /// + [JsonPropertyName("websiteDigitalAssistant")] + public string? WebsiteDigitalAssistant { get; init; } + + /// + /// Gets the website ticketing. + /// + [JsonPropertyName("websiteTicketing")] + public string? WebsiteTicketing { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Contracts/TransportContract.cs b/source/DotBahn.Boards/Internal/Contracts/TransportContract.cs new file mode 100644 index 0000000..f2c6a83 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/TransportContract.cs @@ -0,0 +1,76 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a transport. +/// +[ExcludeFromCodeCoverage] +internal record TransportContract { + /// + /// Gets the administration identifier. + /// + [JsonPropertyName("administrationId")] + public string AdministrationId { get; init; } = string.Empty; + + /// + /// Gets the category. + /// + [JsonPropertyName("category")] + public string Category { get; init; } = string.Empty; + + /// + /// Gets the internal category. + /// + [JsonPropertyName("categoryInternal")] + public string CategoryInternal { get; init; } = string.Empty; + + /// + /// Gets the DFID. + /// + [JsonPropertyName("dfid")] + public string? Dfid { get; init; } + + /// + /// Gets the DTID. + /// + [JsonPropertyName("dtid")] + public string? Dtid { get; init; } + + /// + /// Gets the journey description. + /// + [JsonPropertyName("journeyDescription")] + public string JourneyDescription { get; init; } = string.Empty; + + /// + /// Gets the journey number. + /// + [JsonPropertyName("journeyNumber")] + public int JourneyNumber { get; init; } + + /// + /// Gets the label. + /// + [JsonPropertyName("label")] + public string? Label { get; init; } + + /// + /// Gets the line. + /// + [JsonPropertyName("line")] + public LineInfoContract? Line { get; init; } + + /// + /// Gets the operational journey number. + /// + [JsonPropertyName("operationalJourneyNumber")] + public string OperationalJourneyNumber { get; init; } = string.Empty; + + /// + /// Gets the type. + /// + [JsonPropertyName("type")] + public string Type { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/TransportDestinationPortionWorkingRefContract.cs b/source/DotBahn.Boards/Internal/Contracts/TransportDestinationPortionWorkingRefContract.cs new file mode 100644 index 0000000..f9887fa --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/TransportDestinationPortionWorkingRefContract.cs @@ -0,0 +1,100 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a transport destination reference for portion-working journeys. +/// +[ExcludeFromCodeCoverage] +internal record TransportDestinationPortionWorkingRefContract { + /// + /// Gets the administration identifier. + /// + [JsonPropertyName("administrationId")] + public string AdministrationId { get; init; } = string.Empty; + + /// + /// Gets the category. + /// + [JsonPropertyName("category")] + public string Category { get; init; } = string.Empty; + + /// + /// Gets the internal category. + /// + [JsonPropertyName("categoryInternal")] + public string CategoryInternal { get; init; } = string.Empty; + + /// + /// Gets the destination. + /// + [JsonPropertyName("destination")] + public StopPlaceRefWithCancelContract Destination { get; init; } = new(); + + /// + /// Gets the DFID. + /// + [JsonPropertyName("dfid")] + public string? Dfid { get; init; } + + /// + /// Gets the differing destination. + /// + [JsonPropertyName("differingDestination")] + public StopPlaceRefContract? DifferingDestination { get; init; } + + /// + /// Gets the DTID. + /// + [JsonPropertyName("dtid")] + public string? Dtid { get; init; } + + /// + /// Gets the journey description. + /// + [JsonPropertyName("journeyDescription")] + public string JourneyDescription { get; init; } = string.Empty; + + /// + /// Gets the journey identifier. + /// + [JsonPropertyName("journeyID")] + public string JourneyId { get; init; } = string.Empty; + + /// + /// Gets the journey number. + /// + [JsonPropertyName("journeyNumber")] + public int JourneyNumber { get; init; } + + /// + /// Gets the label. + /// + [JsonPropertyName("label")] + public string? Label { get; init; } + + /// + /// Gets the line. + /// + [JsonPropertyName("line")] + public LineInfoContract? Line { get; init; } + + /// + /// Gets the operational journey number. + /// + [JsonPropertyName("operationalJourneyNumber")] + public string OperationalJourneyNumber { get; init; } = string.Empty; + + /// + /// Gets the separation at. + /// + [JsonPropertyName("separationAt")] + public StopPlaceRefContract? SeparationAt { get; init; } + + /// + /// Gets the type. + /// + [JsonPropertyName("type")] + public string Type { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/TransportDestinationRefContract.cs b/source/DotBahn.Boards/Internal/Contracts/TransportDestinationRefContract.cs new file mode 100644 index 0000000..cd05544 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/TransportDestinationRefContract.cs @@ -0,0 +1,94 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a transport destination reference. +/// +[ExcludeFromCodeCoverage] +internal record TransportDestinationRefContract { + /// + /// Gets the administration identifier. + /// + [JsonPropertyName("administrationId")] + public string AdministrationId { get; init; } = string.Empty; + + /// + /// Gets the category. + /// + [JsonPropertyName("category")] + public string Category { get; init; } = string.Empty; + + /// + /// Gets the internal category. + /// + [JsonPropertyName("categoryInternal")] + public string CategoryInternal { get; init; } = string.Empty; + + /// + /// Gets the destination. + /// + [JsonPropertyName("destination")] + public StopPlaceRefWithCancelContract Destination { get; init; } = new(); + + /// + /// Gets the DFID. + /// + [JsonPropertyName("dfid")] + public string? Dfid { get; init; } + + /// + /// Gets the differing destination. + /// + [JsonPropertyName("differingDestination")] + public StopPlaceRefContract? DifferingDestination { get; init; } + + /// + /// Gets the DTID. + /// + [JsonPropertyName("dtid")] + public string? Dtid { get; init; } + + /// + /// Gets the journey description. + /// + [JsonPropertyName("journeyDescription")] + public string JourneyDescription { get; init; } = string.Empty; + + /// + /// Gets the journey identifier. + /// + [JsonPropertyName("journeyID")] + public string JourneyId { get; init; } = string.Empty; + + /// + /// Gets the journey number. + /// + [JsonPropertyName("journeyNumber")] + public int JourneyNumber { get; init; } + + /// + /// Gets the label. + /// + [JsonPropertyName("label")] + public string? Label { get; init; } + + /// + /// Gets the line. + /// + [JsonPropertyName("line")] + public LineInfoContract? Line { get; init; } + + /// + /// Gets the operational journey number. + /// + [JsonPropertyName("operationalJourneyNumber")] + public string OperationalJourneyNumber { get; init; } = string.Empty; + + /// + /// Gets the type. + /// + [JsonPropertyName("type")] + public string Type { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/TransportOriginRefContract.cs b/source/DotBahn.Boards/Internal/Contracts/TransportOriginRefContract.cs new file mode 100644 index 0000000..4a7cb45 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/TransportOriginRefContract.cs @@ -0,0 +1,94 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a transport origin reference. +/// +[ExcludeFromCodeCoverage] +internal record TransportOriginRefContract { + /// + /// Gets the administration identifier. + /// + [JsonPropertyName("administrationId")] + public string AdministrationId { get; init; } = string.Empty; + + /// + /// Gets the category. + /// + [JsonPropertyName("category")] + public string Category { get; init; } = string.Empty; + + /// + /// Gets the internal category. + /// + [JsonPropertyName("categoryInternal")] + public string CategoryInternal { get; init; } = string.Empty; + + /// + /// Gets the DFID. + /// + [JsonPropertyName("dfid")] + public string? Dfid { get; init; } + + /// + /// Gets the differing origin. + /// + [JsonPropertyName("differingOrigin")] + public StopPlaceRefContract? DifferingOrigin { get; init; } + + /// + /// Gets the DTID. + /// + [JsonPropertyName("dtid")] + public string? Dtid { get; init; } + + /// + /// Gets the journey description. + /// + [JsonPropertyName("journeyDescription")] + public string JourneyDescription { get; init; } = string.Empty; + + /// + /// Gets the journey identifier. + /// + [JsonPropertyName("journeyID")] + public string JourneyId { get; init; } = string.Empty; + + /// + /// Gets the journey number. + /// + [JsonPropertyName("journeyNumber")] + public int JourneyNumber { get; init; } + + /// + /// Gets the label. + /// + [JsonPropertyName("label")] + public string? Label { get; init; } + + /// + /// Gets the line. + /// + [JsonPropertyName("line")] + public LineInfoContract? Line { get; init; } + + /// + /// Gets the operational journey number. + /// + [JsonPropertyName("operationalJourneyNumber")] + public string OperationalJourneyNumber { get; init; } = string.Empty; + + /// + /// Gets the origin. + /// + [JsonPropertyName("origin")] + public StopPlaceRefWithCancelContract Origin { get; init; } = new(); + + /// + /// Gets the type. + /// + [JsonPropertyName("type")] + public string Type { get; init; } = string.Empty; +} diff --git a/source/DotBahn.Boards/Internal/Contracts/TransportWithDirectionAndViaContract.cs b/source/DotBahn.Boards/Internal/Contracts/TransportWithDirectionAndViaContract.cs new file mode 100644 index 0000000..52f3e0f --- /dev/null +++ b/source/DotBahn.Boards/Internal/Contracts/TransportWithDirectionAndViaContract.cs @@ -0,0 +1,94 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; + +namespace DotBahn.Boards.Internal.Contracts; + +/// +/// Raw structure for a transport with direction and via stops. +/// +[ExcludeFromCodeCoverage] +internal record TransportWithDirectionAndViaContract { + /// + /// Gets the administration identifier. + /// + [JsonPropertyName("administrationId")] + public string AdministrationId { get; init; } = string.Empty; + + /// + /// Gets the category. + /// + [JsonPropertyName("category")] + public string Category { get; init; } = string.Empty; + + /// + /// Gets the internal category. + /// + [JsonPropertyName("categoryInternal")] + public string CategoryInternal { get; init; } = string.Empty; + + /// + /// Gets the DFID. + /// + [JsonPropertyName("dfid")] + public string? Dfid { get; init; } + + /// + /// Gets the direction. + /// + [JsonPropertyName("direction")] + public DirectionInfoContract? Direction { get; init; } + + /// + /// Gets the DTID. + /// + [JsonPropertyName("dtid")] + public string? Dtid { get; init; } + + /// + /// Gets the journey description. + /// + [JsonPropertyName("journeyDescription")] + public string JourneyDescription { get; init; } = string.Empty; + + /// + /// Gets the journey number. + /// + [JsonPropertyName("journeyNumber")] + public int JourneyNumber { get; init; } + + /// + /// Gets the label. + /// + [JsonPropertyName("label")] + public string? Label { get; init; } + + /// + /// Gets the line. + /// + [JsonPropertyName("line")] + public LineInfoContract? Line { get; init; } + + /// + /// Gets the operational journey number. + /// + [JsonPropertyName("operationalJourneyNumber")] + public string OperationalJourneyNumber { get; init; } = string.Empty; + + /// + /// Gets the replacement transport. + /// + [JsonPropertyName("replacementTransport")] + public ReplacementTransportContract? ReplacementTransport { get; init; } + + /// + /// Gets the type. + /// + [JsonPropertyName("type")] + public string Type { get; init; } = string.Empty; + + /// + /// Gets the via stops. + /// + [JsonPropertyName("via")] + public List? Via { get; init; } +} diff --git a/source/DotBahn.Boards/Internal/Json/BoardsJsonContext.cs b/source/DotBahn.Boards/Internal/Json/BoardsJsonContext.cs new file mode 100644 index 0000000..5118449 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Json/BoardsJsonContext.cs @@ -0,0 +1,62 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using DotBahn.Boards.Internal.Contracts; + +namespace DotBahn.Boards.Internal.Json; + +/// +/// Source-generated JSON serialization metadata for OpenBoards internal contracts. +/// +[ExcludeFromCodeCoverage] +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] +[JsonSerializable(typeof(ArrivalBoardResponseContract))] +[JsonSerializable(typeof(DepartureBoardResponseContract))] +[JsonSerializable(typeof(AdministrationExtendedMultiLanguageContract))] +[JsonSerializable(typeof(ArrivalContract))] +[JsonSerializable(typeof(BoardMetaContract))] +[JsonSerializable(typeof(CodeShareContract))] +[JsonSerializable(typeof(DepartureContract))] +[JsonSerializable(typeof(DirectionInfoContract))] +[JsonSerializable(typeof(DisruptionCommunicationAttachmentContract))] +[JsonSerializable(typeof(DisruptionCommunicationImageContract))] +[JsonSerializable(typeof(DisruptionCommunicationLinkContract))] +[JsonSerializable(typeof(ErrorDetailContract))] +[JsonSerializable(typeof(ErrorResponseContract))] +[JsonSerializable(typeof(JourneyInfoContract))] +[JsonSerializable(typeof(LineChipVisualizationContract))] +[JsonSerializable(typeof(LineColourContract))] +[JsonSerializable(typeof(LineInfoContract))] +[JsonSerializable(typeof(LineStrokeVisualizationContract))] +[JsonSerializable(typeof(MessageAttributeDescriptionContract))] +[JsonSerializable(typeof(MessageAttributeMultiLanguageContract))] +[JsonSerializable(typeof(MessageDisruptionCommunicationDescriptionContract))] +[JsonSerializable(typeof(MessageDisruptionCommunicationMultiLanguageContract))] +[JsonSerializable(typeof(MessageNoteDescriptionContract))] +[JsonSerializable(typeof(MessageNoteMultiLanguageContract))] +[JsonSerializable(typeof(MessageRisCauseCodeDescriptionContract))] +[JsonSerializable(typeof(MessageRisCauseCodeMultiLanguageContract))] +[JsonSerializable(typeof(MessageRisQualityDeviationDescriptionContract))] +[JsonSerializable(typeof(MessageRisQualityDeviationMultiLanguageContract))] +[JsonSerializable(typeof(MessagesMultiLanguageContract))] +[JsonSerializable(typeof(OpenArrivalBoardRequestContract))] +[JsonSerializable(typeof(OpenDepartureBoardRequestContract))] +[JsonSerializable(typeof(PlatformAccessibilityContract))] +[JsonSerializable(typeof(PlatformContract))] +[JsonSerializable(typeof(PlatformHistoryContract))] +[JsonSerializable(typeof(ReplacementTransportContract))] +[JsonSerializable(typeof(StationMultiLanguageContract))] +[JsonSerializable(typeof(StationNameMultiLanguageContract))] +[JsonSerializable(typeof(StopPlaceMultiLanguageContract))] +[JsonSerializable(typeof(StopPlaceNameMultiLanguageContract))] +[JsonSerializable(typeof(StopPlaceOrStationRequestContract))] +[JsonSerializable(typeof(StopPlaceRefContract))] +[JsonSerializable(typeof(StopPlaceRefViaContract))] +[JsonSerializable(typeof(StopPlaceRefWithCancelContract))] +[JsonSerializable(typeof(TimeWindowContract))] +[JsonSerializable(typeof(TransportContract))] +[JsonSerializable(typeof(TransportCompanyMultiLanguageContract))] +[JsonSerializable(typeof(TransportDestinationPortionWorkingRefContract))] +[JsonSerializable(typeof(TransportDestinationRefContract))] +[JsonSerializable(typeof(TransportOriginRefContract))] +[JsonSerializable(typeof(TransportWithDirectionAndViaContract))] +internal sealed partial class BoardsJsonContext : JsonSerializerContext; diff --git a/source/DotBahn.Boards/Internal/Transformers/ArrivalBoardTransformer.cs b/source/DotBahn.Boards/Internal/Transformers/ArrivalBoardTransformer.cs new file mode 100644 index 0000000..b87859b --- /dev/null +++ b/source/DotBahn.Boards/Internal/Transformers/ArrivalBoardTransformer.cs @@ -0,0 +1,40 @@ +using DotBahn.Boards.Internal.Contracts; +using DotBahn.Boards.Models; +using DotBahn.Boards.Models.Entries; +using DotBahn.Common.Transformer; + +namespace DotBahn.Boards.Internal.Transformers; + +/// +/// Transforms an arrival-board contract into the public domain model. +/// +internal sealed class ArrivalBoardTransformer : TransformerBase, ITransformer, ArrivalBoardResponseContract> { + /// + public Board Transform(ArrivalBoardResponseContract contract) { + ArgumentNullException.ThrowIfNull(contract); + return TransformBoard(contract.StopPlaces ?? [], contract.Stations ?? [], contract.Administrations ?? [], contract.Messages, contract.Meta, contract.DisruptionCommunications ?? [], contract.Arrivals ?? [], TransformArrival); + } + + private static ArrivalEntry TransformArrival(ArrivalContract contract, TransformContext ctx) => new() { + Id = contract.ArrivalId, + StopPlace = ResolveStopPlace(contract.EvaNumber, ctx) ?? new StopPlace { EvaNumber = contract.EvaNumber, Name = contract.EvaNumber }, + Journey = TransformJourneyInfo(contract.JourneyId, contract.JourneyInfo, ctx), + Time = BuildTimeChanged(contract.TimeSchedule, contract.Time, contract.TimeType), + Platform = BuildPlatformChanged(contract.PlatformSchedule, contract.Platform), + Transport = TransformTransport(contract.Transport, ctx), + Messages = ResolveMessages(contract.Messages, ctx.Messages).ToList(), + Cancelled = contract.Cancelled, + Additional = contract.Additional, + OnDemand = contract.OnDemand, + NoPassengerChange = contract.NoPassengerChange, + VehicleSequenceAvailable = contract.VehicleSequenceAvailable ?? false, + Codeshares = TransformCodeshares(contract.Codeshares), + ContinuationBy = (contract.ContinuationBy ?? []).Select(c => TransformTransportReference(c, ctx)).ToList(), + ReliefBy = (contract.ReliefBy ?? []).Select(c => TransformTransportReference(c, ctx)).ToList(), + ReliefFor = (contract.ReliefFor ?? []).Select(c => TransformTransportReference(c, ctx)).ToList(), + ReplacedBy = (contract.ReplacedBy ?? []).Select(c => TransformTransportReference(c, ctx)).ToList(), + ReplacementFor = (contract.ReplacementFor ?? []).Select(c => TransformTransportReference(c, ctx)).ToList(), + TravelsWith = (contract.TravelsWith ?? []).Select(c => TransformTransportReference(c, ctx)).ToList(), + PastDisruptions = contract.PastDisruptions ?? false + }; +} diff --git a/source/DotBahn.Boards/Internal/Transformers/DepartureBoardTransformer.cs b/source/DotBahn.Boards/Internal/Transformers/DepartureBoardTransformer.cs new file mode 100644 index 0000000..e0d705c --- /dev/null +++ b/source/DotBahn.Boards/Internal/Transformers/DepartureBoardTransformer.cs @@ -0,0 +1,40 @@ +using DotBahn.Boards.Internal.Contracts; +using DotBahn.Boards.Models; +using DotBahn.Boards.Models.Entries; +using DotBahn.Common.Transformer; + +namespace DotBahn.Boards.Internal.Transformers; + +/// +/// Transforms a departure-board contract into the public domain model. +/// +internal sealed class DepartureBoardTransformer : TransformerBase, ITransformer, DepartureBoardResponseContract> { + /// + public Board Transform(DepartureBoardResponseContract contract) { + ArgumentNullException.ThrowIfNull(contract); + return TransformBoard(contract.StopPlaces ?? [], contract.Stations ?? [], contract.Administrations ?? [], contract.Messages, contract.Meta, contract.DisruptionCommunications ?? [], contract.Departures ?? [], TransformDeparture); + } + + private static DepartureEntry TransformDeparture(DepartureContract contract, TransformContext ctx) => new() { + Id = contract.DepartureId, + StopPlace = ResolveStopPlace(contract.EvaNumber, ctx) ?? new StopPlace { EvaNumber = contract.EvaNumber, Name = contract.EvaNumber }, + Journey = TransformJourneyInfo(contract.JourneyId, contract.JourneyInfo, ctx), + Time = BuildTimeChanged(contract.TimeSchedule, contract.Time, contract.TimeType), + Platform = BuildPlatformChanged(contract.PlatformSchedule, contract.Platform), + Transport = TransformTransport(contract.Transport, ctx), + Messages = ResolveMessages(contract.Messages, ctx.Messages).ToList(), + Cancelled = contract.Cancelled, + Additional = contract.Additional, + OnDemand = contract.OnDemand, + NoPassengerChange = contract.NoPassengerChange, + VehicleSequenceAvailable = contract.VehicleSequenceAvailable ?? false, + Codeshares = TransformCodeshares(contract.Codeshares), + ContinuationFor = (contract.ContinuationFor ?? []).Select(c => TransformTransportReference(c, ctx)).ToList(), + ReliefBy = (contract.ReliefBy ?? []).Select(c => TransformTransportReference(c, ctx)).ToList(), + ReliefFor = (contract.ReliefFor ?? []).Select(c => TransformTransportReference(c, ctx)).ToList(), + ReplacedBy = (contract.ReplacedBy ?? []).Select(c => TransformTransportReference(c, ctx)).ToList(), + ReplacementFor = (contract.ReplacementFor ?? []).Select(c => TransformTransportReference(c, ctx)).ToList(), + TravelsWith = (contract.TravelsWith ?? []).Select(c => TransformTransportReference(c, ctx)).ToList(), + FutureDisruptions = contract.FutureDisruptions ?? false + }; +} diff --git a/source/DotBahn.Boards/Internal/Transformers/TransformerBase.cs b/source/DotBahn.Boards/Internal/Transformers/TransformerBase.cs new file mode 100644 index 0000000..9e3086f --- /dev/null +++ b/source/DotBahn.Boards/Internal/Transformers/TransformerBase.cs @@ -0,0 +1,384 @@ +using System.Globalization; +using DotBahn.Boards.Internal.Contracts; +using DotBahn.Boards.Models; +using DotBahn.Boards.Models.Entries; +using DotBahn.Boards.Models.Journeys; +using DotBahn.Boards.Models.Messages; +using DotBahn.Boards.Models.Operators; +using DotBahn.Common.Models; + +namespace DotBahn.Boards.Internal.Transformers; + +/// +/// Shared transformation helpers for arrival and departure boards. +/// +internal abstract class TransformerBase { + private const string GermanLanguageCode = "deu"; + private const string EnglishLanguageCode = "eng"; + + /// + /// Lookup context shared by all board transformations. + /// + protected record TransformContext(IReadOnlyDictionary StopPlaces, IReadOnlyDictionary Administrations, IReadOnlyDictionary Messages); + + /// + /// Transforms the shared board structure into the public domain model. + /// + protected static Board TransformBoard(IEnumerable stopPlaceContracts, IEnumerable stationContracts, IEnumerable administrationContracts, MessagesMultiLanguageContract? messagesContract, BoardMetaContract meta, IEnumerable disruptionCommunications, IEnumerable entries, Func transformEntry) where TEntry : BoardEntry { + var ctx = BuildContext(stopPlaceContracts, stationContracts, administrationContracts, messagesContract); + + return new Board { + ConsideredStopPlaces = (meta.ConsideredStopPlaces ?? []) + .Select(eva => ctx.StopPlaces.GetValueOrDefault(eva)) + .Where(s => s != null) + .Cast() + .ToList(), + TruncatedTransportTypes = meta.TruncatedTransportTypes ?? [], + Entries = entries.Select(e => transformEntry(e, ctx)).ToList(), + StationMessages = ResolveMessages(disruptionCommunications, ctx.Messages).ToList() + }; + } + + + /// + /// Builds a from scheduled and best-known time strings. + /// + protected static ChangedValue BuildTimeChanged(string timeSchedule, string time, string timeType) { + var scheduled = ParseTime(timeSchedule); + var actual = ParseTime(time); + var hasUpdate = timeType is "PREVIEW" or "REAL" || actual != scheduled; + + return new ChangedValue { + Original = scheduled, + Updated = hasUpdate ? actual : null + }; + } + + /// + /// Builds a from scheduled and current platform contracts. + /// + protected static ChangedRef BuildPlatformChanged(PlatformContract? platformSchedule, PlatformContract? platform) { + var scheduled = platformSchedule != null ? TransformPlatform(platformSchedule) : platform != null ? TransformPlatform(platform) : new Platform { Name = string.Empty }; + var actual = platform != null && platform.Name != scheduled.Name ? TransformPlatform(platform) : null; + + return new ChangedRef { + Original = scheduled, + Updated = actual + }; + } + + protected static Journey TransformJourneyInfo(string journeyId, JourneyInfoContract contract, TransformContext ctx) => new() { + Id = journeyId, + Origin = ResolveVisit(contract.Origin, ctx), + Destination = ResolveVisit(contract.Destination, ctx), + DifferingOrigin = ResolveStopPlace(contract.DifferingOrigin?.EvaNumber, ctx), + DifferingDestination = ResolveStopPlace(contract.DifferingDestination?.EvaNumber, ctx), + ScheduledStartTime = ParseTime(contract.ScheduledStartTime), + TransportAtStart = TransformTransport(contract.TransportAtStart, ctx), + IsCancelled = contract.JourneyCancelled, + Type = contract.Type, + HeaderAdministration = ctx.Administrations.GetValueOrDefault(contract.HeaderAdministrationId), + HeaderJourneyNumber = contract.HeaderJourneyNumber + }; + + protected static Transport TransformTransport(TransportWithDirectionAndViaContract contract, TransformContext ctx) => + CreateTransport( + contract, + contract.Direction?.Texts ?? [], + contract.Direction != null ? (contract.Direction.StopPlaces ?? []).Select(r => ResolveStopPlace(r.EvaNumber, ctx)).Where(s => s != null).Cast().ToList() : [], + (contract.Via ?? []).Select(v => ResolveVisit(v, ctx)).ToList(), + contract.ReplacementTransport?.RealType, + ctx); + + protected static IReadOnlyDictionary TransformCodeshares(IEnumerable? contracts) => + (contracts ?? []).ToDictionary(c => c.AirlineCode, c => c.Flightnumber); + + protected static TransportReference TransformTransportReference(TransportDestinationRefContract contract, TransformContext ctx) => + CreateTransportReference(contract, ctx, + destination: ResolveVisit(contract.Destination, ctx), + differingDestination: ResolveStopPlace(contract.DifferingDestination?.EvaNumber, ctx)); + + protected static TransportReference TransformTransportReference(TransportOriginRefContract contract, TransformContext ctx) => + CreateTransportReference(contract, ctx, + origin: ResolveVisit(contract.Origin, ctx), + differingOrigin: ResolveStopPlace(contract.DifferingOrigin?.EvaNumber, ctx)); + + protected static TransportReference TransformTransportReference(TransportDestinationPortionWorkingRefContract contract, TransformContext ctx) => + CreateTransportReference(contract, ctx, + destination: ResolveVisit(contract.Destination, ctx), + differingDestination: ResolveStopPlace(contract.DifferingDestination?.EvaNumber, ctx), + separationAt: ResolveStopPlace(contract.SeparationAt?.EvaNumber, ctx)); + + /// + /// Resolves a list of message IDs to messages. + /// + protected static IReadOnlyList ResolveMessages(IEnumerable? messageIds, IReadOnlyDictionary lookup) => + (messageIds ?? []).Select(lookup.GetValueOrDefault) + .Where(m => m != null) + .Cast() + .ToList(); + + protected static StopPlace? ResolveStopPlace(string? evaNumber, TransformContext ctx) => + !string.IsNullOrEmpty(evaNumber) && ctx.StopPlaces.TryGetValue(evaNumber, out var stopPlace) ? stopPlace : null; + + + /// + /// Builds the shared lookup context for all board transformations. + /// + private static TransformContext BuildContext(IEnumerable stopPlaceContracts, IEnumerable stationContracts, IEnumerable administrationContracts, MessagesMultiLanguageContract? messagesContract) { + var stationNames = stationContracts.ToDictionary(s => s.Stada, c => SelectLocalized(c.LocalizedNames, n => n.Language, n => n.Name).Value); + var stopPlaces = stopPlaceContracts.ToDictionary(s => s.EvaNumber, c => TransformStopPlace(c, stationNames)); + + return new TransformContext(stopPlaces, administrationContracts.ToDictionary(a => a.AdministrationId, TransformAdministration), BuildMessageLookup(messagesContract)); + } + + /// + /// Builds a message lookup dictionary from all message collections. + /// + private static IReadOnlyDictionary BuildMessageLookup(MessagesMultiLanguageContract? messages) { + if (messages == null) { + return new Dictionary(); + } + + var lookup = new Dictionary(); + + foreach (var attribute in messages.Attributes ?? []) { + lookup[attribute.MessageId] = TransformMessageAttribute(attribute); + } + + foreach (var disruption in messages.Disruptions ?? []) { + lookup[disruption.MessageId] = TransformMessageDisruption(disruption); + } + + foreach (var note in messages.Notes ?? []) { + lookup[note.MessageId] = TransformMessageNote(note); + } + + foreach (var cause in messages.RisCauseCodes ?? []) { + lookup[cause.MessageId] = TransformMessageRisCauseCode(cause); + } + + foreach (var deviation in messages.RisQualityDeviations ?? []) { + lookup[deviation.MessageId] = TransformMessageRisQualityDeviation(deviation); + } + + return lookup; + } + + private static StopPlace ResolveStopPlaceOrDefault(string evaNumber, TransformContext ctx) => + ResolveStopPlace(evaNumber, ctx) ?? new StopPlace { EvaNumber = evaNumber, Name = evaNumber }; + + private static Visit ResolveVisit(StopPlaceRefWithCancelContract reference, TransformContext ctx) => new() { + StopPlace = ResolveStopPlaceOrDefault(reference.EvaNumber, ctx), + Cancelled = reference.Cancelled + }; + + private static Visit ResolveVisit(StopPlaceRefViaContract reference, TransformContext ctx) => new() { + StopPlace = ResolveStopPlaceOrDefault(reference.EvaNumber, ctx), + Additional = reference.Additional, + Cancelled = reference.Cancelled, + DisplayPriority = reference.DisplayPriority + }; + + private static DateTime ParseTime(string value) => DateTime.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); + + private static StopPlace TransformStopPlace(StopPlaceMultiLanguageContract contract, IReadOnlyDictionary stationNames) { + var localized = SelectLocalized(contract.LocalizedNames, n => n.Language, n => (n.Name, n.Symbol, n.SymbolName)); + return new StopPlace { + EvaNumber = contract.EvaNumber, + Name = localized.Value.Name, + Symbol = localized.Value.Symbol, + SymbolName = localized.Value.SymbolName, + Dhid = contract.Ifopt, + StadaId = contract.Stada, + StationName = !string.IsNullOrEmpty(contract.Stada) && stationNames.TryGetValue(contract.Stada, out var name) ? name : null + }; + } + + private static Administration TransformAdministration(AdministrationExtendedMultiLanguageContract contract) => new() { + Id = contract.AdministrationId, + OperatorCode = contract.OperatorCode, + OperatorName = contract.OperatorName, + TransportCompanies = (contract.TransportCompanies ?? []).Select(TransformTransportCompany).ToList() + }; + + private static TransportCompany TransformTransportCompany(TransportCompanyMultiLanguageContract contract) => new() { + Language = contract.Language, + Name = contract.Name, + ShortName = contract.ShortName, + Email = contract.Email, + PhoneNumber = contract.PhoneNumber, + Website = contract.Website, + WebsiteTicketing = contract.WebsiteTicketing, + WebsiteDigitalAssistant = contract.WebsiteDigitalAssistant + }; + + private static Platform TransformPlatform(PlatformContract contract) => new() { + Name = contract.Name, + Ifopt = contract.Ifopt, + StepFreeAccess = contract.Accessibility?.StepFreeAccess ?? false, + BoardingAid = contract.Accessibility?.BoardingAid ?? false, + TactileGuidingStrips = contract.Accessibility?.TactileGuidingStrips ?? false, + TactileHandrailLabel = contract.Accessibility?.TactileHandrailLabel ?? false, + TactilePlatformAccess = contract.Accessibility?.TactilePlatformAccess ?? false, + AudibleSignalsAvailable = contract.Accessibility?.AudibleSignalsAvailable ?? false, + AutomaticDoor = contract.Accessibility?.AutomaticDoor ?? false, + PassengerInformationDisplay = contract.Accessibility?.PassengerInformationDisplay ?? false, + PlatformSign = contract.Accessibility?.PlatformSign ?? false, + StairsMarking = contract.Accessibility?.StairsMarking ?? false, + StandardPlatformHeight = contract.Accessibility?.StandardPlatformHeight ?? false + }; + + private static Line TransformLine(LineInfoContract contract) => new() { + Name = contract.Name, + PrimaryColour = contract.Colour?.PrimaryColour, + PrimaryTextColour = contract.Colour?.PrimaryTextColour, + ChipDifferingBoundaryColour = contract.Colour?.ChipVisualization?.DifferingBoundaryColour, + ChipDifferingFillColour = contract.Colour?.ChipVisualization?.DifferingFillColour, + ChipDifferingTextColour = contract.Colour?.ChipVisualization?.DifferingTextColour, + ChipSecondaryFillColour = contract.Colour?.ChipVisualization?.SecondaryFillColour, + StrokeDifferingBoundaryColour = contract.Colour?.StrokeVisualization?.DifferingBoundaryColour, + StrokeSecondaryFillColour = contract.Colour?.StrokeVisualization?.SecondaryFillColour + }; + + + private static Transport TransformTransport(TransportContract contract, TransformContext ctx) => + CreateTransport(contract, [], [], [], null, ctx); + + private static Transport CreateTransport( + string administrationId, string category, string categoryInternal, string type, + int journeyNumber, string operationalNumber, string description, string? label, + LineInfoContract? line, string? dfid, string? dtid, + IReadOnlyList direction, IReadOnlyList directionStopPlaces, + IReadOnlyList via, string? replacementTransport, TransformContext ctx) => new() { + Category = category, + InternalCategory = categoryInternal, + Type = type, + Number = journeyNumber.ToString(CultureInfo.InvariantCulture), + OperationalNumber = operationalNumber, + Description = description, + Label = label, + Line = line != null ? TransformLine(line) : null, + Dfid = dfid, + Dtid = dtid, + Direction = direction, + DirectionStopPlaces = directionStopPlaces, + Via = via, + ReplacementTransport = replacementTransport, + Administration = ctx.Administrations.GetValueOrDefault(administrationId) ?? new Administration { + Id = administrationId, + OperatorCode = string.Empty, + OperatorName = string.Empty + } + }; + + private static Transport CreateTransport(TransportWithDirectionAndViaContract c, IReadOnlyList direction, IReadOnlyList directionStopPlaces, IReadOnlyList via, string? replacementTransport, TransformContext ctx) => + CreateTransport(c.AdministrationId, c.Category, c.CategoryInternal, c.Type, c.JourneyNumber, c.OperationalJourneyNumber, c.JourneyDescription, c.Label, c.Line, c.Dfid, c.Dtid, direction, directionStopPlaces, via, replacementTransport, ctx); + + private static Transport CreateTransport(TransportContract c, IReadOnlyList direction, IReadOnlyList directionStopPlaces, IReadOnlyList via, string? replacementTransport, TransformContext ctx) => + CreateTransport(c.AdministrationId, c.Category, c.CategoryInternal, c.Type, c.JourneyNumber, c.OperationalJourneyNumber, c.JourneyDescription, c.Label, c.Line, c.Dfid, c.Dtid, direction, directionStopPlaces, via, replacementTransport, ctx); + + private static TransportReference CreateTransportReference( + string administrationId, string category, string categoryInternal, string type, + string journeyId, int journeyNumber, string operationalNumber, string description, + string? label, LineInfoContract? line, string? dfid, string? dtid, TransformContext ctx, + Visit? origin = null, Visit? destination = null, + StopPlace? differingOrigin = null, StopPlace? differingDestination = null, StopPlace? separationAt = null) => new() { + JourneyId = journeyId, + Category = category, + InternalCategory = categoryInternal, + Type = type, + Number = journeyNumber.ToString(CultureInfo.InvariantCulture), + OperationalNumber = operationalNumber, + Description = description, + Label = label, + Line = line != null ? TransformLine(line) : null, + Dfid = dfid, + Dtid = dtid, + Administration = ctx.Administrations.GetValueOrDefault(administrationId), + Origin = origin, + Destination = destination, + DifferingOrigin = differingOrigin, + DifferingDestination = differingDestination, + SeparationAt = separationAt + }; + + private static TransportReference CreateTransportReference(TransportDestinationRefContract c, TransformContext ctx, Visit? destination, StopPlace? differingDestination) => + CreateTransportReference(c.AdministrationId, c.Category, c.CategoryInternal, c.Type, c.JourneyId, c.JourneyNumber, c.OperationalJourneyNumber, c.JourneyDescription, c.Label, c.Line, c.Dfid, c.Dtid, ctx, destination: destination, differingDestination: differingDestination); + + private static TransportReference CreateTransportReference(TransportOriginRefContract c, TransformContext ctx, Visit? origin, StopPlace? differingOrigin) => + CreateTransportReference(c.AdministrationId, c.Category, c.CategoryInternal, c.Type, c.JourneyId, c.JourneyNumber, c.OperationalJourneyNumber, c.JourneyDescription, c.Label, c.Line, c.Dfid, c.Dtid, ctx, origin: origin, differingOrigin: differingOrigin); + + private static TransportReference CreateTransportReference(TransportDestinationPortionWorkingRefContract c, TransformContext ctx, Visit? destination, StopPlace? differingDestination, StopPlace? separationAt) => + CreateTransportReference(c.AdministrationId, c.Category, c.CategoryInternal, c.Type, c.JourneyId, c.JourneyNumber, c.OperationalJourneyNumber, c.JourneyDescription, c.Label, c.Line, c.Dfid, c.Dtid, ctx, destination: destination, differingDestination: differingDestination, separationAt: separationAt); + + private static Message TransformMessageAttribute(MessageAttributeMultiLanguageContract contract) => new() { + Type = MessageType.Attribute, + Text = SelectLocalized(contract.Descriptions, d => d.Language, d => d.Text).Value, + Code = contract.Code, + Priority = contract.DisplayPriority, + DetailedPriority = contract.DisplayPriorityDetail + }; + + private static Message TransformMessageDisruption(MessageDisruptionCommunicationMultiLanguageContract contract) { + var localized = SelectLocalized(contract.Descriptions, d => d.Language, d => d.Text); + return new Message { + Type = MessageType.Disruption, + Text = localized.Value, + ShortText = localized.Item?.TextShort, + Cause = contract.Cause, + Effect = contract.Effect, + Priority = contract.DisplayPriority, + DisruptionId = contract.DisruptionId, + DisruptionCommunicationId = contract.DisruptionCommunicationId, + HasAlternatives = contract.HasAlternatives ?? false, + Resources = BuildMessageResources(localized.Item?.Links, localized.Item?.Attachments, localized.Item?.Images) + }; + } + + private static Message TransformMessageNote(MessageNoteMultiLanguageContract contract) { + var localized = SelectLocalized(contract.Descriptions, d => d.Language, d => d.Text); + return new Message { + Type = MessageType.Note, + Text = localized.Value, + ShortText = localized.Item?.TextShort, + Category = contract.Category, + Code = contract.Code, + Priority = contract.DisplayPriority, + DisruptionId = contract.DisruptionId, + DisruptionCommunicationId = contract.DisruptionCommunicationId, + Resources = BuildMessageResources(localized.Item?.Links, localized.Item?.Attachments, localized.Item?.Images) + }; + } + + private static Message TransformMessageRisCauseCode(MessageRisCauseCodeMultiLanguageContract contract) => new() { + Type = MessageType.RisCauseCode, + Text = SelectLocalized(contract.Descriptions, d => d.Language, d => d.Text).Value, + Code = contract.Code + }; + + private static Message TransformMessageRisQualityDeviation(MessageRisQualityDeviationMultiLanguageContract contract) => new() { + Type = MessageType.RisQualityDeviation, + Text = SelectLocalized(contract.Descriptions, d => d.Language, d => d.Text).Value, + Code = contract.Code + }; + + private static IReadOnlyList BuildMessageResources(IEnumerable? links, IEnumerable? attachments, IEnumerable? images) => + (links ?? []).Select(c => CreateMessageResource(c.Label, c.Url, MessageResourceType.Link)) + .Concat((attachments ?? []).Select(c => CreateMessageResource(c.Label, c.Url, MessageResourceType.Attachment))) + .Concat((images ?? []).Select(c => CreateMessageResource(c.Label, c.Url, MessageResourceType.Image))) + .ToList(); + + private static MessageResource CreateMessageResource(string label, string url, MessageResourceType type) => new() { + Type = type, + Label = label, + Url = url + }; + + private static (T Item, TValue Value) SelectLocalized(IEnumerable? items, Func languageSelector, Func valueSelector) { + var list = items?.ToList() ?? []; + var selected = list.FirstOrDefault(x => languageSelector(x).Equals(GermanLanguageCode, StringComparison.OrdinalIgnoreCase)) ?? list.FirstOrDefault(x => languageSelector(x).Equals(EnglishLanguageCode, StringComparison.OrdinalIgnoreCase)) ?? list.FirstOrDefault(); + + return selected == null ? (default!, default!) : (selected, valueSelector(selected)); + } +} diff --git a/source/DotBahn.Boards/Internal/Utilities/QueryUtil.cs b/source/DotBahn.Boards/Internal/Utilities/QueryUtil.cs new file mode 100644 index 0000000..13d7a93 --- /dev/null +++ b/source/DotBahn.Boards/Internal/Utilities/QueryUtil.cs @@ -0,0 +1,78 @@ +using System.Globalization; +using System.Runtime.CompilerServices; +using DotBahn.Boards.Internal.Contracts; + +namespace DotBahn.Boards.Internal.Utilities; + +/// +/// Maps public board queries to internal OpenBoards request contracts. +/// +internal static class QueryUtil { + /// + /// Maps a to the internal arrival request contract. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static OpenArrivalBoardRequestContract ToArrivalContract(BoardQuery query) => new() { + StopPlaceOrStation = MapStopPlaceOrStation(query), + TimeWindow = MapTimeWindow(query), + TransportTypes = query.TransportTypes.Count > 0 ? [.. query.TransportTypes] : null, + Languages = query.Languages.Count > 0 ? [.. query.Languages] : null, + MaxEntriesPerTransportType = query.MaxEntriesPerTransportType, + MaxViaStops = query.MaxViaStops ?? 3, + NoCancellations = query.NoCancellations, + OnlyReplacementTransports = query.OnlyReplacementTransports, + SortBy = query.SortBy, + IncludeLineColours = query.IncludeLineColours, + IncludePlatformAccessibility = query.IncludePlatformAccessibility + }; + + /// + /// Maps a to the internal departure request contract. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static OpenDepartureBoardRequestContract ToDepartureContract(BoardQuery query) => new() { + StopPlaceOrStation = MapStopPlaceOrStation(query), + TimeWindow = MapTimeWindow(query), + TransportTypes = query.TransportTypes.Count > 0 ? [.. query.TransportTypes] : null, + Languages = query.Languages.Count > 0 ? [.. query.Languages] : null, + MaxEntriesPerTransportType = query.MaxEntriesPerTransportType, + MaxViaStops = query.MaxViaStops ?? 3, + NoCancellations = query.NoCancellations, + OnlyReplacementTransports = query.OnlyReplacementTransports, + SortBy = query.SortBy, + IncludeLineColours = query.IncludeLineColours, + IncludePlatformAccessibility = query.IncludePlatformAccessibility + }; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static StopPlaceOrStationRequestContract MapStopPlaceOrStation(BoardQuery query) => new() { + EvaNumbers = query.EvaNumbers is { Count: > 0 } ? [.. query.EvaNumbers] : null, + Stada = query.StadaId, + Dhids = query.Dhids is { Count: > 0 } ? [.. query.Dhids] : null, + Platforms = query.Platforms is { Count: > 0 } ? [.. query.Platforms] : null, + BoardConfigurations = query.BoardConfigurations is { Count: > 0 } ? [.. query.BoardConfigurations] : null + }; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static TimeWindowContract? MapTimeWindow(BoardQuery query) { + var start = query.Start; + var end = query.End; + var count = query.EntryCount; + + if (!start.HasValue && !end.HasValue && !count.HasValue) { + return null; + } + + return new TimeWindowContract { + TimeStart = start.HasValue ? FormatDateTime(start.Value) : null, + TimeEnd = end.HasValue ? FormatDateTime(end.Value) : null, + EntryCount = count + }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static string FormatDateTime(DateTime value) { + var utc = value.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(value, DateTimeKind.Utc) : value.ToUniversalTime(); + return utc.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); + } +} diff --git a/source/DotBahn.Boards/Models/Board.cs b/source/DotBahn.Boards/Models/Board.cs new file mode 100644 index 0000000..69681bd --- /dev/null +++ b/source/DotBahn.Boards/Models/Board.cs @@ -0,0 +1,31 @@ + +using DotBahn.Boards.Models.Entries; +using DotBahn.Boards.Models.Messages; + +namespace DotBahn.Boards.Models; + +/// +/// A board of arrival or departure events for one or more stop places. +/// +/// The type of board entry. +public class Board where TEntry : BoardEntry { + /// + /// Stop places the board was created for. + /// + public IReadOnlyList ConsideredStopPlaces { get; init; } = []; + + /// + /// Entries matching the query. + /// + public IReadOnlyList Entries { get; init; } = []; + + /// + /// Station-level disruption messages. + /// + public IReadOnlyList StationMessages { get; init; } = []; + + /// + /// Transport types whose results were truncated to the configured maximum per transport type. + /// + public IReadOnlyList TruncatedTransportTypes { get; init; } = []; +} diff --git a/source/DotBahn.Boards/Models/Entries/ArrivalEntry.cs b/source/DotBahn.Boards/Models/Entries/ArrivalEntry.cs new file mode 100644 index 0000000..170ac8b --- /dev/null +++ b/source/DotBahn.Boards/Models/Entries/ArrivalEntry.cs @@ -0,0 +1,18 @@ +using DotBahn.Boards.Models.Journeys; + +namespace DotBahn.Boards.Models.Entries; + +/// +/// An arrival event at a stop place. +/// +public sealed class ArrivalEntry : BoardEntry { + /// + /// Journeys this arrival continues as. + /// + public IReadOnlyList ContinuationBy { get; init; } = []; + + /// + /// Whether at least one disruption communication exists in the past of this journey. + /// + public bool PastDisruptions { get; init; } +} diff --git a/source/DotBahn.Boards/Models/Entries/BoardEntry.cs b/source/DotBahn.Boards/Models/Entries/BoardEntry.cs new file mode 100644 index 0000000..c39fbc8 --- /dev/null +++ b/source/DotBahn.Boards/Models/Entries/BoardEntry.cs @@ -0,0 +1,100 @@ +using DotBahn.Boards.Models.Journeys; +using DotBahn.Boards.Models.Messages; +using DotBahn.Common.Models; + +namespace DotBahn.Boards.Models.Entries; + +/// +/// Shared data for an arrival or departure event at a stop place. +/// +public abstract class BoardEntry { + /// + /// Identifier of the event within its journey. + /// + public required string Id { get; init; } + + /// + /// Stop place where the event occurs. + /// + public required StopPlace StopPlace { get; init; } + + /// + /// Journey information. + /// + public required Journey Journey { get; init; } + + /// + /// Scheduled and best-known event time. + /// + public required ChangedValue Time { get; init; } + + /// + /// Scheduled and current platform, including accessibility information. + /// + public required ChangedRef Platform { get; init; } + + /// + /// Transport information including direction and via stops. + /// + public required Transport Transport { get; init; } + + /// + /// Messages attached to this event. + /// + public IReadOnlyList Messages { get; init; } = []; + + /// + /// Whether the event has been canceled. + /// + public bool Cancelled { get; init; } + + /// + /// Whether the event is an additional stop. + /// + public bool Additional { get; init; } + + /// + /// Whether the event is an on-demand stop. + /// + public bool OnDemand { get; init; } + + /// + /// Whether passengers are not allowed to board or alight. + /// + public bool NoPassengerChange { get; init; } + + /// + /// Whether a vehicle sequence is available for this event. + /// + public bool VehicleSequenceAvailable { get; init; } + + /// + /// Airline codeshares for this event, keyed by IATA airline code with the flight number as value. + /// + public IReadOnlyDictionary Codeshares { get; init; } = new Dictionary(); + + /// + /// Journeys this event is relieved by. + /// + public IReadOnlyList ReliefBy { get; init; } = []; + + /// + /// Journeys this event reliefs. + /// + public IReadOnlyList ReliefFor { get; init; } = []; + + /// + /// Journeys this event is replaced by. + /// + public IReadOnlyList ReplacedBy { get; init; } = []; + + /// + /// Journeys this event replaces. + /// + public IReadOnlyList ReplacementFor { get; init; } = []; + + /// + /// Journeys this event travels with. + /// + public IReadOnlyList TravelsWith { get; init; } = []; +} diff --git a/source/DotBahn.Boards/Models/Entries/DepartureEntry.cs b/source/DotBahn.Boards/Models/Entries/DepartureEntry.cs new file mode 100644 index 0000000..521287a --- /dev/null +++ b/source/DotBahn.Boards/Models/Entries/DepartureEntry.cs @@ -0,0 +1,18 @@ +using DotBahn.Boards.Models.Journeys; + +namespace DotBahn.Boards.Models.Entries; + +/// +/// A departure event at a stop place. +/// +public sealed class DepartureEntry : BoardEntry { + /// + /// Journeys this departure continues for. + /// + public IReadOnlyList ContinuationFor { get; init; } = []; + + /// + /// Whether at least one disruption communication exists in the future of this journey. + /// + public bool FutureDisruptions { get; init; } +} diff --git a/source/DotBahn.Boards/Models/Journeys/Journey.cs b/source/DotBahn.Boards/Models/Journeys/Journey.cs new file mode 100644 index 0000000..ba20c7f --- /dev/null +++ b/source/DotBahn.Boards/Models/Journeys/Journey.cs @@ -0,0 +1,63 @@ +using DotBahn.Boards.Models.Operators; + +namespace DotBahn.Boards.Models.Journeys; + +/// +/// Journey-level information for a board entry. +/// +public class Journey { + /// + /// Identifier of the journey. + /// + public required string Id { get; init; } + + /// + /// Origin stop place, including cancellation state. + /// + public required Visit Origin { get; init; } + + /// + /// Destination stop place, including cancellation state. + /// + public required Visit Destination { get; init; } + + /// + /// Differing origin stop place, if the journey starts elsewhere. + /// + public StopPlace? DifferingOrigin { get; init; } + + /// + /// Differing destination stop place, if the journey ends elsewhere. + /// + public StopPlace? DifferingDestination { get; init; } + + /// + /// Scheduled start time at the origin. + /// + public required DateTime ScheduledStartTime { get; init; } + + /// + /// Transport information at the start of the journey. + /// + public required Transport TransportAtStart { get; init; } + + /// + /// Whether the entire journey has been canceled. + /// + public bool IsCancelled { get; init; } + + /// + /// Journey type, e.g. REGULAR, REPLACEMENT, RELIEF, EXTRA. + /// + public required string Type { get; init; } + + /// + /// Administration responsible for the journey header, if available. + /// + public Administration? HeaderAdministration { get; init; } + + /// + /// Journey number of the header, if available. + /// + public int? HeaderJourneyNumber { get; init; } +} diff --git a/source/DotBahn.Boards/Models/Journeys/Transport.cs b/source/DotBahn.Boards/Models/Journeys/Transport.cs new file mode 100644 index 0000000..5472caa --- /dev/null +++ b/source/DotBahn.Boards/Models/Journeys/Transport.cs @@ -0,0 +1,83 @@ +using DotBahn.Boards.Models.Operators; + +namespace DotBahn.Boards.Models.Journeys; + +/// +/// Transport information for a journey event. +/// +public class Transport { + /// + /// External transport category, e.g. ICE, RE, RB, S. + /// + public required string Category { get; init; } + + /// + /// Internal category before output control; not intended for customer display. + /// + public required string InternalCategory { get; init; } + + /// + /// Transport type, e.g. HIGH_SPEED_TRAIN, REGIONAL_TRAIN, CITY_TRAIN. + /// + public required string Type { get; init; } + + /// + /// Transport number. + /// + public required string Number { get; init; } + + /// + /// Operational journey number. + /// + public required string OperationalNumber { get; init; } + + /// + /// Customer-facing journey description. + /// + public string? Description { get; init; } + + /// + /// Marketing or product label, e.g. Sprinter. + /// + public string? Label { get; init; } + + /// + /// Deutschlandweite Fahrt ID. + /// + public string? Dfid { get; init; } + + /// + /// Deutschlandweite Teil-Linien ID. + /// + public string? Dtid { get; init; } + + /// + /// Line information. + /// + public Line? Line { get; init; } + + /// + /// Direction texts for the transport. + /// + public IReadOnlyList Direction { get; init; } = []; + + /// + /// Stop places along the direction of the transport. + /// + public IReadOnlyList DirectionStopPlaces { get; init; } = []; + + /// + /// Via stops for the transport, including visit-specific details. + /// + public IReadOnlyList Via { get; init; } = []; + + /// + /// Real type of the replacement transport, if this is a replacement service, e.g. BUS. + /// + public string? ReplacementTransport { get; init; } + + /// + /// Administration and operator of the transport. + /// + public required Administration Administration { get; init; } +} diff --git a/source/DotBahn.Boards/Models/Journeys/TransportReference.cs b/source/DotBahn.Boards/Models/Journeys/TransportReference.cs new file mode 100644 index 0000000..0b3fef7 --- /dev/null +++ b/source/DotBahn.Boards/Models/Journeys/TransportReference.cs @@ -0,0 +1,93 @@ +using DotBahn.Boards.Models.Operators; + +namespace DotBahn.Boards.Models.Journeys; + +/// +/// Reference to another transport, e.g. for continuation, relief, replacement. +/// +public class TransportReference { + /// + /// Identifier of the referenced journey. + /// + public required string JourneyId { get; init; } + + /// + /// Category of the referenced transport. + /// + public required string Category { get; init; } + + /// + /// Internal category of the referenced transport. + /// + public string? InternalCategory { get; init; } + + /// + /// Transport type of the referenced transport. + /// + public string? Type { get; init; } + + /// + /// Number of the referenced transport. + /// + public required string Number { get; init; } + + /// + /// Operational journey number of the referenced transport. + /// + public string? OperationalNumber { get; init; } + + /// + /// Customer-facing journey description. + /// + public string? Description { get; init; } + + /// + /// Marketing or product label. + /// + public string? Label { get; init; } + + /// + /// Line information. + /// + public Line? Line { get; init; } + + /// + /// Deutschlandweite Fahrt ID. + /// + public string? Dfid { get; init; } + + /// + /// Deutschlandweite Teil-Linien ID. + /// + public string? Dtid { get; init; } + + /// + /// Administration and operator of the referenced transport. + /// + public Administration? Administration { get; init; } + + /// + /// Origin of the referenced transport, if applicable. + /// + public Visit? Origin { get; init; } + + /// + /// Destination of the referenced transport, if applicable. + /// + public Visit? Destination { get; init; } + + /// + /// Differing origin stop place, if applicable. + /// + public StopPlace? DifferingOrigin { get; init; } + + /// + /// Differing destination stop place, if applicable. + /// + public StopPlace? DifferingDestination { get; init; } + + /// + /// Stop place where the working portion is separated, if applicable. + /// + public StopPlace? SeparationAt { get; init; } +} diff --git a/source/DotBahn.Boards/Models/Line.cs b/source/DotBahn.Boards/Models/Line.cs new file mode 100644 index 0000000..1e4ddf9 --- /dev/null +++ b/source/DotBahn.Boards/Models/Line.cs @@ -0,0 +1,51 @@ +namespace DotBahn.Boards.Models; + +/// +/// Line information for a transport, including color and visualization details. +/// +public class Line { + /// + /// Name of the line, e.g. RE14 or S1. + /// + public required string Name { get; init; } + + /// + /// Primary color as a HEX code with leading #. + /// + public string? PrimaryColour { get; init; } + + /// + /// Primary text color as a HEX code with leading #. + /// + public string? PrimaryTextColour { get; init; } + + /// + /// Differing boundary color of the chip visualization. + /// + public string? ChipDifferingBoundaryColour { get; init; } + + /// + /// Differing fill color of the chip visualization. + /// + public string? ChipDifferingFillColour { get; init; } + + /// + /// Differing text color of the chip visualization. + /// + public string? ChipDifferingTextColour { get; init; } + + /// + /// Secondary fill color of the chip visualization. + /// + public string? ChipSecondaryFillColour { get; init; } + + /// + /// Differing boundary color of the stroke visualization. + /// + public string? StrokeDifferingBoundaryColour { get; init; } + + /// + /// Secondary fill color of the stroke visualization. + /// + public string? StrokeSecondaryFillColour { get; init; } +} diff --git a/source/DotBahn.Boards/Models/Messages/Message.cs b/source/DotBahn.Boards/Models/Messages/Message.cs new file mode 100644 index 0000000..b3df2a1 --- /dev/null +++ b/source/DotBahn.Boards/Models/Messages/Message.cs @@ -0,0 +1,71 @@ +namespace DotBahn.Boards.Models.Messages; + +/// +/// A message attached to a board entry or station. +/// +public class Message { + /// + /// Message text. + /// + public required string Text { get; init; } + + /// + /// Type of the message. + /// + public required MessageType Type { get; init; } + + /// + /// Optional short message text. + /// + public string? ShortText { get; init; } + + /// + /// Optional category. + /// + public string? Category { get; init; } + + /// + /// Optional code. + /// + public string? Code { get; init; } + + /// + /// Display priority in ascending order. + /// + public int? Priority { get; init; } + + /// + /// Detailed display priority in ascending order. + /// + public int? DetailedPriority { get; init; } + + /// + /// Cause for disruption messages. + /// + public string? Cause { get; init; } + + /// + /// Effect of disruption messages. + /// + public string? Effect { get; init; } + + /// + /// Identifier of the associated disruption, if available. + /// + public string? DisruptionId { get; init; } + + /// + /// Identifier of the associated disruption communication, if available. + /// + public string? DisruptionCommunicationId { get; init; } + + /// + /// Whether alternative connections exist for this message. + /// + public bool HasAlternatives { get; init; } + + /// + /// Related resources such as links, attachments, and images. + /// + public IReadOnlyList Resources { get; init; } = []; +} diff --git a/source/DotBahn.Boards/Models/Messages/MessageResource.cs b/source/DotBahn.Boards/Models/Messages/MessageResource.cs new file mode 100644 index 0000000..5b29ef4 --- /dev/null +++ b/source/DotBahn.Boards/Models/Messages/MessageResource.cs @@ -0,0 +1,21 @@ +namespace DotBahn.Boards.Models.Messages; + +/// +/// A resource attached to a message, such as a link, attachment, or image. +/// +public class MessageResource { + /// + /// Type of the resource. + /// + public required MessageResourceType Type { get; init; } + + /// + /// Label for the resource. + /// + public required string Label { get; init; } + + /// + /// URL of the resource. + /// + public required string Url { get; init; } +} diff --git a/source/DotBahn.Boards/Models/Messages/MessageResourceType.cs b/source/DotBahn.Boards/Models/Messages/MessageResourceType.cs new file mode 100644 index 0000000..82097e9 --- /dev/null +++ b/source/DotBahn.Boards/Models/Messages/MessageResourceType.cs @@ -0,0 +1,21 @@ +namespace DotBahn.Boards.Models.Messages; + +/// +/// Type of resource attached to a message. +/// +public enum MessageResourceType { + /// + /// A hyperlink. + /// + Link, + + /// + /// An attachment. + /// + Attachment, + + /// + /// An image. + /// + Image +} diff --git a/source/DotBahn.Boards/Models/Messages/MessageType.cs b/source/DotBahn.Boards/Models/Messages/MessageType.cs new file mode 100644 index 0000000..41b3334 --- /dev/null +++ b/source/DotBahn.Boards/Models/Messages/MessageType.cs @@ -0,0 +1,31 @@ +namespace DotBahn.Boards.Models.Messages; + +/// +/// Type of board message. +/// +public enum MessageType { + /// + /// Journey attribute. + /// + Attribute, + + /// + /// Disruption communication. + /// + Disruption, + + /// + /// General note. + /// + Note, + + /// + /// RIS cause code. + /// + RisCauseCode, + + /// + /// RIS quality deviation. + /// + RisQualityDeviation +} diff --git a/source/DotBahn.Boards/Models/Operators/Administration.cs b/source/DotBahn.Boards/Models/Operators/Administration.cs new file mode 100644 index 0000000..7650ea0 --- /dev/null +++ b/source/DotBahn.Boards/Models/Operators/Administration.cs @@ -0,0 +1,26 @@ +namespace DotBahn.Boards.Models.Operators; + +/// +/// Administration and operator information for a transport. +/// +public class Administration { + /// + /// Identifier of the administration. + /// + public required string Id { get; init; } + + /// + /// Code of the operator. + /// + public required string OperatorCode { get; init; } + + /// + /// Name of the operator. + /// + public required string OperatorName { get; init; } + + /// + /// Localized transport company information. + /// + public IReadOnlyList TransportCompanies { get; init; } = []; +} diff --git a/source/DotBahn.Boards/Models/Operators/TransportCompany.cs b/source/DotBahn.Boards/Models/Operators/TransportCompany.cs new file mode 100644 index 0000000..0b3dcc4 --- /dev/null +++ b/source/DotBahn.Boards/Models/Operators/TransportCompany.cs @@ -0,0 +1,46 @@ +namespace DotBahn.Boards.Models.Operators; + +/// +/// Transport company information for an administration. +/// +public class TransportCompany { + /// + /// Language of the entry, as ISO-639-3 code. + /// + public required string Language { get; init; } + + /// + /// Name of the transport company. + /// + public required string Name { get; init; } + + /// + /// Short name of the transport company. + /// + public required string ShortName { get; init; } + + /// + /// Email address of the transport company. + /// + public string? Email { get; init; } + + /// + /// Phone number of the transport company. + /// + public string? PhoneNumber { get; init; } + + /// + /// Website of the transport company. + /// + public string? Website { get; init; } + + /// + /// Ticketing website of the transport company. + /// + public string? WebsiteTicketing { get; init; } + + /// + /// Website of the digital assistant of the transport company. + /// + public string? WebsiteDigitalAssistant { get; init; } +} diff --git a/source/DotBahn.Boards/Models/Platform.cs b/source/DotBahn.Boards/Models/Platform.cs new file mode 100644 index 0000000..df240a7 --- /dev/null +++ b/source/DotBahn.Boards/Models/Platform.cs @@ -0,0 +1,71 @@ +namespace DotBahn.Boards.Models; + +/// +/// Platform information for a board entry. +/// +public class Platform { + /// + /// Name of the platform. + /// + public required string Name { get; init; } + + /// + /// IFOPT / DHID of the platform. + /// + public string? Ifopt { get; init; } + + /// + /// Whether step-free access is available. + /// + public bool StepFreeAccess { get; init; } + + /// + /// Whether a boarding aid is available. + /// + public bool BoardingAid { get; init; } + + /// + /// Whether tactile guiding strips are available. + /// + public bool TactileGuidingStrips { get; init; } + + /// + /// Whether tactile handrail labels are available. + /// + public bool TactileHandrailLabel { get; init; } + + /// + /// Whether tactile platform access indicators are available. + /// + public bool TactilePlatformAccess { get; init; } + + /// + /// Whether audible signals are available. + /// + public bool AudibleSignalsAvailable { get; init; } + + /// + /// Whether automatic doors are available. + /// + public bool AutomaticDoor { get; init; } + + /// + /// Whether a passenger information display is available. + /// + public bool PassengerInformationDisplay { get; init; } + + /// + /// Whether a platform sign is available. + /// + public bool PlatformSign { get; init; } + + /// + /// Whether stairs marking is available. + /// + public bool StairsMarking { get; init; } + + /// + /// Whether the platform has a standard height. + /// + public bool StandardPlatformHeight { get; init; } +} diff --git a/source/DotBahn.Boards/Models/StopPlace.cs b/source/DotBahn.Boards/Models/StopPlace.cs new file mode 100644 index 0000000..f7eb9b1 --- /dev/null +++ b/source/DotBahn.Boards/Models/StopPlace.cs @@ -0,0 +1,41 @@ +namespace DotBahn.Boards.Models; + +/// +/// A stop place where a journey stops. +/// +public class StopPlace { + /// + /// EVA number of the stop place. + /// + public required string EvaNumber { get; init; } + + /// + /// Name of the stop place. + /// + public required string Name { get; init; } + + /// + /// STADA identifier of the parent station, if available. + /// + public string? StadaId { get; init; } + + /// + /// Name of the parent station, if available. + /// + public string? StationName { get; init; } + + /// + /// DHID / IFOPT of the stop place, if available. + /// + public string? Dhid { get; init; } + + /// + /// Symbol of the stop place, if available. + /// + public string? Symbol { get; init; } + + /// + /// Name of the symbol of the stop place, if available. + /// + public string? SymbolName { get; init; } +} diff --git a/source/DotBahn.Boards/Models/Visit.cs b/source/DotBahn.Boards/Models/Visit.cs new file mode 100644 index 0000000..f608b67 --- /dev/null +++ b/source/DotBahn.Boards/Models/Visit.cs @@ -0,0 +1,26 @@ +namespace DotBahn.Boards.Models; + +/// +/// A reference to a stop place with visit-specific details. +/// +public class Visit { + /// + /// The referenced stop place. + /// + public required StopPlace StopPlace { get; init; } + + /// + /// Whether this is an additional stop. + /// + public bool Additional { get; init; } + + /// + /// Whether this stop has been canceled. + /// + public bool Cancelled { get; init; } + + /// + /// Display priority in ascending order. + /// + public int? DisplayPriority { get; init; } +} diff --git a/source/DotBahn.Boards/ServiceCollectionExtensions.cs b/source/DotBahn.Boards/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..086820f --- /dev/null +++ b/source/DotBahn.Boards/ServiceCollectionExtensions.cs @@ -0,0 +1,59 @@ +using DotBahn.Boards.Internal.Contracts; +using DotBahn.Boards.Internal.Json; +using DotBahn.Boards.Internal.Transformers; +using DotBahn.Boards.Models; +using DotBahn.Boards.Models.Entries; +using DotBahn.Common.Auth; +using DotBahn.Common.Clients; +using DotBahn.Common.Parsing; +using DotBahn.Common.Transformer; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +namespace DotBahn.Boards; + +/// +/// Extension methods for registering the DotBahn Boards client. +/// +public static class ServiceCollectionExtensions { + private const string OptionsName = "DotBahn.Boards"; + private static readonly Uri DefaultBoardsEndpoint = new("https://apis.deutschebahn.com/db-api-marketplace/apis/open-boards/v1/"); + + /// + /// Registers the with its parser and transformer services. + /// + /// The service collection to add to. + /// Optional action to override default client options. + /// The service collection for chaining. + public static IServiceCollection AddDotBahnBoards(this IServiceCollection services, Action? configuration = null) { + services.AddOptions(OptionsName) + .Configure(opts => { + opts.BaseEndpoint = DefaultBoardsEndpoint; + configuration?.Invoke(opts); + }) + .Validate(o => o.BaseEndpoint.IsAbsoluteUri, "DotBahn: BaseEndpoint must be an absolute URI.") + .ValidateOnStart(); + + services.AddHttpClient(OptionsName, (http, sp) => { + var options = sp.GetRequiredService>().Get(OptionsName); + http.BaseAddress = options.BaseEndpoint; + http.DefaultRequestHeaders.UserAgent.ParseAdd("DotBahn/2.X (+https://github.com/rlvelte/dotbahn)"); + + var auth = sp.GetRequiredService(); + var arrivalParser = sp.GetRequiredService>(); + var departureParser = sp.GetRequiredService>(); + var arrivalTransformer = sp.GetRequiredService, ArrivalBoardResponseContract>>(); + var departureTransformer = sp.GetRequiredService, DepartureBoardResponseContract>>(); + + return new BoardsClient(http, auth, arrivalParser, departureParser, arrivalTransformer, departureTransformer); + }) + .AddStandardResilienceHandler(); + + services.AddSingleton>(_ => new JsonParser(BoardsJsonContext.Default.ArrivalBoardResponseContract)); + services.AddSingleton>(_ => new JsonParser(BoardsJsonContext.Default.DepartureBoardResponseContract)); + services.AddSingleton, ArrivalBoardResponseContract>, ArrivalBoardTransformer>(); + services.AddSingleton, DepartureBoardResponseContract>, DepartureBoardTransformer>(); + + return services; + } +} diff --git a/source/DotBahn.Boards/packages.lock.json b/source/DotBahn.Boards/packages.lock.json new file mode 100644 index 0000000..1f3715b --- /dev/null +++ b/source/DotBahn.Boards/packages.lock.json @@ -0,0 +1,320 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.Extensions.Http": { + "type": "Direct", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Http.Resilience": { + "type": "Direct", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "5VawCrg+VgVT2hNurSSEWUnq0pvNoH+Zt82s5Wpl/8jdnmU8DpRlr+M3DcdtVgeBG7mRyk3GtSRbf8PB/HrL3w==", + "dependencies": { + "Microsoft.Extensions.Http.Diagnostics": "11.0.1", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Resilience": "11.0.1" + } + }, + "Microsoft.Extensions.Options": { + "type": "Direct", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.NET.ILLink.Tasks": { + "type": "Direct", + "requested": "[10.0.15, )", + "resolved": "10.0.15", + "contentHash": "u0WnRcZgBZYHlVFpbe/3Adpmb9rmNJ8/fmEwqc/xjB7fFppq+gfaLJd3Sdaw+J02zV0eP/T9dneQ3Dv5jWw6bw==" + }, + "MinVer": { + "type": "Direct", + "requested": "[8.0.0, )", + "resolved": "8.0.0", + "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" + }, + "Microsoft.Extensions.AmbientMetadata.Application": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "tm28s2ODWZ6RdysP06NI3B23DUY5OfHG35ihMHxVAO3hywZAczDVjrkYMfBY//J4HQqfDHS5op84BhnF7ROseQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Compliance.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "DUwdXgIxJKH9zBNg/SUBqOX0FpXCq7w80CIzrr0Jcw5tBXS926AtCcidoAsEHq5e/c6KQ8rWhSt7NxFxak8N/Q==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15" + } + }, + "Microsoft.Extensions.Compliance.Redaction": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "2rwe98yZEn4+aXjAg5DdcROMg6m2w3tejf/mRk4/fBCHKM2EWCaFTmbHLtz1BfyBxMY00/08XFoN0wzWYNiSiQ==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Configuration": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", + "dependencies": { + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" + }, + "Microsoft.Extensions.DependencyInjection.AutoActivation": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "OuVIF5TmsfonN2Fqmi2zlUtbFQNqQiflhgo/rh64ptrqYrB4wZLwKbXr/HzrQXMf+h3jIbWrjIdJFspGqcvuuQ==", + "dependencies": { + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mqqpmAFNRLa4cozN3RvT/T81k4aarwMc8xb8VVQgLqUE7AAoN/WWayZAvP+4hy9+KujP3dfn3taU06fZJPIbgA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.FileProviders.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "1RSYAUtJeb76m2T0u5BbvwKY3s+ge9fT3cj1odvo5Bm+frc7pU9RSeXeMIlYHV8GjpqLdv2neeeomz010yYL8A==", + "dependencies": { + "Microsoft.Extensions.Primitives": "10.0.15" + } + }, + "Microsoft.Extensions.Hosting.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "s/JBiwR3F/vKRCbe6WO5b6t6or1ISaZ3rllchcw6/FSWZmK8s2fAzD7elrZo7592FnMD1fhGoG/wuJL1YYtVXw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.Http.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mKHY0oFYL3fkAOhBNi2LqWPuEdUJ+HiF28KKUwBkQG2sgXAUdFDDqvJAfu2PcYgtAwsAtl58zuk4SElpPzbCvA==", + "dependencies": { + "Microsoft.Extensions.Compliance.Redaction": "11.0.1", + "Microsoft.Extensions.Http": "10.0.15", + "Microsoft.Extensions.Telemetry": "11.0.1" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Configuration": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "Km6Ml1/nu0T/f80Btonxf9CWmP/BXI84aJwC5fUbCxRArJ0lH++0ADQrjErZvsSIrKhusTkTSGBChKy2fYAF4w==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Configuration.Binder": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.ObjectPool": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "kvd9eyRRQ+OEu9wik7GKgTS+7XnJ5XoOtSXJqmkJtVYV/S4gsBUrobYRSdNeBcb0ymef4L5Q9pZGiTxJ8jJfyQ==" + }, + "Microsoft.Extensions.Options.ConfigurationExtensions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" + }, + "Microsoft.Extensions.Resilience": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "xgKof6iwAByZNrxWOa7Drk4A953L7U2HleTmx7EXE2Vf6j1crp4RsvNlIVsJMtHKf3ftGKd9gOhR3xES9vxUgg==", + "dependencies": { + "Microsoft.Extensions.Diagnostics": "10.0.15", + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1", + "Polly.Extensions": "8.4.2", + "Polly.RateLimiting": "8.4.2" + } + }, + "Microsoft.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "9uuA8entTC9m00m59h6CACSt4IQh9KknB+hPvCteXUTiG67lqJ8BI65fEUJSPSfT3ZDDi01Zg2aY5kRUvD4HPw==", + "dependencies": { + "Microsoft.Extensions.AmbientMetadata.Application": "11.0.1", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "11.0.1", + "Microsoft.Extensions.Logging.Configuration": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1" + } + }, + "Microsoft.Extensions.Telemetry.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "qINZz4G01Wxumqd0hLr6YdzPa3s7jexQWN28EenaiJQnmKdsR9FnBaKENdRRElLc+A5bJKQ+jYw/WHG4ZpIyAg==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15" + } + }, + "Polly.Core": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g==" + }, + "Polly.Extensions": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==", + "dependencies": { + "Microsoft.Extensions.Logging.Abstractions": "8.0.0", + "Microsoft.Extensions.Options": "8.0.0", + "Polly.Core": "8.4.2" + } + }, + "Polly.RateLimiting": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==", + "dependencies": { + "Polly.Core": "8.4.2", + "System.Threading.RateLimiting": "8.0.0" + } + }, + "System.Diagnostics.DiagnosticSource": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" + }, + "System.Threading.RateLimiting": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q==" + }, + "dotbahn.common": { + "type": "Project", + "dependencies": { + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + } + } + } +} \ No newline at end of file diff --git a/source/DotBahn.Common/Auth/AuthorizationOptions.cs b/source/DotBahn.Common/Auth/AuthorizationOptions.cs index 9da9db1..325b2b7 100644 --- a/source/DotBahn.Common/Auth/AuthorizationOptions.cs +++ b/source/DotBahn.Common/Auth/AuthorizationOptions.cs @@ -1,16 +1,16 @@ namespace DotBahn.Common.Auth; /// -/// Options for authorization +/// Options for authorization. /// public record AuthorizationOptions { /// - /// The client ID for your application + /// The client ID for your application. /// public required string ClientId { get; set; } /// - /// The api key for your application + /// The api key for your application. /// public required string ApiKey { get; set; } diff --git a/source/DotBahn.Common/Auth/IAuthorization.cs b/source/DotBahn.Common/Auth/IAuthorization.cs index ef24497..234a298 100644 --- a/source/DotBahn.Common/Auth/IAuthorization.cs +++ b/source/DotBahn.Common/Auth/IAuthorization.cs @@ -1,13 +1,16 @@ +using System.ComponentModel; + namespace DotBahn.Common.Auth; /// -/// Provides authorization for API requests +/// Provides authorization for API requests. /// +[EditorBrowsable(EditorBrowsableState.Advanced)] public interface IAuthorization { /// - /// Authorizes the provided request + /// Authorizes the provided request. /// - /// The request to add authorization to - /// Thrown when is null + /// The request to add authorization to. + /// Thrown when is null. void AuthorizeRequest(HttpRequestMessage request); } diff --git a/source/DotBahn.Common/Clients/ClientBase.cs b/source/DotBahn.Common/Clients/ClientBase.cs index 41644be..564260a 100644 --- a/source/DotBahn.Common/Clients/ClientBase.cs +++ b/source/DotBahn.Common/Clients/ClientBase.cs @@ -1,6 +1,8 @@ using System.Diagnostics; using System.Net; using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json.Serialization.Metadata; using DotBahn.Common.Auth; using DotBahn.Common.Parsing; using DotBahn.Common.Telemetry; @@ -9,30 +11,28 @@ namespace DotBahn.Common.Clients; /// -/// Base class for API clients providing common HTTP functionality +/// Base class for API clients providing common HTTP functionality. /// public abstract class ClientBase : IDisposable { private readonly IAuthorization _authorization; private readonly bool _ownsHttpClient; /// - /// The HTTP client used for requests + /// The HTTP client used for requests. /// protected HttpClient HttpClient { get; } /// - /// The API identifier used for telemetry tags + /// The API identifier used for telemetry tags. /// protected virtual string ApiName => string.Empty; /// /// Initializes a new instance with the specified HTTP client and authorization. - /// The is not owned by this instance and will not be disposed /// - /// The HTTP client - /// The authorization provider - /// Thrown when is null - /// Thrown when is null + /// The HTTP client. + /// The authorization provider. + /// Thrown when or is null. protected ClientBase(HttpClient http, IAuthorization authorization) { ArgumentNullException.ThrowIfNull(http); ArgumentNullException.ThrowIfNull(authorization); @@ -42,12 +42,11 @@ protected ClientBase(HttpClient http, IAuthorization authorization) { } /// - /// Initializes a new instance that creates and owns its own + /// Initializes a new instance that creates and owns its own . /// - /// The client options containing the base endpoint - /// The authorization options containing the API key - /// Thrown when is null - /// Thrown when is null + /// The client options containing the base endpoint. + /// The authorization options containing the API key. + /// Thrown when or is null. protected ClientBase(ClientOptions options, AuthorizationOptions auth) { ArgumentNullException.ThrowIfNull(options); ArgumentNullException.ThrowIfNull(auth); @@ -56,25 +55,25 @@ protected ClientBase(ClientOptions options, AuthorizationOptions auth) { BaseAddress = options.BaseEndpoint }; - HttpClient.DefaultRequestHeaders.UserAgent.ParseAdd("DotBahn/2.0 (+https://github.com/rlvelte/dotbahn)"); + HttpClient.DefaultRequestHeaders.UserAgent.ParseAdd("DotBahn/2.X (+https://github.com/rlvelte/dotbahn)"); _authorization = new ApiKeyAuthorization(auth); _ownsHttpClient = true; } /// - /// Performs a GET request and parses the response into the specified contract type + /// Performs a GET request and parses the response into the specified contract type. /// - /// The type to parse the response into - /// The relative request URL - /// The parser for deserializing the response - /// The acceptance header value - /// Optional query parameters - /// The ct token - /// The parsed response - /// Thrown when is null - /// Thrown when the API responds with a non-success status code - /// Thrown when the operation is canceled via + /// The type to parse the response into. + /// The relative request URL. + /// The parser for deserializing the response. + /// The acceptance header value. + /// Optional query parameters. + /// The ct token. + /// The parsed response. + /// Thrown when is null. + /// Thrown when the API responds with a non-success status code. + /// Thrown when the operation is canceled via . protected async Task GetAsync(string relative, IParser parser, string acceptHeader, QueryParameters? queryParams = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(parser); @@ -102,22 +101,63 @@ protected async Task GetAsync(string relative, IParser - /// Combines the base address with a relative URL to produce an absolute URI + /// Performs a POST request with a JSON body and parses the response into the specified contract type. /// - /// The relative URL path - /// An absolute URI + /// The type to serialize as the request body. + /// The type to parse the response into. + /// The relative request URL. + /// The request body to serialize. + /// The source-generated JSON type info for the request type. + /// The parser for deserializing the response. + /// The acceptance header value. + /// The cancellation token. + /// The parsed response. + /// Thrown when or is null. + /// Thrown when the API responds with a non-success status code. + /// Thrown when the operation is canceled via . + protected async Task PostAsync(string relative, TRequest request, JsonTypeInfo requestType, IParser parser, string acceptHeader, CancellationToken ct = default) { + ArgumentNullException.ThrowIfNull(parser); + ArgumentNullException.ThrowIfNull(requestType); + + var requestUri = BuildRequestUri(relative); + var endpoint = requestUri.ToString(); + + using var activity = DotBahnTelemetry.StartRequest(ApiName, endpoint, HttpClient.BaseAddress?.Host); + var start = Stopwatch.GetTimestamp(); + + try { + var raw = await ExecuteRequestAsync(requestUri, request, requestType, acceptHeader, ct).ConfigureAwait(false); + var result = parser.Parse(raw); + DotBahnTelemetry.RecordRequest(Stopwatch.GetElapsedTime(start).TotalSeconds, ApiName, endpoint, null); + return result; + } catch (OperationCanceledException) { + DotBahnTelemetry.RecordRequest(Stopwatch.GetElapsedTime(start).TotalSeconds, ApiName, endpoint, null); + throw; + } catch (Exception exception) { + activity?.SetStatus(ActivityStatusCode.Error, exception.Message); + activity?.SetTag(DotBahnTelemetry.ErrorTypeTag, exception.GetType().Name); + DotBahnTelemetry.RecordRequest(Stopwatch.GetElapsedTime(start).TotalSeconds, ApiName, endpoint, exception.GetType().Name); + throw; + } + } + + /// + /// Combines the base address with a relative URL to produce an absolute URI. + /// + /// The relative URL path. + /// An absolute URI. private static Uri BuildRequestUri(string relativeUrl) { var path = relativeUrl.TrimStart('/'); return new Uri(path, UriKind.Relative); } /// - /// Sends an authorized GET request and processes the response + /// Sends an authorized GET request and processes the response. /// - /// The request URI - /// The acceptance header value - /// The ct token - /// The response body as a string + /// The request URI. + /// The acceptance header value. + /// The ct token. + /// The response body as a string. private async Task ExecuteRequestAsync(Uri uri, string acceptHeader, CancellationToken ct) { using var request = new HttpRequestMessage(HttpMethod.Get, uri); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader)); @@ -129,30 +169,47 @@ private async Task ExecuteRequestAsync(Uri uri, string acceptHeader, Can } /// - /// Processes the HTTP response, returning the body for success status codes or throwing on errors + /// Sends an authorized POST request with a JSON body and processes the response. /// - /// The HTTP response message - /// The response body for successful requests; string.Empty for 404 - /// Thrown when the API responds with a non-success status code with a descriptive message + /// The type to serialize as the request body. + /// The request URI. + /// The request body to serialize. + /// The source-generated JSON type info for the request type. + /// The acceptance header value. + /// The cancellation token. + /// The response body as a string. + private async Task ExecuteRequestAsync(Uri uri, TRequest request, JsonTypeInfo requestType, string acceptHeader, CancellationToken ct) { + using var requestMessage = new HttpRequestMessage(HttpMethod.Post, uri); + requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader)); + requestMessage.Content = JsonContent.Create(request, requestType, MediaTypeHeaderValue.Parse("application/json")); + + _authorization.AuthorizeRequest(requestMessage); + + using var response = await HttpClient.SendAsync(requestMessage, ct).ConfigureAwait(false); + return await ProcessResponseAsync(response).ConfigureAwait(false); + } + + /// + /// Processes the HTTP response, returning the body for success status codes or throwing on errors. + /// + /// The HTTP response message. + /// The response body for successful requests; string.Empty for 404. + /// Thrown when the API responds with a non-success status code with a descriptive message. private static async Task ProcessResponseAsync(HttpResponseMessage response) { + if (response.StatusCode == HttpStatusCode.NotFound) { + return string.Empty; + } + var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + return !response.IsSuccessStatusCode ? throw new HttpRequestException($"The API responded with {(int)response.StatusCode} ({response.ReasonPhrase}): {DescribeBody(body)}", null, response.StatusCode) : body; - return response.StatusCode switch { - HttpStatusCode.NotFound => string.Empty, - HttpStatusCode.Unauthorized => throw new HttpRequestException("Request was not authorized.", null, response.StatusCode), - HttpStatusCode.BadRequest => throw new HttpRequestException($"Bad request: {DescribeBody(body)}", null, response.StatusCode), - HttpStatusCode.Forbidden => throw new HttpRequestException("Access denied.", null, response.StatusCode), - HttpStatusCode.TooManyRequests => throw new HttpRequestException("Rate limit exceeded.", null, response.StatusCode), - _ when !response.IsSuccessStatusCode => throw new HttpRequestException($"The API responded with status {(int)response.StatusCode}: {DescribeBody(body)}", null, response.StatusCode), - _ => body - }; } /// - /// Truncates the response body for inclusion in exception messages + /// Truncates the response body for inclusion in exception messages. /// - /// The raw response body - /// The body unchanged if 200 characters or fewer; otherwise the first 200 characters with an ellipsis + /// The raw response body. + /// The body unchanged if 200 characters or fewer; otherwise the first 200 characters with an ellipsis. private static string DescribeBody(string body) => string.IsNullOrEmpty(body) ? string.Empty : body.Length <= 200 ? body : body[..200] + "..."; /// diff --git a/source/DotBahn.Common/Clients/ClientOptions.cs b/source/DotBahn.Common/Clients/ClientOptions.cs index 15ddb3b..2e2de4c 100644 --- a/source/DotBahn.Common/Clients/ClientOptions.cs +++ b/source/DotBahn.Common/Clients/ClientOptions.cs @@ -1,11 +1,11 @@ namespace DotBahn.Common.Clients; /// -/// Options for a client +/// Options for a client. /// public record ClientOptions { /// - /// The base endpoint for API requests + /// The base endpoint for API requests. /// public required Uri BaseEndpoint { get; set; } } diff --git a/source/DotBahn.Common/DotBahn.Common.csproj b/source/DotBahn.Common/DotBahn.Common.csproj index 786d0ce..0f15fba 100644 --- a/source/DotBahn.Common/DotBahn.Common.csproj +++ b/source/DotBahn.Common/DotBahn.Common.csproj @@ -13,5 +13,6 @@ + diff --git a/source/DotBahn.Common/Models/ChangedRef.cs b/source/DotBahn.Common/Models/ChangedRef.cs index 9c8aec1..07b43b5 100644 --- a/source/DotBahn.Common/Models/ChangedRef.cs +++ b/source/DotBahn.Common/Models/ChangedRef.cs @@ -3,28 +3,28 @@ namespace DotBahn.Common.Models; /// -/// Represents a reference type that can be updated, tracking both the original and changed value +/// Represents a reference type that can be updated, tracking both the original and changed value. /// -/// The reference type +/// The reference type. public class ChangedRef where T : class { /// - /// The original value + /// The original value. /// public required T Original { get; init; } /// - /// The updated value, if available + /// The updated value, if available. /// public T? Updated { get; set; } /// - /// Indicates if there is an updated value + /// Indicates if there is an updated value. /// [MemberNotNullWhen(true, nameof(Updated))] public bool HasUpdate => Updated != null; /// - /// Gets the currently active value + /// Gets the currently active value. /// public T Actual => Updated ?? Original; } diff --git a/source/DotBahn.Common/Models/ChangedValue.cs b/source/DotBahn.Common/Models/ChangedValue.cs index c988978..6074ea0 100644 --- a/source/DotBahn.Common/Models/ChangedValue.cs +++ b/source/DotBahn.Common/Models/ChangedValue.cs @@ -3,28 +3,28 @@ namespace DotBahn.Common.Models; /// -/// Represents a value type that can be updated, tracking both the original and changed value +/// Represents a value type that can be updated, tracking both the original and changed value. /// -/// The value type +/// The value type. public class ChangedValue where T : struct { /// - /// The original value + /// The original value. /// public required T Original { get; init; } /// - /// The updated value, if available + /// The updated value, if available. /// public T? Updated { get; set; } /// - /// Indicates if there is an updated value + /// Indicates if there is an updated value. /// [MemberNotNullWhen(true, nameof(Updated))] public bool HasUpdate => Updated.HasValue; /// - /// Gets the currently active value + /// Gets the currently active value. /// public T Actual => Updated ?? Original; } diff --git a/source/DotBahn.Common/Models/Coordinates.cs b/source/DotBahn.Common/Models/Coordinates.cs index 4d5bafa..23962e5 100644 --- a/source/DotBahn.Common/Models/Coordinates.cs +++ b/source/DotBahn.Common/Models/Coordinates.cs @@ -1,7 +1,7 @@ namespace DotBahn.Common.Models; /// -/// Geographic coordinates representing the location of an entity +/// Geographic coordinates representing the location of an entity. /// public readonly record struct Coordinates { /// diff --git a/source/DotBahn.Common/Parsing/Converters/BahnDialectJsonConverter.cs b/source/DotBahn.Common/Parsing/Converters/BahnDialectJsonConverter.cs index f041efe..9cf816d 100644 --- a/source/DotBahn.Common/Parsing/Converters/BahnDialectJsonConverter.cs +++ b/source/DotBahn.Common/Parsing/Converters/BahnDialectJsonConverter.cs @@ -4,7 +4,7 @@ namespace DotBahn.Common.Parsing.Converters; /// -/// Converts dialect in the contracts to real types (e.g. 'yes' as 'true') +/// Converts dialect in the contracts to real types (e.g. 'yes' as 'true'). /// public sealed class BahnDialectJsonConverter : JsonConverter { /// @@ -24,6 +24,7 @@ public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSer "FALSE" => false, "YES" => true, "NO" => false, + "JA" => true, "1" => true, _ => false }; @@ -35,7 +36,6 @@ public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSer /// public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options) { ArgumentNullException.ThrowIfNull(writer); - writer.WriteBooleanValue(value); } } diff --git a/source/DotBahn.Common/Parsing/IParser.cs b/source/DotBahn.Common/Parsing/IParser.cs index c206837..6f62ad2 100644 --- a/source/DotBahn.Common/Parsing/IParser.cs +++ b/source/DotBahn.Common/Parsing/IParser.cs @@ -1,14 +1,17 @@ +using System.ComponentModel; + namespace DotBahn.Common.Parsing; /// -/// Generic interface for parsing raw data into a target type +/// Generic interface for parsing raw data into a target type. /// -/// The type to parse into +/// The type to parse into. +[EditorBrowsable(EditorBrowsableState.Advanced)] public interface IParser { /// - /// Parses the provided input string into the target type + /// Parses the provided input string into the target type. /// - /// The input data (e.g., XML, JSON) - /// The parsed object + /// The input data (e.g., XML, JSON). + /// The parsed object. TContract Parse(string input); } diff --git a/source/DotBahn.Common/Parsing/JsonParser.cs b/source/DotBahn.Common/Parsing/JsonParser.cs index 19ee199..ce7e580 100644 --- a/source/DotBahn.Common/Parsing/JsonParser.cs +++ b/source/DotBahn.Common/Parsing/JsonParser.cs @@ -4,13 +4,13 @@ namespace DotBahn.Common.Parsing; /// -/// Generic JSON parser implementation using source-generated metadata +/// Generic JSON parser implementation using source-generated metadata. /// -/// The raw type to deserialize into -/// The source-generated JSON type info for +/// The raw type to deserialize into. +/// The source-generated JSON type info for . public class JsonParser(JsonTypeInfo type) : IParser where TContract : new() { /// - /// Thrown when deserialization fails or returns null + /// Thrown when deserialization fails or returns null. public TContract Parse(string input) { if (string.IsNullOrWhiteSpace(input)) { return new TContract(); diff --git a/source/DotBahn.Common/ServiceCollectionExtensions.cs b/source/DotBahn.Common/ServiceCollectionExtensions.cs index 8a44cf7..9fe2637 100644 --- a/source/DotBahn.Common/ServiceCollectionExtensions.cs +++ b/source/DotBahn.Common/ServiceCollectionExtensions.cs @@ -6,16 +6,16 @@ namespace DotBahn.Common; /// -/// Shared helper for registering DotBahn typed clients +/// Shared helper for registering DotBahn typed clients. /// public static class ServiceCollectionExtensions { /// - /// Registers the DotBahn authorization services using the provided configuration + /// Registers the DotBahn authorization services using the provided configuration. /// - /// The service collection to add to - /// The action to configure authorization options - /// The service collection for chaining - /// Thrown when is null + /// The service collection to add to. + /// The action to configure authorization options. + /// The service collection for chaining. + /// Thrown when is null. public static IServiceCollection AddDotBahnAuthorization(this IServiceCollection services, Action configuration) { ArgumentNullException.ThrowIfNull(configuration); diff --git a/source/DotBahn.Common/Telemetry/DotBahnTelemetry.cs b/source/DotBahn.Common/Telemetry/DotBahnTelemetry.cs index 3f4698e..7a3b81d 100644 --- a/source/DotBahn.Common/Telemetry/DotBahnTelemetry.cs +++ b/source/DotBahn.Common/Telemetry/DotBahnTelemetry.cs @@ -8,52 +8,87 @@ namespace DotBahn.Common.Telemetry; /// public static class DotBahnTelemetry { /// - /// The name of the used for traces + /// The name of the used for traces. /// public const string SourceName = "DotBahn.Common"; /// - /// The name of the used for metrics + /// The name of the used for metrics. /// public const string MeterName = "DotBahn.Common"; /// - /// The name of the activity emitted for each client request + /// The name of the used for AI tool traces. + /// + public const string AiSourceName = "DotBahn.Ai"; + + /// + /// The name of the used for AI tool metrics. + /// + public const string AiMeterName = "DotBahn.Ai"; + + /// + /// The name of the activity emitted for each client request. /// public const string RequestActivityName = "dotbahn.request"; /// - /// The name of the histogram measuring request duration in seconds + /// The name of the activity emitted for each AI tool invocation. + /// + public const string AiToolActivityName = "dotbahn.ai.tool"; + + /// + /// The name of the histogram measuring request duration in seconds. /// public const string RequestDurationMetricName = "dotbahn.request.duration"; /// - /// The name of the counter measuring the number of requests + /// The name of the counter measuring the number of requests. /// public const string RequestCountMetricName = "dotbahn.request.count"; /// - /// Tag identifying the API being accessed ('stations', 'timetables', 'facilities') + /// The name of the histogram measuring AI tool duration in seconds. + /// + public const string AiToolDurationMetricName = "dotbahn.ai.tool.duration"; + + /// + /// The name of the counter measuring the number of AI tool invocations. + /// + public const string AiToolCountMetricName = "dotbahn.ai.tool.count"; + + /// + /// Tag identifying the API being accessed ('stations', 'timetables', 'facilities'). /// public const string ApiTag = "dotbahn.api"; /// - /// Tag identifying the request endpoint including the query string + /// Tag identifying the request endpoint including the query string. /// public const string EndpointTag = "dotbahn.endpoint"; /// - /// Tag identifying the server host, following the stable HTTP semantic conventions + /// Tag identifying the server host, following the stable HTTP semantic conventions. /// public const string ServerAddressTag = "server.address"; /// - /// Tag identifying the error type, following the stable error semantic conventions + /// Tag identifying the AI tool being invoked. + /// + public const string ToolTag = "dotbahn.tool"; + + /// + /// Tag identifying the error type, following the stable error semantic conventions. /// public const string ErrorTypeTag = "error.type"; /// - /// The version of the telemetry source, derived from the assembly version + /// Tag identifying the structured error code returned by an AI tool. + /// + public const string ErrorCodeTag = "dotbahn.error_code"; + + /// + /// The version of the telemetry source, derived from the assembly version. /// public static string Version { get; } = typeof(DotBahnTelemetry).Assembly.GetName().Version?.ToString() ?? "0.0.0"; @@ -61,14 +96,18 @@ public static class DotBahnTelemetry { private static readonly Meter Meter = new(MeterName, Version); private static readonly Histogram RequestDuration = Meter.CreateHistogram(RequestDurationMetricName, "s"); private static readonly Counter RequestCount = Meter.CreateCounter(RequestCountMetricName, "{request}"); + private static readonly ActivitySource AiSource = new(AiSourceName, Version); + private static readonly Meter AiMeter = new(AiMeterName, Version); + private static readonly Histogram AiToolDuration = AiMeter.CreateHistogram(AiToolDurationMetricName, "s"); + private static readonly Counter AiToolCount = AiMeter.CreateCounter(AiToolCountMetricName, "{tool}"); /// /// Starts a request activity. Returns null when no listener is registered, making telemetry a no-op. /// - /// The API identifier, or null when unknown - /// The request endpoint including the query string - /// The server host, or null when unknown - /// The started activity, or null when no listener is registered + /// The API identifier, or null when unknown. + /// The request endpoint including the query string. + /// The server host, or null when unknown. + /// The started activity, or null when no listener is registered. internal static Activity? StartRequest(string? api, string endpoint, string? serverAddress) { var activity = Source.StartActivity(RequestActivityName, ActivityKind.Client); if (activity == null) { @@ -89,12 +128,12 @@ public static class DotBahnTelemetry { } /// - /// Records the duration and count of a completed request + /// Records the duration and count of a completed request. /// - /// The request duration in seconds - /// The API identifier, or null when unknown - /// The request endpoint including the query string - /// The exception type name on failure, or null on success + /// The request duration in seconds. + /// The API identifier, or null when unknown. + /// The request endpoint including the query string. + /// The exception type name on failure, or null on success. internal static void RecordRequest(double durationSeconds, string? api, string endpoint, string? errorType) { var tags = new TagList(); @@ -111,4 +150,43 @@ internal static void RecordRequest(double durationSeconds, string? api, string e RequestDuration.Record(durationSeconds, tags); RequestCount.Add(1, tags); } + + /// + /// Starts an AI tool activity. Returns null when no listener is registered, making telemetry a no-op. + /// + /// The name of the tool being invoked. + /// The started activity, or null when no listener is registered. + public static Activity? StartAiTool(string name) { + var activity = AiSource.StartActivity(AiToolActivityName); + if (activity == null) { + return null; + } + + activity.SetTag(ToolTag, name); + return activity; + } + + /// + /// Records the duration and count of a completed AI tool invocation. + /// + /// The tool duration in seconds. + /// The name of the tool being invoked. + /// The exception type name on failure, or null on success. + /// The structured tool error code on failure, or null on success. + public static void RecordAiTool(double durationSeconds, string name, string? errorType = null, string? errorCode = null) { + var tags = new TagList { + { ToolTag, name } + }; + + if (errorType != null) { + tags.Add(ErrorTypeTag, errorType); + } + + if (errorCode != null) { + tags.Add(ErrorCodeTag, errorCode); + } + + AiToolDuration.Record(durationSeconds, tags); + AiToolCount.Add(1, tags); + } } diff --git a/source/DotBahn.Common/Transformer/IMerger.cs b/source/DotBahn.Common/Transformer/IMerger.cs index bd0f7b4..d390d76 100644 --- a/source/DotBahn.Common/Transformer/IMerger.cs +++ b/source/DotBahn.Common/Transformer/IMerger.cs @@ -3,16 +3,16 @@ namespace DotBahn.Common.Transformer; /// -/// Generic interface for merging data onto a target type +/// Generic interface for merging data onto a target type. /// -/// The type to transform on -[EditorBrowsable(EditorBrowsableState.Never)] +/// The type to transform on. +[EditorBrowsable(EditorBrowsableState.Advanced)] public interface IMerger { /// - /// Merges the incoming changes onto the target object + /// Merges the incoming changes onto the target object. /// - /// The current data - /// The change data to merge on the current - /// The merged object + /// The current data. + /// The change data to merge on the current. + /// The merged object. TModel Merge(TModel current, TModel changes); } diff --git a/source/DotBahn.Common/Transformer/ITransformer.cs b/source/DotBahn.Common/Transformer/ITransformer.cs index 1543805..b8a94e5 100644 --- a/source/DotBahn.Common/Transformer/ITransformer.cs +++ b/source/DotBahn.Common/Transformer/ITransformer.cs @@ -3,16 +3,16 @@ namespace DotBahn.Common.Transformer; /// -/// Generic interface for transforming data into a target type +/// Generic interface for transforming data into a target type. /// -/// The type to transform to -/// The type to extract from -[EditorBrowsable(EditorBrowsableState.Never)] -public interface ITransformer { +/// The type to transform to. +/// The type to extract from. +[EditorBrowsable(EditorBrowsableState.Advanced)] +public interface ITransformer { /// - /// Transform the contract into the domain model + /// Transform the contract into the domain model. /// - /// The contract data to transform - /// The transformed object + /// The contract data to transform. + /// The transformed object. TModel Transform(TContract contracts); } diff --git a/source/DotBahn.Common/Utilities/EnumUtil.cs b/source/DotBahn.Common/Utilities/EnumUtil.cs index 380b044..af067b9 100644 --- a/source/DotBahn.Common/Utilities/EnumUtil.cs +++ b/source/DotBahn.Common/Utilities/EnumUtil.cs @@ -5,14 +5,14 @@ namespace DotBahn.Common.Utilities; /// -/// Helpers for parsing enums to/from their string representation using contracts +/// Helpers for parsing enums to/from their string representation using contracts. /// public static class EnumUtil { /// /// Deserializes a JSON string value into an enum. - /// Returns when is null, empty, or not a valid member name /// - /// The enum type to parse + /// The enum type to parse. + /// Returns when is null, empty, or not a valid member name. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static TEnum Parse(string? value, TEnum defaultValue, JsonTypeInfo typeInfo) where TEnum : struct, Enum { if (string.IsNullOrEmpty(value)) { @@ -28,9 +28,9 @@ public static TEnum Parse(string? value, TEnum defaultValue, JsonTypeInfo /// /// Serializes an enum to its JSON string member name. - /// Returns null when is null /// - /// The enum type to format + /// The enum type to format. + /// Returns null when is null. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string? Format(TEnum? value, JsonTypeInfo typeInfo) where TEnum : struct, Enum => value == null ? null : JsonSerializer.Serialize(value.GetValueOrDefault(), typeInfo).Trim('"'); diff --git a/source/DotBahn.Common/Utilities/QueryParameters.cs b/source/DotBahn.Common/Utilities/QueryParameters.cs index 61ad00b..586a861 100644 --- a/source/DotBahn.Common/Utilities/QueryParameters.cs +++ b/source/DotBahn.Common/Utilities/QueryParameters.cs @@ -1,29 +1,29 @@ namespace DotBahn.Common.Utilities; /// -/// Helper class for building query string parameters in a fluent way +/// Helper class for building query string parameters in a fluent way. /// public class QueryParameters { private readonly Dictionary _parameters = []; /// - /// Creates a new instance of + /// Creates a new instance of . /// - /// A new instance + /// A new instance. public static QueryParameters Create() => new(); /// - /// Checks if any query parameters have been added + /// Checks if any query parameters have been added. /// - /// True if there is at least one parameter; otherwise, false + /// True if there is at least one parameter; otherwise, false. public bool Any() => _parameters.Count > 0; /// - /// Adds a key-value pair to the query parameters if the value is not null, empty, or whitespace + /// Adds a key-value pair to the query parameters if the value is not null, empty, or whitespace. /// - /// The query parameter key - /// The query parameter value - /// The current instance for fluent chaining + /// The query parameter key. + /// The query parameter value. + /// The current instance for fluent chaining. public QueryParameters Add(string key, string? value) { if (!string.IsNullOrWhiteSpace(value)) { _parameters[key] = value; @@ -33,12 +33,12 @@ public QueryParameters Add(string key, string? value) { } /// - /// Adds a key with multiple values to the query parameters as a comma-separated list + /// Adds a key with multiple values to the query parameters as a comma-separated list. /// - /// Type of the values - /// The query parameter key - /// The collection of values to add - /// The current instance for fluent chaining + /// Type of the values. + /// The query parameter key. + /// The collection of values to add. + /// The current instance for fluent chaining. public QueryParameters Add(string key, IEnumerable? values) { if (values == null) { return this; @@ -53,8 +53,8 @@ public QueryParameters Add(string key, IEnumerable? values) { } /// - /// Converts the added parameters into a URL-encoded query string + /// Converts the added parameters into a URL-encoded query string. /// - /// A URL-encoded query string (e.g., "key1=value1&key2=value2") or an empty string if no parameters exist + /// A URL-encoded query string (e.g., "key1=value1&key2=value2") or an empty string if no parameters exist. public string ToQueryString() => _parameters.Count == 0 ? string.Empty : string.Join("&", _parameters.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}")); } diff --git a/source/DotBahn.Common/packages.lock.json b/source/DotBahn.Common/packages.lock.json index a2d73e0..07af035 100644 --- a/source/DotBahn.Common/packages.lock.json +++ b/source/DotBahn.Common/packages.lock.json @@ -4,44 +4,33 @@ "net10.0": { "Microsoft.Extensions.Http": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "IDsXLGGz7nJMsqspWnErsP18WyAVf6V9Ixl4p47/8/95Jak3ZA1YWhQ0iesMVwubVhkVZGoO9m9ADUnK0m6HLw==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Options": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.NET.ILLink.Tasks": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "YlTamXppEQls6DYWt7RdUuwWDb0lyw/vXCaGeQpLCpsLmfwGuCkOz/vIGgMTV7ECsJcavkCOkxZXv9s8rdAHkQ==" - }, - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[10.0.403, )", - "resolved": "10.0.403", - "contentHash": "T4WYxWydJGNQRe/EgURFlhPZ1cHYgivrCCHSomCcfQzGzhkDYGNn5bUwwjs4/PHuMxsmGaLvPv2puG8lluA1IA==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "10.0.403", - "Microsoft.SourceLink.Common": "10.0.403", - "System.IO.Hashing": "10.0.14" - } + "requested": "[10.0.15, )", + "resolved": "10.0.15", + "contentHash": "u0WnRcZgBZYHlVFpbe/3Adpmb9rmNJ8/fmEwqc/xjB7fFppq+gfaLJd3Sdaw+J02zV0eP/T9dneQ3Dv5jWw6bw==" }, "MinVer": { "type": "Direct", @@ -49,116 +38,105 @@ "resolved": "8.0.0", "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" }, - "Microsoft.Build.Tasks.Git": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "1furteBFeemMmZ4s+ORjQb7YtO+wG63NJahbQbRUi91FV6V87BdV0U3vX1jbMC6iKSELYYoXWssSzLu3mx0i2w==", - "dependencies": { - "System.IO.Hashing": "10.0.14" - } - }, "Microsoft.Extensions.Configuration": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Binder": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" }, "Microsoft.Extensions.Diagnostics": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "80VqW8eKxQaxBOLDNpLUdxOlxzWn/jqBSxNBCfD8GCjcshNDpFvUgKh8uvvZwvkfBbwmNPWPWHyy9F+RLd1dlQ==", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" } }, "Microsoft.Extensions.Diagnostics.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vm+PPso6vOwGeX52MdOPh6z/R6KHgxQUwqq7k7Jc9jhy2JOxO2KB4xfoJQBBp2Ni8M4zKgJ4r2a1dgrYG7+MKw==", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Logging": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Logging.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Options.ConfigurationExtensions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4wcIU0rE04ejEfCwHTftu9O8fgH6CRYCe+tseRapikUBn1Kic3QdO7ku22SwFyLrzdWGYPUZMEgv57ZYuuc5gA==", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Primitives": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" - }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "SvzUeqFGrcQxlIgjmcoSGiV5UWcPa0NCTuH69/40uSDsSD/26c6p9cH7XLAxpn+I8+2Zhl1qp+WMugl0oOwBMg==" + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" }, - "System.IO.Hashing": { + "System.Diagnostics.DiagnosticSource": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "lVqovhCt3HlZe7ONG5ydaj6BYwYI004gldVfMMkJl/lR5ueeCtWNpW4nejOX75sPmzm8vXCxB69GqwHaYCnyUQ==" + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" } } } diff --git a/source/DotBahn.Facilities/DotBahn.Facilities.csproj b/source/DotBahn.Facilities/DotBahn.Facilities.csproj index a1419b2..874de34 100644 --- a/source/DotBahn.Facilities/DotBahn.Facilities.csproj +++ b/source/DotBahn.Facilities/DotBahn.Facilities.csproj @@ -17,5 +17,6 @@ + diff --git a/source/DotBahn.Facilities/FacilityClient.cs b/source/DotBahn.Facilities/FacilityClient.cs index 5cb0818..0ab0d97 100644 --- a/source/DotBahn.Facilities/FacilityClient.cs +++ b/source/DotBahn.Facilities/FacilityClient.cs @@ -11,7 +11,7 @@ namespace DotBahn.Facilities; /// -/// Client for accessing 'Deutsche Bahn FaSta'-API +/// Client for accessing 'Deutsche Bahn FaSta'-API. /// public class FacilityClient : ClientBase, IFacilityClient { private readonly IParser> _parser; @@ -21,12 +21,12 @@ public class FacilityClient : ClientBase, IFacilityClient { protected override string ApiName => "facilities"; /// - /// Client for accessing 'Deutsche Bahn FaSta'-API + /// Client for accessing 'Deutsche Bahn FaSta'-API. /// - /// The HTTP client used for requests - /// The provider used for retrieving access tokens - /// The parser for this contract type - /// The transformer for this model and contract types + /// The HTTP client used for requests. + /// The provider used for retrieving access tokens. + /// The parser for this contract type. + /// The transformer for this model and contract types. [ActivatorUtilitiesConstructor] internal FacilityClient(HttpClient http, IAuthorization authorization, IParser> parser, ITransformer, IEnumerable> transformer) : base(http, authorization) { @@ -35,23 +35,22 @@ internal FacilityClient(HttpClient http, IAuthorization authorization, IParser - /// Client for accessing 'Deutsche Bahn FaSta'-API + /// Client for accessing 'Deutsche Bahn FaSta'-API. /// /// /// Creates and owns its own . Dispose this instance to release it. - /// Use only when instantiating manually without a DI container + /// Use only when instantiating manually without a DI container. /// - /// The options for this instance - /// The auth credentials for the client - /// Thrown when is null - /// Thrown when is null + /// The options for this instance. + /// The auth credentials for the client. + /// Thrown when or is null. public FacilityClient(ClientOptions options, AuthorizationOptions auth) : base(options, auth) { _parser = new JsonParser>(FacilitiesJsonContext.Default.ListFacilityContract); _transformer = new FacilityTransformer(); } /// - /// Thrown when is null + /// Thrown when is null. public async Task> GetFacilitiesAsync(FacilityQuery query, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(query); diff --git a/source/DotBahn.Facilities/FacilityQuery.cs b/source/DotBahn.Facilities/FacilityQuery.cs index dbcc5e5..fb8655f 100644 --- a/source/DotBahn.Facilities/FacilityQuery.cs +++ b/source/DotBahn.Facilities/FacilityQuery.cs @@ -6,63 +6,63 @@ namespace DotBahn.Facilities; /// /// Represents the query parameters for searching facilities in stations. -/// Provides fluent methods for convenient building of queries +/// Provides fluent methods for convenient building of queries. /// public sealed record FacilityQuery { /// - /// Type of the facility + /// Type of the facility. /// public FacilityType? Type { get; set; } /// - /// State of the facility + /// State of the facility. /// public FacilityState? State { get; set; } /// - /// Equipment numbers to filter by + /// Equipment numbers to filter by. /// public IEnumerable EquipmentNumbers { get; set; } = []; /// - /// The station ID to filter facilities + /// The station ID to filter facilities. /// public string? StationId { get; set; } /// - /// Westernmost longitude in WGS84 decimal degrees for geographic bounding box filter + /// Westernmost longitude in WGS84 decimal degrees for geographic bounding box filter. /// - /// Must be used together with , , and + /// Must be used together with , , and . /// /// public double? LongitudeWest { get; set; } /// - /// Southernmost latitude in WGS84 decimal degrees for geographic bounding box filter + /// Southernmost latitude in WGS84 decimal degrees for geographic bounding box filter. /// - /// Must be used together with , , and + /// Must be used together with , , and . /// /// public double? LatitudeSouth { get; set; } /// - /// Easternmost longitude in WGS84 decimal degrees for geographic bounding box filter + /// Easternmost longitude in WGS84 decimal degrees for geographic bounding box filter. /// - /// Must be used together with , , and + /// Must be used together with , , and . /// /// public double? LongitudeEast { get; set; } /// - /// Northernmost latitude in WGS84 decimal degrees for geographic bounding box filter + /// Northernmost latitude in WGS84 decimal degrees for geographic bounding box filter. /// - /// Must be used together with , , and + /// Must be used together with , , and . /// /// public double? LatitudeNorth { get; set; } /// - /// Sets the facility type filter + /// Sets the facility type filter. /// public FacilityQuery WithType(FacilityType type) { Type = type; @@ -70,7 +70,7 @@ public FacilityQuery WithType(FacilityType type) { } /// - /// Sets the facility state filter + /// Sets the facility state filter. /// public FacilityQuery WithState(FacilityState state) { State = state; @@ -78,7 +78,7 @@ public FacilityQuery WithState(FacilityState state) { } /// - /// Filters facilities by one or more equipment numbers + /// Filters facilities by one or more equipment numbers. /// public FacilityQuery WithEquipmentNumbers(params string[] numbers) { EquipmentNumbers = numbers; @@ -86,7 +86,7 @@ public FacilityQuery WithEquipmentNumbers(params string[] numbers) { } /// - /// Filters facilities by station ID + /// Filters facilities by station ID. /// public FacilityQuery AtStation(int stationId) { StationId = stationId.ToString(); @@ -94,13 +94,13 @@ public FacilityQuery AtStation(int stationId) { } /// - /// Filters facilities within a geographic bounding box + /// Filters facilities within a geographic bounding box. /// - /// Westernmost longitude in WGS84 decimal degrees - /// Southernmost latitude in WGS84 decimal degrees - /// Easternmost longitude in WGS84 decimal degrees - /// Northernmost latitude in WGS84 decimal degrees - /// The current instance for fluent chaining + /// Westernmost longitude in WGS84 decimal degrees. + /// Southernmost latitude in WGS84 decimal degrees. + /// Easternmost longitude in WGS84 decimal degrees. + /// Northernmost latitude in WGS84 decimal degrees. + /// The current instance for fluent chaining. public FacilityQuery WithArea(double lngWest, double latSouth, double lngEast, double latNorth) { LongitudeWest = lngWest; LatitudeSouth = latSouth; @@ -110,7 +110,7 @@ public FacilityQuery WithArea(double lngWest, double latSouth, double lngEast, d } /// - /// Converts the query into for API calls + /// Converts the query into for API calls. /// internal QueryParameters ToQueryParameters() { var area = LongitudeWest.HasValue && LatitudeSouth.HasValue && LongitudeEast.HasValue && LatitudeNorth.HasValue diff --git a/source/DotBahn.Facilities/IFacilityClient.cs b/source/DotBahn.Facilities/IFacilityClient.cs index 04d250d..4b4aec9 100644 --- a/source/DotBahn.Facilities/IFacilityClient.cs +++ b/source/DotBahn.Facilities/IFacilityClient.cs @@ -3,15 +3,17 @@ namespace DotBahn.Facilities; /// -/// Client for accessing the 'Deutsche Bahn FaSta'-API +/// Client for accessing the 'Deutsche Bahn FaSta'-API. /// public interface IFacilityClient { /// - /// Finds facilities based on optional filter criteria + /// Finds facilities based on optional filter criteria. /// - /// The query to specify results with - /// Token to cancel the request - /// List of facilities matching the criteria - /// Thrown when non-success status codes occur + /// The query to specify results with. + /// Token to cancel the request. + /// List of facilities matching the criteria. + /// Thrown when is null. + /// Thrown when non-success status codes occur. + /// Thrown when the operation is canceled. Task> GetFacilitiesAsync(FacilityQuery query, CancellationToken ct = default); } diff --git a/source/DotBahn.Facilities/Internal/Contracts/FacilityContract.cs b/source/DotBahn.Facilities/Internal/Contracts/FacilityContract.cs index 11da588..ed7effa 100644 --- a/source/DotBahn.Facilities/Internal/Contracts/FacilityContract.cs +++ b/source/DotBahn.Facilities/Internal/Contracts/FacilityContract.cs @@ -4,60 +4,60 @@ namespace DotBahn.Facilities.Internal.Contracts; /// -/// Raw structure for a station facility (elevator or escalator) in the FaSta API +/// Raw structure for a station facility (elevator or escalator) in the FaSta API. /// [ExcludeFromCodeCoverage] internal record FacilityContract { /// - /// Gets the unique equipment number + /// Gets the unique equipment number. /// [JsonPropertyName("equipmentnumber")] public long EquipmentNumber { get; init; } /// - /// Gets the type of the facility (e.g., ELEVATOR, ESCALATOR) + /// Gets the type of the facility (e.g., ELEVATOR, ESCALATOR). /// [JsonPropertyName("type")] public string? Type { get; init; } /// - /// Gets the description of the facility + /// Gets the description of the facility. /// [JsonPropertyName("description")] public string? Description { get; init; } /// - /// Gets the current state of the facility (e.g., ACTIVE, INACTIVE, UNKNOWN) + /// Gets the current state of the facility (e.g., ACTIVE, INACTIVE, UNKNOWN). /// [JsonPropertyName("state")] public string? State { get; init; } /// - /// Gets an explanation for the current state + /// Gets an explanation for the current state. /// [JsonPropertyName("stateExplanation")] public string? StateExplanation { get; init; } /// - /// Gets the station number this facility belongs to + /// Gets the station number this facility belongs to. /// [JsonPropertyName("stationnumber")] public int StationNumber { get; init; } /// - /// Gets the longitude (X coordinate) + /// Gets the longitude (X coordinate). /// [JsonPropertyName("geocoordX")] public double? Longitude { get; init; } /// - /// Gets the latitude (Y coordinate) + /// Gets the latitude (Y coordinate). /// [JsonPropertyName("geocoordY")] public double? Latitude { get; init; } /// - /// Gets the name of the operator + /// Gets the name of the operator. /// [JsonPropertyName("operatorname")] public string? OperatorName { get; init; } diff --git a/source/DotBahn.Facilities/Internal/Json/FacilitiesJsonContext.cs b/source/DotBahn.Facilities/Internal/Json/FacilitiesJsonContext.cs index 6d42c34..4d74f9c 100644 --- a/source/DotBahn.Facilities/Internal/Json/FacilitiesJsonContext.cs +++ b/source/DotBahn.Facilities/Internal/Json/FacilitiesJsonContext.cs @@ -6,7 +6,7 @@ namespace DotBahn.Facilities.Internal.Json; /// -/// Source-generated JSON serialization metadata for facility contracts and enums +/// Source-generated JSON serialization metadata for facility contracts and enums. /// [ExcludeFromCodeCoverage] [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] diff --git a/source/DotBahn.Facilities/Internal/Transformers/FacilityTransformer.cs b/source/DotBahn.Facilities/Internal/Transformers/FacilityTransformer.cs index 06bbe4e..49c4f7d 100644 --- a/source/DotBahn.Facilities/Internal/Transformers/FacilityTransformer.cs +++ b/source/DotBahn.Facilities/Internal/Transformers/FacilityTransformer.cs @@ -9,7 +9,7 @@ namespace DotBahn.Facilities.Internal.Transformers; /// -/// Transforms facility contracts into domain models +/// Transforms facility contracts into domain models. /// internal sealed class FacilityTransformer : ITransformer, IEnumerable> { /// @@ -19,10 +19,10 @@ public IEnumerable Transform(IEnumerable contracts) } /// - /// Transforms the into its domain model + /// Transforms the into its domain model. /// - /// The contract to transform - /// The transformed model + /// The contract to transform. + /// The transformed model. private static Facility TransformFacility(FacilityContract contract) => new() { EquipmentNumber = contract.EquipmentNumber, Type = EnumUtil.Parse(contract.Type, FacilityType.Unknown, FacilitiesJsonContext.Default.FacilityType), diff --git a/source/DotBahn.Facilities/Models/Enumerations/FacilityState.cs b/source/DotBahn.Facilities/Models/Enumerations/FacilityState.cs index a12452a..37c2f84 100644 --- a/source/DotBahn.Facilities/Models/Enumerations/FacilityState.cs +++ b/source/DotBahn.Facilities/Models/Enumerations/FacilityState.cs @@ -4,24 +4,24 @@ namespace DotBahn.Facilities.Models.Enumerations; /// -/// Represents the operational state of a facility +/// Represents the operational state of a facility. /// [JsonConverter(typeof(JsonStringEnumConverter))] public enum FacilityState { /// - /// Facility is active and operational + /// Facility is active and operational. /// [JsonStringEnumMemberName("ACTIVE")] Active, /// - /// Facility is inactive or out of service + /// Facility is inactive or out of service. /// [JsonStringEnumMemberName("INACTIVE")] Inactive, /// - /// Facility state is unknown or not specified + /// Facility state is unknown or not specified. /// [JsonStringEnumMemberName("UNKNOWN")] Unknown diff --git a/source/DotBahn.Facilities/Models/Enumerations/FacilityType.cs b/source/DotBahn.Facilities/Models/Enumerations/FacilityType.cs index e33975b..b1e3c48 100644 --- a/source/DotBahn.Facilities/Models/Enumerations/FacilityType.cs +++ b/source/DotBahn.Facilities/Models/Enumerations/FacilityType.cs @@ -3,24 +3,24 @@ namespace DotBahn.Facilities.Models.Enumerations; /// -/// Represents the type of facility in a station +/// Represents the type of facility in a station. /// [JsonConverter(typeof(JsonStringEnumConverter))] public enum FacilityType { /// - /// Elevator facility + /// Elevator facility. /// [JsonStringEnumMemberName("ELEVATOR")] Elevator, /// - /// Escalator facility + /// Escalator facility. /// [JsonStringEnumMemberName("ESCALATOR")] Escalator, /// - /// There is no further information available + /// There is no further information available. /// Unknown } diff --git a/source/DotBahn.Facilities/Models/Facility.cs b/source/DotBahn.Facilities/Models/Facility.cs index fdfb223..f7318d2 100644 --- a/source/DotBahn.Facilities/Models/Facility.cs +++ b/source/DotBahn.Facilities/Models/Facility.cs @@ -4,46 +4,46 @@ namespace DotBahn.Facilities.Models; /// -/// A station facility such as an elevator or escalator with operational status information +/// A station facility such as an elevator or escalator with operational status information. /// public class Facility { /// - /// Unique equipment number assigned by Deutsche Bahn + /// Unique equipment number assigned by Deutsche Bahn. /// public required long EquipmentNumber { get; init; } /// - /// Type of facility (elevator or escalator) + /// Type of facility (elevator or escalator). /// public required FacilityType Type { get; init; } /// - /// Human-readable description of the facility location and purpose + /// Human-readable description of the facility location and purpose. /// public string? Description { get; init; } /// - /// Current operational state of the facility + /// Current operational state of the facility. /// public required FacilityState State { get; init; } /// - /// Explanation for the current state, typically provided when the facility is inactive + /// Explanation for the current state, typically provided when the facility is inactive. /// public string? StateExplanation { get; init; } /// - /// Station number this facility belongs to + /// Station number this facility belongs to. /// public required int StationNumber { get; init; } /// - /// Geographic coordinates of the facility within the station + /// Geographic coordinates of the facility within the station. /// public required Coordinates Coordinates { get; init; } /// - /// Name of the operator responsible for maintaining this facility + /// Name of the operator responsible for maintaining this facility. /// public string? OperatorName { get; init; } } diff --git a/source/DotBahn.Facilities/ServiceCollectionExtensions.cs b/source/DotBahn.Facilities/ServiceCollectionExtensions.cs index eaef2ee..6174928 100644 --- a/source/DotBahn.Facilities/ServiceCollectionExtensions.cs +++ b/source/DotBahn.Facilities/ServiceCollectionExtensions.cs @@ -12,19 +12,18 @@ namespace DotBahn.Facilities; /// -/// Extension methods for registering the DotBahn Facilities client +/// Extension methods for registering the DotBahn Facilities client. /// public static class ServiceCollectionExtensions { private const string OptionsName = "DotBahn.Facilities"; - private static readonly Uri DefaultFacilitiesEndpoint = new("https://apis.deutschebahn.com/db-api-marketplace/apis/fasta/v2/"); /// - /// Registers the with its parser and transformer services + /// Registers the with its parser and transformer services. /// - /// The service collection to add to - /// Optional action to override default client options - /// The service collection for chaining + /// The service collection to add to. + /// Optional action to override default client options. + /// The service collection for chaining. public static IServiceCollection AddDotBahnFacilities(this IServiceCollection services, Action? configuration = null) { services.AddOptions(OptionsName) .Configure(opts => { @@ -37,7 +36,7 @@ public static IServiceCollection AddDotBahnFacilities(this IServiceCollection se services.AddHttpClient(OptionsName, (http, sp) => { var options = sp.GetRequiredService>().Get(OptionsName); http.BaseAddress = options.BaseEndpoint; - http.DefaultRequestHeaders.UserAgent.ParseAdd("DotBahn/2.0 (+https://github.com/rlvelte/dotbahn)"); + http.DefaultRequestHeaders.UserAgent.ParseAdd("DotBahn/2.X (+https://github.com/rlvelte/dotbahn)"); var auth = sp.GetRequiredService(); var parser = sp.GetRequiredService>>(); diff --git a/source/DotBahn.Facilities/packages.lock.json b/source/DotBahn.Facilities/packages.lock.json index 55c79b9..1f3715b 100644 --- a/source/DotBahn.Facilities/packages.lock.json +++ b/source/DotBahn.Facilities/packages.lock.json @@ -4,55 +4,44 @@ "net10.0": { "Microsoft.Extensions.Http": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "IDsXLGGz7nJMsqspWnErsP18WyAVf6V9Ixl4p47/8/95Jak3ZA1YWhQ0iesMVwubVhkVZGoO9m9ADUnK0m6HLw==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Http.Resilience": { "type": "Direct", - "requested": "[10.11.0, )", - "resolved": "10.11.0", - "contentHash": "6/YEoPCcQLzExm4x4FH5c38JffbhkMaTtXsrDmYNozt9KRtdXK3TsDeuKSBZJno+41oIDGBONb2up0zCsuEERw==", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "5VawCrg+VgVT2hNurSSEWUnq0pvNoH+Zt82s5Wpl/8jdnmU8DpRlr+M3DcdtVgeBG7mRyk3GtSRbf8PB/HrL3w==", "dependencies": { - "Microsoft.Extensions.Http.Diagnostics": "10.11.0", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Resilience": "10.11.0" + "Microsoft.Extensions.Http.Diagnostics": "11.0.1", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Resilience": "11.0.1" } }, "Microsoft.Extensions.Options": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.NET.ILLink.Tasks": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "YlTamXppEQls6DYWt7RdUuwWDb0lyw/vXCaGeQpLCpsLmfwGuCkOz/vIGgMTV7ECsJcavkCOkxZXv9s8rdAHkQ==" - }, - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[10.0.403, )", - "resolved": "10.0.403", - "contentHash": "T4WYxWydJGNQRe/EgURFlhPZ1cHYgivrCCHSomCcfQzGzhkDYGNn5bUwwjs4/PHuMxsmGaLvPv2puG8lluA1IA==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "10.0.403", - "Microsoft.SourceLink.Common": "10.0.403", - "System.IO.Hashing": "10.0.14" - } + "requested": "[10.0.15, )", + "resolved": "10.0.15", + "contentHash": "u0WnRcZgBZYHlVFpbe/3Adpmb9rmNJ8/fmEwqc/xjB7fFppq+gfaLJd3Sdaw+J02zV0eP/T9dneQ3Dv5jWw6bw==" }, "MinVer": { "type": "Direct", @@ -60,232 +49,231 @@ "resolved": "8.0.0", "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" }, - "Microsoft.Build.Tasks.Git": { + "Microsoft.Extensions.AmbientMetadata.Application": { "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "1furteBFeemMmZ4s+ORjQb7YtO+wG63NJahbQbRUi91FV6V87BdV0U3vX1jbMC6iKSELYYoXWssSzLu3mx0i2w==", + "resolved": "11.0.1", + "contentHash": "tm28s2ODWZ6RdysP06NI3B23DUY5OfHG35ihMHxVAO3hywZAczDVjrkYMfBY//J4HQqfDHS5op84BhnF7ROseQ==", "dependencies": { - "System.IO.Hashing": "10.0.14" + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, - "Microsoft.Extensions.AmbientMetadata.Application": { + "Microsoft.Extensions.Compliance.Abstractions": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "aMCm7C6CexZT8W/p8zRp4BoxSnqRs3MmkBF7FvPIXC92b7vqs2SL0J+mVJi5W2Mk9Vb4ZRFWe9sdzFew6zUl1w==", + "resolved": "11.0.1", + "contentHash": "DUwdXgIxJKH9zBNg/SUBqOX0FpXCq7w80CIzrr0Jcw5tBXS926AtCcidoAsEHq5e/c6KQ8rWhSt7NxFxak8N/Q==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15" } }, - "Microsoft.Extensions.Compliance.Abstractions": { + "Microsoft.Extensions.Compliance.Redaction": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2mjAb3Sm5k6uNeI+IyXpggYMpfdDDGgZSwUm9QQsm5QgZboJWbm2eU+6wNMrlfFEao11yq6JS1zXI7SVQQ0NuQ==", + "resolved": "11.0.1", + "contentHash": "2rwe98yZEn4+aXjAg5DdcROMg6m2w3tejf/mRk4/fBCHKM2EWCaFTmbHLtz1BfyBxMY00/08XFoN0wzWYNiSiQ==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13" + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, "Microsoft.Extensions.Configuration": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Binder": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" }, "Microsoft.Extensions.DependencyInjection.AutoActivation": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "h/sovspxVmT2DTIbWORMG0Gi3zVcPQzNl3kbwtpo0LoUXYbe2+66wQqZYwaF2ZWKN8HDdHv5yoc7d0DbDBBlnA==", + "resolved": "11.0.1", + "contentHash": "OuVIF5TmsfonN2Fqmi2zlUtbFQNqQiflhgo/rh64ptrqYrB4wZLwKbXr/HzrQXMf+h3jIbWrjIdJFspGqcvuuQ==", "dependencies": { - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13" + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15" } }, "Microsoft.Extensions.Diagnostics": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "80VqW8eKxQaxBOLDNpLUdxOlxzWn/jqBSxNBCfD8GCjcshNDpFvUgKh8uvvZwvkfBbwmNPWPWHyy9F+RLd1dlQ==", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" } }, "Microsoft.Extensions.Diagnostics.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vm+PPso6vOwGeX52MdOPh6z/R6KHgxQUwqq7k7Jc9jhy2JOxO2KB4xfoJQBBp2Ni8M4zKgJ4r2a1dgrYG7+MKw==", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "Dp/FaAPo3U9h3HsWT1dcdRRV//rm+MQF5iKpY/WxL5swwV+wZNE5eyJZ0kgy9Upl/kHz4ejpiLMloxDIuJaoJQ==", + "resolved": "11.0.1", + "contentHash": "mqqpmAFNRLa4cozN3RvT/T81k4aarwMc8xb8VVQgLqUE7AAoN/WWayZAvP+4hy9+KujP3dfn3taU06fZJPIbgA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13" + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" } }, "Microsoft.Extensions.FileProviders.Abstractions": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "BZDwtN3uoWRghDi5lRRZPDjMMCg2Ds7J6YEYjqka/TLjqnzquEpXyvchrIMeoubwT1ns23ow6PPeAoBHJO81Rw==", + "resolved": "10.0.15", + "contentHash": "1RSYAUtJeb76m2T0u5BbvwKY3s+ge9fT3cj1odvo5Bm+frc7pU9RSeXeMIlYHV8GjpqLdv2neeeomz010yYL8A==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.13" + "Microsoft.Extensions.Primitives": "10.0.15" } }, "Microsoft.Extensions.Hosting.Abstractions": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "zIrbe9vkIFXxW3mOApIOWXw+xMwX7Cgsptr3ZSlglJt4hW2qp4fB/JU1NHgAevteBNH4PicvU9DsFPHxlnnloA==", + "resolved": "10.0.15", + "contentHash": "s/JBiwR3F/vKRCbe6WO5b6t6or1ISaZ3rllchcw6/FSWZmK8s2fAzD7elrZo7592FnMD1fhGoG/wuJL1YYtVXw==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13" + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15" } }, "Microsoft.Extensions.Http.Diagnostics": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "iFcxcuMF/21LO+tDqDyzYVvokJUH03cNalmOJhmjyQSMV3dR4JAgcUBTV1iVH/yruC8wG2RNjvW0xcUgYqmrGg==", + "resolved": "11.0.1", + "contentHash": "mKHY0oFYL3fkAOhBNi2LqWPuEdUJ+HiF28KKUwBkQG2sgXAUdFDDqvJAfu2PcYgtAwsAtl58zuk4SElpPzbCvA==", "dependencies": { - "Microsoft.Extensions.Http": "10.0.13", - "Microsoft.Extensions.Telemetry": "10.11.0" + "Microsoft.Extensions.Compliance.Redaction": "11.0.1", + "Microsoft.Extensions.Http": "10.0.15", + "Microsoft.Extensions.Telemetry": "11.0.1" } }, "Microsoft.Extensions.Logging": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Logging.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Logging.Configuration": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "OyYJOaE9WbBx1Hp+Dd2zrqeFM0JwH5M/x0VL6tNUv3V18vIAVpix8UjhvY9eW/iXpguEHy68JO/Z9YkBOwftIw==", + "resolved": "10.0.15", + "contentHash": "Km6Ml1/nu0T/f80Btonxf9CWmP/BXI84aJwC5fUbCxRArJ0lH++0ADQrjErZvsSIrKhusTkTSGBChKy2fYAF4w==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.Configuration.Binder": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Configuration.Binder": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, "Microsoft.Extensions.ObjectPool": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "NX3bhcc0WitPKAVc9Zfi8jeEPClhfEmobUJM4a4bkWhJcBt5IWg6lCrItUoFy4whLjU+atXktURYCweQlR7wfg==" + "resolved": "10.0.15", + "contentHash": "kvd9eyRRQ+OEu9wik7GKgTS+7XnJ5XoOtSXJqmkJtVYV/S4gsBUrobYRSdNeBcb0ymef4L5Q9pZGiTxJ8jJfyQ==" }, "Microsoft.Extensions.Options.ConfigurationExtensions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4wcIU0rE04ejEfCwHTftu9O8fgH6CRYCe+tseRapikUBn1Kic3QdO7ku22SwFyLrzdWGYPUZMEgv57ZYuuc5gA==", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Primitives": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" }, "Microsoft.Extensions.Resilience": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "GbN7R2BOoZf3F7aK02nz9kWf6ttbvVzpw1orGG30VmrKTmRV6pasQOCfF2fjKXyHIMC/lAiBEYHCKjgf0OiGvQ==", + "resolved": "11.0.1", + "contentHash": "xgKof6iwAByZNrxWOa7Drk4A953L7U2HleTmx7EXE2Vf6j1crp4RsvNlIVsJMtHKf3ftGKd9gOhR3xES9vxUgg==", "dependencies": { - "Microsoft.Extensions.Diagnostics": "10.0.13", - "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "10.11.0", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0", + "Microsoft.Extensions.Diagnostics": "10.0.15", + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1", "Polly.Extensions": "8.4.2", "Polly.RateLimiting": "8.4.2" } }, "Microsoft.Extensions.Telemetry": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2meCfABvkLPtEBBwGzItIGnhrex1AEn2N+dHvxB5UoozeX/xTtBuUz5BRdjNI5oNgd5T31kC69WWw3BHDc9iZA==", + "resolved": "11.0.1", + "contentHash": "9uuA8entTC9m00m59h6CACSt4IQh9KknB+hPvCteXUTiG67lqJ8BI65fEUJSPSfT3ZDDi01Zg2aY5kRUvD4HPw==", "dependencies": { - "Microsoft.Extensions.AmbientMetadata.Application": "10.11.0", - "Microsoft.Extensions.DependencyInjection.AutoActivation": "10.11.0", - "Microsoft.Extensions.Logging.Configuration": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0" + "Microsoft.Extensions.AmbientMetadata.Application": "11.0.1", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "11.0.1", + "Microsoft.Extensions.Logging.Configuration": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1" } }, "Microsoft.Extensions.Telemetry.Abstractions": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "FzcHRan/C2g5X5KD0kPlL4tTROFRpM8sqcXfOIi6FGLsw/d2yoOYMbLJ5hyb8N5QgOVW7e1TdwEN4zVUfcwfdw==", + "resolved": "11.0.1", + "contentHash": "qINZz4G01Wxumqd0hLr6YdzPa3s7jexQWN28EenaiJQnmKdsR9FnBaKENdRRElLc+A5bJKQ+jYw/WHG4ZpIyAg==", "dependencies": { - "Microsoft.Extensions.Compliance.Abstractions": "10.11.0", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13" + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15" } }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "SvzUeqFGrcQxlIgjmcoSGiV5UWcPa0NCTuH69/40uSDsSD/26c6p9cH7XLAxpn+I8+2Zhl1qp+WMugl0oOwBMg==" - }, "Polly.Core": { "type": "Transitive", "resolved": "8.4.2", @@ -310,10 +298,10 @@ "System.Threading.RateLimiting": "8.0.0" } }, - "System.IO.Hashing": { + "System.Diagnostics.DiagnosticSource": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "lVqovhCt3HlZe7ONG5ydaj6BYwYI004gldVfMMkJl/lR5ueeCtWNpW4nejOX75sPmzm8vXCxB69GqwHaYCnyUQ==" + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" }, "System.Threading.RateLimiting": { "type": "Transitive", @@ -323,8 +311,8 @@ "dotbahn.common": { "type": "Project", "dependencies": { - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Options": "[10.0.14, )" + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" } } } diff --git a/source/DotBahn.Stations/DotBahn.Stations.csproj b/source/DotBahn.Stations/DotBahn.Stations.csproj index 30db83e..0f8e0fe 100644 --- a/source/DotBahn.Stations/DotBahn.Stations.csproj +++ b/source/DotBahn.Stations/DotBahn.Stations.csproj @@ -17,5 +17,6 @@ + diff --git a/source/DotBahn.Stations/IStationClient.cs b/source/DotBahn.Stations/IStationClient.cs index d1e99f7..f5758de 100644 --- a/source/DotBahn.Stations/IStationClient.cs +++ b/source/DotBahn.Stations/IStationClient.cs @@ -3,15 +3,17 @@ namespace DotBahn.Stations; /// -/// Client for accessing the 'Deutsche Bahn StaDa'-API +/// Client for accessing the 'Deutsche Bahn StaDa'-API. /// public interface IStationClient { /// - /// Searches for stations using a query structure + /// Searches for stations using a query structure. /// - /// The query to specify results with - /// Token to cancel the request - /// List of stations matching the search criteria - /// Thrown when non-success status codes occur + /// The query to specify results with. + /// Token to cancel the request. + /// List of stations matching the search criteria. + /// Thrown when is null. + /// Thrown when non-success status codes occur. + /// Thrown when the operation is canceled. Task> GetStationsAsync(StationQuery query, CancellationToken ct = default); } diff --git a/source/DotBahn.Stations/Internal/Contracts/EvaNumberContract.cs b/source/DotBahn.Stations/Internal/Contracts/EvaNumberContract.cs index 089ff36..061b7d9 100644 --- a/source/DotBahn.Stations/Internal/Contracts/EvaNumberContract.cs +++ b/source/DotBahn.Stations/Internal/Contracts/EvaNumberContract.cs @@ -5,25 +5,25 @@ namespace DotBahn.Stations.Internal.Contracts; /// -/// Raw structure for an EVA number +/// Raw structure for an EVA number. /// [ExcludeFromCodeCoverage] internal record EvaNumberContract { /// - /// Gets the EVA number + /// Gets the EVA number. /// [JsonPropertyName("number")] public long Number { get; init; } /// - /// Gets a value indicating whether this is the main EVA number + /// Gets a value indicating whether this is the main EVA number. /// [JsonConverter(typeof(BahnDialectJsonConverter))] [JsonPropertyName("isMain")] public bool IsMain { get; init; } /// - /// Gets the geographic coordinates + /// Gets the geographic coordinates. /// [JsonPropertyName("geographicCoordinates")] public GeographicCoordinatesContract? GeographicCoordinates { get; init; } diff --git a/source/DotBahn.Stations/Internal/Contracts/GeographicCoordinatesContract.cs b/source/DotBahn.Stations/Internal/Contracts/GeographicCoordinatesContract.cs index 25720d0..db0ba55 100644 --- a/source/DotBahn.Stations/Internal/Contracts/GeographicCoordinatesContract.cs +++ b/source/DotBahn.Stations/Internal/Contracts/GeographicCoordinatesContract.cs @@ -4,18 +4,18 @@ namespace DotBahn.Stations.Internal.Contracts; /// -/// Raw structure for geographic coordinates +/// Raw structure for geographic coordinates. /// [ExcludeFromCodeCoverage] internal record GeographicCoordinatesContract { /// - /// Gets the type + /// Gets the type. /// [JsonPropertyName("type")] public string Type { get; init; } = string.Empty; /// - /// Gets the coordinates + /// Gets the coordinates. /// [JsonPropertyName("coordinates")] public List Coordinates { get; init; } = []; diff --git a/source/DotBahn.Stations/Internal/Contracts/MailingAddressContract.cs b/source/DotBahn.Stations/Internal/Contracts/MailingAddressContract.cs index b41cf4c..d91033b 100644 --- a/source/DotBahn.Stations/Internal/Contracts/MailingAddressContract.cs +++ b/source/DotBahn.Stations/Internal/Contracts/MailingAddressContract.cs @@ -4,24 +4,24 @@ namespace DotBahn.Stations.Internal.Contracts; /// -/// Raw structure for the mailing address of a station +/// Raw structure for the mailing address of a station. /// [ExcludeFromCodeCoverage] internal record MailingAddressContract { /// - /// Gets the city + /// Gets the city. /// [JsonPropertyName("city")] public string City { get; init; } = string.Empty; /// - /// Gets the zip code + /// Gets the zip code. /// [JsonPropertyName("zipcode")] public string ZipCode { get; init; } = string.Empty; /// - /// Gets the street + /// Gets the street. /// [JsonPropertyName("street")] public string Street { get; init; } = string.Empty; diff --git a/source/DotBahn.Stations/Internal/Contracts/RegionalAreaContract.cs b/source/DotBahn.Stations/Internal/Contracts/RegionalAreaContract.cs index aa92f2c..fc5c12a 100644 --- a/source/DotBahn.Stations/Internal/Contracts/RegionalAreaContract.cs +++ b/source/DotBahn.Stations/Internal/Contracts/RegionalAreaContract.cs @@ -4,24 +4,24 @@ namespace DotBahn.Stations.Internal.Contracts; /// -/// Raw structure for a regional area of the Deutsche Bahn +/// Raw structure for a regional area of the Deutsche Bahn. /// [ExcludeFromCodeCoverage] internal record RegionalAreaContract { /// - /// Gets the number of the regional area + /// Gets the number of the regional area. /// [JsonPropertyName("number")] public int Number { get; init; } /// - /// Gets the name of the regional area + /// Gets the name of the regional area. /// [JsonPropertyName("name")] public string Name { get; init; } = string.Empty; /// - /// Gets the short name of the regional area + /// Gets the short name of the regional area. /// [JsonPropertyName("shortName")] public string ShortName { get; init; } = string.Empty; diff --git a/source/DotBahn.Stations/Internal/Contracts/Ril100IdentifierContract.cs b/source/DotBahn.Stations/Internal/Contracts/Ril100IdentifierContract.cs index 1f281be..993a7ce 100644 --- a/source/DotBahn.Stations/Internal/Contracts/Ril100IdentifierContract.cs +++ b/source/DotBahn.Stations/Internal/Contracts/Ril100IdentifierContract.cs @@ -10,13 +10,13 @@ namespace DotBahn.Stations.Internal.Contracts; [ExcludeFromCodeCoverage] internal record Ril100IdentifierContract { /// - /// Gets the Ril identifier + /// Gets the Ril identifier. /// [JsonPropertyName("rilIdentifier")] public string RilIdentifier { get; init; } = string.Empty; /// - /// Gets a value indicating whether this is the main identifier + /// Gets a value indicating whether this is the main identifier. /// [JsonConverter(typeof(BahnDialectJsonConverter))] [JsonPropertyName("isMain")] diff --git a/source/DotBahn.Stations/Internal/Contracts/StationContract.cs b/source/DotBahn.Stations/Internal/Contracts/StationContract.cs index 5bbf903..86f2201 100644 --- a/source/DotBahn.Stations/Internal/Contracts/StationContract.cs +++ b/source/DotBahn.Stations/Internal/Contracts/StationContract.cs @@ -5,117 +5,117 @@ namespace DotBahn.Stations.Internal.Contracts; /// -/// Raw structure for a station in the StaDa API +/// Raw structure for a station in the StaDa API. /// [ExcludeFromCodeCoverage] internal record StationContract { /// - /// Gets the station number + /// Gets the station number. /// [JsonPropertyName("number")] public int Number { get; init; } /// - /// Gets the station name + /// Gets the station name. /// [JsonPropertyName("name")] public string Name { get; init; } = string.Empty; /// - /// Gets the mailing address + /// Gets the mailing address. /// [JsonPropertyName("mailingAddress")] public MailingAddressContract? MailingAddress { get; init; } /// - /// Gets the regional area + /// Gets the regional area. /// [JsonPropertyName("regionalBereich")] public RegionalAreaContract? RegionalArea { get; init; } /// - /// Gets the Ril100 identifiers + /// Gets the Ril100 identifiers. /// [JsonPropertyName("ril100Identifiers")] public List Ril100Identifiers { get; init; } = []; /// - /// Gets the EVA numbers + /// Gets the EVA numbers. /// [JsonPropertyName("evaNumbers")] public List EvaNumbers { get; init; } = []; /// - /// Gets the category + /// Gets the category. /// [JsonPropertyName("category")] public int Category { get; init; } /// - /// Gets a value indicating whether the station has parking + /// Gets a value indicating whether the station has parking. /// [JsonConverter(typeof(BahnDialectJsonConverter))] [JsonPropertyName("hasParking")] public bool HasParking { get; init; } /// - /// Gets a value indicating whether the station has bicycle parking + /// Gets a value indicating whether the station has bicycle parking. /// [JsonConverter(typeof(BahnDialectJsonConverter))] [JsonPropertyName("hasBicycleParking")] public bool HasBicycleParking { get; init; } /// - /// Gets a value indicating whether the station has public facilities + /// Gets a value indicating whether the station has public facilities. /// [JsonConverter(typeof(BahnDialectJsonConverter))] [JsonPropertyName("hasPublicFacilities")] public bool HasPublicFacilities { get; init; } /// - /// Gets a value indicating whether the station has a locker system + /// Gets a value indicating whether the station has a locker system. /// [JsonConverter(typeof(BahnDialectJsonConverter))] [JsonPropertyName("hasLockerSystem")] public bool HasLockerSystem { get; init; } /// - /// Gets a value indicating whether the station has step-free access + /// Gets a value indicating whether the station has step-free access. /// [JsonConverter(typeof(BahnDialectJsonConverter))] [JsonPropertyName("hasStepFreeAccess")] public bool HasStepFreeAccess { get; init; } /// - /// Gets a value indicating whether the station has a travel center + /// Gets a value indicating whether the station has a travel center. /// [JsonConverter(typeof(BahnDialectJsonConverter))] [JsonPropertyName("hasTravelCenter")] public bool HasTravelCenter { get; init; } /// - /// Gets a value indicating whether the station has travel necessities + /// Gets a value indicating whether the station has travel necessities. /// [JsonConverter(typeof(BahnDialectJsonConverter))] [JsonPropertyName("hasTravelNecessities")] public bool HasTravelNecessities { get; init; } /// - /// Gets a value indicating whether the station has stepless access + /// Gets a value indicating whether the station has stepless access. /// [JsonConverter(typeof(BahnDialectJsonConverter))] [JsonPropertyName("hasSteplessAccess")] public bool HasSteplessAccess { get; init; } /// - /// Gets a value indicating whether the station has mobility service + /// Gets a value indicating whether the station has mobility service. /// [JsonConverter(typeof(BahnDialectJsonConverter))] [JsonPropertyName("hasMobilityService")] public bool HasMobilityService { get; init; } /// - /// Gets a value indicating whether the station has WiFi + /// Gets a value indicating whether the station has WiFi. /// [JsonConverter(typeof(BahnDialectJsonConverter))] [JsonPropertyName("hasWiFi")] diff --git a/source/DotBahn.Stations/Internal/Contracts/StationsResponseContract.cs b/source/DotBahn.Stations/Internal/Contracts/StationsResponseContract.cs index 153508d..9459e4c 100644 --- a/source/DotBahn.Stations/Internal/Contracts/StationsResponseContract.cs +++ b/source/DotBahn.Stations/Internal/Contracts/StationsResponseContract.cs @@ -4,30 +4,30 @@ namespace DotBahn.Stations.Internal.Contracts; /// -/// Raw structure for the response containing a list of stations +/// Raw structure for the response containing a list of stations. /// [ExcludeFromCodeCoverage] internal record StationsResponseContract { /// - /// Gets the offset + /// Gets the offset. /// [JsonPropertyName("offset")] public int Offset { get; init; } /// - /// Gets the limit + /// Gets the limit. /// [JsonPropertyName("limit")] public int Limit { get; init; } /// - /// Gets the total number of items + /// Gets the total number of items. /// [JsonPropertyName("total")] public int Total { get; init; } /// - /// Gets the list of stations + /// Gets the list of stations. /// [JsonPropertyName("result")] public List Stations { get; init; } = []; diff --git a/source/DotBahn.Stations/Internal/Json/StationsJsonContext.cs b/source/DotBahn.Stations/Internal/Json/StationsJsonContext.cs index 34f32dd..b9217bc 100644 --- a/source/DotBahn.Stations/Internal/Json/StationsJsonContext.cs +++ b/source/DotBahn.Stations/Internal/Json/StationsJsonContext.cs @@ -6,7 +6,7 @@ namespace DotBahn.Stations.Internal.Json; /// -/// Source-generated JSON serialization metadata for station contracts and enums +/// Source-generated JSON serialization metadata for station contracts and enums. /// [ExcludeFromCodeCoverage] [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] diff --git a/source/DotBahn.Stations/Internal/Transformers/StationTransformer.cs b/source/DotBahn.Stations/Internal/Transformers/StationTransformer.cs index 731ac34..4d7f30a 100644 --- a/source/DotBahn.Stations/Internal/Transformers/StationTransformer.cs +++ b/source/DotBahn.Stations/Internal/Transformers/StationTransformer.cs @@ -7,7 +7,7 @@ namespace DotBahn.Stations.Internal.Transformers; /// -/// Transforms station contracts into domain models +/// Transforms station contracts into domain models. /// internal sealed class StationTransformer : ITransformer, StationsResponseContract> { /// @@ -17,10 +17,10 @@ public IEnumerable Transform(StationsResponseContract contracts) { } /// - /// Transforms the into its domain model + /// Transforms the into its domain model. /// - /// The contract to transform - /// The transformed model + /// The contract to transform. + /// The transformed model. private static Station TransformStation(StationContract contract) => new() { Number = contract.Number, Name = contract.Name, @@ -33,18 +33,18 @@ public IEnumerable Transform(StationsResponseContract contracts) { }; /// - /// Transforms the category number into the enum + /// Transforms the category number into the enum. /// - /// The category number (1-7) - /// The corresponding station category + /// The category number (1-7). + /// The corresponding station category. private static StationCategory TransformCategory(int category) => category is >= 1 and <= 7 ? (StationCategory)category : StationCategory.Unknown; /// - /// Transforms the into its domain model + /// Transforms the into its domain model. /// - /// The contract to transform - /// The transformed model, or null if the contract is null + /// The contract to transform. + /// The transformed model, or null if the contract is null. private static StationAddress? TransformAddress(MailingAddressContract? contract) { if (contract == null) { return null; @@ -58,10 +58,10 @@ private static StationCategory TransformCategory(int category) => } /// - /// Transforms the into its domain model + /// Transforms the into its domain model. /// - /// The contract to transform - /// The transformed model, or null if the contract is null + /// The contract to transform. + /// The transformed model, or null if the contract is null. private static RegionalArea? TransformRegionalArea(RegionalAreaContract? contract) { if (contract == null) { return null; @@ -75,20 +75,20 @@ private static StationCategory TransformCategory(int category) => } /// - /// Transforms the into its domain model + /// Transforms the into its domain model. /// - /// The contract to transform - /// The transformed model + /// The contract to transform. + /// The transformed model. private static Ril100Identifier TransformRil100Identifier(Ril100IdentifierContract contract) => new() { Identifier = contract.RilIdentifier, IsMain = contract.IsMain }; /// - /// Transforms the into its domain model + /// Transforms the into its domain model. /// - /// The contract to transform - /// The transformed model + /// The contract to transform. + /// The transformed model. private static EvaNumber TransformEvaNumber(EvaNumberContract contract) => new() { Number = contract.Number, IsMain = contract.IsMain, @@ -96,10 +96,10 @@ private static StationCategory TransformCategory(int category) => }; /// - /// Transforms the into its domain model + /// Transforms the into its domain model. /// - /// The contract to transform - /// The transformed model, or null if the contract is null or has insufficient coordinates + /// The contract to transform. + /// The transformed model, or null if the contract is null or has insufficient coordinates. private static Coordinates? TransformCoordinates(GeographicCoordinatesContract? contract) { if (contract?.Coordinates == null || contract.Coordinates.Count < 2) { return null; @@ -112,10 +112,10 @@ private static StationCategory TransformCategory(int category) => } /// - /// Transforms the service flags from the into a model + /// Transforms the service flags from the into a model. /// - /// The station contract containing service flags - /// The transformed services model + /// The station contract containing service flags. + /// The transformed services model. private static StationServices TransformServices(StationContract contract) => new() { HasParking = contract.HasParking, HasBicycleParking = contract.HasBicycleParking, diff --git a/source/DotBahn.Stations/Models/Enumerations/FederalState.cs b/source/DotBahn.Stations/Models/Enumerations/FederalState.cs index 2bdada6..8cb213d 100644 --- a/source/DotBahn.Stations/Models/Enumerations/FederalState.cs +++ b/source/DotBahn.Stations/Models/Enumerations/FederalState.cs @@ -3,108 +3,108 @@ namespace DotBahn.Stations.Models.Enumerations; /// -/// Represents the federal states of Germany +/// Represents the federal states of Germany. /// [JsonConverter(typeof(JsonStringEnumConverter))] public enum FederalState { /// - /// State of Baden-Württemberg + /// State of Baden-Württemberg. /// [JsonStringEnumMemberName("Baden-Württemberg")] BadenWuerttemberg, /// - /// State of Bavaria + /// State of Bavaria. /// [JsonStringEnumMemberName("Bayern")] Bavaria, /// - /// State of Berlin + /// State of Berlin. /// [JsonStringEnumMemberName("Berlin")] Berlin, /// - /// State of Brandenburg + /// State of Brandenburg. /// [JsonStringEnumMemberName("Brandenburg")] Brandenburg, /// - /// State of Bremen + /// State of Bremen. /// [JsonStringEnumMemberName("Bremen")] Bremen, /// - /// State of Hamburg + /// State of Hamburg. /// [JsonStringEnumMemberName("Hamburg")] Hamburg, /// - /// State of Hesse + /// State of Hesse. /// [JsonStringEnumMemberName("Hessen")] Hesse, /// - /// State of Mecklenburg-Vorpommern + /// State of Mecklenburg-Vorpommern. /// [JsonStringEnumMemberName("Mecklenburg-Vorpommern")] MecklenburgVorpommern, /// - /// State of Lower Saxony + /// State of Lower Saxony. /// [JsonStringEnumMemberName("Niedersachsen")] LowerSaxony, /// - /// State of North Rhine-Westphalia + /// State of North Rhine-Westphalia. /// [JsonStringEnumMemberName("Nordrhein-Westfalen")] NorthRhineWestphalia, /// - /// State of Rhineland-Palatinate + /// State of Rhineland-Palatinate. /// [JsonStringEnumMemberName("Rheinland-Pfalz")] RhinelandPalatinate, /// - /// State of Saarland + /// State of Saarland. /// [JsonStringEnumMemberName("Saarland")] Saarland, /// - /// State of Saxony + /// State of Saxony. /// [JsonStringEnumMemberName("Sachsen")] Saxony, /// - /// State of Saxony-Anhalt + /// State of Saxony-Anhalt. /// [JsonStringEnumMemberName("Sachsen-Anhalt")] SaxonyAnhalt, /// - /// State of Schleswig-Holstein + /// State of Schleswig-Holstein. /// [JsonStringEnumMemberName("Schleswig-Holstein")] SchleswigHolstein, /// - /// State of Thuringia + /// State of Thuringia. /// [JsonStringEnumMemberName("Thüringen")] Thuringia, /// - /// There is no further information available + /// There is no further information available. /// Unknown } diff --git a/source/DotBahn.Stations/Models/Enumerations/LogicalOperator.cs b/source/DotBahn.Stations/Models/Enumerations/LogicalOperator.cs index 7cf5e2b..3a89b13 100644 --- a/source/DotBahn.Stations/Models/Enumerations/LogicalOperator.cs +++ b/source/DotBahn.Stations/Models/Enumerations/LogicalOperator.cs @@ -3,18 +3,18 @@ namespace DotBahn.Stations.Models.Enumerations; /// -/// Represents the logical operator to combine multiple filter criteria in a station query +/// Represents the logical operator to combine multiple filter criteria in a station query. /// [JsonConverter(typeof(JsonStringEnumConverter))] public enum LogicalOperator { /// - /// Logical AND operator. All filter conditions must be true + /// Logical AND operator. All filter conditions must be true. /// [JsonStringEnumMemberName("AND")] And, /// - /// Logical OR operator. At least one filter condition must be true + /// Logical OR operator. At least one filter condition must be true. /// [JsonStringEnumMemberName("OR")] Or diff --git a/source/DotBahn.Stations/Models/Enumerations/StationCategory.cs b/source/DotBahn.Stations/Models/Enumerations/StationCategory.cs index 018ea32..28f80a3 100644 --- a/source/DotBahn.Stations/Models/Enumerations/StationCategory.cs +++ b/source/DotBahn.Stations/Models/Enumerations/StationCategory.cs @@ -2,51 +2,51 @@ namespace DotBahn.Stations.Models.Enumerations; /// /// Category of a railway station based on its importance and traffic volume. -/// Categories range from 1 (major hub) to 7 (minor stop) +/// Categories range from 1 (major hub) to 7 (minor stop). /// public enum StationCategory { /// - /// No category information available + /// No category information available. /// None = 0, /// - /// Major transportation hub with highest passenger traffic + /// Major transportation hub with highest passenger traffic. /// Category1 = 1, /// - /// Large station with significant regional and long-distance traffic + /// Large station with significant regional and long-distance traffic. /// Category2 = 2, /// - /// Important regional station with moderate traffic + /// Important regional station with moderate traffic. /// Category3 = 3, /// - /// Larger regional station + /// Larger regional station. /// Category4 = 4, /// - /// Standard station with basic services + /// Standard station with basic services. /// Category5 = 5, /// - /// Small station with limited services + /// Small station with limited services. /// Category6 = 6, /// - /// Minor stop with minimal infrastructure + /// Minor stop with minimal infrastructure. /// Category7 = 7, /// - /// There is no further information available + /// There is no further information available. /// Unknown } diff --git a/source/DotBahn.Stations/Models/EvaNumber.cs b/source/DotBahn.Stations/Models/EvaNumber.cs index b2a1c07..9375b06 100644 --- a/source/DotBahn.Stations/Models/EvaNumber.cs +++ b/source/DotBahn.Stations/Models/EvaNumber.cs @@ -3,24 +3,24 @@ namespace DotBahn.Stations.Models; /// -/// An EVA (Europäische Verkehrsanlagen) number uniquely identifying a railway station or stop +/// An EVA (Europäische Verkehrsanlagen) number uniquely identifying a railway station or stop. /// public class EvaNumber { /// - /// The EVA number + /// The EVA number. /// public required long Number { get; init; } /// - /// Whether this is the primary EVA number for the station + /// Whether this is the primary EVA number for the station. /// - /// Large stations may have multiple EVA numbers for different platform areas + /// Large stations may have multiple EVA numbers for different platform areas. /// /// public required bool IsMain { get; init; } /// - /// Geographic coordinates associated with this EVA number + /// Geographic coordinates associated with this EVA number. /// public Coordinates? Coordinates { get; init; } } diff --git a/source/DotBahn.Stations/Models/RegionalArea.cs b/source/DotBahn.Stations/Models/RegionalArea.cs index 4abcebd..aa7991b 100644 --- a/source/DotBahn.Stations/Models/RegionalArea.cs +++ b/source/DotBahn.Stations/Models/RegionalArea.cs @@ -1,21 +1,21 @@ namespace DotBahn.Stations.Models; /// -/// The regional administrative area of Deutsche Bahn responsible for the station +/// The regional administrative area of Deutsche Bahn responsible for the station. /// public class RegionalArea { /// - /// Unique number identifying the regional area + /// Unique number identifying the regional area. /// public required int Number { get; init; } /// - /// Full name of the regional area + /// Full name of the regional area. /// public required string Name { get; init; } /// - /// Abbreviated name of the regional area + /// Abbreviated name of the regional area. /// public required string ShortName { get; init; } } diff --git a/source/DotBahn.Stations/Models/Ril100Identifier.cs b/source/DotBahn.Stations/Models/Ril100Identifier.cs index 6f91573..edd7b16 100644 --- a/source/DotBahn.Stations/Models/Ril100Identifier.cs +++ b/source/DotBahn.Stations/Models/Ril100Identifier.cs @@ -1,18 +1,18 @@ namespace DotBahn.Stations.Models; /// -/// A RIL 100 identifier (Richtlinie 100) used to uniquely identify railway operating points +/// A RIL 100 identifier (Richtlinie 100) used to uniquely identify railway operating points. /// public class Ril100Identifier { /// - /// The RIL 100 abbreviation code + /// The RIL 100 abbreviation code. /// public required string Identifier { get; init; } /// - /// Whether this is the primary RIL 100 identifier for the station + /// Whether this is the primary RIL 100 identifier for the station. /// - /// A station may have multiple identifiers for different operational areas + /// A station may have multiple identifiers for different operational areas. /// /// public required bool IsMain { get; init; } diff --git a/source/DotBahn.Stations/Models/Station.cs b/source/DotBahn.Stations/Models/Station.cs index 0d0b0a8..a1f519b 100644 --- a/source/DotBahn.Stations/Models/Station.cs +++ b/source/DotBahn.Stations/Models/Station.cs @@ -4,61 +4,61 @@ namespace DotBahn.Stations.Models; /// -/// A railway station with its identification, location, and available services +/// A railway station with its identification, location, and available services. /// public class Station { /// - /// Unique station number assigned by DB Station & Service + /// Unique station number assigned by DB Station & Service. /// public required int Number { get; init; } /// - /// Official name of the station + /// Official name of the station. /// public required string Name { get; init; } /// - /// Station category indicating its importance and size + /// Station category indicating its importance and size. /// public required StationCategory Category { get; init; } /// - /// Mailing address of the station + /// Mailing address of the station. /// public StationAddress? Address { get; init; } /// - /// A regional area of Deutsche Bahn responsible for the station + /// A regional area of Deutsche Bahn responsible for the station. /// public RegionalArea? RegionalArea { get; init; } /// - /// RIL 100 identifiers for the station + /// RIL 100 identifiers for the station. /// public IReadOnlyList Ril100Identifiers { get; init; } = []; /// - /// EVA numbers for the station + /// EVA numbers for the station. /// public IReadOnlyList EvaNumbers { get; init; } = []; /// - /// Available services and facilities at the station + /// Available services and facilities at the station. /// public required StationServices Services { get; init; } /// - /// Primary RIL 100 identifier for the station + /// Primary RIL 100 identifier for the station. /// public Ril100Identifier? PrimaryRil100 => Ril100Identifiers.FirstOrDefault(r => r.IsMain) ?? Ril100Identifiers.FirstOrDefault(); /// - /// Primary EVA number for the station + /// Primary EVA number for the station. /// public EvaNumber? PrimaryEva => EvaNumbers.FirstOrDefault(e => e.IsMain) ?? EvaNumbers.FirstOrDefault(); /// - /// Primary geographic coordinates of the station + /// Primary geographic coordinates of the station. /// public Coordinates? Coordinates => PrimaryEva?.Coordinates; } diff --git a/source/DotBahn.Stations/Models/StationAddress.cs b/source/DotBahn.Stations/Models/StationAddress.cs index af4fc64..ba7fa30 100644 --- a/source/DotBahn.Stations/Models/StationAddress.cs +++ b/source/DotBahn.Stations/Models/StationAddress.cs @@ -1,26 +1,26 @@ namespace DotBahn.Stations.Models; /// -/// Mailing address of a railway station +/// Mailing address of a railway station. /// public class StationAddress { /// - /// Street name and house number + /// Street name and house number. /// public required string Street { get; init; } /// - /// Postal code (ZIP code) + /// Postal code (ZIP code). /// public required string ZipCode { get; init; } /// - /// City or municipality name + /// City or municipality name. /// public required string City { get; init; } /// - /// Formatted single-line address + /// Formatted single-line address. /// public string DisplayAddress => $"{Street}, {ZipCode} {City}"; } diff --git a/source/DotBahn.Stations/Models/StationServices.cs b/source/DotBahn.Stations/Models/StationServices.cs index 5958da8..c4eb564 100644 --- a/source/DotBahn.Stations/Models/StationServices.cs +++ b/source/DotBahn.Stations/Models/StationServices.cs @@ -1,56 +1,56 @@ namespace DotBahn.Stations.Models; /// -/// Services and facilities available at a railway station +/// Services and facilities available at a railway station. /// public class StationServices { /// - /// Whether the station has car parking facilities + /// Whether the station has car parking facilities. /// public bool HasParking { get; init; } /// - /// Whether the station has bicycle parking facilities + /// Whether the station has bicycle parking facilities. /// public bool HasBicycleParking { get; init; } /// - /// Whether the station has public restroom facilities + /// Whether the station has public restroom facilities. /// public bool HasPublicFacilities { get; init; } /// - /// Whether the station has luggage lockers + /// Whether the station has luggage lockers. /// public bool HasLockerSystem { get; init; } /// - /// Whether the station has step-free access to platforms (elevators, ramps) + /// Whether the station has step-free access to platforms (elevators, ramps). /// public bool HasStepFreeAccess { get; init; } /// - /// Whether the station has stepless access (level boarding) + /// Whether the station has stepless access (level boarding). /// public bool HasSteplessAccess { get; init; } /// - /// Whether the station has a DB travel center (Reisezentrum) for ticket sales and customer service + /// Whether the station has a DB travel center (Reisezentrum) for ticket sales and customer service. /// public bool HasTravelCenter { get; init; } /// - /// Whether the station has shops for travel necessities + /// Whether the station has shops for travel necessities. /// public bool HasTravelNecessities { get; init; } /// - /// Whether the station offers mobility assistance services for passengers with reduced mobility + /// Whether the station offers mobility assistance services for passengers with reduced mobility. /// public bool HasMobilityService { get; init; } /// - /// Whether the station has public WiFi access + /// Whether the station has public WiFi access. /// public bool HasWiFi { get; init; } } diff --git a/source/DotBahn.Stations/ServiceCollectionExtensions.cs b/source/DotBahn.Stations/ServiceCollectionExtensions.cs index e965577..d63bc28 100644 --- a/source/DotBahn.Stations/ServiceCollectionExtensions.cs +++ b/source/DotBahn.Stations/ServiceCollectionExtensions.cs @@ -12,18 +12,18 @@ namespace DotBahn.Stations; /// -/// Extension methods for registering the DotBahn Stations client +/// Extension methods for registering the DotBahn Stations client. /// public static class ServiceCollectionExtensions { private const string OptionsName = "DotBahn.Stations"; private static readonly Uri DefaultStationsEndpoint = new("https://apis.deutschebahn.com/db-api-marketplace/apis/station-data/v2/"); /// - /// Registers the with its parser and transformer services + /// Registers the with its parser and transformer services. /// - /// The service collection to add to - /// Optional action to override default client options - /// The service collection for chaining + /// The service collection to add to. + /// Optional action to override default client options. + /// The service collection for chaining. public static IServiceCollection AddDotBahnStations(this IServiceCollection services, Action? configuration = null) { services.AddOptions(OptionsName) .Configure(opts => { @@ -36,7 +36,7 @@ public static IServiceCollection AddDotBahnStations(this IServiceCollection serv services.AddHttpClient(OptionsName, (http, sp) => { var options = sp.GetRequiredService>().Get(OptionsName); http.BaseAddress = options.BaseEndpoint; - http.DefaultRequestHeaders.UserAgent.ParseAdd("DotBahn/2.0 (+https://github.com/rlvelte/dotbahn)"); + http.DefaultRequestHeaders.UserAgent.ParseAdd("DotBahn/2.X (+https://github.com/rlvelte/dotbahn)"); var auth = sp.GetRequiredService(); var parser = sp.GetRequiredService>(); diff --git a/source/DotBahn.Stations/StationClient.cs b/source/DotBahn.Stations/StationClient.cs index 485eaed..e7e6898 100644 --- a/source/DotBahn.Stations/StationClient.cs +++ b/source/DotBahn.Stations/StationClient.cs @@ -11,7 +11,7 @@ namespace DotBahn.Stations; /// -/// Client for accessing 'Deutsche Bahn StaDa'-API +/// Client for accessing 'Deutsche Bahn StaDa'-API. /// public class StationClient : ClientBase, IStationClient { private readonly IParser _parser; @@ -21,12 +21,12 @@ public class StationClient : ClientBase, IStationClient { protected override string ApiName => "stations"; /// - /// Client for accessing 'Deutsche Bahn StaDa'-API + /// Client for accessing 'Deutsche Bahn StaDa'-API. /// - /// The HTTP client used for requests - /// The provider used for retrieving access tokens - /// The parser for this contract type - /// The transformer for this model and contract types + /// The HTTP client used for requests. + /// The provider used for retrieving access tokens. + /// The parser for this contract type. + /// The transformer for this model and contract types. [ActivatorUtilitiesConstructor] internal StationClient(HttpClient http, IAuthorization authorization, IParser parser, ITransformer, StationsResponseContract> transformer) : base(http, authorization) { @@ -35,16 +35,15 @@ internal StationClient(HttpClient http, IAuthorization authorization, IParser - /// Client for accessing 'Deutsche Bahn StaDa'-API + /// Client for accessing 'Deutsche Bahn StaDa'-API. /// /// /// Creates and owns its own . Dispose this instance to release it. - /// Use only when instantiating manually without a DI container + /// Use only when instantiating manually without a DI container. /// - /// The options for this instance - /// The auth credentials for the client - /// Thrown when is null - /// Thrown when is null + /// The options for this instance. + /// The auth credentials for the client. + /// Thrown when or is null. public StationClient(ClientOptions options, AuthorizationOptions auth) : base(options, auth) { _parser = new JsonParser(StationsJsonContext.Default.StationsResponseContract); @@ -52,7 +51,7 @@ public StationClient(ClientOptions options, AuthorizationOptions auth) } /// - /// Thrown when is null + /// Thrown when is null. public async Task> GetStationsAsync(StationQuery query, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(query); diff --git a/source/DotBahn.Stations/StationQuery.cs b/source/DotBahn.Stations/StationQuery.cs index 3b7bfd2..389d782 100644 --- a/source/DotBahn.Stations/StationQuery.cs +++ b/source/DotBahn.Stations/StationQuery.cs @@ -7,79 +7,79 @@ namespace DotBahn.Stations; /// /// Represents the query parameters for searching stations. -/// Provides fluent methods for convenient building of queries +/// Provides fluent methods for convenient building of queries. /// public sealed partial record StationQuery { /// - /// Matches a category range pattern (e.g., "2-4", "1 - 7") + /// Matches a category range pattern (e.g., "2-4", "1 - 7"). /// [GeneratedRegex(@"^(\d+)\s*-\s*(\d+)$")] private static partial Regex ComplexCategoryRegex(); /// - /// Strings to search for station names + /// Strings to search for station names. /// /// - /// Wildcards '*' and '?' are supported + /// Wildcards '*' and '?' are supported. /// public string[]? Names { get; set; } /// - /// Filter by station category + /// Filter by station category. /// /// - /// Single values (1-7), ranges (e.g., "2-4"), or comma-separated (e.g., "1,3-5") + /// Single values (1-7), ranges (e.g., "2-4"), or comma-separated (e.g., "1,3-5"). /// public string? Categories { get; set; } /// - /// Filter by German federal state + /// Filter by German federal state. /// public FederalState? State { get; set; } /// - /// The EVA station number used as a unique identifier + /// The EVA station number used as a unique identifier. /// public string? Eva { get; set; } /// - /// The RIL100 identifier of the station + /// The RIL100 identifier of the station. /// public string? Ril { get; set; } /// - /// Logical operator for combining multiple filters + /// Logical operator for combining multiple filters. /// /// - /// Default is + /// Default is . /// public LogicalOperator Operator { get; set; } = LogicalOperator.And; /// - /// Offset of the first hit returned + /// Offset of the first hit returned. /// /// - /// Default is 0 + /// Default is 0. /// public int Offset { get; set; } /// - /// The maximum number of hits to return + /// The maximum number of hits to return. /// /// - /// Default is 10_000 + /// Default is 10_000. /// public int Limit { get; set; } = 10000; /// - /// Sets the station names or fragments to search for + /// Sets the station names or fragments to search for. /// /// - /// Appends a trailing '*' automatically if no wildcard is present + /// Appends a trailing '*' automatically if no wildcard is present. /// - /// One or more station name patterns - /// The current instance for fluent chaining - /// Thrown if no names are provided + /// One or more station name patterns. + /// The current instance for fluent chaining. + /// Thrown if no names are provided. public StationQuery WithNames(params string[] names) { if (names is not { Length: > 0 }) { throw new ArgumentException("At least one name is required.", nameof(names)); @@ -90,14 +90,14 @@ public StationQuery WithNames(params string[] names) { } /// - /// Sets the station category filter + /// Sets the station category filter. /// /// - /// You can specify a single category, a range (e.g., "2-4") or a list of categories (e.g., "1,3-5"). Categories must be between 1 and 7 + /// You can specify a single category, a range (e.g., "2-4") or a list of categories (e.g., "1,3-5"). Categories must be between 1 and 7. /// - /// One or more category specifications: integers, ranges, or comma-separated values - /// The current instance for fluent chaining - /// Thrown if any category is invalid or out of range (1-7) + /// One or more category specifications: integers, ranges, or comma-separated values. + /// The current instance for fluent chaining. + /// Thrown if any category is invalid or out of range (1-7). public StationQuery WithCategories(string categories) { if (string.IsNullOrWhiteSpace(categories)) { throw new ArgumentException("At least one category must be specified.", nameof(categories)); @@ -136,67 +136,67 @@ public StationQuery WithCategories(string categories) { } /// - /// Filters stations by federal state + /// Filters stations by federal state. /// - /// German federal state - /// The current instance for fluent chaining + /// German federal state. + /// The current instance for fluent chaining. public StationQuery InFederalState(FederalState state) { State = state; return this; } /// - /// Filters stations by EVA number + /// Filters stations by EVA number. /// - /// EVA station number - /// The current instance for fluent chaining + /// EVA station number. + /// The current instance for fluent chaining. public StationQuery WithEva(string eva) { Eva = eva; return this; } /// - /// Filters stations by RIL100 identifier + /// Filters stations by RIL100 identifier. /// - /// RIL100 identifier - /// The current instance for fluent chaining + /// RIL100 identifier. + /// The current instance for fluent chaining. public StationQuery WithRil(string ril) { Ril = ril; return this; } /// - /// Sets the logical operator for combining multiple filters + /// Sets the logical operator for combining multiple filters. /// - /// Logical operator - /// The current instance for fluent chaining + /// Logical operator. + /// The current instance for fluent chaining. public StationQuery CombineAs(LogicalOperator @operator) { Operator = @operator; return this; } /// - /// Sets the number of results to skip for pagination + /// Sets the number of results to skip for pagination. /// - /// Number of results to skip - /// The current instance for fluent chaining + /// Number of results to skip. + /// The current instance for fluent chaining. public StationQuery Skip(int offset) { Offset = offset; return this; } /// - /// Sets the maximum number of results to return + /// Sets the maximum number of results to return. /// - /// Maximum results - /// The current instance for fluent chaining + /// Maximum results. + /// The current instance for fluent chaining. public StationQuery LimitTo(int limit) { Limit = limit; return this; } /// - /// Converts the query into for API calls + /// Converts the query into for API calls. /// internal QueryParameters ToQueryParameters() => QueryParameters.Create() .Add("searchstring", Names != null ? string.Join(',', Names) : string.Empty) diff --git a/source/DotBahn.Stations/packages.lock.json b/source/DotBahn.Stations/packages.lock.json index 55c79b9..1f3715b 100644 --- a/source/DotBahn.Stations/packages.lock.json +++ b/source/DotBahn.Stations/packages.lock.json @@ -4,55 +4,44 @@ "net10.0": { "Microsoft.Extensions.Http": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "IDsXLGGz7nJMsqspWnErsP18WyAVf6V9Ixl4p47/8/95Jak3ZA1YWhQ0iesMVwubVhkVZGoO9m9ADUnK0m6HLw==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Http.Resilience": { "type": "Direct", - "requested": "[10.11.0, )", - "resolved": "10.11.0", - "contentHash": "6/YEoPCcQLzExm4x4FH5c38JffbhkMaTtXsrDmYNozt9KRtdXK3TsDeuKSBZJno+41oIDGBONb2up0zCsuEERw==", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "5VawCrg+VgVT2hNurSSEWUnq0pvNoH+Zt82s5Wpl/8jdnmU8DpRlr+M3DcdtVgeBG7mRyk3GtSRbf8PB/HrL3w==", "dependencies": { - "Microsoft.Extensions.Http.Diagnostics": "10.11.0", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Resilience": "10.11.0" + "Microsoft.Extensions.Http.Diagnostics": "11.0.1", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Resilience": "11.0.1" } }, "Microsoft.Extensions.Options": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.NET.ILLink.Tasks": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "YlTamXppEQls6DYWt7RdUuwWDb0lyw/vXCaGeQpLCpsLmfwGuCkOz/vIGgMTV7ECsJcavkCOkxZXv9s8rdAHkQ==" - }, - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[10.0.403, )", - "resolved": "10.0.403", - "contentHash": "T4WYxWydJGNQRe/EgURFlhPZ1cHYgivrCCHSomCcfQzGzhkDYGNn5bUwwjs4/PHuMxsmGaLvPv2puG8lluA1IA==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "10.0.403", - "Microsoft.SourceLink.Common": "10.0.403", - "System.IO.Hashing": "10.0.14" - } + "requested": "[10.0.15, )", + "resolved": "10.0.15", + "contentHash": "u0WnRcZgBZYHlVFpbe/3Adpmb9rmNJ8/fmEwqc/xjB7fFppq+gfaLJd3Sdaw+J02zV0eP/T9dneQ3Dv5jWw6bw==" }, "MinVer": { "type": "Direct", @@ -60,232 +49,231 @@ "resolved": "8.0.0", "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" }, - "Microsoft.Build.Tasks.Git": { + "Microsoft.Extensions.AmbientMetadata.Application": { "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "1furteBFeemMmZ4s+ORjQb7YtO+wG63NJahbQbRUi91FV6V87BdV0U3vX1jbMC6iKSELYYoXWssSzLu3mx0i2w==", + "resolved": "11.0.1", + "contentHash": "tm28s2ODWZ6RdysP06NI3B23DUY5OfHG35ihMHxVAO3hywZAczDVjrkYMfBY//J4HQqfDHS5op84BhnF7ROseQ==", "dependencies": { - "System.IO.Hashing": "10.0.14" + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, - "Microsoft.Extensions.AmbientMetadata.Application": { + "Microsoft.Extensions.Compliance.Abstractions": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "aMCm7C6CexZT8W/p8zRp4BoxSnqRs3MmkBF7FvPIXC92b7vqs2SL0J+mVJi5W2Mk9Vb4ZRFWe9sdzFew6zUl1w==", + "resolved": "11.0.1", + "contentHash": "DUwdXgIxJKH9zBNg/SUBqOX0FpXCq7w80CIzrr0Jcw5tBXS926AtCcidoAsEHq5e/c6KQ8rWhSt7NxFxak8N/Q==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15" } }, - "Microsoft.Extensions.Compliance.Abstractions": { + "Microsoft.Extensions.Compliance.Redaction": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2mjAb3Sm5k6uNeI+IyXpggYMpfdDDGgZSwUm9QQsm5QgZboJWbm2eU+6wNMrlfFEao11yq6JS1zXI7SVQQ0NuQ==", + "resolved": "11.0.1", + "contentHash": "2rwe98yZEn4+aXjAg5DdcROMg6m2w3tejf/mRk4/fBCHKM2EWCaFTmbHLtz1BfyBxMY00/08XFoN0wzWYNiSiQ==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13" + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, "Microsoft.Extensions.Configuration": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Binder": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" }, "Microsoft.Extensions.DependencyInjection.AutoActivation": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "h/sovspxVmT2DTIbWORMG0Gi3zVcPQzNl3kbwtpo0LoUXYbe2+66wQqZYwaF2ZWKN8HDdHv5yoc7d0DbDBBlnA==", + "resolved": "11.0.1", + "contentHash": "OuVIF5TmsfonN2Fqmi2zlUtbFQNqQiflhgo/rh64ptrqYrB4wZLwKbXr/HzrQXMf+h3jIbWrjIdJFspGqcvuuQ==", "dependencies": { - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13" + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15" } }, "Microsoft.Extensions.Diagnostics": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "80VqW8eKxQaxBOLDNpLUdxOlxzWn/jqBSxNBCfD8GCjcshNDpFvUgKh8uvvZwvkfBbwmNPWPWHyy9F+RLd1dlQ==", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" } }, "Microsoft.Extensions.Diagnostics.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vm+PPso6vOwGeX52MdOPh6z/R6KHgxQUwqq7k7Jc9jhy2JOxO2KB4xfoJQBBp2Ni8M4zKgJ4r2a1dgrYG7+MKw==", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "Dp/FaAPo3U9h3HsWT1dcdRRV//rm+MQF5iKpY/WxL5swwV+wZNE5eyJZ0kgy9Upl/kHz4ejpiLMloxDIuJaoJQ==", + "resolved": "11.0.1", + "contentHash": "mqqpmAFNRLa4cozN3RvT/T81k4aarwMc8xb8VVQgLqUE7AAoN/WWayZAvP+4hy9+KujP3dfn3taU06fZJPIbgA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13" + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" } }, "Microsoft.Extensions.FileProviders.Abstractions": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "BZDwtN3uoWRghDi5lRRZPDjMMCg2Ds7J6YEYjqka/TLjqnzquEpXyvchrIMeoubwT1ns23ow6PPeAoBHJO81Rw==", + "resolved": "10.0.15", + "contentHash": "1RSYAUtJeb76m2T0u5BbvwKY3s+ge9fT3cj1odvo5Bm+frc7pU9RSeXeMIlYHV8GjpqLdv2neeeomz010yYL8A==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.13" + "Microsoft.Extensions.Primitives": "10.0.15" } }, "Microsoft.Extensions.Hosting.Abstractions": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "zIrbe9vkIFXxW3mOApIOWXw+xMwX7Cgsptr3ZSlglJt4hW2qp4fB/JU1NHgAevteBNH4PicvU9DsFPHxlnnloA==", + "resolved": "10.0.15", + "contentHash": "s/JBiwR3F/vKRCbe6WO5b6t6or1ISaZ3rllchcw6/FSWZmK8s2fAzD7elrZo7592FnMD1fhGoG/wuJL1YYtVXw==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13" + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15" } }, "Microsoft.Extensions.Http.Diagnostics": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "iFcxcuMF/21LO+tDqDyzYVvokJUH03cNalmOJhmjyQSMV3dR4JAgcUBTV1iVH/yruC8wG2RNjvW0xcUgYqmrGg==", + "resolved": "11.0.1", + "contentHash": "mKHY0oFYL3fkAOhBNi2LqWPuEdUJ+HiF28KKUwBkQG2sgXAUdFDDqvJAfu2PcYgtAwsAtl58zuk4SElpPzbCvA==", "dependencies": { - "Microsoft.Extensions.Http": "10.0.13", - "Microsoft.Extensions.Telemetry": "10.11.0" + "Microsoft.Extensions.Compliance.Redaction": "11.0.1", + "Microsoft.Extensions.Http": "10.0.15", + "Microsoft.Extensions.Telemetry": "11.0.1" } }, "Microsoft.Extensions.Logging": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Logging.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Logging.Configuration": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "OyYJOaE9WbBx1Hp+Dd2zrqeFM0JwH5M/x0VL6tNUv3V18vIAVpix8UjhvY9eW/iXpguEHy68JO/Z9YkBOwftIw==", + "resolved": "10.0.15", + "contentHash": "Km6Ml1/nu0T/f80Btonxf9CWmP/BXI84aJwC5fUbCxRArJ0lH++0ADQrjErZvsSIrKhusTkTSGBChKy2fYAF4w==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.Configuration.Binder": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Configuration.Binder": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, "Microsoft.Extensions.ObjectPool": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "NX3bhcc0WitPKAVc9Zfi8jeEPClhfEmobUJM4a4bkWhJcBt5IWg6lCrItUoFy4whLjU+atXktURYCweQlR7wfg==" + "resolved": "10.0.15", + "contentHash": "kvd9eyRRQ+OEu9wik7GKgTS+7XnJ5XoOtSXJqmkJtVYV/S4gsBUrobYRSdNeBcb0ymef4L5Q9pZGiTxJ8jJfyQ==" }, "Microsoft.Extensions.Options.ConfigurationExtensions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4wcIU0rE04ejEfCwHTftu9O8fgH6CRYCe+tseRapikUBn1Kic3QdO7ku22SwFyLrzdWGYPUZMEgv57ZYuuc5gA==", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Primitives": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" }, "Microsoft.Extensions.Resilience": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "GbN7R2BOoZf3F7aK02nz9kWf6ttbvVzpw1orGG30VmrKTmRV6pasQOCfF2fjKXyHIMC/lAiBEYHCKjgf0OiGvQ==", + "resolved": "11.0.1", + "contentHash": "xgKof6iwAByZNrxWOa7Drk4A953L7U2HleTmx7EXE2Vf6j1crp4RsvNlIVsJMtHKf3ftGKd9gOhR3xES9vxUgg==", "dependencies": { - "Microsoft.Extensions.Diagnostics": "10.0.13", - "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "10.11.0", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0", + "Microsoft.Extensions.Diagnostics": "10.0.15", + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1", "Polly.Extensions": "8.4.2", "Polly.RateLimiting": "8.4.2" } }, "Microsoft.Extensions.Telemetry": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2meCfABvkLPtEBBwGzItIGnhrex1AEn2N+dHvxB5UoozeX/xTtBuUz5BRdjNI5oNgd5T31kC69WWw3BHDc9iZA==", + "resolved": "11.0.1", + "contentHash": "9uuA8entTC9m00m59h6CACSt4IQh9KknB+hPvCteXUTiG67lqJ8BI65fEUJSPSfT3ZDDi01Zg2aY5kRUvD4HPw==", "dependencies": { - "Microsoft.Extensions.AmbientMetadata.Application": "10.11.0", - "Microsoft.Extensions.DependencyInjection.AutoActivation": "10.11.0", - "Microsoft.Extensions.Logging.Configuration": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0" + "Microsoft.Extensions.AmbientMetadata.Application": "11.0.1", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "11.0.1", + "Microsoft.Extensions.Logging.Configuration": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1" } }, "Microsoft.Extensions.Telemetry.Abstractions": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "FzcHRan/C2g5X5KD0kPlL4tTROFRpM8sqcXfOIi6FGLsw/d2yoOYMbLJ5hyb8N5QgOVW7e1TdwEN4zVUfcwfdw==", + "resolved": "11.0.1", + "contentHash": "qINZz4G01Wxumqd0hLr6YdzPa3s7jexQWN28EenaiJQnmKdsR9FnBaKENdRRElLc+A5bJKQ+jYw/WHG4ZpIyAg==", "dependencies": { - "Microsoft.Extensions.Compliance.Abstractions": "10.11.0", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13" + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15" } }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "SvzUeqFGrcQxlIgjmcoSGiV5UWcPa0NCTuH69/40uSDsSD/26c6p9cH7XLAxpn+I8+2Zhl1qp+WMugl0oOwBMg==" - }, "Polly.Core": { "type": "Transitive", "resolved": "8.4.2", @@ -310,10 +298,10 @@ "System.Threading.RateLimiting": "8.0.0" } }, - "System.IO.Hashing": { + "System.Diagnostics.DiagnosticSource": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "lVqovhCt3HlZe7ONG5ydaj6BYwYI004gldVfMMkJl/lR5ueeCtWNpW4nejOX75sPmzm8vXCxB69GqwHaYCnyUQ==" + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" }, "System.Threading.RateLimiting": { "type": "Transitive", @@ -323,8 +311,8 @@ "dotbahn.common": { "type": "Project", "dependencies": { - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Options": "[10.0.14, )" + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" } } } diff --git a/source/DotBahn.Telemetry/ServiceCollectionExtensions.cs b/source/DotBahn.Telemetry/ServiceCollectionExtensions.cs index 205d8ee..7fb59b8 100644 --- a/source/DotBahn.Telemetry/ServiceCollectionExtensions.cs +++ b/source/DotBahn.Telemetry/ServiceCollectionExtensions.cs @@ -6,21 +6,26 @@ namespace DotBahn.Telemetry; /// -/// Extension methods for registering the DotBahn telemetry options +/// Extension methods for registering the DotBahn telemetry options. /// public static class ServiceCollectionExtensions { /// - /// Registers the DotBahn and + /// Registers the DotBahn client and AI and /// with the OpenTelemetry providers. /// - /// The service collection to add to - /// The service collection for chaining - /// Thrown when is null + /// The service collection to add to. + /// The service collection for chaining. + /// Thrown when is null. public static IServiceCollection AddDotBahnTelemetry(this IServiceCollection services) { ArgumentNullException.ThrowIfNull(services); - services.ConfigureOpenTelemetryTracerProvider((_, builder) => builder.AddSource(DotBahnTelemetry.SourceName)); - services.ConfigureOpenTelemetryMeterProvider((_, builder) => builder.AddMeter(DotBahnTelemetry.MeterName)); + services.ConfigureOpenTelemetryTracerProvider((_, builder) => builder + .AddSource(DotBahnTelemetry.SourceName) + .AddSource(DotBahnTelemetry.AiSourceName)); + + services.ConfigureOpenTelemetryMeterProvider((_, builder) => builder + .AddMeter(DotBahnTelemetry.MeterName) + .AddMeter(DotBahnTelemetry.AiMeterName)); return services; } diff --git a/source/DotBahn.Telemetry/packages.lock.json b/source/DotBahn.Telemetry/packages.lock.json index ec7bab8..6b70fc4 100644 --- a/source/DotBahn.Telemetry/packages.lock.json +++ b/source/DotBahn.Telemetry/packages.lock.json @@ -4,20 +4,9 @@ "net10.0": { "Microsoft.NET.ILLink.Tasks": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "YlTamXppEQls6DYWt7RdUuwWDb0lyw/vXCaGeQpLCpsLmfwGuCkOz/vIGgMTV7ECsJcavkCOkxZXv9s8rdAHkQ==" - }, - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[10.0.403, )", - "resolved": "10.0.403", - "contentHash": "T4WYxWydJGNQRe/EgURFlhPZ1cHYgivrCCHSomCcfQzGzhkDYGNn5bUwwjs4/PHuMxsmGaLvPv2puG8lluA1IA==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "10.0.403", - "Microsoft.SourceLink.Common": "10.0.403", - "System.IO.Hashing": "10.0.14" - } + "requested": "[10.0.15, )", + "resolved": "10.0.15", + "contentHash": "u0WnRcZgBZYHlVFpbe/3Adpmb9rmNJ8/fmEwqc/xjB7fFppq+gfaLJd3Sdaw+J02zV0eP/T9dneQ3Dv5jWw6bw==" }, "MinVer": { "type": "Direct", @@ -27,159 +16,151 @@ }, "OpenTelemetry.Api.ProviderBuilderExtensions": { "type": "Direct", - "requested": "[1.20.1, )", - "resolved": "1.20.1", - "contentHash": "eDzDY/jTBqRytkYECmVKF7ZP5sKmCIqv1SSnA5BSWltIIvc3931TOMRyCW1qCGNIgmtldtJhISnsmFNxOCfauQ==", + "requested": "[1.21.0, )", + "resolved": "1.21.0", + "contentHash": "ZcBCBTGbzjj8Y+9UnZKbSjnRyKc2ub2IvvU68fFHKmyKzTS4hU+4/f0PO1GoIf7FTYLKTyw+l/EwLL/PPIDkxg==", "dependencies": { "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0", - "OpenTelemetry.Api": "1.20.1" - } - }, - "Microsoft.Build.Tasks.Git": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "1furteBFeemMmZ4s+ORjQb7YtO+wG63NJahbQbRUi91FV6V87BdV0U3vX1jbMC6iKSELYYoXWssSzLu3mx0i2w==", - "dependencies": { - "System.IO.Hashing": "10.0.14" + "OpenTelemetry.Api": "1.21.0" } }, "Microsoft.Extensions.Configuration": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Binder": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" }, "Microsoft.Extensions.Diagnostics": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "80VqW8eKxQaxBOLDNpLUdxOlxzWn/jqBSxNBCfD8GCjcshNDpFvUgKh8uvvZwvkfBbwmNPWPWHyy9F+RLd1dlQ==", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" } }, "Microsoft.Extensions.Diagnostics.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vm+PPso6vOwGeX52MdOPh6z/R6KHgxQUwqq7k7Jc9jhy2JOxO2KB4xfoJQBBp2Ni8M4zKgJ4r2a1dgrYG7+MKw==", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Logging": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Logging.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Options.ConfigurationExtensions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4wcIU0rE04ejEfCwHTftu9O8fgH6CRYCe+tseRapikUBn1Kic3QdO7ku22SwFyLrzdWGYPUZMEgv57ZYuuc5gA==", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Primitives": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" - }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "SvzUeqFGrcQxlIgjmcoSGiV5UWcPa0NCTuH69/40uSDsSD/26c6p9cH7XLAxpn+I8+2Zhl1qp+WMugl0oOwBMg==" + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" }, "OpenTelemetry.Api": { "type": "Transitive", - "resolved": "1.20.1", - "contentHash": "QO9hlwadOdJGR4vDpJyDnl9B62v7epIBSTIHUA4C+bCtrRaB4TWmYSnu3QVOIe7caH8dt7NaHRei6zebESJJyw==" + "resolved": "1.21.0", + "contentHash": "KptD6ThegQORUzwot75zW2AUH6IDyKXH1R2yhovJPYfrzqSgHQidMfVfKLjaYEnJa5ySQgQm0RjuM6X+TCJ9yw==", + "dependencies": { + "System.Diagnostics.DiagnosticSource": "11.0.0" + } }, - "System.IO.Hashing": { + "System.Diagnostics.DiagnosticSource": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "lVqovhCt3HlZe7ONG5ydaj6BYwYI004gldVfMMkJl/lR5ueeCtWNpW4nejOX75sPmzm8vXCxB69GqwHaYCnyUQ==" + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" }, "dotbahn.common": { "type": "Project", "dependencies": { - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Options": "[10.0.14, )" + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" } }, "Microsoft.Extensions.Http": { "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "IDsXLGGz7nJMsqspWnErsP18WyAVf6V9Ixl4p47/8/95Jak3ZA1YWhQ0iesMVwubVhkVZGoO9m9ADUnK0m6HLw==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Options": { "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } } } diff --git a/source/DotBahn.Timetables/DotBahn.Timetables.csproj b/source/DotBahn.Timetables/DotBahn.Timetables.csproj index 5652608..d1b8e3f 100644 --- a/source/DotBahn.Timetables/DotBahn.Timetables.csproj +++ b/source/DotBahn.Timetables/DotBahn.Timetables.csproj @@ -17,5 +17,6 @@ + diff --git a/source/DotBahn.Timetables/ITimetableClient.cs b/source/DotBahn.Timetables/ITimetableClient.cs index f3185fb..1e2413d 100644 --- a/source/DotBahn.Timetables/ITimetableClient.cs +++ b/source/DotBahn.Timetables/ITimetableClient.cs @@ -3,38 +3,42 @@ namespace DotBahn.Timetables; /// -/// Client for accessing the 'Deutsche Bahn Timetables'-API +/// Client for accessing the 'Deutsche Bahn Timetables'-API. /// +[Obsolete("The Deutsche Bahn Timetables API is being shut down. Use DotBahn.Boards instead.", false)] public interface ITimetableClient { /// /// Gets full changes for a specific station. - /// If a is supplied, the changes are merged onto this instance + /// If a is supplied, the changes are merged onto this instance. /// - /// The EVA station number - /// Current timetable on which these changes should apply - /// Token to cancel the request - /// A with full change information - /// Thrown when non-success status codes occur + /// The EVA station number. + /// Current timetable on which these changes should apply. + /// Token to cancel the request. + /// A with full change information. + /// Thrown when non-success status codes occur. + /// Thrown when the operation is canceled. Task GetFullChangesAsync(int eva, Timetable? mergeOn = null, CancellationToken ct = default); /// /// Gets recent changes for a specific station. - /// If a is supplied, the changes are merged onto this instance + /// If a is supplied, the changes are merged onto this instance. /// - /// The EVA station number - /// Current timetable on which these changes should apply - /// Token to cancel the request - /// A with recent change information - /// Thrown when non-success status codes occur + /// The EVA station number. + /// Current timetable on which these changes should apply. + /// Token to cancel the request. + /// A with recent change information. + /// Thrown when non-success status codes occur. + /// Thrown when the operation is canceled. Task GetRecentChangesAsync(int eva, Timetable? mergeOn = null, CancellationToken ct = default); /// - /// Gets the timetable for a specific station and time + /// Gets the timetable for a specific station and time. /// - /// The EVA station number - /// The date and hour (only YYMMDD/HH are used) - /// Token to cancel the request - /// A for the specified hour - /// Thrown when non-success status codes occur + /// The EVA station number. + /// The date and hour (only YYMMDD/HH are used). + /// Token to cancel the request. + /// A for the specified hour. + /// Thrown when non-success status codes occur. + /// Thrown when the operation is canceled. Task GetTimetableAsync(int eva, DateTime dateTime, CancellationToken ct = default); } diff --git a/source/DotBahn.Timetables/Internal/Contracts/EventContract.cs b/source/DotBahn.Timetables/Internal/Contracts/EventContract.cs index 97ec736..3758e8b 100644 --- a/source/DotBahn.Timetables/Internal/Contracts/EventContract.cs +++ b/source/DotBahn.Timetables/Internal/Contracts/EventContract.cs @@ -3,77 +3,77 @@ namespace DotBahn.Timetables.Internal.Contracts; /// -/// Raw event information (Arrival/Departure) +/// Raw event information (Arrival/Departure). /// [ExcludeFromCodeCoverage] internal record EventContract { /// - /// Planned time (YYMMDDhhmm format) + /// Planned time (YYMMDDhhmm format). /// public string? PlannedTime { get; init; } /// - /// Planned platform + /// Planned platform. /// public string? PlannedPlatform { get; init; } /// - /// Planned status (e.g., "p" for planned) + /// Planned status (e.g., "p" for planned). /// public string? PlannedStatus { get; init; } /// - /// Changed time (YYMMDDhhmm format) + /// Changed time (YYMMDDhhmm format). /// public string? ChangedTime { get; init; } /// - /// Changed platform + /// Changed platform. /// public string? ChangedPlatform { get; init; } /// - /// Changed status (e.g., "c" for canceled) + /// Changed status (e.g., "c" for canceled). /// public string? ChangedStatus { get; init; } /// - /// Hidden (0 or 1) + /// Hidden (0 or 1). /// public string? IsHidden { get; init; } /// - /// Line + /// Line. /// public string? Line { get; init; } /// - /// Planned path (pipe-separated station list) + /// Planned path (pipe-separated station list). /// public string? PlannedPath { get; init; } /// - /// Changed path (pipe-separated station list) + /// Changed path (pipe-separated station list). /// public string? ChangedPath { get; init; } /// - /// Wing train information + /// Wing train information. /// public string? Wings { get; init; } /// - /// Transition information + /// Transition information. /// public string? Transition { get; init; } /// - /// Planned distant endpoint + /// Planned distant endpoint. /// public string? PlannedDistantEndpoint { get; init; } /// - /// Changed distant endpoint + /// Changed distant endpoint. /// public string? ChangedDistantEndpoint { get; init; } } diff --git a/source/DotBahn.Timetables/Internal/Contracts/MessageContract.cs b/source/DotBahn.Timetables/Internal/Contracts/MessageContract.cs index 8aca998..bf19d3f 100644 --- a/source/DotBahn.Timetables/Internal/Contracts/MessageContract.cs +++ b/source/DotBahn.Timetables/Internal/Contracts/MessageContract.cs @@ -3,72 +3,72 @@ namespace DotBahn.Timetables.Internal.Contracts; /// -/// Raw message/disruption information +/// Raw message/disruption information. /// [ExcludeFromCodeCoverage] internal record MessageContract { /// - /// Message ID + /// Message ID. /// public string? Id { get; init; } /// - /// Type + /// Type. /// public string? Type { get; init; } /// - /// Valid from timestamp (YYMMDDhhmm) + /// Valid from timestamp (YYMMDDhhmm). /// public string? ValidFrom { get; init; } /// - /// Valid to timestamp (YYMMDDhhmm) + /// Valid to timestamp (YYMMDDhhmm). /// public string? ValidTo { get; init; } /// - /// Message code + /// Message code. /// public string? Code { get; init; } /// - /// Internal message flag + /// Internal message flag. /// public string? IsInternal { get; init; } /// - /// Deleted flag + /// Deleted flag. /// public string? IsDeleted { get; init; } /// - /// External category + /// External category. /// public string? ExternalCategory { get; init; } /// - /// Timestamp (YYMMDDhhmm) + /// Timestamp (YYMMDDhhmm). /// public string? Timestamp { get; init; } /// - /// Priority + /// Priority. /// public string? Priority { get; init; } /// - /// Message owner + /// Message owner. /// public string? Owner { get; init; } /// - /// Category + /// Category. /// public string? Category { get; init; } /// - /// Message text content + /// Message text content. /// public string? Text { get; init; } } diff --git a/source/DotBahn.Timetables/Internal/Contracts/StopDataContract.cs b/source/DotBahn.Timetables/Internal/Contracts/StopDataContract.cs index 629f1fe..d6cd2a4 100644 --- a/source/DotBahn.Timetables/Internal/Contracts/StopDataContract.cs +++ b/source/DotBahn.Timetables/Internal/Contracts/StopDataContract.cs @@ -3,37 +3,37 @@ namespace DotBahn.Timetables.Internal.Contracts; /// -/// Raw structure for a single stop +/// Raw structure for a single stop. /// [ExcludeFromCodeCoverage] internal record StopDataContract { /// - /// Unique stop ID + /// Unique stop ID. /// public string Id { get; init; } = string.Empty; /// - /// EVA number of the station + /// EVA number of the station. /// public string Eva { get; init; } = string.Empty; /// - /// Trip label information + /// Trip label information. /// public TripInfoContract? TripInfo { get; init; } /// - /// Arrival information + /// Arrival information. /// public EventContract? Arrival { get; init; } /// - /// Departure information + /// Departure information. /// public EventContract? Departure { get; init; } /// - /// List of messages + /// List of messages. /// public List? Messages { get; init; } } diff --git a/source/DotBahn.Timetables/Internal/Contracts/TimetableResponseContract.cs b/source/DotBahn.Timetables/Internal/Contracts/TimetableResponseContract.cs index 90a8b18..50d0066 100644 --- a/source/DotBahn.Timetables/Internal/Contracts/TimetableResponseContract.cs +++ b/source/DotBahn.Timetables/Internal/Contracts/TimetableResponseContract.cs @@ -3,17 +3,17 @@ namespace DotBahn.Timetables.Internal.Contracts; /// -/// Raw timetable response +/// Raw timetable response. /// [ExcludeFromCodeCoverage] internal record TimetableResponseContract { /// - /// Station name or ID + /// Station name or ID. /// public string Station { get; init; } = string.Empty; /// - /// List of stops in the timetable + /// List of stops in the timetable. /// public List Stops { get; init; } = []; } diff --git a/source/DotBahn.Timetables/Internal/Contracts/TripInfoContract.cs b/source/DotBahn.Timetables/Internal/Contracts/TripInfoContract.cs index 6f67dc0..4db4d53 100644 --- a/source/DotBahn.Timetables/Internal/Contracts/TripInfoContract.cs +++ b/source/DotBahn.Timetables/Internal/Contracts/TripInfoContract.cs @@ -3,32 +3,32 @@ namespace DotBahn.Timetables.Internal.Contracts; /// -/// Raw trip label (train information) +/// Raw trip label (train information). /// [ExcludeFromCodeCoverage] internal record TripInfoContract { /// - /// Filter flags + /// Filter flags. /// public string? FilterFlags { get; init; } /// - /// Trip type (p, e, f) + /// Trip type (p, e, f). /// public string? TripType { get; init; } /// - /// Train owner + /// Train owner. /// public string? Owner { get; init; } /// - /// Train category (e.g., ICE) + /// Train category (e.g., ICE). /// public string? Category { get; init; } /// - /// Train number + /// Train number. /// public string? Number { get; init; } } diff --git a/source/DotBahn.Timetables/Internal/Json/TimetableJsonContext.cs b/source/DotBahn.Timetables/Internal/Json/TimetableJsonContext.cs index 3fd8c39..89ca32a 100644 --- a/source/DotBahn.Timetables/Internal/Json/TimetableJsonContext.cs +++ b/source/DotBahn.Timetables/Internal/Json/TimetableJsonContext.cs @@ -6,7 +6,7 @@ namespace DotBahn.Timetables.Internal.Json; /// -/// Source-generated JSON serialization metadata for timetable contracts and enums +/// Source-generated JSON serialization metadata for timetable contracts and enums. /// [ExcludeFromCodeCoverage] [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] diff --git a/source/DotBahn.Timetables/Internal/Parsing/TimetableXmlParser.cs b/source/DotBahn.Timetables/Internal/Parsing/TimetableXmlParser.cs index d541d3b..f1dd9a6 100644 --- a/source/DotBahn.Timetables/Internal/Parsing/TimetableXmlParser.cs +++ b/source/DotBahn.Timetables/Internal/Parsing/TimetableXmlParser.cs @@ -6,7 +6,7 @@ namespace DotBahn.Timetables.Internal.Parsing; /// -/// Manual XML parser for +/// Manual XML parser for . /// internal sealed class TimetableXmlParser : IParser { private static readonly XName StationName = "timetable"; @@ -17,7 +17,7 @@ internal sealed class TimetableXmlParser : IParser { private static readonly XName MessageName = "m"; /// - /// Thrown when the XML is malformed or required attributes are missing + /// Thrown when the XML is malformed or required attributes are missing. public TimetableResponseContract Parse(string input) { if (string.IsNullOrWhiteSpace(input)) { return new TimetableResponseContract(); @@ -38,7 +38,7 @@ public TimetableResponseContract Parse(string input) { } /// - /// Parses a single stop element + /// Parses a single stop element. /// private static StopDataContract ParseStop(XElement stopElement) { var tripInfo = stopElement.Element(TripInfoName) is { } tripInfoElement ? ParseTripInfo(tripInfoElement) : null; @@ -52,23 +52,23 @@ private static StopDataContract ParseStop(XElement stopElement) { TripInfo = tripInfo, Arrival = arrival, Departure = departure, - Messages = messages.Count > 0 ? messages : null, + Messages = messages.Count > 0 ? messages : null }; } /// - /// Parses a trip label element + /// Parses a trip label element. /// private static TripInfoContract ParseTripInfo(XElement element) => new() { Category = (string?)element.Attribute("c"), Number = (string?)element.Attribute("n"), Owner = (string?)element.Attribute("o"), TripType = (string?)element.Attribute("t"), - FilterFlags = (string?)element.Attribute("f"), + FilterFlags = (string?)element.Attribute("f") }; /// - /// Parses an arrival or departure event element + /// Parses an arrival or departure event element. /// private static EventContract ParseEvent(XElement element) => new() { PlannedTime = (string?)element.Attribute("pt"), @@ -84,11 +84,11 @@ private static StopDataContract ParseStop(XElement stopElement) { PlannedDistantEndpoint = (string?)element.Attribute("pde"), ChangedDistantEndpoint = (string?)element.Attribute("cde"), Wings = (string?)element.Attribute("wings"), - Transition = (string?)element.Attribute("tra"), + Transition = (string?)element.Attribute("tra") }; /// - /// Parses a message element + /// Parses a message element. /// private static MessageContract ParseMessage(XElement element) => new() { Id = (string?)element.Attribute("id"), @@ -103,7 +103,7 @@ private static StopDataContract ParseStop(XElement stopElement) { Priority = (string?)element.Attribute("priority"), Owner = (string?)element.Attribute("owner"), Category = (string?)element.Attribute("cat"), - Text = element.Value, + Text = element.Value }; private static string RequiredAttr(XElement element, string name) => (string?)element.Attribute(name) ?? throw new XmlException($"Missing required attribute '{name}' on <{element.Name}>."); diff --git a/source/DotBahn.Timetables/Internal/Transformers/TimetableMerger.cs b/source/DotBahn.Timetables/Internal/Transformers/TimetableMerger.cs index 9efa4ff..beecddd 100644 --- a/source/DotBahn.Timetables/Internal/Transformers/TimetableMerger.cs +++ b/source/DotBahn.Timetables/Internal/Transformers/TimetableMerger.cs @@ -5,7 +5,7 @@ namespace DotBahn.Timetables.Internal.Transformers; /// -/// Merges timetable model updates into the current timetable +/// Merges timetable model updates into the current timetable. /// internal sealed class TimetableMerger : IMerger { /// @@ -30,11 +30,11 @@ public Timetable Merge(Timetable current, Timetable changes) { } /// - /// Merges two in a new instance + /// Merges two in a new instance. /// - /// The current value - /// The changed value - /// Instance with combined values + /// The current value. + /// The changed value. + /// Instance with combined values. private static TimetableStop MergeStop(TimetableStop current, TimetableStop change) => new() { Id = current.Id, Train = current.Train, @@ -44,11 +44,11 @@ public Timetable Merge(Timetable current, Timetable changes) { }; /// - /// Merges two in a new instance + /// Merges two in a new instance. /// - /// The current value - /// The changed value - /// Instance with combined values + /// The current value. + /// The changed value. + /// Instance with combined values. private static TrainEvent? MergeEvent(TrainEvent? current, TrainEvent? change) { if (current == null || change == null) { return change; @@ -66,12 +66,12 @@ public Timetable Merge(Timetable current, Timetable changes) { } /// - /// Merges two in a new instance + /// Merges two in a new instance. /// - /// The current value - /// The changed value - /// The type that can be changed - /// Instance with combined values + /// The current value. + /// The changed value. + /// The type that can be changed. + /// Instance with combined values. private static ChangedValue MergeValue(ChangedValue current, ChangedValue change) where T : struct { var hasRealUpdate = change.HasUpdate && !EqualityComparer.Default.Equals(change.Updated!.Value, current.Original); return new ChangedValue { @@ -81,12 +81,12 @@ private static ChangedValue MergeValue(ChangedValue current, ChangedVal } /// - /// Merges two in a new instance + /// Merges two in a new instance. /// - /// The current value - /// The changed value - /// The type that can be changed - /// Instance with combined values + /// The current value. + /// The changed value. + /// The type that can be changed. + /// Instance with combined values. private static ChangedRef MergeRef(ChangedRef current, ChangedRef change) where T : class { var hasRealUpdate = change.HasUpdate && !Equals(change.Updated, current.Original); return new ChangedRef { @@ -96,11 +96,11 @@ private static ChangedRef MergeRef(ChangedRef current, ChangedRef ch } /// - /// Merges two message sequences, appending new messages while avoiding duplicates by ID + /// Merges two message sequences, appending new messages while avoiding duplicates by ID. /// - /// The current messages - /// The changed messages - /// Combined list of messages + /// The current messages. + /// The changed messages. + /// Combined list of messages. private static IReadOnlyList MergeMessages(IReadOnlyList current, IReadOnlyList change) { var messages = current.ToList(); var existing = new HashSet(messages.Select(m => m.Id)); diff --git a/source/DotBahn.Timetables/Internal/Transformers/TimetableTransformer.cs b/source/DotBahn.Timetables/Internal/Transformers/TimetableTransformer.cs index cfcaa01..f67a3be 100644 --- a/source/DotBahn.Timetables/Internal/Transformers/TimetableTransformer.cs +++ b/source/DotBahn.Timetables/Internal/Transformers/TimetableTransformer.cs @@ -10,7 +10,7 @@ namespace DotBahn.Timetables.Internal.Transformers; /// -/// Transforms timetable contracts into domain models +/// Transforms timetable contracts into domain models. /// internal sealed class TimetableTransformer : ITransformer { private const string BahnTimeFormat = "yyMMddHHmm"; @@ -27,10 +27,10 @@ public Timetable Transform(TimetableResponseContract contracts) { } /// - /// Transforms the into its domain model + /// Transforms the into its domain model. /// - /// The contract to transform - /// The transformed model + /// The contract to transform. + /// The transformed model. private static TimetableStop TransformStop(StopDataContract contract) => new() { Id = contract.Id, Train = TransformTrainLabel(contract.TripInfo, contract), @@ -40,10 +40,10 @@ public Timetable Transform(TimetableResponseContract contracts) { }; /// - /// Transforms the into its domain model + /// Transforms the into its domain model. /// - /// The contract to transform - /// The transformed model + /// The contract to transform. + /// The transformed model. private static TrainEvent? TransformEvent(EventContract? contract) { if (contract == null) { return null; @@ -87,25 +87,25 @@ public Timetable Transform(TimetableResponseContract contracts) { } /// - /// Transforms the into its domain model + /// Transforms the into its domain model. /// - /// The contract to transform - /// The stop contract that owns the trip label - /// The transformed model + /// The contract to transform. + /// The stop contract that owns the trip label. + /// The transformed model. private static TrainLabel TransformTrainLabel(TripInfoContract? contract, StopDataContract stop) => new() { Category = contract?.Category ?? string.Empty, Number = contract?.Number ?? string.Empty, Owner = contract?.Owner ?? string.Empty, Type = string.IsNullOrEmpty(contract?.TripType) ? null : EnumUtil.Parse(contract.TripType, TripType.Passenger, TimetableJsonContext.Default.TripType), FilterFlags = contract?.FilterFlags, - Line = stop.Departure?.Line ?? stop.Arrival?.Line, + Line = stop.Departure?.Line ?? stop.Arrival?.Line }; /// - /// Transforms the into its domain model + /// Transforms the into its domain model. /// - /// The contract to transform - /// The transformed model + /// The contract to transform. + /// The transformed model. private static TimetableMessage TransformMessage(MessageContract contract) => new() { Id = contract.Id ?? string.Empty, Type = EnumUtil.Parse(contract.Type, MessageType.Him, TimetableJsonContext.Default.MessageType), @@ -125,10 +125,10 @@ public Timetable Transform(TimetableResponseContract contracts) { }; /// - /// Parses the Bahn time to a + /// Parses the Bahn time to a . /// - /// A bahn formatted time - /// A parsed time + /// A bahn formatted time. + /// A parsed time. private static DateTime? ParseBahnTime(string? time) { if (string.IsNullOrEmpty(time)) { return null; @@ -138,9 +138,9 @@ public Timetable Transform(TimetableResponseContract contracts) { } /// - /// Parses a pipe-separated list to an array + /// Parses a pipe-separated list to an array. /// - /// The list to separate - /// A parsed list + /// The list to separate. + /// A parsed list. private static string[] ParsePipeSeparatedList(string? list) => (string.IsNullOrEmpty(list) ? null : list.Split('|', StringSplitOptions.RemoveEmptyEntries)) ?? []; } diff --git a/source/DotBahn.Timetables/Models/Enumerations/EventStatus.cs b/source/DotBahn.Timetables/Models/Enumerations/EventStatus.cs index 0cb2112..22d50b1 100644 --- a/source/DotBahn.Timetables/Models/Enumerations/EventStatus.cs +++ b/source/DotBahn.Timetables/Models/Enumerations/EventStatus.cs @@ -3,30 +3,30 @@ namespace DotBahn.Timetables.Models.Enumerations; /// -/// Status of an arrival or departure event +/// Status of an arrival or departure event. /// [JsonConverter(typeof(JsonStringEnumConverter))] public enum EventStatus { /// - /// The event was planned. This status is also used when the cancellation of an event has been revoked + /// The event was planned. This status is also used when the cancellation of an event has been revoked. /// [JsonStringEnumMemberName("p")] Planned, /// - /// The event was added to the planned data (new stop) + /// The event was added to the planned data (new stop). /// [JsonStringEnumMemberName("a")] Added, /// - /// The event was canceled. As a changed status, this can apply to both planned and added stops + /// The event was canceled. As a changed status, this can apply to both planned and added stops. /// [JsonStringEnumMemberName("c")] Cancelled, /// - /// There is no further information available + /// There is no further information available. /// Unknown } diff --git a/source/DotBahn.Timetables/Models/Enumerations/MessagePriority.cs b/source/DotBahn.Timetables/Models/Enumerations/MessagePriority.cs index 27672fb..913e13d 100644 --- a/source/DotBahn.Timetables/Models/Enumerations/MessagePriority.cs +++ b/source/DotBahn.Timetables/Models/Enumerations/MessagePriority.cs @@ -1,36 +1,36 @@ namespace DotBahn.Timetables.Models.Enumerations; /// -/// Priority level of a timetable message +/// Priority level of a timetable message. /// public enum MessagePriority { /// - /// No priority information available + /// No priority information available. /// None = 0, /// - /// High priority message + /// High priority message. /// High = 1, /// - /// Medium priority message + /// Medium priority message. /// Medium = 2, /// - /// Low priority message + /// Low priority message. /// Low = 3, /// - /// Message has been resolved/done + /// Message has been resolved/done. /// Done = 4, /// - /// There is no further information available + /// There is no further information available. /// Unknown } diff --git a/source/DotBahn.Timetables/Models/Enumerations/MessageType.cs b/source/DotBahn.Timetables/Models/Enumerations/MessageType.cs index 8d8946c..c20b1bf 100644 --- a/source/DotBahn.Timetables/Models/Enumerations/MessageType.cs +++ b/source/DotBahn.Timetables/Models/Enumerations/MessageType.cs @@ -3,60 +3,60 @@ namespace DotBahn.Timetables.Models.Enumerations; /// -/// Type of timetable message +/// Type of timetable message. /// [JsonConverter(typeof(JsonStringEnumConverter))] public enum MessageType { /// - /// A HIM message + /// A HIM message. /// [JsonStringEnumMemberName("h")] Him, /// - /// A message about a quality change + /// A message about a quality change. /// [JsonStringEnumMemberName("q")] QualityChange, /// - /// A free text message + /// A free text message. /// [JsonStringEnumMemberName("f")] Free, /// - /// A message about the cause of a delay + /// A message about the cause of a delay. /// [JsonStringEnumMemberName("d")] CauseOfDelay, /// - /// An IBIS message (generated from IRIS-AP) + /// An IBIS message (generated from IRIS-AP). /// [JsonStringEnumMemberName("i")] Ibis, /// - /// An IBIS message (generated from IRIS-AP) not yet assigned to a train + /// An IBIS message (generated from IRIS-AP) not yet assigned to a train. /// [JsonStringEnumMemberName("u")] UnassignedIbis, /// - /// A major disruption + /// A major disruption. /// [JsonStringEnumMemberName("r")] Disruption, /// - /// A connection message + /// A connection message. /// [JsonStringEnumMemberName("c")] Connection, /// - /// There is no further information available + /// There is no further information available. /// Unknown } diff --git a/source/DotBahn.Timetables/Models/Enumerations/TripType.cs b/source/DotBahn.Timetables/Models/Enumerations/TripType.cs index 3ffbfd1..f721b26 100644 --- a/source/DotBahn.Timetables/Models/Enumerations/TripType.cs +++ b/source/DotBahn.Timetables/Models/Enumerations/TripType.cs @@ -3,48 +3,48 @@ namespace DotBahn.Timetables.Models.Enumerations; /// -/// Type of trip/train service +/// Type of trip/train service. /// [JsonConverter(typeof(JsonStringEnumConverter))] public enum TripType { /// - /// Regular passenger service + /// Regular passenger service. /// [JsonStringEnumMemberName("p")] Passenger, /// - /// Empty train movement (no passengers) + /// Empty train movement (no passengers). /// [JsonStringEnumMemberName("e")] Empty, /// - /// Additional train type (z) + /// Additional train type (z). /// [JsonStringEnumMemberName("z")] Z, /// - /// Additional train type (s) + /// Additional train type (s). /// [JsonStringEnumMemberName("s")] S, /// - /// Additional train type (h) + /// Additional train type (h). /// [JsonStringEnumMemberName("h")] H, /// - /// Additional train type (n) + /// Additional train type (n). /// [JsonStringEnumMemberName("n")] N, /// - /// There is no further information available + /// There is no further information available. /// Unknown } diff --git a/source/DotBahn.Timetables/Models/Timetable.cs b/source/DotBahn.Timetables/Models/Timetable.cs index 5037487..400303a 100644 --- a/source/DotBahn.Timetables/Models/Timetable.cs +++ b/source/DotBahn.Timetables/Models/Timetable.cs @@ -1,21 +1,21 @@ namespace DotBahn.Timetables.Models; /// -/// A timetable containing stops and messages for a station +/// A timetable containing stops and messages for a station. /// public class Timetable { /// - /// Station name + /// Station name. /// public required string Station { get; init; } /// - /// List of stops (arrivals and departures) at this station + /// List of stops (arrivals and departures) at this station. /// public IEnumerable Stops { get; init; } = []; /// - /// Station-level messages (disruptions, announcements) + /// Station-level messages (disruptions, announcements). /// public IReadOnlyList Messages { get; init; } = []; } diff --git a/source/DotBahn.Timetables/Models/TimetableMessage.cs b/source/DotBahn.Timetables/Models/TimetableMessage.cs index 9cf9a00..d93eee5 100644 --- a/source/DotBahn.Timetables/Models/TimetableMessage.cs +++ b/source/DotBahn.Timetables/Models/TimetableMessage.cs @@ -4,91 +4,91 @@ namespace DotBahn.Timetables.Models; /// /// A message associated with an event, a stop, or a trip. -/// Messages can represent disruptions, delays, quality changes, or general information +/// Messages can represent disruptions, delays, quality changes, or general information. /// public class TimetableMessage { /// - /// Unique message identifier + /// Unique message identifier. /// public required string Id { get; init; } /// - /// Type of message indicating its source and purpose + /// Type of message indicating its source and purpose. /// public required MessageType Type { get; init; } /// - /// Timestamp when the message was created + /// Timestamp when the message was created. /// public required DateTime Timestamp { get; init; } /// - /// Message code + /// Message code. /// public int? Code { get; init; } /// - /// Message category + /// Message category. /// public string? Category { get; init; } /// - /// External category for the message + /// External category for the message. /// public string? ExternalCategory { get; init; } /// - /// Message priority level + /// Message priority level. /// public MessagePriority? Priority { get; init; } /// - /// Message owner/source + /// Message owner/source. /// public string? Owner { get; init; } /// - /// Start of the message validity period + /// Start of the message validity period. /// public DateTime? ValidFrom { get; init; } /// - /// End of the message validity period + /// End of the message validity period. /// public DateTime? ValidTo { get; init; } /// - /// Internal text (not intended for public display) + /// Internal text (not intended for public display). /// public string? InternalText { get; init; } /// - /// External text (public-facing message content) + /// External text (public-facing message content). /// public string? ExternalText { get; init; } /// - /// External link associated with the message + /// External link associated with the message. /// public string? ExternalLink { get; init; } /// - /// Whether the message has been deleted + /// Whether the message has been deleted. /// public bool IsDeleted { get; init; } /// - /// Trip labels of affected trains + /// Trip labels of affected trains. /// public IReadOnlyList AffectedTrips { get; init; } = []; /// - /// The display text, preferring external text over internal text + /// The display text, preferring external text over internal text. /// public string? Text => ExternalText ?? InternalText; /// - /// Whether the message is currently active (not deleted and within validity period) + /// Whether the message is currently active (not deleted and within validity period). /// public bool IsActive => !IsDeleted && (ValidTo == null || ValidTo > DateTime.Now); } diff --git a/source/DotBahn.Timetables/Models/TimetableStop.cs b/source/DotBahn.Timetables/Models/TimetableStop.cs index a886822..3e61f22 100644 --- a/source/DotBahn.Timetables/Models/TimetableStop.cs +++ b/source/DotBahn.Timetables/Models/TimetableStop.cs @@ -1,52 +1,52 @@ namespace DotBahn.Timetables.Models; /// -/// A stop in a timetable, representing a train's arrival and/or departure at a station +/// A stop in a timetable, representing a train's arrival and/or departure at a station. /// public class TimetableStop { /// /// Unique stop identifier consisting of: /// - /// A daily trip ID that uniquely identifies a trip within one day (maybe negative) - /// A 6-digit date specifier (YYMMdd) indicating the planned departure date from the start station - /// An index indicating the position of the stop within the trip + /// A daily trip ID that uniquely identifies a trip within one day (maybe negative). + /// A 6-digit date specifier (YYMMdd) indicating the planned departure date from the start station. + /// An index indicating the position of the stop within the trip. /// /// /// -7874571842864554321-140331-11 public required string Id { get; init; } /// - /// Train identification information + /// Train identification information. /// public required TrainLabel Train { get; init; } /// - /// Arrival event, if the train arrives at this station + /// Arrival event, if the train arrives at this station. /// public TrainEvent? Arrival { get; init; } /// - /// Whether this is an arrival-only stop (train terminates here) + /// Whether this is an arrival-only stop (train terminates here). /// public bool IsArrivalOnly => Arrival != null && Departure == null; /// - /// Departure event, if the train departs from this station + /// Departure event, if the train departs from this station. /// public TrainEvent? Departure { get; init; } /// - /// Whether this is a departure-only stop (train originates here) + /// Whether this is a departure-only stop (train originates here). /// public bool IsDepartureOnly => Departure != null && Arrival == null; /// - /// Whether this is a through stop (train both arrives and departs) + /// Whether this is a through stop (train both arrives and departs). /// public bool IsThrough => Arrival != null && Departure != null; /// - /// Messages associated with this stop + /// Messages associated with this stop. /// public IReadOnlyList Messages { get; init; } = []; } diff --git a/source/DotBahn.Timetables/Models/TrainEvent.cs b/source/DotBahn.Timetables/Models/TrainEvent.cs index eac31f4..633ec33 100644 --- a/source/DotBahn.Timetables/Models/TrainEvent.cs +++ b/source/DotBahn.Timetables/Models/TrainEvent.cs @@ -4,28 +4,28 @@ namespace DotBahn.Timetables.Models; /// -/// Represents an arrival or departure event at a station +/// Represents an arrival or departure event at a station. /// public class TrainEvent { /// - /// The time of this event + /// The time of this event. /// public required ChangedValue Time { get; init; } /// - /// The platform this event occurs on + /// The platform this event occurs on. /// public required ChangedRef Platform { get; init; } /// - /// The event status + /// The event status. /// public required ChangedValue Status { get; init; } /// /// Planned distant endpoint. /// - /// For international trains, this indicates the final destination beyond the stations listed in the path + /// For international trains, this indicates the final destination beyond the stations listed in the path. /// /// public required ChangedRef DistantEndpoint { get; init; } @@ -33,20 +33,20 @@ public class TrainEvent { /// /// Planned path as a sequence of station names. /// - /// For arrival, the path indicates stations before the current station (the first element is trip's start) - /// For departure, the path indicates stations after the current station (the last element is the trip's destination) - /// The current station is never included in the path + /// For arrival, the path indicates stations before the current station (the first element is trip's start). + /// For departure, the path indicates stations after the current station (the last element is the trip's destination). + /// The current station is never included in the path. /// /// public ChangedRef> Path { get; init; } = new() { Original = [] }; /// - /// Wing train IDs. A list of trip IDs for coupled trains (train portions) + /// Wing train IDs. A list of trip IDs for coupled trains (train portions). /// public IReadOnlyList Wings { get; init; } = []; /// - /// Messages associated with this event + /// Messages associated with this event. /// public IReadOnlyList Messages { get; init; } = []; } diff --git a/source/DotBahn.Timetables/Models/TrainLabel.cs b/source/DotBahn.Timetables/Models/TrainLabel.cs index aaa37a9..659dcfe 100644 --- a/source/DotBahn.Timetables/Models/TrainLabel.cs +++ b/source/DotBahn.Timetables/Models/TrainLabel.cs @@ -3,36 +3,36 @@ namespace DotBahn.Timetables.Models; /// -/// Identifies a train with its category, number, operator, and service type information +/// Identifies a train with its category, number, operator, and service type information. /// public class TrainLabel { /// - /// Trip category (e.g. "ICE", "RE", "RB", "S") + /// Trip category (e.g. "ICE", "RE", "RB", "S"). /// public required string Category { get; init; } /// - /// Trip/train number (e.g. "4523") + /// Trip/train number (e.g. "4523"). /// public required string Number { get; init; } /// - /// A unique short-form code intended to map a trip to a specific railway undertaking (EVU) + /// A unique short-form code intended to map a trip to a specific railway undertaking (EVU). /// public required string Owner { get; init; } /// - /// Customer-facing line name (e.g. "RE14" or "S1") + /// Customer-facing line name (e.g. "RE14" or "S1"). /// public string? Line { get; init; } /// - /// Trip type indicating the kind of service + /// Trip type indicating the kind of service. /// public TripType? Type { get; init; } /// - /// Filter flags indicating service classification (e.g. "N" for regional, "F" for long-distance, "D" for international) + /// Filter flags indicating service classification (e.g. "N" for regional, "F" for long-distance, "D" for international). /// public string? FilterFlags { get; init; } diff --git a/source/DotBahn.Timetables/ServiceCollectionExtensions.cs b/source/DotBahn.Timetables/ServiceCollectionExtensions.cs index 6db5f84..24e0488 100644 --- a/source/DotBahn.Timetables/ServiceCollectionExtensions.cs +++ b/source/DotBahn.Timetables/ServiceCollectionExtensions.cs @@ -12,19 +12,19 @@ namespace DotBahn.Timetables; /// -/// Extension methods for registering the DotBahn Timetables client +/// Extension methods for registering the DotBahn Timetables client. /// public static class ServiceCollectionExtensions { private const string OptionsName = "DotBahn.Timetables"; - private static readonly Uri DefaultTimetablesEndpoint = new("https://apis.deutschebahn.com/db-api-marketplace/apis/timetables/v1/"); /// - /// Registers the with its parser, transformer, and merger services + /// Registers the with its parser, transformer, and merger services. /// - /// The service collection to add to - /// Optional action to override default client options - /// The service collection for chaining + /// The service collection to add to. + /// Optional action to override default client options. + /// The service collection for chaining. + [Obsolete("The Deutsche Bahn Timetables API is being shut down. Use AddDotBahnBoards() from DotBahn.Boards instead.", false)] public static IServiceCollection AddDotBahnTimetables(this IServiceCollection services, Action? configuration = null) { services.AddOptions(OptionsName) .Configure(opts => { @@ -37,7 +37,7 @@ public static IServiceCollection AddDotBahnTimetables(this IServiceCollection se services.AddHttpClient(OptionsName, (http, sp) => { var options = sp.GetRequiredService>().Get(OptionsName); http.BaseAddress = options.BaseEndpoint; - http.DefaultRequestHeaders.UserAgent.ParseAdd("DotBahn/2.0 (+https://github.com/rlvelte/dotbahn)"); + http.DefaultRequestHeaders.UserAgent.ParseAdd("DotBahn/2.X (+https://github.com/rlvelte/dotbahn)"); var auth = sp.GetRequiredService(); var parser = sp.GetRequiredService>(); diff --git a/source/DotBahn.Timetables/TimetableClient.cs b/source/DotBahn.Timetables/TimetableClient.cs index 6ea7f99..2346b84 100644 --- a/source/DotBahn.Timetables/TimetableClient.cs +++ b/source/DotBahn.Timetables/TimetableClient.cs @@ -1,3 +1,4 @@ +using System.Globalization; using DotBahn.Common.Auth; using DotBahn.Common.Clients; using DotBahn.Common.Parsing; @@ -11,8 +12,9 @@ namespace DotBahn.Timetables; /// -/// Client for accessing 'Deutsche Bahn Timetables'-API +/// Client for accessing 'Deutsche Bahn Timetables'-API. /// +[Obsolete("The Deutsche Bahn Timetables API is being shut down. Use DotBahn.Boards instead.", false)] public class TimetableClient : ClientBase, ITimetableClient { private readonly IParser _parser; private readonly ITransformer _transformer; @@ -22,13 +24,13 @@ public class TimetableClient : ClientBase, ITimetableClient { protected override string ApiName => "timetables"; /// - /// Client for accessing 'Deutsche Bahn Timetables'-API + /// Client for accessing 'Deutsche Bahn Timetables'-API. /// - /// The HTTP client used for requests - /// The provider used for retrieving access tokens - /// The parser for this contract type - /// The transformer for this model and contract types - /// The merger for the target type + /// The HTTP client used for requests. + /// The provider used for retrieving access tokens. + /// The parser for this contract type. + /// The transformer for this model and contract types. + /// The merger for the target type. [ActivatorUtilitiesConstructor] internal TimetableClient(HttpClient http, IAuthorization authorization, IParser parser, ITransformer transformer, IMerger merger) : base(http, authorization) { @@ -38,16 +40,15 @@ internal TimetableClient(HttpClient http, IAuthorization authorization, IParser< } /// - /// Client for accessing 'Deutsche Bahn Timetables'-API + /// Client for accessing 'Deutsche Bahn Timetables'-API. /// /// /// Creates and owns its own . Dispose this instance to release it. - /// Use only when instantiating manually without a DI container + /// Use only when instantiating manually without a DI container. /// - /// The options for this instance - /// The auth credentials for the client - /// Thrown when is null - /// Thrown when is null + /// The options for this instance. + /// The auth credentials for the client. + /// Thrown when or is null. public TimetableClient(ClientOptions options, AuthorizationOptions auth) : base(options, auth) { _parser = new TimetableXmlParser(); _transformer = new TimetableTransformer(); @@ -56,8 +57,8 @@ public TimetableClient(ClientOptions options, AuthorizationOptions auth) : base( /// public async Task GetTimetableAsync(int eva, DateTime dateTime, CancellationToken ct = default) { - var dateStr = dateTime.ToString("yyMMdd"); - var hourStr = dateTime.ToString("HH"); + var dateStr = dateTime.ToString("yyMMdd", CultureInfo.InvariantCulture); + var hourStr = dateTime.ToString("HH", CultureInfo.InvariantCulture); var response = await GetAsync($"/plan/{eva}/{dateStr}/{hourStr}", _parser, "application/xml", null, ct).ConfigureAwait(false); return _transformer.Transform(response); } diff --git a/source/DotBahn.Timetables/packages.lock.json b/source/DotBahn.Timetables/packages.lock.json index 55c79b9..1f3715b 100644 --- a/source/DotBahn.Timetables/packages.lock.json +++ b/source/DotBahn.Timetables/packages.lock.json @@ -4,55 +4,44 @@ "net10.0": { "Microsoft.Extensions.Http": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "IDsXLGGz7nJMsqspWnErsP18WyAVf6V9Ixl4p47/8/95Jak3ZA1YWhQ0iesMVwubVhkVZGoO9m9ADUnK0m6HLw==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Http.Resilience": { "type": "Direct", - "requested": "[10.11.0, )", - "resolved": "10.11.0", - "contentHash": "6/YEoPCcQLzExm4x4FH5c38JffbhkMaTtXsrDmYNozt9KRtdXK3TsDeuKSBZJno+41oIDGBONb2up0zCsuEERw==", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "5VawCrg+VgVT2hNurSSEWUnq0pvNoH+Zt82s5Wpl/8jdnmU8DpRlr+M3DcdtVgeBG7mRyk3GtSRbf8PB/HrL3w==", "dependencies": { - "Microsoft.Extensions.Http.Diagnostics": "10.11.0", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Resilience": "10.11.0" + "Microsoft.Extensions.Http.Diagnostics": "11.0.1", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Resilience": "11.0.1" } }, "Microsoft.Extensions.Options": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.NET.ILLink.Tasks": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "YlTamXppEQls6DYWt7RdUuwWDb0lyw/vXCaGeQpLCpsLmfwGuCkOz/vIGgMTV7ECsJcavkCOkxZXv9s8rdAHkQ==" - }, - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[10.0.403, )", - "resolved": "10.0.403", - "contentHash": "T4WYxWydJGNQRe/EgURFlhPZ1cHYgivrCCHSomCcfQzGzhkDYGNn5bUwwjs4/PHuMxsmGaLvPv2puG8lluA1IA==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "10.0.403", - "Microsoft.SourceLink.Common": "10.0.403", - "System.IO.Hashing": "10.0.14" - } + "requested": "[10.0.15, )", + "resolved": "10.0.15", + "contentHash": "u0WnRcZgBZYHlVFpbe/3Adpmb9rmNJ8/fmEwqc/xjB7fFppq+gfaLJd3Sdaw+J02zV0eP/T9dneQ3Dv5jWw6bw==" }, "MinVer": { "type": "Direct", @@ -60,232 +49,231 @@ "resolved": "8.0.0", "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" }, - "Microsoft.Build.Tasks.Git": { + "Microsoft.Extensions.AmbientMetadata.Application": { "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "1furteBFeemMmZ4s+ORjQb7YtO+wG63NJahbQbRUi91FV6V87BdV0U3vX1jbMC6iKSELYYoXWssSzLu3mx0i2w==", + "resolved": "11.0.1", + "contentHash": "tm28s2ODWZ6RdysP06NI3B23DUY5OfHG35ihMHxVAO3hywZAczDVjrkYMfBY//J4HQqfDHS5op84BhnF7ROseQ==", "dependencies": { - "System.IO.Hashing": "10.0.14" + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, - "Microsoft.Extensions.AmbientMetadata.Application": { + "Microsoft.Extensions.Compliance.Abstractions": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "aMCm7C6CexZT8W/p8zRp4BoxSnqRs3MmkBF7FvPIXC92b7vqs2SL0J+mVJi5W2Mk9Vb4ZRFWe9sdzFew6zUl1w==", + "resolved": "11.0.1", + "contentHash": "DUwdXgIxJKH9zBNg/SUBqOX0FpXCq7w80CIzrr0Jcw5tBXS926AtCcidoAsEHq5e/c6KQ8rWhSt7NxFxak8N/Q==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15" } }, - "Microsoft.Extensions.Compliance.Abstractions": { + "Microsoft.Extensions.Compliance.Redaction": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2mjAb3Sm5k6uNeI+IyXpggYMpfdDDGgZSwUm9QQsm5QgZboJWbm2eU+6wNMrlfFEao11yq6JS1zXI7SVQQ0NuQ==", + "resolved": "11.0.1", + "contentHash": "2rwe98yZEn4+aXjAg5DdcROMg6m2w3tejf/mRk4/fBCHKM2EWCaFTmbHLtz1BfyBxMY00/08XFoN0wzWYNiSiQ==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13" + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, "Microsoft.Extensions.Configuration": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Configuration.Binder": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" } }, "Microsoft.Extensions.DependencyInjection.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" }, "Microsoft.Extensions.DependencyInjection.AutoActivation": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "h/sovspxVmT2DTIbWORMG0Gi3zVcPQzNl3kbwtpo0LoUXYbe2+66wQqZYwaF2ZWKN8HDdHv5yoc7d0DbDBBlnA==", + "resolved": "11.0.1", + "contentHash": "OuVIF5TmsfonN2Fqmi2zlUtbFQNqQiflhgo/rh64ptrqYrB4wZLwKbXr/HzrQXMf+h3jIbWrjIdJFspGqcvuuQ==", "dependencies": { - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13" + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15" } }, "Microsoft.Extensions.Diagnostics": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "80VqW8eKxQaxBOLDNpLUdxOlxzWn/jqBSxNBCfD8GCjcshNDpFvUgKh8uvvZwvkfBbwmNPWPWHyy9F+RLd1dlQ==", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" } }, "Microsoft.Extensions.Diagnostics.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vm+PPso6vOwGeX52MdOPh6z/R6KHgxQUwqq7k7Jc9jhy2JOxO2KB4xfoJQBBp2Ni8M4zKgJ4r2a1dgrYG7+MKw==", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "Dp/FaAPo3U9h3HsWT1dcdRRV//rm+MQF5iKpY/WxL5swwV+wZNE5eyJZ0kgy9Upl/kHz4ejpiLMloxDIuJaoJQ==", + "resolved": "11.0.1", + "contentHash": "mqqpmAFNRLa4cozN3RvT/T81k4aarwMc8xb8VVQgLqUE7AAoN/WWayZAvP+4hy9+KujP3dfn3taU06fZJPIbgA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13" + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" } }, "Microsoft.Extensions.FileProviders.Abstractions": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "BZDwtN3uoWRghDi5lRRZPDjMMCg2Ds7J6YEYjqka/TLjqnzquEpXyvchrIMeoubwT1ns23ow6PPeAoBHJO81Rw==", + "resolved": "10.0.15", + "contentHash": "1RSYAUtJeb76m2T0u5BbvwKY3s+ge9fT3cj1odvo5Bm+frc7pU9RSeXeMIlYHV8GjpqLdv2neeeomz010yYL8A==", "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.13" + "Microsoft.Extensions.Primitives": "10.0.15" } }, "Microsoft.Extensions.Hosting.Abstractions": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "zIrbe9vkIFXxW3mOApIOWXw+xMwX7Cgsptr3ZSlglJt4hW2qp4fB/JU1NHgAevteBNH4PicvU9DsFPHxlnnloA==", + "resolved": "10.0.15", + "contentHash": "s/JBiwR3F/vKRCbe6WO5b6t6or1ISaZ3rllchcw6/FSWZmK8s2fAzD7elrZo7592FnMD1fhGoG/wuJL1YYtVXw==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13" + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15" } }, "Microsoft.Extensions.Http.Diagnostics": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "iFcxcuMF/21LO+tDqDyzYVvokJUH03cNalmOJhmjyQSMV3dR4JAgcUBTV1iVH/yruC8wG2RNjvW0xcUgYqmrGg==", + "resolved": "11.0.1", + "contentHash": "mKHY0oFYL3fkAOhBNi2LqWPuEdUJ+HiF28KKUwBkQG2sgXAUdFDDqvJAfu2PcYgtAwsAtl58zuk4SElpPzbCvA==", "dependencies": { - "Microsoft.Extensions.Http": "10.0.13", - "Microsoft.Extensions.Telemetry": "10.11.0" + "Microsoft.Extensions.Compliance.Redaction": "11.0.1", + "Microsoft.Extensions.Http": "10.0.15", + "Microsoft.Extensions.Telemetry": "11.0.1" } }, "Microsoft.Extensions.Logging": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" } }, "Microsoft.Extensions.Logging.Abstractions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" } }, "Microsoft.Extensions.Logging.Configuration": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "OyYJOaE9WbBx1Hp+Dd2zrqeFM0JwH5M/x0VL6tNUv3V18vIAVpix8UjhvY9eW/iXpguEHy68JO/Z9YkBOwftIw==", + "resolved": "10.0.15", + "contentHash": "Km6Ml1/nu0T/f80Btonxf9CWmP/BXI84aJwC5fUbCxRArJ0lH++0ADQrjErZvsSIrKhusTkTSGBChKy2fYAF4w==", "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.Configuration.Binder": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Configuration.Binder": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" } }, "Microsoft.Extensions.ObjectPool": { "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "NX3bhcc0WitPKAVc9Zfi8jeEPClhfEmobUJM4a4bkWhJcBt5IWg6lCrItUoFy4whLjU+atXktURYCweQlR7wfg==" + "resolved": "10.0.15", + "contentHash": "kvd9eyRRQ+OEu9wik7GKgTS+7XnJ5XoOtSXJqmkJtVYV/S4gsBUrobYRSdNeBcb0ymef4L5Q9pZGiTxJ8jJfyQ==" }, "Microsoft.Extensions.Options.ConfigurationExtensions": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4wcIU0rE04ejEfCwHTftu9O8fgH6CRYCe+tseRapikUBn1Kic3QdO7ku22SwFyLrzdWGYPUZMEgv57ZYuuc5gA==", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" } }, "Microsoft.Extensions.Primitives": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" }, "Microsoft.Extensions.Resilience": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "GbN7R2BOoZf3F7aK02nz9kWf6ttbvVzpw1orGG30VmrKTmRV6pasQOCfF2fjKXyHIMC/lAiBEYHCKjgf0OiGvQ==", + "resolved": "11.0.1", + "contentHash": "xgKof6iwAByZNrxWOa7Drk4A953L7U2HleTmx7EXE2Vf6j1crp4RsvNlIVsJMtHKf3ftGKd9gOhR3xES9vxUgg==", "dependencies": { - "Microsoft.Extensions.Diagnostics": "10.0.13", - "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "10.11.0", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0", + "Microsoft.Extensions.Diagnostics": "10.0.15", + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1", "Polly.Extensions": "8.4.2", "Polly.RateLimiting": "8.4.2" } }, "Microsoft.Extensions.Telemetry": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2meCfABvkLPtEBBwGzItIGnhrex1AEn2N+dHvxB5UoozeX/xTtBuUz5BRdjNI5oNgd5T31kC69WWw3BHDc9iZA==", + "resolved": "11.0.1", + "contentHash": "9uuA8entTC9m00m59h6CACSt4IQh9KknB+hPvCteXUTiG67lqJ8BI65fEUJSPSfT3ZDDi01Zg2aY5kRUvD4HPw==", "dependencies": { - "Microsoft.Extensions.AmbientMetadata.Application": "10.11.0", - "Microsoft.Extensions.DependencyInjection.AutoActivation": "10.11.0", - "Microsoft.Extensions.Logging.Configuration": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0" + "Microsoft.Extensions.AmbientMetadata.Application": "11.0.1", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "11.0.1", + "Microsoft.Extensions.Logging.Configuration": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1" } }, "Microsoft.Extensions.Telemetry.Abstractions": { "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "FzcHRan/C2g5X5KD0kPlL4tTROFRpM8sqcXfOIi6FGLsw/d2yoOYMbLJ5hyb8N5QgOVW7e1TdwEN4zVUfcwfdw==", + "resolved": "11.0.1", + "contentHash": "qINZz4G01Wxumqd0hLr6YdzPa3s7jexQWN28EenaiJQnmKdsR9FnBaKENdRRElLc+A5bJKQ+jYw/WHG4ZpIyAg==", "dependencies": { - "Microsoft.Extensions.Compliance.Abstractions": "10.11.0", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13" + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15" } }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "SvzUeqFGrcQxlIgjmcoSGiV5UWcPa0NCTuH69/40uSDsSD/26c6p9cH7XLAxpn+I8+2Zhl1qp+WMugl0oOwBMg==" - }, "Polly.Core": { "type": "Transitive", "resolved": "8.4.2", @@ -310,10 +298,10 @@ "System.Threading.RateLimiting": "8.0.0" } }, - "System.IO.Hashing": { + "System.Diagnostics.DiagnosticSource": { "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "lVqovhCt3HlZe7ONG5ydaj6BYwYI004gldVfMMkJl/lR5ueeCtWNpW4nejOX75sPmzm8vXCxB69GqwHaYCnyUQ==" + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" }, "System.Threading.RateLimiting": { "type": "Transitive", @@ -323,8 +311,8 @@ "dotbahn.common": { "type": "Project", "dependencies": { - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Options": "[10.0.14, )" + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" } } } diff --git a/stryker-config.json b/stryker-config.json index e6e6399..f5bc275 100644 --- a/stryker-config.json +++ b/stryker-config.json @@ -1,21 +1,25 @@ { "stryker-config": { - "coverage-analysis": "off", + "test-runner": "mtp", "mutation-level": "Advanced", + "coverage-analysis": "off", "additional-timeout": 30000, - "reporters": ["html", "json", "progress"], - "ignore-mutations": ["string"], + "reporters": ["html", "json", "markdown", "progress"], + "ignore-mutations": ["block", "statement"], "ignore-methods": [ - "*LogInformation", - "*LogError", - "*LogWarning", - "*LogDebug", - "*LogTrace", - "*LogCritical" + "ConfigureAwait", + "Dispose", + "*ThrowIfNull", + "*ThrowIfNullOrEmpty" ], "mutate": [ "!**/*Options.cs", "!**/ServiceCollectionExtensions.cs" - ] + ], + "thresholds": { + "high": 90, + "low": 80, + "break": 0 + } } } diff --git a/tests/DotBahn.Common.Tests/ClientTestBase.cs b/tests/DotBahn.Common.Tests/ClientTestBase.cs deleted file mode 100644 index 9ffd8d2..0000000 --- a/tests/DotBahn.Common.Tests/ClientTestBase.cs +++ /dev/null @@ -1,33 +0,0 @@ -using DotBahn.Common.Auth; -using Moq; - -namespace DotBahn.Common.Tests; - -public abstract class ClientTestBase : IDisposable { - protected MockHttpHandler HttpHandler { get; } = new(); - protected HttpClient HttpClient { get; } - protected Mock AuthorizationMock { get; } = new(); - - protected ClientTestBase() { - HttpClient = new HttpClient(HttpHandler, disposeHandler: false); - } - - protected void AssertRequest(HttpMethod method, string relativeUrl, string? acceptHeader = null, int? expectedCount = 1) { - var count = expectedCount ?? 1; - var matchingRequests = HttpHandler.SentRequests.Where(r => r.Method == method && r.RequestUri?.ToString().EndsWith(relativeUrl.TrimStart('/'), StringComparison.Ordinal) == true).ToList(); - - Assert.Equal(count, matchingRequests.Count); - - if (acceptHeader == null || matchingRequests.Count <= 0) { - return; - } - - var hasAcceptHeader = matchingRequests[0].Headers.Accept.Any(h => h.MediaType == acceptHeader); - Assert.True(hasAcceptHeader, $"Expected Accept header '{acceptHeader}' not found. Actual headers: {string.Join(", ", matchingRequests[0].Headers.Accept.Select(h => h.MediaType))}"); - } - - public void Dispose() { - HttpClient.Dispose(); - HttpHandler.Dispose(); - } -} diff --git a/tests/DotBahn.Common.Tests/MockHttpHandler.cs b/tests/DotBahn.Common.Tests/MockHttpHandler.cs deleted file mode 100644 index 948a983..0000000 --- a/tests/DotBahn.Common.Tests/MockHttpHandler.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.Net; - -namespace DotBahn.Common.Tests; - -/// -/// Configurable HttpMessageHandler that returns predefined responses -/// and captures requests for verification. -/// -public class MockHttpHandler : HttpMessageHandler { - private readonly Queue> _responseFactories = new(); - - /// - /// Gets the list of all sent HTTP requests. - /// - public List SentRequests { get; } = new(); - - /// - /// Configures the handler to respond with a specific status code and content. - /// - /// The HTTP status code to return. - /// The response content body. - /// The content type header value (default: "application/xml"). - /// The handler instance for fluent chaining. - public void RespondWith(HttpStatusCode status, string content, string contentType = "application/xml") { - _responseFactories.Enqueue(_ => new HttpResponseMessage(status) { - Content = new StringContent(content, System.Text.Encoding.UTF8, contentType) - }); - } - - /// - /// Configures the handler to respond with a dynamically generated response. - /// - /// A function that takes the request and returns a response. - /// The handler instance for fluent chaining. - public void RespondWith(Func factory) { - _responseFactories.Enqueue(factory); - } - - /// - protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) { - SentRequests.Add(request); - - if (_responseFactories.Count == 0) { - throw new InvalidOperationException("No response configured. Use RespondWith() to set up a response."); - } - - var factory = _responseFactories.Dequeue(); - return Task.FromResult(factory(request)); - } -} diff --git a/tests/DotBahn.Common.Tests/packages.lock.json b/tests/DotBahn.Common.Tests/packages.lock.json deleted file mode 100644 index dc446df..0000000 --- a/tests/DotBahn.Common.Tests/packages.lock.json +++ /dev/null @@ -1,343 +0,0 @@ -{ - "version": 2, - "dependencies": { - "net10.0": { - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[10.0.403, )", - "resolved": "10.0.403", - "contentHash": "T4WYxWydJGNQRe/EgURFlhPZ1cHYgivrCCHSomCcfQzGzhkDYGNn5bUwwjs4/PHuMxsmGaLvPv2puG8lluA1IA==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "10.0.403", - "Microsoft.SourceLink.Common": "10.0.403", - "System.IO.Hashing": "10.0.14" - } - }, - "Microsoft.Testing.Extensions.CodeCoverage": { - "type": "Direct", - "requested": "[18.12.0, )", - "resolved": "18.12.0", - "contentHash": "BST/sWYpKk9OXO7Yxktcg6FWORRsHU0EdCbMwZ7d3OqJsMKlrNHIZ30g0Ib4k5T5acJYXRBmg9mNrTU/N6cy1g==", - "dependencies": { - "Microsoft.DiaSymReader": "2.2.10", - "Microsoft.Extensions.DependencyModel": "10.0.10", - "Microsoft.Testing.Platform": "2.5.0", - "Mono.Cecil": "0.11.6" - } - }, - "MinVer": { - "type": "Direct", - "requested": "[8.0.0, )", - "resolved": "8.0.0", - "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" - }, - "Moq": { - "type": "Direct", - "requested": "[4.21.0, )", - "resolved": "4.21.0", - "contentHash": "HUjrhhzEJ/AfbSBCnR8lPkpveVGpV/dNuOlnpfqBNTME93izly1CRV4N5zBySqz4m2yCRlHLPy/PnPzYokbwIg==", - "dependencies": { - "Castle.Core": "5.2.1" - } - }, - "xunit.v3": { - "type": "Direct", - "requested": "[4.0.2, )", - "resolved": "4.0.2", - "contentHash": "TdjM2OAx7w/0E88E6PgaigLoTbQaxbSR3HF/8p92plchTjf29jPHW27ylvEOz+Nx8CvPwWKGQlOR1fDv6/Qh5A==", - "dependencies": { - "xunit.v3.mtp-v2": "[4.0.2]" - } - }, - "xunit.v3.runner.common": { - "type": "Direct", - "requested": "[4.0.2, )", - "resolved": "4.0.2", - "contentHash": "YlYKVhTJVcwEgJ6rm59Pjf71lQqKwKxEHqVRxWUuwrwm/nxB/mNFP/lP4vlntDO3GclNnLT9BjYOpJH9gViGQg==", - "dependencies": { - "Microsoft.Win32.Registry": "[5.0.0]", - "System.Security.AccessControl": "[6.0.1]", - "xunit.v3.common": "[4.0.2]" - } - }, - "Castle.Core": { - "type": "Transitive", - "resolved": "5.2.1", - "contentHash": "wHARzQA695jwwKreOzNsq54KiGqKP38tv8hi8e2FXDEC/sA6BtrX90tVPDkOfVu13PbEzr00TCV8coikl+D1Iw==", - "dependencies": { - "System.Diagnostics.EventLog": "6.0.0" - } - }, - "Microsoft.ApplicationInsights": { - "type": "Transitive", - "resolved": "2.23.0", - "contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw==" - }, - "Microsoft.Bcl.AsyncInterfaces": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg==" - }, - "Microsoft.Build.Tasks.Git": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "1furteBFeemMmZ4s+ORjQb7YtO+wG63NJahbQbRUi91FV6V87BdV0U3vX1jbMC6iKSELYYoXWssSzLu3mx0i2w==", - "dependencies": { - "System.IO.Hashing": "10.0.14" - } - }, - "Microsoft.DiaSymReader": { - "type": "Transitive", - "resolved": "2.2.10", - "contentHash": "zmGsm6b2y3STDa/Of7rdkkfTDV8VuGB8aCqIkLoJIQh5tL78K3zJ8OUyFKnfsaORXmGr9iOKwDkZfUjeXi+CwA==" - }, - "Microsoft.Extensions.Configuration": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.Binder": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.DependencyInjection": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.DependencyInjection.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" - }, - "Microsoft.Extensions.DependencyModel": { - "type": "Transitive", - "resolved": "10.0.10", - "contentHash": "rfZA1RjR021RPqSmIPovfz2aOd79TGqJ9BengbjnzIISOVwjLmuSDnhCMmiY/1c6iYvGolQ1iNGzkav0u11XEA==" - }, - "Microsoft.Extensions.Diagnostics": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "80VqW8eKxQaxBOLDNpLUdxOlxzWn/jqBSxNBCfD8GCjcshNDpFvUgKh8uvvZwvkfBbwmNPWPWHyy9F+RLd1dlQ==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" - } - }, - "Microsoft.Extensions.Diagnostics.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vm+PPso6vOwGeX52MdOPh6z/R6KHgxQUwqq7k7Jc9jhy2JOxO2KB4xfoJQBBp2Ni8M4zKgJ4r2a1dgrYG7+MKw==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Logging": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.Options.ConfigurationExtensions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4wcIU0rE04ejEfCwHTftu9O8fgH6CRYCe+tseRapikUBn1Kic3QdO7ku22SwFyLrzdWGYPUZMEgv57ZYuuc5gA==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Primitives": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" - }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "SvzUeqFGrcQxlIgjmcoSGiV5UWcPa0NCTuH69/40uSDsSD/26c6p9cH7XLAxpn+I8+2Zhl1qp+WMugl0oOwBMg==" - }, - "Microsoft.Testing.Extensions.Telemetry": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "mu2iyoHovwl0q1mGeeRU0h8+LALXC7HqbxniLa1shTKYdJGl+KPoCEgjWIQ8MLzk1tlTGPOfg1JsxdH3RxhMCA==", - "dependencies": { - "Microsoft.ApplicationInsights": "2.23.0", - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Testing.Extensions.TrxReport.Abstractions": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "DYTZAguaHz0wNJdHDTTGYOXtnlDoLoIbTMDKSApNNcytm55DJcnwpwELfQGLk5DB5QlgaEjNhnGo1Pu5QvL5VA==", - "dependencies": { - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Testing.Platform": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "FAMaFFWnULW+hDHMb40Qzhcgz9cAU2/EtgRCBNX/DdQoKo0sPG2EiY+w7bQdl/BgHnf/DbpXLbf5Xy0o15M8NA==" - }, - "Microsoft.Testing.Platform.MSBuild": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "lYawcAwY+h76rQmpma2n0HaL8zkOFbbKapso0Eb+uOAUQn7333pIByLftEuiO67csAoZufHNMwi6PqhNemWQXA==", - "dependencies": { - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Win32.Registry": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg==" - }, - "Mono.Cecil": { - "type": "Transitive", - "resolved": "0.11.6", - "contentHash": "f33RkDtZO8VlGXCtmQIviOtxgnUdym9xx/b1p9h91CRGOsJFxCFOFK1FDbVt1OCf1aWwYejUFa2MOQyFWTFjbA==" - }, - "System.Diagnostics.EventLog": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "lcyUiXTsETK2ALsZrX+nWuHSIQeazhqPphLfaRxzdGaG93+0kELqpgEHtwWOlQe7+jSFnKwaCAgL4kjeZCQJnw==" - }, - "System.IO.Hashing": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "lVqovhCt3HlZe7ONG5ydaj6BYwYI004gldVfMMkJl/lR5ueeCtWNpW4nejOX75sPmzm8vXCxB69GqwHaYCnyUQ==" - }, - "System.Security.AccessControl": { - "type": "Transitive", - "resolved": "6.0.1", - "contentHash": "IQ4NXP/B3Ayzvw0rDQzVTYsCKyy0Jp9KI6aYcK7UnGVlR9+Awz++TIPCQtPYfLJfOpm8ajowMR09V7quD3sEHw==" - }, - "xunit.analyzers": { - "type": "Transitive", - "resolved": "2.2.0", - "contentHash": "dXMIIztipcAyL3a19gtUrih/RLrE33/4VJdICoinYqIXXo1KLtsMPsaQ9dO2pE8xajDguwE2kqVbBqE5/EoJ0Q==" - }, - "xunit.v3.assert": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "5PKRexYlvufWFdXenRcRGKqvaJBBZFJZpqUGlUs9p13eKEgVdOrLpkPknjzUvLY5kEUicK9871DIUDcCPA6AXA==" - }, - "xunit.v3.common": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "++CtT8daIf6qfieQev/8V88U3zViIDWou5cj+oWps1/Hf73UoaY/L0hKyi3v7Zlt3BmbU0pUc73zCB1GiB4nYA==", - "dependencies": { - "Microsoft.Bcl.AsyncInterfaces": "6.0.0" - } - }, - "xunit.v3.core.mtp-v2": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "XyPMcQRsnUQLhmBBRRgYWsuPc8TyiANzcXtqfzyWfDpPuyh3Q0K4oWozZYQKZRNGnqJ97ifD6qUDWhsEEe32uw==", - "dependencies": { - "Microsoft.Testing.Extensions.Telemetry": "2.5.1", - "Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.5.1", - "Microsoft.Testing.Platform": "2.5.1", - "Microsoft.Testing.Platform.MSBuild": "2.5.1", - "xunit.v3.extensibility.core": "[4.0.2]", - "xunit.v3.runner.inproc.console": "[4.0.2]" - } - }, - "xunit.v3.extensibility.core": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "ARTt+pGyd86mdtiFBkKpyBQvRC3u0rr8oidBlII2GsAg7D6TfOsDFCsoQtFij83V5pE57m3whUIqT4xjiARXbQ==", - "dependencies": { - "xunit.v3.common": "[4.0.2]" - } - }, - "xunit.v3.mtp-v2": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "XLV32FhkuvheBStvX0DvjfPEtI+4SOVcIhnlTS+549r8VfVwsjpWdkJtQmQ7D23PA+Zoaqo+sTjBkRSkidC6Tw==", - "dependencies": { - "xunit.analyzers": "2.2.0", - "xunit.v3.assert": "[4.0.2]", - "xunit.v3.core.mtp-v2": "[4.0.2]" - } - }, - "xunit.v3.runner.inproc.console": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "cg4XNpCN4Ry9nswutknpreN3ckSUBwtjMRmEQSNK/sIKPo6KN5tDGGGCaHDm5HGA4yFVVtTJX65tLCsZArUNfQ==", - "dependencies": { - "xunit.v3.extensibility.core": "[4.0.2]", - "xunit.v3.runner.common": "[4.0.2]" - } - }, - "dotbahn.common": { - "type": "Project", - "dependencies": { - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Options": "[10.0.14, )" - } - }, - "Microsoft.Extensions.Http": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "IDsXLGGz7nJMsqspWnErsP18WyAVf6V9Ixl4p47/8/95Jak3ZA1YWhQ0iesMVwubVhkVZGoO9m9ADUnK0m6HLw==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Options": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - } - } - } -} \ No newline at end of file diff --git a/tests/DotBahn.Facilities.Tests/Client/FacilityClientTests.cs b/tests/DotBahn.Facilities.Tests/Client/FacilityClientTests.cs deleted file mode 100644 index 2b219cb..0000000 --- a/tests/DotBahn.Facilities.Tests/Client/FacilityClientTests.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System.Net; -using DotBahn.Common.Parsing; -using DotBahn.Common.Tests; -using DotBahn.Common.Transformer; -using DotBahn.Facilities.Internal.Contracts; -using DotBahn.Facilities.Models; -using DotBahn.Facilities.Models.Enumerations; -using Moq; - -namespace DotBahn.Facilities.Tests.Client; - -public class FacilityClientTests : ClientTestBase { - private readonly Mock>> _parserMock = new(); - private readonly Mock, IEnumerable>> _transformerMock = new(); - - public FacilityClientTests() { - HttpClient.BaseAddress = new Uri("https://api.deutschebahn.com"); - } - - [Fact] - public async Task GetFacilitiesAsync_BuildsUrlWithFacilitiesEndpoint() { - var client = CreateClient(); - var query = new FacilityQuery(); - SetupParserAndTransformer(); - HttpHandler.RespondWith(HttpStatusCode.OK, "[]", "application/json"); - - await client.GetFacilitiesAsync(query, TestContext.Current.CancellationToken); - - AssertRequest(HttpMethod.Get, "/facilities", "application/json"); - } - - [Fact] - public async Task GetFacilitiesAsync_AppliesQueryParametersFromFacilityQuery() { - var client = CreateClient(); - var query = new FacilityQuery { - Type = FacilityType.Elevator, - StationId = "8002549" - }; - - SetupParserAndTransformer(); - HttpHandler.RespondWith(HttpStatusCode.OK, "[]", "application/json"); - - await client.GetFacilitiesAsync(query, TestContext.Current.CancellationToken); - - var requestUri = HttpHandler.SentRequests[0].RequestUri?.ToString(); - Assert.Contains("type=ELEVATOR", requestUri); - Assert.Contains("stationnumber=8002549", requestUri); - } - - [Fact] - public async Task GetFacilitiesAsync_CallsToListBeforeTransform() { - var client = CreateClient(); - var query = new FacilityQuery(); - SetupParserAndTransformer(); - HttpHandler.RespondWith(HttpStatusCode.OK, "[]", "application/json"); - - var result = await client.GetFacilitiesAsync(query, TestContext.Current.CancellationToken); - - Assert.NotNull(result); - } - - [Fact] - public async Task GetFacilitiesAsync_WithNullQuery_ThrowsArgumentNullException() { - var client = CreateClient(); - - await Assert.ThrowsAsync(() => client.GetFacilitiesAsync(null!, TestContext.Current.CancellationToken)); - } - - private FacilityClient CreateClient() => new(HttpClient, AuthorizationMock.Object, _parserMock.Object, _transformerMock.Object); - - private void SetupParserAndTransformer() { - var emptyContracts = new List(); - var emptyFacilities = new List(); - - _parserMock.Setup(p => p.Parse(It.IsAny())).Returns(emptyContracts); - _transformerMock.Setup(t => t.Transform(It.IsAny>())).Returns(emptyFacilities); - } -} diff --git a/tests/DotBahn.Facilities.Tests/Enumerations/EnumUtilTests.cs b/tests/DotBahn.Facilities.Tests/Enumerations/EnumUtilTests.cs deleted file mode 100644 index 14b6fef..0000000 --- a/tests/DotBahn.Facilities.Tests/Enumerations/EnumUtilTests.cs +++ /dev/null @@ -1,92 +0,0 @@ -using DotBahn.Common.Utilities; -using DotBahn.Facilities.Models.Enumerations; -using FacilitiesJsonContext = DotBahn.Facilities.Internal.Json.FacilitiesJsonContext; - -namespace DotBahn.Facilities.Tests.Enumerations; - -public class EnumUtilTests { - [Theory] - [InlineData("ACTIVE", FacilityState.Active)] - [InlineData("INACTIVE", FacilityState.Inactive)] - [InlineData("UNKNOWN", FacilityState.Unknown)] - public void Parse_WithExactCaseValue_ReturnsCorrectEnum(string value, FacilityState expected) { - var result = EnumUtil.Parse(value, FacilityState.Unknown, FacilitiesJsonContext.Default.FacilityState); - - Assert.Equal(expected, result); - } - - [Fact] - public void Parse_WithNull_ReturnsDefault() { - var result = EnumUtil.Parse(null, FacilityState.Unknown, FacilitiesJsonContext.Default.FacilityState); - - Assert.Equal(FacilityState.Unknown, result); - } - - [Fact] - public void Parse_WithEmptyString_ReturnsDefault() { - var result = EnumUtil.Parse(string.Empty, FacilityState.Unknown, FacilitiesJsonContext.Default.FacilityState); - - Assert.Equal(FacilityState.Unknown, result); - } - - [Fact] - public void Parse_WithWhiteSpace_ReturnsDefault() { - var result = EnumUtil.Parse(" ", FacilityState.Unknown, FacilitiesJsonContext.Default.FacilityState); - - Assert.Equal(FacilityState.Unknown, result); - } - - [Fact] - public void Parse_WithUnknownValue_ReturnsDefault() { - var result = EnumUtil.Parse("NONEXISTENT", FacilityState.Unknown, FacilitiesJsonContext.Default.FacilityState); - - Assert.Equal(FacilityState.Unknown, result); - } - - [Fact] - public void Format_WithValidEnum_ReturnsCorrectString() { - var result = EnumUtil.Format(FacilityState.Active, FacilitiesJsonContext.Default.FacilityState); - - Assert.Equal("ACTIVE", result); - } - - [Fact] - public void Format_WithNull_ReturnsNull() { - FacilityState? nullState = null; - var result = EnumUtil.Format(nullState, FacilitiesJsonContext.Default.FacilityState); - - Assert.Null(result); - } - - [Fact] - public void Format_WithInactive_ReturnsInactiveString() { - var result = EnumUtil.Format(FacilityState.Inactive, FacilitiesJsonContext.Default.FacilityState); - - Assert.Equal("INACTIVE", result); - } - - [Theory] - [InlineData(FacilityType.Elevator, "ELEVATOR")] - [InlineData(FacilityType.Escalator, "ESCALATOR")] - public void Format_FacilityType_ReturnsCorrectString(FacilityType value, string expected) { - var result = EnumUtil.Format(value, FacilitiesJsonContext.Default.FacilityType); - - Assert.Equal(expected, result); - } - - [Theory] - [InlineData("ELEVATOR", FacilityType.Elevator)] - [InlineData("ESCALATOR", FacilityType.Escalator)] - public void Parse_FacilityType_ReturnsCorrectEnum(string value, FacilityType expected) { - var result = EnumUtil.Parse(value, FacilityType.Unknown, FacilitiesJsonContext.Default.FacilityType); - - Assert.Equal(expected, result); - } - - [Fact] - public void Parse_FacilityType_UnknownValue_ReturnsDefault() { - var result = EnumUtil.Parse("BOGEY", FacilityType.Unknown, FacilitiesJsonContext.Default.FacilityType); - - Assert.Equal(FacilityType.Unknown, result); - } -} diff --git a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryAreaFluentApiTests.cs b/tests/DotBahn.Facilities.Tests/Query/FacilityQueryAreaFluentApiTests.cs deleted file mode 100644 index e92c692..0000000 --- a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryAreaFluentApiTests.cs +++ /dev/null @@ -1,97 +0,0 @@ -using DotBahn.Facilities.Models.Enumerations; - -namespace DotBahn.Facilities.Tests.Query; - -public class FacilityQueryAreaFluentApiTests { - [Fact] - public void WithArea_FourCoordinates_ShouldSetAllProperties() { - var query = new FacilityQuery() - .WithArea(8.6821, 50.1109, 8.6822, 50.1110); - - Assert.Equal(8.6821, query.LongitudeWest); - Assert.Equal(50.1109, query.LatitudeSouth); - Assert.Equal(8.6822, query.LongitudeEast); - Assert.Equal(50.1110, query.LatitudeNorth); - } - - [Fact] - public void WithArea_CalledMultipleTimes_ShouldOverwritePreviousValues() { - var query = new FacilityQuery() - .WithArea(8.6821, 50.1109, 8.6822, 50.1110) - .WithArea(9.0, 51.0, 10.0, 52.0); - - Assert.Equal(9.0, query.LongitudeWest); - Assert.Equal(51.0, query.LatitudeSouth); - Assert.Equal(10.0, query.LongitudeEast); - Assert.Equal(52.0, query.LatitudeNorth); - } - - [Fact] - public void WithArea_ReturnsSameInstance() { - var query = new FacilityQuery(); - - var result = query.WithArea(8.6821, 50.1109, 8.6822, 50.1110); - - Assert.Same(query, result); - } - - [Fact] - public void CompleteChaining_WithArea_ShouldSetAllProperties() { - var query = new FacilityQuery() - .WithType(FacilityType.Elevator) - .WithState(FacilityState.Inactive) - .WithEquipmentNumbers("10562421") - .AtStation(8002549) - .WithArea(8.1, 50.2, 8.3, 50.4); - - Assert.Equal(FacilityType.Elevator, query.Type); - Assert.Equal(FacilityState.Inactive, query.State); - Assert.Equal(["10562421"], query.EquipmentNumbers); - Assert.Equal("8002549", query.StationId); - Assert.Equal(8.1, query.LongitudeWest); - Assert.Equal(50.2, query.LatitudeSouth); - Assert.Equal(8.3, query.LongitudeEast); - Assert.Equal(50.4, query.LatitudeNorth); - } - - [Fact] - public void FluentApi_PartialChaining_WithoutArea_ShouldLeaveAreaPropertiesNull() { - var query = new FacilityQuery() - .WithType(FacilityType.Escalator) - .AtStation(8000105); - - Assert.Equal(FacilityType.Escalator, query.Type); - Assert.Equal("8000105", query.StationId); - Assert.Null(query.LongitudeWest); - Assert.Null(query.LatitudeSouth); - Assert.Null(query.LongitudeEast); - Assert.Null(query.LatitudeNorth); - } - - [Fact] - public void FluentApi_MixedWithObjectInitializer_ShouldCombineBothApproaches() { - var query = new FacilityQuery { - Type = FacilityType.Elevator - }.WithState(FacilityState.Active) - .WithArea(8.1, 50.2, 8.3, 50.4); - - Assert.Equal(FacilityType.Elevator, query.Type); - Assert.Equal(FacilityState.Active, query.State); - Assert.Equal(8.1, query.LongitudeWest); - Assert.Equal(50.2, query.LatitudeSouth); - Assert.Equal(8.3, query.LongitudeEast); - Assert.Equal(50.4, query.LatitudeNorth); - } - - [Fact] - public void ChainingWithAreaAndOtherMethods_ReturnsSameInstance() { - var query = new FacilityQuery(); - - var result = query - .WithType(FacilityType.Escalator) - .WithArea(8.6821, 50.1109, 8.6822, 50.1110) - .AtStation(8000105); - - Assert.Same(query, result); - } -} diff --git a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryAreaTests.cs b/tests/DotBahn.Facilities.Tests/Query/FacilityQueryAreaTests.cs deleted file mode 100644 index 3fefac3..0000000 --- a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryAreaTests.cs +++ /dev/null @@ -1,90 +0,0 @@ -namespace DotBahn.Facilities.Tests.Query; - -public class FacilityQueryAreaTests { - [Fact] - public void Area_Default_AllCoordinatesShouldBeNull() { - var query = new FacilityQuery(); - - Assert.Null(query.LongitudeWest); - Assert.Null(query.LatitudeSouth); - Assert.Null(query.LongitudeEast); - Assert.Null(query.LatitudeNorth); - } - - [Fact] - public void Area_WithFourCoordinates_ShouldSetValues() { - var query = new FacilityQuery { - LongitudeWest = 8.6821, - LatitudeSouth = 50.1109, - LongitudeEast = 8.6822, - LatitudeNorth = 50.1110 - }; - - Assert.Equal(8.6821, query.LongitudeWest); - Assert.Equal(50.1109, query.LatitudeSouth); - Assert.Equal(8.6822, query.LongitudeEast); - Assert.Equal(50.1110, query.LatitudeNorth); - } - - [Fact] - public void Area_NegativeCoordinates_ShouldSetValues() { - var query = new FacilityQuery { - LongitudeWest = -0.1276, - LatitudeSouth = 51.5074, - LongitudeEast = 0.0, - LatitudeNorth = 51.5075 - }; - - Assert.Equal(-0.1276, query.LongitudeWest); - Assert.Equal(51.5074, query.LatitudeSouth); - } - - [Fact] - public void Area_PartialCoordinates_ShouldAllowPartialSetting() { - var query = new FacilityQuery { - LongitudeWest = 8.6821, - LatitudeSouth = 50.1109 - }; - - Assert.Equal(8.6821, query.LongitudeWest); - Assert.Equal(50.1109, query.LatitudeSouth); - Assert.Null(query.LongitudeEast); - Assert.Null(query.LatitudeNorth); - } - - [Fact] - public void LongitudeWest_WithNull_ShouldSetNull() { - var query = new FacilityQuery { LongitudeWest = 8.6821 }; - - query.LongitudeWest = null; - - Assert.Null(query.LongitudeWest); - } - - [Fact] - public void LatitudeSouth_WithNull_ShouldSetNull() { - var query = new FacilityQuery { LatitudeSouth = 50.1109 }; - - query.LatitudeSouth = null; - - Assert.Null(query.LatitudeSouth); - } - - [Fact] - public void LongitudeEast_WithNull_ShouldSetNull() { - var query = new FacilityQuery { LongitudeEast = 8.6822 }; - - query.LongitudeEast = null; - - Assert.Null(query.LongitudeEast); - } - - [Fact] - public void LatitudeNorth_WithNull_ShouldSetNull() { - var query = new FacilityQuery { LatitudeNorth = 50.1110 }; - - query.LatitudeNorth = null; - - Assert.Null(query.LatitudeNorth); - } -} diff --git a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryAreaToQueryParametersTests.cs b/tests/DotBahn.Facilities.Tests/Query/FacilityQueryAreaToQueryParametersTests.cs deleted file mode 100644 index e5d378a..0000000 --- a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryAreaToQueryParametersTests.cs +++ /dev/null @@ -1,102 +0,0 @@ -using DotBahn.Facilities.Models.Enumerations; - -namespace DotBahn.Facilities.Tests.Query; - -public class FacilityQueryAreaToQueryParametersTests { - [Fact] - public void ToQueryParameters_WithArea_ShouldIncludeAreaParameter() { - var query = new FacilityQuery { - LongitudeWest = 8.1, - LatitudeSouth = 50.2, - LongitudeEast = 8.3, - LatitudeNorth = 50.4 - }; - - var parameters = query.ToQueryParameters(); - var qs = parameters.ToQueryString(); - var decoded = Uri.UnescapeDataString(qs); - - Assert.Contains("area=", qs); - Assert.Contains("8.1,50.2,8.3,50.4", decoded); - } - - [Fact] - public void ToQueryParameters_WithoutArea_ShouldOmitAreaParameter() { - var query = new FacilityQuery(); - - var parameters = query.ToQueryParameters(); - var qs = parameters.ToQueryString(); - - Assert.DoesNotContain("area", qs); - } - - [Fact] - public void ToQueryParameters_WithPartialArea_ShouldOmitAreaParameter() { - var query = new FacilityQuery { - LongitudeWest = 8.1, - LatitudeSouth = 50.2 - }; - - var parameters = query.ToQueryParameters(); - var qs = parameters.ToQueryString(); - - Assert.DoesNotContain("area", qs); - } - - [Fact] - public void ToQueryParameters_WithAreaOnly_ShouldContainAreaWithAllCoordinates() { - var query = new FacilityQuery { - LongitudeWest = -122.41, - LatitudeSouth = 37.77, - LongitudeEast = -122.01, - LatitudeNorth = 37.79 - }; - - var parameters = query.ToQueryParameters(); - var qs = parameters.ToQueryString(); - var decoded = Uri.UnescapeDataString(qs); - - Assert.Contains("area=", qs); - Assert.Equal("-122.41,37.77,-122.01,37.79", decoded["area=".Length..]); - } - - public static TheoryData ToQueryParametersAreaAllFourRequiredCases => new() - { - { "BL—all_set", 8.0, 50.0, 9.0, 51.0, true }, - { "C1—lngw_null", null, 50.0, 9.0, 51.0, false }, - { "C2—lats_null", 8.0, null, 9.0, 51.0, false }, - { "C3—lnge_null", 8.0, 50.0, null, 51.0, false }, - { "C4—latn_null", 8.0, 50.0, 9.0, null, false }, - }; - - [Theory] - [MemberData(nameof(ToQueryParametersAreaAllFourRequiredCases))] - public void ToQueryParametersAreaAllFourRequired(string _, double? lngWest, double? latSouth, double? lngEast, double? latNorth, bool expectedHasArea) { - var query = new FacilityQuery { LongitudeWest = lngWest, LatitudeSouth = latSouth, LongitudeEast = lngEast, LatitudeNorth = latNorth }; - var qs = query.ToQueryParameters().ToQueryString(); - if (expectedHasArea) - Assert.Contains("area=", qs); - else - Assert.DoesNotContain("area=", qs); - } - - [Fact] - public void ToQueryParameters_WithAreaAndOtherFilters_ShouldCombineAllParameters() { - var query = new FacilityQuery { - Type = FacilityType.Elevator, - State = FacilityState.Inactive, - LongitudeWest = 8.1, - LatitudeSouth = 50.2, - LongitudeEast = 8.3, - LatitudeNorth = 50.4, - StationId = "8000105" - }; - - var qs = query.ToQueryParameters().ToQueryString(); - - Assert.Contains("area=", qs); - Assert.Contains("type=", qs); - Assert.Contains("state=", qs); - Assert.Contains("stationnumber=8000105", qs); - } -} diff --git a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryEquipmentNumbersTests.cs b/tests/DotBahn.Facilities.Tests/Query/FacilityQueryEquipmentNumbersTests.cs deleted file mode 100644 index c45abc3..0000000 --- a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryEquipmentNumbersTests.cs +++ /dev/null @@ -1,76 +0,0 @@ -namespace DotBahn.Facilities.Tests.Query; - -public class FacilityQueryEquipmentNumbersTests { - [Fact] - public void EquipmentNumbers_WithSingleNumber_ShouldSetValue() { - var query = new FacilityQuery { - EquipmentNumbers = ["10562421"] - }; - - Assert.Single(query.EquipmentNumbers); - Assert.Equal("10562421", query.EquipmentNumbers.First()); - } - - [Fact] - public void EquipmentNumbers_WithMultipleNumbers_ShouldSetAllValues() { - var query = new FacilityQuery(); - var numbers = new[] { "10562421", "10562422", "10562423" }; - - query.EquipmentNumbers = numbers; - - Assert.Equal(3, query.EquipmentNumbers.Count()); - Assert.Equal(numbers, query.EquipmentNumbers); - } - - [Fact] - public void EquipmentNumbers_WithEmptyArray_ShouldSetEmptyArray() { - var query = new FacilityQuery { - EquipmentNumbers = [] - }; - - Assert.NotNull(query.EquipmentNumbers); - Assert.Empty(query.EquipmentNumbers); - } - - [Fact] - public void EquipmentNumbers_WithNull_ShouldSetNull() { - var query = new FacilityQuery { EquipmentNumbers = ["10562421"] }; - - query.EquipmentNumbers = null!; - - Assert.Null(query.EquipmentNumbers); - } - - [Fact] - public void WithEquipmentNumbers_WithSingleParameter_ShouldSetArray() { - var query = new FacilityQuery(); - - var result = query.WithEquipmentNumbers("10562421"); - - Assert.Same(query, result); - Assert.Single(query.EquipmentNumbers); - Assert.Equal("10562421", query.EquipmentNumbers.First()); - } - - [Fact] - public void WithEquipmentNumbers_WithMultipleParameters_ShouldSetAllValues() { - var query = new FacilityQuery(); - - var result = query.WithEquipmentNumbers("10562421", "10562422", "10562423"); - - Assert.Same(query, result); - Assert.Equal(3, query.EquipmentNumbers.Count()); - Assert.Equal(["10562421", "10562422", "10562423"], query.EquipmentNumbers); - } - - [Fact] - public void WithEquipmentNumbers_CalledMultipleTimes_ShouldOverwritePreviousValue() { - var query = new FacilityQuery(); - - query.WithEquipmentNumbers("10562421") - .WithEquipmentNumbers("10562422", "10562423"); - - Assert.Equal(2, query.EquipmentNumbers.Count()); - Assert.Equal(["10562422", "10562423"], query.EquipmentNumbers); - } -} diff --git a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryFluentApiTests.cs b/tests/DotBahn.Facilities.Tests/Query/FacilityQueryFluentApiTests.cs deleted file mode 100644 index 488414f..0000000 --- a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryFluentApiTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -using DotBahn.Facilities.Models.Enumerations; - -namespace DotBahn.Facilities.Tests.Query; - -public class FacilityQueryFluentApiTests { - [Fact] - public void FluentApi_CompleteChaining_ShouldSetAllProperties() { - var query = new FacilityQuery() - .WithType(FacilityType.Elevator) - .WithState(FacilityState.Active) - .WithEquipmentNumbers("10562421", "10562422") - .AtStation(8002549); - - Assert.Equal(FacilityType.Elevator, query.Type); - Assert.Equal(FacilityState.Active, query.State); - Assert.Equal(["10562421", "10562422"], query.EquipmentNumbers); - Assert.Equal("8002549", query.StationId); - } - - [Fact] - public void FluentApi_PartialChaining_ShouldSetOnlySpecifiedProperties() { - var query = new FacilityQuery() - .WithType(FacilityType.Escalator) - .AtStation(8000105); - - Assert.Equal(FacilityType.Escalator, query.Type); - Assert.Null(query.State); - Assert.Empty(query.EquipmentNumbers); - Assert.Equal("8000105", query.StationId); - } - - [Fact] - public void FluentApi_ChainingSingleMethod_ShouldReturnSameInstance() { - var query = new FacilityQuery(); - - var result1 = query.WithType(FacilityType.Elevator); - var result2 = result1.WithState(FacilityState.Active); - var result3 = result2.WithEquipmentNumbers("10562421"); - var result4 = result3.AtStation(8002549); - - Assert.Same(query, result1); - Assert.Same(query, result2); - Assert.Same(query, result3); - Assert.Same(query, result4); - } - - [Fact] - public void FluentApi_MixedWithObjectInitializer_ShouldCombineBothApproaches() { - var query = new FacilityQuery { - Type = FacilityType.Elevator - }.WithState(FacilityState.Active) - .AtStation(8002549); - - Assert.Equal(FacilityType.Elevator, query.Type); - Assert.Equal(FacilityState.Active, query.State); - Assert.Equal("8002549", query.StationId); - } - - [Fact] - public void FluentApi_OverwritingValues_ShouldUseLastSetValue() { - var query = new FacilityQuery() - .WithType(FacilityType.Elevator) - .WithType(FacilityType.Escalator) - .AtStation(8002549) - .AtStation(8000105); - - Assert.Equal(FacilityType.Escalator, query.Type); - Assert.Equal("8000105", query.StationId); - } -} diff --git a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryRecordBehaviorTests.cs b/tests/DotBahn.Facilities.Tests/Query/FacilityQueryRecordBehaviorTests.cs deleted file mode 100644 index c5f0324..0000000 --- a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryRecordBehaviorTests.cs +++ /dev/null @@ -1,91 +0,0 @@ -using DotBahn.Facilities.Models.Enumerations; - -namespace DotBahn.Facilities.Tests.Query; - -public class FacilityQueryRecordBehaviorTests { - [Fact] - public void Equality_WithSameValues_ShouldBeEqual() { - var query1 = new FacilityQuery { - Type = FacilityType.Elevator, - State = FacilityState.Active, - StationId = "8002549", - LongitudeWest = 8.1, - LatitudeSouth = 50.2, - LongitudeEast = 8.3, - LatitudeNorth = 50.4 - }; - - var query2 = new FacilityQuery { - Type = FacilityType.Elevator, - State = FacilityState.Active, - StationId = "8002549", - LongitudeWest = 8.1, - LatitudeSouth = 50.2, - LongitudeEast = 8.3, - LatitudeNorth = 50.4 - }; - - Assert.Equal(query1, query2); - Assert.True(query1 == query2); - } - - [Fact] - public void Equality_WithDifferentValues_ShouldNotBeEqual() { - var query1 = new FacilityQuery { - Type = FacilityType.Elevator, - StationId = "8002549", - LongitudeWest = 8.1 - }; - - var query2 = new FacilityQuery { - Type = FacilityType.Elevator, - StationId = "8002549", - LongitudeWest = 9.9 - }; - - Assert.NotEqual(query1, query2); - Assert.False(query1 == query2); - } - - [Fact] - public void With_ShouldCreateNewInstanceWithModifiedProperty() { - var original = new FacilityQuery { - Type = FacilityType.Elevator, - State = FacilityState.Active, - StationId = "8002549", - LongitudeWest = 8.1, - LatitudeSouth = 50.2, - LongitudeEast = 8.3, - LatitudeNorth = 50.4 - }; - - var modified = original with { Type = FacilityType.Escalator }; - - Assert.NotSame(original, modified); - Assert.Equal(FacilityType.Elevator, original.Type); - Assert.Equal(FacilityType.Escalator, modified.Type); - Assert.Equal(original.State, modified.State); - Assert.Equal(original.StationId, modified.StationId); - Assert.Equal(original.LongitudeWest, modified.LongitudeWest); - Assert.Equal(original.LatitudeSouth, modified.LatitudeSouth); - Assert.Equal(original.LongitudeEast, modified.LongitudeEast); - Assert.Equal(original.LatitudeNorth, modified.LatitudeNorth); - } - - [Fact] - public void GetHashCode_WithSameValues_ShouldBeEqual() { - var query1 = new FacilityQuery { - Type = FacilityType.Elevator, - StationId = "8002549", - LongitudeWest = 8.1 - }; - - var query2 = new FacilityQuery { - Type = FacilityType.Elevator, - StationId = "8002549", - LongitudeWest = 8.1 - }; - - Assert.Equal(query1.GetHashCode(), query2.GetHashCode()); - } -} diff --git a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryStateTests.cs b/tests/DotBahn.Facilities.Tests/Query/FacilityQueryStateTests.cs deleted file mode 100644 index d049de0..0000000 --- a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryStateTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -using DotBahn.Facilities.Models.Enumerations; - -namespace DotBahn.Facilities.Tests.Query; - -public class FacilityQueryStateTests { - [Theory] - [InlineData(FacilityState.Active)] - [InlineData(FacilityState.Inactive)] - [InlineData(FacilityState.Unknown)] - public void State_ShouldSetAndGetValue(FacilityState state) { - var query = new FacilityQuery { - State = state - }; - - Assert.Equal(state, query.State); - } - - [Fact] - public void State_WithNull_ShouldSetNull() { - var query = new FacilityQuery { State = FacilityState.Active }; - - query.State = null; - - Assert.Null(query.State); - } - - [Fact] - public void WithState_ShouldSetStateAndReturnQuery() { - var query = new FacilityQuery(); - - var result = query.WithState(FacilityState.Active); - - Assert.Same(query, result); - Assert.Equal(FacilityState.Active, query.State); - } - - [Theory] - [InlineData(FacilityState.Active)] - [InlineData(FacilityState.Inactive)] - [InlineData(FacilityState.Unknown)] - public void WithState_WithDifferentStates_ShouldSetCorrectState(FacilityState state) { - var query = new FacilityQuery(); - - query.WithState(state); - - Assert.Equal(state, query.State); - } -} diff --git a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryStationIdTests.cs b/tests/DotBahn.Facilities.Tests/Query/FacilityQueryStationIdTests.cs deleted file mode 100644 index 12f2905..0000000 --- a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryStationIdTests.cs +++ /dev/null @@ -1,60 +0,0 @@ -namespace DotBahn.Facilities.Tests.Query; - -public class FacilityQueryStationIdTests { - [Theory] - [InlineData("8002549")] - [InlineData("8000105")] - [InlineData("8011160")] - public void StationId_ShouldSetAndGetValue(string stationId) { - var query = new FacilityQuery { - StationId = stationId - }; - - Assert.Equal(stationId, query.StationId); - } - - [Fact] - public void StationId_WithNull_ShouldSetNull() { - var query = new FacilityQuery { StationId = "8002549" }; - - query.StationId = null; - - Assert.Null(query.StationId); - } - - [Theory] - [InlineData("")] - [InlineData(" ")] - public void StationId_WithEmptyOrWhitespace_ShouldSetValue(string stationId) { - var query = new FacilityQuery { - StationId = stationId - }; - - Assert.Equal(stationId, query.StationId); - } - - [Theory] - [InlineData(8002549)] - [InlineData(8000105)] - [InlineData(8011160)] - public void AtStation_ShouldConvertIntToStringAndReturnQuery(int stationId) { - var query = new FacilityQuery(); - - var result = query.AtStation(stationId); - - Assert.Same(query, result); - Assert.Equal(stationId.ToString(), query.StationId); - } - - [Theory] - [InlineData(0, "0")] - [InlineData(-1, "-1")] - [InlineData(999999999, "999999999")] - public void AtStation_WithEdgeCaseValues_ShouldConvertCorrectly(int stationId, string expected) { - var query = new FacilityQuery(); - - query.AtStation(stationId); - - Assert.Equal(expected, query.StationId); - } -} diff --git a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryTests.cs b/tests/DotBahn.Facilities.Tests/Query/FacilityQueryTests.cs deleted file mode 100644 index d51a08f..0000000 --- a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryTests.cs +++ /dev/null @@ -1,59 +0,0 @@ -using DotBahn.Facilities.Models.Enumerations; - -namespace DotBahn.Facilities.Tests.Query; - -public class FacilityQueryTests { - [Fact] - public void Constructor_ShouldInitializeWithDefaultValues() { - var query = new FacilityQuery(); - - Assert.Null(query.Type); - Assert.Null(query.State); - Assert.Empty(query.EquipmentNumbers); - Assert.Null(query.StationId); - Assert.Null(query.LongitudeWest); - Assert.Null(query.LatitudeSouth); - Assert.Null(query.LongitudeEast); - Assert.Null(query.LatitudeNorth); - } - - [Fact] - public void ObjectInitializer_ShouldSetAllProperties() { - var query = new FacilityQuery { - Type = FacilityType.Elevator, - State = FacilityState.Active, - EquipmentNumbers = ["10562421", "10562422"], - StationId = "8002549", - LongitudeWest = 8.1, - LatitudeSouth = 50.2, - LongitudeEast = 8.3, - LatitudeNorth = 50.4 - }; - - Assert.Equal(FacilityType.Elevator, query.Type); - Assert.Equal(FacilityState.Active, query.State); - Assert.Equal(["10562421", "10562422"], query.EquipmentNumbers); - Assert.Equal("8002549", query.StationId); - Assert.Equal(8.1, query.LongitudeWest); - Assert.Equal(50.2, query.LatitudeSouth); - Assert.Equal(8.3, query.LongitudeEast); - Assert.Equal(50.4, query.LatitudeNorth); - } - - [Fact] - public void ObjectInitializer_WithPartialProperties_ShouldSetOnlySpecified() { - var query = new FacilityQuery { - Type = FacilityType.Escalator, - StationId = "8000105" - }; - - Assert.Equal(FacilityType.Escalator, query.Type); - Assert.Null(query.State); - Assert.Empty(query.EquipmentNumbers); - Assert.Equal("8000105", query.StationId); - Assert.Null(query.LongitudeWest); - Assert.Null(query.LatitudeSouth); - Assert.Null(query.LongitudeEast); - Assert.Null(query.LatitudeNorth); - } -} diff --git a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryToQueryParametersTests.cs b/tests/DotBahn.Facilities.Tests/Query/FacilityQueryToQueryParametersTests.cs deleted file mode 100644 index ad16164..0000000 --- a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryToQueryParametersTests.cs +++ /dev/null @@ -1,57 +0,0 @@ -using DotBahn.Facilities.Models.Enumerations; - -namespace DotBahn.Facilities.Tests.Query; - -public class FacilityQueryToQueryParametersTests { - [Fact] - public void ToQueryParameters_WithAllPropertiesSet_ShouldConvertCorrectly() { - var query = new FacilityQuery { - Type = FacilityType.Elevator, - State = FacilityState.Active, - EquipmentNumbers = ["10562421", "10562422"], - StationId = "8002549", - LongitudeWest = 8.1, - LatitudeSouth = 50.2, - LongitudeEast = 8.3, - LatitudeNorth = 50.4 - }; - - var parameters = query.ToQueryParameters(); - var qs = parameters.ToQueryString(); - - Assert.NotNull(parameters); - Assert.Contains("area=", qs); - } - - [Fact] - public void ToQueryParameters_WithMinimalProperties_ShouldConvertCorrectly() { - var query = new FacilityQuery(); - - var parameters = query.ToQueryParameters(); - - Assert.NotNull(parameters); - } - - [Fact] - public void ToQueryParameters_WithPartialProperties_ShouldHandleNullValues() { - var query = new FacilityQuery { - Type = FacilityType.Elevator, - StationId = "8002549" - }; - - var parameters = query.ToQueryParameters(); - - Assert.NotNull(parameters); - } - - [Fact] - public void ToQueryParameters_WithEmptyEquipmentNumbers_ShouldHandleGracefully() { - var query = new FacilityQuery { - EquipmentNumbers = [] - }; - - var parameters = query.ToQueryParameters(); - - Assert.NotNull(parameters); - } -} diff --git a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryTypeTests.cs b/tests/DotBahn.Facilities.Tests/Query/FacilityQueryTypeTests.cs deleted file mode 100644 index ca96ef2..0000000 --- a/tests/DotBahn.Facilities.Tests/Query/FacilityQueryTypeTests.cs +++ /dev/null @@ -1,46 +0,0 @@ -using DotBahn.Facilities.Models.Enumerations; - -namespace DotBahn.Facilities.Tests.Query; - -public class FacilityQueryTypeTests { - [Theory] - [InlineData(FacilityType.Elevator)] - [InlineData(FacilityType.Escalator)] - public void Type_ShouldSetAndGetValue(FacilityType type) { - var query = new FacilityQuery { - Type = type - }; - - Assert.Equal(type, query.Type); - } - - [Fact] - public void Type_WithNull_ShouldSetNull() { - var query = new FacilityQuery { Type = FacilityType.Elevator }; - - query.Type = null; - - Assert.Null(query.Type); - } - - [Fact] - public void WithType_ShouldSetTypeAndReturnQuery() { - var query = new FacilityQuery(); - - var result = query.WithType(FacilityType.Elevator); - - Assert.Same(query, result); - Assert.Equal(FacilityType.Elevator, query.Type); - } - - [Theory] - [InlineData(FacilityType.Elevator)] - [InlineData(FacilityType.Escalator)] - public void WithType_WithDifferentTypes_ShouldSetCorrectType(FacilityType type) { - var query = new FacilityQuery(); - - query.WithType(type); - - Assert.Equal(type, query.Type); - } -} diff --git a/tests/DotBahn.Facilities.Tests/Transformer/FacilityTransformerTests.cs b/tests/DotBahn.Facilities.Tests/Transformer/FacilityTransformerTests.cs deleted file mode 100644 index 8f8b9ff..0000000 --- a/tests/DotBahn.Facilities.Tests/Transformer/FacilityTransformerTests.cs +++ /dev/null @@ -1,61 +0,0 @@ -using DotBahn.Facilities.Internal.Contracts; -using DotBahn.Facilities.Internal.Transformers; -using DotBahn.Facilities.Models.Enumerations; - -namespace DotBahn.Facilities.Tests.Transformer; - -public class FacilityTransformerTests { - private readonly FacilityTransformer _transformer = new(); - - [Theory] - [InlineData(null, 53.5)] - [InlineData(10.0, null)] - [InlineData(null, null)] - public void Transform_NullCoordinates_FiltersOut(double? longitude, double? latitude) { - var contract = new FacilityContract { - EquipmentNumber = 100, - Type = "ELEVATOR", - State = "ACTIVE", - Longitude = longitude, - Latitude = latitude - }; - - var result = _transformer.Transform([contract]); - - Assert.Empty(result); - } - - [Fact] - public void TransformNullContractsThrowsArgumentNullException() { - Assert.Throws(() => _transformer.Transform(null!)); - } - - [Fact] - public void Transform_ValidContract_MapsAllFieldsIncludingCoordinates() { - var contract = new FacilityContract { - EquipmentNumber = 200, - Type = "ESCALATOR", - Description = "Platform 1 Escalator", - State = "ACTIVE", - StateExplanation = "Fully operational", - StationNumber = 8000001, - Longitude = 10.0, - Latitude = 53.5, - OperatorName = "DB Station&Service AG" - }; - - var result = _transformer.Transform([contract]).ToList(); - - Assert.Single(result); - var facility = result[0]; - Assert.Equal(200, facility.EquipmentNumber); - Assert.Equal(FacilityType.Escalator, facility.Type); - Assert.Equal("Platform 1 Escalator", facility.Description); - Assert.Equal(FacilityState.Active, facility.State); - Assert.Equal("Fully operational", facility.StateExplanation); - Assert.Equal(8000001, facility.StationNumber); - Assert.Equal(10.0, facility.Coordinates.Longitude); - Assert.Equal(53.5, facility.Coordinates.Latitude); - Assert.Equal("DB Station&Service AG", facility.OperatorName); - } -} diff --git a/tests/DotBahn.Facilities.Tests/packages.lock.json b/tests/DotBahn.Facilities.Tests/packages.lock.json deleted file mode 100644 index 95c51ad..0000000 --- a/tests/DotBahn.Facilities.Tests/packages.lock.json +++ /dev/null @@ -1,522 +0,0 @@ -{ - "version": 2, - "dependencies": { - "net10.0": { - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[10.0.403, )", - "resolved": "10.0.403", - "contentHash": "T4WYxWydJGNQRe/EgURFlhPZ1cHYgivrCCHSomCcfQzGzhkDYGNn5bUwwjs4/PHuMxsmGaLvPv2puG8lluA1IA==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "10.0.403", - "Microsoft.SourceLink.Common": "10.0.403", - "System.IO.Hashing": "10.0.14" - } - }, - "Microsoft.Testing.Extensions.CodeCoverage": { - "type": "Direct", - "requested": "[18.12.0, )", - "resolved": "18.12.0", - "contentHash": "BST/sWYpKk9OXO7Yxktcg6FWORRsHU0EdCbMwZ7d3OqJsMKlrNHIZ30g0Ib4k5T5acJYXRBmg9mNrTU/N6cy1g==", - "dependencies": { - "Microsoft.DiaSymReader": "2.2.10", - "Microsoft.Extensions.DependencyModel": "10.0.10", - "Microsoft.Testing.Platform": "2.5.0", - "Mono.Cecil": "0.11.6" - } - }, - "MinVer": { - "type": "Direct", - "requested": "[8.0.0, )", - "resolved": "8.0.0", - "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" - }, - "xunit.v3": { - "type": "Direct", - "requested": "[4.0.2, )", - "resolved": "4.0.2", - "contentHash": "TdjM2OAx7w/0E88E6PgaigLoTbQaxbSR3HF/8p92plchTjf29jPHW27ylvEOz+Nx8CvPwWKGQlOR1fDv6/Qh5A==", - "dependencies": { - "xunit.v3.mtp-v2": "[4.0.2]" - } - }, - "xunit.v3.runner.common": { - "type": "Direct", - "requested": "[4.0.2, )", - "resolved": "4.0.2", - "contentHash": "YlYKVhTJVcwEgJ6rm59Pjf71lQqKwKxEHqVRxWUuwrwm/nxB/mNFP/lP4vlntDO3GclNnLT9BjYOpJH9gViGQg==", - "dependencies": { - "Microsoft.Win32.Registry": "[5.0.0]", - "System.Security.AccessControl": "[6.0.1]", - "xunit.v3.common": "[4.0.2]" - } - }, - "Castle.Core": { - "type": "Transitive", - "resolved": "5.2.1", - "contentHash": "wHARzQA695jwwKreOzNsq54KiGqKP38tv8hi8e2FXDEC/sA6BtrX90tVPDkOfVu13PbEzr00TCV8coikl+D1Iw==", - "dependencies": { - "System.Diagnostics.EventLog": "6.0.0" - } - }, - "Microsoft.ApplicationInsights": { - "type": "Transitive", - "resolved": "2.23.0", - "contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw==" - }, - "Microsoft.Bcl.AsyncInterfaces": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg==" - }, - "Microsoft.Build.Tasks.Git": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "1furteBFeemMmZ4s+ORjQb7YtO+wG63NJahbQbRUi91FV6V87BdV0U3vX1jbMC6iKSELYYoXWssSzLu3mx0i2w==", - "dependencies": { - "System.IO.Hashing": "10.0.14" - } - }, - "Microsoft.DiaSymReader": { - "type": "Transitive", - "resolved": "2.2.10", - "contentHash": "zmGsm6b2y3STDa/Of7rdkkfTDV8VuGB8aCqIkLoJIQh5tL78K3zJ8OUyFKnfsaORXmGr9iOKwDkZfUjeXi+CwA==" - }, - "Microsoft.Extensions.AmbientMetadata.Application": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "aMCm7C6CexZT8W/p8zRp4BoxSnqRs3MmkBF7FvPIXC92b7vqs2SL0J+mVJi5W2Mk9Vb4ZRFWe9sdzFew6zUl1w==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" - } - }, - "Microsoft.Extensions.Compliance.Abstractions": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2mjAb3Sm5k6uNeI+IyXpggYMpfdDDGgZSwUm9QQsm5QgZboJWbm2eU+6wNMrlfFEao11yq6JS1zXI7SVQQ0NuQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13" - } - }, - "Microsoft.Extensions.Configuration": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.Binder": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.DependencyInjection": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.DependencyInjection.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" - }, - "Microsoft.Extensions.DependencyInjection.AutoActivation": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "h/sovspxVmT2DTIbWORMG0Gi3zVcPQzNl3kbwtpo0LoUXYbe2+66wQqZYwaF2ZWKN8HDdHv5yoc7d0DbDBBlnA==", - "dependencies": { - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13" - } - }, - "Microsoft.Extensions.DependencyModel": { - "type": "Transitive", - "resolved": "10.0.10", - "contentHash": "rfZA1RjR021RPqSmIPovfz2aOd79TGqJ9BengbjnzIISOVwjLmuSDnhCMmiY/1c6iYvGolQ1iNGzkav0u11XEA==" - }, - "Microsoft.Extensions.Diagnostics": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "80VqW8eKxQaxBOLDNpLUdxOlxzWn/jqBSxNBCfD8GCjcshNDpFvUgKh8uvvZwvkfBbwmNPWPWHyy9F+RLd1dlQ==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" - } - }, - "Microsoft.Extensions.Diagnostics.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vm+PPso6vOwGeX52MdOPh6z/R6KHgxQUwqq7k7Jc9jhy2JOxO2KB4xfoJQBBp2Ni8M4zKgJ4r2a1dgrYG7+MKw==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "Dp/FaAPo3U9h3HsWT1dcdRRV//rm+MQF5iKpY/WxL5swwV+wZNE5eyJZ0kgy9Upl/kHz4ejpiLMloxDIuJaoJQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13" - } - }, - "Microsoft.Extensions.FileProviders.Abstractions": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "BZDwtN3uoWRghDi5lRRZPDjMMCg2Ds7J6YEYjqka/TLjqnzquEpXyvchrIMeoubwT1ns23ow6PPeAoBHJO81Rw==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.13" - } - }, - "Microsoft.Extensions.Hosting.Abstractions": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "zIrbe9vkIFXxW3mOApIOWXw+xMwX7Cgsptr3ZSlglJt4hW2qp4fB/JU1NHgAevteBNH4PicvU9DsFPHxlnnloA==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13" - } - }, - "Microsoft.Extensions.Http.Diagnostics": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "iFcxcuMF/21LO+tDqDyzYVvokJUH03cNalmOJhmjyQSMV3dR4JAgcUBTV1iVH/yruC8wG2RNjvW0xcUgYqmrGg==", - "dependencies": { - "Microsoft.Extensions.Http": "10.0.13", - "Microsoft.Extensions.Telemetry": "10.11.0" - } - }, - "Microsoft.Extensions.Logging": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Configuration": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "OyYJOaE9WbBx1Hp+Dd2zrqeFM0JwH5M/x0VL6tNUv3V18vIAVpix8UjhvY9eW/iXpguEHy68JO/Z9YkBOwftIw==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.Configuration.Binder": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" - } - }, - "Microsoft.Extensions.ObjectPool": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "NX3bhcc0WitPKAVc9Zfi8jeEPClhfEmobUJM4a4bkWhJcBt5IWg6lCrItUoFy4whLjU+atXktURYCweQlR7wfg==" - }, - "Microsoft.Extensions.Options.ConfigurationExtensions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4wcIU0rE04ejEfCwHTftu9O8fgH6CRYCe+tseRapikUBn1Kic3QdO7ku22SwFyLrzdWGYPUZMEgv57ZYuuc5gA==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Primitives": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" - }, - "Microsoft.Extensions.Resilience": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "GbN7R2BOoZf3F7aK02nz9kWf6ttbvVzpw1orGG30VmrKTmRV6pasQOCfF2fjKXyHIMC/lAiBEYHCKjgf0OiGvQ==", - "dependencies": { - "Microsoft.Extensions.Diagnostics": "10.0.13", - "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "10.11.0", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0", - "Polly.Extensions": "8.4.2", - "Polly.RateLimiting": "8.4.2" - } - }, - "Microsoft.Extensions.Telemetry": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2meCfABvkLPtEBBwGzItIGnhrex1AEn2N+dHvxB5UoozeX/xTtBuUz5BRdjNI5oNgd5T31kC69WWw3BHDc9iZA==", - "dependencies": { - "Microsoft.Extensions.AmbientMetadata.Application": "10.11.0", - "Microsoft.Extensions.DependencyInjection.AutoActivation": "10.11.0", - "Microsoft.Extensions.Logging.Configuration": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0" - } - }, - "Microsoft.Extensions.Telemetry.Abstractions": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "FzcHRan/C2g5X5KD0kPlL4tTROFRpM8sqcXfOIi6FGLsw/d2yoOYMbLJ5hyb8N5QgOVW7e1TdwEN4zVUfcwfdw==", - "dependencies": { - "Microsoft.Extensions.Compliance.Abstractions": "10.11.0", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13" - } - }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "SvzUeqFGrcQxlIgjmcoSGiV5UWcPa0NCTuH69/40uSDsSD/26c6p9cH7XLAxpn+I8+2Zhl1qp+WMugl0oOwBMg==" - }, - "Microsoft.Testing.Extensions.Telemetry": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "mu2iyoHovwl0q1mGeeRU0h8+LALXC7HqbxniLa1shTKYdJGl+KPoCEgjWIQ8MLzk1tlTGPOfg1JsxdH3RxhMCA==", - "dependencies": { - "Microsoft.ApplicationInsights": "2.23.0", - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Testing.Extensions.TrxReport.Abstractions": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "DYTZAguaHz0wNJdHDTTGYOXtnlDoLoIbTMDKSApNNcytm55DJcnwpwELfQGLk5DB5QlgaEjNhnGo1Pu5QvL5VA==", - "dependencies": { - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Testing.Platform": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "FAMaFFWnULW+hDHMb40Qzhcgz9cAU2/EtgRCBNX/DdQoKo0sPG2EiY+w7bQdl/BgHnf/DbpXLbf5Xy0o15M8NA==" - }, - "Microsoft.Testing.Platform.MSBuild": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "lYawcAwY+h76rQmpma2n0HaL8zkOFbbKapso0Eb+uOAUQn7333pIByLftEuiO67csAoZufHNMwi6PqhNemWQXA==", - "dependencies": { - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Win32.Registry": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg==" - }, - "Mono.Cecil": { - "type": "Transitive", - "resolved": "0.11.6", - "contentHash": "f33RkDtZO8VlGXCtmQIviOtxgnUdym9xx/b1p9h91CRGOsJFxCFOFK1FDbVt1OCf1aWwYejUFa2MOQyFWTFjbA==" - }, - "Polly.Core": { - "type": "Transitive", - "resolved": "8.4.2", - "contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g==" - }, - "Polly.Extensions": { - "type": "Transitive", - "resolved": "8.4.2", - "contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==", - "dependencies": { - "Microsoft.Extensions.Logging.Abstractions": "8.0.0", - "Microsoft.Extensions.Options": "8.0.0", - "Polly.Core": "8.4.2" - } - }, - "Polly.RateLimiting": { - "type": "Transitive", - "resolved": "8.4.2", - "contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==", - "dependencies": { - "Polly.Core": "8.4.2", - "System.Threading.RateLimiting": "8.0.0" - } - }, - "System.Diagnostics.EventLog": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "lcyUiXTsETK2ALsZrX+nWuHSIQeazhqPphLfaRxzdGaG93+0kELqpgEHtwWOlQe7+jSFnKwaCAgL4kjeZCQJnw==" - }, - "System.IO.Hashing": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "lVqovhCt3HlZe7ONG5ydaj6BYwYI004gldVfMMkJl/lR5ueeCtWNpW4nejOX75sPmzm8vXCxB69GqwHaYCnyUQ==" - }, - "System.Security.AccessControl": { - "type": "Transitive", - "resolved": "6.0.1", - "contentHash": "IQ4NXP/B3Ayzvw0rDQzVTYsCKyy0Jp9KI6aYcK7UnGVlR9+Awz++TIPCQtPYfLJfOpm8ajowMR09V7quD3sEHw==" - }, - "System.Threading.RateLimiting": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q==" - }, - "xunit.analyzers": { - "type": "Transitive", - "resolved": "2.2.0", - "contentHash": "dXMIIztipcAyL3a19gtUrih/RLrE33/4VJdICoinYqIXXo1KLtsMPsaQ9dO2pE8xajDguwE2kqVbBqE5/EoJ0Q==" - }, - "xunit.v3.assert": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "5PKRexYlvufWFdXenRcRGKqvaJBBZFJZpqUGlUs9p13eKEgVdOrLpkPknjzUvLY5kEUicK9871DIUDcCPA6AXA==" - }, - "xunit.v3.common": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "++CtT8daIf6qfieQev/8V88U3zViIDWou5cj+oWps1/Hf73UoaY/L0hKyi3v7Zlt3BmbU0pUc73zCB1GiB4nYA==", - "dependencies": { - "Microsoft.Bcl.AsyncInterfaces": "6.0.0" - } - }, - "xunit.v3.core.mtp-v2": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "XyPMcQRsnUQLhmBBRRgYWsuPc8TyiANzcXtqfzyWfDpPuyh3Q0K4oWozZYQKZRNGnqJ97ifD6qUDWhsEEe32uw==", - "dependencies": { - "Microsoft.Testing.Extensions.Telemetry": "2.5.1", - "Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.5.1", - "Microsoft.Testing.Platform": "2.5.1", - "Microsoft.Testing.Platform.MSBuild": "2.5.1", - "xunit.v3.extensibility.core": "[4.0.2]", - "xunit.v3.runner.inproc.console": "[4.0.2]" - } - }, - "xunit.v3.extensibility.core": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "ARTt+pGyd86mdtiFBkKpyBQvRC3u0rr8oidBlII2GsAg7D6TfOsDFCsoQtFij83V5pE57m3whUIqT4xjiARXbQ==", - "dependencies": { - "xunit.v3.common": "[4.0.2]" - } - }, - "xunit.v3.mtp-v2": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "XLV32FhkuvheBStvX0DvjfPEtI+4SOVcIhnlTS+549r8VfVwsjpWdkJtQmQ7D23PA+Zoaqo+sTjBkRSkidC6Tw==", - "dependencies": { - "xunit.analyzers": "2.2.0", - "xunit.v3.assert": "[4.0.2]", - "xunit.v3.core.mtp-v2": "[4.0.2]" - } - }, - "xunit.v3.runner.inproc.console": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "cg4XNpCN4Ry9nswutknpreN3ckSUBwtjMRmEQSNK/sIKPo6KN5tDGGGCaHDm5HGA4yFVVtTJX65tLCsZArUNfQ==", - "dependencies": { - "xunit.v3.extensibility.core": "[4.0.2]", - "xunit.v3.runner.common": "[4.0.2]" - } - }, - "dotbahn.common": { - "type": "Project", - "dependencies": { - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Options": "[10.0.14, )" - } - }, - "dotbahn.common.tests": { - "type": "Project", - "dependencies": { - "DotBahn.Common": "[1.0.0, )", - "Microsoft.Testing.Extensions.CodeCoverage": "[18.12.0, )", - "Moq": "[4.21.0, )", - "xunit.v3": "[4.0.2, )", - "xunit.v3.runner.common": "[4.0.2, )" - } - }, - "dotbahn.facilities": { - "type": "Project", - "dependencies": { - "DotBahn.Common": "[1.0.0, )", - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Http.Resilience": "[10.11.0, )", - "Microsoft.Extensions.Options": "[10.0.14, )" - } - }, - "Microsoft.Extensions.Http": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "IDsXLGGz7nJMsqspWnErsP18WyAVf6V9Ixl4p47/8/95Jak3ZA1YWhQ0iesMVwubVhkVZGoO9m9ADUnK0m6HLw==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Http.Resilience": { - "type": "CentralTransitive", - "requested": "[10.11.0, )", - "resolved": "10.11.0", - "contentHash": "6/YEoPCcQLzExm4x4FH5c38JffbhkMaTtXsrDmYNozt9KRtdXK3TsDeuKSBZJno+41oIDGBONb2up0zCsuEERw==", - "dependencies": { - "Microsoft.Extensions.Http.Diagnostics": "10.11.0", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Resilience": "10.11.0" - } - }, - "Microsoft.Extensions.Options": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Moq": { - "type": "CentralTransitive", - "requested": "[4.21.0, )", - "resolved": "4.21.0", - "contentHash": "HUjrhhzEJ/AfbSBCnR8lPkpveVGpV/dNuOlnpfqBNTME93izly1CRV4N5zBySqz4m2yCRlHLPy/PnPzYokbwIg==", - "dependencies": { - "Castle.Core": "5.2.1" - } - } - } - } -} \ No newline at end of file diff --git a/tests/DotBahn.Stations.Tests/Authorization/ApiKeyAuthorizationTests.cs b/tests/DotBahn.Stations.Tests/Authorization/ApiKeyAuthorizationTests.cs deleted file mode 100644 index 39ee96b..0000000 --- a/tests/DotBahn.Stations.Tests/Authorization/ApiKeyAuthorizationTests.cs +++ /dev/null @@ -1,55 +0,0 @@ -using DotBahn.Common.Auth; - -namespace DotBahn.Stations.Tests.Authorization; - -public class ApiKeyAuthorizationTests { - [Fact] - public void AuthorizeRequest_SetsClientIdHeader() { - var auth = new ApiKeyAuthorization(new AuthorizationOptions { - ClientId = "my-client-id", - ApiKey = "my-api-key" - }); - using var request = new HttpRequestMessage(HttpMethod.Get, "https://example.com"); - - auth.AuthorizeRequest(request); - - Assert.Equal("my-client-id", request.Headers.GetValues("DB-Client-Id").Single()); - } - - [Fact] - public void AuthorizeRequest_SetsApiKeyHeader() { - var auth = new ApiKeyAuthorization(new AuthorizationOptions { - ClientId = "my-client-id", - ApiKey = "my-api-key" - }); - using var request = new HttpRequestMessage(HttpMethod.Get, "https://example.com"); - - auth.AuthorizeRequest(request); - - Assert.Equal("my-api-key", request.Headers.GetValues("DB-Api-Key").Single()); - } - - [Fact] - public void AuthorizeRequest_WithNullRequest_ThrowsArgumentNullException() { - var auth = new ApiKeyAuthorization(new AuthorizationOptions { - ClientId = "my-client-id", - ApiKey = "my-api-key" - }); - - Assert.Throws(() => auth.AuthorizeRequest(null!)); - } - - [Fact] - public void AuthorizeRequest_SetsBothClientIdAndApiKeyHeaders() { - var auth = new ApiKeyAuthorization(new AuthorizationOptions { - ClientId = "my-client-id", - ApiKey = "my-api-key" - }); - using var request = new HttpRequestMessage(HttpMethod.Get, "https://example.com"); - - auth.AuthorizeRequest(request); - - Assert.Equal("my-client-id", request.Headers.GetValues("DB-Client-Id").Single()); - Assert.Equal("my-api-key", request.Headers.GetValues("DB-Api-Key").Single()); - } -} diff --git a/tests/DotBahn.Stations.Tests/Client/StationClientTests.cs b/tests/DotBahn.Stations.Tests/Client/StationClientTests.cs deleted file mode 100644 index 7c238bb..0000000 --- a/tests/DotBahn.Stations.Tests/Client/StationClientTests.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System.Net; -using DotBahn.Common.Parsing; -using DotBahn.Common.Tests; -using DotBahn.Common.Transformer; -using DotBahn.Stations.Internal.Contracts; -using DotBahn.Stations.Models; -using Moq; - -namespace DotBahn.Stations.Tests.Client; - -public class StationClientTests : ClientTestBase { - private readonly Mock> _parserMock = new(); - private readonly Mock, StationsResponseContract>> _transformerMock = new(); - - public StationClientTests() { - HttpClient.BaseAddress = new Uri("https://api.deutschebahn.com"); - } - - [Fact] - public async Task GetStationsAsync_BuildsStationsUrl() { - var client = CreateClient(); - var query = new StationQuery(); - var contract = new StationsResponseContract(); - - SetupMocks(contract); - HttpHandler.RespondWith(HttpStatusCode.OK, "{}", "application/json"); - - await client.GetStationsAsync(query, TestContext.Current.CancellationToken); - - var requestUri = HttpHandler.SentRequests[0].RequestUri!.ToString(); - Assert.Contains("/stations", requestUri); - var request = HttpHandler.SentRequests[0]; - - Assert.Equal(HttpMethod.Get, request.Method); - Assert.Contains("application/json", request.Headers.Accept.Select(h => h.MediaType)); - } - - [Fact] - public async Task GetStationsAsync_AppliesQueryParametersToUrl() { - var client = CreateClient(); - var query = new StationQuery { Names = ["Berlin"] }; - var contract = new StationsResponseContract(); - - _parserMock.Setup(p => p.Parse(It.IsAny())).Returns(contract); - _transformerMock.Setup(t => t.Transform(It.IsAny())).Returns([]); - HttpHandler.RespondWith(HttpStatusCode.OK, "{}", "application/json"); - - await client.GetStationsAsync(query, TestContext.Current.CancellationToken); - - var request = HttpHandler.SentRequests[0]; - Assert.Contains("searchstring=Berlin", request.RequestUri?.ToString()); - } - - [Fact] - public async Task GetStationsAsync_SortsStationsByCategoryAscending() { - var client = CreateClient(); - var query = new StationQuery(); - var contract = new StationsResponseContract { - Stations = [ - new StationContract { Number = 1, Name = "Station C", Category = 5 }, - new StationContract { Number = 2, Name = "Station A", Category = 2 }, - new StationContract { Number = 3, Name = "Station B", Category = 7 } - ] - }; - _parserMock.Setup(p => p.Parse(It.IsAny())).Returns(contract); - _transformerMock.Setup(t => t.Transform(It.IsAny())).Returns([]); - HttpHandler.RespondWith(HttpStatusCode.OK, "{}", "application/json"); - - await client.GetStationsAsync(query, TestContext.Current.CancellationToken); - - Assert.Equal(2, contract.Stations[0].Category); - Assert.Equal(5, contract.Stations[1].Category); - Assert.Equal(7, contract.Stations[2].Category); - } - - [Fact] - public async Task GetStationsAsync_WithNullQuery_ThrowsArgumentNullException() { - var client = CreateClient(); - - await Assert.ThrowsAsync(() => - client.GetStationsAsync(null!, TestContext.Current.CancellationToken)); - } - - private StationClient CreateClient() => - new(HttpClient, AuthorizationMock.Object, _parserMock.Object, _transformerMock.Object); - - private void SetupMocks(StationsResponseContract contract) { - _parserMock.Setup(p => p.Parse(It.IsAny())).Returns(contract); - _transformerMock.Setup(t => t.Transform(It.IsAny())).Returns([]); - } -} diff --git a/tests/DotBahn.Stations.Tests/Models/StationTests.cs b/tests/DotBahn.Stations.Tests/Models/StationTests.cs deleted file mode 100644 index be8ebd4..0000000 --- a/tests/DotBahn.Stations.Tests/Models/StationTests.cs +++ /dev/null @@ -1,91 +0,0 @@ -using DotBahn.Common.Models; -using DotBahn.Stations.Models; -using DotBahn.Stations.Models.Enumerations; - -namespace DotBahn.Stations.Tests.Models; - -public class StationTests { - private static Station Make(IReadOnlyList? ril100 = null, IReadOnlyList? evaNumbers = null) => new() { - Number = 1, - Name = "Test", - Category = StationCategory.Category1, - Services = new StationServices(), - Ril100Identifiers = ril100 ?? [], - EvaNumbers = evaNumbers ?? [] - }; - - - [Fact] - public void PrimaryRil100_Empty_ReturnsNull() { - var station = Make(); - - Assert.Null(station.PrimaryRil100); - } - - [Fact] - public void PrimaryRil100_MainExists_ReturnsMain() { - var main = new Ril100Identifier { Identifier = "HH", IsMain = true }; - var other = new Ril100Identifier { Identifier = "HH2", IsMain = false }; - var station = Make(ril100: [other, main]); - - Assert.Same(main, station.PrimaryRil100); - } - - [Fact] - public void PrimaryRil100_NoMain_ReturnsFallbackFirst() { - var first = new Ril100Identifier { Identifier = "HH", IsMain = false }; - var second = new Ril100Identifier { Identifier = "HH2", IsMain = false }; - var station = Make(ril100: [first, second]); - - Assert.Same(first, station.PrimaryRil100); - } - - - [Fact] - public void PrimaryEva_Empty_ReturnsNull() { - var station = Make(); - - Assert.Null(station.PrimaryEva); - } - - [Fact] - public void PrimaryEva_MainExists_ReturnsMain() { - var main = new EvaNumber { Number = 8000105, IsMain = true }; - var other = new EvaNumber { Number = 8000106, IsMain = false }; - var station = Make(evaNumbers: [other, main]); - - Assert.Same(main, station.PrimaryEva); - } - - [Fact] - public void PrimaryEva_NoMain_ReturnsFallbackFirst() { - var first = new EvaNumber { Number = 8000105, IsMain = false }; - var second = new EvaNumber { Number = 8000106, IsMain = false }; - var station = Make(evaNumbers: [first, second]); - - Assert.Same(first, station.PrimaryEva); - } - - - [Fact] - public void Coordinates_NoEva_ReturnsNull() { - var station = Make(); - - Assert.Null(station.Coordinates); - } - - [Fact] - public void Coordinates_PrimaryEvaHasNoCoordinates_ReturnsNull() { - var eva = new EvaNumber { Number = 8000105, IsMain = true, Coordinates = null }; - - Assert.Null(Make(evaNumbers: [eva]).Coordinates); - } - - [Fact] - public void Coordinates_PrimaryEvaHasCoordinates_ReturnsCoordinates() { - var coords = new Coordinates { Longitude = 10.0, Latitude = 53.5 }; - var eva = new EvaNumber { Number = 8000105, IsMain = true, Coordinates = coords }; - - Assert.Equal(coords, Make(evaNumbers: [eva]).Coordinates); - } -} diff --git a/tests/DotBahn.Stations.Tests/Query/StationQueryCategoriesTests.cs b/tests/DotBahn.Stations.Tests/Query/StationQueryCategoriesTests.cs deleted file mode 100644 index b8eab92..0000000 --- a/tests/DotBahn.Stations.Tests/Query/StationQueryCategoriesTests.cs +++ /dev/null @@ -1,157 +0,0 @@ -namespace DotBahn.Stations.Tests.Query; - -public class StationQueryCategoriesTests { - [Fact] - public void WithCategories_Null_ShouldThrowArgumentException() { - var query = new StationQuery(); - - var exception = Assert.Throws(() => query.WithCategories(null!)); - Assert.Equal("categories", exception.ParamName); - Assert.Contains("At least one category must be specified", exception.Message); - } - - [Theory] - [InlineData("")] - [InlineData(" ")] - [InlineData("\t")] - public void WithCategories_Whitespace_ShouldThrowArgumentException(string whitespace) { - var query = new StationQuery(); - - var exception = Assert.Throws(() => query.WithCategories(whitespace)); - Assert.Equal("categories", exception.ParamName); - } - - [Theory] - [InlineData("1", "1")] - [InlineData("7", "7")] - [InlineData("4", "4")] - public void WithCategories_ValidSingle_SetsValue(string input, string expected) { - var query = new StationQuery().WithCategories(input); - - Assert.Equal(expected, query.Categories); - } - - [Theory] - [InlineData("0")] - [InlineData("8")] - [InlineData("10")] - [InlineData("abc")] - public void WithCategories_InvalidSingle_Throws(string invalid) { - var query = new StationQuery(); - - Assert.Throws(() => query.WithCategories(invalid)); - } - - [Theory] - [InlineData("1-3", "1-3")] - [InlineData("2-7", "2-7")] - [InlineData("1-1", "1-1")] - public void WithCategories_ValidRange_SetsValue(string input, string expected) { - var query = new StationQuery().WithCategories(input); - - Assert.Equal(expected, query.Categories); - } - - [Theory] - [InlineData("0-3")] - [InlineData("1-8")] - [InlineData("8-8")] - [InlineData("5-4")] - [InlineData("-1-3")] - public void WithCategories_InvalidRange_Throws(string invalidRange) { - var query = new StationQuery(); - - Assert.Throws(() => query.WithCategories(invalidRange)); - } - - [Theory] - [InlineData("a-3")] - [InlineData("1-b")] - [InlineData("x-y")] - [InlineData("1--3")] - public void WithCategories_NonNumericRange_Throws(string invalidRange) { - var query = new StationQuery(); - - var exception = Assert.Throws(() => query.WithCategories(invalidRange)); - Assert.Contains("Invalid category range", exception.Message); - } - - [Theory] - [InlineData("1,3,5", "1,3,5")] - [InlineData("1,2,3", "1,2,3")] - [InlineData("7,6,5", "7,6,5")] - public void WithCategories_MultipleValues_SetsValue(string input, string expected) { - var query = new StationQuery().WithCategories(input); - - Assert.Equal(expected, query.Categories); - } - - [Theory] - [InlineData("1,3-5,7", "1,3-5,7")] - [InlineData("1-2,4,6-7", "1-2,4,6-7")] - public void WithCategories_MixedCategoriesAndRanges_SetsValue(string input, string expected) { - var query = new StationQuery().WithCategories(input); - - Assert.Equal(expected, query.Categories); - } - - [Theory] - [InlineData(" 1 , 3 , 5 ", "1,3,5")] - [InlineData(" 1-3 ", "1-3")] - [InlineData(" 1 - 3 ", "1-3")] - public void WithCategories_Whitespace_TrimsAndNormalizes(string input, string expected) { - var query = new StationQuery().WithCategories(input); - - Assert.Equal(expected, query.Categories); - } - - [Fact] - public void WithCategories_ReturnsSameQuery() { - var query = new StationQuery(); - - var result = query.WithCategories("1-3"); - - Assert.Same(query, result); - Assert.Equal("1-3", query.Categories); - } - - [Fact] - public void WithCategories_RangeAtBoundary_SetsValue() { - var query = new StationQuery().WithCategories("7-7"); - - Assert.Equal("7-7", query.Categories); - } - - [Fact] - public void WithCategoriesRangeOverflowThrowsOverflowException() { - var query = new StationQuery(); - - Assert.Throws(() => query.WithCategories("9999999999999-1")); - } - - [Fact] - public void Categories_SetDirectly_RawValue() { - var query = new StationQuery { Categories = "1-3" }; - - Assert.Equal("1-3", query.Categories); - } - - public static TheoryData WithCategoriesRangeBoundaryCases => new() - { - { "BL—all_valid", "2-6", false }, - { "C1—start_lt_1", "0-3", true }, - { "C2—start_gt_7", "8-8", true }, - { "C4—end_gt_7", "1-8", true }, - { "C5—start_gt_end", "3-1", true }, - }; - - [Theory] - [MemberData(nameof(WithCategoriesRangeBoundaryCases))] - public void WithCategoriesRangeBoundary(string _, string categories, bool shouldThrow) { - var query = new StationQuery(); - if (shouldThrow) - Assert.Throws(() => query.WithCategories(categories)); - else - Assert.Equal(categories, query.WithCategories(categories).Categories); - } -} diff --git a/tests/DotBahn.Stations.Tests/Query/StationQueryFluentApiTests.cs b/tests/DotBahn.Stations.Tests/Query/StationQueryFluentApiTests.cs deleted file mode 100644 index 37cd771..0000000 --- a/tests/DotBahn.Stations.Tests/Query/StationQueryFluentApiTests.cs +++ /dev/null @@ -1,104 +0,0 @@ -using DotBahn.Stations.Models.Enumerations; - -namespace DotBahn.Stations.Tests.Query; - -public class StationQueryFluentApiTests { - [Fact] - public void InFederalState_ShouldSetStateAndReturnQuery() { - var query = new StationQuery(); - - var result = query.InFederalState(FederalState.Hamburg); - - Assert.Same(query, result); - Assert.Equal(FederalState.Hamburg, query.State); - } - - [Fact] - public void WithEva_ShouldSetEvaAndReturnQuery() { - var query = new StationQuery(); - - var result = query.WithEva("8002549"); - - Assert.Same(query, result); - Assert.Equal("8002549", query.Eva); - } - - [Fact] - public void WithRil_ShouldSetRilAndReturnQuery() { - var query = new StationQuery(); - - var result = query.WithRil("AH"); - - Assert.Same(query, result); - Assert.Equal("AH", query.Ril); - } - - [Fact] - public void CombineAs_ShouldSetOperatorAndReturnQuery() { - var query = new StationQuery(); - - var result = query.CombineAs(LogicalOperator.Or); - - Assert.Same(query, result); - Assert.Equal(LogicalOperator.Or, query.Operator); - } - - [Fact] - public void Skip_ShouldSetOffsetAndReturnQuery() { - var query = new StationQuery(); - - var result = query.Skip(50); - - Assert.Same(query, result); - Assert.Equal(50, query.Offset); - } - - [Fact] - public void LimitTo_ShouldSetLimitAndReturnQuery() { - var query = new StationQuery(); - - var result = query.LimitTo(100); - - Assert.Same(query, result); - Assert.Equal(100, query.Limit); - } - - [Fact] - public void FluentApi_ComplexChaining_ShouldSetAllProperties() { - var query = new StationQuery() - .WithNames("Hamburg", "Berlin") - .WithCategories("1-3") - .InFederalState(FederalState.Hamburg) - .WithEva("8002549") - .WithRil("AH") - .CombineAs(LogicalOperator.Or) - .Skip(10) - .LimitTo(50); - - Assert.Equal(["Hamburg*", "Berlin*"], query.Names!); - Assert.Equal("1-3", query.Categories); - Assert.Equal(FederalState.Hamburg, query.State); - Assert.Equal("8002549", query.Eva); - Assert.Equal("AH", query.Ril); - Assert.Equal(LogicalOperator.Or, query.Operator); - Assert.Equal(10, query.Offset); - Assert.Equal(50, query.Limit); - } - - [Fact] - public void FluentApi_PartialChaining_ShouldSetOnlySpecifiedProperties() { - var query = new StationQuery() - .WithNames("Hamburg") - .WithCategories("1") - .LimitTo(5); - - Assert.Equal(["Hamburg*"], query.Names!); - Assert.Equal("1", query.Categories); - Assert.Null(query.State); - Assert.Null(query.Eva); - Assert.Null(query.Ril); - Assert.Equal(LogicalOperator.And, query.Operator); - Assert.Equal(0, query.Offset); - Assert.Equal(5, query.Limit); - } -} diff --git a/tests/DotBahn.Stations.Tests/Query/StationQueryNamesTests.cs b/tests/DotBahn.Stations.Tests/Query/StationQueryNamesTests.cs deleted file mode 100644 index fc3f0a8..0000000 --- a/tests/DotBahn.Stations.Tests/Query/StationQueryNamesTests.cs +++ /dev/null @@ -1,86 +0,0 @@ -namespace DotBahn.Stations.Tests.Query; - -public class StationQueryNamesTests { - [Fact] - public void WithNames_Null_ShouldThrowArgumentException() { - var query = new StationQuery(); - - var exception = Assert.Throws(() => query.WithNames(null!)); - Assert.Equal("names", exception.ParamName); - Assert.Contains("At least one name is required", exception.Message); - } - - [Fact] - public void WithNames_Empty_ShouldThrowArgumentException() { - var query = new StationQuery(); - - var exception = Assert.Throws(() => query.WithNames()); - Assert.Equal("names", exception.ParamName); - } - - [Theory] - [InlineData("Hamburg", "Hamburg*")] - [InlineData("Berlin", "Berlin*")] - [InlineData("München", "München*")] - public void WithNames_WithoutWildcard_ShouldAppendAsterisk(string input, string expected) { - var query = new StationQuery().WithNames(input); - - Assert.Single(query.Names!); - Assert.Equal(expected, query.Names![0]); - } - - [Theory] - [InlineData("Hamburg*")] - [InlineData("*Hamburg")] - [InlineData("Ham*burg")] - [InlineData("Hamburg?")] - [InlineData("?Hamburg")] - [InlineData("Ham?burg")] - [InlineData("*Hamburg?")] - public void WithNames_WithWildcard_ShouldNotAppendAsterisk(string nameWithWildcard) { - var query = new StationQuery().WithNames(nameWithWildcard); - - Assert.Equal(nameWithWildcard, query.Names![0]); - } - - [Fact] - public void WithNames_WithMultipleValues_ShouldProcessEachIndividually() { - var query = new StationQuery().WithNames("Hamburg", "Berlin*", "München?"); - - Assert.Equal(3, query.Names!.Length); - Assert.Equal("Hamburg*", query.Names[0]); - Assert.Equal("Berlin*", query.Names[1]); - Assert.Equal("München?", query.Names[2]); - } - - [Fact] - public void WithNames_ShouldSetNamesAndReturnQuery() { - var query = new StationQuery(); - - var result = query.WithNames("Hamburg", "Berlin"); - - Assert.Same(query, result); - Assert.Equal(["Hamburg*", "Berlin*"], query.Names!); - } - - [Fact] - public void WithNames_FluentChaining_ShouldWork() { - var query = new StationQuery() - .WithNames("Hamburg") - .WithCategories("1") - .LimitTo(5); - - Assert.Equal(["Hamburg*"], query.Names!); - Assert.Equal("1", query.Categories); - Assert.Equal(5, query.Limit); - } - - [Theory] - [InlineData("Hamburg")] - [InlineData("Berlin")] - public void Names_SetDirectly_RawValues(string input) { - var query = new StationQuery { Names = [input] }; - - Assert.Equal([input], query.Names!); - } -} diff --git a/tests/DotBahn.Stations.Tests/Query/StationQueryOtherPropertiesTests.cs b/tests/DotBahn.Stations.Tests/Query/StationQueryOtherPropertiesTests.cs deleted file mode 100644 index 65f75f1..0000000 --- a/tests/DotBahn.Stations.Tests/Query/StationQueryOtherPropertiesTests.cs +++ /dev/null @@ -1,74 +0,0 @@ -using DotBahn.Stations.Models.Enumerations; - -namespace DotBahn.Stations.Tests.Query; - -public class StationQueryOtherPropertiesTests { - [Theory] - [InlineData(FederalState.Hamburg)] - [InlineData(FederalState.Bavaria)] - [InlineData(FederalState.Berlin)] - public void State_ShouldSetAndGetValue(FederalState state) { - var query = new StationQuery { - State = state - }; - - Assert.Equal(state, query.State); - } - - [Theory] - [InlineData("8002549")] - [InlineData("8000105")] - public void Eva_ShouldSetAndGetValue(string eva) { - var query = new StationQuery { - Eva = eva - }; - - Assert.Equal(eva, query.Eva); - } - - [Theory] - [InlineData("AH")] - [InlineData("BL")] - public void Ril_ShouldSetAndGetValue(string ril) { - var query = new StationQuery { - Ril = ril - }; - - Assert.Equal(ril, query.Ril); - } - - [Theory] - [InlineData(LogicalOperator.And)] - [InlineData(LogicalOperator.Or)] - public void Operator_ShouldSetAndGetValue(LogicalOperator op) { - var query = new StationQuery { - Operator = op - }; - - Assert.Equal(op, query.Operator); - } - - [Theory] - [InlineData(0)] - [InlineData(10)] - [InlineData(100)] - public void Offset_ShouldSetAndGetValue(int offset) { - var query = new StationQuery { - Offset = offset - }; - - Assert.Equal(offset, query.Offset); - } - - [Theory] - [InlineData(1)] - [InlineData(100)] - [InlineData(10000)] - public void Limit_ShouldSetAndGetValue(int limit) { - var query = new StationQuery { - Limit = limit - }; - - Assert.Equal(limit, query.Limit); - } -} diff --git a/tests/DotBahn.Stations.Tests/Query/StationQueryTests.cs b/tests/DotBahn.Stations.Tests/Query/StationQueryTests.cs deleted file mode 100644 index 6f53b5a..0000000 --- a/tests/DotBahn.Stations.Tests/Query/StationQueryTests.cs +++ /dev/null @@ -1,69 +0,0 @@ -using DotBahn.Stations.Models.Enumerations; - -namespace DotBahn.Stations.Tests.Query; - -public class StationQueryTests { - [Fact] - public void Constructor_ShouldInitializeWithDefaultValues() { - var query = new StationQuery(); - - Assert.Null(query.Names); - Assert.Null(query.Categories); - Assert.Null(query.State); - Assert.Null(query.Eva); - Assert.Null(query.Ril); - Assert.Equal(LogicalOperator.And, query.Operator); - Assert.Equal(0, query.Offset); - Assert.Equal(10000, query.Limit); - } - - [Fact] - public void ObjectInitializer_ShouldSetAllProperties() { - var query = new StationQuery { - Names = ["Hamburg"], - Categories = "1-3", - State = FederalState.Hamburg, - Eva = "8002549", - Ril = "AH", - Operator = LogicalOperator.Or, - Offset = 10, - Limit = 50 - }; - - Assert.Equal(["Hamburg"], query.Names); - Assert.Equal("1-3", query.Categories); - Assert.Equal(FederalState.Hamburg, query.State); - Assert.Equal("8002549", query.Eva); - Assert.Equal("AH", query.Ril); - Assert.Equal(LogicalOperator.Or, query.Operator); - Assert.Equal(10, query.Offset); - Assert.Equal(50, query.Limit); - } - - [Fact] - public void SkipNegativeOffsetSetsOffset() { - var query = new StationQuery(); - - query.Skip(-5); - - Assert.Equal(-5, query.Offset); - } - - [Fact] - public void LimitToZeroSetsLimit() { - var query = new StationQuery(); - - query.LimitTo(0); - - Assert.Equal(0, query.Limit); - } - - [Fact] - public void LimitToNegativeSetsLimit() { - var query = new StationQuery(); - - query.LimitTo(-1); - - Assert.Equal(-1, query.Limit); - } -} diff --git a/tests/DotBahn.Stations.Tests/Transformer/StationTransformerTests.cs b/tests/DotBahn.Stations.Tests/Transformer/StationTransformerTests.cs deleted file mode 100644 index 822f547..0000000 --- a/tests/DotBahn.Stations.Tests/Transformer/StationTransformerTests.cs +++ /dev/null @@ -1,167 +0,0 @@ -using DotBahn.Stations.Internal.Contracts; -using DotBahn.Stations.Internal.Transformers; -using DotBahn.Stations.Models.Enumerations; - -namespace DotBahn.Stations.Tests.Transformer; - -public class StationTransformerTests { - private readonly StationTransformer _transformer = new(); - - private static StationsResponseContract Wrap(StationContract station) => new() { - Stations = [station] - }; - - private static StationContract Minimal(int category = 1) => new() { - Number = 1, - Name = "Test", - Category = category - }; - - [Theory] - [InlineData(1, StationCategory.Category1)] - [InlineData(3, StationCategory.Category3)] - [InlineData(7, StationCategory.Category7)] - public void Transform_ValidCategory_MapsToEnum(int cat, StationCategory expected) { - var result = _transformer.Transform(Wrap(Minimal(cat))).First(); - - Assert.Equal(expected, result.Category); - } - - [Theory] - [InlineData(0)] - [InlineData(8)] - [InlineData(-1)] - public void Transform_OutOfRangeCategory_MapsToUnknown(int cat) { - var result = _transformer.Transform(Wrap(Minimal(cat))).First(); - - Assert.Equal(StationCategory.Unknown, result.Category); - } - - [Fact] - public void Transform_NullAddress_ReturnsNullAddress() { - var contract = Minimal() with { MailingAddress = null }; - - var result = _transformer.Transform(Wrap(contract)).First(); - - Assert.Null(result.Address); - } - - [Fact] - public void Transform_WithAddress_MapsFields() { - var contract = Minimal() with { - MailingAddress = new MailingAddressContract { - Street = "Hauptstraße 1", - ZipCode = "20095", - City = "Hamburg" - } - }; - - var result = _transformer.Transform(Wrap(contract)).First(); - - Assert.NotNull(result.Address); - Assert.Equal("Hauptstraße 1", result.Address.Street); - Assert.Equal("20095", result.Address.ZipCode); - Assert.Equal("Hamburg", result.Address.City); - } - - - [Fact] - public void Transform_NullRegionalArea_ReturnsNullRegionalArea() { - var contract = Minimal() with { RegionalArea = null }; - - var result = _transformer.Transform(Wrap(contract)).First(); - - Assert.Null(result.RegionalArea); - } - - [Fact] - public void Transform_WithRegionalArea_MapsFields() { - var contract = Minimal() with { - RegionalArea = new RegionalAreaContract { - Number = 10, - Name = "Nord", - ShortName = "N" - } - }; - - var result = _transformer.Transform(Wrap(contract)).First(); - - Assert.NotNull(result.RegionalArea); - Assert.Equal(10, result.RegionalArea.Number); - Assert.Equal("Nord", result.RegionalArea.Name); - Assert.Equal("N", result.RegionalArea.ShortName); - } - - - [Fact] - public void Transform_EvaWithNullCoordinates_ReturnsNullCoordinatesOnEva() { - var contract = Minimal() with { - EvaNumbers = [new EvaNumberContract { Number = 8000001, IsMain = true, GeographicCoordinates = null }] - }; - - var result = _transformer.Transform(Wrap(contract)).First(); - - Assert.Null(result.EvaNumbers.First().Coordinates); - } - - [Fact] - public void Transform_EvaWithZeroCoordinates_ReturnsNullCoordinates() { - var contract = Minimal() with { - EvaNumbers = [new EvaNumberContract { - Number = 8000001, - IsMain = true, - GeographicCoordinates = new GeographicCoordinatesContract { Coordinates = [] } - }] - }; - - var result = _transformer.Transform(Wrap(contract)).First(); - - Assert.Null(result.EvaNumbers.First().Coordinates); - } - - [Fact] - public void Transform_EvaWithSingleCoordinate_ReturnsNullCoordinates() { - var contract = Minimal() with { - EvaNumbers = [new EvaNumberContract { - Number = 8000001, - IsMain = true, - GeographicCoordinates = new GeographicCoordinatesContract { Coordinates = [10.0] } - }] - }; - - var result = _transformer.Transform(Wrap(contract)).First(); - - Assert.Null(result.EvaNumbers.First().Coordinates); - } - - [Fact] - public void Transform_EvaWithTwoCoordinates_MapsLongitudeAndLatitude() { - var contract = Minimal() with { - EvaNumbers = [new EvaNumberContract { - Number = 8000001, - IsMain = true, - GeographicCoordinates = new GeographicCoordinatesContract { Coordinates = [10.0, 53.5] } - }] - }; - - var result = _transformer.Transform(Wrap(contract)).First(); - var coords = result.EvaNumbers.First().Coordinates; - - Assert.NotNull(coords); - - var c = coords.Value; - Assert.Equal(10.0, c.Longitude); - Assert.Equal(53.5, c.Latitude); - } - - - [Fact] - public void Transform_AfterConstruction_DoesNotThrow() { - var transformer = new StationTransformer(); - - var result = transformer.Transform(Wrap(Minimal())); - - Assert.NotNull(result); - Assert.NotEmpty(result); - } -} diff --git a/tests/DotBahn.Stations.Tests/packages.lock.json b/tests/DotBahn.Stations.Tests/packages.lock.json deleted file mode 100644 index b7aeacb..0000000 --- a/tests/DotBahn.Stations.Tests/packages.lock.json +++ /dev/null @@ -1,522 +0,0 @@ -{ - "version": 2, - "dependencies": { - "net10.0": { - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[10.0.403, )", - "resolved": "10.0.403", - "contentHash": "T4WYxWydJGNQRe/EgURFlhPZ1cHYgivrCCHSomCcfQzGzhkDYGNn5bUwwjs4/PHuMxsmGaLvPv2puG8lluA1IA==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "10.0.403", - "Microsoft.SourceLink.Common": "10.0.403", - "System.IO.Hashing": "10.0.14" - } - }, - "Microsoft.Testing.Extensions.CodeCoverage": { - "type": "Direct", - "requested": "[18.12.0, )", - "resolved": "18.12.0", - "contentHash": "BST/sWYpKk9OXO7Yxktcg6FWORRsHU0EdCbMwZ7d3OqJsMKlrNHIZ30g0Ib4k5T5acJYXRBmg9mNrTU/N6cy1g==", - "dependencies": { - "Microsoft.DiaSymReader": "2.2.10", - "Microsoft.Extensions.DependencyModel": "10.0.10", - "Microsoft.Testing.Platform": "2.5.0", - "Mono.Cecil": "0.11.6" - } - }, - "MinVer": { - "type": "Direct", - "requested": "[8.0.0, )", - "resolved": "8.0.0", - "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" - }, - "Moq": { - "type": "Direct", - "requested": "[4.21.0, )", - "resolved": "4.21.0", - "contentHash": "HUjrhhzEJ/AfbSBCnR8lPkpveVGpV/dNuOlnpfqBNTME93izly1CRV4N5zBySqz4m2yCRlHLPy/PnPzYokbwIg==", - "dependencies": { - "Castle.Core": "5.2.1" - } - }, - "xunit.v3": { - "type": "Direct", - "requested": "[4.0.2, )", - "resolved": "4.0.2", - "contentHash": "TdjM2OAx7w/0E88E6PgaigLoTbQaxbSR3HF/8p92plchTjf29jPHW27ylvEOz+Nx8CvPwWKGQlOR1fDv6/Qh5A==", - "dependencies": { - "xunit.v3.mtp-v2": "[4.0.2]" - } - }, - "xunit.v3.runner.common": { - "type": "Direct", - "requested": "[4.0.2, )", - "resolved": "4.0.2", - "contentHash": "YlYKVhTJVcwEgJ6rm59Pjf71lQqKwKxEHqVRxWUuwrwm/nxB/mNFP/lP4vlntDO3GclNnLT9BjYOpJH9gViGQg==", - "dependencies": { - "Microsoft.Win32.Registry": "[5.0.0]", - "System.Security.AccessControl": "[6.0.1]", - "xunit.v3.common": "[4.0.2]" - } - }, - "Castle.Core": { - "type": "Transitive", - "resolved": "5.2.1", - "contentHash": "wHARzQA695jwwKreOzNsq54KiGqKP38tv8hi8e2FXDEC/sA6BtrX90tVPDkOfVu13PbEzr00TCV8coikl+D1Iw==", - "dependencies": { - "System.Diagnostics.EventLog": "6.0.0" - } - }, - "Microsoft.ApplicationInsights": { - "type": "Transitive", - "resolved": "2.23.0", - "contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw==" - }, - "Microsoft.Bcl.AsyncInterfaces": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg==" - }, - "Microsoft.Build.Tasks.Git": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "1furteBFeemMmZ4s+ORjQb7YtO+wG63NJahbQbRUi91FV6V87BdV0U3vX1jbMC6iKSELYYoXWssSzLu3mx0i2w==", - "dependencies": { - "System.IO.Hashing": "10.0.14" - } - }, - "Microsoft.DiaSymReader": { - "type": "Transitive", - "resolved": "2.2.10", - "contentHash": "zmGsm6b2y3STDa/Of7rdkkfTDV8VuGB8aCqIkLoJIQh5tL78K3zJ8OUyFKnfsaORXmGr9iOKwDkZfUjeXi+CwA==" - }, - "Microsoft.Extensions.AmbientMetadata.Application": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "aMCm7C6CexZT8W/p8zRp4BoxSnqRs3MmkBF7FvPIXC92b7vqs2SL0J+mVJi5W2Mk9Vb4ZRFWe9sdzFew6zUl1w==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" - } - }, - "Microsoft.Extensions.Compliance.Abstractions": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2mjAb3Sm5k6uNeI+IyXpggYMpfdDDGgZSwUm9QQsm5QgZboJWbm2eU+6wNMrlfFEao11yq6JS1zXI7SVQQ0NuQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13" - } - }, - "Microsoft.Extensions.Configuration": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.Binder": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.DependencyInjection": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.DependencyInjection.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" - }, - "Microsoft.Extensions.DependencyInjection.AutoActivation": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "h/sovspxVmT2DTIbWORMG0Gi3zVcPQzNl3kbwtpo0LoUXYbe2+66wQqZYwaF2ZWKN8HDdHv5yoc7d0DbDBBlnA==", - "dependencies": { - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13" - } - }, - "Microsoft.Extensions.DependencyModel": { - "type": "Transitive", - "resolved": "10.0.10", - "contentHash": "rfZA1RjR021RPqSmIPovfz2aOd79TGqJ9BengbjnzIISOVwjLmuSDnhCMmiY/1c6iYvGolQ1iNGzkav0u11XEA==" - }, - "Microsoft.Extensions.Diagnostics": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "80VqW8eKxQaxBOLDNpLUdxOlxzWn/jqBSxNBCfD8GCjcshNDpFvUgKh8uvvZwvkfBbwmNPWPWHyy9F+RLd1dlQ==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" - } - }, - "Microsoft.Extensions.Diagnostics.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vm+PPso6vOwGeX52MdOPh6z/R6KHgxQUwqq7k7Jc9jhy2JOxO2KB4xfoJQBBp2Ni8M4zKgJ4r2a1dgrYG7+MKw==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "Dp/FaAPo3U9h3HsWT1dcdRRV//rm+MQF5iKpY/WxL5swwV+wZNE5eyJZ0kgy9Upl/kHz4ejpiLMloxDIuJaoJQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13" - } - }, - "Microsoft.Extensions.FileProviders.Abstractions": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "BZDwtN3uoWRghDi5lRRZPDjMMCg2Ds7J6YEYjqka/TLjqnzquEpXyvchrIMeoubwT1ns23ow6PPeAoBHJO81Rw==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.13" - } - }, - "Microsoft.Extensions.Hosting.Abstractions": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "zIrbe9vkIFXxW3mOApIOWXw+xMwX7Cgsptr3ZSlglJt4hW2qp4fB/JU1NHgAevteBNH4PicvU9DsFPHxlnnloA==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13" - } - }, - "Microsoft.Extensions.Http.Diagnostics": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "iFcxcuMF/21LO+tDqDyzYVvokJUH03cNalmOJhmjyQSMV3dR4JAgcUBTV1iVH/yruC8wG2RNjvW0xcUgYqmrGg==", - "dependencies": { - "Microsoft.Extensions.Http": "10.0.13", - "Microsoft.Extensions.Telemetry": "10.11.0" - } - }, - "Microsoft.Extensions.Logging": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Configuration": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "OyYJOaE9WbBx1Hp+Dd2zrqeFM0JwH5M/x0VL6tNUv3V18vIAVpix8UjhvY9eW/iXpguEHy68JO/Z9YkBOwftIw==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.Configuration.Binder": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" - } - }, - "Microsoft.Extensions.ObjectPool": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "NX3bhcc0WitPKAVc9Zfi8jeEPClhfEmobUJM4a4bkWhJcBt5IWg6lCrItUoFy4whLjU+atXktURYCweQlR7wfg==" - }, - "Microsoft.Extensions.Options.ConfigurationExtensions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4wcIU0rE04ejEfCwHTftu9O8fgH6CRYCe+tseRapikUBn1Kic3QdO7ku22SwFyLrzdWGYPUZMEgv57ZYuuc5gA==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Primitives": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" - }, - "Microsoft.Extensions.Resilience": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "GbN7R2BOoZf3F7aK02nz9kWf6ttbvVzpw1orGG30VmrKTmRV6pasQOCfF2fjKXyHIMC/lAiBEYHCKjgf0OiGvQ==", - "dependencies": { - "Microsoft.Extensions.Diagnostics": "10.0.13", - "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "10.11.0", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0", - "Polly.Extensions": "8.4.2", - "Polly.RateLimiting": "8.4.2" - } - }, - "Microsoft.Extensions.Telemetry": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2meCfABvkLPtEBBwGzItIGnhrex1AEn2N+dHvxB5UoozeX/xTtBuUz5BRdjNI5oNgd5T31kC69WWw3BHDc9iZA==", - "dependencies": { - "Microsoft.Extensions.AmbientMetadata.Application": "10.11.0", - "Microsoft.Extensions.DependencyInjection.AutoActivation": "10.11.0", - "Microsoft.Extensions.Logging.Configuration": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0" - } - }, - "Microsoft.Extensions.Telemetry.Abstractions": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "FzcHRan/C2g5X5KD0kPlL4tTROFRpM8sqcXfOIi6FGLsw/d2yoOYMbLJ5hyb8N5QgOVW7e1TdwEN4zVUfcwfdw==", - "dependencies": { - "Microsoft.Extensions.Compliance.Abstractions": "10.11.0", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13" - } - }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "SvzUeqFGrcQxlIgjmcoSGiV5UWcPa0NCTuH69/40uSDsSD/26c6p9cH7XLAxpn+I8+2Zhl1qp+WMugl0oOwBMg==" - }, - "Microsoft.Testing.Extensions.Telemetry": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "mu2iyoHovwl0q1mGeeRU0h8+LALXC7HqbxniLa1shTKYdJGl+KPoCEgjWIQ8MLzk1tlTGPOfg1JsxdH3RxhMCA==", - "dependencies": { - "Microsoft.ApplicationInsights": "2.23.0", - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Testing.Extensions.TrxReport.Abstractions": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "DYTZAguaHz0wNJdHDTTGYOXtnlDoLoIbTMDKSApNNcytm55DJcnwpwELfQGLk5DB5QlgaEjNhnGo1Pu5QvL5VA==", - "dependencies": { - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Testing.Platform": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "FAMaFFWnULW+hDHMb40Qzhcgz9cAU2/EtgRCBNX/DdQoKo0sPG2EiY+w7bQdl/BgHnf/DbpXLbf5Xy0o15M8NA==" - }, - "Microsoft.Testing.Platform.MSBuild": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "lYawcAwY+h76rQmpma2n0HaL8zkOFbbKapso0Eb+uOAUQn7333pIByLftEuiO67csAoZufHNMwi6PqhNemWQXA==", - "dependencies": { - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Win32.Registry": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg==" - }, - "Mono.Cecil": { - "type": "Transitive", - "resolved": "0.11.6", - "contentHash": "f33RkDtZO8VlGXCtmQIviOtxgnUdym9xx/b1p9h91CRGOsJFxCFOFK1FDbVt1OCf1aWwYejUFa2MOQyFWTFjbA==" - }, - "Polly.Core": { - "type": "Transitive", - "resolved": "8.4.2", - "contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g==" - }, - "Polly.Extensions": { - "type": "Transitive", - "resolved": "8.4.2", - "contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==", - "dependencies": { - "Microsoft.Extensions.Logging.Abstractions": "8.0.0", - "Microsoft.Extensions.Options": "8.0.0", - "Polly.Core": "8.4.2" - } - }, - "Polly.RateLimiting": { - "type": "Transitive", - "resolved": "8.4.2", - "contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==", - "dependencies": { - "Polly.Core": "8.4.2", - "System.Threading.RateLimiting": "8.0.0" - } - }, - "System.Diagnostics.EventLog": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "lcyUiXTsETK2ALsZrX+nWuHSIQeazhqPphLfaRxzdGaG93+0kELqpgEHtwWOlQe7+jSFnKwaCAgL4kjeZCQJnw==" - }, - "System.IO.Hashing": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "lVqovhCt3HlZe7ONG5ydaj6BYwYI004gldVfMMkJl/lR5ueeCtWNpW4nejOX75sPmzm8vXCxB69GqwHaYCnyUQ==" - }, - "System.Security.AccessControl": { - "type": "Transitive", - "resolved": "6.0.1", - "contentHash": "IQ4NXP/B3Ayzvw0rDQzVTYsCKyy0Jp9KI6aYcK7UnGVlR9+Awz++TIPCQtPYfLJfOpm8ajowMR09V7quD3sEHw==" - }, - "System.Threading.RateLimiting": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q==" - }, - "xunit.analyzers": { - "type": "Transitive", - "resolved": "2.2.0", - "contentHash": "dXMIIztipcAyL3a19gtUrih/RLrE33/4VJdICoinYqIXXo1KLtsMPsaQ9dO2pE8xajDguwE2kqVbBqE5/EoJ0Q==" - }, - "xunit.v3.assert": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "5PKRexYlvufWFdXenRcRGKqvaJBBZFJZpqUGlUs9p13eKEgVdOrLpkPknjzUvLY5kEUicK9871DIUDcCPA6AXA==" - }, - "xunit.v3.common": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "++CtT8daIf6qfieQev/8V88U3zViIDWou5cj+oWps1/Hf73UoaY/L0hKyi3v7Zlt3BmbU0pUc73zCB1GiB4nYA==", - "dependencies": { - "Microsoft.Bcl.AsyncInterfaces": "6.0.0" - } - }, - "xunit.v3.core.mtp-v2": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "XyPMcQRsnUQLhmBBRRgYWsuPc8TyiANzcXtqfzyWfDpPuyh3Q0K4oWozZYQKZRNGnqJ97ifD6qUDWhsEEe32uw==", - "dependencies": { - "Microsoft.Testing.Extensions.Telemetry": "2.5.1", - "Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.5.1", - "Microsoft.Testing.Platform": "2.5.1", - "Microsoft.Testing.Platform.MSBuild": "2.5.1", - "xunit.v3.extensibility.core": "[4.0.2]", - "xunit.v3.runner.inproc.console": "[4.0.2]" - } - }, - "xunit.v3.extensibility.core": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "ARTt+pGyd86mdtiFBkKpyBQvRC3u0rr8oidBlII2GsAg7D6TfOsDFCsoQtFij83V5pE57m3whUIqT4xjiARXbQ==", - "dependencies": { - "xunit.v3.common": "[4.0.2]" - } - }, - "xunit.v3.mtp-v2": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "XLV32FhkuvheBStvX0DvjfPEtI+4SOVcIhnlTS+549r8VfVwsjpWdkJtQmQ7D23PA+Zoaqo+sTjBkRSkidC6Tw==", - "dependencies": { - "xunit.analyzers": "2.2.0", - "xunit.v3.assert": "[4.0.2]", - "xunit.v3.core.mtp-v2": "[4.0.2]" - } - }, - "xunit.v3.runner.inproc.console": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "cg4XNpCN4Ry9nswutknpreN3ckSUBwtjMRmEQSNK/sIKPo6KN5tDGGGCaHDm5HGA4yFVVtTJX65tLCsZArUNfQ==", - "dependencies": { - "xunit.v3.extensibility.core": "[4.0.2]", - "xunit.v3.runner.common": "[4.0.2]" - } - }, - "dotbahn.common": { - "type": "Project", - "dependencies": { - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Options": "[10.0.14, )" - } - }, - "dotbahn.common.tests": { - "type": "Project", - "dependencies": { - "DotBahn.Common": "[1.0.0, )", - "Microsoft.Testing.Extensions.CodeCoverage": "[18.12.0, )", - "Moq": "[4.21.0, )", - "xunit.v3": "[4.0.2, )", - "xunit.v3.runner.common": "[4.0.2, )" - } - }, - "dotbahn.stations": { - "type": "Project", - "dependencies": { - "DotBahn.Common": "[1.0.0, )", - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Http.Resilience": "[10.11.0, )", - "Microsoft.Extensions.Options": "[10.0.14, )" - } - }, - "Microsoft.Extensions.Http": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "IDsXLGGz7nJMsqspWnErsP18WyAVf6V9Ixl4p47/8/95Jak3ZA1YWhQ0iesMVwubVhkVZGoO9m9ADUnK0m6HLw==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Http.Resilience": { - "type": "CentralTransitive", - "requested": "[10.11.0, )", - "resolved": "10.11.0", - "contentHash": "6/YEoPCcQLzExm4x4FH5c38JffbhkMaTtXsrDmYNozt9KRtdXK3TsDeuKSBZJno+41oIDGBONb2up0zCsuEERw==", - "dependencies": { - "Microsoft.Extensions.Http.Diagnostics": "10.11.0", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Resilience": "10.11.0" - } - }, - "Microsoft.Extensions.Options": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - } - } - } -} \ No newline at end of file diff --git a/tests/DotBahn.Telemetry.Tests/AddDotBahnTelemetryTests.cs b/tests/DotBahn.Telemetry.Tests/AddDotBahnTelemetryTests.cs deleted file mode 100644 index aae888c..0000000 --- a/tests/DotBahn.Telemetry.Tests/AddDotBahnTelemetryTests.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Diagnostics; -using System.Net; -using DotBahn.Common.Auth; -using DotBahn.Common.Parsing; -using DotBahn.Common.Telemetry; -using DotBahn.Common.Tests; -using DotBahn.Common.Transformer; -using DotBahn.Stations; -using DotBahn.Stations.Internal.Contracts; -using DotBahn.Stations.Models; -using Microsoft.Extensions.DependencyInjection; -using Moq; -using OpenTelemetry.Trace; - -namespace DotBahn.Telemetry.Tests; - -[Collection("Telemetry")] -public class AddDotBahnTelemetryTests { - [Fact] - public async Task AddDotBahnTelemetry_RegistersSourceWithOpenTelemetry() { - var activities = new List(); - var services = new ServiceCollection(); - - services.AddOpenTelemetry().WithTracing(tracing => tracing.AddInMemoryExporter(activities)); - services.AddDotBahnTelemetry(); - - await using var provider = services.BuildServiceProvider(); - provider.GetRequiredService(); - - var parserMock = new Mock>(); - parserMock.Setup(p => p.Parse(It.IsAny())).Returns(new StationsResponseContract()); - var transformerMock = new Mock, StationsResponseContract>>(); - transformerMock.Setup(t => t.Transform(It.IsAny())).Returns([]); - - var handler = new MockHttpHandler(); - handler.RespondWith(HttpStatusCode.OK, "{}", "application/json"); - using var client = new StationClient(new HttpClient(handler) { - BaseAddress = new Uri("https://apis.deutschebahn.com/") - }, Mock.Of(), parserMock.Object, transformerMock.Object); - - await client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); - - var exported = Assert.Single(activities, activity => activity.Source.Name == DotBahnTelemetry.SourceName); - Assert.Equal(DotBahnTelemetry.RequestActivityName, exported.OperationName); - Assert.Equal("stations", exported.GetTagItem(DotBahnTelemetry.ApiTag)); - } -} diff --git a/tests/DotBahn.Telemetry.Tests/DotBahn.Telemetry.Tests.csproj b/tests/DotBahn.Telemetry.Tests/DotBahn.Telemetry.Tests.csproj deleted file mode 100644 index d556540..0000000 --- a/tests/DotBahn.Telemetry.Tests/DotBahn.Telemetry.Tests.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/DotBahn.Telemetry.Tests/DotBahnTelemetryTests.cs b/tests/DotBahn.Telemetry.Tests/DotBahnTelemetryTests.cs deleted file mode 100644 index ef26601..0000000 --- a/tests/DotBahn.Telemetry.Tests/DotBahnTelemetryTests.cs +++ /dev/null @@ -1,138 +0,0 @@ -using System.Diagnostics; -using System.Diagnostics.Metrics; -using System.Net; -using DotBahn.Common.Parsing; -using DotBahn.Common.Telemetry; -using DotBahn.Common.Tests; -using DotBahn.Common.Transformer; -using DotBahn.Stations; -using DotBahn.Stations.Internal.Contracts; -using DotBahn.Stations.Models; -using Moq; - -namespace DotBahn.Telemetry.Tests; - -[Collection("Telemetry")] -public class DotBahnTelemetryTests : ClientTestBase { - private readonly Mock> _parserMock = new(); - private readonly Mock, StationsResponseContract>> _transformerMock = new(); - private readonly StationClient _client; - - public DotBahnTelemetryTests() { - HttpClient.BaseAddress = new Uri("https://apis.deutschebahn.com/"); - _client = new StationClient(HttpClient, AuthorizationMock.Object, _parserMock.Object, _transformerMock.Object); - } - - [Fact] - public void StartRequest_WithoutListener_ReturnsNull() { - var activity = DotBahnTelemetry.StartRequest("stations", "/stations", null); - - Assert.Null(activity); - } - - [Fact] - public void StartRequest_WithListener_CreatesActivityWithTags() { - using var _ = CreateListener(); - - using var activity = DotBahnTelemetry.StartRequest("stations", "/stations?limit=1", "apis.deutschebahn.com"); - - Assert.NotNull(activity); - Assert.Equal(DotBahnTelemetry.RequestActivityName, activity.OperationName); - Assert.Equal(ActivityKind.Client, activity.Kind); - Assert.Equal("stations", activity.GetTagItem(DotBahnTelemetry.ApiTag)); - Assert.Equal("/stations?limit=1", activity.GetTagItem(DotBahnTelemetry.EndpointTag)); - Assert.Equal("apis.deutschebahn.com", activity.GetTagItem(DotBahnTelemetry.ServerAddressTag)); - } - - [Fact] - public void StartRequest_WithUnknownApi_OmitsApiTag() { - using var _ = CreateListener(); - - using var activity = DotBahnTelemetry.StartRequest(null, "/stations", null); - - Assert.NotNull(activity); - Assert.Null(activity.GetTagItem(DotBahnTelemetry.ApiTag)); - Assert.Null(activity.GetTagItem(DotBahnTelemetry.ServerAddressTag)); - } - - [Fact] - public async Task GetStationsAsync_WithListener_EmitsSuccessfulRequestTelemetry() { - SetupEmptyResponse(); - HttpHandler.RespondWith(HttpStatusCode.OK, "{}", "application/json"); - var histogramValues = new List(); - var counterValues = new List(); - using var meterListener = CreateMeterListener(histogramValues, counterValues); - - var result = await _client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); - - Assert.Empty(result); - var request = Assert.Single(HttpHandler.SentRequests); - Assert.Equal(HttpMethod.Get, request.Method); - Assert.Contains("/stations", request.RequestUri?.ToString()); - Assert.Contains("application/json", request.Headers.Accept.Select(h => h.MediaType)); - var measurement = Assert.Single(histogramValues); - Assert.True(measurement >= 0); - Assert.Single(counterValues); - } - - [Fact] - public async Task GetStationsAsync_OnHttpError_EmitsErrorTelemetry() { - SetupEmptyResponse(); - HttpHandler.RespondWith(HttpStatusCode.InternalServerError, "{}", "application/json"); - Activity? captured = null; - - using var listener = new ActivityListener(); - listener.ShouldListenTo = source => source.Name == DotBahnTelemetry.SourceName; - listener.Sample = (ref _) => ActivitySamplingResult.AllDataAndRecorded; - listener.ActivityStarted = activity => captured = activity; - ActivitySource.AddActivityListener(listener); - - await Assert.ThrowsAsync(() => - _client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken)); - - Assert.NotNull(captured); - Assert.Equal(ActivityStatusCode.Error, captured.Status); - Assert.Equal("HttpRequestException", captured.GetTagItem(DotBahnTelemetry.ErrorTypeTag)); - Assert.Equal("stations", captured.GetTagItem(DotBahnTelemetry.ApiTag)); - } - - [Fact] - public async Task GetStationsAsync_WithoutListener_DoesNotThrow() { - SetupEmptyResponse(); - HttpHandler.RespondWith(HttpStatusCode.OK, "{}", "application/json"); - - var result = await _client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); - - Assert.Empty(result); - } - - private void SetupEmptyResponse() { - _parserMock.Setup(p => p.Parse(It.IsAny())).Returns(new StationsResponseContract()); - _transformerMock.Setup(t => t.Transform(It.IsAny())).Returns([]); - } - - private static ActivityListener CreateListener() { - var listener = new ActivityListener { - ShouldListenTo = source => source.Name == DotBahnTelemetry.SourceName, - Sample = (ref _) => ActivitySamplingResult.AllDataAndRecorded - }; - ActivitySource.AddActivityListener(listener); - return listener; - } - - private static MeterListener CreateMeterListener(List histogramValues, List counterValues) { - var listener = new MeterListener { - InstrumentPublished = (instrument, meterListener) => { - if (instrument.Meter.Name == DotBahnTelemetry.MeterName) { - meterListener.EnableMeasurementEvents(instrument, null); - } - } - }; - - listener.SetMeasurementEventCallback((_, measurement, _, _) => histogramValues.Add(measurement)); - listener.SetMeasurementEventCallback((_, measurement, _, _) => counterValues.Add(measurement)); - listener.Start(); - - return listener; - } -} diff --git a/tests/DotBahn.Telemetry.Tests/packages.lock.json b/tests/DotBahn.Telemetry.Tests/packages.lock.json deleted file mode 100644 index 0f759b3..0000000 --- a/tests/DotBahn.Telemetry.Tests/packages.lock.json +++ /dev/null @@ -1,584 +0,0 @@ -{ - "version": 2, - "dependencies": { - "net10.0": { - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[10.0.403, )", - "resolved": "10.0.403", - "contentHash": "T4WYxWydJGNQRe/EgURFlhPZ1cHYgivrCCHSomCcfQzGzhkDYGNn5bUwwjs4/PHuMxsmGaLvPv2puG8lluA1IA==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "10.0.403", - "Microsoft.SourceLink.Common": "10.0.403", - "System.IO.Hashing": "10.0.14" - } - }, - "Microsoft.Testing.Extensions.CodeCoverage": { - "type": "Direct", - "requested": "[18.12.0, )", - "resolved": "18.12.0", - "contentHash": "BST/sWYpKk9OXO7Yxktcg6FWORRsHU0EdCbMwZ7d3OqJsMKlrNHIZ30g0Ib4k5T5acJYXRBmg9mNrTU/N6cy1g==", - "dependencies": { - "Microsoft.DiaSymReader": "2.2.10", - "Microsoft.Extensions.DependencyModel": "10.0.10", - "Microsoft.Testing.Platform": "2.5.0", - "Mono.Cecil": "0.11.6" - } - }, - "MinVer": { - "type": "Direct", - "requested": "[8.0.0, )", - "resolved": "8.0.0", - "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" - }, - "Moq": { - "type": "Direct", - "requested": "[4.21.0, )", - "resolved": "4.21.0", - "contentHash": "HUjrhhzEJ/AfbSBCnR8lPkpveVGpV/dNuOlnpfqBNTME93izly1CRV4N5zBySqz4m2yCRlHLPy/PnPzYokbwIg==", - "dependencies": { - "Castle.Core": "5.2.1" - } - }, - "OpenTelemetry": { - "type": "Direct", - "requested": "[1.20.1, )", - "resolved": "1.20.1", - "contentHash": "+XDw3fYbiv1a40aFnDJSQleeuUJciXuhoIA19XmcGhT47Hy/xZRqk8NCjHUDKrg72Ixjthicecp8ygBDNeH/Jw==", - "dependencies": { - "Microsoft.Extensions.Configuration.EnvironmentVariables": "10.0.0", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.0", - "Microsoft.Extensions.Logging.Configuration": "10.0.0", - "OpenTelemetry.Api.ProviderBuilderExtensions": "1.20.1" - } - }, - "OpenTelemetry.Exporter.InMemory": { - "type": "Direct", - "requested": "[1.20.1, )", - "resolved": "1.20.1", - "contentHash": "mjK/0K+cHh04GAnYWiwohu4JWKuSv44Itvt+VyW+31czYVJfcfQCc4VZVY4+gMOqox3NweUInsuJmCr0mHwzXg==", - "dependencies": { - "OpenTelemetry": "1.20.1" - } - }, - "OpenTelemetry.Extensions.Hosting": { - "type": "Direct", - "requested": "[1.20.1, )", - "resolved": "1.20.1", - "contentHash": "wnoK07COxyQBR47QwP80SIO4cpD2xeF4PrBDYFXDMnhDLmOP4nN0Szy1wCBLo5UABU1I4xwWRGzZM0bFdCbRog==", - "dependencies": { - "Microsoft.Extensions.Hosting.Abstractions": "10.0.0", - "OpenTelemetry": "1.20.1" - } - }, - "xunit.v3": { - "type": "Direct", - "requested": "[4.0.2, )", - "resolved": "4.0.2", - "contentHash": "TdjM2OAx7w/0E88E6PgaigLoTbQaxbSR3HF/8p92plchTjf29jPHW27ylvEOz+Nx8CvPwWKGQlOR1fDv6/Qh5A==", - "dependencies": { - "xunit.v3.mtp-v2": "[4.0.2]" - } - }, - "xunit.v3.runner.common": { - "type": "Direct", - "requested": "[4.0.2, )", - "resolved": "4.0.2", - "contentHash": "YlYKVhTJVcwEgJ6rm59Pjf71lQqKwKxEHqVRxWUuwrwm/nxB/mNFP/lP4vlntDO3GclNnLT9BjYOpJH9gViGQg==", - "dependencies": { - "Microsoft.Win32.Registry": "[5.0.0]", - "System.Security.AccessControl": "[6.0.1]", - "xunit.v3.common": "[4.0.2]" - } - }, - "Castle.Core": { - "type": "Transitive", - "resolved": "5.2.1", - "contentHash": "wHARzQA695jwwKreOzNsq54KiGqKP38tv8hi8e2FXDEC/sA6BtrX90tVPDkOfVu13PbEzr00TCV8coikl+D1Iw==", - "dependencies": { - "System.Diagnostics.EventLog": "6.0.0" - } - }, - "Microsoft.ApplicationInsights": { - "type": "Transitive", - "resolved": "2.23.0", - "contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw==" - }, - "Microsoft.Bcl.AsyncInterfaces": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg==" - }, - "Microsoft.Build.Tasks.Git": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "1furteBFeemMmZ4s+ORjQb7YtO+wG63NJahbQbRUi91FV6V87BdV0U3vX1jbMC6iKSELYYoXWssSzLu3mx0i2w==", - "dependencies": { - "System.IO.Hashing": "10.0.14" - } - }, - "Microsoft.DiaSymReader": { - "type": "Transitive", - "resolved": "2.2.10", - "contentHash": "zmGsm6b2y3STDa/Of7rdkkfTDV8VuGB8aCqIkLoJIQh5tL78K3zJ8OUyFKnfsaORXmGr9iOKwDkZfUjeXi+CwA==" - }, - "Microsoft.Extensions.AmbientMetadata.Application": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "aMCm7C6CexZT8W/p8zRp4BoxSnqRs3MmkBF7FvPIXC92b7vqs2SL0J+mVJi5W2Mk9Vb4ZRFWe9sdzFew6zUl1w==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" - } - }, - "Microsoft.Extensions.Compliance.Abstractions": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2mjAb3Sm5k6uNeI+IyXpggYMpfdDDGgZSwUm9QQsm5QgZboJWbm2eU+6wNMrlfFEao11yq6JS1zXI7SVQQ0NuQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13" - } - }, - "Microsoft.Extensions.Configuration": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.Binder": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.EnvironmentVariables": { - "type": "Transitive", - "resolved": "10.0.0", - "contentHash": "TmFegsI/uCdwMBD4yKpmO+OkjVNHQL49Dh/ep83NI5rPUEoBK9OdsJo1zURc1A2FuS/R/Pos3wsTjlyLnguBLA==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.0", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.0" - } - }, - "Microsoft.Extensions.DependencyInjection": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.DependencyInjection.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" - }, - "Microsoft.Extensions.DependencyInjection.AutoActivation": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "h/sovspxVmT2DTIbWORMG0Gi3zVcPQzNl3kbwtpo0LoUXYbe2+66wQqZYwaF2ZWKN8HDdHv5yoc7d0DbDBBlnA==", - "dependencies": { - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13" - } - }, - "Microsoft.Extensions.DependencyModel": { - "type": "Transitive", - "resolved": "10.0.10", - "contentHash": "rfZA1RjR021RPqSmIPovfz2aOd79TGqJ9BengbjnzIISOVwjLmuSDnhCMmiY/1c6iYvGolQ1iNGzkav0u11XEA==" - }, - "Microsoft.Extensions.Diagnostics": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "80VqW8eKxQaxBOLDNpLUdxOlxzWn/jqBSxNBCfD8GCjcshNDpFvUgKh8uvvZwvkfBbwmNPWPWHyy9F+RLd1dlQ==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" - } - }, - "Microsoft.Extensions.Diagnostics.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vm+PPso6vOwGeX52MdOPh6z/R6KHgxQUwqq7k7Jc9jhy2JOxO2KB4xfoJQBBp2Ni8M4zKgJ4r2a1dgrYG7+MKw==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "Dp/FaAPo3U9h3HsWT1dcdRRV//rm+MQF5iKpY/WxL5swwV+wZNE5eyJZ0kgy9Upl/kHz4ejpiLMloxDIuJaoJQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13" - } - }, - "Microsoft.Extensions.FileProviders.Abstractions": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "BZDwtN3uoWRghDi5lRRZPDjMMCg2Ds7J6YEYjqka/TLjqnzquEpXyvchrIMeoubwT1ns23ow6PPeAoBHJO81Rw==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.13" - } - }, - "Microsoft.Extensions.Hosting.Abstractions": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "zIrbe9vkIFXxW3mOApIOWXw+xMwX7Cgsptr3ZSlglJt4hW2qp4fB/JU1NHgAevteBNH4PicvU9DsFPHxlnnloA==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13" - } - }, - "Microsoft.Extensions.Http.Diagnostics": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "iFcxcuMF/21LO+tDqDyzYVvokJUH03cNalmOJhmjyQSMV3dR4JAgcUBTV1iVH/yruC8wG2RNjvW0xcUgYqmrGg==", - "dependencies": { - "Microsoft.Extensions.Http": "10.0.13", - "Microsoft.Extensions.Telemetry": "10.11.0" - } - }, - "Microsoft.Extensions.Logging": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Configuration": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "OyYJOaE9WbBx1Hp+Dd2zrqeFM0JwH5M/x0VL6tNUv3V18vIAVpix8UjhvY9eW/iXpguEHy68JO/Z9YkBOwftIw==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.Configuration.Binder": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" - } - }, - "Microsoft.Extensions.ObjectPool": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "NX3bhcc0WitPKAVc9Zfi8jeEPClhfEmobUJM4a4bkWhJcBt5IWg6lCrItUoFy4whLjU+atXktURYCweQlR7wfg==" - }, - "Microsoft.Extensions.Options.ConfigurationExtensions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4wcIU0rE04ejEfCwHTftu9O8fgH6CRYCe+tseRapikUBn1Kic3QdO7ku22SwFyLrzdWGYPUZMEgv57ZYuuc5gA==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Primitives": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" - }, - "Microsoft.Extensions.Resilience": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "GbN7R2BOoZf3F7aK02nz9kWf6ttbvVzpw1orGG30VmrKTmRV6pasQOCfF2fjKXyHIMC/lAiBEYHCKjgf0OiGvQ==", - "dependencies": { - "Microsoft.Extensions.Diagnostics": "10.0.13", - "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "10.11.0", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0", - "Polly.Extensions": "8.4.2", - "Polly.RateLimiting": "8.4.2" - } - }, - "Microsoft.Extensions.Telemetry": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2meCfABvkLPtEBBwGzItIGnhrex1AEn2N+dHvxB5UoozeX/xTtBuUz5BRdjNI5oNgd5T31kC69WWw3BHDc9iZA==", - "dependencies": { - "Microsoft.Extensions.AmbientMetadata.Application": "10.11.0", - "Microsoft.Extensions.DependencyInjection.AutoActivation": "10.11.0", - "Microsoft.Extensions.Logging.Configuration": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0" - } - }, - "Microsoft.Extensions.Telemetry.Abstractions": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "FzcHRan/C2g5X5KD0kPlL4tTROFRpM8sqcXfOIi6FGLsw/d2yoOYMbLJ5hyb8N5QgOVW7e1TdwEN4zVUfcwfdw==", - "dependencies": { - "Microsoft.Extensions.Compliance.Abstractions": "10.11.0", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13" - } - }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "SvzUeqFGrcQxlIgjmcoSGiV5UWcPa0NCTuH69/40uSDsSD/26c6p9cH7XLAxpn+I8+2Zhl1qp+WMugl0oOwBMg==" - }, - "Microsoft.Testing.Extensions.Telemetry": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "mu2iyoHovwl0q1mGeeRU0h8+LALXC7HqbxniLa1shTKYdJGl+KPoCEgjWIQ8MLzk1tlTGPOfg1JsxdH3RxhMCA==", - "dependencies": { - "Microsoft.ApplicationInsights": "2.23.0", - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Testing.Extensions.TrxReport.Abstractions": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "DYTZAguaHz0wNJdHDTTGYOXtnlDoLoIbTMDKSApNNcytm55DJcnwpwELfQGLk5DB5QlgaEjNhnGo1Pu5QvL5VA==", - "dependencies": { - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Testing.Platform": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "FAMaFFWnULW+hDHMb40Qzhcgz9cAU2/EtgRCBNX/DdQoKo0sPG2EiY+w7bQdl/BgHnf/DbpXLbf5Xy0o15M8NA==" - }, - "Microsoft.Testing.Platform.MSBuild": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "lYawcAwY+h76rQmpma2n0HaL8zkOFbbKapso0Eb+uOAUQn7333pIByLftEuiO67csAoZufHNMwi6PqhNemWQXA==", - "dependencies": { - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Win32.Registry": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg==" - }, - "Mono.Cecil": { - "type": "Transitive", - "resolved": "0.11.6", - "contentHash": "f33RkDtZO8VlGXCtmQIviOtxgnUdym9xx/b1p9h91CRGOsJFxCFOFK1FDbVt1OCf1aWwYejUFa2MOQyFWTFjbA==" - }, - "OpenTelemetry.Api": { - "type": "Transitive", - "resolved": "1.20.1", - "contentHash": "QO9hlwadOdJGR4vDpJyDnl9B62v7epIBSTIHUA4C+bCtrRaB4TWmYSnu3QVOIe7caH8dt7NaHRei6zebESJJyw==" - }, - "Polly.Core": { - "type": "Transitive", - "resolved": "8.4.2", - "contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g==" - }, - "Polly.Extensions": { - "type": "Transitive", - "resolved": "8.4.2", - "contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==", - "dependencies": { - "Microsoft.Extensions.Logging.Abstractions": "8.0.0", - "Microsoft.Extensions.Options": "8.0.0", - "Polly.Core": "8.4.2" - } - }, - "Polly.RateLimiting": { - "type": "Transitive", - "resolved": "8.4.2", - "contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==", - "dependencies": { - "Polly.Core": "8.4.2", - "System.Threading.RateLimiting": "8.0.0" - } - }, - "System.Diagnostics.EventLog": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "lcyUiXTsETK2ALsZrX+nWuHSIQeazhqPphLfaRxzdGaG93+0kELqpgEHtwWOlQe7+jSFnKwaCAgL4kjeZCQJnw==" - }, - "System.IO.Hashing": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "lVqovhCt3HlZe7ONG5ydaj6BYwYI004gldVfMMkJl/lR5ueeCtWNpW4nejOX75sPmzm8vXCxB69GqwHaYCnyUQ==" - }, - "System.Security.AccessControl": { - "type": "Transitive", - "resolved": "6.0.1", - "contentHash": "IQ4NXP/B3Ayzvw0rDQzVTYsCKyy0Jp9KI6aYcK7UnGVlR9+Awz++TIPCQtPYfLJfOpm8ajowMR09V7quD3sEHw==" - }, - "System.Threading.RateLimiting": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q==" - }, - "xunit.analyzers": { - "type": "Transitive", - "resolved": "2.2.0", - "contentHash": "dXMIIztipcAyL3a19gtUrih/RLrE33/4VJdICoinYqIXXo1KLtsMPsaQ9dO2pE8xajDguwE2kqVbBqE5/EoJ0Q==" - }, - "xunit.v3.assert": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "5PKRexYlvufWFdXenRcRGKqvaJBBZFJZpqUGlUs9p13eKEgVdOrLpkPknjzUvLY5kEUicK9871DIUDcCPA6AXA==" - }, - "xunit.v3.common": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "++CtT8daIf6qfieQev/8V88U3zViIDWou5cj+oWps1/Hf73UoaY/L0hKyi3v7Zlt3BmbU0pUc73zCB1GiB4nYA==", - "dependencies": { - "Microsoft.Bcl.AsyncInterfaces": "6.0.0" - } - }, - "xunit.v3.core.mtp-v2": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "XyPMcQRsnUQLhmBBRRgYWsuPc8TyiANzcXtqfzyWfDpPuyh3Q0K4oWozZYQKZRNGnqJ97ifD6qUDWhsEEe32uw==", - "dependencies": { - "Microsoft.Testing.Extensions.Telemetry": "2.5.1", - "Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.5.1", - "Microsoft.Testing.Platform": "2.5.1", - "Microsoft.Testing.Platform.MSBuild": "2.5.1", - "xunit.v3.extensibility.core": "[4.0.2]", - "xunit.v3.runner.inproc.console": "[4.0.2]" - } - }, - "xunit.v3.extensibility.core": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "ARTt+pGyd86mdtiFBkKpyBQvRC3u0rr8oidBlII2GsAg7D6TfOsDFCsoQtFij83V5pE57m3whUIqT4xjiARXbQ==", - "dependencies": { - "xunit.v3.common": "[4.0.2]" - } - }, - "xunit.v3.mtp-v2": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "XLV32FhkuvheBStvX0DvjfPEtI+4SOVcIhnlTS+549r8VfVwsjpWdkJtQmQ7D23PA+Zoaqo+sTjBkRSkidC6Tw==", - "dependencies": { - "xunit.analyzers": "2.2.0", - "xunit.v3.assert": "[4.0.2]", - "xunit.v3.core.mtp-v2": "[4.0.2]" - } - }, - "xunit.v3.runner.inproc.console": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "cg4XNpCN4Ry9nswutknpreN3ckSUBwtjMRmEQSNK/sIKPo6KN5tDGGGCaHDm5HGA4yFVVtTJX65tLCsZArUNfQ==", - "dependencies": { - "xunit.v3.extensibility.core": "[4.0.2]", - "xunit.v3.runner.common": "[4.0.2]" - } - }, - "dotbahn.common": { - "type": "Project", - "dependencies": { - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Options": "[10.0.14, )" - } - }, - "dotbahn.common.tests": { - "type": "Project", - "dependencies": { - "DotBahn.Common": "[1.0.0, )", - "Microsoft.Testing.Extensions.CodeCoverage": "[18.12.0, )", - "Moq": "[4.21.0, )", - "xunit.v3": "[4.0.2, )", - "xunit.v3.runner.common": "[4.0.2, )" - } - }, - "dotbahn.stations": { - "type": "Project", - "dependencies": { - "DotBahn.Common": "[1.0.0, )", - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Http.Resilience": "[10.11.0, )", - "Microsoft.Extensions.Options": "[10.0.14, )" - } - }, - "dotbahn.telemetry": { - "type": "Project", - "dependencies": { - "DotBahn.Common": "[1.0.0, )", - "OpenTelemetry.Api.ProviderBuilderExtensions": "[1.20.1, )" - } - }, - "Microsoft.Extensions.Http": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "IDsXLGGz7nJMsqspWnErsP18WyAVf6V9Ixl4p47/8/95Jak3ZA1YWhQ0iesMVwubVhkVZGoO9m9ADUnK0m6HLw==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Http.Resilience": { - "type": "CentralTransitive", - "requested": "[10.11.0, )", - "resolved": "10.11.0", - "contentHash": "6/YEoPCcQLzExm4x4FH5c38JffbhkMaTtXsrDmYNozt9KRtdXK3TsDeuKSBZJno+41oIDGBONb2up0zCsuEERw==", - "dependencies": { - "Microsoft.Extensions.Http.Diagnostics": "10.11.0", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Resilience": "10.11.0" - } - }, - "Microsoft.Extensions.Options": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "OpenTelemetry.Api.ProviderBuilderExtensions": { - "type": "CentralTransitive", - "requested": "[1.20.1, )", - "resolved": "1.20.1", - "contentHash": "eDzDY/jTBqRytkYECmVKF7ZP5sKmCIqv1SSnA5BSWltIIvc3931TOMRyCW1qCGNIgmtldtJhISnsmFNxOCfauQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0", - "OpenTelemetry.Api": "1.20.1" - } - } - } - } -} \ No newline at end of file diff --git a/tests/DotBahn.Tests.Boards/Client/BoardsClientTests.cs b/tests/DotBahn.Tests.Boards/Client/BoardsClientTests.cs new file mode 100644 index 0000000..0f88086 --- /dev/null +++ b/tests/DotBahn.Tests.Boards/Client/BoardsClientTests.cs @@ -0,0 +1,110 @@ +using System.Diagnostics; +using System.Net; +using DotBahn.Boards; +using DotBahn.Common.Auth; +using DotBahn.Common.Telemetry; +using DotBahn.Tests.Boards.Support; +using NSubstitute; +using Shouldly; + +namespace DotBahn.Tests.Boards.Client; + +public class BoardsClientTests { + [Fact] + public async Task GetArrivalsAsync_Should_ThrowArgumentNullException_When_QueryIsNull() { + using var fixture = new BoardsClientFixture(); + + var exception = await Should.ThrowAsync(() => fixture.Client.GetArrivalsAsync(null!)); + + exception.ParamName.ShouldBe("query"); + } + + [Fact] + public async Task GetDeparturesAsync_Should_ThrowArgumentNullException_When_QueryIsNull() { + using var fixture = new BoardsClientFixture(); + + var exception = await Should.ThrowAsync(() => fixture.Client.GetDeparturesAsync(null!)); + + exception.ParamName.ShouldBe("query"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task GetArrivalsAsync_Should_PostToArrivalsEndpoint_When_Called(bool departures) { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, "{\"meta\":{}}"); + + if (departures) { + await fixture.Client.GetDeparturesAsync(new BoardQuery(), TestContext.Current.CancellationToken); + } else { + await fixture.Client.GetArrivalsAsync(new BoardQuery(), TestContext.Current.CancellationToken); + } + + var request = fixture.Handler.SentRequests.ShouldHaveSingleItem(); + request.Method.ShouldBe(HttpMethod.Post); + request.RequestUri!.ToString().ShouldBe(departures ? "https://api.example.com/departures" : "https://api.example.com/arrivals"); + } + + [Theory] + [InlineData(HttpStatusCode.BadRequest, 400)] + [InlineData(HttpStatusCode.Unauthorized, 401)] + public async Task GetArrivalsAsync_Should_ThrowHttpRequestException_When_ApiReturnsError(HttpStatusCode statusCode, int expectedCode) { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(statusCode, "error"); + + var exception = await Should.ThrowAsync(() => fixture.Client.GetArrivalsAsync(new BoardQuery(), TestContext.Current.CancellationToken)); + + exception.StatusCode.ShouldBe(statusCode); + exception.Message.ShouldContain(expectedCode.ToString()); + } + + [Fact] + public async Task GetDeparturesAsync_Should_ThrowOperationCanceledException_When_Canceled() { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, "{\"meta\":{}}"); + using var cts = new CancellationTokenSource(); + await cts.CancelAsync(); + + await Should.ThrowAsync(() => fixture.Client.GetDeparturesAsync(new BoardQuery(), cts.Token)); + } + + [Theory] + [InlineData("{invalid")] + [InlineData("not json")] + [InlineData("null")] + public async Task GetArrivalsAsync_Should_ThrowJsonException_When_ResponseIsInvalid(string json) { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, json); + + await Should.ThrowAsync(() => fixture.Client.GetArrivalsAsync(new BoardQuery(), TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task GetArrivalsAsync_Should_ReportBoardsApiTag_When_ListenerIsActive() { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, "{\"meta\":{}}"); + var activities = new List(); + using var listener = new ActivityListener(); + listener.ShouldListenTo = source => source.Name == DotBahnTelemetry.SourceName; + listener.Sample = (ref _) => ActivitySamplingResult.AllDataAndRecorded; + listener.ActivityStarted = activities.Add; + ActivitySource.AddActivityListener(listener); + + await fixture.Client.GetArrivalsAsync(new BoardQuery(), TestContext.Current.CancellationToken); + + activities.ShouldContain(a => (string?)a.GetTagItem(DotBahnTelemetry.ApiTag) == "boards"); + } + + [Fact] + public async Task GetArrivalsAsync_Should_AuthorizeAndSetAcceptHeader_When_Called() { + var authorization = Substitute.For(); + using var fixture = new BoardsClientFixture(authorization); + fixture.Handler.RespondWith(HttpStatusCode.OK, "{\"meta\":{}}"); + + await fixture.Client.GetArrivalsAsync(new BoardQuery(), TestContext.Current.CancellationToken); + + authorization.Received(1).AuthorizeRequest(Arg.Any()); + fixture.Handler.SentRequests.ShouldHaveSingleItem().Headers.Accept.ShouldContain(header => header.MediaType == "application/json"); + } +} diff --git a/tests/DotBahn.Tests.Boards/DotBahn.Tests.Boards.csproj b/tests/DotBahn.Tests.Boards/DotBahn.Tests.Boards.csproj new file mode 100644 index 0000000..2e5dae8 --- /dev/null +++ b/tests/DotBahn.Tests.Boards/DotBahn.Tests.Boards.csproj @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/tests/DotBahn.Tests.Boards/Extensions/ServiceCollectionExtensionsTests.cs b/tests/DotBahn.Tests.Boards/Extensions/ServiceCollectionExtensionsTests.cs new file mode 100644 index 0000000..31348ee --- /dev/null +++ b/tests/DotBahn.Tests.Boards/Extensions/ServiceCollectionExtensionsTests.cs @@ -0,0 +1,75 @@ +using System.Net; +using DotBahn.Boards; +using DotBahn.Common.Auth; +using DotBahn.Tests.Shared.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Shouldly; + +namespace DotBahn.Tests.Boards.Extensions; + +public class ServiceCollectionExtensionsTests { + [Fact] + public void AddDotBahnBoards_Should_RegisterBoardsClient_When_Called() { + var (provider, _, _) = Create(); + using (provider) { + provider.GetRequiredService().ShouldNotBeNull(); + } + } + + [Fact] + public async Task GetArrivalsAsync_Should_UseDefaultEndpoint_When_NoConfigurationProvided() { + var (provider, handler, client) = Create(); + await using (provider) { + handler.RespondWith(HttpStatusCode.OK, "{\"meta\":{}}"); + + await client.GetArrivalsAsync(new BoardQuery(), TestContext.Current.CancellationToken); + + handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe("https://apis.deutschebahn.com/db-api-marketplace/apis/open-boards/v1/arrivals"); + } + } + + [Theory] + [InlineData("https://api.example.com/", "https://api.example.com/departures")] + [InlineData("https://example.org/boards/v1/", "https://example.org/boards/v1/departures")] + public async Task GetDeparturesAsync_Should_UseConfiguredEndpoint_When_ConfigurationProvided(string endpoint, string expectedUri) { + var (provider, handler, client) = Create(new Uri(endpoint)); + await using (provider) { + handler.RespondWith(HttpStatusCode.OK, "{\"meta\":{}}"); + + await client.GetDeparturesAsync(new BoardQuery(), TestContext.Current.CancellationToken); + + handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe(expectedUri); + } + } + + [Fact] + public async Task ValidateAsync_Should_RejectRelativeEndpoint_When_ValidationRuns() { + var services = new ServiceCollection(); + services.AddDotBahnBoards(options => options.BaseEndpoint = new Uri("relative", UriKind.Relative)); + await using var provider = services.BuildServiceProvider(); + var validator = provider.GetRequiredService(); + + var exception = await Should.ThrowAsync(() => validator.ValidateAsync()); + + exception.Message.ShouldContain("DotBahn: BaseEndpoint must be an absolute URI."); + } + + private static (ServiceProvider Provider, FakeHttpHandler Handler, IBoardsClient Client) Create(Uri? endpoint = null) { + var handler = new FakeHttpHandler(); + var services = new ServiceCollection(); + services.AddSingleton(new ApiKeyAuthorization(new AuthorizationOptions { + ClientId = "client", + ApiKey = "key" + })); + services.AddDotBahnBoards(options => { + if (endpoint != null) { + options.BaseEndpoint = endpoint; + } + }); + services.AddHttpClient("DotBahn.Boards").ConfigurePrimaryHttpMessageHandler(() => handler); + + var provider = services.BuildServiceProvider(); + return (provider, handler, provider.GetRequiredService()); + } +} diff --git a/tests/DotBahn.Tests.Boards/Models/ModelDefaultsTests.cs b/tests/DotBahn.Tests.Boards/Models/ModelDefaultsTests.cs new file mode 100644 index 0000000..ef55b74 --- /dev/null +++ b/tests/DotBahn.Tests.Boards/Models/ModelDefaultsTests.cs @@ -0,0 +1,95 @@ +using DotBahn.Boards.Models; +using DotBahn.Boards.Models.Entries; +using DotBahn.Boards.Models.Journeys; +using DotBahn.Boards.Models.Messages; +using DotBahn.Boards.Models.Operators; +using DotBahn.Common.Models; +using Shouldly; + +namespace DotBahn.Tests.Boards.Models; + +public class ModelDefaultsTests { + [Fact] + public void Board_Should_UseEmptyCollections_When_NotProvided() { + var arrival = new Board(); + var departure = new Board(); + + arrival.ConsideredStopPlaces.ShouldBeEmpty(); + arrival.Entries.ShouldBeEmpty(); + arrival.StationMessages.ShouldBeEmpty(); + arrival.TruncatedTransportTypes.ShouldBeEmpty(); + departure.Entries.ShouldBeEmpty(); + } + + [Fact] + public void Entries_Should_UseEmptyCollections_When_NotProvided() { + var arrival = CreateArrivalEntry(); + var departure = CreateDepartureEntry(); + + arrival.Messages.ShouldBeEmpty(); + arrival.ReliefBy.ShouldBeEmpty(); + arrival.ReliefFor.ShouldBeEmpty(); + arrival.ReplacedBy.ShouldBeEmpty(); + arrival.ReplacementFor.ShouldBeEmpty(); + arrival.TravelsWith.ShouldBeEmpty(); + arrival.ContinuationBy.ShouldBeEmpty(); + departure.Messages.ShouldBeEmpty(); + departure.ContinuationFor.ShouldBeEmpty(); + } + + [Fact] + public void SupportingModels_Should_UseEmptyCollections_When_NotProvided() { + var transport = new Transport { + Category = "ICE", + InternalCategory = "ICE", + Type = "HIGH_SPEED_TRAIN", + Number = "1", + OperationalNumber = "1", + Administration = new Administration { Id = "A", OperatorCode = "DB", OperatorName = "DB" } + }; + var message = new Message { Text = "text", Type = MessageType.Note }; + var administration = new Administration { Id = "A", OperatorCode = "DB", OperatorName = "DB" }; + + transport.Direction.ShouldBeEmpty(); + transport.DirectionStopPlaces.ShouldBeEmpty(); + transport.Via.ShouldBeEmpty(); + message.Resources.ShouldBeEmpty(); + administration.TransportCompanies.ShouldBeEmpty(); + } + + private static ArrivalEntry CreateArrivalEntry() => new() { + Id = "a1", + StopPlace = new StopPlace { EvaNumber = "1", Name = "Station" }, + Journey = CreateJourney(), + Time = new ChangedValue { Original = DateTime.UnixEpoch }, + Platform = new ChangedRef { Original = new Platform { Name = "1" } }, + Transport = CreateTransport() + }; + + private static DepartureEntry CreateDepartureEntry() => new() { + Id = "d1", + StopPlace = new StopPlace { EvaNumber = "1", Name = "Station" }, + Journey = CreateJourney(), + Time = new ChangedValue { Original = DateTime.UnixEpoch }, + Platform = new ChangedRef { Original = new Platform { Name = "1" } }, + Transport = CreateTransport() + }; + + private static Journey CreateJourney() => new() { + Id = "j1", + Origin = new Visit { StopPlace = new StopPlace { EvaNumber = "1", Name = "Station" } }, + Destination = new Visit { StopPlace = new StopPlace { EvaNumber = "2", Name = "Station 2" } }, + ScheduledStartTime = DateTime.UnixEpoch, + TransportAtStart = CreateTransport(), + Type = "REGULAR" + }; + + private static Transport CreateTransport() => new() { + Category = "ICE", + InternalCategory = "ICE", + Type = "HIGH_SPEED_TRAIN", + Number = "1", + OperationalNumber = "1", + Administration = new Administration { Id = "A", OperatorCode = "DB", OperatorName = "DB" } + }; +} diff --git a/tests/DotBahn.Tests.Boards/Query/BoardQueryMappingTests.cs b/tests/DotBahn.Tests.Boards/Query/BoardQueryMappingTests.cs new file mode 100644 index 0000000..c1a712a --- /dev/null +++ b/tests/DotBahn.Tests.Boards/Query/BoardQueryMappingTests.cs @@ -0,0 +1,160 @@ +using System.Net; +using DotBahn.Boards; +using DotBahn.Tests.Boards.Support; +using Shouldly; + +namespace DotBahn.Tests.Boards.Query; + +public class BoardQueryMappingTests { + [Theory] + [InlineData("\"maxViaStops\":3")] + [InlineData("\"languages\":[\"deu\",\"eng\"]")] + [InlineData("\"transportTypes\":null")] + [InlineData("\"timeWindow\":null")] + [InlineData("\"sortBy\":\"TIME\"")] + [InlineData("\"maxEntriesPerTransportType\":25")] + public async Task GetArrivalsAsync_Should_UseDocumentedDefaults_When_QueryIsEmpty(string expectedFragment) { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, "{\"meta\":{}}"); + + await fixture.Client.GetArrivalsAsync(new BoardQuery(), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequestBodies.ShouldHaveSingleItem().ShouldContain(expectedFragment); + } + + [Theory] + [InlineData(false, false, 0, "\"timeWindow\":null")] + [InlineData(true, false, 0, "\"timeStart\":\"2024-12-31T12:00:00Z\"")] + [InlineData(false, true, 0, "\"timeEnd\":\"2024-12-31T14:00:00Z\"")] + [InlineData(false, false, 5, "\"entryCount\":5")] + [InlineData(true, true, 5, "\"entryCount\":5")] + public async Task GetArrivalsAsync_Should_MapTimeWindow_When_ValuesProvided(bool withStart, bool withEnd, int entryCount, string expectedFragment) { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, "{\"meta\":{}}"); + var query = new BoardQuery(); + if (withStart) { + query = query.StartingAt(new DateTime(2024, 12, 31, 12, 0, 0, DateTimeKind.Utc)); + } + if (withEnd) { + query = query.EndingAt(new DateTime(2024, 12, 31, 14, 0, 0, DateTimeKind.Utc)); + } + if (entryCount > 0) { + query = query.ForNext(entryCount); + } + + await fixture.Client.GetArrivalsAsync(query, TestContext.Current.CancellationToken); + + fixture.Handler.SentRequestBodies.ShouldHaveSingleItem().ShouldContain(expectedFragment); + } + + [Theory] + [InlineData("\"evaNumbers\":null")] + [InlineData("\"dhids\":null")] + [InlineData("\"stada\":null")] + [InlineData("\"platforms\":null")] + [InlineData("\"boardConfigurations\":null")] + public async Task GetDeparturesAsync_Should_MapStopPlaceSelector_When_QueryIsEmpty(string expectedFragment) { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, "{\"meta\":{}}"); + + await fixture.Client.GetDeparturesAsync(new BoardQuery(), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequestBodies.ShouldHaveSingleItem().ShouldContain(expectedFragment); + } + + [Fact] + public async Task GetDeparturesAsync_Should_MapAllSelectors_When_Provided() { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, "{\"meta\":{}}"); + var query = new BoardQuery() + .ForEvaNumbers("8002549") + .ForStada("8002549") + .ForDhids("DH1") + .OnPlatforms("1") + .WithBoardConfigurations("TO_NEARBY") + .WithTransportTypes("ICE") + .InLanguages("deu") + .WithMaxEntriesPerTransportType(10) + .WithMaxViaStops(5) + .WithLineColours() + .WithPlatformAccessibility() + .WithoutCancellations() + .WithOnlyReplacementTransports() + .SortByTimeSchedule(); + + await fixture.Client.GetDeparturesAsync(query, TestContext.Current.CancellationToken); + + var body = fixture.Handler.SentRequestBodies.ShouldHaveSingleItem(); + body.ShouldContain("\"evaNumbers\":[\"8002549\"]"); + body.ShouldContain("\"stada\":\"8002549\""); + body.ShouldContain("\"dhids\":[\"DH1\"]"); + body.ShouldContain("\"platforms\":[\"1\"]"); + body.ShouldContain("\"boardConfigurations\":[\"TO_NEARBY\"]"); + body.ShouldContain("\"transportTypes\":[\"ICE\"]"); + body.ShouldContain("\"languages\":[\"deu\"]"); + body.ShouldContain("\"maxEntriesPerTransportType\":10"); + body.ShouldContain("\"maxViaStops\":5"); + body.ShouldContain("\"includeLineColours\":true"); + body.ShouldContain("\"includePlatformAccessibility\":true"); + body.ShouldContain("\"noCancellations\":true"); + body.ShouldContain("\"onlyReplacementTransports\":true"); + body.ShouldContain("\"sortBy\":\"TIME_SCHEDULE\""); + } + + [Theory] + [InlineData("\"evaNumbers\":null")] + [InlineData("\"dhids\":null")] + [InlineData("\"platforms\":null")] + [InlineData("\"boardConfigurations\":null")] + public async Task GetArrivalsAsync_Should_MapEmptySelectorsAsNull_When_EmptyArraysProvided(string expectedFragment) { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """{"meta":{}}"""); + var query = new BoardQuery() + .ForEvaNumbers() + .ForDhids() + .OnPlatforms() + .WithBoardConfigurations(); + + await fixture.Client.GetArrivalsAsync(query, TestContext.Current.CancellationToken); + + fixture.Handler.SentRequestBodies.ShouldHaveSingleItem().ShouldContain(expectedFragment); + } + + [Fact] + public async Task GetArrivalsAsync_Should_MapEmptyTransportTypesAndLanguagesAsNull_When_EmptyArraysProvided() { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """{"meta":{}}"""); + var query = new BoardQuery().WithTransportTypes().InLanguages(); + + await fixture.Client.GetArrivalsAsync(query, TestContext.Current.CancellationToken); + + var body = fixture.Handler.SentRequestBodies.ShouldHaveSingleItem(); + body.ShouldContain("\"transportTypes\":null"); + body.ShouldContain("\"languages\":null"); + } + + [Fact] + public async Task GetArrivalsAsync_Should_UseExplicitMaxViaStops_When_Provided() { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """{"meta":{}}"""); + + await fixture.Client.GetArrivalsAsync(new BoardQuery().WithMaxViaStops(7), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequestBodies.ShouldHaveSingleItem().ShouldContain("\"maxViaStops\":7"); + } + + [Theory] + [InlineData(DateTimeKind.Unspecified)] + [InlineData(DateTimeKind.Local)] + public async Task GetArrivalsAsync_Should_NormalizeStartTimeToUtc_When_KindProvided(DateTimeKind kind) { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """{"meta":{}}"""); + var local = new DateTime(2024, 12, 31, 12, 0, 0, DateTimeKind.Local); + var start = kind == DateTimeKind.Local ? local : DateTime.SpecifyKind(local, DateTimeKind.Unspecified); + var expected = (kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(start, DateTimeKind.Utc) : start.ToUniversalTime()).ToString("yyyy-MM-ddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture); + + await fixture.Client.GetArrivalsAsync(new BoardQuery().StartingAt(start), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequestBodies.ShouldHaveSingleItem().ShouldContain($"\"timeStart\":\"{expected}\""); + } +} diff --git a/tests/DotBahn.Tests.Boards/Query/BoardQueryTests.cs b/tests/DotBahn.Tests.Boards/Query/BoardQueryTests.cs new file mode 100644 index 0000000..367fc47 --- /dev/null +++ b/tests/DotBahn.Tests.Boards/Query/BoardQueryTests.cs @@ -0,0 +1,191 @@ +using DotBahn.Boards; +using Shouldly; + +namespace DotBahn.Tests.Boards.Query; + +public class BoardQueryTests { + [Fact] + public void Constructor_Should_UseDocumentedDefaults_When_Called() { + var sut = new BoardQuery(); + + sut.EvaNumbers.ShouldBeNull(); + sut.StadaId.ShouldBeNull(); + sut.Dhids.ShouldBeNull(); + sut.Platforms.ShouldBeNull(); + sut.BoardConfigurations.ShouldBeNull(); + sut.Start.ShouldBeNull(); + sut.End.ShouldBeNull(); + sut.EntryCount.ShouldBeNull(); + sut.TransportTypes.ShouldBeEmpty(); + sut.Languages.ShouldBe(["deu", "eng"]); + sut.MaxEntriesPerTransportType.ShouldBe(25); + sut.MaxViaStops.ShouldBeNull(); + sut.IncludeLineColours.ShouldBeFalse(); + sut.IncludePlatformAccessibility.ShouldBeFalse(); + sut.NoCancellations.ShouldBeFalse(); + sut.OnlyReplacementTransports.ShouldBeFalse(); + sut.SortBy.ShouldBe("TIME"); + } + + [Theory] + [InlineData("8002549")] + [InlineData("8002549", "8002548")] + public void ForEvaNumbers_Should_ReturnNewQuery_When_ValuesProvided(params string[] numbers) { + var sut = new BoardQuery(); + + var result = sut.ForEvaNumbers(numbers); + + result.ShouldNotBeSameAs(sut); + result.EvaNumbers.ShouldBe(numbers); + sut.EvaNumbers.ShouldBeNull(); + } + + [Theory] + [InlineData("8002549")] + [InlineData("8002549", "8002548")] + public void ForDhids_Should_ReturnNewQuery_When_ValuesProvided(params string[] dhids) { + var sut = new BoardQuery(); + + var result = sut.ForDhids(dhids); + + result.ShouldNotBeSameAs(sut); + result.Dhids.ShouldBe(dhids); + sut.Dhids.ShouldBeNull(); + } + + [Theory] + [InlineData("1")] + [InlineData("1", "2")] + public void OnPlatforms_Should_ReturnNewQuery_When_ValuesProvided(params string[] platforms) { + var sut = new BoardQuery(); + + var result = sut.OnPlatforms(platforms); + + result.ShouldNotBeSameAs(sut); + result.Platforms.ShouldBe(platforms); + sut.Platforms.ShouldBeNull(); + } + + [Theory] + [InlineData("TO_NEARBY")] + [InlineData("TO_NEARBY", "ALL")] + public void WithBoardConfigurations_Should_ReturnNewQuery_When_ValuesProvided(params string[] configurations) { + var sut = new BoardQuery(); + + var result = sut.WithBoardConfigurations(configurations); + + result.ShouldNotBeSameAs(sut); + result.BoardConfigurations.ShouldBe(configurations); + sut.BoardConfigurations.ShouldBeNull(); + } + + [Theory] + [InlineData("ICE")] + [InlineData("ICE", "IC")] + public void WithTransportTypes_Should_ReturnNewQuery_When_ValuesProvided(params string[] types) { + var sut = new BoardQuery(); + + var result = sut.WithTransportTypes(types); + + result.ShouldNotBeSameAs(sut); + result.TransportTypes.ShouldBe(types); + sut.TransportTypes.ShouldBeEmpty(); + } + + [Theory] + [InlineData("deu")] + [InlineData("deu", "eng")] + public void InLanguages_Should_ReturnNewQuery_When_ValuesProvided(params string[] languages) { + var sut = new BoardQuery(); + + var result = sut.InLanguages(languages); + + result.ShouldNotBeSameAs(sut); + result.Languages.ShouldBe(languages); + sut.Languages.ShouldBe(["deu", "eng"]); + } + + [Theory] + [InlineData("")] + [InlineData("8002549")] + public void ForStada_Should_SetStadaId_When_ValueProvided(string stadaId) { + var sut = new BoardQuery(); + + var result = sut.ForStada(stadaId); + + result.ShouldNotBeSameAs(sut); + result.StadaId.ShouldBe(stadaId); + sut.StadaId.ShouldBeNull(); + } + + [Fact] + public void StartingAt_And_EndingAt_Should_SetTimeWindow_When_ValuesProvided() { + var start = new DateTime(2024, 12, 31, 12, 0, 0); + var end = start.AddHours(2); + var sut = new BoardQuery(); + + var result = sut.StartingAt(start).EndingAt(end); + + result.Start.ShouldBe(start); + result.End.ShouldBe(end); + sut.Start.ShouldBeNull(); + sut.End.ShouldBeNull(); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(100)] + public void ForNext_Should_SetEntryCount_When_ValueProvided(int count) { + var sut = new BoardQuery(); + + var result = sut.ForNext(count); + + result.EntryCount.ShouldBe(count); + sut.EntryCount.ShouldBeNull(); + } + + [Theory] + [InlineData(0)] + [InlineData(25)] + [InlineData(int.MaxValue)] + public void WithMaxEntriesPerTransportType_Should_SetLimit_When_ValueProvided(int max) { + var sut = new BoardQuery(); + + var result = sut.WithMaxEntriesPerTransportType(max); + + result.MaxEntriesPerTransportType.ShouldBe(max); + sut.MaxEntriesPerTransportType.ShouldBe(25); + } + + [Theory] + [InlineData(0)] + [InlineData(3)] + [InlineData(int.MaxValue)] + public void WithMaxViaStops_Should_SetLimit_When_ValueProvided(int max) { + var sut = new BoardQuery(); + + var result = sut.WithMaxViaStops(max); + + result.MaxViaStops.ShouldBe(max); + sut.MaxViaStops.ShouldBeNull(); + } + + [Fact] + public void FlagAndSortMethods_Should_SetValues_When_Called() { + var result = new BoardQuery() + .WithLineColours() + .WithPlatformAccessibility() + .WithoutCancellations() + .WithOnlyReplacementTransports() + .SortByTimeSchedule(); + + result.IncludeLineColours.ShouldBeTrue(); + result.IncludePlatformAccessibility.ShouldBeTrue(); + result.NoCancellations.ShouldBeTrue(); + result.OnlyReplacementTransports.ShouldBeTrue(); + result.SortBy.ShouldBe("TIME_SCHEDULE"); + + result.SortByTime().SortBy.ShouldBe("TIME"); + } +} diff --git a/tests/DotBahn.Tests.Boards/Support/BoardsClientFixture.cs b/tests/DotBahn.Tests.Boards/Support/BoardsClientFixture.cs new file mode 100644 index 0000000..5cb7b13 --- /dev/null +++ b/tests/DotBahn.Tests.Boards/Support/BoardsClientFixture.cs @@ -0,0 +1,33 @@ +using DotBahn.Boards; +using DotBahn.Common.Auth; +using DotBahn.Common.Clients; +using DotBahn.Tests.Shared.Http; +using Microsoft.Extensions.DependencyInjection; + +namespace DotBahn.Tests.Boards.Support; + +internal sealed class BoardsClientFixture : IDisposable { + private readonly ServiceProvider _provider; + + public FakeHttpHandler Handler { get; } = new(); + + public IBoardsClient Client { get; } + + public BoardsClientFixture(IAuthorization? authorization = null, Action? configure = null) { + var services = new ServiceCollection(); + services.AddSingleton(authorization ?? new ApiKeyAuthorization(new AuthorizationOptions { + ClientId = "client", + ApiKey = "key" + })); + services.AddDotBahnBoards(options => { + options.BaseEndpoint = new Uri("https://api.example.com/"); + configure?.Invoke(options); + }); + services.AddHttpClient("DotBahn.Boards").ConfigurePrimaryHttpMessageHandler(() => Handler); + + _provider = services.BuildServiceProvider(); + Client = _provider.GetRequiredService(); + } + + public void Dispose() => _provider.Dispose(); +} diff --git a/tests/DotBahn.Tests.Boards/Transform/ArrivalBoardTransformerTests.cs b/tests/DotBahn.Tests.Boards/Transform/ArrivalBoardTransformerTests.cs new file mode 100644 index 0000000..3a1c2bc --- /dev/null +++ b/tests/DotBahn.Tests.Boards/Transform/ArrivalBoardTransformerTests.cs @@ -0,0 +1,218 @@ +using System.Globalization; +using System.Net; +using DotBahn.Boards; +using DotBahn.Boards.Models; +using DotBahn.Boards.Models.Entries; +using DotBahn.Boards.Models.Messages; +using DotBahn.Tests.Boards.Support; +using Shouldly; + +namespace DotBahn.Tests.Boards.Transform; + +public class ArrivalBoardTransformerTests { + private const string BaseResponse = """ + { + "stopPlaces":[{"evaNumber":"8002549","stada":"8002549","ifopt":"IF","localizedNames":[ + {"language":"eng","name":"English Station","symbol":"ES","symbolName":"Eng Symbol"}, + {"language":"deu","name":"Deutscher Bahnhof","symbol":"DS","symbolName":"Deu Symbol"}]}], + "stations":[{"stada":"8002549","localizedNames":[ + {"language":"eng","name":"English Parent"},{"language":"deu","name":"Deutscher Parent"}]}], + "administrations":[{"administrationId":"A1","operatorCode":"DB","operatorName":"Deutsche Bahn","transportCompanies":[ + {"language":"deu","name":"DB Fernverkehr","shortName":"DBF","website":"https://db.de","email":"a@b.de","phoneNumber":"123","websiteTicketing":"https://t","websiteDigitalAssistant":"https://d"}]}], + "messages":{ + "attributes":[{"messageID":1,"code":"C1","displayPriority":1,"displayPriorityDetail":2,"descriptions":[ + {"language":"eng","text":"Attribute EN"},{"language":"deu","text":"Attribut DE"}]}], + "disruptions":[{"messageID":2,"disruptionID":"D1","disruptionCommunicationID":"DC1","cause":"Bau","effect":"Verspaetung","hasAlternatives":true,"descriptions":[ + {"language":"deu","text":"Stoerung","textShort":"Kurz","links":[{"label":"Link","url":"https://link"}],"attachments":[{"label":"Att","url":"https://att"}],"images":[{"label":"Img","url":"https://img"}]}]}], + "notes":[{"messageID":3,"category":"CAT","code":"N1","displayPriority":3,"descriptions":[{"language":"deu","text":"Notiz"}]}], + "risCauseCodes":[{"messageID":4,"code":"R1","descriptions":[{"language":"deu","text":"Ursache"}]}], + "risQualityDeviations":[{"messageID":5,"code":"Q1","descriptions":[{"language":"deu","text":"Qualitaet"}]}] + }, + "meta":{"consideredStopPlaces":["8002549","missing"],"truncatedTransportTypes":["ICE"]}, + "disruptionCommunications":[2,999], + "arrivals":[ENTRIES] + } + """; + + private const string DefaultEntry = """ + {"arrivalId":"a1","evaNumber":"8002549","journeyId":"j1", + "journeyInfo":{"scheduledStartTime":"2024-12-31T10:00:00+01:00","origin":{"evaNumber":"8002549"},"destination":{"evaNumber":"missing"},"type":"REGULAR","headerAdministrationId":"A1","headerJourneyNumber":42,"transportAtStart":{"administrationId":"A1","category":"ICE","categoryInternal":"ICE","type":"HIGH_SPEED_TRAIN","journeyNumber":123}}, + "timeSchedule":"2024-12-31T12:00:00+01:00","time":"2024-12-31T12:05:00+01:00","timeType":"REAL", + "platformSchedule":{"name":"1"},"platform":{"name":"2"}, + "transport":{"administrationId":"A1","category":"ICE","categoryInternal":"ICE","type":"HIGH_SPEED_TRAIN","journeyNumber":123,"operationalJourneyNumber":"456","journeyDescription":"ICE 123","replacementTransport":{"realType":"BUS"}}, + "messages":[1,2,999],"cancelled":true,"additional":true,"onDemand":true,"noPassengerChange":true,"vehicleSequenceAvailable":true,"pastDisruptions":true, + "codeshares":[{"airlineCode":"LH","flightnumber":1234}]} + """; + + [Fact] + public async Task GetArrivalsAsync_Should_UseGermanLocalization_When_GermanNameExists() { + var board = await GetBoardAsync(DefaultEntry); + + var stopPlace = board.Entries.ShouldHaveSingleItem().StopPlace; + stopPlace.Name.ShouldBe("Deutscher Bahnhof"); + stopPlace.Symbol.ShouldBe("DS"); + stopPlace.SymbolName.ShouldBe("Deu Symbol"); + stopPlace.StationName.ShouldBe("Deutscher Parent"); + board.ConsideredStopPlaces.ShouldHaveSingleItem().Name.ShouldBe("Deutscher Bahnhof"); + board.TruncatedTransportTypes.ShouldBe(["ICE"]); + } + + [Theory] + [InlineData("REAL", true)] + [InlineData("PREVIEW", true)] + [InlineData("OTHER", false)] + [InlineData("null", false)] + public async Task GetArrivalsAsync_Should_SetTimeUpdate_When_TimeTypeOrTimesDiffer(string timeType, bool hasUpdate) { + var attribute = timeType == "null" ? string.Empty : $",\"timeType\":\"{timeType}\""; + var entry = DefaultEntry.Replace("\"timeType\":\"REAL\"", $"\"timeType\":\"{timeType}\"").Replace("\"time\":\"2024-12-31T12:05:00+01:00\"", timeType == "OTHER" || timeType == "null" ? "\"time\":\"2024-12-31T12:00:00+01:00\"" : "\"time\":\"2024-12-31T12:05:00+01:00\""); + if (timeType == "null") { + entry = entry.Replace($",\"timeType\":\"null\"{attribute}", string.Empty).Replace(",\"timeType\":\"null\"", string.Empty); + } + + var board = await GetBoardAsync(entry); + + var time = board.Entries.ShouldHaveSingleItem().Time; + time.Original.ShouldBe(DateTimeOffset.Parse("2024-12-31T12:00:00+01:00", CultureInfo.InvariantCulture).LocalDateTime); + time.HasUpdate.ShouldBe(hasUpdate); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task GetArrivalsAsync_Should_SetPlatformUpdate_When_PlatformNamesDiffer(bool withPlatform) { + var entry = withPlatform ? DefaultEntry : DefaultEntry.Replace(",\"platform\":{\"name\":\"2\"}", string.Empty); + + var board = await GetBoardAsync(entry); + + var platform = board.Entries.ShouldHaveSingleItem().Platform; + platform.Original.Name.ShouldBe("1"); + platform.HasUpdate.ShouldBe(withPlatform); + } + + [Fact] + public async Task GetArrivalsAsync_Should_ResolveMessagesAndResources_When_IdsProvided() { + var board = await GetBoardAsync(DefaultEntry); + + var messages = board.Entries.ShouldHaveSingleItem().Messages; + messages.Select(m => m.Type).ShouldBe([MessageType.Attribute, MessageType.Disruption]); + messages[0].Text.ShouldBe("Attribut DE"); + messages[1].ShortText.ShouldBe("Kurz"); + messages[1].Resources.Select(r => r.Type).ShouldBe([MessageResourceType.Link, MessageResourceType.Attachment, MessageResourceType.Image]); + board.StationMessages.ShouldHaveSingleItem().Text.ShouldBe("Stoerung"); + } + + [Fact] + public async Task GetArrivalsAsync_Should_MapTransportFlagsAndFallbacks_When_EntryIsComplete() { + var board = await GetBoardAsync(DefaultEntry); + + var entry = board.Entries.ShouldHaveSingleItem(); + entry.Cancelled.ShouldBeTrue(); + entry.Additional.ShouldBeTrue(); + entry.OnDemand.ShouldBeTrue(); + entry.NoPassengerChange.ShouldBeTrue(); + entry.VehicleSequenceAvailable.ShouldBeTrue(); + entry.PastDisruptions.ShouldBeTrue(); + entry.Codeshares.ShouldContainKeyAndValue("LH", 1234); + entry.Transport.Number.ShouldBe("123"); + entry.Transport.Administration.OperatorName.ShouldBe("Deutsche Bahn"); + entry.Transport.Administration.TransportCompanies.ShouldHaveSingleItem().ShortName.ShouldBe("DBF"); + entry.Transport.ReplacementTransport.ShouldBe("BUS"); + entry.Journey.HeaderAdministration?.OperatorCode.ShouldBe("DB"); + entry.Journey.HeaderJourneyNumber.ShouldBe(42); + entry.Journey.Destination.StopPlace.Name.ShouldBe("missing"); + } + + [Fact] + public async Task GetArrivalsAsync_Should_UseFallbackAdministration_When_IdIsUnknown() { + var entry = DefaultEntry.Replace("\"administrationId\":\"A1\"", "\"administrationId\":\"unknown\""); + + var board = await GetBoardAsync(entry); + + var administration = board.Entries.ShouldHaveSingleItem().Transport.Administration; + administration.Id.ShouldBe("unknown"); + administration.OperatorCode.ShouldBeEmpty(); + administration.OperatorName.ShouldBeEmpty(); + } + + [Fact] + public async Task GetArrivalsAsync_Should_ReturnEmptyBoard_When_ResponseIsEmpty() { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """{"meta":{}}"""); + + var board = await fixture.Client.GetArrivalsAsync(new BoardQuery(), TestContext.Current.CancellationToken); + + board.Entries.ShouldBeEmpty(); + board.ConsideredStopPlaces.ShouldBeEmpty(); + board.StationMessages.ShouldBeEmpty(); + board.TruncatedTransportTypes.ShouldBeEmpty(); + } + + private const string RichEntry = """ + {"arrivalId":"a1","evaNumber":"8002549","journeyId":"j1", + "journeyInfo":{"scheduledStartTime":"2024-12-31T10:00:00+01:00","origin":{"evaNumber":"8002549","cancelled":true},"destination":{"evaNumber":"8002549"},"differingOrigin":{"evaNumber":"8002549"},"differingDestination":{"evaNumber":"8002549"},"headerAdministrationId":"A1","headerJourneyNumber":1,"journeyCancelled":true,"type":"EXTRA","transportAtStart":{"administrationId":"A1","category":"ICE","categoryInternal":"ICE","type":"HIGH_SPEED_TRAIN","journeyNumber":1}}, + "timeSchedule":"2024-12-31T12:00:00+01:00","time":"2024-12-31T12:00:00+01:00","timeType":"OTHER", + "platformSchedule":{"name":"1","ifopt":"IF","accessibility":{"stepFreeAccess":true,"boardingAid":true,"tactileGuidingStrips":true,"tactileHandrailLabel":true,"tactilePlatformAccess":true,"audibleSignalsAvailable":true,"automaticDoor":true,"passengerInformationDisplay":true,"platformSign":true,"stairsMarking":true,"standardPlatformHeight":true}}, + "platform":{"name":"1","accessibility":{"stepFreeAccess":false}}, + "transport":{"administrationId":"A1","category":"ICE","categoryInternal":"ICE","type":"HIGH_SPEED_TRAIN","journeyNumber":1,"line":{"name":"RE14","colour":{"primaryColour":"#fff","primaryTextColour":"#000","chipVisualization":{"differingBoundaryColour":"#1","differingFillColour":"#2","differingTextColour":"#3","secondaryFillColour":"#4"},"strokeVisualization":{"differingBoundaryColour":"#5","secondaryFillColour":"#6"}}},"direction":{"texts":["A","B"],"stopPlaces":[{"evaNumber":"8002549"}]},"via":[{"evaNumber":"8002549","additional":true,"cancelled":true,"displayPriority":2}],"replacementTransport":{"realType":"BUS"}}, + "messages":[1]} + """; + + [Fact] + public async Task GetArrivalsAsync_Should_MapRichTransportLineAndAccessibility_When_Provided() { + var board = await GetBoardAsync(RichEntry); + + var entry = board.Entries.ShouldHaveSingleItem(); + entry.Journey.IsCancelled.ShouldBeTrue(); + entry.Journey.Type.ShouldBe("EXTRA"); + entry.Journey.DifferingOrigin.ShouldNotBeNull(); + entry.Journey.DifferingDestination.ShouldNotBeNull(); + entry.Journey.Origin.Cancelled.ShouldBeTrue(); + entry.Transport.Line!.Name.ShouldBe("RE14"); + entry.Transport.Line.PrimaryColour.ShouldBe("#fff"); + entry.Transport.Line.ChipDifferingBoundaryColour.ShouldBe("#1"); + entry.Transport.Line.StrokeSecondaryFillColour.ShouldBe("#6"); + entry.Transport.Direction.ShouldBe(["A", "B"]); + entry.Transport.DirectionStopPlaces.ShouldHaveSingleItem().Name.ShouldBe("Deutscher Bahnhof"); + entry.Transport.Via.ShouldHaveSingleItem().Additional.ShouldBeTrue(); + entry.Transport.Via.ShouldHaveSingleItem().DisplayPriority.ShouldBe(2); + entry.Transport.ReplacementTransport.ShouldBe("BUS"); + entry.Platform.Original.Ifopt.ShouldBe("IF"); + entry.Platform.Original.StepFreeAccess.ShouldBeTrue(); + entry.Platform.Original.BoardingAid.ShouldBeTrue(); + entry.Platform.Original.StandardPlatformHeight.ShouldBeTrue(); + entry.Platform.HasUpdate.ShouldBeFalse(); + } + + private const string MinimalEntry = """ + {"arrivalId":"a1","evaNumber":"unknown","journeyId":"j1", + "journeyInfo":{"scheduledStartTime":"2024-12-31T10:00:00+01:00","origin":{"evaNumber":""},"destination":{"evaNumber":""},"headerAdministrationId":"","transportAtStart":{"administrationId":"","category":"ICE","categoryInternal":"ICE","type":"HIGH_SPEED_TRAIN","journeyNumber":1}}, + "timeSchedule":"2024-12-31T12:00:00+01:00","time":"2024-12-31T12:00:00+01:00", + "transport":{"administrationId":"unknown","category":"ICE","categoryInternal":"ICE","type":"HIGH_SPEED_TRAIN","journeyNumber":1}} + """; + + [Fact] + public async Task GetArrivalsAsync_Should_UseDefaults_When_OptionalFieldsAreMissing() { + var board = await GetBoardAsync(MinimalEntry); + + var arrival = board.Entries.ShouldHaveSingleItem(); + arrival.Cancelled.ShouldBeFalse(); + arrival.Additional.ShouldBeFalse(); + arrival.OnDemand.ShouldBeFalse(); + arrival.NoPassengerChange.ShouldBeFalse(); + arrival.VehicleSequenceAvailable.ShouldBeFalse(); + arrival.PastDisruptions.ShouldBeFalse(); + arrival.Messages.ShouldBeEmpty(); + arrival.Codeshares.ShouldBeEmpty(); + arrival.ReliefBy.ShouldBeEmpty(); + arrival.TravelsWith.ShouldBeEmpty(); + arrival.Time.HasUpdate.ShouldBeFalse(); + arrival.Platform.Original.Name.ShouldBeEmpty(); + } + + private static async Task> GetBoardAsync(string entry) { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, BaseResponse.Replace("ENTRIES", entry)); + + return await fixture.Client.GetArrivalsAsync(new BoardQuery(), TestContext.Current.CancellationToken); + } +} diff --git a/tests/DotBahn.Tests.Boards/Transform/DepartureBoardTransformerTests.cs b/tests/DotBahn.Tests.Boards/Transform/DepartureBoardTransformerTests.cs new file mode 100644 index 0000000..96ce7a3 --- /dev/null +++ b/tests/DotBahn.Tests.Boards/Transform/DepartureBoardTransformerTests.cs @@ -0,0 +1,101 @@ +using System.Globalization; +using System.Net; +using DotBahn.Boards; +using DotBahn.Boards.Models; +using DotBahn.Boards.Models.Entries; +using DotBahn.Tests.Boards.Support; +using Shouldly; + +namespace DotBahn.Tests.Boards.Transform; + +public class DepartureBoardTransformerTests { + private const string BaseResponse = """ + { + "stopPlaces":[{"evaNumber":"8002549","localizedNames":[{"language":"deu","name":"Hamburg Hbf"}]}], + "meta":{}, + "departures":[ENTRY] + } + """; + + private const string DefaultEntry = """ + {"departureId":"d1","evaNumber":"8002549","journeyId":"j1", + "journeyInfo":{"scheduledStartTime":"2024-12-31T10:00:00+01:00","origin":{"evaNumber":"8002549"},"destination":{"evaNumber":"8002549"},"headerAdministrationId":"","type":"REGULAR","transportAtStart":{"administrationId":"unknown","category":"ICE","categoryInternal":"ICE","type":"HIGH_SPEED_TRAIN","journeyNumber":123}}, + "timeSchedule":"2024-12-31T12:00:00+01:00","time":"2024-12-31T12:05:00+01:00","timeType":"REAL", + "platformSchedule":{"name":"1"},"platform":{"name":"2"}, + "transport":{"administrationId":"unknown","category":"ICE","categoryInternal":"ICE","type":"HIGH_SPEED_TRAIN","journeyNumber":123}, + "futureDisruptions":true,"cancelled":true} + """; + + [Fact] + public async Task GetDeparturesAsync_Should_MapEntryAndJourney_When_ResponseIsComplete() { + var board = await GetBoardAsync(DefaultEntry); + + var entry = board.Entries.ShouldHaveSingleItem(); + entry.Id.ShouldBe("d1"); + entry.StopPlace.Name.ShouldBe("Hamburg Hbf"); + entry.Journey.Id.ShouldBe("j1"); + entry.Journey.ScheduledStartTime.ShouldBe(DateTimeOffset.Parse("2024-12-31T10:00:00+01:00", CultureInfo.InvariantCulture).LocalDateTime); + entry.Journey.Type.ShouldBe("REGULAR"); + entry.Time.HasUpdate.ShouldBeTrue(); + entry.Platform.HasUpdate.ShouldBeTrue(); + entry.Cancelled.ShouldBeTrue(); + entry.FutureDisruptions.ShouldBeTrue(); + } + + [Fact] + public async Task GetDeparturesAsync_Should_FallbackToEvaName_When_StopPlaceIsUnknown() { + var entry = DefaultEntry.Replace("\"evaNumber\":\"8002549\"", "\"evaNumber\":\"unknown\""); + + var board = await GetBoardAsync(entry); + + board.Entries.ShouldHaveSingleItem().StopPlace.Name.ShouldBe("unknown"); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task GetDeparturesAsync_Should_SetPlatformUpdate_When_NamesDiffer(bool withPlatform) { + var entry = withPlatform ? DefaultEntry : DefaultEntry.Replace(",\"platform\":{\"name\":\"2\"}", string.Empty); + + var board = await GetBoardAsync(entry); + + board.Entries.ShouldHaveSingleItem().Platform.HasUpdate.ShouldBe(withPlatform); + } + + [Fact] + public async Task GetDeparturesAsync_Should_ReturnEmptyBoard_When_ResponseIsEmpty() { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """{"meta":{}}"""); + + var board = await fixture.Client.GetDeparturesAsync(new BoardQuery(), TestContext.Current.CancellationToken); + + board.Entries.ShouldBeEmpty(); + } + + private const string MinimalEntry = """ + {"departureId":"d1","evaNumber":"unknown","journeyId":"j1", + "journeyInfo":{"scheduledStartTime":"2024-12-31T10:00:00+01:00","origin":{"evaNumber":""},"destination":{"evaNumber":""},"headerAdministrationId":"","transportAtStart":{"administrationId":"","category":"ICE","categoryInternal":"ICE","type":"HIGH_SPEED_TRAIN","journeyNumber":1}}, + "timeSchedule":"2024-12-31T12:00:00+01:00","time":"2024-12-31T12:00:00+01:00", + "transport":{"administrationId":"unknown","category":"ICE","categoryInternal":"ICE","type":"HIGH_SPEED_TRAIN","journeyNumber":1}} + """; + + [Fact] + public async Task GetDeparturesAsync_Should_UseDefaults_When_OptionalFieldsAreMissing() { + var board = await GetBoardAsync(MinimalEntry); + + var departure = board.Entries.ShouldHaveSingleItem(); + departure.Cancelled.ShouldBeFalse(); + departure.FutureDisruptions.ShouldBeFalse(); + departure.Time.HasUpdate.ShouldBeFalse(); + departure.Platform.Original.Name.ShouldBeEmpty(); + departure.ContinuationFor.ShouldBeEmpty(); + departure.ReliefBy.ShouldBeEmpty(); + } + + private static async Task> GetBoardAsync(string entry) { + using var fixture = new BoardsClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, BaseResponse.Replace("ENTRY", entry)); + + return await fixture.Client.GetDeparturesAsync(new BoardQuery(), TestContext.Current.CancellationToken); + } +} diff --git a/tests/DotBahn.Tests.Boards/packages.lock.json b/tests/DotBahn.Tests.Boards/packages.lock.json new file mode 100644 index 0000000..715561d --- /dev/null +++ b/tests/DotBahn.Tests.Boards/packages.lock.json @@ -0,0 +1,543 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.Testing.Extensions.CodeCoverage": { + "type": "Direct", + "requested": "[18.12.0, )", + "resolved": "18.12.0", + "contentHash": "BST/sWYpKk9OXO7Yxktcg6FWORRsHU0EdCbMwZ7d3OqJsMKlrNHIZ30g0Ib4k5T5acJYXRBmg9mNrTU/N6cy1g==", + "dependencies": { + "Microsoft.DiaSymReader": "2.2.10", + "Microsoft.Extensions.DependencyModel": "10.0.10", + "Microsoft.Testing.Platform": "2.5.0", + "Mono.Cecil": "0.11.6" + } + }, + "MinVer": { + "type": "Direct", + "requested": "[8.0.0, )", + "resolved": "8.0.0", + "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" + }, + "NSubstitute": { + "type": "Direct", + "requested": "[6.2.0, )", + "resolved": "6.2.0", + "contentHash": "05oaAmBAvYYUQb/NTb9/kWBDjq0iS772X4t428WJcHRcH+5ULJx6rTbEvqkZJBIHWRLI8MlU3et3F5/gkEHKIw==", + "dependencies": { + "Castle.Core": "5.1.1" + } + }, + "Shouldly": { + "type": "Direct", + "requested": "[4.3.0, )", + "resolved": "4.3.0", + "contentHash": "sDetrWXrl6YXZ4HeLsdBoNk3uIa7K+V4uvIJ+cqdRa5DrFxeTED7VkjoxCuU1kJWpUuBDZz2QXFzSxBtVXLwRQ==", + "dependencies": { + "DiffEngine": "11.3.0", + "EmptyFiles": "4.4.0" + } + }, + "xunit.v3": { + "type": "Direct", + "requested": "[4.0.3, )", + "resolved": "4.0.3", + "contentHash": "GxBopTuV5aU7NS0iE1P6I6YCQscIAP0iIyyZqZhs1c8Ry3cdiOouEtQQpX8cA7E1gEnKGRMNA+7NlhBy13AEyg==", + "dependencies": { + "xunit.v3.mtp-v2": "[4.0.3]" + } + }, + "xunit.v3.runner.common": { + "type": "Direct", + "requested": "[4.0.3, )", + "resolved": "4.0.3", + "contentHash": "J/kkhBgJg3wu1xI8gY2Esm3oRE47gNrGmKpT/XZDPOzZ3/F33yTK/ZH1CM6qDpAHoTT3GY/JgrVbS4T1JEKYiQ==", + "dependencies": { + "Microsoft.Win32.Registry": "[5.0.0]", + "System.Security.AccessControl": "[6.0.1]", + "xunit.v3.common": "[4.0.3]" + } + }, + "Castle.Core": { + "type": "Transitive", + "resolved": "5.1.1", + "contentHash": "rpYtIczkzGpf+EkZgDr9CClTdemhsrwA/W5hMoPjLkRFnXzH44zDLoovXeKtmxb1ykXK9aJVODSpiJml8CTw2g==", + "dependencies": { + "System.Diagnostics.EventLog": "6.0.0" + } + }, + "DiffEngine": { + "type": "Transitive", + "resolved": "11.3.0", + "contentHash": "k0ZgZqd09jLZQjR8FyQbSQE86Q7QZnjEzq1LPHtj1R2AoWO8sjV5x+jlSisL7NZAbUOI4y+7Bog8gkr9WIRBGw==", + "dependencies": { + "EmptyFiles": "4.4.0", + "System.Management": "6.0.1" + } + }, + "EmptyFiles": { + "type": "Transitive", + "resolved": "4.4.0", + "contentHash": "gwJEfIGS7FhykvtZoscwXj/XwW+mJY6UbAZk+qtLKFUGWC95kfKXnj8VkxsZQnWBxJemM/q664rGLN5nf+OHZw==" + }, + "Microsoft.ApplicationInsights": { + "type": "Transitive", + "resolved": "2.23.0", + "contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw==" + }, + "Microsoft.Bcl.AsyncInterfaces": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg==" + }, + "Microsoft.DiaSymReader": { + "type": "Transitive", + "resolved": "2.2.10", + "contentHash": "zmGsm6b2y3STDa/Of7rdkkfTDV8VuGB8aCqIkLoJIQh5tL78K3zJ8OUyFKnfsaORXmGr9iOKwDkZfUjeXi+CwA==" + }, + "Microsoft.Extensions.AmbientMetadata.Application": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "tm28s2ODWZ6RdysP06NI3B23DUY5OfHG35ihMHxVAO3hywZAczDVjrkYMfBY//J4HQqfDHS5op84BhnF7ROseQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Compliance.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "DUwdXgIxJKH9zBNg/SUBqOX0FpXCq7w80CIzrr0Jcw5tBXS926AtCcidoAsEHq5e/c6KQ8rWhSt7NxFxak8N/Q==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15" + } + }, + "Microsoft.Extensions.Compliance.Redaction": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "2rwe98yZEn4+aXjAg5DdcROMg6m2w3tejf/mRk4/fBCHKM2EWCaFTmbHLtz1BfyBxMY00/08XFoN0wzWYNiSiQ==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Configuration": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", + "dependencies": { + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" + }, + "Microsoft.Extensions.DependencyInjection.AutoActivation": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "OuVIF5TmsfonN2Fqmi2zlUtbFQNqQiflhgo/rh64ptrqYrB4wZLwKbXr/HzrQXMf+h3jIbWrjIdJFspGqcvuuQ==", + "dependencies": { + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.DependencyModel": { + "type": "Transitive", + "resolved": "10.0.10", + "contentHash": "rfZA1RjR021RPqSmIPovfz2aOd79TGqJ9BengbjnzIISOVwjLmuSDnhCMmiY/1c6iYvGolQ1iNGzkav0u11XEA==" + }, + "Microsoft.Extensions.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mqqpmAFNRLa4cozN3RvT/T81k4aarwMc8xb8VVQgLqUE7AAoN/WWayZAvP+4hy9+KujP3dfn3taU06fZJPIbgA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.FileProviders.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "1RSYAUtJeb76m2T0u5BbvwKY3s+ge9fT3cj1odvo5Bm+frc7pU9RSeXeMIlYHV8GjpqLdv2neeeomz010yYL8A==", + "dependencies": { + "Microsoft.Extensions.Primitives": "10.0.15" + } + }, + "Microsoft.Extensions.Hosting.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "s/JBiwR3F/vKRCbe6WO5b6t6or1ISaZ3rllchcw6/FSWZmK8s2fAzD7elrZo7592FnMD1fhGoG/wuJL1YYtVXw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.Http.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mKHY0oFYL3fkAOhBNi2LqWPuEdUJ+HiF28KKUwBkQG2sgXAUdFDDqvJAfu2PcYgtAwsAtl58zuk4SElpPzbCvA==", + "dependencies": { + "Microsoft.Extensions.Compliance.Redaction": "11.0.1", + "Microsoft.Extensions.Http": "10.0.15", + "Microsoft.Extensions.Telemetry": "11.0.1" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Configuration": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "Km6Ml1/nu0T/f80Btonxf9CWmP/BXI84aJwC5fUbCxRArJ0lH++0ADQrjErZvsSIrKhusTkTSGBChKy2fYAF4w==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Configuration.Binder": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.ObjectPool": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "kvd9eyRRQ+OEu9wik7GKgTS+7XnJ5XoOtSXJqmkJtVYV/S4gsBUrobYRSdNeBcb0ymef4L5Q9pZGiTxJ8jJfyQ==" + }, + "Microsoft.Extensions.Options.ConfigurationExtensions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" + }, + "Microsoft.Extensions.Resilience": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "xgKof6iwAByZNrxWOa7Drk4A953L7U2HleTmx7EXE2Vf6j1crp4RsvNlIVsJMtHKf3ftGKd9gOhR3xES9vxUgg==", + "dependencies": { + "Microsoft.Extensions.Diagnostics": "10.0.15", + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1", + "Polly.Extensions": "8.4.2", + "Polly.RateLimiting": "8.4.2" + } + }, + "Microsoft.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "9uuA8entTC9m00m59h6CACSt4IQh9KknB+hPvCteXUTiG67lqJ8BI65fEUJSPSfT3ZDDi01Zg2aY5kRUvD4HPw==", + "dependencies": { + "Microsoft.Extensions.AmbientMetadata.Application": "11.0.1", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "11.0.1", + "Microsoft.Extensions.Logging.Configuration": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1" + } + }, + "Microsoft.Extensions.Telemetry.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "qINZz4G01Wxumqd0hLr6YdzPa3s7jexQWN28EenaiJQnmKdsR9FnBaKENdRRElLc+A5bJKQ+jYw/WHG4ZpIyAg==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15" + } + }, + "Microsoft.Testing.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "j1XGKCBrmfNm0tmotMa05GlqVtb2cW5UaMkKCFHPyyFHz5rdOy7TD0SVXnZJ+QMrjPAHjRoRqn5qcsUjICSWwg==", + "dependencies": { + "Microsoft.ApplicationInsights": "2.23.0", + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Testing.Extensions.TrxReport.Abstractions": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "+xTIaIU9H44GxOyjrfieMSZnxltGvleA3jCRtdEAzlXKb85pMmVYMLUv2JS8KwD+U2wQHUgvy5YfQfWoPEfVdQ==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Testing.Platform": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "ocX0rgGY78dKfmZlZe4hB0/dvlh7wJgUAWS+KfwrqxB9DpNsjshnne9dppCKnFNEOkX4QYsrdUU++NInFPiCBw==" + }, + "Microsoft.Testing.Platform.MSBuild": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "Jey2v0hd7WHHa7pr6MRNKtA07FvxcOMTCtIhTI7uBZ/qR5m1mgCVCo5L1rtVAtqgMhGA205bUwq9+is4LiCzpw==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Win32.Registry": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg==" + }, + "Mono.Cecil": { + "type": "Transitive", + "resolved": "0.11.6", + "contentHash": "f33RkDtZO8VlGXCtmQIviOtxgnUdym9xx/b1p9h91CRGOsJFxCFOFK1FDbVt1OCf1aWwYejUFa2MOQyFWTFjbA==" + }, + "Polly.Core": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g==" + }, + "Polly.Extensions": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==", + "dependencies": { + "Microsoft.Extensions.Logging.Abstractions": "8.0.0", + "Microsoft.Extensions.Options": "8.0.0", + "Polly.Core": "8.4.2" + } + }, + "Polly.RateLimiting": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==", + "dependencies": { + "Polly.Core": "8.4.2", + "System.Threading.RateLimiting": "8.0.0" + } + }, + "System.CodeDom": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "CPc6tWO1LAer3IzfZufDBRL+UZQcj5uS207NHALQzP84Vp/z6wF0Aa0YZImOQY8iStY0A2zI/e3ihKNPfUm8XA==" + }, + "System.Diagnostics.DiagnosticSource": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" + }, + "System.Diagnostics.EventLog": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "lcyUiXTsETK2ALsZrX+nWuHSIQeazhqPphLfaRxzdGaG93+0kELqpgEHtwWOlQe7+jSFnKwaCAgL4kjeZCQJnw==" + }, + "System.Management": { + "type": "Transitive", + "resolved": "6.0.1", + "contentHash": "10J1D0h/lioojphfJ4Fuh5ZUThT/xOVHdV9roGBittKKNP2PMjrvibEdbVTGZcPra1399Ja3tqIJLyQrc5Wmhg==", + "dependencies": { + "System.CodeDom": "6.0.0" + } + }, + "System.Security.AccessControl": { + "type": "Transitive", + "resolved": "6.0.1", + "contentHash": "IQ4NXP/B3Ayzvw0rDQzVTYsCKyy0Jp9KI6aYcK7UnGVlR9+Awz++TIPCQtPYfLJfOpm8ajowMR09V7quD3sEHw==" + }, + "System.Threading.RateLimiting": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q==" + }, + "xunit.analyzers": { + "type": "Transitive", + "resolved": "2.3.0", + "contentHash": "FcuLqoNBgQA4MmQXOdNWsDnlw+LBysWUcWOql6MCTXXFJZPn+qjbxHA9F9KBRiPH0Y97MLr1VE6LxdH8MgKUoQ==" + }, + "xunit.v3.assert": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "RrlWQ3yXla+ud9JBWDIY9GnUS/DS44r3ObqqV7wdWt1GhS+SveCe0MBDL238VXYoV2mWnX/DhO2LdTq5FTlT7g==" + }, + "xunit.v3.common": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "+2qGz3rcveIxzbXeZVHU8dhMyaawt01mgm/zv1FJH2FPcvJpfTUqc1vQ3hK2V5zVt8QEDddA+B6fkf9/LWf/Pg==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "6.0.0" + } + }, + "xunit.v3.core.mtp-v2": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "CsmxEanMln1chMExl6TUjnH5kF0XUDb/SqWKXqnGD8UjpkZARAXi8JDtsUYdxuROcIIdwEfs3iHZeHmTeA8DUA==", + "dependencies": { + "Microsoft.Testing.Extensions.Telemetry": "2.5.2", + "Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.5.2", + "Microsoft.Testing.Platform": "2.5.2", + "Microsoft.Testing.Platform.MSBuild": "2.5.2", + "xunit.v3.extensibility.core": "[4.0.3]", + "xunit.v3.runner.inproc.console": "[4.0.3]" + } + }, + "xunit.v3.extensibility.core": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "TBYqQKyT+XBDLSHjG6PnmQpooqatflBcWvNiESVS5ptQxWXVf/FGlkUfkNyHKRCUDSCxxHIJNgwO+SRosUmZEw==", + "dependencies": { + "xunit.v3.common": "[4.0.3]" + } + }, + "xunit.v3.mtp-v2": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "lad1hGmodKkfp3AgIwHVVIYeA9GfW125tnkYj7HvOyiwbDH8gpMKPPhzHRC1wc0w4a+0UsOHx2Ero/DtLXvtqA==", + "dependencies": { + "xunit.analyzers": "2.3.0", + "xunit.v3.assert": "[4.0.3]", + "xunit.v3.core.mtp-v2": "[4.0.3]" + } + }, + "xunit.v3.runner.inproc.console": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "lDvNs5exa8rBdWXX/wdapPTp81SNCvUarXC5iXzr1qvO168+Sx/Ytrk9VSLbSD3Y9KNK8PcOjMl1q7JfCoo3LQ==", + "dependencies": { + "xunit.v3.extensibility.core": "[4.0.3]", + "xunit.v3.runner.common": "[4.0.3]" + } + }, + "dotbahn.boards": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )", + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Http.Resilience": "[11.0.1, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.common": { + "type": "Project", + "dependencies": { + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.tests.shared": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )" + } + }, + "Microsoft.Extensions.Http": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Http.Resilience": { + "type": "CentralTransitive", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "5VawCrg+VgVT2hNurSSEWUnq0pvNoH+Zt82s5Wpl/8jdnmU8DpRlr+M3DcdtVgeBG7mRyk3GtSRbf8PB/HrL3w==", + "dependencies": { + "Microsoft.Extensions.Http.Diagnostics": "11.0.1", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Resilience": "11.0.1" + } + }, + "Microsoft.Extensions.Options": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + } + } + } +} \ No newline at end of file diff --git a/tests/DotBahn.Tests.Common/Auth/ApiKeyAuthorizationTests.cs b/tests/DotBahn.Tests.Common/Auth/ApiKeyAuthorizationTests.cs new file mode 100644 index 0000000..c5df5dd --- /dev/null +++ b/tests/DotBahn.Tests.Common/Auth/ApiKeyAuthorizationTests.cs @@ -0,0 +1,73 @@ +using DotBahn.Common.Auth; +using Shouldly; + +namespace DotBahn.Tests.Common.Auth; + +public class ApiKeyAuthorizationTests { + [Theory] + [InlineData("client-1", "key-1")] + [InlineData("another-client", "another-key")] + public void AuthorizeRequest_Should_SetDbClientIdHeader_When_Called(string clientId, string apiKey) { + var options = new AuthorizationOptions { + ClientId = clientId, + ApiKey = apiKey + }; + var sut = new ApiKeyAuthorization(options); + var request = new HttpRequestMessage(); + + sut.AuthorizeRequest(request); + + request.Headers.ShouldContain(h => h.Key == "DB-Client-Id"); + request.Headers.GetValues("DB-Client-Id").Single().ShouldBe(clientId); + } + + [Theory] + [InlineData("client-1", "key-1")] + [InlineData("another-client", "another-key")] + public void AuthorizeRequest_Should_SetDbApiKeyHeader_When_Called(string clientId, string apiKey) { + var options = new AuthorizationOptions { + ClientId = clientId, + ApiKey = apiKey + }; + var sut = new ApiKeyAuthorization(options); + var request = new HttpRequestMessage(); + + sut.AuthorizeRequest(request); + + request.Headers.ShouldContain(h => h.Key == "DB-Api-Key"); + request.Headers.GetValues("DB-Api-Key").Single().ShouldBe(apiKey); + } + + [Fact] + public void AuthorizeRequest_Should_ThrowArgumentNullException_When_RequestIsNull() { + var options = new AuthorizationOptions { + ClientId = "client", + ApiKey = "key" + }; + var sut = new ApiKeyAuthorization(options); + + var exception = Should.Throw(() => sut.AuthorizeRequest(null!)); + + exception.ParamName.ShouldBe("request"); + } + + [Theory] + [InlineData("client-123", "secret-key")] + [InlineData("", "")] + [InlineData(" ", " ")] + public void AuthorizeRequest_Should_SetBothHeaders_When_Called(string clientId, string apiKey) { + var options = new AuthorizationOptions { + ClientId = clientId, + ApiKey = apiKey + }; + var sut = new ApiKeyAuthorization(options); + var request = new HttpRequestMessage(); + + sut.AuthorizeRequest(request); + + request.Headers.ShouldContain(h => h.Key == "DB-Client-Id"); + request.Headers.ShouldContain(h => h.Key == "DB-Api-Key"); + request.Headers.GetValues("DB-Client-Id").Single().ShouldBe(clientId); + request.Headers.GetValues("DB-Api-Key").Single().ShouldBe(apiKey); + } +} diff --git a/tests/DotBahn.Tests.Common/Auth/AuthorizationOptionsTests.cs b/tests/DotBahn.Tests.Common/Auth/AuthorizationOptionsTests.cs new file mode 100644 index 0000000..40492f1 --- /dev/null +++ b/tests/DotBahn.Tests.Common/Auth/AuthorizationOptionsTests.cs @@ -0,0 +1,37 @@ +using DotBahn.Common.Auth; +using Shouldly; + +namespace DotBahn.Tests.Common.Auth; + +public class AuthorizationOptionsTests { + [Theory] + [InlineData("client", "key", "ClientId: set, ApiKey: set")] + [InlineData(" ", "key", "ClientId: not set, ApiKey: set")] + [InlineData("client", "\t", "ClientId: set, ApiKey: not set")] + [InlineData("", "", "ClientId: not set, ApiKey: not set")] + [InlineData(" ", " ", "ClientId: not set, ApiKey: not set")] + [InlineData("client", "", "ClientId: set, ApiKey: not set")] + [InlineData("", "key", "ClientId: not set, ApiKey: set")] + public void ToString_Should_ReflectWhichFieldsAreSet_When_ValuesAreProvided(string clientId, string apiKey, string expected) { + var sut = new AuthorizationOptions { + ClientId = clientId, + ApiKey = apiKey + }; + + var result = sut.ToString(); + + result.ShouldBe(expected); + } + + [Fact] + public void ToString_Should_IndicateBothSet_When_ValuesAreNonWhitespace() { + var sut = new AuthorizationOptions { + ClientId = "my-client", + ApiKey = "my-api-key" + }; + + var result = sut.ToString(); + + result.ShouldBe("ClientId: set, ApiKey: set"); + } +} diff --git a/tests/DotBahn.Tests.Common/Clients/ClientBaseTests.cs b/tests/DotBahn.Tests.Common/Clients/ClientBaseTests.cs new file mode 100644 index 0000000..b92c826 --- /dev/null +++ b/tests/DotBahn.Tests.Common/Clients/ClientBaseTests.cs @@ -0,0 +1,305 @@ +using System.Net; +using System.Text.Json.Serialization.Metadata; +using DotBahn.Common.Auth; +using DotBahn.Common.Clients; +using DotBahn.Common.Parsing; +using DotBahn.Common.Utilities; +using DotBahn.Tests.Shared; +using DotBahn.Tests.Shared.Contracts; +using DotBahn.Tests.Shared.Http; +using NSubstitute; +using Shouldly; + +namespace DotBahn.Tests.Common.Clients; + +public class ClientBaseTests { + private static JsonTypeInfo SimpleTypeInfo => (JsonTypeInfo)TestsJsonContext.Default.GetTypeInfo(typeof(SimpleDto))!; + private static JsonTypeInfo PostRequestTypeInfo => (JsonTypeInfo)TestsJsonContext.Default.GetTypeInfo(typeof(PostRequestDto))!; + private static JsonTypeInfo NullTypeInfo => (JsonTypeInfo)TestsJsonContext.Default.GetTypeInfo(typeof(AlwaysNullDto))!; + + [Fact] + public void Constructor_Should_ThrowArgumentNullException_When_HttpClientIsNull() { + var authorization = Substitute.For(); + + var exception = Should.Throw(() => new TestClientBase(null!, authorization)); + + exception.ParamName.ShouldBe("http"); + } + + [Fact] + public void Constructor_Should_ThrowArgumentNullException_When_AuthorizationIsNull() { + using var client = new HttpClient(); + + var exception = Should.Throw(() => new TestClientBase(client, null!)); + + exception.ParamName.ShouldBe("authorization"); + } + + [Fact] + public void Constructor_Should_ThrowArgumentNullException_When_OptionsIsNull() { + var auth = new AuthorizationOptions { + ClientId = "id", + ApiKey = "key" + }; + + var exception = Should.Throw(() => new TestClientBase(null!, auth)); + + exception.ParamName.ShouldBe("options"); + } + + [Fact] + public void Constructor_Should_ThrowArgumentNullException_When_AuthorizationOptionsIsNull() { + var options = new ClientOptions { + BaseEndpoint = new Uri("https://api.example.com/") + }; + + var exception = Should.Throw(() => new TestClientBase(options, null!)); + + exception.ParamName.ShouldBe("auth"); + } + + [Fact] + public void Constructor_Should_SetBaseAddressAndUserAgent_When_UsingOptionsOverload() { + var options = new ClientOptions { + BaseEndpoint = new Uri("https://api.example.com/") + }; + var auth = new AuthorizationOptions { + ClientId = "id", + ApiKey = "key" + }; + var sut = new TestClientBase(options, auth); + + sut.SharedClient.BaseAddress.ShouldBe(new Uri("https://api.example.com/")); + sut.SharedClient.DefaultRequestHeaders.UserAgent.ShouldContain(h => h.Product!.Name.Contains("DotBahn")); + } + + [Fact] + public async Task GetAsync_Should_ThrowArgumentNullException_When_ParserIsNull() { + using var client = CreateHttpClient(out _); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + + var exception = await Should.ThrowAsync(() => sut.GetAsyncWrapper("path", null!, "application/json")); + + exception.ParamName.ShouldBe("parser"); + } + + [Fact] + public async Task GetAsync_Should_AppendQueryParameters_When_Provided() { + using var client = CreateHttpClient(out var handler); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + handler.RespondWith(HttpStatusCode.OK, "{}"); + var parser = Substitute.For>(); + parser.Parse(Arg.Any()).Returns("ok"); + + await sut.GetAsyncWrapper("path", parser, "application/json", QueryParameters.Create().Add("a", "1"), TestContext.Current.CancellationToken); + + handler.SentRequests.ShouldHaveSingleItem(); + handler.SentRequests[0].RequestUri!.ToString().ShouldContain("?a=1"); + } + + [Fact] + public async Task GetAsync_Should_NotAppendQuery_When_QueryParametersAreEmpty() { + using var client = CreateHttpClient(out var handler); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + handler.RespondWith(HttpStatusCode.OK, "{}"); + var parser = Substitute.For>(); + parser.Parse(Arg.Any()).Returns("ok"); + + await sut.GetAsyncWrapper("path", parser, "application/json", QueryParameters.Create().Add("a", null), TestContext.Current.CancellationToken); + + handler.SentRequests[0].RequestUri!.ToString().ShouldNotContain("?"); + } + + [Fact] + public async Task GetAsync_Should_ReturnParsedResponse_When_Success() { + using var client = CreateHttpClient(out var handler); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + handler.RespondWith(HttpStatusCode.OK, "{\"Name\":\"ok\",\"Value\":1}"); + var parser = new JsonParser(SimpleTypeInfo); + + var result = await sut.GetAsyncWrapper("path", parser, "application/json", ct: TestContext.Current.CancellationToken); + + result.Name.ShouldBe("ok"); + result.Value.ShouldBe(1); + } + + [Fact] + public async Task GetAsync_Should_ReturnDefaultContract_When_NotFound() { + using var client = CreateHttpClient(out var handler); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + handler.RespondWith(HttpStatusCode.NotFound, "not found"); + var parser = new JsonParser(SimpleTypeInfo); + + var result = await sut.GetAsyncWrapper("path", parser, "application/json", ct: TestContext.Current.CancellationToken); + + result.ShouldNotBeNull(); + result.Name.ShouldBeNull(); + } + + [Theory] + [InlineData(HttpStatusCode.BadRequest, 0, false)] + [InlineData(HttpStatusCode.Unauthorized, 3, false)] + [InlineData(HttpStatusCode.InternalServerError, 250, true)] + [InlineData(HttpStatusCode.BadGateway, 200, false)] + public async Task GetAsync_Should_ThrowHttpRequestException_When_ApiReturnsError(HttpStatusCode statusCode, int bodyLength, bool truncated) { + using var client = CreateHttpClient(out var handler); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + var body = new string('x', bodyLength); + handler.RespondWith(statusCode, body); + + var exception = await Should.ThrowAsync(() => sut.GetAsyncWrapper("path", Substitute.For>(), "application/json")); + + exception.StatusCode.ShouldBe(statusCode); + var reasonPhrase = new HttpResponseMessage(statusCode).ReasonPhrase; + var expectedBody = truncated ? new string('x', 200) + "..." : body; + exception.Message.ShouldBe($"The API responded with {(int)statusCode} ({reasonPhrase}): {expectedBody}"); + handler.SentRequestBodies.ShouldHaveSingleItem().ShouldBeEmpty(); + } + + [Fact] + public async Task GetAsync_Should_CallAuthorization_ForOutgoingRequest() { + using var client = CreateHttpClient(out var handler); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + handler.RespondWith(HttpStatusCode.OK, "{}"); + var parser = Substitute.For>(); + parser.Parse(Arg.Any()).Returns("ok"); + + await sut.GetAsyncWrapper("path", parser, "application/json", ct: TestContext.Current.CancellationToken); + + authorization.Received(1).AuthorizeRequest(Arg.Any()); + } + + [Fact] + public async Task GetAsync_Should_SetAcceptHeader() { + using var client = CreateHttpClient(out var handler); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + handler.RespondWith(HttpStatusCode.OK, "{}"); + var parser = Substitute.For>(); + parser.Parse(Arg.Any()).Returns("ok"); + + await sut.GetAsyncWrapper("path", parser, "application/json", ct: TestContext.Current.CancellationToken); + + handler.SentRequests[0].Headers.Accept.ShouldContain(h => h.MediaType == "application/json"); + } + + [Fact] + public async Task GetAsync_Should_ThrowOperationCanceledException_When_Canceled() { + using var client = CreateHttpClient(out _); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + using var cts = new CancellationTokenSource(); + await cts.CancelAsync(); + + await Should.ThrowAsync(() => sut.GetAsyncWrapper("path", Substitute.For>(), "application/json", ct: cts.Token)); + } + + [Fact] + public async Task PostAsync_Should_ThrowArgumentNullException_When_ParserIsNull() { + using var client = CreateHttpClient(out _); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + + var exception = await Should.ThrowAsync(() => sut.PostAsyncWrapper("path", new PostRequestDto(), PostRequestTypeInfo, null!, "application/json")); + + exception.ParamName.ShouldBe("parser"); + } + + [Fact] + public async Task PostAsync_Should_ThrowArgumentNullException_When_RequestTypeIsNull() { + using var client = CreateHttpClient(out _); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + JsonTypeInfo? requestType = null; + + var exception = await Should.ThrowAsync(() => sut.PostAsyncWrapper("path", new PostRequestDto(), requestType!, Substitute.For>(), "application/json")); + + exception.ParamName.ShouldBe("requestType"); + } + + [Fact] + public async Task PostAsync_Should_ReturnParsedResponse_When_Success() { + using var client = CreateHttpClient(out var handler); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + handler.RespondWith(HttpStatusCode.OK, "{\"Name\":\"post\",\"Value\":2}"); + var parser = new JsonParser(SimpleTypeInfo); + + var result = await sut.PostAsyncWrapper("path", new PostRequestDto { Name = "request", Count = 5 }, PostRequestTypeInfo, parser, "application/json", TestContext.Current.CancellationToken); + + result.Name.ShouldBe("post"); + } + + [Fact] + public async Task PostAsync_Should_SendJsonContent_WithCorrectMediaType() { + using var client = CreateHttpClient(out var handler); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + handler.RespondWith(HttpStatusCode.OK, "{}"); + var parser = Substitute.For>(); + parser.Parse(Arg.Any()).Returns("ok"); + + await sut.PostAsyncWrapper("path", new PostRequestDto { Name = "request", Count = 5 }, PostRequestTypeInfo, parser, "application/json", TestContext.Current.CancellationToken); + + handler.SentRequestContentTypes[0].ShouldBe("application/json"); + var body = handler.SentRequestBodies[0]; + body.ShouldContain("\"Name\":\"request\""); + body.ShouldContain("\"Count\":5"); + } + + [Fact] + public async Task PostAsync_Should_CallAuthorization_ForOutgoingRequest() { + using var client = CreateHttpClient(out var handler); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + handler.RespondWith(HttpStatusCode.OK, "{}"); + var parser = Substitute.For>(); + parser.Parse(Arg.Any()).Returns("ok"); + + await sut.PostAsyncWrapper("path", new PostRequestDto(), PostRequestTypeInfo, parser, "application/json", TestContext.Current.CancellationToken); + + authorization.Received(1).AuthorizeRequest(Arg.Any()); + } + + [Fact] + public async Task PostAsync_Should_ThrowHttpRequestException_When_ApiReturnsError() { + using var client = CreateHttpClient(out var handler); + var authorization = Substitute.For(); + var sut = new TestClientBase(client, authorization); + handler.RespondWith(HttpStatusCode.BadRequest, "invalid"); + + var exception = await Should.ThrowAsync(() => sut.PostAsyncWrapper("path", new PostRequestDto(), PostRequestTypeInfo, Substitute.For>(), "application/json")); + + exception.StatusCode.ShouldBe(HttpStatusCode.BadRequest); + } + + private static HttpClient CreateHttpClient(out FakeHttpHandler handler) { + handler = new FakeHttpHandler(); + return new HttpClient(handler, disposeHandler: false) { + BaseAddress = new Uri("https://api.example.com/") + }; + } + + private sealed class TestClientBase : ClientBase { + public TestClientBase(HttpClient http, IAuthorization authorization) : base(http, authorization) { } + + public TestClientBase(ClientOptions options, AuthorizationOptions auth) : base(options, auth) { } + + protected override string ApiName => "test"; + + public HttpClient SharedClient => HttpClient; + + public Task GetAsyncWrapper(string relative, IParser parser, string acceptHeader, QueryParameters? queryParams = null, CancellationToken ct = default) + => GetAsync(relative, parser, acceptHeader, queryParams, ct); + + public Task PostAsyncWrapper(string relative, TRequest request, JsonTypeInfo requestType, IParser parser, string acceptHeader, CancellationToken ct = default) + => PostAsync(relative, request, requestType, parser, acceptHeader, ct); + } +} diff --git a/tests/DotBahn.Tests.Common/Clients/ClientOptionsTests.cs b/tests/DotBahn.Tests.Common/Clients/ClientOptionsTests.cs new file mode 100644 index 0000000..52da4fa --- /dev/null +++ b/tests/DotBahn.Tests.Common/Clients/ClientOptionsTests.cs @@ -0,0 +1,16 @@ +using DotBahn.Common.Clients; +using Shouldly; + +namespace DotBahn.Tests.Common.Clients; + +public class ClientOptionsTests { + [Fact] + public void BaseEndpoint_Should_Be_Settable_And_Gettable_When_Initialized() { + var expected = new Uri("https://example.com/"); + var sut = new ClientOptions { + BaseEndpoint = expected + }; + + sut.BaseEndpoint.ShouldBe(expected); + } +} diff --git a/tests/DotBahn.Common.Tests/DotBahn.Common.Tests.csproj b/tests/DotBahn.Tests.Common/DotBahn.Tests.Common.csproj similarity index 72% rename from tests/DotBahn.Common.Tests/DotBahn.Common.Tests.csproj rename to tests/DotBahn.Tests.Common/DotBahn.Tests.Common.csproj index 650d5d2..8ff2ce4 100644 --- a/tests/DotBahn.Common.Tests/DotBahn.Common.Tests.csproj +++ b/tests/DotBahn.Tests.Common/DotBahn.Tests.Common.csproj @@ -1,15 +1,17 @@ - + - + + + diff --git a/tests/DotBahn.Tests.Common/Models/ChangedRefTests.cs b/tests/DotBahn.Tests.Common/Models/ChangedRefTests.cs new file mode 100644 index 0000000..fc8eebd --- /dev/null +++ b/tests/DotBahn.Tests.Common/Models/ChangedRefTests.cs @@ -0,0 +1,68 @@ +using DotBahn.Common.Models; +using Shouldly; + +namespace DotBahn.Tests.Common.Models; + +public class ChangedRefTests { + [Fact] + public void Actual_Should_ReturnOriginal_When_UpdatedIsNull() { + var sut = new ChangedRef { + Original = "original" + }; + + sut.Actual.ShouldBe("original"); + } + + [Fact] + public void Actual_Should_ReturnUpdated_When_UpdatedIsSet() { + var sut = new ChangedRef { + Original = "original", + Updated = "updated" + }; + + sut.Actual.ShouldBe("updated"); + } + + [Fact] + public void HasUpdate_Should_BeFalse_When_UpdatedIsNull() { + var sut = new ChangedRef { + Original = "original" + }; + + sut.HasUpdate.ShouldBeFalse(); + } + + [Fact] + public void HasUpdate_Should_BeTrue_When_UpdatedIsSet() { + var sut = new ChangedRef { + Original = "original", + Updated = "updated" + }; + + sut.HasUpdate.ShouldBeTrue(); + } + + [Fact] + public void HasUpdate_Should_BeTrue_When_UpdatedIsEmptyString() { + var sut = new ChangedRef { + Original = "original", + Updated = string.Empty + }; + + sut.HasUpdate.ShouldBeTrue(); + sut.Actual.ShouldBeEmpty(); + } + + [Fact] + public void Actual_Should_ReturnUpdated_When_UpdatedIsReferenceTypeInstance() { + var originalList = new List { 1, 2 }; + var updatedList = new List { 3, 4 }; + var sut = new ChangedRef> { + Original = originalList, + Updated = updatedList + }; + + sut.Actual.ShouldBe(updatedList); + sut.HasUpdate.ShouldBeTrue(); + } +} diff --git a/tests/DotBahn.Tests.Common/Models/ChangedValueTests.cs b/tests/DotBahn.Tests.Common/Models/ChangedValueTests.cs new file mode 100644 index 0000000..26de732 --- /dev/null +++ b/tests/DotBahn.Tests.Common/Models/ChangedValueTests.cs @@ -0,0 +1,89 @@ +using DotBahn.Common.Models; +using Shouldly; + +namespace DotBahn.Tests.Common.Models; + +public class ChangedValueTests { + [Fact] + public void Actual_Should_ReturnOriginal_When_UpdatedIsNull() { + var sut = new ChangedValue { + Original = 42 + }; + + sut.Actual.ShouldBe(42); + } + + [Fact] + public void Actual_Should_ReturnUpdated_When_UpdatedIsSet() { + var sut = new ChangedValue { + Original = 42, + Updated = 99 + }; + + sut.Actual.ShouldBe(99); + } + + [Fact] + public void HasUpdate_Should_BeFalse_When_UpdatedIsNull() { + var sut = new ChangedValue { + Original = 42 + }; + + sut.HasUpdate.ShouldBeFalse(); + } + + [Fact] + public void HasUpdate_Should_BeTrue_When_UpdatedIsSet() { + var sut = new ChangedValue { + Original = 42, + Updated = 99 + }; + + sut.HasUpdate.ShouldBeTrue(); + } + + [Fact] + public void HasUpdate_Should_BeTrue_When_UpdatedIsZero() { + var sut = new ChangedValue { + Original = 42, + Updated = 0 + }; + + sut.HasUpdate.ShouldBeTrue(); + sut.Actual.ShouldBe(0); + } + + [Fact] + public void Actual_Should_ReturnOriginal_When_UpdatedIsNullForNullableValue() { + var sut = new ChangedValue { + Original = new DateTime(2024, 1, 1) + }; + + sut.Actual.ShouldBe(new DateTime(2024, 1, 1)); + sut.HasUpdate.ShouldBeFalse(); + } + + [Fact] + public void Actual_Should_ReturnUpdated_When_UpdatedIsSetForNullableValue() { + var sut = new ChangedValue { + Original = new DateTime(2024, 1, 1), + Updated = new DateTime(2024, 12, 31) + }; + + sut.Actual.ShouldBe(new DateTime(2024, 12, 31)); + sut.HasUpdate.ShouldBeTrue(); + } + + [Theory] + [InlineData(0, 1, 1)] + [InlineData(-10, -5, -5)] + [InlineData(int.MaxValue, int.MinValue, int.MinValue)] + public void Actual_Should_ReturnUpdated_ForBoundaryValues(int original, int updated, int expected) { + var sut = new ChangedValue { + Original = original, + Updated = updated + }; + + sut.Actual.ShouldBe(expected); + } +} diff --git a/tests/DotBahn.Tests.Common/Parsing/BahnDialectJsonConverterTests.cs b/tests/DotBahn.Tests.Common/Parsing/BahnDialectJsonConverterTests.cs new file mode 100644 index 0000000..ea9a882 --- /dev/null +++ b/tests/DotBahn.Tests.Common/Parsing/BahnDialectJsonConverterTests.cs @@ -0,0 +1,47 @@ +using System.Text.Json; +using DotBahn.Common.Parsing.Converters; +using Shouldly; + +namespace DotBahn.Tests.Common.Parsing; + +public class BahnDialectJsonConverterTests { + private readonly JsonSerializerOptions _options = new() { + Converters = { + new BahnDialectJsonConverter() + } + }; + + [Theory] + [InlineData("true", true)] + [InlineData("false", false)] + [InlineData("\"TRUE\"", true)] + [InlineData("\"FALSE\"", false)] + [InlineData("\"YES\"", true)] + [InlineData("\"NO\"", false)] + [InlineData("\"JA\"", true)] + [InlineData("\"1\"", true)] + [InlineData("\"yes\"", true)] + [InlineData("\"no\"", false)] + [InlineData("\"maybe\"", false)] + [InlineData("\" TRUE \"", true)] + public void Read_Should_Parse_Dialect_Boolean_When_Input_Is_Valid(string json, bool expected) { + var result = JsonSerializer.Deserialize(json, _options); + + result.ShouldBe(expected); + } + + [Fact] + public void Read_Should_Throw_JsonException_When_Token_Is_Number() { + Should.Throw(() => JsonSerializer.Deserialize("42", _options)); + } + + [Fact] + public void Write_Should_Serialize_True_As_Boolean_Token_When_Value_Is_True() { + JsonSerializer.Serialize(true, _options).ShouldBe("true"); + } + + [Fact] + public void Write_Should_Serialize_False_As_Boolean_Token_When_Value_Is_False() { + JsonSerializer.Serialize(false, _options).ShouldBe("false"); + } +} diff --git a/tests/DotBahn.Tests.Common/Parsing/JsonParserTests.cs b/tests/DotBahn.Tests.Common/Parsing/JsonParserTests.cs new file mode 100644 index 0000000..d338ffb --- /dev/null +++ b/tests/DotBahn.Tests.Common/Parsing/JsonParserTests.cs @@ -0,0 +1,74 @@ +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; +using DotBahn.Common.Parsing; +using DotBahn.Tests.Shared; +using DotBahn.Tests.Shared.Contracts; +using Shouldly; + +namespace DotBahn.Tests.Common.Parsing; + +public class JsonParserTests { + private static JsonTypeInfo SimpleTypeInfo => (JsonTypeInfo)TestsJsonContext.Default.GetTypeInfo(typeof(SimpleDto))!; + private static JsonTypeInfo NullTypeInfo => (JsonTypeInfo)TestsJsonContext.Default.GetTypeInfo(typeof(AlwaysNullDto))!; + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void Parse_Should_Return_Default_Instance_When_Input_Is_Empty_Or_Whitespace(string input) { + var sut = new JsonParser(SimpleTypeInfo); + + var result = sut.Parse(input); + + result.ShouldNotBeNull(); + result.Name.ShouldBeNull(); + result.Value.ShouldBe(0); + } + + [Fact] + public void Parse_Should_Return_Default_Instance_When_Input_Is_Null() { + var sut = new JsonParser(SimpleTypeInfo); + + var result = sut.Parse(null!); + + result.ShouldNotBeNull(); + result.Name.ShouldBeNull(); + result.Value.ShouldBe(0); + } + + [Fact] + public void Parse_Should_Return_Populated_Contract_When_Input_Is_Valid_Json() { + var sut = new JsonParser(SimpleTypeInfo); + const string json = """{"Name":"test","Value":42}"""; + + var result = sut.Parse(json); + + result.Name.ShouldBe("test"); + result.Value.ShouldBe(42); + } + + [Theory] + [InlineData("{invalid", false)] + [InlineData("not json", false)] + [InlineData("null, extra", false)] + [InlineData("null", true)] + public void Parse_Should_Throw_JsonException_When_Input_Is_Invalid_Json(string input, bool deserializesToNull) { + var sut = new JsonParser(SimpleTypeInfo); + + var act = () => sut.Parse(input); + + var exception = Should.Throw(() => act()); + if (deserializesToNull) { + exception.Message.ShouldContain("Deserialization of API response returned null"); + } + } + + [Fact] + public void Parse_Should_Throw_JsonException_When_Deserialization_Returns_Null() { + var sut = new JsonParser(NullTypeInfo); + const string json = "{}"; + + var act = () => sut.Parse(json); + + act.ShouldThrow(); + } +} diff --git a/tests/DotBahn.Tests.Common/Utilities/EnumUtilTests.cs b/tests/DotBahn.Tests.Common/Utilities/EnumUtilTests.cs new file mode 100644 index 0000000..4848c96 --- /dev/null +++ b/tests/DotBahn.Tests.Common/Utilities/EnumUtilTests.cs @@ -0,0 +1,58 @@ +using System.Text.Json.Serialization.Metadata; +using DotBahn.Common.Utilities; +using DotBahn.Tests.Shared; +using DotBahn.Tests.Shared.Contracts; +using Shouldly; + +namespace DotBahn.Tests.Common.Utilities; + +public class EnumUtilTests { + private static JsonTypeInfo TypeInfo => (JsonTypeInfo)TestsJsonContext.Default.GetTypeInfo(typeof(TestEnum))!; + + [Theory] + [InlineData(null)] + [InlineData("")] + public void Parse_Should_Return_Default_Value_When_Value_Is_Null_Or_Empty(string? value) { + var result = EnumUtil.Parse(value!, TestEnum.Unknown, TypeInfo); + + result.ShouldBe(TestEnum.Unknown); + } + + [Fact] + public void Parse_Should_Return_Enum_Value_When_Value_Is_Valid_Name() { + var result = EnumUtil.Parse("Active", TestEnum.Unknown, TypeInfo); + + result.ShouldBe(TestEnum.Active); + } + + [Fact] + public void Parse_Should_Return_Default_Value_When_Value_Is_Invalid_Name() { + var result = EnumUtil.Parse("NonExistent", TestEnum.Unknown, TypeInfo); + + result.ShouldBe(TestEnum.Unknown); + } + + [Fact] + public void Parse_Should_Be_Case_Insensitive_When_Value_Has_Different_Casing() { + var result = EnumUtil.Parse("active", TestEnum.Unknown, TypeInfo); + + result.ShouldBe(TestEnum.Active); + } + + [Fact] + public void Format_Should_Return_Null_When_Value_Is_Null() { + var result = EnumUtil.Format(null, TypeInfo); + + result.ShouldBeNull(); + } + + [Theory] + [InlineData(TestEnum.Active, "Active")] + [InlineData(TestEnum.Inactive, "Inactive")] + [InlineData(TestEnum.Unknown, "Unknown")] + public void Format_Should_Return_String_Name_When_Value_Is_Provided(TestEnum value, string expected) { + var result = EnumUtil.Format(value, TypeInfo); + + result.ShouldBe(expected); + } +} diff --git a/tests/DotBahn.Tests.Common/Utilities/QueryParametersTests.cs b/tests/DotBahn.Tests.Common/Utilities/QueryParametersTests.cs new file mode 100644 index 0000000..8dbb275 --- /dev/null +++ b/tests/DotBahn.Tests.Common/Utilities/QueryParametersTests.cs @@ -0,0 +1,74 @@ +using DotBahn.Common.Utilities; +using Shouldly; + +namespace DotBahn.Tests.Common.Utilities; + +public class QueryParametersTests { + [Fact] + public void Create_Should_Return_Empty_Instance_When_Called() { + var sut = QueryParameters.Create(); + + sut.Any().ShouldBeFalse(); + sut.ToQueryString().ShouldBeEmpty(); + } + + [Fact] + public void Add_Should_Store_Value_When_Value_Is_NonWhitespace() { + var sut = QueryParameters.Create().Add("key", "value"); + + sut.Any().ShouldBeTrue(); + sut.ToQueryString().ShouldBe("key=value"); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void Add_Should_Ignore_Value_When_Value_Is_Null_Or_Whitespace(string? value) { + var sut = QueryParameters.Create().Add("key", value); + + sut.Any().ShouldBeFalse(); + } + + [Fact] + public void Add_Should_Overwrite_Existing_Key_When_Duplicate_Added() { + var sut = QueryParameters.Create().Add("key", "first").Add("key", "second"); + + sut.ToQueryString().ShouldBe("key=second"); + } + + [Fact] + public void Add_Collection_Should_Join_Values_With_Comma_When_Values_Provided() { + var sut = QueryParameters.Create().Add("ids", [1, 2, 3]); + + sut.ToQueryString().ShouldBe("ids=1%2C2%2C3"); + } + + [Fact] + public void Add_Collection_Should_Ignore_When_Values_Are_Null() { + var sut = QueryParameters.Create().Add("ids", null); + + sut.Any().ShouldBeFalse(); + } + + [Fact] + public void Add_Collection_Should_Ignore_When_Values_Are_Empty() { + var sut = QueryParameters.Create().Add("ids", Array.Empty()); + + sut.Any().ShouldBeFalse(); + } + + [Fact] + public void ToQueryString_Should_UrlEncode_Keys_And_Values() { + var sut = QueryParameters.Create().Add("key name", "value&=?"); + + sut.ToQueryString().ShouldBe("key%20name=value%26%3D%3F"); + } + + [Fact] + public void Add_Should_Return_Same_Instance_For_Fluent_Chaining() { + var sut = QueryParameters.Create(); + + sut.Add("a", "1").ShouldBeSameAs(sut); + } +} diff --git a/tests/DotBahn.Tests.Common/packages.lock.json b/tests/DotBahn.Tests.Common/packages.lock.json new file mode 100644 index 0000000..d77c19e --- /dev/null +++ b/tests/DotBahn.Tests.Common/packages.lock.json @@ -0,0 +1,364 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.Testing.Extensions.CodeCoverage": { + "type": "Direct", + "requested": "[18.12.0, )", + "resolved": "18.12.0", + "contentHash": "BST/sWYpKk9OXO7Yxktcg6FWORRsHU0EdCbMwZ7d3OqJsMKlrNHIZ30g0Ib4k5T5acJYXRBmg9mNrTU/N6cy1g==", + "dependencies": { + "Microsoft.DiaSymReader": "2.2.10", + "Microsoft.Extensions.DependencyModel": "10.0.10", + "Microsoft.Testing.Platform": "2.5.0", + "Mono.Cecil": "0.11.6" + } + }, + "MinVer": { + "type": "Direct", + "requested": "[8.0.0, )", + "resolved": "8.0.0", + "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" + }, + "NSubstitute": { + "type": "Direct", + "requested": "[6.2.0, )", + "resolved": "6.2.0", + "contentHash": "05oaAmBAvYYUQb/NTb9/kWBDjq0iS772X4t428WJcHRcH+5ULJx6rTbEvqkZJBIHWRLI8MlU3et3F5/gkEHKIw==", + "dependencies": { + "Castle.Core": "5.1.1" + } + }, + "Shouldly": { + "type": "Direct", + "requested": "[4.3.0, )", + "resolved": "4.3.0", + "contentHash": "sDetrWXrl6YXZ4HeLsdBoNk3uIa7K+V4uvIJ+cqdRa5DrFxeTED7VkjoxCuU1kJWpUuBDZz2QXFzSxBtVXLwRQ==", + "dependencies": { + "DiffEngine": "11.3.0", + "EmptyFiles": "4.4.0" + } + }, + "xunit.v3": { + "type": "Direct", + "requested": "[4.0.3, )", + "resolved": "4.0.3", + "contentHash": "GxBopTuV5aU7NS0iE1P6I6YCQscIAP0iIyyZqZhs1c8Ry3cdiOouEtQQpX8cA7E1gEnKGRMNA+7NlhBy13AEyg==", + "dependencies": { + "xunit.v3.mtp-v2": "[4.0.3]" + } + }, + "xunit.v3.runner.common": { + "type": "Direct", + "requested": "[4.0.3, )", + "resolved": "4.0.3", + "contentHash": "J/kkhBgJg3wu1xI8gY2Esm3oRE47gNrGmKpT/XZDPOzZ3/F33yTK/ZH1CM6qDpAHoTT3GY/JgrVbS4T1JEKYiQ==", + "dependencies": { + "Microsoft.Win32.Registry": "[5.0.0]", + "System.Security.AccessControl": "[6.0.1]", + "xunit.v3.common": "[4.0.3]" + } + }, + "Castle.Core": { + "type": "Transitive", + "resolved": "5.1.1", + "contentHash": "rpYtIczkzGpf+EkZgDr9CClTdemhsrwA/W5hMoPjLkRFnXzH44zDLoovXeKtmxb1ykXK9aJVODSpiJml8CTw2g==", + "dependencies": { + "System.Diagnostics.EventLog": "6.0.0" + } + }, + "DiffEngine": { + "type": "Transitive", + "resolved": "11.3.0", + "contentHash": "k0ZgZqd09jLZQjR8FyQbSQE86Q7QZnjEzq1LPHtj1R2AoWO8sjV5x+jlSisL7NZAbUOI4y+7Bog8gkr9WIRBGw==", + "dependencies": { + "EmptyFiles": "4.4.0", + "System.Management": "6.0.1" + } + }, + "EmptyFiles": { + "type": "Transitive", + "resolved": "4.4.0", + "contentHash": "gwJEfIGS7FhykvtZoscwXj/XwW+mJY6UbAZk+qtLKFUGWC95kfKXnj8VkxsZQnWBxJemM/q664rGLN5nf+OHZw==" + }, + "Microsoft.ApplicationInsights": { + "type": "Transitive", + "resolved": "2.23.0", + "contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw==" + }, + "Microsoft.Bcl.AsyncInterfaces": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg==" + }, + "Microsoft.DiaSymReader": { + "type": "Transitive", + "resolved": "2.2.10", + "contentHash": "zmGsm6b2y3STDa/Of7rdkkfTDV8VuGB8aCqIkLoJIQh5tL78K3zJ8OUyFKnfsaORXmGr9iOKwDkZfUjeXi+CwA==" + }, + "Microsoft.Extensions.Configuration": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", + "dependencies": { + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" + }, + "Microsoft.Extensions.DependencyModel": { + "type": "Transitive", + "resolved": "10.0.10", + "contentHash": "rfZA1RjR021RPqSmIPovfz2aOd79TGqJ9BengbjnzIISOVwjLmuSDnhCMmiY/1c6iYvGolQ1iNGzkav0u11XEA==" + }, + "Microsoft.Extensions.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Options.ConfigurationExtensions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" + }, + "Microsoft.Testing.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "j1XGKCBrmfNm0tmotMa05GlqVtb2cW5UaMkKCFHPyyFHz5rdOy7TD0SVXnZJ+QMrjPAHjRoRqn5qcsUjICSWwg==", + "dependencies": { + "Microsoft.ApplicationInsights": "2.23.0", + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Testing.Extensions.TrxReport.Abstractions": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "+xTIaIU9H44GxOyjrfieMSZnxltGvleA3jCRtdEAzlXKb85pMmVYMLUv2JS8KwD+U2wQHUgvy5YfQfWoPEfVdQ==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Testing.Platform": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "ocX0rgGY78dKfmZlZe4hB0/dvlh7wJgUAWS+KfwrqxB9DpNsjshnne9dppCKnFNEOkX4QYsrdUU++NInFPiCBw==" + }, + "Microsoft.Testing.Platform.MSBuild": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "Jey2v0hd7WHHa7pr6MRNKtA07FvxcOMTCtIhTI7uBZ/qR5m1mgCVCo5L1rtVAtqgMhGA205bUwq9+is4LiCzpw==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Win32.Registry": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg==" + }, + "Mono.Cecil": { + "type": "Transitive", + "resolved": "0.11.6", + "contentHash": "f33RkDtZO8VlGXCtmQIviOtxgnUdym9xx/b1p9h91CRGOsJFxCFOFK1FDbVt1OCf1aWwYejUFa2MOQyFWTFjbA==" + }, + "System.CodeDom": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "CPc6tWO1LAer3IzfZufDBRL+UZQcj5uS207NHALQzP84Vp/z6wF0Aa0YZImOQY8iStY0A2zI/e3ihKNPfUm8XA==" + }, + "System.Diagnostics.DiagnosticSource": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" + }, + "System.Diagnostics.EventLog": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "lcyUiXTsETK2ALsZrX+nWuHSIQeazhqPphLfaRxzdGaG93+0kELqpgEHtwWOlQe7+jSFnKwaCAgL4kjeZCQJnw==" + }, + "System.Management": { + "type": "Transitive", + "resolved": "6.0.1", + "contentHash": "10J1D0h/lioojphfJ4Fuh5ZUThT/xOVHdV9roGBittKKNP2PMjrvibEdbVTGZcPra1399Ja3tqIJLyQrc5Wmhg==", + "dependencies": { + "System.CodeDom": "6.0.0" + } + }, + "System.Security.AccessControl": { + "type": "Transitive", + "resolved": "6.0.1", + "contentHash": "IQ4NXP/B3Ayzvw0rDQzVTYsCKyy0Jp9KI6aYcK7UnGVlR9+Awz++TIPCQtPYfLJfOpm8ajowMR09V7quD3sEHw==" + }, + "xunit.analyzers": { + "type": "Transitive", + "resolved": "2.3.0", + "contentHash": "FcuLqoNBgQA4MmQXOdNWsDnlw+LBysWUcWOql6MCTXXFJZPn+qjbxHA9F9KBRiPH0Y97MLr1VE6LxdH8MgKUoQ==" + }, + "xunit.v3.assert": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "RrlWQ3yXla+ud9JBWDIY9GnUS/DS44r3ObqqV7wdWt1GhS+SveCe0MBDL238VXYoV2mWnX/DhO2LdTq5FTlT7g==" + }, + "xunit.v3.common": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "+2qGz3rcveIxzbXeZVHU8dhMyaawt01mgm/zv1FJH2FPcvJpfTUqc1vQ3hK2V5zVt8QEDddA+B6fkf9/LWf/Pg==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "6.0.0" + } + }, + "xunit.v3.core.mtp-v2": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "CsmxEanMln1chMExl6TUjnH5kF0XUDb/SqWKXqnGD8UjpkZARAXi8JDtsUYdxuROcIIdwEfs3iHZeHmTeA8DUA==", + "dependencies": { + "Microsoft.Testing.Extensions.Telemetry": "2.5.2", + "Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.5.2", + "Microsoft.Testing.Platform": "2.5.2", + "Microsoft.Testing.Platform.MSBuild": "2.5.2", + "xunit.v3.extensibility.core": "[4.0.3]", + "xunit.v3.runner.inproc.console": "[4.0.3]" + } + }, + "xunit.v3.extensibility.core": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "TBYqQKyT+XBDLSHjG6PnmQpooqatflBcWvNiESVS5ptQxWXVf/FGlkUfkNyHKRCUDSCxxHIJNgwO+SRosUmZEw==", + "dependencies": { + "xunit.v3.common": "[4.0.3]" + } + }, + "xunit.v3.mtp-v2": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "lad1hGmodKkfp3AgIwHVVIYeA9GfW125tnkYj7HvOyiwbDH8gpMKPPhzHRC1wc0w4a+0UsOHx2Ero/DtLXvtqA==", + "dependencies": { + "xunit.analyzers": "2.3.0", + "xunit.v3.assert": "[4.0.3]", + "xunit.v3.core.mtp-v2": "[4.0.3]" + } + }, + "xunit.v3.runner.inproc.console": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "lDvNs5exa8rBdWXX/wdapPTp81SNCvUarXC5iXzr1qvO168+Sx/Ytrk9VSLbSD3Y9KNK8PcOjMl1q7JfCoo3LQ==", + "dependencies": { + "xunit.v3.extensibility.core": "[4.0.3]", + "xunit.v3.runner.common": "[4.0.3]" + } + }, + "dotbahn.common": { + "type": "Project", + "dependencies": { + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.tests.shared": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )" + } + }, + "Microsoft.Extensions.Http": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Options": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + } + } + } +} \ No newline at end of file diff --git a/tests/DotBahn.Tests.Facilities/Client/FacilityClientTests.cs b/tests/DotBahn.Tests.Facilities/Client/FacilityClientTests.cs new file mode 100644 index 0000000..f241450 --- /dev/null +++ b/tests/DotBahn.Tests.Facilities/Client/FacilityClientTests.cs @@ -0,0 +1,105 @@ +using System.Diagnostics; +using System.Net; +using DotBahn.Common.Auth; +using DotBahn.Common.Telemetry; +using DotBahn.Facilities; +using DotBahn.Tests.Facilities.Support; +using NSubstitute; +using Shouldly; + +namespace DotBahn.Tests.Facilities.Client; + +public class FacilityClientTests { + private const string EmptyResponse = "[]"; + + [Fact] + public async Task GetFacilitiesAsync_Should_ThrowArgumentNullException_When_QueryIsNull() { + using var fixture = new FacilityClientFixture(); + + var exception = await Should.ThrowAsync(() => fixture.Client.GetFacilitiesAsync(null!)); + + exception.ParamName.ShouldBe("query"); + } + + [Fact] + public async Task GetFacilitiesAsync_Should_ReturnEmptyList_When_ResponseContainsNoFacilities() { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + var result = await fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + result.ShouldBeEmpty(); + } + + [Fact] + public async Task GetFacilitiesAsync_Should_RequestFacilitiesEndpoint_When_Called() { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe("https://api.example.com/facilities"); + } + + [Theory] + [InlineData(HttpStatusCode.BadRequest, 400)] + [InlineData(HttpStatusCode.Unauthorized, 401)] + public async Task GetFacilitiesAsync_Should_ThrowHttpRequestException_When_ApiReturnsError(HttpStatusCode statusCode, int expectedCode) { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(statusCode, "error"); + + var exception = await Should.ThrowAsync(() => fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken)); + + exception.StatusCode.ShouldBe(statusCode); + exception.Message.ShouldContain(expectedCode.ToString()); + } + + [Fact] + public async Task GetFacilitiesAsync_Should_ThrowOperationCanceledException_When_Canceled() { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + using var cts = new CancellationTokenSource(); + await cts.CancelAsync(); + + await Should.ThrowAsync(() => fixture.Client.GetFacilitiesAsync(new FacilityQuery(), cts.Token)); + } + + [Theory] + [InlineData("{invalid")] + [InlineData("not json")] + [InlineData("null")] + public async Task GetFacilitiesAsync_Should_ThrowJsonException_When_ResponseIsInvalid(string json) { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, json); + + await Should.ThrowAsync(() => fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task GetFacilitiesAsync_Should_ReportFacilitiesApiTag_When_ListenerIsActive() { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + var activities = new List(); + using var listener = new ActivityListener(); + listener.ShouldListenTo = source => source.Name == DotBahnTelemetry.SourceName; + listener.Sample = (ref _) => ActivitySamplingResult.AllDataAndRecorded; + listener.ActivityStarted = activities.Add; + ActivitySource.AddActivityListener(listener); + + await fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + activities.ShouldContain(a => (string?)a.GetTagItem(DotBahnTelemetry.ApiTag) == "facilities"); + } + + [Fact] + public async Task GetFacilitiesAsync_Should_AuthorizeAndSetAcceptHeader_When_Called() { + var authorization = Substitute.For(); + using var fixture = new FacilityClientFixture(authorization); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + authorization.Received(1).AuthorizeRequest(Arg.Any()); + fixture.Handler.SentRequests.ShouldHaveSingleItem().Headers.Accept.ShouldContain(header => header.MediaType == "application/json"); + } +} diff --git a/tests/DotBahn.Facilities.Tests/DotBahn.Facilities.Tests.csproj b/tests/DotBahn.Tests.Facilities/DotBahn.Tests.Facilities.csproj similarity index 66% rename from tests/DotBahn.Facilities.Tests/DotBahn.Facilities.Tests.csproj rename to tests/DotBahn.Tests.Facilities/DotBahn.Tests.Facilities.csproj index 74958bf..eef4aa8 100644 --- a/tests/DotBahn.Facilities.Tests/DotBahn.Facilities.Tests.csproj +++ b/tests/DotBahn.Tests.Facilities/DotBahn.Tests.Facilities.csproj @@ -1,16 +1,17 @@ - + + - + + - - + diff --git a/tests/DotBahn.Tests.Facilities/Extensions/ServiceCollectionExtensionsTests.cs b/tests/DotBahn.Tests.Facilities/Extensions/ServiceCollectionExtensionsTests.cs new file mode 100644 index 0000000..99a4f3e --- /dev/null +++ b/tests/DotBahn.Tests.Facilities/Extensions/ServiceCollectionExtensionsTests.cs @@ -0,0 +1,75 @@ +using System.Net; +using DotBahn.Common.Auth; +using DotBahn.Facilities; +using DotBahn.Tests.Shared.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Shouldly; + +namespace DotBahn.Tests.Facilities.Extensions; + +public class ServiceCollectionExtensionsTests { + [Fact] + public void AddDotBahnFacilities_Should_RegisterFacilityClient_When_Called() { + var (provider, _, _) = Create(); + using (provider) { + provider.GetRequiredService().ShouldNotBeNull(); + } + } + + [Fact] + public async Task GetFacilitiesAsync_Should_UseDefaultEndpoint_When_NoConfigurationProvided() { + var (provider, handler, client) = Create(); + await using (provider) { + handler.RespondWith(HttpStatusCode.OK, "[]"); + + await client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe("https://apis.deutschebahn.com/db-api-marketplace/apis/fasta/v2/facilities"); + } + } + + [Theory] + [InlineData("https://api.example.com/", "https://api.example.com/facilities")] + [InlineData("https://example.org/fasta/v2/", "https://example.org/fasta/v2/facilities")] + public async Task GetFacilitiesAsync_Should_UseConfiguredEndpoint_When_ConfigurationProvided(string endpoint, string expectedUri) { + var (provider, handler, client) = Create(new Uri(endpoint)); + await using (provider) { + handler.RespondWith(HttpStatusCode.OK, "[]"); + + await client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe(expectedUri); + } + } + + [Fact] + public async Task ValidateAsync_Should_RejectRelativeEndpoint_When_ValidationRuns() { + var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection(); + services.AddDotBahnFacilities(options => options.BaseEndpoint = new Uri("relative", UriKind.Relative)); + await using var provider = services.BuildServiceProvider(); + var validator = provider.GetRequiredService(); + + var exception = await Should.ThrowAsync(() => validator.ValidateAsync()); + + exception.Message.ShouldContain("DotBahn: BaseEndpoint must be an absolute URI."); + } + + private static (ServiceProvider Provider, FakeHttpHandler Handler, IFacilityClient Client) Create(Uri? endpoint = null) { + var handler = new FakeHttpHandler(); + var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection(); + services.AddSingleton(new ApiKeyAuthorization(new AuthorizationOptions { + ClientId = "client", + ApiKey = "key" + })); + services.AddDotBahnFacilities(options => { + if (endpoint != null) { + options.BaseEndpoint = endpoint; + } + }); + services.AddHttpClient("DotBahn.Facilities").ConfigurePrimaryHttpMessageHandler(() => handler); + + var provider = services.BuildServiceProvider(); + return (provider, handler, provider.GetRequiredService()); + } +} diff --git a/tests/DotBahn.Tests.Facilities/Query/FacilityQueryParameterTests.cs b/tests/DotBahn.Tests.Facilities/Query/FacilityQueryParameterTests.cs new file mode 100644 index 0000000..58d303a --- /dev/null +++ b/tests/DotBahn.Tests.Facilities/Query/FacilityQueryParameterTests.cs @@ -0,0 +1,133 @@ +using System.Globalization; +using System.Net; +using DotBahn.Facilities; +using DotBahn.Facilities.Models.Enumerations; +using DotBahn.Tests.Facilities.Support; +using Shouldly; + +namespace DotBahn.Tests.Facilities.Query; + +public class FacilityQueryParameterTests { + private const string EmptyResponse = "[]"; + + [Theory] + [InlineData(FacilityType.Elevator, "type=ELEVATOR")] + [InlineData(FacilityType.Escalator, "type=ESCALATOR")] + [InlineData(FacilityType.Unknown, "type=Unknown")] + public async Task GetFacilitiesAsync_Should_FormatType_When_TypeProvided(FacilityType type, string expected) { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetFacilitiesAsync(new FacilityQuery().WithType(type), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldContain(expected); + } + + [Theory] + [InlineData(FacilityState.Active, "state=ACTIVE")] + [InlineData(FacilityState.Inactive, "state=INACTIVE")] + [InlineData(FacilityState.Unknown, "state=UNKNOWN")] + public async Task GetFacilitiesAsync_Should_FormatState_When_StateProvided(FacilityState state, string expected) { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetFacilitiesAsync(new FacilityQuery().WithState(state), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldContain(expected); + } + + [Theory] + [InlineData("10562421", "equipmentnumbers=10562421")] + [InlineData("10562421&22", "equipmentnumbers=10562421%2622")] + public async Task GetFacilitiesAsync_Should_EncodeEquipmentNumbers_When_ValuesProvided(string number, string expected) { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetFacilitiesAsync(new FacilityQuery().WithEquipmentNumbers(number), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldContain(expected); + } + + [Fact] + public async Task GetFacilitiesAsync_Should_JoinEquipmentNumbers_When_MultipleProvided() { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetFacilitiesAsync(new FacilityQuery().WithEquipmentNumbers("1", "2"), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString() + .ShouldContain("equipmentnumbers=1%2C2"); + } + + [Fact] + public async Task GetFacilitiesAsync_Should_OmitEquipmentNumbers_When_NoneProvided() { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldNotContain("equipmentnumbers"); + } + + [Theory] + [InlineData(8.1, 50.2, 8.3, 50.4, true)] + [InlineData(null, 50.2, 8.3, 50.4, false)] + [InlineData(8.1, null, 8.3, 50.4, false)] + [InlineData(8.1, 50.2, null, 50.4, false)] + [InlineData(8.1, 50.2, 8.3, null, false)] + public async Task GetFacilitiesAsync_Should_EmitArea_When_AllBoundsProvided(double? west, double? south, double? east, double? north, bool expected) { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + var query = new FacilityQuery { + LongitudeWest = west, + LatitudeSouth = south, + LongitudeEast = east, + LatitudeNorth = north + }; + + await fixture.Client.GetFacilitiesAsync(query, TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().Contains("area=").ShouldBe(expected); + } + + [Fact] + public async Task GetFacilitiesAsync_Should_FormatAreaInvariant_When_CultureUsesCommaDecimalSeparator() { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + var original = CultureInfo.CurrentCulture; + CultureInfo.CurrentCulture = new CultureInfo("de-DE"); + try { + await fixture.Client.GetFacilitiesAsync(new FacilityQuery().WithArea(8.1, 50.2, 8.3, 50.4), TestContext.Current.CancellationToken); + } finally { + CultureInfo.CurrentCulture = original; + } + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldContain("area=8.1%2C50.2%2C8.3%2C50.4"); + } + + [Fact] + public async Task GetFacilitiesAsync_Should_SendNoQuery_When_QueryIsEmpty() { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe("https://api.example.com/facilities"); + } + + [Fact] + public async Task GetFacilitiesAsync_Should_CombineAllFilters_When_MultipleFiltersProvided() { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + var query = new FacilityQuery() + .WithType(FacilityType.Elevator) + .WithState(FacilityState.Active) + .WithEquipmentNumbers("10562421", "10562422") + .AtStation(8002549) + .WithArea(8.1, 50.2, 8.3, 50.4); + + await fixture.Client.GetFacilitiesAsync(query, TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe("https://api.example.com/facilities?type=ELEVATOR&state=ACTIVE&equipmentnumbers=10562421%2C10562422&stationnumber=8002549&area=8.1%2C50.2%2C8.3%2C50.4"); + } +} diff --git a/tests/DotBahn.Tests.Facilities/Query/FacilityQueryTests.cs b/tests/DotBahn.Tests.Facilities/Query/FacilityQueryTests.cs new file mode 100644 index 0000000..ae6465d --- /dev/null +++ b/tests/DotBahn.Tests.Facilities/Query/FacilityQueryTests.cs @@ -0,0 +1,101 @@ +using DotBahn.Facilities; +using DotBahn.Facilities.Models.Enumerations; +using Shouldly; + +namespace DotBahn.Tests.Facilities.Query; + +public class FacilityQueryTests { + [Fact] + public void Constructor_Should_UseDocumentedDefaults_When_Called() { + var sut = new FacilityQuery(); + + sut.Type.ShouldBeNull(); + sut.State.ShouldBeNull(); + sut.EquipmentNumbers.ShouldBeEmpty(); + sut.StationId.ShouldBeNull(); + sut.LongitudeWest.ShouldBeNull(); + sut.LatitudeSouth.ShouldBeNull(); + sut.LongitudeEast.ShouldBeNull(); + sut.LatitudeNorth.ShouldBeNull(); + } + + [Theory] + [InlineData(FacilityType.Elevator)] + [InlineData(FacilityType.Escalator)] + [InlineData(FacilityType.Unknown)] + public void WithType_Should_SetType_When_ValueProvided(FacilityType type) { + var sut = new FacilityQuery(); + + var result = sut.WithType(type); + + result.ShouldBeSameAs(sut); + sut.Type.ShouldBe(type); + } + + [Theory] + [InlineData(FacilityState.Active)] + [InlineData(FacilityState.Inactive)] + [InlineData(FacilityState.Unknown)] + public void WithState_Should_SetState_When_ValueProvided(FacilityState state) { + var sut = new FacilityQuery(); + + var result = sut.WithState(state); + + result.ShouldBeSameAs(sut); + sut.State.ShouldBe(state); + } + + [Theory] + [InlineData("10562421")] + [InlineData("10562421", "10562422")] + [InlineData] + public void WithEquipmentNumbers_Should_SetNumbers_When_ValuesProvided(params string[] numbers) { + var sut = new FacilityQuery(); + + var result = sut.WithEquipmentNumbers(numbers); + + result.ShouldBeSameAs(sut); + sut.EquipmentNumbers.ShouldBe(numbers); + } + + [Fact] + public void WithEquipmentNumbers_Should_SetNull_When_NullProvided() { + var sut = new FacilityQuery(); + + sut.WithEquipmentNumbers(null!); + + sut.EquipmentNumbers.ShouldBeNull(); + } + + [Theory] + [InlineData(-1, "-1")] + [InlineData(0, "0")] + [InlineData(8002549, "8002549")] + [InlineData(int.MaxValue, "2147483647")] + [InlineData(int.MinValue, "-2147483648")] + public void AtStation_Should_SetStationId_When_ValueProvided(int stationId, string expected) { + var sut = new FacilityQuery(); + + var result = sut.AtStation(stationId); + + result.ShouldBeSameAs(sut); + sut.StationId.ShouldBe(expected); + } + + [Theory] + [InlineData(0d, 0d, 0d, 0d)] + [InlineData(-180d, -90d, 180d, 90d)] + [InlineData(8.1d, 50.2d, 8.3d, 50.4d)] + [InlineData(double.MaxValue, double.MinValue, double.Epsilon, double.NaN)] + public void WithArea_Should_SetAllBounds_When_ValuesProvided(double west, double south, double east, double north) { + var sut = new FacilityQuery(); + + var result = sut.WithArea(west, south, east, north); + + result.ShouldBeSameAs(sut); + sut.LongitudeWest.ShouldBe(west); + sut.LatitudeSouth.ShouldBe(south); + sut.LongitudeEast.ShouldBe(east); + sut.LatitudeNorth.ShouldBe(north); + } +} diff --git a/tests/DotBahn.Tests.Facilities/Support/FacilityClientFixture.cs b/tests/DotBahn.Tests.Facilities/Support/FacilityClientFixture.cs new file mode 100644 index 0000000..5062d9a --- /dev/null +++ b/tests/DotBahn.Tests.Facilities/Support/FacilityClientFixture.cs @@ -0,0 +1,33 @@ +using DotBahn.Common.Auth; +using DotBahn.Common.Clients; +using DotBahn.Facilities; +using DotBahn.Tests.Shared.Http; +using Microsoft.Extensions.DependencyInjection; + +namespace DotBahn.Tests.Facilities.Support; + +internal sealed class FacilityClientFixture : IDisposable { + private readonly ServiceProvider _provider; + + public FakeHttpHandler Handler { get; } = new(); + + public IFacilityClient Client { get; } + + public FacilityClientFixture(IAuthorization? authorization = null, Action? configure = null) { + var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection(); + services.AddSingleton(authorization ?? new ApiKeyAuthorization(new AuthorizationOptions { + ClientId = "client", + ApiKey = "key" + })); + services.AddDotBahnFacilities(options => { + options.BaseEndpoint = new Uri("https://api.example.com/"); + configure?.Invoke(options); + }); + services.AddHttpClient("DotBahn.Facilities").ConfigurePrimaryHttpMessageHandler(() => Handler); + + _provider = services.BuildServiceProvider(); + Client = _provider.GetRequiredService(); + } + + public void Dispose() => _provider.Dispose(); +} diff --git a/tests/DotBahn.Tests.Facilities/Transform/FacilityTransformationTests.cs b/tests/DotBahn.Tests.Facilities/Transform/FacilityTransformationTests.cs new file mode 100644 index 0000000..dcd7bf2 --- /dev/null +++ b/tests/DotBahn.Tests.Facilities/Transform/FacilityTransformationTests.cs @@ -0,0 +1,136 @@ +using System.Net; +using DotBahn.Facilities; +using DotBahn.Facilities.Models.Enumerations; +using DotBahn.Tests.Facilities.Support; +using Shouldly; + +namespace DotBahn.Tests.Facilities.Transform; + +public class FacilityTransformationTests { + [Theory] + [InlineData("8.1", "50.2", true)] + [InlineData("8.1", "null", false)] + [InlineData("null", "50.2", false)] + [InlineData("null", "null", false)] + public async Task GetFacilitiesAsync_Should_FilterByCoordinates_When_EitherIsMissing(string longitude, string latitude, bool expected) { + using var fixture = new FacilityClientFixture(); + var json = """[{"equipmentnumber":1,"type":"ELEVATOR","state":"ACTIVE","geocoordX":LON,"geocoordY":LAT}]""".Replace("LON", longitude).Replace("LAT", latitude); + fixture.Handler.RespondWith(HttpStatusCode.OK, json); + + var result = await fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + result.Count.ShouldBe(expected ? 1 : 0); + } + + [Theory] + [InlineData("0", "0", 0d, 0d)] + [InlineData("-180", "-90", -180d, -90d)] + [InlineData("180", "90", 180d, 90d)] + [InlineData("1.7976931348623157E+308", "1.7976931348623157E+308", double.MaxValue, double.MaxValue)] + public async Task GetFacilitiesAsync_Should_MapCoordinates_When_ValuesAreBoundary(string longitude, string latitude, double expectedLongitude, double expectedLatitude) { + using var fixture = new FacilityClientFixture(); + var json = """[{"equipmentnumber":1,"geocoordX":LON,"geocoordY":LAT}]""" + .Replace("LON", longitude).Replace("LAT", latitude); + fixture.Handler.RespondWith(HttpStatusCode.OK, json); + + var result = await fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + var facility = result.ShouldHaveSingleItem(); + facility.Coordinates.Longitude.ShouldBe(expectedLongitude); + facility.Coordinates.Latitude.ShouldBe(expectedLatitude); + } + + [Theory] + [InlineData("\"ELEVATOR\"", FacilityType.Elevator)] + [InlineData("\"ESCALATOR\"", FacilityType.Escalator)] + [InlineData("\"0\"", FacilityType.Elevator)] + [InlineData("\"elevator\"", FacilityType.Unknown)] + [InlineData("\"BOGUS\"", FacilityType.Unknown)] + [InlineData("\"UNKNOWN\"", FacilityType.Unknown)] + [InlineData("null", FacilityType.Unknown)] + [InlineData("\"\"", FacilityType.Unknown)] + [InlineData("\" \"", FacilityType.Unknown)] + public async Task GetFacilitiesAsync_Should_ParseType_When_ContractValueProvided(string jsonValue, FacilityType expected) { + using var fixture = new FacilityClientFixture(); + var json = """[{"equipmentnumber":1,"type":VALUE,"geocoordX":8.1,"geocoordY":50.2}]""".Replace("VALUE", jsonValue); + fixture.Handler.RespondWith(HttpStatusCode.OK, json); + + var result = await fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + result.ShouldHaveSingleItem().Type.ShouldBe(expected); + } + + [Theory] + [InlineData("\"ACTIVE\"", FacilityState.Active)] + [InlineData("\"INACTIVE\"", FacilityState.Inactive)] + [InlineData("\"UNKNOWN\"", FacilityState.Unknown)] + [InlineData("\"active\"", FacilityState.Unknown)] + [InlineData("\"BOGUS\"", FacilityState.Unknown)] + [InlineData("null", FacilityState.Unknown)] + [InlineData("\"\"", FacilityState.Unknown)] + public async Task GetFacilitiesAsync_Should_ParseState_When_ContractValueProvided(string jsonValue, FacilityState expected) { + using var fixture = new FacilityClientFixture(); + var json = """[{"equipmentnumber":1,"state":VALUE,"geocoordX":8.1,"geocoordY":50.2}]""".Replace("VALUE", jsonValue); + fixture.Handler.RespondWith(HttpStatusCode.OK, json); + + var result = await fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + result.ShouldHaveSingleItem().State.ShouldBe(expected); + } + + [Fact] + public async Task GetFacilitiesAsync_Should_MapAllFields_When_ContractIsComplete() { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """ + [{ + "equipmentnumber":10562421,"type":"ELEVATOR","description":"Aufzug Gleis 1", + "state":"INACTIVE","stateExplanation":"Wartung","stationnumber":8002549, + "geocoordX":10.0,"geocoordY":53.55,"operatorname":"DB Station&Service" + }] + """); + + var result = await fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + var facility = result.ShouldHaveSingleItem(); + facility.EquipmentNumber.ShouldBe(10562421); + facility.Type.ShouldBe(FacilityType.Elevator); + facility.Description.ShouldBe("Aufzug Gleis 1"); + facility.State.ShouldBe(FacilityState.Inactive); + facility.StateExplanation.ShouldBe("Wartung"); + facility.StationNumber.ShouldBe(8002549); + facility.Coordinates.Longitude.ShouldBe(10.0); + facility.Coordinates.Latitude.ShouldBe(53.55); + facility.OperatorName.ShouldBe("DB Station&Service"); + } + + [Fact] + public async Task GetFacilitiesAsync_Should_LeaveOptionalFieldsNull_When_ContractIsMinimal() { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """[{"equipmentnumber":1,"geocoordX":8.1,"geocoordY":50.2}]"""); + + var result = await fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + var facility = result.ShouldHaveSingleItem(); + facility.Description.ShouldBeNull(); + facility.StateExplanation.ShouldBeNull(); + facility.OperatorName.ShouldBeNull(); + facility.Type.ShouldBe(FacilityType.Unknown); + facility.State.ShouldBe(FacilityState.Unknown); + } + + [Fact] + public async Task GetFacilitiesAsync_Should_PreserveOrder_AndDropIncompleteFacilities() { + using var fixture = new FacilityClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """ + [ + {"equipmentnumber":3,"geocoordX":8.1,"geocoordY":50.2}, + {"equipmentnumber":1,"geocoordX":8.2}, + {"equipmentnumber":2,"geocoordX":8.3,"geocoordY":50.4} + ] + """); + + var result = await fixture.Client.GetFacilitiesAsync(new FacilityQuery(), TestContext.Current.CancellationToken); + + result.Select(facility => facility.EquipmentNumber).ShouldBe([3, 2]); + } +} diff --git a/tests/DotBahn.Tests.Facilities/packages.lock.json b/tests/DotBahn.Tests.Facilities/packages.lock.json new file mode 100644 index 0000000..2d52f46 --- /dev/null +++ b/tests/DotBahn.Tests.Facilities/packages.lock.json @@ -0,0 +1,543 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.Testing.Extensions.CodeCoverage": { + "type": "Direct", + "requested": "[18.12.0, )", + "resolved": "18.12.0", + "contentHash": "BST/sWYpKk9OXO7Yxktcg6FWORRsHU0EdCbMwZ7d3OqJsMKlrNHIZ30g0Ib4k5T5acJYXRBmg9mNrTU/N6cy1g==", + "dependencies": { + "Microsoft.DiaSymReader": "2.2.10", + "Microsoft.Extensions.DependencyModel": "10.0.10", + "Microsoft.Testing.Platform": "2.5.0", + "Mono.Cecil": "0.11.6" + } + }, + "MinVer": { + "type": "Direct", + "requested": "[8.0.0, )", + "resolved": "8.0.0", + "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" + }, + "NSubstitute": { + "type": "Direct", + "requested": "[6.2.0, )", + "resolved": "6.2.0", + "contentHash": "05oaAmBAvYYUQb/NTb9/kWBDjq0iS772X4t428WJcHRcH+5ULJx6rTbEvqkZJBIHWRLI8MlU3et3F5/gkEHKIw==", + "dependencies": { + "Castle.Core": "5.1.1" + } + }, + "Shouldly": { + "type": "Direct", + "requested": "[4.3.0, )", + "resolved": "4.3.0", + "contentHash": "sDetrWXrl6YXZ4HeLsdBoNk3uIa7K+V4uvIJ+cqdRa5DrFxeTED7VkjoxCuU1kJWpUuBDZz2QXFzSxBtVXLwRQ==", + "dependencies": { + "DiffEngine": "11.3.0", + "EmptyFiles": "4.4.0" + } + }, + "xunit.v3": { + "type": "Direct", + "requested": "[4.0.3, )", + "resolved": "4.0.3", + "contentHash": "GxBopTuV5aU7NS0iE1P6I6YCQscIAP0iIyyZqZhs1c8Ry3cdiOouEtQQpX8cA7E1gEnKGRMNA+7NlhBy13AEyg==", + "dependencies": { + "xunit.v3.mtp-v2": "[4.0.3]" + } + }, + "xunit.v3.runner.common": { + "type": "Direct", + "requested": "[4.0.3, )", + "resolved": "4.0.3", + "contentHash": "J/kkhBgJg3wu1xI8gY2Esm3oRE47gNrGmKpT/XZDPOzZ3/F33yTK/ZH1CM6qDpAHoTT3GY/JgrVbS4T1JEKYiQ==", + "dependencies": { + "Microsoft.Win32.Registry": "[5.0.0]", + "System.Security.AccessControl": "[6.0.1]", + "xunit.v3.common": "[4.0.3]" + } + }, + "Castle.Core": { + "type": "Transitive", + "resolved": "5.1.1", + "contentHash": "rpYtIczkzGpf+EkZgDr9CClTdemhsrwA/W5hMoPjLkRFnXzH44zDLoovXeKtmxb1ykXK9aJVODSpiJml8CTw2g==", + "dependencies": { + "System.Diagnostics.EventLog": "6.0.0" + } + }, + "DiffEngine": { + "type": "Transitive", + "resolved": "11.3.0", + "contentHash": "k0ZgZqd09jLZQjR8FyQbSQE86Q7QZnjEzq1LPHtj1R2AoWO8sjV5x+jlSisL7NZAbUOI4y+7Bog8gkr9WIRBGw==", + "dependencies": { + "EmptyFiles": "4.4.0", + "System.Management": "6.0.1" + } + }, + "EmptyFiles": { + "type": "Transitive", + "resolved": "4.4.0", + "contentHash": "gwJEfIGS7FhykvtZoscwXj/XwW+mJY6UbAZk+qtLKFUGWC95kfKXnj8VkxsZQnWBxJemM/q664rGLN5nf+OHZw==" + }, + "Microsoft.ApplicationInsights": { + "type": "Transitive", + "resolved": "2.23.0", + "contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw==" + }, + "Microsoft.Bcl.AsyncInterfaces": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg==" + }, + "Microsoft.DiaSymReader": { + "type": "Transitive", + "resolved": "2.2.10", + "contentHash": "zmGsm6b2y3STDa/Of7rdkkfTDV8VuGB8aCqIkLoJIQh5tL78K3zJ8OUyFKnfsaORXmGr9iOKwDkZfUjeXi+CwA==" + }, + "Microsoft.Extensions.AmbientMetadata.Application": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "tm28s2ODWZ6RdysP06NI3B23DUY5OfHG35ihMHxVAO3hywZAczDVjrkYMfBY//J4HQqfDHS5op84BhnF7ROseQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Compliance.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "DUwdXgIxJKH9zBNg/SUBqOX0FpXCq7w80CIzrr0Jcw5tBXS926AtCcidoAsEHq5e/c6KQ8rWhSt7NxFxak8N/Q==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15" + } + }, + "Microsoft.Extensions.Compliance.Redaction": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "2rwe98yZEn4+aXjAg5DdcROMg6m2w3tejf/mRk4/fBCHKM2EWCaFTmbHLtz1BfyBxMY00/08XFoN0wzWYNiSiQ==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Configuration": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", + "dependencies": { + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" + }, + "Microsoft.Extensions.DependencyInjection.AutoActivation": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "OuVIF5TmsfonN2Fqmi2zlUtbFQNqQiflhgo/rh64ptrqYrB4wZLwKbXr/HzrQXMf+h3jIbWrjIdJFspGqcvuuQ==", + "dependencies": { + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.DependencyModel": { + "type": "Transitive", + "resolved": "10.0.10", + "contentHash": "rfZA1RjR021RPqSmIPovfz2aOd79TGqJ9BengbjnzIISOVwjLmuSDnhCMmiY/1c6iYvGolQ1iNGzkav0u11XEA==" + }, + "Microsoft.Extensions.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mqqpmAFNRLa4cozN3RvT/T81k4aarwMc8xb8VVQgLqUE7AAoN/WWayZAvP+4hy9+KujP3dfn3taU06fZJPIbgA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.FileProviders.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "1RSYAUtJeb76m2T0u5BbvwKY3s+ge9fT3cj1odvo5Bm+frc7pU9RSeXeMIlYHV8GjpqLdv2neeeomz010yYL8A==", + "dependencies": { + "Microsoft.Extensions.Primitives": "10.0.15" + } + }, + "Microsoft.Extensions.Hosting.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "s/JBiwR3F/vKRCbe6WO5b6t6or1ISaZ3rllchcw6/FSWZmK8s2fAzD7elrZo7592FnMD1fhGoG/wuJL1YYtVXw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.Http.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mKHY0oFYL3fkAOhBNi2LqWPuEdUJ+HiF28KKUwBkQG2sgXAUdFDDqvJAfu2PcYgtAwsAtl58zuk4SElpPzbCvA==", + "dependencies": { + "Microsoft.Extensions.Compliance.Redaction": "11.0.1", + "Microsoft.Extensions.Http": "10.0.15", + "Microsoft.Extensions.Telemetry": "11.0.1" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Configuration": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "Km6Ml1/nu0T/f80Btonxf9CWmP/BXI84aJwC5fUbCxRArJ0lH++0ADQrjErZvsSIrKhusTkTSGBChKy2fYAF4w==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Configuration.Binder": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.ObjectPool": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "kvd9eyRRQ+OEu9wik7GKgTS+7XnJ5XoOtSXJqmkJtVYV/S4gsBUrobYRSdNeBcb0ymef4L5Q9pZGiTxJ8jJfyQ==" + }, + "Microsoft.Extensions.Options.ConfigurationExtensions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" + }, + "Microsoft.Extensions.Resilience": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "xgKof6iwAByZNrxWOa7Drk4A953L7U2HleTmx7EXE2Vf6j1crp4RsvNlIVsJMtHKf3ftGKd9gOhR3xES9vxUgg==", + "dependencies": { + "Microsoft.Extensions.Diagnostics": "10.0.15", + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1", + "Polly.Extensions": "8.4.2", + "Polly.RateLimiting": "8.4.2" + } + }, + "Microsoft.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "9uuA8entTC9m00m59h6CACSt4IQh9KknB+hPvCteXUTiG67lqJ8BI65fEUJSPSfT3ZDDi01Zg2aY5kRUvD4HPw==", + "dependencies": { + "Microsoft.Extensions.AmbientMetadata.Application": "11.0.1", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "11.0.1", + "Microsoft.Extensions.Logging.Configuration": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1" + } + }, + "Microsoft.Extensions.Telemetry.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "qINZz4G01Wxumqd0hLr6YdzPa3s7jexQWN28EenaiJQnmKdsR9FnBaKENdRRElLc+A5bJKQ+jYw/WHG4ZpIyAg==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15" + } + }, + "Microsoft.Testing.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "j1XGKCBrmfNm0tmotMa05GlqVtb2cW5UaMkKCFHPyyFHz5rdOy7TD0SVXnZJ+QMrjPAHjRoRqn5qcsUjICSWwg==", + "dependencies": { + "Microsoft.ApplicationInsights": "2.23.0", + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Testing.Extensions.TrxReport.Abstractions": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "+xTIaIU9H44GxOyjrfieMSZnxltGvleA3jCRtdEAzlXKb85pMmVYMLUv2JS8KwD+U2wQHUgvy5YfQfWoPEfVdQ==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Testing.Platform": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "ocX0rgGY78dKfmZlZe4hB0/dvlh7wJgUAWS+KfwrqxB9DpNsjshnne9dppCKnFNEOkX4QYsrdUU++NInFPiCBw==" + }, + "Microsoft.Testing.Platform.MSBuild": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "Jey2v0hd7WHHa7pr6MRNKtA07FvxcOMTCtIhTI7uBZ/qR5m1mgCVCo5L1rtVAtqgMhGA205bUwq9+is4LiCzpw==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Win32.Registry": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg==" + }, + "Mono.Cecil": { + "type": "Transitive", + "resolved": "0.11.6", + "contentHash": "f33RkDtZO8VlGXCtmQIviOtxgnUdym9xx/b1p9h91CRGOsJFxCFOFK1FDbVt1OCf1aWwYejUFa2MOQyFWTFjbA==" + }, + "Polly.Core": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g==" + }, + "Polly.Extensions": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==", + "dependencies": { + "Microsoft.Extensions.Logging.Abstractions": "8.0.0", + "Microsoft.Extensions.Options": "8.0.0", + "Polly.Core": "8.4.2" + } + }, + "Polly.RateLimiting": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==", + "dependencies": { + "Polly.Core": "8.4.2", + "System.Threading.RateLimiting": "8.0.0" + } + }, + "System.CodeDom": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "CPc6tWO1LAer3IzfZufDBRL+UZQcj5uS207NHALQzP84Vp/z6wF0Aa0YZImOQY8iStY0A2zI/e3ihKNPfUm8XA==" + }, + "System.Diagnostics.DiagnosticSource": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" + }, + "System.Diagnostics.EventLog": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "lcyUiXTsETK2ALsZrX+nWuHSIQeazhqPphLfaRxzdGaG93+0kELqpgEHtwWOlQe7+jSFnKwaCAgL4kjeZCQJnw==" + }, + "System.Management": { + "type": "Transitive", + "resolved": "6.0.1", + "contentHash": "10J1D0h/lioojphfJ4Fuh5ZUThT/xOVHdV9roGBittKKNP2PMjrvibEdbVTGZcPra1399Ja3tqIJLyQrc5Wmhg==", + "dependencies": { + "System.CodeDom": "6.0.0" + } + }, + "System.Security.AccessControl": { + "type": "Transitive", + "resolved": "6.0.1", + "contentHash": "IQ4NXP/B3Ayzvw0rDQzVTYsCKyy0Jp9KI6aYcK7UnGVlR9+Awz++TIPCQtPYfLJfOpm8ajowMR09V7quD3sEHw==" + }, + "System.Threading.RateLimiting": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q==" + }, + "xunit.analyzers": { + "type": "Transitive", + "resolved": "2.3.0", + "contentHash": "FcuLqoNBgQA4MmQXOdNWsDnlw+LBysWUcWOql6MCTXXFJZPn+qjbxHA9F9KBRiPH0Y97MLr1VE6LxdH8MgKUoQ==" + }, + "xunit.v3.assert": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "RrlWQ3yXla+ud9JBWDIY9GnUS/DS44r3ObqqV7wdWt1GhS+SveCe0MBDL238VXYoV2mWnX/DhO2LdTq5FTlT7g==" + }, + "xunit.v3.common": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "+2qGz3rcveIxzbXeZVHU8dhMyaawt01mgm/zv1FJH2FPcvJpfTUqc1vQ3hK2V5zVt8QEDddA+B6fkf9/LWf/Pg==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "6.0.0" + } + }, + "xunit.v3.core.mtp-v2": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "CsmxEanMln1chMExl6TUjnH5kF0XUDb/SqWKXqnGD8UjpkZARAXi8JDtsUYdxuROcIIdwEfs3iHZeHmTeA8DUA==", + "dependencies": { + "Microsoft.Testing.Extensions.Telemetry": "2.5.2", + "Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.5.2", + "Microsoft.Testing.Platform": "2.5.2", + "Microsoft.Testing.Platform.MSBuild": "2.5.2", + "xunit.v3.extensibility.core": "[4.0.3]", + "xunit.v3.runner.inproc.console": "[4.0.3]" + } + }, + "xunit.v3.extensibility.core": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "TBYqQKyT+XBDLSHjG6PnmQpooqatflBcWvNiESVS5ptQxWXVf/FGlkUfkNyHKRCUDSCxxHIJNgwO+SRosUmZEw==", + "dependencies": { + "xunit.v3.common": "[4.0.3]" + } + }, + "xunit.v3.mtp-v2": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "lad1hGmodKkfp3AgIwHVVIYeA9GfW125tnkYj7HvOyiwbDH8gpMKPPhzHRC1wc0w4a+0UsOHx2Ero/DtLXvtqA==", + "dependencies": { + "xunit.analyzers": "2.3.0", + "xunit.v3.assert": "[4.0.3]", + "xunit.v3.core.mtp-v2": "[4.0.3]" + } + }, + "xunit.v3.runner.inproc.console": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "lDvNs5exa8rBdWXX/wdapPTp81SNCvUarXC5iXzr1qvO168+Sx/Ytrk9VSLbSD3Y9KNK8PcOjMl1q7JfCoo3LQ==", + "dependencies": { + "xunit.v3.extensibility.core": "[4.0.3]", + "xunit.v3.runner.common": "[4.0.3]" + } + }, + "dotbahn.common": { + "type": "Project", + "dependencies": { + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.facilities": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )", + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Http.Resilience": "[11.0.1, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.tests.shared": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )" + } + }, + "Microsoft.Extensions.Http": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Http.Resilience": { + "type": "CentralTransitive", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "5VawCrg+VgVT2hNurSSEWUnq0pvNoH+Zt82s5Wpl/8jdnmU8DpRlr+M3DcdtVgeBG7mRyk3GtSRbf8PB/HrL3w==", + "dependencies": { + "Microsoft.Extensions.Http.Diagnostics": "11.0.1", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Resilience": "11.0.1" + } + }, + "Microsoft.Extensions.Options": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + } + } + } +} \ No newline at end of file diff --git a/tests/DotBahn.Tests.Shared/Contracts/AlwaysNullDto.cs b/tests/DotBahn.Tests.Shared/Contracts/AlwaysNullDto.cs new file mode 100644 index 0000000..9e5e60a --- /dev/null +++ b/tests/DotBahn.Tests.Shared/Contracts/AlwaysNullDto.cs @@ -0,0 +1,7 @@ +using System.Text.Json.Serialization; +using DotBahn.Tests.Shared.Converters; + +namespace DotBahn.Tests.Shared.Contracts; + +[JsonConverter(typeof(AlwaysNullConverter))] +public class AlwaysNullDto; diff --git a/tests/DotBahn.Tests.Shared/Contracts/PostRequestDto.cs b/tests/DotBahn.Tests.Shared/Contracts/PostRequestDto.cs new file mode 100644 index 0000000..927dbfb --- /dev/null +++ b/tests/DotBahn.Tests.Shared/Contracts/PostRequestDto.cs @@ -0,0 +1,6 @@ +namespace DotBahn.Tests.Shared.Contracts; + +public class PostRequestDto { + public string? Name { get; set; } + public int Count { get; set; } +} diff --git a/tests/DotBahn.Tests.Shared/Contracts/SimpleDto.cs b/tests/DotBahn.Tests.Shared/Contracts/SimpleDto.cs new file mode 100644 index 0000000..8c46b90 --- /dev/null +++ b/tests/DotBahn.Tests.Shared/Contracts/SimpleDto.cs @@ -0,0 +1,6 @@ +namespace DotBahn.Tests.Shared.Contracts; + +public class SimpleDto { + public string? Name { get; set; } + public int Value { get; set; } +} diff --git a/tests/DotBahn.Tests.Shared/Contracts/TestEnum.cs b/tests/DotBahn.Tests.Shared/Contracts/TestEnum.cs new file mode 100644 index 0000000..e134ad7 --- /dev/null +++ b/tests/DotBahn.Tests.Shared/Contracts/TestEnum.cs @@ -0,0 +1,7 @@ +namespace DotBahn.Tests.Shared.Contracts; + +public enum TestEnum { + Unknown, + Active, + Inactive +} diff --git a/tests/DotBahn.Tests.Shared/Converters/AlwaysNullConverter.cs b/tests/DotBahn.Tests.Shared/Converters/AlwaysNullConverter.cs new file mode 100644 index 0000000..5f692c3 --- /dev/null +++ b/tests/DotBahn.Tests.Shared/Converters/AlwaysNullConverter.cs @@ -0,0 +1,13 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using DotBahn.Tests.Shared.Contracts; + +namespace DotBahn.Tests.Shared.Converters; + +public class AlwaysNullConverter : JsonConverter { + /// + public override AlwaysNullDto? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => null; + + /// + public override void Write(Utf8JsonWriter writer, AlwaysNullDto value, JsonSerializerOptions options) => writer.WriteNullValue(); +} diff --git a/tests/DotBahn.Tests.Shared/DotBahn.Tests.Shared.csproj b/tests/DotBahn.Tests.Shared/DotBahn.Tests.Shared.csproj new file mode 100644 index 0000000..412d840 --- /dev/null +++ b/tests/DotBahn.Tests.Shared/DotBahn.Tests.Shared.csproj @@ -0,0 +1,9 @@ + + + + Library + + + + + diff --git a/tests/DotBahn.Tests.Shared/Http/FakeHttpHandler.cs b/tests/DotBahn.Tests.Shared/Http/FakeHttpHandler.cs new file mode 100644 index 0000000..d297e7f --- /dev/null +++ b/tests/DotBahn.Tests.Shared/Http/FakeHttpHandler.cs @@ -0,0 +1,67 @@ +using System.Net; + +namespace DotBahn.Tests.Shared.Http; + +/// +/// Configurable HttpMessageHandler that returns predefined responses and captures requests for verification. +/// +public class FakeHttpHandler : HttpMessageHandler { + private readonly Queue> _responses = new(); + + /// + /// Gets the list of all sent HTTP requests. + /// + public List SentRequests { get; } = []; + + /// + /// Gets the captured request body content for each sent request. + /// + public List SentRequestBodies { get; } = []; + + /// + /// Gets the captured request content type media type for each sent request. + /// + public List SentRequestContentTypes { get; } = []; + + /// + /// Configures the handler to respond with a specific status code and content. + /// + /// The HTTP status code to return. + /// The response content body. + /// The content type header value. + public void RespondWith(HttpStatusCode status, string content, string contentType = "application/json") { + _responses.Enqueue(_ => new HttpResponseMessage(status) { + Content = new StringContent(content, System.Text.Encoding.UTF8, contentType) + }); + } + + /// + /// Configures the handler to respond with a dynamically generated response. + /// + /// A function that takes the request and returns a response. + public void RespondWith(Func factory) { + _responses.Enqueue(factory); + } + + /// + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) { + ct.ThrowIfCancellationRequested(); + + SentRequests.Add(request); + + if (request.Content != null) { + SentRequestBodies.Add(await request.Content.ReadAsStringAsync(ct).ConfigureAwait(false)); + SentRequestContentTypes.Add(request.Content.Headers.ContentType?.MediaType); + } else { + SentRequestBodies.Add(string.Empty); + SentRequestContentTypes.Add(null); + } + + if (_responses.Count == 0) { + throw new InvalidOperationException("No response configured."); + } + + var factory = _responses.Dequeue(); + return factory(request); + } +} diff --git a/tests/DotBahn.Tests.Shared/Http/HttpTestFixture.cs b/tests/DotBahn.Tests.Shared/Http/HttpTestFixture.cs new file mode 100644 index 0000000..1af33a4 --- /dev/null +++ b/tests/DotBahn.Tests.Shared/Http/HttpTestFixture.cs @@ -0,0 +1,31 @@ +namespace DotBahn.Tests.Shared.Http; + +/// +/// Shared fixture that provides an wired to a configurable . +/// +public sealed class HttpTestFixture : IDisposable { + /// + /// Gets the fake HTTP handler used to stub responses. + /// + public FakeHttpHandler Handler { get; } = new(); + + /// + /// Gets the HTTP client configured with the fake handler. + /// + public HttpClient Client { get; } + + /// + /// Initializes a new instance of the class. + /// + public HttpTestFixture() { + Client = new HttpClient(Handler, disposeHandler: false) { + BaseAddress = new Uri("https://api.deutschebahn.com") + }; + } + + /// + public void Dispose() { + Client.Dispose(); + Handler.Dispose(); + } +} diff --git a/tests/DotBahn.Tests.Shared/TestsJsonContext.cs b/tests/DotBahn.Tests.Shared/TestsJsonContext.cs new file mode 100644 index 0000000..29b8468 --- /dev/null +++ b/tests/DotBahn.Tests.Shared/TestsJsonContext.cs @@ -0,0 +1,14 @@ +using System.Text.Json.Serialization; +using DotBahn.Tests.Shared.Contracts; + +namespace DotBahn.Tests.Shared; + +/// +/// Shared source-generated JSON context for all tests. +/// +[JsonSourceGenerationOptions(UseStringEnumConverter = true)] +[JsonSerializable(typeof(SimpleDto))] +[JsonSerializable(typeof(AlwaysNullDto))] +[JsonSerializable(typeof(PostRequestDto))] +[JsonSerializable(typeof(TestEnum))] +public partial class TestsJsonContext : JsonSerializerContext; diff --git a/tests/DotBahn.Tests.Shared/packages.lock.json b/tests/DotBahn.Tests.Shared/packages.lock.json new file mode 100644 index 0000000..106d639 --- /dev/null +++ b/tests/DotBahn.Tests.Shared/packages.lock.json @@ -0,0 +1,144 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "MinVer": { + "type": "Direct", + "requested": "[8.0.0, )", + "resolved": "8.0.0", + "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" + }, + "Microsoft.Extensions.Configuration": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", + "dependencies": { + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" + }, + "Microsoft.Extensions.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Options.ConfigurationExtensions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" + }, + "System.Diagnostics.DiagnosticSource": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" + }, + "dotbahn.common": { + "type": "Project", + "dependencies": { + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "Microsoft.Extensions.Http": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Options": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + } + } + } +} \ No newline at end of file diff --git a/tests/DotBahn.Tests.Stations/Client/StationClientTests.cs b/tests/DotBahn.Tests.Stations/Client/StationClientTests.cs new file mode 100644 index 0000000..d894c57 --- /dev/null +++ b/tests/DotBahn.Tests.Stations/Client/StationClientTests.cs @@ -0,0 +1,119 @@ +using System.Diagnostics; +using System.Net; +using DotBahn.Common.Auth; +using DotBahn.Common.Telemetry; +using DotBahn.Stations; +using DotBahn.Tests.Stations.Support; +using NSubstitute; +using Shouldly; + +namespace DotBahn.Tests.Stations.Client; + +public class StationClientTests { + private const string EmptyResponse = """{"result":[]}"""; + + [Fact] + public async Task GetStationsAsync_Should_ThrowArgumentNullException_When_QueryIsNull() { + using var fixture = new StationClientFixture(); + + var exception = await Should.ThrowAsync(() => fixture.Client.GetStationsAsync(null!)); + + exception.ParamName.ShouldBe("query"); + } + + [Fact] + public async Task GetStationsAsync_Should_ReturnEmptyList_When_ResponseContainsNoStations() { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + var result = await fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + result.ShouldBeEmpty(); + } + + [Fact] + public async Task GetStationsAsync_Should_RequestStationsEndpoint_When_Called() { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe("https://api.example.com/stations?logicaloperator=AND&offset=0&limit=10000"); + } + + [Theory] + [InlineData("7,1,4", "1,4,7")] + [InlineData("1,1,7", "1,1,7")] + [InlineData("3,2,1", "1,2,3")] + public async Task GetStationsAsync_Should_SortByCategoryAscending_When_StationsAreUnsorted(string categories, string expected) { + using var fixture = new StationClientFixture(); + var stations = string.Join(",", categories.Split(',').Select(category => $$"""{"number":1,"name":"S{{category}}","category":{{category}},"ril100Identifiers":[],"evaNumbers":[]}""")); + fixture.Handler.RespondWith(HttpStatusCode.OK, $$"""{"result":[{{stations}}]}"""); + + var result = await fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + result.Select(station => (int)station.Category).ShouldBe(categories.Split(',').Select(int.Parse).Order()); + result.Select(station => station.Name).ShouldBe(expected.Split(',').Select(name => $"S{name}")); + } + + [Theory] + [InlineData(HttpStatusCode.BadRequest, 400)] + [InlineData(HttpStatusCode.Unauthorized, 401)] + public async Task GetStationsAsync_Should_ThrowHttpRequestException_When_ApiReturnsError(HttpStatusCode statusCode, int expectedCode) { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(statusCode, "error"); + + var exception = await Should.ThrowAsync(() => fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken)); + + exception.StatusCode.ShouldBe(statusCode); + exception.Message.ShouldContain(expectedCode.ToString()); + } + + [Fact] + public async Task GetStationsAsync_Should_ThrowOperationCanceledException_When_Canceled() { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + using var cts = new CancellationTokenSource(); + await cts.CancelAsync(); + + await Should.ThrowAsync(() => fixture.Client.GetStationsAsync(new StationQuery(), cts.Token)); + } + + [Theory] + [InlineData("{invalid")] + [InlineData("not json")] + public async Task GetStationsAsync_Should_ThrowJsonException_When_ResponseIsInvalidJson(string json) { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, json); + + await Should.ThrowAsync(() => fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task GetStationsAsync_Should_ReportStationsApiTag_When_ListenerIsActive() { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + var activities = new List(); + using var listener = new ActivityListener(); + listener.ShouldListenTo = source => source.Name == DotBahnTelemetry.SourceName; + listener.Sample = (ref _) => ActivitySamplingResult.AllDataAndRecorded; + listener.ActivityStarted = activities.Add; + ActivitySource.AddActivityListener(listener); + + await fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + activities.ShouldContain(a => (string?)a.GetTagItem(DotBahnTelemetry.ApiTag) == "stations"); + } + + [Fact] + public async Task GetStationsAsync_Should_AuthorizeAndSetAcceptHeader_When_Called() { + var authorization = Substitute.For(); + using var fixture = new StationClientFixture(authorization); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + authorization.Received(1).AuthorizeRequest(Arg.Any()); + fixture.Handler.SentRequests.ShouldHaveSingleItem().Headers.Accept.ShouldContain(header => header.MediaType == "application/json"); + } +} diff --git a/tests/DotBahn.Stations.Tests/DotBahn.Stations.Tests.csproj b/tests/DotBahn.Tests.Stations/DotBahn.Tests.Stations.csproj similarity index 63% rename from tests/DotBahn.Stations.Tests/DotBahn.Stations.Tests.csproj rename to tests/DotBahn.Tests.Stations/DotBahn.Tests.Stations.csproj index 68dc953..6cb2ee5 100644 --- a/tests/DotBahn.Stations.Tests/DotBahn.Stations.Tests.csproj +++ b/tests/DotBahn.Tests.Stations/DotBahn.Tests.Stations.csproj @@ -1,17 +1,17 @@ - + - + - + + - - + diff --git a/tests/DotBahn.Tests.Stations/Extensions/ServiceCollectionExtensionsTests.cs b/tests/DotBahn.Tests.Stations/Extensions/ServiceCollectionExtensionsTests.cs new file mode 100644 index 0000000..97fd701 --- /dev/null +++ b/tests/DotBahn.Tests.Stations/Extensions/ServiceCollectionExtensionsTests.cs @@ -0,0 +1,75 @@ +using System.Net; +using DotBahn.Common.Auth; +using DotBahn.Stations; +using DotBahn.Tests.Shared.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Shouldly; + +namespace DotBahn.Tests.Stations.Extensions; + +public class ServiceCollectionExtensionsTests { + [Fact] + public void AddDotBahnStations_Should_RegisterStationClient_When_Called() { + var (provider, _, _) = Create(); + using (provider) { + provider.GetRequiredService().ShouldNotBeNull(); + } + } + + [Fact] + public async Task GetStationsAsync_Should_UseDefaultEndpoint_When_NoConfigurationProvided() { + var (provider, handler, client) = Create(); + await using (provider) { + handler.RespondWith(HttpStatusCode.OK, """{"result":[]}"""); + + await client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe("https://apis.deutschebahn.com/db-api-marketplace/apis/station-data/v2/stations?logicaloperator=AND&offset=0&limit=10000"); + } + } + + [Theory] + [InlineData("https://api.example.com/", "https://api.example.com/stations?logicaloperator=AND&offset=0&limit=10000")] + [InlineData("https://example.org/stada/v2/", "https://example.org/stada/v2/stations?logicaloperator=AND&offset=0&limit=10000")] + public async Task GetStationsAsync_Should_UseConfiguredEndpoint_When_ConfigurationProvided(string endpoint, string expectedUri) { + var (provider, handler, client) = Create(new Uri(endpoint)); + await using (provider) { + handler.RespondWith(HttpStatusCode.OK, """{"result":[]}"""); + + await client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe(expectedUri); + } + } + + [Fact] + public async Task ValidateAsync_Should_RejectRelativeEndpoint_When_ValidationRuns() { + var services = new ServiceCollection(); + services.AddDotBahnStations(options => options.BaseEndpoint = new Uri("relative", UriKind.Relative)); + await using var provider = services.BuildServiceProvider(); + var validator = provider.GetRequiredService(); + + var exception = await Should.ThrowAsync(() => validator.ValidateAsync()); + + exception.Message.ShouldContain("DotBahn: BaseEndpoint must be an absolute URI."); + } + + private static (ServiceProvider Provider, FakeHttpHandler Handler, IStationClient Client) Create(Uri? endpoint = null) { + var handler = new FakeHttpHandler(); + var services = new ServiceCollection(); + services.AddSingleton(new ApiKeyAuthorization(new AuthorizationOptions { + ClientId = "client", + ApiKey = "key" + })); + services.AddDotBahnStations(options => { + if (endpoint != null) { + options.BaseEndpoint = endpoint; + } + }); + services.AddHttpClient("DotBahn.Stations").ConfigurePrimaryHttpMessageHandler(() => handler); + + var provider = services.BuildServiceProvider(); + return (provider, handler, provider.GetRequiredService()); + } +} diff --git a/tests/DotBahn.Tests.Stations/Models/StationModelTests.cs b/tests/DotBahn.Tests.Stations/Models/StationModelTests.cs new file mode 100644 index 0000000..df5ab39 --- /dev/null +++ b/tests/DotBahn.Tests.Stations/Models/StationModelTests.cs @@ -0,0 +1,103 @@ +using DotBahn.Common.Models; +using DotBahn.Stations.Models; +using DotBahn.Stations.Models.Enumerations; +using Shouldly; + +namespace DotBahn.Tests.Stations.Models; + +public class StationModelTests { + [Fact] + public void Constructor_Should_UseEmptyCollections_When_NotProvided() { + var sut = new Station { + Number = 1, + Name = "Test", + Category = StationCategory.Category1, + Services = new StationServices() + }; + + sut.Ril100Identifiers.ShouldBeEmpty(); + sut.EvaNumbers.ShouldBeEmpty(); + } + + [Fact] + public void PrimaryRil100_Should_BeNull_When_NoIdentifiersExist() { + var sut = CreateStation(); + + sut.PrimaryRil100.ShouldBeNull(); + } + + [Theory] + [InlineData(false, false, "A")] + [InlineData(false, true, "B")] + [InlineData(true, false, "A")] + [InlineData(true, true, "A")] + public void PrimaryRil100_Should_PreferMain_When_IdentifiersExist(bool firstIsMain, bool secondIsMain, string expected) { + var sut = CreateStation(rils: [ + new Ril100Identifier { Identifier = "A", IsMain = firstIsMain }, + new Ril100Identifier { Identifier = "B", IsMain = secondIsMain } + ]); + + sut.PrimaryRil100!.Identifier.ShouldBe(expected); + } + + [Fact] + public void PrimaryEva_Should_BeNull_When_NoEvaNumbersExist() { + var sut = CreateStation(); + + sut.PrimaryEva.ShouldBeNull(); + } + + [Theory] + [InlineData(false, false, 1L)] + [InlineData(false, true, 2L)] + [InlineData(true, false, 1L)] + [InlineData(true, true, 1L)] + public void PrimaryEva_Should_PreferMain_When_EvaNumbersExist(bool firstIsMain, bool secondIsMain, long expected) { + var sut = CreateStation(evas: [ + new EvaNumber { Number = 1, IsMain = firstIsMain }, + new EvaNumber { Number = 2, IsMain = secondIsMain } + ]); + + sut.PrimaryEva!.Number.ShouldBe(expected); + } + + [Fact] + public void Coordinates_Should_UsePrimaryEva_When_MainEvaHasCoordinates() { + var coordinates = new Coordinates { Longitude = 10.0, Latitude = 53.55 }; + var sut = CreateStation(evas: [ + new EvaNumber { Number = 1, IsMain = false, Coordinates = new Coordinates { Longitude = 20.0, Latitude = 40.0 } }, + new EvaNumber { Number = 2, IsMain = true, Coordinates = coordinates } + ]); + + sut.Coordinates.ShouldBe(coordinates); + } + + [Fact] + public void Coordinates_Should_BeNull_When_PrimaryEvaHasNoCoordinates() { + var sut = CreateStation(evas: [ + new EvaNumber { Number = 1, IsMain = false, Coordinates = new Coordinates { Longitude = 20.0, Latitude = 40.0 } }, + new EvaNumber { Number = 2, IsMain = true } + ]); + + sut.Coordinates.ShouldBeNull(); + } + + [Theory] + [InlineData("Hachmannplatz 16", "20095", "Hamburg", "Hachmannplatz 16, 20095 Hamburg")] + [InlineData("", "", "", ", ")] + [InlineData("Bahnhofstraße 1", "10115", "Berlin", "Bahnhofstraße 1, 10115 Berlin")] + public void DisplayAddress_Should_FormatComponents_When_AddressIsCreated(string street, string zipCode, string city, string expected) { + var sut = new StationAddress { Street = street, ZipCode = zipCode, City = city }; + + sut.DisplayAddress.ShouldBe(expected); + } + + private static Station CreateStation(Ril100Identifier[]? rils = null, EvaNumber[]? evas = null) => new() { + Number = 1, + Name = "Test", + Category = StationCategory.Category1, + Services = new StationServices(), + Ril100Identifiers = rils ?? [], + EvaNumbers = evas ?? [] + }; +} diff --git a/tests/DotBahn.Tests.Stations/Query/StationQueryParameterTests.cs b/tests/DotBahn.Tests.Stations/Query/StationQueryParameterTests.cs new file mode 100644 index 0000000..a18526e --- /dev/null +++ b/tests/DotBahn.Tests.Stations/Query/StationQueryParameterTests.cs @@ -0,0 +1,107 @@ +using System.Net; +using DotBahn.Stations; +using DotBahn.Stations.Models.Enumerations; +using DotBahn.Tests.Stations.Support; +using Shouldly; + +namespace DotBahn.Tests.Stations.Query; + +public class StationQueryParameterTests { + private const string EmptyResponse = """{"result":[]}"""; + + [Theory] + [InlineData("Hamburg", "searchstring=Hamburg%2A")] + [InlineData("München", "searchstring=München%2A")] + [InlineData("Ham*", "searchstring=Ham%2A")] + [InlineData("H?mb", "searchstring=H%3Fmb")] + public async Task GetStationsAsync_Should_EncodeNames_When_PatternsProvided(string name, string expected) { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetStationsAsync(new StationQuery().WithNames(name), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldContain(expected); + } + + [Theory] + [InlineData("1", "category=1")] + [InlineData("1,3-5", "category=1%2C3-5")] + [InlineData("1 - 7", "category=1-7")] + public async Task GetStationsAsync_Should_EncodeCategories_When_CategoriesProvided(string categories, string expected) { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetStationsAsync(new StationQuery().WithCategories(categories), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldContain(expected); + } + + [Theory] + [InlineData(FederalState.Berlin, "federalstate=Berlin")] + [InlineData(FederalState.BadenWuerttemberg, "federalstate=Baden-W%5Cu00FCrttemberg")] + [InlineData(FederalState.NorthRhineWestphalia, "federalstate=Nordrhein-Westfalen")] + [InlineData(FederalState.Unknown, "federalstate=Unknown")] + public async Task GetStationsAsync_Should_FormatFederalState_When_StateProvided(FederalState state, string expected) { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetStationsAsync(new StationQuery().InFederalState(state), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldContain(expected); + } + + [Theory] + [InlineData(LogicalOperator.And, "logicaloperator=AND")] + [InlineData(LogicalOperator.Or, "logicaloperator=OR")] + public async Task GetStationsAsync_Should_FormatLogicalOperator_When_OperatorProvided(LogicalOperator @operator, string expected) { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetStationsAsync(new StationQuery().CombineAs(@operator), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldContain(expected); + } + + [Theory] + [InlineData(0, 10000, "offset=0&limit=10000")] + [InlineData(1, 1, "offset=1&limit=1")] + [InlineData(-1, -1, "offset=-1&limit=-1")] + [InlineData(int.MaxValue, int.MaxValue, "offset=2147483647&limit=2147483647")] + public async Task GetStationsAsync_Should_IncludePagination_When_BoundaryValuesProvided(int offset, int limit, string expected) { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetStationsAsync(new StationQuery().Skip(offset).LimitTo(limit), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldContain(expected); + } + + [Fact] + public async Task GetStationsAsync_Should_SendOnlyDefaultParameters_When_QueryIsEmpty() { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + + await fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe("https://api.example.com/stations?logicaloperator=AND&offset=0&limit=10000"); + } + + [Fact] + public async Task GetStationsAsync_Should_CombineAllFilters_When_MultipleFiltersProvided() { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyResponse); + var query = new StationQuery() + .WithNames("Hamburg") + .WithCategories("1,3-5") + .InFederalState(FederalState.Hamburg) + .WithEva("8002549") + .WithRil("AH") + .CombineAs(LogicalOperator.Or) + .Skip(10) + .LimitTo(50); + + await fixture.Client.GetStationsAsync(query, TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe("https://api.example.com/stations?searchstring=Hamburg%2A&category=1%2C3-5&federalstate=Hamburg&eva=8002549&ril=AH&logicaloperator=OR&offset=10&limit=50"); + } +} diff --git a/tests/DotBahn.Tests.Stations/Query/StationQueryTests.cs b/tests/DotBahn.Tests.Stations/Query/StationQueryTests.cs new file mode 100644 index 0000000..eeee86d --- /dev/null +++ b/tests/DotBahn.Tests.Stations/Query/StationQueryTests.cs @@ -0,0 +1,190 @@ +using DotBahn.Stations; +using DotBahn.Stations.Models.Enumerations; +using Shouldly; + +namespace DotBahn.Tests.Stations.Query; + +public class StationQueryTests { + [Fact] + public void Constructor_Should_UseDocumentedDefaults_When_Called() { + var sut = new StationQuery(); + + sut.Names.ShouldBeNull(); + sut.Categories.ShouldBeNull(); + sut.State.ShouldBeNull(); + sut.Eva.ShouldBeNull(); + sut.Ril.ShouldBeNull(); + sut.Operator.ShouldBe(LogicalOperator.And); + sut.Offset.ShouldBe(0); + sut.Limit.ShouldBe(10000); + } + + [Theory] + [InlineData("Hamburg", "Hamburg*")] + [InlineData("München", "München*")] + [InlineData("Ham*", "Ham*")] + [InlineData("H?mb", "H?mb")] + [InlineData("*", "*")] + [InlineData("", "*")] + [InlineData(" ", " *")] + public void WithNames_Should_AppendWildcard_When_PatternHasNoWildcard(string name, string expected) { + var sut = new StationQuery(); + + var result = sut.WithNames(name); + + result.ShouldBeSameAs(sut); + sut.Names.ShouldBe([expected]); + } + + [Fact] + public void WithNames_Should_ThrowArgumentException_When_NamesAreNull() { + var sut = new StationQuery(); + + var exception = Should.Throw(() => sut.WithNames(null!)); + + exception.ParamName.ShouldBe("names"); + exception.Message.ShouldContain("At least one name is required."); + } + + [Fact] + public void WithNames_Should_ThrowArgumentException_When_NamesAreEmpty() { + var sut = new StationQuery(); + + var exception = Should.Throw(() => sut.WithNames([])); + + exception.ParamName.ShouldBe("names"); + exception.Message.ShouldContain("At least one name is required."); + } + + [Theory] + [InlineData("4", "4")] + [InlineData("1", "1")] + [InlineData("7", "7")] + [InlineData("2-4", "2-4")] + [InlineData("1 - 7", "1-7")] + [InlineData("2 - 4", "2-4")] + [InlineData("1,3-5,7", "1,3-5,7")] + [InlineData(" 2 , 4 ", "2,4")] + [InlineData("1,,2", "1,2")] + [InlineData("1-1", "1-1")] + [InlineData("7-7", "7-7")] + public void WithCategories_Should_Normalize_When_InputIsValid(string input, string expected) { + var sut = new StationQuery(); + + var result = sut.WithCategories(input); + + result.ShouldBeSameAs(sut); + sut.Categories.ShouldBe(expected); + } + + [Theory] + [InlineData(null, "At least one category must be specified.")] + [InlineData("", "At least one category must be specified.")] + [InlineData(" ", "At least one category must be specified.")] + [InlineData("0", "Category must be between 1 and 7")] + [InlineData("8", "Category must be between 1 and 7")] + [InlineData("-1", "Invalid category range")] + [InlineData("abc", "Category must be between 1 and 7")] + [InlineData("1.5", "Category must be between 1 and 7")] + [InlineData("0-3", "Category range out of bounds")] + [InlineData("3-8", "Category range out of bounds")] + [InlineData("5-2", "Category range out of bounds")] + [InlineData("0-0", "Category range out of bounds")] + [InlineData("8-8", "Category range out of bounds")] + [InlineData("2-", "Invalid category range")] + [InlineData("a-b", "Invalid category range")] + [InlineData("1-2-3", "Invalid category range")] + [InlineData("1 - x", "Invalid category range")] + public void WithCategories_Should_ThrowArgumentException_When_InputIsInvalid(string? input, string expectedMessage) { + var sut = new StationQuery(); + + var exception = Should.Throw(() => sut.WithCategories(input!)); + + exception.ParamName.ShouldBe("categories"); + exception.Message.ShouldContain(expectedMessage); + } + + [Theory] + [InlineData(-1)] + [InlineData(0)] + [InlineData(1)] + [InlineData(5000)] + [InlineData(int.MaxValue)] + [InlineData(int.MinValue)] + public void Skip_Should_SetOffset_When_ValueIsBoundaryOrInterior(int value) { + var sut = new StationQuery(); + + var result = sut.Skip(value); + + result.ShouldBeSameAs(sut); + sut.Offset.ShouldBe(value); + } + + [Theory] + [InlineData(-1)] + [InlineData(0)] + [InlineData(1)] + [InlineData(9999)] + [InlineData(10000)] + [InlineData(10001)] + [InlineData(int.MaxValue)] + public void LimitTo_Should_SetLimit_When_ValueIsBoundaryOrInterior(int value) { + var sut = new StationQuery(); + + var result = sut.LimitTo(value); + + result.ShouldBeSameAs(sut); + sut.Limit.ShouldBe(value); + } + + [Theory] + [InlineData(LogicalOperator.And)] + [InlineData(LogicalOperator.Or)] + public void CombineAs_Should_SetOperator_When_ValueIsProvided(LogicalOperator value) { + var sut = new StationQuery(); + + var result = sut.CombineAs(value); + + result.ShouldBeSameAs(sut); + sut.Operator.ShouldBe(value); + } + + [Theory] + [InlineData(FederalState.Berlin)] + [InlineData(FederalState.BadenWuerttemberg)] + [InlineData(FederalState.NorthRhineWestphalia)] + [InlineData(FederalState.Unknown)] + public void InFederalState_Should_SetState_When_ValueIsProvided(FederalState value) { + var sut = new StationQuery(); + + var result = sut.InFederalState(value); + + result.ShouldBeSameAs(sut); + sut.State.ShouldBe(value); + } + + [Theory] + [InlineData("")] + [InlineData("0")] + [InlineData("8002549")] + public void WithEva_Should_SetEva_When_ValueIsProvided(string value) { + var sut = new StationQuery(); + + var result = sut.WithEva(value); + + result.ShouldBeSameAs(sut); + sut.Eva.ShouldBe(value); + } + + [Theory] + [InlineData("")] + [InlineData("AH")] + public void WithRil_Should_SetRil_When_ValueIsProvided(string value) { + var sut = new StationQuery(); + + var result = sut.WithRil(value); + + result.ShouldBeSameAs(sut); + sut.Ril.ShouldBe(value); + } +} diff --git a/tests/DotBahn.Tests.Stations/Support/StationClientFixture.cs b/tests/DotBahn.Tests.Stations/Support/StationClientFixture.cs new file mode 100644 index 0000000..c55a7a3 --- /dev/null +++ b/tests/DotBahn.Tests.Stations/Support/StationClientFixture.cs @@ -0,0 +1,33 @@ +using DotBahn.Common.Auth; +using DotBahn.Common.Clients; +using DotBahn.Stations; +using DotBahn.Tests.Shared.Http; +using Microsoft.Extensions.DependencyInjection; + +namespace DotBahn.Tests.Stations.Support; + +internal sealed class StationClientFixture : IDisposable { + private readonly ServiceProvider _provider; + + public FakeHttpHandler Handler { get; } = new(); + + public IStationClient Client { get; } + + public StationClientFixture(IAuthorization? authorization = null, Action? configure = null) { + var services = new ServiceCollection(); + services.AddSingleton(authorization ?? new ApiKeyAuthorization(new AuthorizationOptions { + ClientId = "client", + ApiKey = "key" + })); + services.AddDotBahnStations(options => { + options.BaseEndpoint = new Uri("https://api.example.com/"); + configure?.Invoke(options); + }); + services.AddHttpClient("DotBahn.Stations").ConfigurePrimaryHttpMessageHandler(() => Handler); + + _provider = services.BuildServiceProvider(); + Client = _provider.GetRequiredService(); + } + + public void Dispose() => _provider.Dispose(); +} diff --git a/tests/DotBahn.Tests.Stations/Transform/StationTransformationTests.cs b/tests/DotBahn.Tests.Stations/Transform/StationTransformationTests.cs new file mode 100644 index 0000000..bd60c15 --- /dev/null +++ b/tests/DotBahn.Tests.Stations/Transform/StationTransformationTests.cs @@ -0,0 +1,132 @@ +using System.Net; +using DotBahn.Stations; +using DotBahn.Stations.Models.Enumerations; +using DotBahn.Tests.Stations.Support; +using Shouldly; + +namespace DotBahn.Tests.Stations.Transform; + +public class StationTransformationTests { + [Theory] + [InlineData(-1, StationCategory.Unknown)] + [InlineData(0, StationCategory.Unknown)] + [InlineData(1, StationCategory.Category1)] + [InlineData(2, StationCategory.Category2)] + [InlineData(4, StationCategory.Category4)] + [InlineData(6, StationCategory.Category6)] + [InlineData(7, StationCategory.Category7)] + [InlineData(8, StationCategory.Unknown)] + public async Task GetStationsAsync_Should_MapCategory_When_ValueIsBoundaryOrInterior(int category, StationCategory expected) { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, $$"""{"result":[{"number":1,"name":"S","category":{{category}},"ril100Identifiers":[],"evaNumbers":[]}]}"""); + + var result = await fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + result.ShouldHaveSingleItem().Category.ShouldBe(expected); + } + + [Theory] + [InlineData("null", null, null)] + [InlineData("[]", null, null)] + [InlineData("[13.4]", null, null)] + [InlineData("[13.4,52.5]", 13.4, 52.5)] + [InlineData("[13.4,52.5,99]", 13.4, 52.5)] + public async Task GetStationsAsync_Should_MapCoordinates_When_CountIsBoundaryOrInterior(string coordinates, double? longitude, double? latitude) { + using var fixture = new StationClientFixture(); + var json = """{"result":[{"number":1,"name":"S","category":1,"ril100Identifiers":[],"evaNumbers":[{"number":8002549,"isMain":true,"geographicCoordinates":{"type":"Point","coordinates":COORDS}}]}]}""".Replace("COORDS", coordinates); + fixture.Handler.RespondWith(HttpStatusCode.OK, json); + + var result = await fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + var station = result.ShouldHaveSingleItem(); + station.Coordinates.HasValue.ShouldBe(longitude.HasValue); + station.Coordinates?.Longitude.ShouldBe(longitude.GetValueOrDefault()); + station.Coordinates?.Latitude.ShouldBe(latitude.GetValueOrDefault()); + } + + [Fact] + public async Task GetStationsAsync_Should_LeaveCoordinatesNull_When_NoEvaNumbersExist() { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """{"result":[{"number":1,"name":"S","category":1,"ril100Identifiers":[],"evaNumbers":[]}]}"""); + + var result = await fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + var station = result.ShouldHaveSingleItem(); + station.PrimaryEva.ShouldBeNull(); + station.Coordinates.ShouldBeNull(); + } + + [Fact] + public async Task GetStationsAsync_Should_UseMainEvaCoordinates_When_OtherEvaHasCoordinates() { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """ + {"result":[{"number":1,"name":"S","category":1,"ril100Identifiers":[],"evaNumbers":[ + {"number":1,"isMain":false,"geographicCoordinates":{"coordinates":[10.0,50.0]}}, + {"number":2,"isMain":true} + ]}]} + """); + + var result = await fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + result.ShouldHaveSingleItem().Coordinates.ShouldBeNull(); + } + + [Fact] + public async Task GetStationsAsync_Should_MapAllFields_When_ContractIsComplete() { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """ + {"offset":0,"limit":10,"total":1,"result":[{ + "number":123,"name":"Hamburg Hbf","category":2, + "mailingAddress":{"city":"Hamburg","zipcode":"20095","street":"Hachmannplatz 16"}, + "regionalBereich":{"number":101,"name":"Hamburg","shortName":"RB"}, + "ril100Identifiers":[{"rilIdentifier":"AH","isMain":"JA"},{"rilIdentifier":"AHS","isMain":false}], + "evaNumbers":[{"number":8002549,"isMain":true,"geographicCoordinates":{"type":"Point","coordinates":[10.0,53.55]}},{"number":8002548,"isMain":false}], + "hasParking":"YES","hasBicycleParking":true,"hasPublicFacilities":"NO","hasLockerSystem":false, + "hasStepFreeAccess":"1","hasSteplessAccess":"FALSE","hasTravelCenter":true, + "hasTravelNecessities":"maybe","hasMobilityService":true,"hasWiFi":true + }]} + """); + + var result = await fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + var station = result.ShouldHaveSingleItem(); + station.Number.ShouldBe(123); + station.Name.ShouldBe("Hamburg Hbf"); + station.Category.ShouldBe(StationCategory.Category2); + station.Address!.DisplayAddress.ShouldBe("Hachmannplatz 16, 20095 Hamburg"); + station.RegionalArea!.Number.ShouldBe(101); + station.RegionalArea.Name.ShouldBe("Hamburg"); + station.RegionalArea.ShortName.ShouldBe("RB"); + station.PrimaryRil100!.Identifier.ShouldBe("AH"); + station.PrimaryRil100.IsMain.ShouldBeTrue(); + station.PrimaryEva!.Number.ShouldBe(8002549); + station.Coordinates!.Value.Longitude.ShouldBe(10.0); + station.Coordinates!.Value.Latitude.ShouldBe(53.55); + station.Services.HasParking.ShouldBeTrue(); + station.Services.HasBicycleParking.ShouldBeTrue(); + station.Services.HasPublicFacilities.ShouldBeFalse(); + station.Services.HasLockerSystem.ShouldBeFalse(); + station.Services.HasStepFreeAccess.ShouldBeTrue(); + station.Services.HasSteplessAccess.ShouldBeFalse(); + station.Services.HasTravelCenter.ShouldBeTrue(); + station.Services.HasTravelNecessities.ShouldBeFalse(); + station.Services.HasMobilityService.ShouldBeTrue(); + station.Services.HasWiFi.ShouldBeTrue(); + } + + [Fact] + public async Task GetStationsAsync_Should_LeaveOptionalPartsNull_When_ContractIsMinimal() { + using var fixture = new StationClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """{"result":[{"number":1,"name":"S","category":1,"ril100Identifiers":[],"evaNumbers":[]}]}"""); + + var result = await fixture.Client.GetStationsAsync(new StationQuery(), TestContext.Current.CancellationToken); + + var station = result.ShouldHaveSingleItem(); + station.Address.ShouldBeNull(); + station.RegionalArea.ShouldBeNull(); + station.Ril100Identifiers.ShouldBeEmpty(); + station.EvaNumbers.ShouldBeEmpty(); + station.PrimaryRil100.ShouldBeNull(); + station.PrimaryEva.ShouldBeNull(); + } +} diff --git a/tests/DotBahn.Tests.Stations/packages.lock.json b/tests/DotBahn.Tests.Stations/packages.lock.json new file mode 100644 index 0000000..2da2961 --- /dev/null +++ b/tests/DotBahn.Tests.Stations/packages.lock.json @@ -0,0 +1,543 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.Testing.Extensions.CodeCoverage": { + "type": "Direct", + "requested": "[18.12.0, )", + "resolved": "18.12.0", + "contentHash": "BST/sWYpKk9OXO7Yxktcg6FWORRsHU0EdCbMwZ7d3OqJsMKlrNHIZ30g0Ib4k5T5acJYXRBmg9mNrTU/N6cy1g==", + "dependencies": { + "Microsoft.DiaSymReader": "2.2.10", + "Microsoft.Extensions.DependencyModel": "10.0.10", + "Microsoft.Testing.Platform": "2.5.0", + "Mono.Cecil": "0.11.6" + } + }, + "MinVer": { + "type": "Direct", + "requested": "[8.0.0, )", + "resolved": "8.0.0", + "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" + }, + "NSubstitute": { + "type": "Direct", + "requested": "[6.2.0, )", + "resolved": "6.2.0", + "contentHash": "05oaAmBAvYYUQb/NTb9/kWBDjq0iS772X4t428WJcHRcH+5ULJx6rTbEvqkZJBIHWRLI8MlU3et3F5/gkEHKIw==", + "dependencies": { + "Castle.Core": "5.1.1" + } + }, + "Shouldly": { + "type": "Direct", + "requested": "[4.3.0, )", + "resolved": "4.3.0", + "contentHash": "sDetrWXrl6YXZ4HeLsdBoNk3uIa7K+V4uvIJ+cqdRa5DrFxeTED7VkjoxCuU1kJWpUuBDZz2QXFzSxBtVXLwRQ==", + "dependencies": { + "DiffEngine": "11.3.0", + "EmptyFiles": "4.4.0" + } + }, + "xunit.v3": { + "type": "Direct", + "requested": "[4.0.3, )", + "resolved": "4.0.3", + "contentHash": "GxBopTuV5aU7NS0iE1P6I6YCQscIAP0iIyyZqZhs1c8Ry3cdiOouEtQQpX8cA7E1gEnKGRMNA+7NlhBy13AEyg==", + "dependencies": { + "xunit.v3.mtp-v2": "[4.0.3]" + } + }, + "xunit.v3.runner.common": { + "type": "Direct", + "requested": "[4.0.3, )", + "resolved": "4.0.3", + "contentHash": "J/kkhBgJg3wu1xI8gY2Esm3oRE47gNrGmKpT/XZDPOzZ3/F33yTK/ZH1CM6qDpAHoTT3GY/JgrVbS4T1JEKYiQ==", + "dependencies": { + "Microsoft.Win32.Registry": "[5.0.0]", + "System.Security.AccessControl": "[6.0.1]", + "xunit.v3.common": "[4.0.3]" + } + }, + "Castle.Core": { + "type": "Transitive", + "resolved": "5.1.1", + "contentHash": "rpYtIczkzGpf+EkZgDr9CClTdemhsrwA/W5hMoPjLkRFnXzH44zDLoovXeKtmxb1ykXK9aJVODSpiJml8CTw2g==", + "dependencies": { + "System.Diagnostics.EventLog": "6.0.0" + } + }, + "DiffEngine": { + "type": "Transitive", + "resolved": "11.3.0", + "contentHash": "k0ZgZqd09jLZQjR8FyQbSQE86Q7QZnjEzq1LPHtj1R2AoWO8sjV5x+jlSisL7NZAbUOI4y+7Bog8gkr9WIRBGw==", + "dependencies": { + "EmptyFiles": "4.4.0", + "System.Management": "6.0.1" + } + }, + "EmptyFiles": { + "type": "Transitive", + "resolved": "4.4.0", + "contentHash": "gwJEfIGS7FhykvtZoscwXj/XwW+mJY6UbAZk+qtLKFUGWC95kfKXnj8VkxsZQnWBxJemM/q664rGLN5nf+OHZw==" + }, + "Microsoft.ApplicationInsights": { + "type": "Transitive", + "resolved": "2.23.0", + "contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw==" + }, + "Microsoft.Bcl.AsyncInterfaces": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg==" + }, + "Microsoft.DiaSymReader": { + "type": "Transitive", + "resolved": "2.2.10", + "contentHash": "zmGsm6b2y3STDa/Of7rdkkfTDV8VuGB8aCqIkLoJIQh5tL78K3zJ8OUyFKnfsaORXmGr9iOKwDkZfUjeXi+CwA==" + }, + "Microsoft.Extensions.AmbientMetadata.Application": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "tm28s2ODWZ6RdysP06NI3B23DUY5OfHG35ihMHxVAO3hywZAczDVjrkYMfBY//J4HQqfDHS5op84BhnF7ROseQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Compliance.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "DUwdXgIxJKH9zBNg/SUBqOX0FpXCq7w80CIzrr0Jcw5tBXS926AtCcidoAsEHq5e/c6KQ8rWhSt7NxFxak8N/Q==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15" + } + }, + "Microsoft.Extensions.Compliance.Redaction": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "2rwe98yZEn4+aXjAg5DdcROMg6m2w3tejf/mRk4/fBCHKM2EWCaFTmbHLtz1BfyBxMY00/08XFoN0wzWYNiSiQ==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Configuration": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", + "dependencies": { + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" + }, + "Microsoft.Extensions.DependencyInjection.AutoActivation": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "OuVIF5TmsfonN2Fqmi2zlUtbFQNqQiflhgo/rh64ptrqYrB4wZLwKbXr/HzrQXMf+h3jIbWrjIdJFspGqcvuuQ==", + "dependencies": { + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.DependencyModel": { + "type": "Transitive", + "resolved": "10.0.10", + "contentHash": "rfZA1RjR021RPqSmIPovfz2aOd79TGqJ9BengbjnzIISOVwjLmuSDnhCMmiY/1c6iYvGolQ1iNGzkav0u11XEA==" + }, + "Microsoft.Extensions.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mqqpmAFNRLa4cozN3RvT/T81k4aarwMc8xb8VVQgLqUE7AAoN/WWayZAvP+4hy9+KujP3dfn3taU06fZJPIbgA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.FileProviders.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "1RSYAUtJeb76m2T0u5BbvwKY3s+ge9fT3cj1odvo5Bm+frc7pU9RSeXeMIlYHV8GjpqLdv2neeeomz010yYL8A==", + "dependencies": { + "Microsoft.Extensions.Primitives": "10.0.15" + } + }, + "Microsoft.Extensions.Hosting.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "s/JBiwR3F/vKRCbe6WO5b6t6or1ISaZ3rllchcw6/FSWZmK8s2fAzD7elrZo7592FnMD1fhGoG/wuJL1YYtVXw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.Http.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mKHY0oFYL3fkAOhBNi2LqWPuEdUJ+HiF28KKUwBkQG2sgXAUdFDDqvJAfu2PcYgtAwsAtl58zuk4SElpPzbCvA==", + "dependencies": { + "Microsoft.Extensions.Compliance.Redaction": "11.0.1", + "Microsoft.Extensions.Http": "10.0.15", + "Microsoft.Extensions.Telemetry": "11.0.1" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Configuration": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "Km6Ml1/nu0T/f80Btonxf9CWmP/BXI84aJwC5fUbCxRArJ0lH++0ADQrjErZvsSIrKhusTkTSGBChKy2fYAF4w==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Configuration.Binder": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.ObjectPool": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "kvd9eyRRQ+OEu9wik7GKgTS+7XnJ5XoOtSXJqmkJtVYV/S4gsBUrobYRSdNeBcb0ymef4L5Q9pZGiTxJ8jJfyQ==" + }, + "Microsoft.Extensions.Options.ConfigurationExtensions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" + }, + "Microsoft.Extensions.Resilience": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "xgKof6iwAByZNrxWOa7Drk4A953L7U2HleTmx7EXE2Vf6j1crp4RsvNlIVsJMtHKf3ftGKd9gOhR3xES9vxUgg==", + "dependencies": { + "Microsoft.Extensions.Diagnostics": "10.0.15", + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1", + "Polly.Extensions": "8.4.2", + "Polly.RateLimiting": "8.4.2" + } + }, + "Microsoft.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "9uuA8entTC9m00m59h6CACSt4IQh9KknB+hPvCteXUTiG67lqJ8BI65fEUJSPSfT3ZDDi01Zg2aY5kRUvD4HPw==", + "dependencies": { + "Microsoft.Extensions.AmbientMetadata.Application": "11.0.1", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "11.0.1", + "Microsoft.Extensions.Logging.Configuration": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1" + } + }, + "Microsoft.Extensions.Telemetry.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "qINZz4G01Wxumqd0hLr6YdzPa3s7jexQWN28EenaiJQnmKdsR9FnBaKENdRRElLc+A5bJKQ+jYw/WHG4ZpIyAg==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15" + } + }, + "Microsoft.Testing.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "j1XGKCBrmfNm0tmotMa05GlqVtb2cW5UaMkKCFHPyyFHz5rdOy7TD0SVXnZJ+QMrjPAHjRoRqn5qcsUjICSWwg==", + "dependencies": { + "Microsoft.ApplicationInsights": "2.23.0", + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Testing.Extensions.TrxReport.Abstractions": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "+xTIaIU9H44GxOyjrfieMSZnxltGvleA3jCRtdEAzlXKb85pMmVYMLUv2JS8KwD+U2wQHUgvy5YfQfWoPEfVdQ==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Testing.Platform": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "ocX0rgGY78dKfmZlZe4hB0/dvlh7wJgUAWS+KfwrqxB9DpNsjshnne9dppCKnFNEOkX4QYsrdUU++NInFPiCBw==" + }, + "Microsoft.Testing.Platform.MSBuild": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "Jey2v0hd7WHHa7pr6MRNKtA07FvxcOMTCtIhTI7uBZ/qR5m1mgCVCo5L1rtVAtqgMhGA205bUwq9+is4LiCzpw==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Win32.Registry": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg==" + }, + "Mono.Cecil": { + "type": "Transitive", + "resolved": "0.11.6", + "contentHash": "f33RkDtZO8VlGXCtmQIviOtxgnUdym9xx/b1p9h91CRGOsJFxCFOFK1FDbVt1OCf1aWwYejUFa2MOQyFWTFjbA==" + }, + "Polly.Core": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g==" + }, + "Polly.Extensions": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==", + "dependencies": { + "Microsoft.Extensions.Logging.Abstractions": "8.0.0", + "Microsoft.Extensions.Options": "8.0.0", + "Polly.Core": "8.4.2" + } + }, + "Polly.RateLimiting": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==", + "dependencies": { + "Polly.Core": "8.4.2", + "System.Threading.RateLimiting": "8.0.0" + } + }, + "System.CodeDom": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "CPc6tWO1LAer3IzfZufDBRL+UZQcj5uS207NHALQzP84Vp/z6wF0Aa0YZImOQY8iStY0A2zI/e3ihKNPfUm8XA==" + }, + "System.Diagnostics.DiagnosticSource": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" + }, + "System.Diagnostics.EventLog": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "lcyUiXTsETK2ALsZrX+nWuHSIQeazhqPphLfaRxzdGaG93+0kELqpgEHtwWOlQe7+jSFnKwaCAgL4kjeZCQJnw==" + }, + "System.Management": { + "type": "Transitive", + "resolved": "6.0.1", + "contentHash": "10J1D0h/lioojphfJ4Fuh5ZUThT/xOVHdV9roGBittKKNP2PMjrvibEdbVTGZcPra1399Ja3tqIJLyQrc5Wmhg==", + "dependencies": { + "System.CodeDom": "6.0.0" + } + }, + "System.Security.AccessControl": { + "type": "Transitive", + "resolved": "6.0.1", + "contentHash": "IQ4NXP/B3Ayzvw0rDQzVTYsCKyy0Jp9KI6aYcK7UnGVlR9+Awz++TIPCQtPYfLJfOpm8ajowMR09V7quD3sEHw==" + }, + "System.Threading.RateLimiting": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q==" + }, + "xunit.analyzers": { + "type": "Transitive", + "resolved": "2.3.0", + "contentHash": "FcuLqoNBgQA4MmQXOdNWsDnlw+LBysWUcWOql6MCTXXFJZPn+qjbxHA9F9KBRiPH0Y97MLr1VE6LxdH8MgKUoQ==" + }, + "xunit.v3.assert": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "RrlWQ3yXla+ud9JBWDIY9GnUS/DS44r3ObqqV7wdWt1GhS+SveCe0MBDL238VXYoV2mWnX/DhO2LdTq5FTlT7g==" + }, + "xunit.v3.common": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "+2qGz3rcveIxzbXeZVHU8dhMyaawt01mgm/zv1FJH2FPcvJpfTUqc1vQ3hK2V5zVt8QEDddA+B6fkf9/LWf/Pg==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "6.0.0" + } + }, + "xunit.v3.core.mtp-v2": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "CsmxEanMln1chMExl6TUjnH5kF0XUDb/SqWKXqnGD8UjpkZARAXi8JDtsUYdxuROcIIdwEfs3iHZeHmTeA8DUA==", + "dependencies": { + "Microsoft.Testing.Extensions.Telemetry": "2.5.2", + "Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.5.2", + "Microsoft.Testing.Platform": "2.5.2", + "Microsoft.Testing.Platform.MSBuild": "2.5.2", + "xunit.v3.extensibility.core": "[4.0.3]", + "xunit.v3.runner.inproc.console": "[4.0.3]" + } + }, + "xunit.v3.extensibility.core": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "TBYqQKyT+XBDLSHjG6PnmQpooqatflBcWvNiESVS5ptQxWXVf/FGlkUfkNyHKRCUDSCxxHIJNgwO+SRosUmZEw==", + "dependencies": { + "xunit.v3.common": "[4.0.3]" + } + }, + "xunit.v3.mtp-v2": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "lad1hGmodKkfp3AgIwHVVIYeA9GfW125tnkYj7HvOyiwbDH8gpMKPPhzHRC1wc0w4a+0UsOHx2Ero/DtLXvtqA==", + "dependencies": { + "xunit.analyzers": "2.3.0", + "xunit.v3.assert": "[4.0.3]", + "xunit.v3.core.mtp-v2": "[4.0.3]" + } + }, + "xunit.v3.runner.inproc.console": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "lDvNs5exa8rBdWXX/wdapPTp81SNCvUarXC5iXzr1qvO168+Sx/Ytrk9VSLbSD3Y9KNK8PcOjMl1q7JfCoo3LQ==", + "dependencies": { + "xunit.v3.extensibility.core": "[4.0.3]", + "xunit.v3.runner.common": "[4.0.3]" + } + }, + "dotbahn.common": { + "type": "Project", + "dependencies": { + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.stations": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )", + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Http.Resilience": "[11.0.1, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.tests.shared": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )" + } + }, + "Microsoft.Extensions.Http": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Http.Resilience": { + "type": "CentralTransitive", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "5VawCrg+VgVT2hNurSSEWUnq0pvNoH+Zt82s5Wpl/8jdnmU8DpRlr+M3DcdtVgeBG7mRyk3GtSRbf8PB/HrL3w==", + "dependencies": { + "Microsoft.Extensions.Http.Diagnostics": "11.0.1", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Resilience": "11.0.1" + } + }, + "Microsoft.Extensions.Options": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + } + } + } +} \ No newline at end of file diff --git a/tests/DotBahn.Tests.Timetables/Client/TimetableClientTests.cs b/tests/DotBahn.Tests.Timetables/Client/TimetableClientTests.cs new file mode 100644 index 0000000..480f126 --- /dev/null +++ b/tests/DotBahn.Tests.Timetables/Client/TimetableClientTests.cs @@ -0,0 +1,119 @@ +using System.Diagnostics; +using System.Globalization; +using System.Net; +using DotBahn.Common.Auth; +using DotBahn.Common.Telemetry; +using DotBahn.Tests.Timetables.Support; +using DotBahn.Timetables; +using DotBahn.Timetables.Models; +using NSubstitute; +using Shouldly; + +namespace DotBahn.Tests.Timetables.Client; + +public class TimetableClientTests { + private const string EmptyXml = ""; + + [Theory] + [InlineData(2024, 12, 31, 23, 59, "/plan/8002549/241231/23")] + [InlineData(2000, 1, 1, 0, 0, "/plan/8002549/000101/00")] + [InlineData(1999, 12, 31, 12, 30, "/plan/8002549/991231/12")] + public async Task GetTimetableAsync_Should_RequestInvariantDateAndHour_When_Called(int year, int month, int day, int hour, int minute, string expectedPath) { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyXml, "application/xml"); + var dateTime = new DateTime(year, month, day, hour, minute, 0); + + await fixture.Client.GetTimetableAsync(8002549, dateTime, TestContext.Current.CancellationToken); + + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe($"https://api.example.com{expectedPath}"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task GetFullChangesAsync_Should_UseChanges_When_MergeOnProvided(bool mergeOnProvided) { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """""", "application/xml"); + var mergeOn = new Timetable { Station = "Old" }; + + var result = await fixture.Client.GetFullChangesAsync(8002549, mergeOnProvided ? mergeOn : null, TestContext.Current.CancellationToken); + + result.Station.ShouldBe(mergeOnProvided ? "Old" : "New"); + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe("https://api.example.com/fchg/8002549"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task GetRecentChangesAsync_Should_UseChanges_When_MergeOnProvided(bool mergeOnProvided) { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """""", "application/xml"); + var mergeOn = new Timetable { Station = "Old" }; + + var result = await fixture.Client.GetRecentChangesAsync(8002549, mergeOnProvided ? mergeOn : null, TestContext.Current.CancellationToken); + + result.Station.ShouldBe(mergeOnProvided ? "Old" : "New"); + fixture.Handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe("https://api.example.com/rchg/8002549"); + } + + [Theory] + [InlineData(HttpStatusCode.BadRequest, 400)] + [InlineData(HttpStatusCode.Unauthorized, 401)] + public async Task GetTimetableAsync_Should_ThrowHttpRequestException_When_ApiReturnsError(HttpStatusCode statusCode, int expectedCode) { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(statusCode, "error", "application/xml"); + + var exception = await Should.ThrowAsync(() => fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken)); + + exception.StatusCode.ShouldBe(statusCode); + exception.Message.ShouldContain(expectedCode.ToString()); + } + + [Fact] + public async Task GetTimetableAsync_Should_ThrowOperationCanceledException_When_Canceled() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyXml, "application/xml"); + using var cts = new CancellationTokenSource(); + await cts.CancelAsync(); + + await Should.ThrowAsync(() => fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, cts.Token)); + } + + [Theory] + [InlineData("")] + [InlineData("")] + public async Task GetTimetableAsync_Should_ThrowXmlException_When_XmlIsInvalid(string xml) { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, xml, "application/xml"); + + await Should.ThrowAsync(() => fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task GetTimetableAsync_Should_ReportTimetablesApiTag_When_ListenerIsActive() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyXml, "application/xml"); + var activities = new List(); + using var listener = new ActivityListener(); + listener.ShouldListenTo = source => source.Name == DotBahnTelemetry.SourceName; + listener.Sample = (ref _) => ActivitySamplingResult.AllDataAndRecorded; + listener.ActivityStarted = activities.Add; + ActivitySource.AddActivityListener(listener); + + await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + activities.ShouldContain(a => (string?)a.GetTagItem(DotBahnTelemetry.ApiTag) == "timetables"); + } + + [Fact] + public async Task GetTimetableAsync_Should_AuthorizeAndSetAcceptHeader_When_Called() { + var authorization = Substitute.For(); + using var fixture = new TimetableClientFixture(authorization); + fixture.Handler.RespondWith(HttpStatusCode.OK, EmptyXml, "application/xml"); + + await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + authorization.Received(1).AuthorizeRequest(Arg.Any()); + fixture.Handler.SentRequests.ShouldHaveSingleItem().Headers.Accept.ShouldContain(header => header.MediaType == "application/xml"); + } +} diff --git a/tests/DotBahn.Timetables.Tests/DotBahn.Timetables.Tests.csproj b/tests/DotBahn.Tests.Timetables/DotBahn.Tests.Timetables.csproj similarity index 59% rename from tests/DotBahn.Timetables.Tests/DotBahn.Timetables.Tests.csproj rename to tests/DotBahn.Tests.Timetables/DotBahn.Tests.Timetables.csproj index 894b46f..db71b5a 100644 --- a/tests/DotBahn.Timetables.Tests/DotBahn.Timetables.Tests.csproj +++ b/tests/DotBahn.Tests.Timetables/DotBahn.Tests.Timetables.csproj @@ -1,17 +1,20 @@ - + - + - + + + + $(NoWarn);CS0618 + - - + diff --git a/tests/DotBahn.Tests.Timetables/Extensions/ServiceCollectionExtensionsTests.cs b/tests/DotBahn.Tests.Timetables/Extensions/ServiceCollectionExtensionsTests.cs new file mode 100644 index 0000000..1ea35f0 --- /dev/null +++ b/tests/DotBahn.Tests.Timetables/Extensions/ServiceCollectionExtensionsTests.cs @@ -0,0 +1,75 @@ +using System.Net; +using DotBahn.Common.Auth; +using DotBahn.Tests.Shared.Http; +using DotBahn.Timetables; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Shouldly; + +namespace DotBahn.Tests.Timetables.Extensions; + +public class ServiceCollectionExtensionsTests { + [Fact] + public void AddDotBahnTimetables_Should_RegisterTimetableClient_When_Called() { + var (provider, _, _) = Create(); + using (provider) { + provider.GetRequiredService().ShouldNotBeNull(); + } + } + + [Fact] + public async Task GetTimetableAsync_Should_UseDefaultEndpoint_When_NoConfigurationProvided() { + var (provider, handler, client) = Create(); + await using (provider) { + handler.RespondWith(HttpStatusCode.OK, "", "application/xml"); + + await client.GetTimetableAsync(8002549, new DateTime(2024, 12, 31, 12, 0, 0), TestContext.Current.CancellationToken); + + handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe("https://apis.deutschebahn.com/db-api-marketplace/apis/timetables/v1/plan/8002549/241231/12"); + } + } + + [Theory] + [InlineData("https://api.example.com/", "https://api.example.com/plan/1/240101/00")] + [InlineData("https://example.org/timetables/v1/", "https://example.org/timetables/v1/plan/1/240101/00")] + public async Task GetTimetableAsync_Should_UseConfiguredEndpoint_When_ConfigurationProvided(string endpoint, string expectedUri) { + var (provider, handler, client) = Create(new Uri(endpoint)); + await using (provider) { + handler.RespondWith(HttpStatusCode.OK, "", "application/xml"); + + await client.GetTimetableAsync(1, new DateTime(2024, 1, 1, 0, 0, 0), TestContext.Current.CancellationToken); + + handler.SentRequests.ShouldHaveSingleItem().RequestUri!.ToString().ShouldBe(expectedUri); + } + } + + [Fact] + public async Task ValidateAsync_Should_RejectRelativeEndpoint_When_ValidationRuns() { + var services = new ServiceCollection(); + services.AddDotBahnTimetables(options => options.BaseEndpoint = new Uri("relative", UriKind.Relative)); + await using var provider = services.BuildServiceProvider(); + var validator = provider.GetRequiredService(); + + var exception = await Should.ThrowAsync(() => validator.ValidateAsync()); + + exception.Message.ShouldContain("DotBahn: BaseEndpoint must be an absolute URI."); + } + + private static (ServiceProvider Provider, FakeHttpHandler Handler, ITimetableClient Client) Create(Uri? endpoint = null) { + var handler = new FakeHttpHandler(); + var services = new ServiceCollection(); + services.AddSingleton(new ApiKeyAuthorization(new AuthorizationOptions { + ClientId = "client", + ApiKey = "key" + })); + services.AddDotBahnTimetables(options => { + if (endpoint != null) { + options.BaseEndpoint = endpoint; + } + }); + services.AddHttpClient("DotBahn.Timetables").ConfigurePrimaryHttpMessageHandler(() => handler); + + var provider = services.BuildServiceProvider(); + return (provider, handler, provider.GetRequiredService()); + } +} diff --git a/tests/DotBahn.Tests.Timetables/Merge/TimetableMergerTests.cs b/tests/DotBahn.Tests.Timetables/Merge/TimetableMergerTests.cs new file mode 100644 index 0000000..d9faeb2 --- /dev/null +++ b/tests/DotBahn.Tests.Timetables/Merge/TimetableMergerTests.cs @@ -0,0 +1,153 @@ +using System.Net; +using DotBahn.Common.Models; +using DotBahn.Tests.Timetables.Support; +using DotBahn.Timetables.Models; +using DotBahn.Timetables.Models.Enumerations; +using Shouldly; + +namespace DotBahn.Tests.Timetables.Merge; + +public class TimetableMergerTests { + [Fact] + public async Task GetFullChangesAsync_Should_AddNewStop_When_MergeOnProvided() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """""", "application/xml"); + var current = new Timetable { + Station = "Old" + }; + + var result = await fixture.Client.GetFullChangesAsync(1, current, TestContext.Current.CancellationToken); + + result.Station.ShouldBe("Old"); + result.Stops.ShouldHaveSingleItem().Id.ShouldBe("new-stop"); + } + + [Fact] + public async Task GetFullChangesAsync_Should_MergeExistingStop_When_SameIdProvided() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """ + + + + """, "application/xml"); + var current = new Timetable { + Station = "Old", + Stops = [Stop("1", departure: Event(platform: "3"))] + }; + + var result = await fixture.Client.GetFullChangesAsync(1, current, TestContext.Current.CancellationToken); + + var stop = result.Stops.ShouldHaveSingleItem(); + stop.Id.ShouldBe("1"); + stop.Departure!.Platform.Original.ShouldBe("3"); + stop.Departure.Platform.Updated.ShouldBe("5"); + stop.Departure.Status.Updated!.Value.ShouldBe(EventStatus.Cancelled); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task GetFullChangesAsync_Should_MergeEvent_When_OnlyOneSideHasEvent(bool currentHasEvent) { + using var fixture = new TimetableClientFixture(); + var xml = currentHasEvent ? """""" : """"""; + fixture.Handler.RespondWith(HttpStatusCode.OK, xml, "application/xml"); + var current = new Timetable { + Station = "Old", + Stops = [Stop("1", departure: currentHasEvent ? Event() : null)] + }; + + var result = await fixture.Client.GetFullChangesAsync(1, current, TestContext.Current.CancellationToken); + + if (currentHasEvent) { + result.Stops.ShouldHaveSingleItem().Departure.ShouldBeNull(); + } else { + result.Stops.ShouldHaveSingleItem().Departure.ShouldNotBeNull(); + } + } + + [Fact] + public async Task GetFullChangesAsync_Should_KeepCurrentWings_When_ChangeHasNone() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """""", "application/xml"); + var current = new Timetable { + Station = "Old", + Stops = [Stop("1", departure: Event(wings: ["W1", "W2"]))] + }; + + var result = await fixture.Client.GetFullChangesAsync(1, current, TestContext.Current.CancellationToken); + + result.Stops.ShouldHaveSingleItem().Departure!.Wings.ShouldBe(["W1", "W2"]); + } + + [Fact] + public async Task GetRecentChangesAsync_Should_AppendMessages_WithoutDuplicates() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """ + + + + """, "application/xml"); + var current = new Timetable { + Station = "Old", + Stops = [Stop("1", messages: [Message("m1"), Message("old")])] + }; + + var result = await fixture.Client.GetRecentChangesAsync(1, current, TestContext.Current.CancellationToken); + + result.Stops.ShouldHaveSingleItem().Messages.Select(m => m.Id).ShouldBe(["m1", "old", "m2"]); + } + + [Fact] + public async Task GetFullChangesAsync_Should_IgnoreUpdatesEqualToOriginal_When_MergingValues() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, + """""", "application/xml"); + var current = new Timetable { + Station = "Old", + Stops = [Stop("1", departure: Event(platform: "3", time: new DateTime(2024, 12, 31, 12, 0, 0)))] + }; + + var result = await fixture.Client.GetFullChangesAsync(1, current, TestContext.Current.CancellationToken); + + var departure = result.Stops.ShouldHaveSingleItem().Departure!; + departure.Platform.HasUpdate.ShouldBeFalse(); + departure.Time.HasUpdate.ShouldBeFalse(); + } + + [Fact] + public async Task GetFullChangesAsync_Should_UseLastCurrentStop_When_DuplicateIdsExist() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """""", "application/xml"); + var current = new Timetable { + Station = "Old", + Stops = [Stop("1", departure: Event(platform: "first")), Stop("1", departure: Event(platform: "last"))] + }; + + var result = await fixture.Client.GetFullChangesAsync(1, current, TestContext.Current.CancellationToken); + + result.Stops.ShouldHaveSingleItem().Departure!.Platform.Original.ShouldBe("last"); + } + + private static TimetableStop Stop(string id, TrainEvent? arrival = null, TrainEvent? departure = null, TimetableMessage[]? messages = null) => new() { + Id = id, + Train = new TrainLabel { Category = "ICE", Number = "1", Owner = "DB" }, + Arrival = arrival, + Departure = departure, + Messages = messages ?? [] + }; + + private static TrainEvent Event(DateTime? time = null, string platform = "3", string[]? wings = null) => new() { + Time = new ChangedValue { Original = time ?? new DateTime(2024, 1, 1, 12, 0, 0) }, + Platform = new ChangedRef { Original = platform }, + Status = new ChangedValue { Original = EventStatus.Planned }, + DistantEndpoint = new ChangedRef { Original = string.Empty }, + Path = new ChangedRef> { Original = [] }, + Wings = wings ?? [] + }; + + private static TimetableMessage Message(string id) => new() { + Id = id, + Type = MessageType.Him, + Timestamp = new DateTime(2024, 1, 1) + }; +} diff --git a/tests/DotBahn.Tests.Timetables/Models/TimetableModelTests.cs b/tests/DotBahn.Tests.Timetables/Models/TimetableModelTests.cs new file mode 100644 index 0000000..2febe00 --- /dev/null +++ b/tests/DotBahn.Tests.Timetables/Models/TimetableModelTests.cs @@ -0,0 +1,88 @@ +using DotBahn.Common.Models; +using DotBahn.Timetables.Models; +using DotBahn.Timetables.Models.Enumerations; +using Shouldly; + +namespace DotBahn.Tests.Timetables.Models; + +public class TimetableModelTests { + [Theory] + [InlineData(true, false, true, false, false)] + [InlineData(false, true, false, true, false)] + [InlineData(true, true, false, false, true)] + [InlineData(false, false, false, false, false)] + public void StopFlags_Should_ReflectEventPresence(bool hasArrival, bool hasDeparture, bool arrivalOnly, bool departureOnly, bool through) { + var sut = CreateStop(hasArrival, hasDeparture); + + sut.IsArrivalOnly.ShouldBe(arrivalOnly); + sut.IsDepartureOnly.ShouldBe(departureOnly); + sut.IsThrough.ShouldBe(through); + } + + [Theory] + [InlineData(null, "ICE123")] + [InlineData("", "ICE123")] + [InlineData(" ", "ICE123")] + [InlineData("RE14", "RE14")] + public void DisplayName_Should_PreferLine_When_ItIsNotWhitespace(string? line, string expected) { + var sut = new TrainLabel { + Category = "ICE", + Number = "123", + Owner = "DB", + Line = line + }; + + sut.DisplayName.ShouldBe(expected); + } + + [Theory] + [InlineData(null, null, true)] + [InlineData(null, 1, true)] + [InlineData(null, -1, false)] + [InlineData(true, 1, false)] + public void IsActive_Should_DependOnDeletionAndValidity(bool? deleted, int? validToDaysFromNow, bool expected) { + var sut = new TimetableMessage { + Id = "m1", + Type = MessageType.Him, + Timestamp = DateTime.UnixEpoch, + IsDeleted = deleted ?? false, + ValidTo = validToDaysFromNow.HasValue ? DateTime.Now.AddDays(validToDaysFromNow.Value) : null + }; + + sut.IsActive.ShouldBe(expected); + } + + [Theory] + [InlineData(null, null, null)] + [InlineData("internal", null, "internal")] + [InlineData("internal", "external", "external")] + public void Text_Should_PreferExternalText_When_Present(string? internalText, string? externalText, string? expected) { + var sut = new TimetableMessage { + Id = "m1", + Type = MessageType.Him, + Timestamp = DateTime.UnixEpoch, + InternalText = internalText, + ExternalText = externalText + }; + + sut.Text.ShouldBe(expected); + } + + private static TimetableStop CreateStop(bool hasArrival, bool hasDeparture) { + var train = new TrainLabel { Category = "ICE", Number = "1", Owner = "DB" }; + var arrival = hasArrival ? new TrainEvent { + Time = new ChangedValue { Original = DateTime.UnixEpoch }, + Platform = new ChangedRef { Original = "1" }, + Status = new ChangedValue { Original = EventStatus.Planned }, + DistantEndpoint = new ChangedRef { Original = string.Empty } + } : null; + var departure = hasDeparture ? new TrainEvent { + Time = new ChangedValue { Original = DateTime.UnixEpoch }, + Platform = new ChangedRef { Original = "1" }, + Status = new ChangedValue { Original = EventStatus.Planned }, + DistantEndpoint = new ChangedRef { Original = string.Empty } + } : null; + + return new TimetableStop { Id = "1", Train = train, Arrival = arrival, Departure = departure }; + } +} diff --git a/tests/DotBahn.Tests.Timetables/Parsing/TimetableXmlParserTests.cs b/tests/DotBahn.Tests.Timetables/Parsing/TimetableXmlParserTests.cs new file mode 100644 index 0000000..b787132 --- /dev/null +++ b/tests/DotBahn.Tests.Timetables/Parsing/TimetableXmlParserTests.cs @@ -0,0 +1,102 @@ +using System.Net; +using DotBahn.Tests.Timetables.Support; +using DotBahn.Timetables.Models; +using Shouldly; + +namespace DotBahn.Tests.Timetables.Parsing; + +public class TimetableXmlParserTests { + [Theory] + [InlineData("")] + [InlineData(" ")] + public async Task GetTimetableAsync_Should_ReturnEmptyTimetable_When_InputIsEmpty(string xml) { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, xml, "application/xml"); + + var result = await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + result.Station.ShouldBeEmpty(); + result.Stops.ShouldBeEmpty(); + result.Messages.ShouldBeEmpty(); + } + + [Theory] + [InlineData("""""")] + [InlineData("""""")] + public async Task GetTimetableAsync_Should_ReturnEmptyTimetable_When_RootIsNotTimetable(string xml) { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, xml, "application/xml"); + + var result = await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + result.Station.ShouldBeEmpty(); + result.Stops.ShouldBeEmpty(); + } + + [Fact] + public async Task GetTimetableAsync_Should_ParseStationAndStops_When_AttributesProvided() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """ + + + + + """, "application/xml"); + + var result = await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + result.Station.ShouldBe("Hamburg"); + var stops = result.Stops.ToList(); + stops.Count.ShouldBe(2); + stops[0].Id.ShouldBe("stop-1"); + stops[1].Id.ShouldBe("stop-2"); + } + + [Fact] + public async Task GetTimetableAsync_Should_ThrowXmlException_When_StopIdIsMissing() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, "", "application/xml"); + + var exception = await Should.ThrowAsync(() => fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken)); + + exception.Message.ShouldContain("Missing required attribute 'id'"); + } + + [Fact] + public async Task GetTimetableAsync_Should_SetMessagesNull_When_StopHasNoMessages() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, "", "application/xml"); + + var result = await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + result.Stops.ShouldHaveSingleItem().Messages.ShouldBeEmpty(); + } + + [Fact] + public async Task GetTimetableAsync_Should_ParseMessageAttributes_When_MessageProvided() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """ + + Bauarbeiten + + """, "application/xml"); + + var result = await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + var message = result.Stops.ShouldHaveSingleItem().Messages.ShouldHaveSingleItem(); + message.Id.ShouldBe("m1"); + message.Type.ShouldBe(DotBahn.Timetables.Models.Enumerations.MessageType.QualityChange); + message.Timestamp.ShouldBe(new DateTime(2024, 12, 31, 12, 0, 0)); + message.ValidFrom.ShouldBe(new DateTime(2024, 12, 31, 11, 0, 0)); + message.ValidTo.ShouldBe(new DateTime(2024, 12, 31, 13, 0, 0)); + message.Code.ShouldBe(42); + message.Priority.ShouldBe(DotBahn.Timetables.Models.Enumerations.MessagePriority.Medium); + message.Owner.ShouldBe("DB"); + message.Category.ShouldBe("C"); + message.ExternalCategory.ShouldBe("E"); + message.InternalText.ShouldBe("Bauarbeiten"); + message.ExternalText.ShouldBeNull(); + message.IsDeleted.ShouldBeTrue(); + } +} diff --git a/tests/DotBahn.Tests.Timetables/Support/TimetableClientFixture.cs b/tests/DotBahn.Tests.Timetables/Support/TimetableClientFixture.cs new file mode 100644 index 0000000..d236645 --- /dev/null +++ b/tests/DotBahn.Tests.Timetables/Support/TimetableClientFixture.cs @@ -0,0 +1,33 @@ +using DotBahn.Common.Auth; +using DotBahn.Common.Clients; +using DotBahn.Tests.Shared.Http; +using DotBahn.Timetables; +using Microsoft.Extensions.DependencyInjection; + +namespace DotBahn.Tests.Timetables.Support; + +internal sealed class TimetableClientFixture : IDisposable { + private readonly ServiceProvider _provider; + + public FakeHttpHandler Handler { get; } = new(); + + public ITimetableClient Client { get; } + + public TimetableClientFixture(IAuthorization? authorization = null, Action? configure = null) { + var services = new ServiceCollection(); + services.AddSingleton(authorization ?? new ApiKeyAuthorization(new AuthorizationOptions { + ClientId = "client", + ApiKey = "key" + })); + services.AddDotBahnTimetables(options => { + options.BaseEndpoint = new Uri("https://api.example.com/"); + configure?.Invoke(options); + }); + services.AddHttpClient("DotBahn.Timetables").ConfigurePrimaryHttpMessageHandler(() => Handler); + + _provider = services.BuildServiceProvider(); + Client = _provider.GetRequiredService(); + } + + public void Dispose() => _provider.Dispose(); +} diff --git a/tests/DotBahn.Tests.Timetables/Transform/TimetableTransformerTests.cs b/tests/DotBahn.Tests.Timetables/Transform/TimetableTransformerTests.cs new file mode 100644 index 0000000..2856006 --- /dev/null +++ b/tests/DotBahn.Tests.Timetables/Transform/TimetableTransformerTests.cs @@ -0,0 +1,188 @@ +using System.Net; +using DotBahn.Tests.Timetables.Support; +using DotBahn.Timetables.Models; +using DotBahn.Timetables.Models.Enumerations; +using Shouldly; + +namespace DotBahn.Tests.Timetables.Transform; + +public class TimetableTransformerTests { + [Theory] + [InlineData("2412311200", 2024, 12, 31, 12, 0)] + [InlineData("0001010000", 2000, 1, 1, 0, 0)] + [InlineData("9912312359", 1999, 12, 31, 23, 59)] + [InlineData("", 1, 1, 1, 0, 0)] + [InlineData("not-a-time", 1, 1, 1, 0, 0)] + public async Task GetTimetableAsync_Should_ParsePlannedTime_When_ValueProvided(string time, int year, int month, int day, int hour, int minute) { + var departure = await GetDepartureAsync($""""""); + + var expected = year == 1 ? default : new DateTime(year, month, day, hour, minute, 0); + departure.Time.Original.ShouldBe(expected); + departure.Time.HasUpdate.ShouldBeFalse(); + } + + [Theory] + [InlineData("2412311300", 2024, 12, 31, 13)] + [InlineData("bad", 2024, 12, 31, 12)] + [InlineData("null", 2024, 12, 31, 12)] + public async Task GetTimetableAsync_Should_ParseChangedTime_When_ValueProvided(string time, int year, int month, int day, int hour) { + var attribute = time == "null" ? string.Empty : $" ct=\"{time}\""; + var departure = await GetDepartureAsync($""""""); + + var hasUpdate = time != "bad" && time != "null"; + departure.Time.HasUpdate.ShouldBe(hasUpdate); + if (hasUpdate) { + departure.Time.Updated!.Value.ShouldBe(new DateTime(year, month, day, hour, 0, 0)); + } + } + + [Theory] + [InlineData("p", EventStatus.Planned)] + [InlineData("a", EventStatus.Added)] + [InlineData("c", EventStatus.Cancelled)] + [InlineData("x", EventStatus.Unknown)] + public async Task GetTimetableAsync_Should_ParsePlannedStatus_When_ValueProvided(string status, EventStatus expected) { + var departure = await GetDepartureAsync($""""""); + + departure.Status.Original.ShouldBe(expected); + } + + [Theory] + [InlineData("c", true)] + [InlineData("a", true)] + [InlineData("x", false)] + [InlineData("null", false)] + public async Task GetTimetableAsync_Should_SetChangedStatus_When_ValueIsKnown(string status, bool hasUpdate) { + var attribute = status == "null" ? string.Empty : $" cs=\"{status}\""; + var departure = await GetDepartureAsync($""""""); + + departure.Status.HasUpdate.ShouldBe(hasUpdate); + if (hasUpdate) { + departure.Status.Updated!.Value.ShouldNotBe(EventStatus.Unknown); + } + } + + [Theory] + [InlineData("A|B|C", 3)] + [InlineData("A||B", 2)] + [InlineData("", 0)] + [InlineData("null", 0)] + public async Task GetTimetableAsync_Should_ParsePipeSeparatedPath_When_ValueProvided(string path, int expectedCount) { + var attribute = path == "null" ? string.Empty : $" ppth=\"{path}\""; + var departure = await GetDepartureAsync($""""""); + + departure.Path.Original.Count().ShouldBe(expectedCount); + departure.Path.HasUpdate.ShouldBeFalse(); + } + + [Fact] + public async Task GetTimetableAsync_Should_SetChangedPath_When_ChangedPathProvided() { + var departure = await GetDepartureAsync(""""""); + + departure.Path.HasUpdate.ShouldBeTrue(); + departure.Path.Updated!.ShouldBe(new[] { "C", "D" }); + } + + [Theory] + [InlineData("p", TripType.Passenger)] + [InlineData("e", TripType.Empty)] + [InlineData("z", TripType.Z)] + [InlineData("s", TripType.S)] + [InlineData("h", TripType.H)] + [InlineData("n", TripType.N)] + [InlineData("x", TripType.Passenger)] + [InlineData("null", null)] + public async Task GetTimetableAsync_Should_ParseTripType_When_ValueProvided(string type, TripType? expected) { + using var fixture = new TimetableClientFixture(); + var attribute = type == "null" ? string.Empty : $" t=\"{type}\""; + fixture.Handler.RespondWith(HttpStatusCode.OK, $"""""", "application/xml"); + + var result = await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + result.Stops.ShouldHaveSingleItem().Train.Type.ShouldBe(expected); + } + + [Fact] + public async Task GetTimetableAsync_Should_PreferDepartureLine_When_BothEventsProvideLine() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """ + + + + """, "application/xml"); + + var result = await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + result.Stops.ShouldHaveSingleItem().Train.Line.ShouldBe("DP-LINE"); + } + + [Fact] + public async Task GetTimetableAsync_Should_FallBackToArrivalLine_When_DepartureHasNoLine() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, """ + + + + """, "application/xml"); + + var result = await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + result.Stops.ShouldHaveSingleItem().Train.Line.ShouldBe("AR-LINE"); + } + + [Theory] + [InlineData("1", true)] + [InlineData("0", false)] + [InlineData("null", false)] + public async Task GetTimetableAsync_Should_AssignMessageText_When_InternalFlagProvided(string internalFlag, bool isInternal) { + using var fixture = new TimetableClientFixture(); + var attribute = internalFlag == "null" ? string.Empty : $" int=\"{internalFlag}\""; + fixture.Handler.RespondWith(HttpStatusCode.OK, $"""Text""", "application/xml"); + + var result = await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + var message = result.Stops.ShouldHaveSingleItem().Messages.ShouldHaveSingleItem(); + message.InternalText.ShouldBe(isInternal ? "Text" : null); + message.ExternalText.ShouldBe(isInternal ? null : "Text"); + } + + [Theory] + [InlineData("42", 42)] + [InlineData("abc", null)] + [InlineData("null", null)] + public async Task GetTimetableAsync_Should_ParseMessageCode_When_ValueProvided(string code, int? expected) { + using var fixture = new TimetableClientFixture(); + var attribute = code == "null" ? string.Empty : $" c=\"{code}\""; + fixture.Handler.RespondWith(HttpStatusCode.OK, $"""""", "application/xml"); + + var result = await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + result.Stops.ShouldHaveSingleItem().Messages.ShouldHaveSingleItem().Code.ShouldBe(expected); + } + + [Fact] + public async Task GetTimetableAsync_Should_UseDefaults_When_StopHasNoOptionalParts() { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, "", "application/xml"); + + var result = await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + var stop = result.Stops.ShouldHaveSingleItem(); + stop.Arrival.ShouldBeNull(); + stop.Departure.ShouldBeNull(); + stop.Train.Category.ShouldBeEmpty(); + stop.Train.Number.ShouldBeEmpty(); + stop.Train.Owner.ShouldBeEmpty(); + stop.Train.Type.ShouldBeNull(); + } + + private static async Task GetDepartureAsync(string eventXml) { + using var fixture = new TimetableClientFixture(); + fixture.Handler.RespondWith(HttpStatusCode.OK, + $"{eventXml}", "application/xml"); + + var result = await fixture.Client.GetTimetableAsync(1, DateTime.UnixEpoch, TestContext.Current.CancellationToken); + + return result.Stops.ShouldHaveSingleItem().Departure!; + } +} diff --git a/tests/DotBahn.Tests.Timetables/packages.lock.json b/tests/DotBahn.Tests.Timetables/packages.lock.json new file mode 100644 index 0000000..709209e --- /dev/null +++ b/tests/DotBahn.Tests.Timetables/packages.lock.json @@ -0,0 +1,543 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.Testing.Extensions.CodeCoverage": { + "type": "Direct", + "requested": "[18.12.0, )", + "resolved": "18.12.0", + "contentHash": "BST/sWYpKk9OXO7Yxktcg6FWORRsHU0EdCbMwZ7d3OqJsMKlrNHIZ30g0Ib4k5T5acJYXRBmg9mNrTU/N6cy1g==", + "dependencies": { + "Microsoft.DiaSymReader": "2.2.10", + "Microsoft.Extensions.DependencyModel": "10.0.10", + "Microsoft.Testing.Platform": "2.5.0", + "Mono.Cecil": "0.11.6" + } + }, + "MinVer": { + "type": "Direct", + "requested": "[8.0.0, )", + "resolved": "8.0.0", + "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" + }, + "NSubstitute": { + "type": "Direct", + "requested": "[6.2.0, )", + "resolved": "6.2.0", + "contentHash": "05oaAmBAvYYUQb/NTb9/kWBDjq0iS772X4t428WJcHRcH+5ULJx6rTbEvqkZJBIHWRLI8MlU3et3F5/gkEHKIw==", + "dependencies": { + "Castle.Core": "5.1.1" + } + }, + "Shouldly": { + "type": "Direct", + "requested": "[4.3.0, )", + "resolved": "4.3.0", + "contentHash": "sDetrWXrl6YXZ4HeLsdBoNk3uIa7K+V4uvIJ+cqdRa5DrFxeTED7VkjoxCuU1kJWpUuBDZz2QXFzSxBtVXLwRQ==", + "dependencies": { + "DiffEngine": "11.3.0", + "EmptyFiles": "4.4.0" + } + }, + "xunit.v3": { + "type": "Direct", + "requested": "[4.0.3, )", + "resolved": "4.0.3", + "contentHash": "GxBopTuV5aU7NS0iE1P6I6YCQscIAP0iIyyZqZhs1c8Ry3cdiOouEtQQpX8cA7E1gEnKGRMNA+7NlhBy13AEyg==", + "dependencies": { + "xunit.v3.mtp-v2": "[4.0.3]" + } + }, + "xunit.v3.runner.common": { + "type": "Direct", + "requested": "[4.0.3, )", + "resolved": "4.0.3", + "contentHash": "J/kkhBgJg3wu1xI8gY2Esm3oRE47gNrGmKpT/XZDPOzZ3/F33yTK/ZH1CM6qDpAHoTT3GY/JgrVbS4T1JEKYiQ==", + "dependencies": { + "Microsoft.Win32.Registry": "[5.0.0]", + "System.Security.AccessControl": "[6.0.1]", + "xunit.v3.common": "[4.0.3]" + } + }, + "Castle.Core": { + "type": "Transitive", + "resolved": "5.1.1", + "contentHash": "rpYtIczkzGpf+EkZgDr9CClTdemhsrwA/W5hMoPjLkRFnXzH44zDLoovXeKtmxb1ykXK9aJVODSpiJml8CTw2g==", + "dependencies": { + "System.Diagnostics.EventLog": "6.0.0" + } + }, + "DiffEngine": { + "type": "Transitive", + "resolved": "11.3.0", + "contentHash": "k0ZgZqd09jLZQjR8FyQbSQE86Q7QZnjEzq1LPHtj1R2AoWO8sjV5x+jlSisL7NZAbUOI4y+7Bog8gkr9WIRBGw==", + "dependencies": { + "EmptyFiles": "4.4.0", + "System.Management": "6.0.1" + } + }, + "EmptyFiles": { + "type": "Transitive", + "resolved": "4.4.0", + "contentHash": "gwJEfIGS7FhykvtZoscwXj/XwW+mJY6UbAZk+qtLKFUGWC95kfKXnj8VkxsZQnWBxJemM/q664rGLN5nf+OHZw==" + }, + "Microsoft.ApplicationInsights": { + "type": "Transitive", + "resolved": "2.23.0", + "contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw==" + }, + "Microsoft.Bcl.AsyncInterfaces": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg==" + }, + "Microsoft.DiaSymReader": { + "type": "Transitive", + "resolved": "2.2.10", + "contentHash": "zmGsm6b2y3STDa/Of7rdkkfTDV8VuGB8aCqIkLoJIQh5tL78K3zJ8OUyFKnfsaORXmGr9iOKwDkZfUjeXi+CwA==" + }, + "Microsoft.Extensions.AmbientMetadata.Application": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "tm28s2ODWZ6RdysP06NI3B23DUY5OfHG35ihMHxVAO3hywZAczDVjrkYMfBY//J4HQqfDHS5op84BhnF7ROseQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Compliance.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "DUwdXgIxJKH9zBNg/SUBqOX0FpXCq7w80CIzrr0Jcw5tBXS926AtCcidoAsEHq5e/c6KQ8rWhSt7NxFxak8N/Q==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15" + } + }, + "Microsoft.Extensions.Compliance.Redaction": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "2rwe98yZEn4+aXjAg5DdcROMg6m2w3tejf/mRk4/fBCHKM2EWCaFTmbHLtz1BfyBxMY00/08XFoN0wzWYNiSiQ==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.Configuration": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "VQS/GkFU9oLQmXZv0AR/zluF0YAbEAoUQ5aYMqcRc2TWeKa6m2AjInAOnDhCcoWI5a6LQUCzTcl8B3DZZaPZLg==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "oyBSWnEsEi9SZTiwAfuKIdVIiEZ7TvNOtdFaGqyzF9WtomNV+uZHCqhQbnz/ipjtM50BYJ4s0MWbYafolq2mAg==", + "dependencies": { + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "3eoaKF4Stat1PSN+KFwqmy04sM9DwGuHM1o1lHwuNFM/TqwQ+PCIvaQHS4lcT3kJl5rwvDK4w/rIlR0wc024eQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "KygQMITBDDPXw7+AAgdwQvVAaTXuDsc1iCAuvhO73ERxKX+d92cdbgZmpoYF7DIUq2hfs/yO2KD87uIreRy3MA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" + }, + "Microsoft.Extensions.DependencyInjection.AutoActivation": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "OuVIF5TmsfonN2Fqmi2zlUtbFQNqQiflhgo/rh64ptrqYrB4wZLwKbXr/HzrQXMf+h3jIbWrjIdJFspGqcvuuQ==", + "dependencies": { + "Microsoft.Extensions.Hosting.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.DependencyModel": { + "type": "Transitive", + "resolved": "10.0.10", + "contentHash": "rfZA1RjR021RPqSmIPovfz2aOd79TGqJ9BengbjnzIISOVwjLmuSDnhCMmiY/1c6iYvGolQ1iNGzkav0u11XEA==" + }, + "Microsoft.Extensions.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "tX8piU+KbYHXIf5F70leczIWwtTkPKhyjRqjbo6D2uTA1PwrhcMD+Ls7rzqSMkx1U3osyrD4/kCrZeF13Lkgnw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "11.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "11.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "o188Hh1AqAI91K+R8eY3REW5HzofGastQk8OPLIy4uS8FnJo4Niok/X+HH/nHRO1ApsxW7q1yYFoHDpAZC36fA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mqqpmAFNRLa4cozN3RvT/T81k4aarwMc8xb8VVQgLqUE7AAoN/WWayZAvP+4hy9+KujP3dfn3taU06fZJPIbgA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.FileProviders.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "1RSYAUtJeb76m2T0u5BbvwKY3s+ge9fT3cj1odvo5Bm+frc7pU9RSeXeMIlYHV8GjpqLdv2neeeomz010yYL8A==", + "dependencies": { + "Microsoft.Extensions.Primitives": "10.0.15" + } + }, + "Microsoft.Extensions.Hosting.Abstractions": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "s/JBiwR3F/vKRCbe6WO5b6t6or1ISaZ3rllchcw6/FSWZmK8s2fAzD7elrZo7592FnMD1fhGoG/wuJL1YYtVXw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.15", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15" + } + }, + "Microsoft.Extensions.Http.Diagnostics": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "mKHY0oFYL3fkAOhBNi2LqWPuEdUJ+HiF28KKUwBkQG2sgXAUdFDDqvJAfu2PcYgtAwsAtl58zuk4SElpPzbCvA==", + "dependencies": { + "Microsoft.Extensions.Compliance.Redaction": "11.0.1", + "Microsoft.Extensions.Http": "10.0.15", + "Microsoft.Extensions.Telemetry": "11.0.1" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "zsse8MOgo0bj2KAEsSkg9WtNAfZbHbTlGeqfhy5PGozomM3zQM0XzumSQzQ0451IWNSJWLqYaSIQEpCi2j1sCA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Logging.Configuration": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "Km6Ml1/nu0T/f80Btonxf9CWmP/BXI84aJwC5fUbCxRArJ0lH++0ADQrjErZvsSIrKhusTkTSGBChKy2fYAF4w==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.15", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.15", + "Microsoft.Extensions.Configuration.Binder": "10.0.15", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.15", + "Microsoft.Extensions.Logging": "10.0.15", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15" + } + }, + "Microsoft.Extensions.ObjectPool": { + "type": "Transitive", + "resolved": "10.0.15", + "contentHash": "kvd9eyRRQ+OEu9wik7GKgTS+7XnJ5XoOtSXJqmkJtVYV/S4gsBUrobYRSdNeBcb0ymef4L5Q9pZGiTxJ8jJfyQ==" + }, + "Microsoft.Extensions.Options.ConfigurationExtensions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "s4JrxDPwxk8pE6LFVj+M5TrDHxOVIoCnQBy5lexs5uAYeggPYwAc/pSDNgVuZN14pCmZGCInygI/2ylCdLYShw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.Configuration.Binder": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" + }, + "Microsoft.Extensions.Resilience": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "xgKof6iwAByZNrxWOa7Drk4A953L7U2HleTmx7EXE2Vf6j1crp4RsvNlIVsJMtHKf3ftGKd9gOhR3xES9vxUgg==", + "dependencies": { + "Microsoft.Extensions.Diagnostics": "10.0.15", + "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "11.0.1", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1", + "Polly.Extensions": "8.4.2", + "Polly.RateLimiting": "8.4.2" + } + }, + "Microsoft.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "9uuA8entTC9m00m59h6CACSt4IQh9KknB+hPvCteXUTiG67lqJ8BI65fEUJSPSfT3ZDDi01Zg2aY5kRUvD4HPw==", + "dependencies": { + "Microsoft.Extensions.AmbientMetadata.Application": "11.0.1", + "Microsoft.Extensions.DependencyInjection.AutoActivation": "11.0.1", + "Microsoft.Extensions.Logging.Configuration": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Telemetry.Abstractions": "11.0.1" + } + }, + "Microsoft.Extensions.Telemetry.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "qINZz4G01Wxumqd0hLr6YdzPa3s7jexQWN28EenaiJQnmKdsR9FnBaKENdRRElLc+A5bJKQ+jYw/WHG4ZpIyAg==", + "dependencies": { + "Microsoft.Extensions.Compliance.Abstractions": "11.0.1", + "Microsoft.Extensions.Logging.Abstractions": "10.0.15", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Options": "10.0.15" + } + }, + "Microsoft.Testing.Extensions.Telemetry": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "j1XGKCBrmfNm0tmotMa05GlqVtb2cW5UaMkKCFHPyyFHz5rdOy7TD0SVXnZJ+QMrjPAHjRoRqn5qcsUjICSWwg==", + "dependencies": { + "Microsoft.ApplicationInsights": "2.23.0", + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Testing.Extensions.TrxReport.Abstractions": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "+xTIaIU9H44GxOyjrfieMSZnxltGvleA3jCRtdEAzlXKb85pMmVYMLUv2JS8KwD+U2wQHUgvy5YfQfWoPEfVdQ==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Testing.Platform": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "ocX0rgGY78dKfmZlZe4hB0/dvlh7wJgUAWS+KfwrqxB9DpNsjshnne9dppCKnFNEOkX4QYsrdUU++NInFPiCBw==" + }, + "Microsoft.Testing.Platform.MSBuild": { + "type": "Transitive", + "resolved": "2.5.2", + "contentHash": "Jey2v0hd7WHHa7pr6MRNKtA07FvxcOMTCtIhTI7uBZ/qR5m1mgCVCo5L1rtVAtqgMhGA205bUwq9+is4LiCzpw==", + "dependencies": { + "Microsoft.Testing.Platform": "[2.5.2, 3.0.0)" + } + }, + "Microsoft.Win32.Registry": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg==" + }, + "Mono.Cecil": { + "type": "Transitive", + "resolved": "0.11.6", + "contentHash": "f33RkDtZO8VlGXCtmQIviOtxgnUdym9xx/b1p9h91CRGOsJFxCFOFK1FDbVt1OCf1aWwYejUFa2MOQyFWTFjbA==" + }, + "Polly.Core": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g==" + }, + "Polly.Extensions": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==", + "dependencies": { + "Microsoft.Extensions.Logging.Abstractions": "8.0.0", + "Microsoft.Extensions.Options": "8.0.0", + "Polly.Core": "8.4.2" + } + }, + "Polly.RateLimiting": { + "type": "Transitive", + "resolved": "8.4.2", + "contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==", + "dependencies": { + "Polly.Core": "8.4.2", + "System.Threading.RateLimiting": "8.0.0" + } + }, + "System.CodeDom": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "CPc6tWO1LAer3IzfZufDBRL+UZQcj5uS207NHALQzP84Vp/z6wF0Aa0YZImOQY8iStY0A2zI/e3ihKNPfUm8XA==" + }, + "System.Diagnostics.DiagnosticSource": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" + }, + "System.Diagnostics.EventLog": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "lcyUiXTsETK2ALsZrX+nWuHSIQeazhqPphLfaRxzdGaG93+0kELqpgEHtwWOlQe7+jSFnKwaCAgL4kjeZCQJnw==" + }, + "System.Management": { + "type": "Transitive", + "resolved": "6.0.1", + "contentHash": "10J1D0h/lioojphfJ4Fuh5ZUThT/xOVHdV9roGBittKKNP2PMjrvibEdbVTGZcPra1399Ja3tqIJLyQrc5Wmhg==", + "dependencies": { + "System.CodeDom": "6.0.0" + } + }, + "System.Security.AccessControl": { + "type": "Transitive", + "resolved": "6.0.1", + "contentHash": "IQ4NXP/B3Ayzvw0rDQzVTYsCKyy0Jp9KI6aYcK7UnGVlR9+Awz++TIPCQtPYfLJfOpm8ajowMR09V7quD3sEHw==" + }, + "System.Threading.RateLimiting": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q==" + }, + "xunit.analyzers": { + "type": "Transitive", + "resolved": "2.3.0", + "contentHash": "FcuLqoNBgQA4MmQXOdNWsDnlw+LBysWUcWOql6MCTXXFJZPn+qjbxHA9F9KBRiPH0Y97MLr1VE6LxdH8MgKUoQ==" + }, + "xunit.v3.assert": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "RrlWQ3yXla+ud9JBWDIY9GnUS/DS44r3ObqqV7wdWt1GhS+SveCe0MBDL238VXYoV2mWnX/DhO2LdTq5FTlT7g==" + }, + "xunit.v3.common": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "+2qGz3rcveIxzbXeZVHU8dhMyaawt01mgm/zv1FJH2FPcvJpfTUqc1vQ3hK2V5zVt8QEDddA+B6fkf9/LWf/Pg==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "6.0.0" + } + }, + "xunit.v3.core.mtp-v2": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "CsmxEanMln1chMExl6TUjnH5kF0XUDb/SqWKXqnGD8UjpkZARAXi8JDtsUYdxuROcIIdwEfs3iHZeHmTeA8DUA==", + "dependencies": { + "Microsoft.Testing.Extensions.Telemetry": "2.5.2", + "Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.5.2", + "Microsoft.Testing.Platform": "2.5.2", + "Microsoft.Testing.Platform.MSBuild": "2.5.2", + "xunit.v3.extensibility.core": "[4.0.3]", + "xunit.v3.runner.inproc.console": "[4.0.3]" + } + }, + "xunit.v3.extensibility.core": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "TBYqQKyT+XBDLSHjG6PnmQpooqatflBcWvNiESVS5ptQxWXVf/FGlkUfkNyHKRCUDSCxxHIJNgwO+SRosUmZEw==", + "dependencies": { + "xunit.v3.common": "[4.0.3]" + } + }, + "xunit.v3.mtp-v2": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "lad1hGmodKkfp3AgIwHVVIYeA9GfW125tnkYj7HvOyiwbDH8gpMKPPhzHRC1wc0w4a+0UsOHx2Ero/DtLXvtqA==", + "dependencies": { + "xunit.analyzers": "2.3.0", + "xunit.v3.assert": "[4.0.3]", + "xunit.v3.core.mtp-v2": "[4.0.3]" + } + }, + "xunit.v3.runner.inproc.console": { + "type": "Transitive", + "resolved": "4.0.3", + "contentHash": "lDvNs5exa8rBdWXX/wdapPTp81SNCvUarXC5iXzr1qvO168+Sx/Ytrk9VSLbSD3Y9KNK8PcOjMl1q7JfCoo3LQ==", + "dependencies": { + "xunit.v3.extensibility.core": "[4.0.3]", + "xunit.v3.runner.common": "[4.0.3]" + } + }, + "dotbahn.common": { + "type": "Project", + "dependencies": { + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "dotbahn.tests.shared": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )" + } + }, + "dotbahn.timetables": { + "type": "Project", + "dependencies": { + "DotBahn.Common": "[1.0.0, )", + "Microsoft.Extensions.Http": "[11.0.0, )", + "Microsoft.Extensions.Http.Resilience": "[11.0.1, )", + "Microsoft.Extensions.Options": "[11.0.0, )" + } + }, + "Microsoft.Extensions.Http": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "Pa5xJYtE5weFzv8sRwei1yvqCc05PareJABDtUSigzyj0xmrnG7ZU5VBy0hf5tgh7HN3/psGiOQouw5PLaQD8w==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Diagnostics": "11.0.0", + "Microsoft.Extensions.Logging": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "Microsoft.Extensions.Options": "11.0.0" + } + }, + "Microsoft.Extensions.Http.Resilience": { + "type": "CentralTransitive", + "requested": "[11.0.1, )", + "resolved": "11.0.1", + "contentHash": "5VawCrg+VgVT2hNurSSEWUnq0pvNoH+Zt82s5Wpl/8jdnmU8DpRlr+M3DcdtVgeBG7mRyk3GtSRbf8PB/HrL3w==", + "dependencies": { + "Microsoft.Extensions.Http.Diagnostics": "11.0.1", + "Microsoft.Extensions.ObjectPool": "10.0.15", + "Microsoft.Extensions.Resilience": "11.0.1" + } + }, + "Microsoft.Extensions.Options": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "AaNswJ3NqdNCNqQVlU7iTkvrrrzqrSSxkOC3bLlrwv/CPN7YRz3HoJk7o4ey5v6U8bOHocHsyYoJ7ihK1KUWyQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Primitives": "11.0.0" + } + } + } + } +} \ No newline at end of file diff --git a/tests/DotBahn.Timetables.Tests/Client/ClientBaseTests.cs b/tests/DotBahn.Timetables.Tests/Client/ClientBaseTests.cs deleted file mode 100644 index 8077f7e..0000000 --- a/tests/DotBahn.Timetables.Tests/Client/ClientBaseTests.cs +++ /dev/null @@ -1,230 +0,0 @@ -using System.Net; -using DotBahn.Common.Auth; -using DotBahn.Common.Clients; -using DotBahn.Common.Parsing; -using DotBahn.Common.Tests; -using DotBahn.Common.Utilities; -using Moq; - -namespace DotBahn.Timetables.Tests.Client; - -public class ClientBaseTests : ClientTestBase { - - public ClientBaseTests() { - HttpClient.BaseAddress = new Uri("https://api.deutschebahn.com"); - } - - [Fact] - public void Constructor_DIConstructor_StoresHttpClientReference() { - var http = new HttpClient(); - var authorization = new Mock().Object; - - var client = new TestClientBase(http, authorization); - - Assert.NotNull(client); - } - - [Fact] - public void Constructor_DIConstructor_WithNullHttpClient_ThrowsArgumentNullException() { - var authorization = new Mock().Object; - - Assert.Throws(() => new TestClientBase(null!, authorization)); - } - - [Fact] - public void Constructor_DIConstructor_WithNullAuthorization_ThrowsArgumentNullException() { - var http = new HttpClient(); - - Assert.Throws(() => new TestClientBase(http, null!)); - } - - [Fact] - public void Constructor_ConvenienceConstructor_CreatesHttpClientWithBaseAddress() { - var endpoint = new Uri("https://api.deutschebahn.com"); - var options = new ClientOptions { BaseEndpoint = endpoint }; - var auth = new AuthorizationOptions { - ClientId = "test-client", - ApiKey = "test-key" - }; - - using var client = new TestClientBase(options, auth); - - Assert.NotNull(client); - Assert.NotNull(client.HttpClient); - Assert.Equal(endpoint, client.HttpClient.BaseAddress); - } - - [Fact] - public void Constructor_ConvenienceConstructor_WithNullOptions_ThrowsArgumentNullException() { - var auth = new AuthorizationOptions { - ClientId = "test-client", - ApiKey = "test-key" - }; - - Assert.Throws(() => new TestClientBase(null!, auth)); - } - - [Fact] - public void Constructor_ConvenienceConstructor_WithNullAuth_ThrowsArgumentNullException() { - var options = new ClientOptions { - BaseEndpoint = new Uri("https://api.deutschebahn.com") - }; - - Assert.Throws(() => new TestClientBase(options, null!)); - } - - [Fact] - public async Task GetAsync_BuildsCorrectUrlFromBaseAndRelative() { - var client = CreateClient(); - var parser = new Mock>().Object; - HttpHandler.RespondWith(HttpStatusCode.OK, ""); - - await client.GetAsync("/test/path", parser, "application/xml", ct: TestContext.Current.CancellationToken); - - AssertRequest(HttpMethod.Get, "/test/path", "application/xml"); - } - - [Fact] - public async Task GetAsync_AppendsQueryParametersToUrl() { - var client = CreateClient(); - var parser = new Mock>().Object; - var queryParams = QueryParameters.Create().Add("key1", "value1").Add("key2", "value2"); - HttpHandler.RespondWith(HttpStatusCode.OK, ""); - - await client.GetAsync("/test", parser, "application/xml", queryParams, TestContext.Current.CancellationToken); - - var request = HttpHandler.SentRequests[0]; - Assert.Contains("key1=value1", request.RequestUri?.ToString()); - Assert.Contains("key2=value2", request.RequestUri?.ToString()); - } - - [Fact] - public async Task GetAsync_SetsAcceptHeader() { - var client = CreateClient(); - var parser = new Mock>().Object; - HttpHandler.RespondWith(HttpStatusCode.OK, "", "application/json"); - - await client.GetAsync("/test", parser, "application/json", ct: TestContext.Current.CancellationToken); - - AssertRequest(HttpMethod.Get, "/test", "application/json"); - } - - [Fact] - public async Task GetAsync_CallsAuthorizeRequestExactlyOnce() { - var client = CreateClient(); - var parser = new Mock>().Object; - HttpHandler.RespondWith(HttpStatusCode.OK, ""); - - await client.GetAsync("/test", parser, "application/xml", ct: TestContext.Current.CancellationToken); - - AuthorizationMock.Verify(a => a.AuthorizeRequest(It.IsAny()), Times.Once); - } - - [Fact] - public async Task GetAsync_ReturnsParsedContractOnSuccess() { - var client = CreateClient(); - var expectedContract = "test-contract"; - var parserMock = new Mock>(); - parserMock.Setup(p => p.Parse(It.IsAny())).Returns(expectedContract); - HttpHandler.RespondWith(HttpStatusCode.OK, "data"); - - var result = await client.GetAsync("/test", parserMock.Object, "application/xml", ct: TestContext.Current.CancellationToken); - - Assert.Equal(expectedContract, result); - } - - [Fact] - public async Task GetAsync_WithNullParser_ThrowsArgumentNullException() { - var client = CreateClient(); - - await Assert.ThrowsAsync(() => client.GetAsync("/test", null!, "application/xml", ct: TestContext.Current.CancellationToken)); - } - - [Fact] - public async Task GetAsync_With401Status_ThrowsHttpRequestExceptionUnauthorized() { - var client = CreateClient(); - var parserMock = new Mock>().Object; - HttpHandler.RespondWith(HttpStatusCode.Unauthorized, ""); - - var ex = await Assert.ThrowsAsync(() => client.GetAsync("/test", parserMock, "application/xml", ct: TestContext.Current.CancellationToken)); - Assert.Equal(HttpStatusCode.Unauthorized, ex.StatusCode); - Assert.Contains("not authorized", ex.Message, StringComparison.OrdinalIgnoreCase); - } - - [Fact] - public async Task GetAsync_With400Status_ThrowsHttpRequestExceptionBadRequest() { - var client = CreateClient(); - var parserMock = new Mock>().Object; - HttpHandler.RespondWith(HttpStatusCode.BadRequest, ""); - - var ex = await Assert.ThrowsAsync(() => client.GetAsync("/test", parserMock, "application/xml", ct: TestContext.Current.CancellationToken)); - Assert.Equal(HttpStatusCode.BadRequest, ex.StatusCode); - Assert.Contains("Bad request", ex.Message, StringComparison.OrdinalIgnoreCase); - } - - [Fact] - public async Task GetAsync_With404Status_ReturnsDefaultEmptyString() { - var client = CreateClient(); - var parserMock = new Mock>(); - parserMock.Setup(p => p.Parse("")).Returns(""); - HttpHandler.RespondWith(HttpStatusCode.NotFound, ""); - - var result = await client.GetAsync("/test", parserMock.Object, "application/xml", ct: TestContext.Current.CancellationToken); - - Assert.Equal("", result); - parserMock.Verify(p => p.Parse(""), Times.Once); - } - - [Fact] - public async Task GetAsync_With500Status_ThrowsHttpRequestException() { - var client = CreateClient(); - var parserMock = new Mock>().Object; - HttpHandler.RespondWith(HttpStatusCode.InternalServerError, ""); - - await Assert.ThrowsAsync(() => client.GetAsync("/test", parserMock, "application/xml", ct: TestContext.Current.CancellationToken)); - } - - - public static TheoryData GetAsyncUrlQueryParamHandlingCases => new() { - { "BL—has_params", true, true }, - { "C1—null_params", false, false }, - { "C2—empty_params", true, false }, - }; - - [Theory] - [MemberData(nameof(GetAsyncUrlQueryParamHandlingCases))] - public async Task GetAsyncUrlQueryParamHandling(string _, bool createParams, bool addParam) { - var client = CreateClient(); - var parser = new Mock>().Object; - HttpHandler.RespondWith(HttpStatusCode.OK, ""); - - QueryParameters? queryParams = null; - if (createParams) { - queryParams = QueryParameters.Create(); - if (addParam) - queryParams.Add("key", "val"); - } - - await client.GetAsync("/test", parser, "application/xml", queryParams, TestContext.Current.CancellationToken); - var requestUri = HttpHandler.SentRequests[0].RequestUri!.ToString(); - - if (addParam) { - Assert.Contains("?key=val", requestUri); - } else { - Assert.DoesNotContain("?", requestUri); - } - } - - private TestClientBase CreateClient() => new(HttpClient, AuthorizationMock.Object); - - private sealed class TestClientBase : ClientBase { - public TestClientBase(HttpClient http, IAuthorization authorization) : base(http, authorization) { } - - public TestClientBase(ClientOptions options, AuthorizationOptions auth) : base(options, auth) { } - - public new HttpClient HttpClient => base.HttpClient; - - public Task GetAsync(string relativeUrl, IParser parser, string acceptHeader, QueryParameters? queryParams = null, CancellationToken ct = default) => - base.GetAsync(relativeUrl, parser, acceptHeader, queryParams, ct); - } -} diff --git a/tests/DotBahn.Timetables.Tests/Client/QueryParametersTests.cs b/tests/DotBahn.Timetables.Tests/Client/QueryParametersTests.cs deleted file mode 100644 index 0b7f6d1..0000000 --- a/tests/DotBahn.Timetables.Tests/Client/QueryParametersTests.cs +++ /dev/null @@ -1,46 +0,0 @@ -using DotBahn.Common.Utilities; - -namespace DotBahn.Timetables.Tests.Client; - -public class QueryParametersTests { - public static TheoryData?, bool> AddCollectionEdgeCases => new() { - { "BL—non_empty", ["a", "b"], true }, - { "C1—null", null, false }, - { "C2—empty", [], false }, - }; - - [Theory] - [MemberData(nameof(AddCollectionEdgeCases))] - public void AddCollectionEdge(string _, IEnumerable? values, bool expectedAdded) { - var qp = QueryParameters.Create(); - qp.Add("key", values); - var qs = qp.ToQueryString(); - - if (expectedAdded) { - Assert.Contains("key=", qs); - } else { - Assert.DoesNotContain("key=", qs); - } - } - - public static TheoryData AddStringEdgeCases => new() { - { "BL—valid", "val", true }, - { "C1—null", null, false }, - { "C2—empty", "", false }, - { "C3—whitespace", " ", false }, - }; - - [Theory] - [MemberData(nameof(AddStringEdgeCases))] - public void AddStringEdge(string _, string? value, bool expectedAdded) { - var qp = QueryParameters.Create(); - qp.Add("key", value); - var qs = qp.ToQueryString(); - - if (expectedAdded) { - Assert.Contains("key=", qs); - } else { - Assert.DoesNotContain("key=", qs); - } - } -} diff --git a/tests/DotBahn.Timetables.Tests/Client/TimetableClientTests.cs b/tests/DotBahn.Timetables.Tests/Client/TimetableClientTests.cs deleted file mode 100644 index 9812728..0000000 --- a/tests/DotBahn.Timetables.Tests/Client/TimetableClientTests.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System.Net; -using DotBahn.Common.Parsing; -using DotBahn.Common.Tests; -using DotBahn.Common.Transformer; -using DotBahn.Timetables.Internal.Contracts; -using DotBahn.Timetables.Models; -using Moq; - -namespace DotBahn.Timetables.Tests.Client; - -public class TimetableClientTests : ClientTestBase { - private const int TestEva = 8000105; - - private readonly Mock> _parserMock = new(); - private readonly Timetable _defaultTimetable = new() { Station = "TestStation" }; - private readonly TimetableResponseContract _defaultContract = new() { Station = "TestStation" }; - - public TimetableClientTests() { - HttpClient.BaseAddress = new Uri("https://api.deutschebahn.com"); - } - - [Fact] - public async Task GetFullChangesAsync_WithoutCurrentTimetable_ReturnsTransformedChanges() { - var transformer = new StubTransformer(_defaultTimetable); - var merger = new StubMerger(_defaultTimetable); - _parserMock.Setup(p => p.Parse(It.IsAny())).Returns(_defaultContract); - HttpHandler.RespondWith(HttpStatusCode.OK, ""); - - var client = new TimetableClient(HttpClient, AuthorizationMock.Object, _parserMock.Object, transformer, merger); - var result = await client.GetFullChangesAsync(TestEva, ct: TestContext.Current.CancellationToken); - - Assert.Same(_defaultTimetable, result); - Assert.Equal(1, transformer.TransformCallCount); - Assert.Equal(0, merger.MergeCallCount); - AssertRequest(HttpMethod.Get, "/fchg/8000105", "application/xml"); - } - - [Fact] - public async Task GetFullChangesAsync_WithCurrentTimetable_CallsMergerMerge() { - var currentTimetable = new Timetable { Station = "CurrentStation" }; - var changesTimetable = new Timetable { Station = "ChangesStation" }; - var mergedTimetable = new Timetable { Station = "MergedStation" }; - var transformer = new StubTransformer(changesTimetable); - var merger = new StubMerger(mergedTimetable); - _parserMock.Setup(p => p.Parse(It.IsAny())).Returns(_defaultContract); - HttpHandler.RespondWith(HttpStatusCode.OK, ""); - - var client = new TimetableClient(HttpClient, AuthorizationMock.Object, _parserMock.Object, transformer, merger); - var result = await client.GetFullChangesAsync(TestEva, currentTimetable, TestContext.Current.CancellationToken); - - Assert.Same(mergedTimetable, result); - Assert.Equal(1, transformer.TransformCallCount); - Assert.Equal(1, merger.MergeCallCount); - AssertRequest(HttpMethod.Get, "/fchg/8000105", "application/xml"); - } - - [Fact] - public async Task GetRecentChangesAsync_WithoutCurrentTimetable_ReturnsTransformedChanges() { - var transformer = new StubTransformer(_defaultTimetable); - var merger = new StubMerger(_defaultTimetable); - _parserMock.Setup(p => p.Parse(It.IsAny())).Returns(_defaultContract); - HttpHandler.RespondWith(HttpStatusCode.OK, ""); - - var client = new TimetableClient(HttpClient, AuthorizationMock.Object, _parserMock.Object, transformer, merger); - var result = await client.GetRecentChangesAsync(TestEva, ct: TestContext.Current.CancellationToken); - - Assert.Same(_defaultTimetable, result); - Assert.Equal(1, transformer.TransformCallCount); - Assert.Equal(0, merger.MergeCallCount); - AssertRequest(HttpMethod.Get, "/rchg/8000105", "application/xml"); - } - - [Fact] - public async Task GetRecentChangesAsync_WithCurrentTimetable_CallsMergerMerge() { - var currentTimetable = new Timetable { Station = "CurrentStation" }; - var changesTimetable = new Timetable { Station = "RecentChangesStation" }; - var mergedTimetable = new Timetable { Station = "MergedRecentStation" }; - var transformer = new StubTransformer(changesTimetable); - var merger = new StubMerger(mergedTimetable); - _parserMock.Setup(p => p.Parse(It.IsAny())).Returns(_defaultContract); - HttpHandler.RespondWith(HttpStatusCode.OK, ""); - - var client = new TimetableClient(HttpClient, AuthorizationMock.Object, _parserMock.Object, transformer, merger); - var result = await client.GetRecentChangesAsync(TestEva, currentTimetable, TestContext.Current.CancellationToken); - - Assert.Same(mergedTimetable, result); - Assert.Equal(1, transformer.TransformCallCount); - Assert.Equal(1, merger.MergeCallCount); - AssertRequest(HttpMethod.Get, "/rchg/8000105", "application/xml"); - } - - [Fact] - public async Task GetTimetableAsync_ValidDateTime_BuildsCorrectUrl() { - var dateTime = new DateTime(2025, 6, 15, 14, 30, 0); - var transformer = new StubTransformer(_defaultTimetable); - _parserMock.Setup(p => p.Parse(It.IsAny())).Returns(_defaultContract); - HttpHandler.RespondWith(HttpStatusCode.OK, ""); - - var client = new TimetableClient(HttpClient, AuthorizationMock.Object, _parserMock.Object, transformer, new StubMerger(_defaultTimetable)); - var result = await client.GetTimetableAsync(TestEva, dateTime, TestContext.Current.CancellationToken); - - Assert.Same(_defaultTimetable, result); - Assert.Equal(1, transformer.TransformCallCount); - AssertRequest(HttpMethod.Get, "/plan/8000105/250615/14", "application/xml"); - } - - [Fact] - public async Task GetFullChangesAsync_CancellationRequested_ThrowsOperationCanceledException() { - using var cts = new CancellationTokenSource(); - await cts.CancelAsync(); - HttpHandler.RespondWith(_ => throw new OperationCanceledException(cts.Token)); - - var client = new TimetableClient(HttpClient, AuthorizationMock.Object, _parserMock.Object, new StubTransformer(_defaultTimetable), new StubMerger(_defaultTimetable)); - - await Assert.ThrowsAnyAsync(() => client.GetFullChangesAsync(TestEva, null, cts.Token)); - } - - private void AssertRequest(HttpMethod method, string relativeUrl, string acceptHeader) { - var match = HttpHandler.SentRequests - .Where(r => r.Method == method && r.RequestUri?.ToString().EndsWith(relativeUrl.TrimStart('/'), StringComparison.Ordinal) == true) - .ToList(); - - Assert.NotEmpty(match); - Assert.Single(match); - Assert.True(match[0].Headers.Accept.Any(h => h.MediaType == acceptHeader), $"Expected Accept header '{acceptHeader}' not found."); - } - - private sealed class StubTransformer(Timetable result) : ITransformer { - public int TransformCallCount { get; private set; } - public Timetable Transform(TimetableResponseContract contracts) { - TransformCallCount++; - return result; - } - } - - private sealed class StubMerger(Timetable result) : IMerger { - public int MergeCallCount { get; private set; } - public Timetable Merge(Timetable current, Timetable changes) { - MergeCallCount++; - return result; - } - } -} diff --git a/tests/DotBahn.Timetables.Tests/Client/UriUtilTests.cs b/tests/DotBahn.Timetables.Tests/Client/UriUtilTests.cs deleted file mode 100644 index 3708a01..0000000 --- a/tests/DotBahn.Timetables.Tests/Client/UriUtilTests.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System.Net; -using DotBahn.Common.Auth; -using DotBahn.Common.Clients; -using DotBahn.Common.Parsing; -using DotBahn.Common.Tests; -using DotBahn.Common.Utilities; -using Moq; - -namespace DotBahn.Timetables.Tests.Client; - -public class UriUtilTests : ClientTestBase { - private readonly Mock> _parserMock = new(); - - public UriUtilTests() { - HttpClient.BaseAddress = new Uri("https://api.deutschebahn.com"); - } - - [Fact] - public async Task GetAsync_WithNullQueryParameters_NoQueryStringInUrl() { - var client = CreateClient(); - HttpHandler.RespondWith(HttpStatusCode.OK, ""); - - await client.GetAsync("/test", _parserMock.Object, "application/xml", ct: TestContext.Current.CancellationToken); - - var requestUri = HttpHandler.SentRequests[0].RequestUri!.ToString(); - Assert.DoesNotContain("?", requestUri); - } - - [Fact] - public async Task GetAsync_WithEmptyQueryParameters_NoQueryStringInUrl() { - var client = CreateClient(); - var queryParams = QueryParameters.Create(); - HttpHandler.RespondWith(HttpStatusCode.OK, ""); - - await client.GetAsync("/test", _parserMock.Object, "application/xml", queryParams, TestContext.Current.CancellationToken); - - var requestUri = HttpHandler.SentRequests[0].RequestUri!.ToString(); - Assert.DoesNotContain("?", requestUri); - } - - [Fact] - public async Task GetAsync_WithQueryParameters_AppendsQueryStringToUrl() { - var client = CreateClient(); - var queryParams = QueryParameters.Create() - .Add("key1", "value1") - .Add("key2", "value2"); - HttpHandler.RespondWith(HttpStatusCode.OK, ""); - - await client.GetAsync("/test", _parserMock.Object, "application/xml", queryParams, TestContext.Current.CancellationToken); - - var requestUri = HttpHandler.SentRequests[0].RequestUri!.ToString(); - Assert.Contains("?key1=value1", requestUri); - Assert.Contains("&key2=value2", requestUri); - } - - [Fact] - public async Task GetAsync_WithSpecialCharacters_UrlEncodesParameters() { - var client = CreateClient(); - var queryParams = QueryParameters.Create().Add("search", "test value"); - HttpHandler.RespondWith(HttpStatusCode.OK, ""); - - await client.GetAsync("/test", _parserMock.Object, "application/xml", queryParams, TestContext.Current.CancellationToken); - - Assert.Single(HttpHandler.SentRequests); - var requestUri = HttpHandler.SentRequests[0].RequestUri!.AbsoluteUri; - Assert.Contains("%20", requestUri); - } - - private TestClientBase CreateClient() => new(HttpClient, AuthorizationMock.Object); - - private class TestClientBase(HttpClient http, IAuthorization authorization) : ClientBase(http, authorization) { - public Task GetAsync(string relativeUrl, IParser parser, string acceptHeader, QueryParameters? queryParams = null, CancellationToken ct = default) => - base.GetAsync(relativeUrl, parser, acceptHeader, queryParams, ct); - } -} diff --git a/tests/DotBahn.Timetables.Tests/Models/ChangedRefTests.cs b/tests/DotBahn.Timetables.Tests/Models/ChangedRefTests.cs deleted file mode 100644 index fcd2e5e..0000000 --- a/tests/DotBahn.Timetables.Tests/Models/ChangedRefTests.cs +++ /dev/null @@ -1,19 +0,0 @@ -using DotBahn.Common.Models; - -namespace DotBahn.Timetables.Tests.Models; - -public class ChangedRefTests { - [Theory] - [InlineData("original", null, "original", false)] - [InlineData("original", "updated", "updated", true)] - [InlineData("x", null, "x", false)] - public void Actual_ReturnsExpectedValue(string original, string? updated, string expected, bool hasUpdate) { - var changed = new ChangedRef { - Original = original, - Updated = updated - }; - - Assert.Equal(expected, changed.Actual); - Assert.Equal(hasUpdate, changed.HasUpdate); - } -} diff --git a/tests/DotBahn.Timetables.Tests/Models/ChangedValueTests.cs b/tests/DotBahn.Timetables.Tests/Models/ChangedValueTests.cs deleted file mode 100644 index 6a63971..0000000 --- a/tests/DotBahn.Timetables.Tests/Models/ChangedValueTests.cs +++ /dev/null @@ -1,28 +0,0 @@ -using DotBahn.Common.Models; - -namespace DotBahn.Timetables.Tests.Models; - -public class ChangedValueTests { - [Theory] - [InlineData(42, null, 42, false)] - [InlineData(42, 99, 99, true)] - public void Actual_ReturnsExpectedValue(int original, int? updated, int expected, bool hasUpdate) { - var changed = new ChangedValue { - Original = original, - Updated = updated - }; - - Assert.Equal(expected, changed.Actual); - Assert.Equal(hasUpdate, changed.HasUpdate); - } - - [Fact] - public void HasUpdate_WhenUpdatedIsNull_ReturnsFalse() { - var changed = new ChangedValue { - Original = DateTime.MinValue, - Updated = null - }; - - Assert.False(changed.HasUpdate); - } -} diff --git a/tests/DotBahn.Timetables.Tests/Models/TimetableMessageTests.cs b/tests/DotBahn.Timetables.Tests/Models/TimetableMessageTests.cs deleted file mode 100644 index 111e458..0000000 --- a/tests/DotBahn.Timetables.Tests/Models/TimetableMessageTests.cs +++ /dev/null @@ -1,76 +0,0 @@ -using DotBahn.Timetables.Models; -using DotBahn.Timetables.Models.Enumerations; - -namespace DotBahn.Timetables.Tests.Models; - -public class TimetableMessageTests { - private static TimetableMessage Make(bool isDeleted = false, DateTime? validTo = null, string? internalText = null, string? externalText = null) => new() { - Id = "m1", - Type = MessageType.Him, - Timestamp = DateTime.UtcNow, - IsDeleted = isDeleted, - ValidTo = validTo, - InternalText = internalText, - ExternalText = externalText - }; - - [Theory] - [InlineData(null, "public info", "public info")] - [InlineData("internal info", null, "internal info")] - [InlineData("internal", "external", "external")] - [InlineData(null, null, null)] - public void Text_ReturnsExpected(string? internalText, string? externalText, string? expected) { - var msg = Make(internalText: internalText, externalText: externalText); - - Assert.Equal(expected, msg.Text); - } - - [Fact] - public void Text_NeitherSet_ReturnsNull() { - var msg = Make(); - - Assert.Null(msg.Text); - } - - [Fact] - public void IsActive_NotDeletedAndNoValidTo_ReturnsTrue() { - var msg = Make(isDeleted: false, validTo: null); - - Assert.True(msg.IsActive); - } - - [Fact] - public void IsActive_NotDeletedAndValidToInFuture_ReturnsTrue() { - var msg = Make(isDeleted: false, validTo: DateTime.Now.AddHours(1)); - - Assert.True(msg.IsActive); - } - - [Fact] - public void IsActive_NotDeletedAndValidToInPast_ReturnsFalse() { - var msg = Make(isDeleted: false, validTo: DateTime.Now.AddHours(-1)); - - Assert.False(msg.IsActive); - } - - [Fact] - public void IsActive_Deleted_ReturnsFalse() { - var msg = Make(isDeleted: true, validTo: null); - - Assert.False(msg.IsActive); - } - - [Fact] - public void IsActive_DeletedAndValidToInFuture_ReturnsFalse() { - var msg = Make(isDeleted: true, validTo: DateTime.Now.AddHours(1)); - - Assert.False(msg.IsActive); - } - - [Fact] - public void IsActive_WithValidToExactlyNow_ReturnsFalse() { - var msg = Make(isDeleted: false, validTo: DateTime.Now); - - Assert.False(msg.IsActive); - } -} diff --git a/tests/DotBahn.Timetables.Tests/Models/TimetableStopTests.cs b/tests/DotBahn.Timetables.Tests/Models/TimetableStopTests.cs deleted file mode 100644 index 8703b70..0000000 --- a/tests/DotBahn.Timetables.Tests/Models/TimetableStopTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using DotBahn.Common.Models; -using DotBahn.Timetables.Models; -using DotBahn.Timetables.Models.Enumerations; - -namespace DotBahn.Timetables.Tests.Models; - -public class TimetableStopTests { - private static TrainLabel EmptyTrain => new() { Category = "", Number = "", Owner = "" }; - private static TrainEvent AnyEvent => new() { - Time = new ChangedValue { Original = DateTime.MinValue }, - Platform = new ChangedRef { Original = "" }, - Status = new ChangedValue { Original = EventStatus.Unknown }, - DistantEndpoint = new ChangedRef { Original = "" }, - Path = new ChangedRef> { Original = [] } - }; - - [Theory] - [InlineData(true, false, true, false, false)] - [InlineData(false, true, false, true, false)] - [InlineData(true, true, false, false, true)] - [InlineData(false, false, false, false, false)] - public void StopType_ReturnsCorrectFlags(bool hasArrival, bool hasDeparture, - bool expectedArrivalOnly, bool expectedDepartureOnly, bool expectedThrough) { - var stop = new TimetableStop { - Id = "x", - Train = EmptyTrain, - Arrival = hasArrival ? AnyEvent : null, - Departure = hasDeparture ? AnyEvent : null - }; - - Assert.Equal(expectedArrivalOnly, stop.IsArrivalOnly); - Assert.Equal(expectedDepartureOnly, stop.IsDepartureOnly); - Assert.Equal(expectedThrough, stop.IsThrough); - } -} diff --git a/tests/DotBahn.Timetables.Tests/Parsing/BahnDialectParserTests.cs b/tests/DotBahn.Timetables.Tests/Parsing/BahnDialectParserTests.cs deleted file mode 100644 index d442672..0000000 --- a/tests/DotBahn.Timetables.Tests/Parsing/BahnDialectParserTests.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System.Text.Json; -using DotBahn.Common.Parsing.Converters; - -namespace DotBahn.Timetables.Tests.Parsing; - -public class BahnDialectParserTests { - private readonly JsonSerializerOptions _options = new() { - PropertyNameCaseInsensitive = true, - Converters = { new BahnDialectJsonConverter() } - }; - - [Theory] - [InlineData("true", true)] - [InlineData("false", false)] - public void Read_BooleanLiteral_ReturnsCorrectValue(string json, bool expected) { - var result = JsonSerializer.Deserialize(json, _options); - - Assert.Equal(expected, result); - } - - [Theory] - [InlineData("\"true\"")] - [InlineData("\"TRUE\"")] - [InlineData("\"yes\"")] - [InlineData("\"YES\"")] - [InlineData("\"1\"")] - public void Read_TruthyString_ReturnsTrue(string json) { - var result = JsonSerializer.Deserialize(json, _options); - - Assert.True(result); - } - - [Theory] - [InlineData("\"false\"")] - [InlineData("\"FALSE\"")] - [InlineData("\"no\"")] - [InlineData("\"NO\"")] - [InlineData("\"0\"")] - [InlineData("\"\"")] - [InlineData("\"anything\"")] - public void Read_FalsyString_ReturnsFalse(string json) { - var result = JsonSerializer.Deserialize(json, _options); - - Assert.False(result); - } - - [Fact] - public void Read_UnexpectedTokenType_ThrowsJsonException() => - Assert.Throws(() => JsonSerializer.Deserialize("42", _options)); - - [Theory] - [InlineData(true, "true")] - [InlineData(false, "false")] - public void Write_BooleanValue_WritesCorrectJson(bool value, string expected) { - var result = JsonSerializer.Serialize(value, _options); - - Assert.Equal(expected, result); - } - - [Theory] - [InlineData(true)] - [InlineData(false)] - public void Write_ThenRead_RoundTripsBooleanValue(bool value) { - var json = JsonSerializer.Serialize(value, _options); - var result = JsonSerializer.Deserialize(json, _options); - - Assert.Equal(value, result); - } -} diff --git a/tests/DotBahn.Timetables.Tests/Parsing/JsonParserTests.cs b/tests/DotBahn.Timetables.Tests/Parsing/JsonParserTests.cs deleted file mode 100644 index 596e7bb..0000000 --- a/tests/DotBahn.Timetables.Tests/Parsing/JsonParserTests.cs +++ /dev/null @@ -1,29 +0,0 @@ -using DotBahn.Common.Parsing; -using DotBahn.Timetables.Internal.Contracts; -using DotBahn.Timetables.Internal.Json; - -namespace DotBahn.Timetables.Tests.Parsing; - -public class JsonParserTests { - private readonly JsonParser _parser = new(TimetableJsonContext.Default.TimetableResponseContract); - - [Theory] - [InlineData("")] - [InlineData(" ")] - public void Parse_EmptyOrWhitespace_ReturnsDefaultInstance(string input) { - var result = _parser.Parse(input); - - Assert.NotNull(result); - Assert.Empty(result.Stops); - } - - [Fact] - public void Parse_ValidJson_ReturnsPopulatedContract() { - const string json = """{"station":"Hamburg Hbf","stops":[]}"""; - - var result = _parser.Parse(json); - - Assert.Equal("Hamburg Hbf", result.Station); - } - -} diff --git a/tests/DotBahn.Timetables.Tests/Parsing/XmlParserTests.cs b/tests/DotBahn.Timetables.Tests/Parsing/XmlParserTests.cs deleted file mode 100644 index b5c8517..0000000 --- a/tests/DotBahn.Timetables.Tests/Parsing/XmlParserTests.cs +++ /dev/null @@ -1,76 +0,0 @@ -using DotBahn.Timetables.Internal.Parsing; - -namespace DotBahn.Timetables.Tests.Parsing; - -public class XmlParserTests { - private readonly TimetableXmlParser _parser = new(); - - [Theory] - [InlineData("")] - [InlineData(" ")] - public void Parse_EmptyOrWhitespace_ReturnsDefaultInstance(string input) { - var result = _parser.Parse(input); - - Assert.NotNull(result); - Assert.Empty(result.Stops); - } - - [Fact] - public void Parse_ValidXml_ReturnsPopulatedContract() { - const string xml = """"""; - - var result = _parser.Parse(xml); - - Assert.Equal("München Hbf", result.Station); - } - - public static TheoryData ParseRootRequiresTimetableTagCases => new() - { - { "BL—valid_tag", """""", "Frankfurt Hbf" }, - { "C2—wrong_tag", """""", "" }, - }; - - [Theory] - [MemberData(nameof(ParseRootRequiresTimetableTagCases))] - public void ParseRootRequiresTimetableTag(string _, string xml, string expectedStation) { - var result = _parser.Parse(xml); - Assert.Equal(expectedStation, result.Station); - } - - [Fact] - public void ParseStopMissingIdThrowsXmlException() { - var xml = """"""; - - Assert.Throws(() => _parser.Parse(xml)); - } - - [Fact] - public void ParseStopMissingEvaDefaultsToEmpty() { - var xml = """"""; - - var result = _parser.Parse(xml); - - Assert.Equal("", result.Stops[0].Eva); - } - - [Fact] - public void ParseRootMissingStationDefaultsToEmpty() { - var xml = """"""; - - var result = _parser.Parse(xml); - - Assert.Equal("", result.Station); - Assert.Empty(result.Stops); - } - - [Fact] - public void Parse_ValidXmlWithStop_ReturnsStops() { - const string xml = """"""; - - var result = _parser.Parse(xml); - - Assert.Equal("Berlin Hbf", result.Station); - Assert.Single(result.Stops); - Assert.Equal("stop-1", result.Stops[0].Id); - } -} diff --git a/tests/DotBahn.Timetables.Tests/Transformer/TimetableMergerMergeTests.cs b/tests/DotBahn.Timetables.Tests/Transformer/TimetableMergerMergeTests.cs deleted file mode 100644 index 6d7556f..0000000 --- a/tests/DotBahn.Timetables.Tests/Transformer/TimetableMergerMergeTests.cs +++ /dev/null @@ -1,357 +0,0 @@ -using DotBahn.Common.Models; -using DotBahn.Timetables.Internal.Transformers; -using DotBahn.Timetables.Models; -using DotBahn.Timetables.Models.Enumerations; - -namespace DotBahn.Timetables.Tests.Transformer; - -public class TimetableMergerMergeTests { - private readonly TimetableMerger _merger = new(); - - [Fact] - public void Merge_WithNoChanges_ShouldReturnCurrent() { - var current = CreateTimetable("Hamburg Hbf", [CreateStop("stop-1")]); - var changes = CreateTimetable("Hamburg Hbf", []); - - var result = _merger.Merge(current, changes); - - Assert.Equal("Hamburg Hbf", result.Station); - Assert.Single(result.Stops); - } - - [Fact] - public void Merge_WithNewStop_ShouldAddStop() { - var current = CreateTimetable("Berlin Hbf", [CreateStop("stop-1")]); - var changes = CreateTimetable("Berlin Hbf", [CreateStop("stop-2")]); - - var result = _merger.Merge(current, changes); - - Assert.Equal(2, result.Stops.Count()); - Assert.Contains(result.Stops, s => s.Id == "stop-1"); - Assert.Contains(result.Stops, s => s.Id == "stop-2"); - } - - [Fact] - public void Merge_WithExistingStop_ShouldUpdateStop() { - var current = CreateTimetable("München Hbf", [ - CreateStopWithDeparture("stop-1", "2501191000", "5") - ]); - var changes = CreateTimetable("München Hbf", [ - CreateStopWithDepartureUpdate("stop-1", "2501191015", "6") - ]); - - var result = _merger.Merge(current, changes); - - var stop = Assert.Single(result.Stops); - Assert.Equal("stop-1", stop.Id); - Assert.Equal(new DateTime(2025, 1, 19, 10, 0, 0), stop.Departure!.Time.Original); - Assert.Equal(new DateTime(2025, 1, 19, 10, 15, 0), stop.Departure.Time.Updated); - Assert.Equal("5", stop.Departure.Platform.Original); - Assert.Equal("6", stop.Departure.Platform.Updated); - } - - [Fact] - public void Merge_PreservesOriginalValues() { - var current = CreateTimetable("Köln Hbf", [ - CreateStopWithDeparture("stop-1", "2501191200", "8") - ]); - var changes = CreateTimetable("Köln Hbf", [ - CreateStopWithDepartureUpdate("stop-1", "2501191230", null) - ]); - - var result = _merger.Merge(current, changes); - - var departure = result.Stops.First().Departure!; - Assert.Equal(new DateTime(2025, 1, 19, 12, 0, 0), departure.Time.Original); - Assert.Equal("8", departure.Platform.Original); - } - - [Fact] - public void Merge_WithNoUpdate_ShouldKeepCurrentUpdate() { - var current = CreateTimetable("Stuttgart Hbf", [ - CreateStopWithExistingUpdate("stop-1", "2501191400", "2501191415") - ]); - var changes = CreateTimetable("Stuttgart Hbf", [ - CreateStopWithDeparture("stop-1", "2501191400", "10") - ]); - - var result = _merger.Merge(current, changes); - - var departure = result.Stops.First().Departure!; - Assert.Equal(new DateTime(2025, 1, 19, 14, 15, 0), departure.Time.Updated); - } - - [Fact] - public void Merge_WithMessages_ShouldCombineWithoutDuplicates() { - var current = CreateTimetable("Frankfurt Hbf", [], [ - CreateMessage("msg-1"), - CreateMessage("msg-2") - ]); - var changes = CreateTimetable("Frankfurt Hbf", [], [ - CreateMessage("msg-2"), - CreateMessage("msg-3") - ]); - - var result = _merger.Merge(current, changes); - - Assert.Equal(3, result.Messages.Count()); - Assert.Contains(result.Messages, m => m.Id == "msg-1"); - Assert.Contains(result.Messages, m => m.Id == "msg-2"); - Assert.Contains(result.Messages, m => m.Id == "msg-3"); - } - - [Fact] - public void Merge_WithEmptyCurrentMessages_OnlyTakesChangeMessages() { - var current = CreateTimetable("Frankfurt Hbf", [], []); - var changes = CreateTimetable("Frankfurt Hbf", [], [CreateMessage("msg-1"), CreateMessage("msg-2")]); - - var result = _merger.Merge(current, changes); - - Assert.Equal(2, result.Messages.Count()); - } - - [Fact] - public void Merge_WithEmptyChangeMessages_PreservesCurrentMessages() { - var current = CreateTimetable("Frankfurt Hbf", [], [CreateMessage("msg-1"), CreateMessage("msg-2")]); - var changes = CreateTimetable("Frankfurt Hbf", [], []); - - var result = _merger.Merge(current, changes); - - Assert.Equal(2, result.Messages.Count()); - } - - [Fact] - public void Merge_PreservesStation() { - var current = CreateTimetable("Leipzig Hbf", []); - var changes = CreateTimetable("Other Station", []); - - var result = _merger.Merge(current, changes); - - Assert.Equal("Leipzig Hbf", result.Station); - } - - [Fact] - public void Merge_WithDuplicateStopIdsInCurrent_TakesLastOccurrence() { - var arrivalOnly = new TimetableStop { - Id = "stop-1", - Train = new TrainLabel { Category = "NX", Number = "22064", Owner = "8000098" }, - Arrival = new TrainEvent { - Time = new ChangedValue { Original = new(2026, 1, 19, 10, 0, 0) }, - Platform = new ChangedRef { Original = "2" }, - Status = new ChangedValue { Original = EventStatus.Unknown }, - DistantEndpoint = new ChangedRef { Original = string.Empty }, - }, - }; - var withDeparture = new TimetableStop { - Id = arrivalOnly.Id, - Train = arrivalOnly.Train, - Arrival = arrivalOnly.Arrival, - Departure = new TrainEvent { - Time = new ChangedValue { Original = new(2026, 1, 19, 10, 9, 0) }, - Platform = new ChangedRef { Original = "2" }, - Status = new ChangedValue { Original = EventStatus.Unknown }, - DistantEndpoint = new ChangedRef { Original = string.Empty }, - }, - }; - var current = CreateTimetable("Essen Hbf", [arrivalOnly, withDeparture]); - var changes = CreateTimetable("Essen Hbf", []); - - var result = _merger.Merge(current, changes); - - var stop = Assert.Single(result.Stops); - Assert.NotNull(stop.Departure); - Assert.Equal(new(2026, 1, 19, 10, 9, 0), stop.Departure!.Time.Original); - } - - [Fact] - public void Merge_PreservesTrainLabel() { - var current = CreateTimetable("Dresden Hbf", [ - new TimetableStop { - Id = "stop-1", - Train = new TrainLabel { Category = "ICE", Number = "123", Owner = "80" } - } - ]); - var changes = CreateTimetable("Dresden Hbf", [ - new TimetableStop { - Id = "stop-1", - Train = new TrainLabel { Category = "RE", Number = "456", Owner = "99" } - } - ]); - - var result = _merger.Merge(current, changes); - - var stop = Assert.Single(result.Stops); - Assert.Equal("ICE", stop.Train.Category); - Assert.Equal("123", stop.Train.Number); - Assert.Equal("80", stop.Train.Owner); - } - - [Fact] - public void Merge_WithNullCurrentEvent_ShouldTakeChange() { - var current = CreateTimetable("Hannover Hbf", [CreateStop("stop-1")]); - var changes = CreateTimetable("Hannover Hbf", [ - CreateStopWithDeparture("stop-1", "2501191600", "12") - ]); - - var result = _merger.Merge(current, changes); - - var stop = Assert.Single(result.Stops); - Assert.NotNull(stop.Departure); - Assert.Equal(new DateTime(2025, 1, 19, 16, 0, 0), stop.Departure.Time.Original); - } - - [Fact] - public void Merge_WingsNonEmpty_ShouldTakeChangeWings() { - var current = CreateTimetable("Hamburg Hbf", [ - CreateStopWithWings("stop-1", "2501191000", "5", ["C"]) - ]); - var changes = CreateTimetable("Hamburg Hbf", [ - CreateStopWithWings("stop-1", "2501191000", "5", ["A", "B"]) - ]); - - var result = _merger.Merge(current, changes); - - var wings = result.Stops.First().Departure!.Wings; - Assert.Equal(2, wings.Count()); - Assert.Contains("A", wings); - Assert.Contains("B", wings); - Assert.DoesNotContain("C", wings); - } - - [Fact] - public void Merge_WingsEmpty_ShouldKeepCurrentWings() { - var current = CreateTimetable("Hamburg Hbf", [ - CreateStopWithWings("stop-1", "2501191000", "5", ["C"]) - ]); - var changes = CreateTimetable("Hamburg Hbf", [ - CreateStopWithWings("stop-1", "2501191000", "5", []) - ]); - - var result = _merger.Merge(current, changes); - - var wings = result.Stops.First().Departure!.Wings; - Assert.Single(wings); - Assert.Contains("C", wings); - } - - [Fact] - public void Merge_UpdatedEqualsOriginal_ShouldPreserveCurrentUpdate() { - var current = CreateTimetable("Berlin Hbf", [new TimetableStop { - Id = "stop-1", - Train = new TrainLabel { Category = "ICE", Number = "1", Owner = "80" }, - Departure = new TrainEvent { - Time = new ChangedValue { Original = ParseTime("2501191000") }, - Platform = new ChangedRef { Original = "5", Updated = "5A" }, - Status = new ChangedValue { Original = EventStatus.Planned }, - DistantEndpoint = new ChangedRef { Original = string.Empty }, - Path = new ChangedRef> { Original = [] } - } - }]); - var changes = CreateTimetable("Berlin Hbf", [new TimetableStop { - Id = "stop-1", - Train = new TrainLabel { Category = "ICE", Number = "1", Owner = "80" }, - Departure = new TrainEvent { - Time = new ChangedValue { Original = ParseTime("2501191000") }, - Platform = new ChangedRef { Original = "5", Updated = "5" }, - Status = new ChangedValue { Original = EventStatus.Planned }, - DistantEndpoint = new ChangedRef { Original = string.Empty }, - Path = new ChangedRef> { Original = [] } - } - }]); - - var result = _merger.Merge(current, changes); - - var platform = result.Stops.First().Departure!.Platform; - Assert.Equal("5", platform.Original); - Assert.Equal("5A", platform.Updated); - } - - [Fact] - public void Merge_WithDuplicateSimplerStopIdsInCurrent_TakesLastOccurrence() { - var current = CreateTimetable("Test", [CreateStop("dup-id"), CreateStopWithDeparture("dup-id", "2501191015", "5")]); - var changes = CreateTimetable("Test", []); - - var result = _merger.Merge(current, changes); - - var stop = Assert.Single(result.Stops); - Assert.NotNull(stop.Departure); - } - - private static Timetable CreateTimetable(string station, IReadOnlyList stops, IReadOnlyList? messages = null) => new() { - Station = station, - Stops = stops, - Messages = messages ?? [] - }; - - private static TimetableStop CreateStop(string id) => new() { - Id = id, - Train = new TrainLabel { Category = "ICE", Number = "1", Owner = "80" } - }; - - private static TimetableStop CreateStopWithDeparture(string id, string time, string platform) => new() { - Id = id, - Train = new TrainLabel { Category = "ICE", Number = "1", Owner = "80" }, - Departure = new TrainEvent { - Time = new ChangedValue { Original = ParseTime(time) }, - Platform = new ChangedRef { Original = platform }, - Status = new ChangedValue { Original = EventStatus.Planned }, - DistantEndpoint = new ChangedRef { Original = string.Empty }, - Path = new ChangedRef> { Original = [] } - } - }; - - private static TimetableStop CreateStopWithWings(string id, string time, string platform, IReadOnlyList wings) => new() { - Id = id, - Train = new TrainLabel { Category = "ICE", Number = "1", Owner = "80" }, - Departure = new TrainEvent { - Time = new ChangedValue { Original = ParseTime(time) }, - Platform = new ChangedRef { Original = platform }, - Status = new ChangedValue { Original = EventStatus.Planned }, - DistantEndpoint = new ChangedRef { Original = string.Empty }, - Path = new ChangedRef> { Original = [] }, - Wings = wings - } - }; - - private static TimetableStop CreateStopWithDepartureUpdate(string id, string? updatedTime, string? updatedPlatform) => new() { - Id = id, - Train = new TrainLabel { Category = "ICE", Number = "1", Owner = "80" }, - Departure = new TrainEvent { - Time = new ChangedValue { - Original = default, - Updated = updatedTime != null ? ParseTime(updatedTime) : null - }, - Platform = new ChangedRef { - Original = string.Empty, - Updated = updatedPlatform - }, - Status = new ChangedValue { Original = EventStatus.Planned }, - DistantEndpoint = new ChangedRef { Original = string.Empty }, - Path = new ChangedRef> { Original = [] } - } - }; - - private static TimetableStop CreateStopWithExistingUpdate(string id, string originalTime, string updatedTime) => new() { - Id = id, - Train = new TrainLabel { Category = "ICE", Number = "1", Owner = "80" }, - Departure = new TrainEvent { - Time = new ChangedValue { - Original = ParseTime(originalTime), - Updated = ParseTime(updatedTime) - }, - Platform = new ChangedRef { Original = "10" }, - Status = new ChangedValue { Original = EventStatus.Planned }, - DistantEndpoint = new ChangedRef { Original = string.Empty }, - Path = new ChangedRef> { Original = [] } - } - }; - - private static TimetableMessage CreateMessage(string id) => new() { - Id = id, - Type = MessageType.Him, - Timestamp = DateTime.Now - }; - - private static DateTime ParseTime(string time) => - DateTime.ParseExact(time, "yyMMddHHmm", System.Globalization.CultureInfo.InvariantCulture); -} diff --git a/tests/DotBahn.Timetables.Tests/Transformer/TimetableTransformerMessageTests.cs b/tests/DotBahn.Timetables.Tests/Transformer/TimetableTransformerMessageTests.cs deleted file mode 100644 index 0f05c05..0000000 --- a/tests/DotBahn.Timetables.Tests/Transformer/TimetableTransformerMessageTests.cs +++ /dev/null @@ -1,177 +0,0 @@ -using DotBahn.Timetables.Internal.Contracts; -using DotBahn.Timetables.Internal.Transformers; -using DotBahn.Timetables.Models.Enumerations; - -namespace DotBahn.Timetables.Tests.Transformer; - -public class TimetableTransformerMessageTests { - private readonly TimetableTransformer _transformer = new(); - - [Fact] - public void Transform_InternalMessage_SetsInternalTextOnly() { - var contract = WithStop(new StopDataContract { - Id = "s1", - Messages = [new MessageContract { - Id = "m1", - Type = "h", - Timestamp = "2501191200", - IsInternal = "1", - Text = "internal info" - }] - }); - - var stop = _transformer.Transform(contract).Stops.First(); - - var msg = Assert.Single(stop.Messages); - Assert.Equal("internal info", msg.InternalText); - Assert.Null(msg.ExternalText); - } - - [Fact] - public void Transform_ExternalMessage_SetsExternalTextOnly() { - var contract = WithStop(new StopDataContract { - Id = "s1", - Messages = [new MessageContract { - Id = "m1", - Type = "h", - Timestamp = "2501191200", - IsInternal = "0", - Text = "public info" - }] - }); - - var stop = _transformer.Transform(contract).Stops.First(); - - var msg = Assert.Single(stop.Messages); - Assert.Null(msg.InternalText); - Assert.Equal("public info", msg.ExternalText); - } - - [Fact] - public void Transform_DeletedMessage_SetsIsDeletedTrue() { - var contract = WithStop(new StopDataContract { - Id = "s1", - Messages = [new MessageContract { - Id = "m1", - Type = "h", - Timestamp = "2501191200", - IsDeleted = "1" - }] - }); - - var stop = _transformer.Transform(contract).Stops.First(); - - Assert.True(Assert.Single(stop.Messages).IsDeleted); - } - - [Fact] - public void Transform_NotDeletedMessage_SetsIsDeletedFalse() { - var contract = WithStop(new StopDataContract { - Id = "s1", - Messages = [new MessageContract { - Id = "m1", - Type = "h", - Timestamp = "2501191200", - IsDeleted = "0" - }] - }); - - var stop = _transformer.Transform(contract).Stops.First(); - - Assert.False(Assert.Single(stop.Messages).IsDeleted); - } - - [Fact] - public void Transform_MessageWithValidityRange_SetsValidFromAndTo() { - var contract = WithStop(new StopDataContract { - Id = "s1", - Messages = [new MessageContract { - Id = "m1", - Type = "h", - Timestamp = "2501191200", - ValidFrom = "2501190800", - ValidTo = "2501192200" - }] - }); - - var stop = _transformer.Transform(contract).Stops.First(); - - var msg = Assert.Single(stop.Messages); - Assert.Equal(new DateTime(2025, 1, 19, 8, 0, 0), msg.ValidFrom); - Assert.Equal(new DateTime(2025, 1, 19, 22, 0, 0), msg.ValidTo); - } - - [Fact] - public void Transform_StopWithoutMessages_ReturnsEmptyMessageList() { - var contract = WithStop(new StopDataContract { Id = "s1" }); - - var stop = _transformer.Transform(contract).Stops.First(); - - Assert.Empty(stop.Messages); - } - - public static TheoryData TransformMessageIsInternalClassificationCases => new() - { - { "BL—internal", "1", "secret info", "secret info", null }, - { "C1—external", "0", "public info", null, "public info" }, - { "C2—null_flag", null, "some text", null, "some text" }, - { "C3—empty_flag", "", "other text", null, "other text" }, - }; - - [Theory] - [MemberData(nameof(TransformMessageIsInternalClassificationCases))] - public void TransformMessageIsInternalClassification(string _, string? isInternal, string text, string? expectedInternal, string? expectedExternal) { - var contract = WithStop(new StopDataContract { - Id = "s1", - Messages = [new MessageContract { Id = "m1", Type = "h", Timestamp = "2501191200", IsInternal = isInternal, Text = text }] - }); - var msg = _transformer.Transform(contract).Stops.First().Messages.First(); - Assert.Equal(expectedInternal, msg.InternalText); - Assert.Equal(expectedExternal, msg.ExternalText); - } - - [Fact] - public void Transform_MessageType_ParsedCorrectly() { - var contract = WithStop(new StopDataContract { - Id = "s1", - Messages = [new MessageContract { - Id = "m1", - Type = "q", - Timestamp = "2501191200" - }] - }); - - var msg = _transformer.Transform(contract).Stops.First().Messages.First(); - - Assert.Equal(MessageType.QualityChange, msg.Type); - } - - public static TheoryData TransformMessagePriorityCases => new() - { - { "BL—none", "0", MessagePriority.None }, - { "B1—high", "1", MessagePriority.High }, - { "B2—medium", "2", MessagePriority.Medium }, - { "B3—low", "3", MessagePriority.Low }, - { "B4—done", "4", MessagePriority.Done }, - { "B5—unknown", "5", MessagePriority.Unknown }, - { "C1—undefined", "6", (MessagePriority)6 }, - { "C2—negative", "-1", (MessagePriority)(-1) }, - { "C3—unparseable", "abc", null }, - }; - - [Theory] - [MemberData(nameof(TransformMessagePriorityCases))] - public void TransformMessagePriority(string _, string priority, MessagePriority? expected) { - var contract = WithStop(new StopDataContract { - Id = "s1", - Messages = [new MessageContract { Id = "m1", Type = "h", Timestamp = "2501191200", Priority = priority }] - }); - var msg = _transformer.Transform(contract).Stops.First().Messages.First(); - Assert.Equal(expected, msg.Priority); - } - - private static TimetableResponseContract WithStop(StopDataContract stop) => new() { - Station = "Test", - Stops = [stop] - }; -} diff --git a/tests/DotBahn.Timetables.Tests/Transformer/TimetableTransformerTransformTests.cs b/tests/DotBahn.Timetables.Tests/Transformer/TimetableTransformerTransformTests.cs deleted file mode 100644 index 05b0a80..0000000 --- a/tests/DotBahn.Timetables.Tests/Transformer/TimetableTransformerTransformTests.cs +++ /dev/null @@ -1,358 +0,0 @@ -using DotBahn.Timetables.Internal.Contracts; -using DotBahn.Timetables.Internal.Transformers; -using DotBahn.Timetables.Models.Enumerations; - -namespace DotBahn.Timetables.Tests.Transformer; - -public class TimetableTransformerTransformTests { - private readonly TimetableTransformer _transformer = new(); - - [Fact] - public void Transform_WithBasicContract_ShouldSetStation() { - var contract = new TimetableResponseContract { - Station = "Hamburg Hbf", - Stops = [] - }; - - var result = _transformer.Transform(contract); - - Assert.Equal("Hamburg Hbf", result.Station); - Assert.Empty(result.Stops); - Assert.Empty(result.Messages); - } - - [Fact] - public void Transform_WithStop_ShouldTransformStopData() { - var contract = new TimetableResponseContract { - Station = "Berlin Hbf", - Stops = [ - new StopDataContract { - Id = "stop-1", - TripInfo = new TripInfoContract { - Category = "ICE", - Number = "123", - Owner = "80" - } - } - ] - }; - - var result = _transformer.Transform(contract); - - var stop = Assert.Single(result.Stops); - Assert.Equal("stop-1", stop.Id); - Assert.Equal("ICE", stop.Train.Category); - Assert.Equal("123", stop.Train.Number); - Assert.Equal("80", stop.Train.Owner); - } - - [Fact] - public void Transform_WithDeparture_ShouldTransformEvent() { - var contract = new TimetableResponseContract { - Station = "München Hbf", - Stops = [ - new StopDataContract { - Id = "stop-1", - Departure = new EventContract { - PlannedTime = "2501191430", - PlannedPlatform = "12", - PlannedPath = "Augsburg|Nürnberg|Frankfurt" - } - } - ] - }; - - var result = _transformer.Transform(contract); - - var stop = Assert.Single(result.Stops); - Assert.NotNull(stop.Departure); - Assert.Null(stop.Arrival); - Assert.Equal(new DateTime(2025, 1, 19, 14, 30, 0), stop.Departure.Time.Original); - Assert.Equal("12", stop.Departure.Platform.Original); - Assert.Equal(["Augsburg", "Nürnberg", "Frankfurt"], stop.Departure.Path.Original); - } - - [Fact] - public void Transform_WithArrival_ShouldTransformEvent() { - var contract = new TimetableResponseContract { - Station = "Köln Hbf", - Stops = [ - new StopDataContract { - Id = "stop-2", - Arrival = new EventContract { - PlannedTime = "2501191200", - PlannedPlatform = "5" - } - } - ] - }; - - var result = _transformer.Transform(contract); - - var stop = Assert.Single(result.Stops); - Assert.NotNull(stop.Arrival); - Assert.Null(stop.Departure); - Assert.Equal(new DateTime(2025, 1, 19, 12, 0, 0), stop.Arrival.Time.Original); - Assert.Equal("5", stop.Arrival.Platform.Original); - } - - [Fact] - public void Transform_WithChangedValues_ShouldSetUpdatedProperties() { - var contract = new TimetableResponseContract { - Station = "Stuttgart Hbf", - Stops = [ - new StopDataContract { - Id = "stop-3", - Departure = new EventContract { - PlannedTime = "2501191000", - PlannedPlatform = "8", - ChangedTime = "2501191015", - ChangedPlatform = "9" - } - } - ] - }; - - var result = _transformer.Transform(contract); - - var departure = result.Stops.First().Departure!; - Assert.Equal(new DateTime(2025, 1, 19, 10, 0, 0), departure.Time.Original); - Assert.Equal(new DateTime(2025, 1, 19, 10, 15, 0), departure.Time.Updated); - Assert.True(departure.Time.HasUpdate); - Assert.Equal("8", departure.Platform.Original); - Assert.Equal("9", departure.Platform.Updated); - Assert.True(departure.Platform.HasUpdate); - } - - [Fact] - public void Transform_WithoutChangedValues_ShouldNotHaveUpdates() { - var contract = new TimetableResponseContract { - Station = "Düsseldorf Hbf", - Stops = [ - new StopDataContract { - Id = "stop-4", - Departure = new EventContract { - PlannedTime = "2501191800", - PlannedPlatform = "3" - } - } - ] - }; - - var result = _transformer.Transform(contract); - - var departure = result.Stops.First().Departure!; - Assert.False(departure.Time.HasUpdate); - Assert.False(departure.Platform.HasUpdate); - Assert.Equal(departure.Time.Original, departure.Time.Actual); - Assert.Equal(departure.Platform.Original, departure.Platform.Actual); - } - - [Fact] - public void Transform_WithChangedStatus_ShouldSetStatusUpdate() { - var contract = new TimetableResponseContract { - Station = "Leipzig Hbf", - Stops = [ - new StopDataContract { - Id = "stop-5", - Departure = new EventContract { - PlannedTime = "2501191600", - PlannedStatus = "p", - ChangedStatus = "c" - } - } - ] - }; - - var result = _transformer.Transform(contract); - - var departure = result.Stops.First().Departure!; - Assert.Equal(EventStatus.Planned, departure.Status.Original); - Assert.Equal(EventStatus.Cancelled, departure.Status.Updated); - Assert.True(departure.Status.HasUpdate); - } - - [Fact] - public void Transform_WithDistantEndpoint_ShouldSetDistantEndpoint() { - var contract = new TimetableResponseContract { - Station = "Basel SBB", - Stops = [ - new StopDataContract { - Id = "stop-6", - Departure = new EventContract { - PlannedTime = "2501191400", - PlannedDistantEndpoint = "Milano Centrale", - ChangedDistantEndpoint = "Roma Termini" - } - } - ] - }; - - var result = _transformer.Transform(contract); - - var departure = result.Stops.First().Departure!; - Assert.NotNull(departure.DistantEndpoint); - Assert.Equal("Milano Centrale", departure.DistantEndpoint.Original); - Assert.Equal("Roma Termini", departure.DistantEndpoint.Updated); - } - - [Fact] - public void Transform_WithMultipleStops_ShouldTransformAll() { - var contract = new TimetableResponseContract { - Station = "Frankfurt Hbf", - Stops = [ - new StopDataContract { Id = "stop-a" }, - new StopDataContract { Id = "stop-b" }, - new StopDataContract { Id = "stop-c" } - ] - }; - - var result = _transformer.Transform(contract); - - Assert.Equal(3, result.Stops.Count()); - Assert.Contains(result.Stops, s => s.Id == "stop-a"); - Assert.Contains(result.Stops, s => s.Id == "stop-b"); - Assert.Contains(result.Stops, s => s.Id == "stop-c"); - } - - [Fact] - public void Transform_WithNullContract_ThrowsArgumentNullException() { - TimetableResponseContract contract = null!; - - var exception = Assert.Throws(() => _transformer.Transform(contract)); - Assert.Equal("contracts", exception.ParamName); - } - - [Fact] - public void Transform_WithNullTripInfo_ShouldUseDefaultValues() { - var contract = new TimetableResponseContract { - Station = "Hannover Hbf", - Stops = [ - new StopDataContract { - Id = "stop-1", - TripInfo = null - } - ] - }; - - var result = _transformer.Transform(contract); - - var stop = Assert.Single(result.Stops); - Assert.Equal(string.Empty, stop.Train.Category); - Assert.Equal(string.Empty, stop.Train.Number); - Assert.Equal(string.Empty, stop.Train.Owner); - Assert.Null(stop.Train.Type); - } - - [Fact] - public void Transform_WithNullPlannedPath_ShouldDefaultToEmptyList() { - var contract = new TimetableResponseContract { - Station = "Dortmund Hbf", - Stops = [ - new StopDataContract { - Id = "stop-1", - Departure = new EventContract { - PlannedTime = "2501191000", - PlannedPath = null - } - } - ] - }; - - var result = _transformer.Transform(contract); - - var departure = result.Stops.First().Departure!; - Assert.Empty(departure.Path.Original); - Assert.Null(departure.Path.Updated); - Assert.False(departure.Path.HasUpdate); - } - - [Fact] - public void Transform_WithNullWings_ShouldDefaultToEmptyList() { - var contract = new TimetableResponseContract { - Station = "Bremen Hbf", - Stops = [ - new StopDataContract { - Id = "stop-1", - Departure = new EventContract { - PlannedTime = "2501191000", - Wings = null - } - } - ] - }; - - var result = _transformer.Transform(contract); - - var departure = result.Stops.First().Departure!; - Assert.Empty(departure.Wings); - } - - public static TheoryData ParseBahnTimeEdgeCases => new() - { - { "BL—valid", "2501191430", new DateTime(2025, 1, 19, 14, 30, 0) }, - { "B1—leap_year", "2402291200", new DateTime(2024, 2, 29, 12, 0, 0) }, - { "B2—non_leap_feb29", "2302291200", null }, - { "B3—midnight", "2501190000", new DateTime(2025, 1, 19, 0, 0, 0) }, - { "B4—end_of_day", "2501192359", new DateTime(2025, 1, 19, 23, 59, 0) }, - { "B5—invalid_month", "2501320000", null }, - { "B6—invalid_day", "2502301200", null }, - { "B7—invalid_hour", "2501192400", null }, - { "B8—invalid_minute", "2501190060", null }, - { "B9—year_rollover", "9912311200", new DateTime(1999, 12, 31, 12, 0, 0) }, - { "B10—century_leap", "0002291200", new DateTime(2000, 2, 29, 12, 0, 0) }, - { "B11—invalid_century_day", "0102291200", null }, - }; - - [Theory] - [MemberData(nameof(ParseBahnTimeEdgeCases))] - public void ParseBahnTimeEdge(string _, string plannedTime, DateTime? expected) { - var contract = new TimetableResponseContract { - Station = "Test", - Stops = [new StopDataContract { Id = "s1", Departure = new EventContract { PlannedTime = plannedTime } }], - }; - var result = _transformer.Transform(contract); - var departure = result.Stops.First().Departure!; - - Assert.Equal(expected ?? default, departure.Time.Original); - } - - [Fact] - public void TransformWithUnrecognizedTripTypeDefaultsToPassenger() { - var contract = new TimetableResponseContract { - Station = "Test", - Stops = [new StopDataContract { - Id = "s1", - TripInfo = new TripInfoContract { TripType = "UNKNOWN_TYPE" } - }] - }; - - var result = _transformer.Transform(contract); - - Assert.Equal(TripType.Passenger, result.Stops.First().Train.Type); - } - - [Fact] - public void Transform_WithChangedStatusNull_ShouldNotSetUpdate() { - var contract = new TimetableResponseContract { - Station = "Nürnberg Hbf", - Stops = [ - new StopDataContract { - Id = "stop-1", - Departure = new EventContract { - PlannedTime = "2501191000", - PlannedStatus = "p", - ChangedStatus = null - } - } - ] - }; - - var result = _transformer.Transform(contract); - - var departure = result.Stops.First().Departure!; - Assert.Equal(EventStatus.Planned, departure.Status.Original); - Assert.Null(departure.Status.Updated); - Assert.False(departure.Status.HasUpdate); - } -} diff --git a/tests/DotBahn.Timetables.Tests/packages.lock.json b/tests/DotBahn.Timetables.Tests/packages.lock.json deleted file mode 100644 index 01cdf2f..0000000 --- a/tests/DotBahn.Timetables.Tests/packages.lock.json +++ /dev/null @@ -1,522 +0,0 @@ -{ - "version": 2, - "dependencies": { - "net10.0": { - "Microsoft.SourceLink.GitHub": { - "type": "Direct", - "requested": "[10.0.403, )", - "resolved": "10.0.403", - "contentHash": "T4WYxWydJGNQRe/EgURFlhPZ1cHYgivrCCHSomCcfQzGzhkDYGNn5bUwwjs4/PHuMxsmGaLvPv2puG8lluA1IA==", - "dependencies": { - "Microsoft.Build.Tasks.Git": "10.0.403", - "Microsoft.SourceLink.Common": "10.0.403", - "System.IO.Hashing": "10.0.14" - } - }, - "Microsoft.Testing.Extensions.CodeCoverage": { - "type": "Direct", - "requested": "[18.12.0, )", - "resolved": "18.12.0", - "contentHash": "BST/sWYpKk9OXO7Yxktcg6FWORRsHU0EdCbMwZ7d3OqJsMKlrNHIZ30g0Ib4k5T5acJYXRBmg9mNrTU/N6cy1g==", - "dependencies": { - "Microsoft.DiaSymReader": "2.2.10", - "Microsoft.Extensions.DependencyModel": "10.0.10", - "Microsoft.Testing.Platform": "2.5.0", - "Mono.Cecil": "0.11.6" - } - }, - "MinVer": { - "type": "Direct", - "requested": "[8.0.0, )", - "resolved": "8.0.0", - "contentHash": "AJy/KVjXgUbgjf6HiI8wAk4DSSq0SCmvXQF8aU6IB+pnIQq+YJvofvMczug2hqO8yEvnQY557ryew66KPpyCsA==" - }, - "Moq": { - "type": "Direct", - "requested": "[4.21.0, )", - "resolved": "4.21.0", - "contentHash": "HUjrhhzEJ/AfbSBCnR8lPkpveVGpV/dNuOlnpfqBNTME93izly1CRV4N5zBySqz4m2yCRlHLPy/PnPzYokbwIg==", - "dependencies": { - "Castle.Core": "5.2.1" - } - }, - "xunit.v3": { - "type": "Direct", - "requested": "[4.0.2, )", - "resolved": "4.0.2", - "contentHash": "TdjM2OAx7w/0E88E6PgaigLoTbQaxbSR3HF/8p92plchTjf29jPHW27ylvEOz+Nx8CvPwWKGQlOR1fDv6/Qh5A==", - "dependencies": { - "xunit.v3.mtp-v2": "[4.0.2]" - } - }, - "xunit.v3.runner.common": { - "type": "Direct", - "requested": "[4.0.2, )", - "resolved": "4.0.2", - "contentHash": "YlYKVhTJVcwEgJ6rm59Pjf71lQqKwKxEHqVRxWUuwrwm/nxB/mNFP/lP4vlntDO3GclNnLT9BjYOpJH9gViGQg==", - "dependencies": { - "Microsoft.Win32.Registry": "[5.0.0]", - "System.Security.AccessControl": "[6.0.1]", - "xunit.v3.common": "[4.0.2]" - } - }, - "Castle.Core": { - "type": "Transitive", - "resolved": "5.2.1", - "contentHash": "wHARzQA695jwwKreOzNsq54KiGqKP38tv8hi8e2FXDEC/sA6BtrX90tVPDkOfVu13PbEzr00TCV8coikl+D1Iw==", - "dependencies": { - "System.Diagnostics.EventLog": "6.0.0" - } - }, - "Microsoft.ApplicationInsights": { - "type": "Transitive", - "resolved": "2.23.0", - "contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw==" - }, - "Microsoft.Bcl.AsyncInterfaces": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg==" - }, - "Microsoft.Build.Tasks.Git": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "1furteBFeemMmZ4s+ORjQb7YtO+wG63NJahbQbRUi91FV6V87BdV0U3vX1jbMC6iKSELYYoXWssSzLu3mx0i2w==", - "dependencies": { - "System.IO.Hashing": "10.0.14" - } - }, - "Microsoft.DiaSymReader": { - "type": "Transitive", - "resolved": "2.2.10", - "contentHash": "zmGsm6b2y3STDa/Of7rdkkfTDV8VuGB8aCqIkLoJIQh5tL78K3zJ8OUyFKnfsaORXmGr9iOKwDkZfUjeXi+CwA==" - }, - "Microsoft.Extensions.AmbientMetadata.Application": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "aMCm7C6CexZT8W/p8zRp4BoxSnqRs3MmkBF7FvPIXC92b7vqs2SL0J+mVJi5W2Mk9Vb4ZRFWe9sdzFew6zUl1w==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" - } - }, - "Microsoft.Extensions.Compliance.Abstractions": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2mjAb3Sm5k6uNeI+IyXpggYMpfdDDGgZSwUm9QQsm5QgZboJWbm2eU+6wNMrlfFEao11yq6JS1zXI7SVQQ0NuQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13" - } - }, - "Microsoft.Extensions.Configuration": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "UcnvaEaMvRckDDhyqY1OZkFwBqpZArkHFKB6dWaQWT9XTuNttNNX8Cqsb/Sic2LfJxsMLJUXnYrxY3iX5LN9pQ==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4YdfvaoWn3tB1xQQHGrhRTFWJ8fGOqxThxduynSZy9ZFTiSaUi3vX4EK/kj8h2HQMwTlks9MWV1fv2WRBv5/1w==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Configuration.Binder": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "brDb5kgle2iY2lWHgeV/KOqnBEpVnlMFigGJ/WW7KP9Nj6C/t53f/h5boYyVXB0bEhgpL+ctbewDJMI+zAMj1w==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.DependencyInjection": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "2LzcuVjemeXR+WdY9wGIr8iGb7fYsDAit+IScxXX2XJnX0b++mWcE/WO6fEGIqhdMfSQM2ZS5JGMHYZix7YXZg==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.DependencyInjection.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "QtpQzuSZVyTPCuHW058yCs9Nj0394uUkNyFHS813nOmK9UgUdBdaprJ5PPsBgsQIpxADTsTkbaMMonykem6qdw==" - }, - "Microsoft.Extensions.DependencyInjection.AutoActivation": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "h/sovspxVmT2DTIbWORMG0Gi3zVcPQzNl3kbwtpo0LoUXYbe2+66wQqZYwaF2ZWKN8HDdHv5yoc7d0DbDBBlnA==", - "dependencies": { - "Microsoft.Extensions.Hosting.Abstractions": "10.0.13" - } - }, - "Microsoft.Extensions.DependencyModel": { - "type": "Transitive", - "resolved": "10.0.10", - "contentHash": "rfZA1RjR021RPqSmIPovfz2aOd79TGqJ9BengbjnzIISOVwjLmuSDnhCMmiY/1c6iYvGolQ1iNGzkav0u11XEA==" - }, - "Microsoft.Extensions.Diagnostics": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "80VqW8eKxQaxBOLDNpLUdxOlxzWn/jqBSxNBCfD8GCjcshNDpFvUgKh8uvvZwvkfBbwmNPWPWHyy9F+RLd1dlQ==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.14", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.14", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.14" - } - }, - "Microsoft.Extensions.Diagnostics.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "vm+PPso6vOwGeX52MdOPh6z/R6KHgxQUwqq7k7Jc9jhy2JOxO2KB4xfoJQBBp2Ni8M4zKgJ4r2a1dgrYG7+MKw==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Diagnostics.ExceptionSummarization": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "Dp/FaAPo3U9h3HsWT1dcdRRV//rm+MQF5iKpY/WxL5swwV+wZNE5eyJZ0kgy9Upl/kHz4ejpiLMloxDIuJaoJQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13" - } - }, - "Microsoft.Extensions.FileProviders.Abstractions": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "BZDwtN3uoWRghDi5lRRZPDjMMCg2Ds7J6YEYjqka/TLjqnzquEpXyvchrIMeoubwT1ns23ow6PPeAoBHJO81Rw==", - "dependencies": { - "Microsoft.Extensions.Primitives": "10.0.13" - } - }, - "Microsoft.Extensions.Hosting.Abstractions": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "zIrbe9vkIFXxW3mOApIOWXw+xMwX7Cgsptr3ZSlglJt4hW2qp4fB/JU1NHgAevteBNH4PicvU9DsFPHxlnnloA==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13", - "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13" - } - }, - "Microsoft.Extensions.Http.Diagnostics": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "iFcxcuMF/21LO+tDqDyzYVvokJUH03cNalmOJhmjyQSMV3dR4JAgcUBTV1iVH/yruC8wG2RNjvW0xcUgYqmrGg==", - "dependencies": { - "Microsoft.Extensions.Http": "10.0.13", - "Microsoft.Extensions.Telemetry": "10.11.0" - } - }, - "Microsoft.Extensions.Logging": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "O2fXL6JmtkFwkigxS8fPTQpLXxGDjgZco5D+h88s++Cl0bDCs023PVkpNoifciJ+f30I82jnp8tpwF0wCLdFtA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Abstractions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "SwcbEBtkECq3D2oywvHkm46fyrX9Dd2JPWphDnHUc2+cUWR1Mdo41atAjh/9iZjgQxuvbKfZKXqostT/LZfefA==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14" - } - }, - "Microsoft.Extensions.Logging.Configuration": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "OyYJOaE9WbBx1Hp+Dd2zrqeFM0JwH5M/x0VL6tNUv3V18vIAVpix8UjhvY9eW/iXpguEHy68JO/Z9YkBOwftIw==", - "dependencies": { - "Microsoft.Extensions.Configuration": "10.0.13", - "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", - "Microsoft.Extensions.Configuration.Binder": "10.0.13", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", - "Microsoft.Extensions.Logging": "10.0.13", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" - } - }, - "Microsoft.Extensions.ObjectPool": { - "type": "Transitive", - "resolved": "10.0.13", - "contentHash": "NX3bhcc0WitPKAVc9Zfi8jeEPClhfEmobUJM4a4bkWhJcBt5IWg6lCrItUoFy4whLjU+atXktURYCweQlR7wfg==" - }, - "Microsoft.Extensions.Options.ConfigurationExtensions": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "4wcIU0rE04ejEfCwHTftu9O8fgH6CRYCe+tseRapikUBn1Kic3QdO7ku22SwFyLrzdWGYPUZMEgv57ZYuuc5gA==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.Configuration.Binder": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - }, - "Microsoft.Extensions.Primitives": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "1bbZqqCJTPba3inTADExbp/9PsGVyvGOX3zr6tFr7ySCgVkX9Lpw7BV0TizktNItd3SsbUu1sQfSAYm1GZMoNw==" - }, - "Microsoft.Extensions.Resilience": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "GbN7R2BOoZf3F7aK02nz9kWf6ttbvVzpw1orGG30VmrKTmRV6pasQOCfF2fjKXyHIMC/lAiBEYHCKjgf0OiGvQ==", - "dependencies": { - "Microsoft.Extensions.Diagnostics": "10.0.13", - "Microsoft.Extensions.Diagnostics.ExceptionSummarization": "10.11.0", - "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0", - "Polly.Extensions": "8.4.2", - "Polly.RateLimiting": "8.4.2" - } - }, - "Microsoft.Extensions.Telemetry": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "2meCfABvkLPtEBBwGzItIGnhrex1AEn2N+dHvxB5UoozeX/xTtBuUz5BRdjNI5oNgd5T31kC69WWw3BHDc9iZA==", - "dependencies": { - "Microsoft.Extensions.AmbientMetadata.Application": "10.11.0", - "Microsoft.Extensions.DependencyInjection.AutoActivation": "10.11.0", - "Microsoft.Extensions.Logging.Configuration": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Telemetry.Abstractions": "10.11.0" - } - }, - "Microsoft.Extensions.Telemetry.Abstractions": { - "type": "Transitive", - "resolved": "10.11.0", - "contentHash": "FzcHRan/C2g5X5KD0kPlL4tTROFRpM8sqcXfOIi6FGLsw/d2yoOYMbLJ5hyb8N5QgOVW7e1TdwEN4zVUfcwfdw==", - "dependencies": { - "Microsoft.Extensions.Compliance.Abstractions": "10.11.0", - "Microsoft.Extensions.Logging.Abstractions": "10.0.13", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Options": "10.0.13" - } - }, - "Microsoft.SourceLink.Common": { - "type": "Transitive", - "resolved": "10.0.403", - "contentHash": "SvzUeqFGrcQxlIgjmcoSGiV5UWcPa0NCTuH69/40uSDsSD/26c6p9cH7XLAxpn+I8+2Zhl1qp+WMugl0oOwBMg==" - }, - "Microsoft.Testing.Extensions.Telemetry": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "mu2iyoHovwl0q1mGeeRU0h8+LALXC7HqbxniLa1shTKYdJGl+KPoCEgjWIQ8MLzk1tlTGPOfg1JsxdH3RxhMCA==", - "dependencies": { - "Microsoft.ApplicationInsights": "2.23.0", - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Testing.Extensions.TrxReport.Abstractions": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "DYTZAguaHz0wNJdHDTTGYOXtnlDoLoIbTMDKSApNNcytm55DJcnwpwELfQGLk5DB5QlgaEjNhnGo1Pu5QvL5VA==", - "dependencies": { - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Testing.Platform": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "FAMaFFWnULW+hDHMb40Qzhcgz9cAU2/EtgRCBNX/DdQoKo0sPG2EiY+w7bQdl/BgHnf/DbpXLbf5Xy0o15M8NA==" - }, - "Microsoft.Testing.Platform.MSBuild": { - "type": "Transitive", - "resolved": "2.5.1", - "contentHash": "lYawcAwY+h76rQmpma2n0HaL8zkOFbbKapso0Eb+uOAUQn7333pIByLftEuiO67csAoZufHNMwi6PqhNemWQXA==", - "dependencies": { - "Microsoft.Testing.Platform": "[2.5.1, 3.0.0)" - } - }, - "Microsoft.Win32.Registry": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg==" - }, - "Mono.Cecil": { - "type": "Transitive", - "resolved": "0.11.6", - "contentHash": "f33RkDtZO8VlGXCtmQIviOtxgnUdym9xx/b1p9h91CRGOsJFxCFOFK1FDbVt1OCf1aWwYejUFa2MOQyFWTFjbA==" - }, - "Polly.Core": { - "type": "Transitive", - "resolved": "8.4.2", - "contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g==" - }, - "Polly.Extensions": { - "type": "Transitive", - "resolved": "8.4.2", - "contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==", - "dependencies": { - "Microsoft.Extensions.Logging.Abstractions": "8.0.0", - "Microsoft.Extensions.Options": "8.0.0", - "Polly.Core": "8.4.2" - } - }, - "Polly.RateLimiting": { - "type": "Transitive", - "resolved": "8.4.2", - "contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==", - "dependencies": { - "Polly.Core": "8.4.2", - "System.Threading.RateLimiting": "8.0.0" - } - }, - "System.Diagnostics.EventLog": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "lcyUiXTsETK2ALsZrX+nWuHSIQeazhqPphLfaRxzdGaG93+0kELqpgEHtwWOlQe7+jSFnKwaCAgL4kjeZCQJnw==" - }, - "System.IO.Hashing": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "lVqovhCt3HlZe7ONG5ydaj6BYwYI004gldVfMMkJl/lR5ueeCtWNpW4nejOX75sPmzm8vXCxB69GqwHaYCnyUQ==" - }, - "System.Security.AccessControl": { - "type": "Transitive", - "resolved": "6.0.1", - "contentHash": "IQ4NXP/B3Ayzvw0rDQzVTYsCKyy0Jp9KI6aYcK7UnGVlR9+Awz++TIPCQtPYfLJfOpm8ajowMR09V7quD3sEHw==" - }, - "System.Threading.RateLimiting": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q==" - }, - "xunit.analyzers": { - "type": "Transitive", - "resolved": "2.2.0", - "contentHash": "dXMIIztipcAyL3a19gtUrih/RLrE33/4VJdICoinYqIXXo1KLtsMPsaQ9dO2pE8xajDguwE2kqVbBqE5/EoJ0Q==" - }, - "xunit.v3.assert": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "5PKRexYlvufWFdXenRcRGKqvaJBBZFJZpqUGlUs9p13eKEgVdOrLpkPknjzUvLY5kEUicK9871DIUDcCPA6AXA==" - }, - "xunit.v3.common": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "++CtT8daIf6qfieQev/8V88U3zViIDWou5cj+oWps1/Hf73UoaY/L0hKyi3v7Zlt3BmbU0pUc73zCB1GiB4nYA==", - "dependencies": { - "Microsoft.Bcl.AsyncInterfaces": "6.0.0" - } - }, - "xunit.v3.core.mtp-v2": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "XyPMcQRsnUQLhmBBRRgYWsuPc8TyiANzcXtqfzyWfDpPuyh3Q0K4oWozZYQKZRNGnqJ97ifD6qUDWhsEEe32uw==", - "dependencies": { - "Microsoft.Testing.Extensions.Telemetry": "2.5.1", - "Microsoft.Testing.Extensions.TrxReport.Abstractions": "2.5.1", - "Microsoft.Testing.Platform": "2.5.1", - "Microsoft.Testing.Platform.MSBuild": "2.5.1", - "xunit.v3.extensibility.core": "[4.0.2]", - "xunit.v3.runner.inproc.console": "[4.0.2]" - } - }, - "xunit.v3.extensibility.core": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "ARTt+pGyd86mdtiFBkKpyBQvRC3u0rr8oidBlII2GsAg7D6TfOsDFCsoQtFij83V5pE57m3whUIqT4xjiARXbQ==", - "dependencies": { - "xunit.v3.common": "[4.0.2]" - } - }, - "xunit.v3.mtp-v2": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "XLV32FhkuvheBStvX0DvjfPEtI+4SOVcIhnlTS+549r8VfVwsjpWdkJtQmQ7D23PA+Zoaqo+sTjBkRSkidC6Tw==", - "dependencies": { - "xunit.analyzers": "2.2.0", - "xunit.v3.assert": "[4.0.2]", - "xunit.v3.core.mtp-v2": "[4.0.2]" - } - }, - "xunit.v3.runner.inproc.console": { - "type": "Transitive", - "resolved": "4.0.2", - "contentHash": "cg4XNpCN4Ry9nswutknpreN3ckSUBwtjMRmEQSNK/sIKPo6KN5tDGGGCaHDm5HGA4yFVVtTJX65tLCsZArUNfQ==", - "dependencies": { - "xunit.v3.extensibility.core": "[4.0.2]", - "xunit.v3.runner.common": "[4.0.2]" - } - }, - "dotbahn.common": { - "type": "Project", - "dependencies": { - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Options": "[10.0.14, )" - } - }, - "dotbahn.common.tests": { - "type": "Project", - "dependencies": { - "DotBahn.Common": "[1.0.0, )", - "Microsoft.Testing.Extensions.CodeCoverage": "[18.12.0, )", - "Moq": "[4.21.0, )", - "xunit.v3": "[4.0.2, )", - "xunit.v3.runner.common": "[4.0.2, )" - } - }, - "dotbahn.timetables": { - "type": "Project", - "dependencies": { - "DotBahn.Common": "[1.0.0, )", - "Microsoft.Extensions.Http": "[10.0.14, )", - "Microsoft.Extensions.Http.Resilience": "[10.11.0, )", - "Microsoft.Extensions.Options": "[10.0.14, )" - } - }, - "Microsoft.Extensions.Http": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "IDsXLGGz7nJMsqspWnErsP18WyAVf6V9Ixl4p47/8/95Jak3ZA1YWhQ0iesMVwubVhkVZGoO9m9ADUnK0m6HLw==", - "dependencies": { - "Microsoft.Extensions.Configuration.Abstractions": "10.0.14", - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Diagnostics": "10.0.14", - "Microsoft.Extensions.Logging": "10.0.14", - "Microsoft.Extensions.Logging.Abstractions": "10.0.14", - "Microsoft.Extensions.Options": "10.0.14" - } - }, - "Microsoft.Extensions.Http.Resilience": { - "type": "CentralTransitive", - "requested": "[10.11.0, )", - "resolved": "10.11.0", - "contentHash": "6/YEoPCcQLzExm4x4FH5c38JffbhkMaTtXsrDmYNozt9KRtdXK3TsDeuKSBZJno+41oIDGBONb2up0zCsuEERw==", - "dependencies": { - "Microsoft.Extensions.Http.Diagnostics": "10.11.0", - "Microsoft.Extensions.ObjectPool": "10.0.13", - "Microsoft.Extensions.Resilience": "10.11.0" - } - }, - "Microsoft.Extensions.Options": { - "type": "CentralTransitive", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "EeN/33S418m9oWEaZY4N5T+BNxtOqNTIFoFbIgBKwylh4OJPKIWFAzbIhpTdNbwUs26MhkmbLCAbdY+YCJ1dIQ==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.14", - "Microsoft.Extensions.Primitives": "10.0.14" - } - } - } - } -} \ No newline at end of file