Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(graphql): Add model property names test #1434

Merged
merged 4 commits into from
Nov 11, 2024

Conversation

oskogstad
Copy link
Collaborator

@oskogstad oskogstad commented Nov 10, 2024

Tests ensuring property/enum values are matching from domain => graphql
Adds test for Dialog, Transmissions, GuiAction, and Attatchments

Summary by CodeRabbit

  • New Features

    • Introduced unit tests for various GraphQL object types, ensuring property names match their corresponding domain entities.
    • Added tests for Attachment, DialogEntity, GuiAction, and Transmission types to enhance reliability and consistency.
  • Tests

    • Implemented multiple test methods to validate property names and report discrepancies clearly.

@oskogstad oskogstad requested a review from a team as a code owner November 10, 2024 23:28
Copy link
Contributor

coderabbitai bot commented Nov 10, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces a series of unit tests across multiple files to validate the property names of various GraphQL object types against their corresponding domain entities. The tests ensure that the GraphQL representations accurately reflect the structure of the domain models by comparing property names, while excluding specific properties from the validation process.

Changes

File Change Summary
tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/AttachmentTests.cs Added AttachmentTests class with methods to validate property names of Attachment and AttachmentUrl.
tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/DialogEntityTests.cs Added DialogEntityTests class to validate property names of DialogEntity and DialogStatus.
tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/GuiActionTests.cs Added GuiActionTests class with methods to validate property names of GuiAction and GuiActionPriority.
tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/TransmissionTests.cs Added DialogTransmissionTests class with methods to validate property names of DialogTransmission and DialogTransmissionType.Values.

Possibly related PRs

Suggested reviewers

  • arealmaas
  • elsand

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (10)
tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/TransmissionTests.cs (2)

8-37: Add XML documentation to explain the test's purpose and property exclusions.

The test would benefit from documentation explaining why certain properties are excluded from the comparison.

Apply this diff:

+    /// <summary>
+    /// Validates that all properties from the domain DialogTransmission entity are represented in the GraphQL Transmission type.
+    /// </summary>
+    /// <remarks>
+    /// Properties are excluded from validation when they:
+    /// - Represent navigation properties (e.g., RelatedTransmission, Dialog)
+    /// - Are internal identifiers (e.g., DialogId, TypeId)
+    /// - Represent collections (e.g., Activities, RelatedTransmissions)
+    /// </remarks>
     [Fact]
     public void Transmission_Object_Type_Should_Match_Property_Names_On_DialogTransmission()

22-37: Consider enhancing the property validation.

The current implementation has some limitations:

  1. Case-insensitive comparison might mask naming inconsistencies
  2. Only checks for missing properties in one direction
  3. No validation that GraphQL doesn't have extra properties

Consider this enhanced implementation:

-        var domainTransmissionProperties = typeof(DialogTransmission)
+        var domainProperties = typeof(DialogTransmission)
             .GetProperties()
             .Select(p => p.Name)
             .Where(name => !ignoreList.Contains(name))
             .ToList();
 
-        var transmissionProperties = typeof(Transmission)
+        var graphqlProperties = typeof(Transmission)
             .GetProperties()
             .Select(p => p.Name)
             .ToList();
 
-        var missingProperties = domainTransmissionProperties.Except(transmissionProperties, StringComparer.OrdinalIgnoreCase).ToList();
+        // Check for case-sensitive matches
+        var missingInGraphQL = domainProperties.Except(graphqlProperties).ToList();
+        var extraInGraphQL = graphqlProperties.Except(domainProperties).ToList();
+        
+        // Check for case mismatches
+        var caseMismatches = domainProperties
+            .Where(dp => graphqlProperties.Any(gp => 
+                string.Equals(dp, gp, StringComparison.OrdinalIgnoreCase) && 
+                !string.Equals(dp, gp, StringComparison.Ordinal)))
+            .ToList();
 
         // Assert
-        Assert.True(missingProperties.Count == 0, $"Properties missing in graphql transmission: {string.Join(", ", missingProperties)}");
+        Assert.Empty(missingInGraphQL, $"Properties missing in GraphQL: {string.Join(", ", missingInGraphQL)}");
+        Assert.Empty(extraInGraphQL, $"Extra properties in GraphQL: {string.Join(", ", extraInGraphQL)}");
+        Assert.Empty(caseMismatches, $"Properties with case mismatches: {string.Join(", ", caseMismatches)}");
tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/GuiActionTests.cs (2)

12-20: Document the rationale for ignored properties.

Consider adding XML comments or a summary explaining why these specific properties are excluded from the comparison. This helps future maintainers understand the test's assumptions.

+        // Properties excluded from comparison:
+        // - CreatedAt/UpdatedAt: Internal tracking fields not exposed in GraphQL
+        // - PriorityId/HttpMethodId: Internal FK fields represented differently in GraphQL
+        // - DialogId/Dialog: Navigation properties handled separately in GraphQL
         var ignoreList = new List<string>

22-40: Consider enhancing test maintainability and coverage.

A few suggestions to improve this test:

  1. Extract the property comparison logic into a reusable helper method
  2. Add a reverse check to ensure no extra properties exist in GraphQL type
  3. Enhance the assertion message with both expected and actual property sets

Here's a suggested refactor:

+    private static void AssertPropertyNamesMatch<TDomain, TGraphQL>(
+        IEnumerable<string> ignoreList = null)
+    {
+        var domainProps = typeof(TDomain).GetProperties()
+            .Select(p => p.Name)
+            .Where(name => ignoreList?.Contains(name) != true)
+            .ToList();
+
+        var graphqlProps = typeof(TGraphQL).GetProperties()
+            .Select(p => p.Name)
+            .ToList();
+
+        var missingInGraphQL = domainProps
+            .Except(graphqlProps, StringComparer.OrdinalIgnoreCase)
+            .ToList();
+
+        var extraInGraphQL = graphqlProps
+            .Except(domainProps, StringComparer.OrdinalIgnoreCase)
+            .ToList();
+
+        Assert.True(
+            missingInGraphQL.Count == 0 && extraInGraphQL.Count == 0,
+            $"""
+            Property name mismatch between {typeof(TDomain).Name} and {typeof(TGraphQL).Name}:
+            Missing in GraphQL: {string.Join(", ", missingInGraphQL)}
+            Extra in GraphQL: {string.Join(", ", extraInGraphQL)}
+            """);
+    }
tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/DialogEntityTests.cs (4)

14-22: Document the rationale for ignored properties.

Consider adding comments explaining why each property is excluded from the comparison. This will help future maintainers understand the test's design decisions.

 var ignoreList = new List<string>
 {
+    // Excluded as it's an internal tracking property
     nameof(DialogEntity.Deleted),
+    // Excluded as it's an internal timestamp
     nameof(DialogEntity.DeletedAt),
+    // Excluded as it's replaced by Status in GraphQL
     nameof(DialogEntity.StatusId),
+    // Excluded as it's handled differently in GraphQL
     nameof(DialogEntity.SearchTags),
     nameof(DialogEntity.SeenLog),
     nameof(DialogEntity.DialogEndUserContext)
 };

24-39: Consider refactoring for better maintainability and clarity.

The property comparison logic could be improved for better maintainability and more precise error reporting.

Consider these improvements:

+private static readonly IReadOnlySet<string> IgnoredProperties = new HashSet<string>
+{
+    nameof(DialogEntity.Deleted),
+    // ... other properties
+};
+
+private static List<string> GetPropertyNames(Type type, ISet<string> ignoreList = null) =>
+    type.GetProperties()
+        .Select(p => p.Name)
+        .Where(name => ignoreList?.Contains(name) != true)
+        .ToList();
+
 [Fact]
 public void Dialog_Object_Type_Should_Match_Property_Names_On_DialogEntity()
 {
-    // Arrange
-    var ignoreList = new List<string>
-    {
-        // ... current list
-    };
-
-    var dialogProperties = typeof(DialogEntity)
-        .GetProperties()
-        .Select(p => p.Name)
-        .Where(name => !ignoreList.Contains(name))
-        .ToList();
-
-    var domainDialogProperties = typeof(Dialog)
-        .GetProperties()
-        .Select(p => p.Name)
-        .ToList();
+    var dialogProperties = GetPropertyNames(typeof(DialogEntity), IgnoredProperties);
+    var domainDialogProperties = GetPropertyNames(typeof(Dialog));
 
     var missingProperties = dialogProperties.Except(domainDialogProperties, StringComparer.OrdinalIgnoreCase).ToList();
 
-    // Assert
-    Assert.True(missingProperties.Count == 0, $"Properties missing in graphql dialog: {string.Join(", ", missingProperties)}");
+    Assert.Empty(missingProperties);
 }

41-59: Consider standardizing the test implementation.

This test could benefit from the same improvements suggested for the first test method. Additionally, consider making the comparison case-sensitive to catch potential casing mismatches.

 [Fact]
 public void DialogStatus_Object_Type_Should_Match_Property_Names_On_DialogStatusValues()
 {
-    // Arrange
-    var dialogStatusValues = typeof(DialogStatus)
-        .GetProperties()
-        .Select(p => p.Name)
-        .ToList();
-
-    var domainDialogStatusValues = typeof(DialogStatusValues)
-        .GetProperties()
-        .Select(p => p.Name)
-        .ToList();
+    var dialogStatusValues = GetPropertyNames(typeof(DialogStatus));
+    var domainDialogStatusValues = GetPropertyNames(typeof(DialogStatusValues));
 
-    var missingProperties = domainDialogStatusValues.Except(dialogStatusValues, StringComparer.OrdinalIgnoreCase).ToList();
+    // Use case-sensitive comparison to catch casing mismatches
+    var missingProperties = domainDialogStatusValues.Except(dialogStatusValues).ToList();
 
-    // Assert
-    Assert.True(missingProperties.Count == 0, $"Properties missing in graphql dialog status: {string.Join(", ", missingProperties)}");
+    Assert.Empty(missingProperties);
 }

8-60: Consider enhancing the test architecture.

The tests could benefit from a more structured approach to improve maintainability and readability:

  1. Consider implementing a custom assertion for property comparison:
public static class PropertyAssert
{
    public static void PropertiesMatch<T1, T2>(
        ISet<string> ignoredProperties = null,
        bool caseSensitive = true)
    {
        var comparer = caseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
        // ... implementation
    }
}
  1. Consider using the test data builder pattern if the test setup grows more complex.

This would make the tests more maintainable and provide better error messages.

tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/AttachmentTests.cs (2)

1-2: Consider more explicit type aliases.

The current aliases could be more descriptive to better distinguish between GraphQL and domain types.

-using Attachment = Digdir.Domain.Dialogporten.GraphQL.EndUser.DialogById.Attachment;
-using DomainAttachmentUrl = Digdir.Domain.Dialogporten.Domain.Attachments.AttachmentUrl;
+using GraphQlAttachment = Digdir.Domain.Dialogporten.GraphQL.EndUser.DialogById.Attachment;
+using GraphQlAttachmentUrl = Digdir.Domain.Dialogporten.GraphQL.EndUser.DialogById.AttachmentUrl;
+using DomainAttachment = Digdir.Domain.Dialogporten.Domain.Attachments.Attachment;
+using DomainAttachmentUrl = Digdir.Domain.Dialogporten.Domain.Attachments.AttachmentUrl;

6-70: Consider extracting common test logic to a base class.

Both test methods share similar property comparison logic. Consider creating a base test class to reduce code duplication and standardize the testing approach across all GraphQL type tests.

Example base class:

public abstract class GraphQlTypeTestBase
{
    protected void ValidatePropertyNames<TGraphQl, TDomain>(IEnumerable<string> ignoreList)
    {
        var graphQlProperties = typeof(TGraphQl)
            .GetProperties()
            .Select(p => p.Name)
            .ToList();

        var domainProperties = typeof(TDomain)
            .GetProperties()
            .Select(p => p.Name)
            .Where(name => !ignoreList.Contains(name))
            .ToList();

        var missingProperties = domainProperties
            .Except(graphQlProperties, StringComparer.OrdinalIgnoreCase)
            .ToList();

        var extraProperties = graphQlProperties
            .Except(domainProperties, StringComparer.OrdinalIgnoreCase)
            .ToList();

        Assert.True(missingProperties.Count == 0,
            $"Properties missing in GraphQL type: {string.Join(", ", missingProperties)}");
        Assert.True(extraProperties.Count == 0,
            $"Extra properties in GraphQL type: {string.Join(", ", extraProperties)}");
    }
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a1e89fb and 48311ed.

📒 Files selected for processing (4)
  • tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/AttachmentTests.cs (1 hunks)
  • tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/DialogEntityTests.cs (1 hunks)
  • tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/GuiActionTests.cs (1 hunks)
  • tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/TransmissionTests.cs (1 hunks)
🔇 Additional comments (3)
tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/TransmissionTests.cs (1)

1-5: LGTM! Clean and minimal imports.

The imports are focused and relevant to the test requirements.

tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/DialogEntityTests.cs (1)

1-6: LGTM! Well-organized imports with clear alias usage.

The imports are properly organized and use clear aliases to avoid naming conflicts between domain and GraphQL types.

tests/Digdir.Domain.Dialogporten.GraphQl.Unit.Tests/ObjectTypes/AttachmentTests.cs (1)

38-69: Document property exclusions and consider design implications.

The large number of excluded properties might indicate a potential mismatch between the domain and GraphQL models.

Let's verify if these exclusions are consistent with other similar tests:

Consider:

  1. Adding XML documentation explaining why each property is excluded
  2. Evaluating if the GraphQL type could better align with the domain model
  3. Adding bidirectional validation like in the previous test
+    /// <summary>
+    /// Validates that all domain model properties are present in the GraphQL type, excluding:
+    /// - CreatedAt, UpdatedAt: Audit fields not exposed in GraphQL
+    /// - ConsumerTypeId, AttachmentId: Internal reference fields
+    /// - Attachment: Navigation property handled separately
+    /// </summary>
     [Fact]
     public void AttachmentUrl_Object_Type_Should_Match_Property_Names_On_DialogAttachmentUrl()
     {
         // Similar improvements as suggested for the first test method
     }
✅ Verification successful

The search results show a consistent pattern across multiple test files where certain properties are excluded from GraphQL types. These exclusions follow clear patterns:

  1. Audit fields (CreatedAt, UpdatedAt, Deleted, DeletedAt)
  2. Internal IDs and references (ConsumerTypeId, AttachmentId, PriorityId, HttpMethodId, StatusId)
  3. Navigation properties (Attachment, Dialog, RelatedTransmission, etc.)

Property exclusions follow established patterns and architectural decisions

The large number of excluded properties in the AttachmentUrl test aligns with the project's consistent approach across different GraphQL types, where:

  • Audit fields are systematically excluded from the GraphQL layer
  • Internal IDs and references are hidden from the public API
  • Navigation properties are handled separately in the GraphQL schema
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar property exclusion patterns in other test files
rg -A 5 "ignoreList = new List<string>" tests/

Length of output: 3758

Comment on lines +39 to +57
[Fact]
public void TransmissionType_Object_Type_Should_Match_Property_Names_On_DialogTransmissionTypeValues()
{
// Arrange
var transmissionTypes = typeof(TransmissionType)
.GetFields()
.Select(f => f.Name)
.ToList();

var domainTransmissionTypes = typeof(DialogTransmissionType.Values)
.GetFields()
.Select(f => f.Name)
.ToList();

var missingProperties = domainTransmissionTypes.Except(transmissionTypes, StringComparer.OrdinalIgnoreCase).ToList();

// Assert
Assert.True(missingProperties.Count == 0, $"Properties missing in graphql TransmissionType: {string.Join(", ", missingProperties)}");
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance enum validation and add documentation.

The test would benefit from documentation and more thorough validation.

Apply these improvements:

+    /// <summary>
+    /// Validates that all enum values from the domain DialogTransmissionType are represented in the GraphQL TransmissionType.
+    /// </summary>
     [Fact]
     public void TransmissionType_Object_Type_Should_Match_Property_Names_On_DialogTransmissionTypeValues()
     {
         // Arrange
-        var transmissionTypes = typeof(TransmissionType)
+        var graphqlEnumValues = typeof(TransmissionType)
             .GetFields()
-            .Select(f => f.Name)
+            .Where(f => f.IsLiteral && !f.IsSpecialName)
+            .ToDictionary(f => f.Name, f => f.GetRawConstantValue())
             .ToList();
 
-        var domainTransmissionTypes = typeof(DialogTransmissionType.Values)
+        var domainEnumValues = typeof(DialogTransmissionType.Values)
             .GetFields()
-            .Select(f => f.Name)
+            .Where(f => f.IsLiteral && !f.IsSpecialName)
+            .ToDictionary(f => f.Name, f => f.GetRawConstantValue())
             .ToList();
 
-        var missingProperties = domainTransmissionTypes.Except(transmissionTypes, StringComparer.OrdinalIgnoreCase).ToList();
+        var missingInGraphQL = domainEnumValues.Keys
+            .Except(graphqlEnumValues.Keys)
+            .ToList();
+
+        var extraInGraphQL = graphqlEnumValues.Keys
+            .Except(domainEnumValues.Keys)
+            .ToList();
+
+        var valueMismatches = domainEnumValues
+            .Where(dv => graphqlEnumValues.ContainsKey(dv.Key) && 
+                  !Equals(dv.Value, graphqlEnumValues[dv.Key]))
+            .Select(dv => dv.Key)
+            .ToList();
 
         // Assert
-        Assert.True(missingProperties.Count == 0, $"Properties missing in graphql TransmissionType: {string.Join(", ", missingProperties)}");
+        Assert.Empty(missingInGraphQL, 
+            $"Enum values missing in GraphQL: {string.Join(", ", missingInGraphQL)}");
+        Assert.Empty(extraInGraphQL, 
+            $"Extra enum values in GraphQL: {string.Join(", ", extraInGraphQL)}");
+        Assert.Empty(valueMismatches, 
+            $"Enum values with mismatched values: {string.Join(", ", valueMismatches)}");
     }

This enhancement:

  1. Adds documentation explaining the test's purpose
  2. Validates both enum names and their underlying values
  3. Checks for missing and extra values in both directions
  4. Provides clearer error messages
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
[Fact]
public void TransmissionType_Object_Type_Should_Match_Property_Names_On_DialogTransmissionTypeValues()
{
// Arrange
var transmissionTypes = typeof(TransmissionType)
.GetFields()
.Select(f => f.Name)
.ToList();
var domainTransmissionTypes = typeof(DialogTransmissionType.Values)
.GetFields()
.Select(f => f.Name)
.ToList();
var missingProperties = domainTransmissionTypes.Except(transmissionTypes, StringComparer.OrdinalIgnoreCase).ToList();
// Assert
Assert.True(missingProperties.Count == 0, $"Properties missing in graphql TransmissionType: {string.Join(", ", missingProperties)}");
}
/// <summary>
/// Validates that all enum values from the domain DialogTransmissionType are represented in the GraphQL TransmissionType.
/// </summary>
[Fact]
public void TransmissionType_Object_Type_Should_Match_Property_Names_On_DialogTransmissionTypeValues()
{
// Arrange
var graphqlEnumValues = typeof(TransmissionType)
.GetFields()
.Where(f => f.IsLiteral && !f.IsSpecialName)
.ToDictionary(f => f.Name, f => f.GetRawConstantValue())
.ToList();
var domainEnumValues = typeof(DialogTransmissionType.Values)
.GetFields()
.Where(f => f.IsLiteral && !f.IsSpecialName)
.ToDictionary(f => f.Name, f => f.GetRawConstantValue())
.ToList();
var missingInGraphQL = domainEnumValues.Keys
.Except(graphqlEnumValues.Keys)
.ToList();
var extraInGraphQL = graphqlEnumValues.Keys
.Except(domainEnumValues.Keys)
.ToList();
var valueMismatches = domainEnumValues
.Where(dv => graphqlEnumValues.ContainsKey(dv.Key) &&
!Equals(dv.Value, graphqlEnumValues[dv.Key]))
.Select(dv => dv.Key)
.ToList();
// Assert
Assert.Empty(missingInGraphQL,
$"Enum values missing in GraphQL: {string.Join(", ", missingInGraphQL)}");
Assert.Empty(extraInGraphQL,
$"Extra enum values in GraphQL: {string.Join(", ", extraInGraphQL)}");
Assert.Empty(valueMismatches,
$"Enum values with mismatched values: {string.Join(", ", valueMismatches)}");
}

Comment on lines +42 to +63
[Fact]
public void GuiActionPriority_Object_Type_Should_Match_Property_Names_On_DialogGuiActionPriorityValues()
{
// Arrange
var guiActionPriorities = typeof(GuiActionPriority)
.GetProperties()
.Select(p => p.Name)
.ToList();

var domainGuiActionPriorities = typeof(DialogGuiActionPriority.Values)
.GetProperties()
.Select(p => p.Name)
.ToList();

var missingProperties = domainGuiActionPriorities
.Except(guiActionPriorities, StringComparer.OrdinalIgnoreCase)
.ToList();

// Assert
Assert.True(missingProperties.Count == 0,
$"Properties missing in graphql GuiActionPriority: {string.Join(", ", missingProperties)}");
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance enum value validation.

The current test only checks property names but for enums, we should also validate that the actual values match between domain and GraphQL types.

Consider adding value comparison:

     [Fact]
     public void GuiActionPriority_Object_Type_Should_Match_Property_Names_On_DialogGuiActionPriorityValues()
     {
-        // Arrange
-        var guiActionPriorities = typeof(GuiActionPriority)
-            .GetProperties()
-            .Select(p => p.Name)
-            .ToList();
-
-        var domainGuiActionPriorities = typeof(DialogGuiActionPriority.Values)
-            .GetProperties()
-            .Select(p => p.Name)
-            .ToList();
-
-        var missingProperties = domainGuiActionPriorities
-            .Except(guiActionPriorities, StringComparer.OrdinalIgnoreCase)
-            .ToList();
-
-        // Assert
-        Assert.True(missingProperties.Count == 0,
-            $"Properties missing in graphql GuiActionPriority: {string.Join(", ", missingProperties)}");
+        // Check property names
+        AssertPropertyNamesMatch<DialogGuiActionPriority.Values, GuiActionPriority>();
+
+        // Check enum values match
+        var domainValues = typeof(DialogGuiActionPriority.Values)
+            .GetProperties()
+            .ToDictionary(p => p.Name, p => p.GetValue(null));
+
+        var graphqlValues = typeof(GuiActionPriority)
+            .GetProperties()
+            .ToDictionary(p => p.Name, p => p.GetValue(null));
+
+        foreach (var (name, domainValue) in domainValues)
+        {
+            Assert.True(
+                graphqlValues.TryGetValue(name, out var graphqlValue) && 
+                domainValue?.ToString() == graphqlValue?.ToString(),
+                $"Value mismatch for {name}: Domain={domainValue}, GraphQL={graphqlValue}");
+        }
     }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +8 to +36
[Fact]
public void Attachment_Object_Type_Should_Match_Property_Names_On_AttachmentEntity()
{
// Arrange
var ignoreList = new List<string>
{
nameof(Domain.Attachments.Attachment.CreatedAt),
nameof(Domain.Attachments.Attachment.UpdatedAt)
};

var attachmentProperties = typeof(Attachment)
.GetProperties()
.Select(p => p.Name)
.ToList();

var domainAttachmentProperties = typeof(Domain.Attachments.Attachment)
.GetProperties()
.Select(p => p.Name)
.Where(name => !ignoreList.Contains(name))
.ToList();

var missingProperties = domainAttachmentProperties
.Except(attachmentProperties, StringComparer.OrdinalIgnoreCase)
.ToList();

// Assert
Assert.True(missingProperties.Count == 0,
$"Properties missing in graphql Attachment: {string.Join(", ", missingProperties)}");
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance test coverage and documentation.

While the test validates domain properties exist in GraphQL type, consider these improvements:

  1. Add XML documentation explaining the test's purpose and excluded properties
  2. Add bidirectional validation to ensure GraphQL type doesn't have extra properties
  3. Add test cases for inheritance scenarios
+    /// <summary>
+    /// Validates that all domain model properties (except audit fields) are present in the GraphQL type.
+    /// Excluded properties:
+    /// - CreatedAt: Audit field not exposed in GraphQL
+    /// - UpdatedAt: Audit field not exposed in GraphQL
+    /// </summary>
     [Fact]
     public void Attachment_Object_Type_Should_Match_Property_Names_On_AttachmentEntity()
     {
         // Arrange
         var ignoreList = new List<string>
         {
             nameof(Domain.Attachments.Attachment.CreatedAt),
             nameof(Domain.Attachments.Attachment.UpdatedAt)
         };

         var attachmentProperties = typeof(Attachment)
             .GetProperties()
             .Select(p => p.Name)
             .ToList();

         var domainAttachmentProperties = typeof(Domain.Attachments.Attachment)
             .GetProperties()
             .Select(p => p.Name)
             .Where(name => !ignoreList.Contains(name))
             .ToList();

+        // Check domain properties exist in GraphQL type
         var missingProperties = domainAttachmentProperties
             .Except(attachmentProperties, StringComparer.OrdinalIgnoreCase)
             .ToList();

+        // Check no extra properties in GraphQL type
+        var extraProperties = attachmentProperties
+            .Except(domainAttachmentProperties, StringComparer.OrdinalIgnoreCase)
+            .ToList();

         // Assert
         Assert.True(missingProperties.Count == 0,
             $"Properties missing in graphql Attachment: {string.Join(", ", missingProperties)}");
+        Assert.True(extraProperties.Count == 0,
+            $"Extra properties in graphql Attachment: {string.Join(", ", extraProperties)}");
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
[Fact]
public void Attachment_Object_Type_Should_Match_Property_Names_On_AttachmentEntity()
{
// Arrange
var ignoreList = new List<string>
{
nameof(Domain.Attachments.Attachment.CreatedAt),
nameof(Domain.Attachments.Attachment.UpdatedAt)
};
var attachmentProperties = typeof(Attachment)
.GetProperties()
.Select(p => p.Name)
.ToList();
var domainAttachmentProperties = typeof(Domain.Attachments.Attachment)
.GetProperties()
.Select(p => p.Name)
.Where(name => !ignoreList.Contains(name))
.ToList();
var missingProperties = domainAttachmentProperties
.Except(attachmentProperties, StringComparer.OrdinalIgnoreCase)
.ToList();
// Assert
Assert.True(missingProperties.Count == 0,
$"Properties missing in graphql Attachment: {string.Join(", ", missingProperties)}");
}
/// <summary>
/// Validates that all domain model properties (except audit fields) are present in the GraphQL type.
/// Excluded properties:
/// - CreatedAt: Audit field not exposed in GraphQL
/// - UpdatedAt: Audit field not exposed in GraphQL
/// </summary>
[Fact]
public void Attachment_Object_Type_Should_Match_Property_Names_On_AttachmentEntity()
{
// Arrange
var ignoreList = new List<string>
{
nameof(Domain.Attachments.Attachment.CreatedAt),
nameof(Domain.Attachments.Attachment.UpdatedAt)
};
var attachmentProperties = typeof(Attachment)
.GetProperties()
.Select(p => p.Name)
.ToList();
var domainAttachmentProperties = typeof(Domain.Attachments.Attachment)
.GetProperties()
.Select(p => p.Name)
.Where(name => !ignoreList.Contains(name))
.ToList();
// Check domain properties exist in GraphQL type
var missingProperties = domainAttachmentProperties
.Except(attachmentProperties, StringComparer.OrdinalIgnoreCase)
.ToList();
// Check no extra properties in GraphQL type
var extraProperties = attachmentProperties
.Except(domainAttachmentProperties, StringComparer.OrdinalIgnoreCase)
.ToList();
// Assert
Assert.True(missingProperties.Count == 0,
$"Properties missing in graphql Attachment: {string.Join(", ", missingProperties)}");
Assert.True(extraProperties.Count == 0,
$"Extra properties in graphql Attachment: {string.Join(", ", extraProperties)}");
}

Copy link

@oskogstad oskogstad merged commit fec472b into main Nov 11, 2024
18 checks passed
@oskogstad oskogstad deleted the chore/add-graphql-model-tests branch November 11, 2024 09:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants