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

test(workflow): add integration tests for workflow controller #2888

Merged
merged 7 commits into from
Dec 15, 2024

Conversation

tomer-shvadron
Copy link
Collaborator

@tomer-shvadron tomer-shvadron commented Dec 11, 2024

  • Create integration tests for the external workflow controller
  • Validate authentication and input parameters in various scenarios

(your test suite is so long, I half expect it to come with a subscription plan)

Summary by CodeRabbit

  • New Features

    • Introduced a comprehensive suite of integration tests for the external workflow controller.
    • Enhanced validation and error handling in workflow creation and update processes.
  • Bug Fixes

    • Improved error handling for invalid documents and workflow definitions.
  • Documentation

    • Updated method signatures to reflect changes in validation logic and error handling.

- Create integration tests for the external workflow controller
- Validate authentication and input parameters in various scenarios

(your test suite is so long, I half expect it to come with a subscription plan)
Copy link

changeset-bot bot commented Dec 11, 2024

⚠️ No Changeset found

Latest commit: fe6fbd7

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

Walkthrough

The pull request introduces a suite of integration tests for the external workflow controller in a NestJS application, specifically targeting the /api/v1/external/workflows endpoint. It includes tests for both unauthenticated and authenticated requests, validating various scenarios and error conditions. Additionally, modifications to the WorkflowControllerExternal and WorkflowService classes enhance validation and error handling, ensuring the API behaves predictably under different conditions.

Changes

File Path Change Summary
services/workflows-service/src/workflow/workflow.controller.external.intg.test.ts Added integration tests for the external workflow controller, covering various scenarios including authentication and error handling.
services/workflows-service/src/workflow/workflow.controller.external.ts Updated validation logic and error handling in createWorkflowRuntimeData and updateById methods.
services/workflows-service/src/workflow/workflow.service.ts Modified validation in __validateWorkflowDefinitionContext and improved error handling in runOCROnDocument.

Possibly related PRs

Suggested reviewers

  • liorzam
  • alonp99

Poem

🐰 In the garden where workflows bloom,
New tests sprout, dispelling the gloom.
With checks for the tokens, both right and wrong,
Our API dances, robust and strong.
So hop along, dear friends, let's play,
For the code is now bright, come what may! 🌼


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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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: 2

🧹 Outside diff range and nitpick comments (3)
services/workflows-service/src/workflow/workflow.controller.external.intg.test.ts (3)

1-175: LGTM! Test setup is comprehensive and well-structured.

The test setup follows best practices with proper isolation and dependencies initialization. Consider extracting the test data creation into helper functions for better reusability across test files.

Consider refactoring the test data creation into helper functions:

const createTestWorkflowDefinition = async (workflowDefinitionRepository: WorkflowDefinitionRepository, projectId: string) => {
  return await workflowDefinitionRepository.create({
    data: {
      id: 'workflow-id',
      name: 'workflow-name',
      definitionType: 'statechart-json',
      definition: {},
      project: {
        connect: {
          id: projectId,
        },
      },
    },
  });
};

177-199: LGTM! Authentication test cases are well-defined.

The tests properly validate unauthorized access scenarios. Consider enhancing the error message validation to ensure proper error responses.

Add error message validation:

 it('should return 401 when not recieving authorization token', async () => {
   const res = await request(app.getHttpServer())
     .post('/external/workflows/run')
     .send({});

   expect(res.statusCode).toEqual(401);
+  expect(res.body).toEqual({
+    message: 'Unauthorized',
+    statusCode: 401
+  });
 });

201-287: LGTM! Error test cases are comprehensive and well-structured.

The tests thoroughly validate various error scenarios with proper error messages. Consider reducing duplication in test setup.

Extract common test setup:

const makeAuthenticatedRequest = (app: INestApplication, data: any) => {
  return request(app.getHttpServer())
    .post('/external/workflows/run')
    .set('authorization', `Bearer ${API_KEY}`)
    .send(data);
};

it('should return 400 when there is no context', async () => {
  const res = await makeAuthenticatedRequest(app, {});
  expect(res.statusCode).toEqual(400);
  expect(res.body.message).toEqual('Context is required');
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3750829 and 65b069c.

📒 Files selected for processing (3)
  • services/workflows-service/src/workflow/workflow.controller.external.intg.test.ts (1 hunks)
  • services/workflows-service/src/workflow/workflow.controller.external.ts (2 hunks)
  • services/workflows-service/src/workflow/workflow.service.ts (1 hunks)
🔇 Additional comments (1)
services/workflows-service/src/workflow/workflow.service.ts (1)

1926-1926: LGTM! Document validation is more robust.

The changes improve the handling of document validation by properly handling null cases and improving type safety.

Let's verify the document validation logic:

✅ Verification successful

Document validation changes are properly implemented and consistent

The codebase search reveals that:

  • The document validation logic is consistently handling null/undefined cases using optional chaining across multiple locations
  • The implementation properly strips out the propertiesSchema property during validation
  • Similar null-safe patterns are used throughout the service for document handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify document validation implementation

# Check for potential edge cases in document validation
ast-grep --pattern 'documents: (context?.documents || []).map' | \
while read -r line; do
  echo "Found document validation pattern. Checking for test coverage..."
  rg -q "context: { documents: \[\] }" services/workflows-service/src/workflow/workflow.controller.external.intg.test.ts && \
  echo "Empty documents array test case found" || \
  echo "Warning: Missing test case for empty documents array"
done

Length of output: 79


Script:

#!/bin/bash
# Let's verify the document validation implementation with a broader search

# Check the implementation context
rg -A 5 -B 5 "documents: \(context\?\.documents \|\| \[\]\)\.map" services/workflows-service/src/workflow/workflow.service.ts

# Check test coverage for document validation
rg -A 5 "documents:" services/workflows-service/src/workflow/workflow.controller.external.intg.test.ts

# Look for other document validation patterns
rg "context\?\.documents" services/workflows-service/src/workflow/workflow.service.ts

Length of output: 1212

- Update the assertion to match an object structure
- Include additional expected properties in the response check

(That test is so thorough, it could pass a background check for a secret agent)
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: 2

🧹 Outside diff range and nitpick comments (6)
services/workflows-service/src/workflow/workflow.controller.external.intg.test.ts (6)

178-178: Typo in test description

The word "recieving" is misspelled. The correct spelling is "receiving".

Please correct the typo in the test description:

-it('should return 401 when not recieving authorization token', async () => {
+it('should return 401 when not receiving authorization token', async () => {

253-253: Typo in variable name 'NON_EXISTANT_WORKFLOW_ID'

The word "NON_EXISTANT" is misspelled. The correct spelling is "NON_EXISTENT".

Please correct the variable name:

-const workflowId = 'NON_EXISTANT_WORKFLOW_ID';
+const workflowId = 'NON_EXISTENT_WORKFLOW_ID';

191-191: Avoid hard-coded credentials in test code

The string "Bearer INVALID_API_KEY" is hard-coded as an authorization header. While this is a test, it's good practice to define such values as constants or use a more generic placeholder.

Consider defining a constant for invalid API keys or using a clearly invalid placeholder to improve readability.

-  .set('authorization', 'Bearer INVALID_API_KEY')
+  .set('authorization', 'Bearer INVALID_API_KEY_PLACEHOLDER')

193-193: Inconsistent property name in payload

The property workflowDefinitionId is used here, whereas other tests use workflowId. For consistency and to avoid potential bugs, it's advisable to use the same property name across all tests.

Update the property name to match the other test cases:

-  workflowDefinitionId: 'test-id',
+  workflowId: 'test-id',

195-195: Inconsistent structure for 'context' property

The context object uses entityId directly, while other tests nest it inside an entity object. This inconsistency might lead to confusion or errors.

Align the structure with other test cases for consistency:

-  context: { entityId: 'test-entity' },
+  context: { entity: { id: 'test-entity' } },

112-112: Avoid using '@ts-ignore' directive

The // @ts-ignore directive suppresses TypeScript errors but can hide potential issues.

Consider properly typing the req.user property instead of ignoring TypeScript checks. You can extend the Request interface to include a user property:

interface AuthenticatedRequest extends Request {
  user: {
    user: User;
    type: string;
    projectIds: string[];
  };
}

// Then use AuthenticatedRequest in the middleware
const userAuthOverrideMiddleware = (req: AuthenticatedRequest, res: any, next: any) => {
  req.user = {
    user: assignee,
    type: 'user',
    projectIds: [project.id],
  };
  next();
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 65b069c and 640ba0b.

📒 Files selected for processing (1)
  • services/workflows-service/src/workflow/workflow.controller.external.intg.test.ts (1 hunks)

- Update test and exception messages to fix the spelling of "Definition"
- Ensure consistency in error handling output across the service

(your typos are so recurrent, they're basically the project's middle name)
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: 1

🧹 Outside diff range and nitpick comments (2)
services/workflows-service/src/workflow/workflow.controller.external.intg.test.ts (2)

140-174: Consider extracting test data setup into helper functions

The test data setup logic could be extracted into helper functions to improve readability and reusability.

// Example helper function:
async function createTestWorkflowDefinition(
  repository: WorkflowDefinitionRepository,
  projectId: string,
  workflowId: string,
) {
  return repository.create({
    data: {
      id: workflowId,
      name: 'workflow-name',
      definitionType: 'statechart-json',
      definition: {},
      project: {
        connect: {
          id: projectId,
        },
      },
    },
  });
}

178-178: Fix typo in test description

"recieving" should be "receiving"

-    it('should return 401 when not recieving authorization token', async () => {
+    it('should return 401 when not receiving authorization token', async () => {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 640ba0b and b99c150.

📒 Files selected for processing (2)
  • services/workflows-service/src/workflow/workflow.controller.external.intg.test.ts (1 hunks)
  • services/workflows-service/src/workflow/workflow.controller.external.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • services/workflows-service/src/workflow/workflow.controller.external.ts
🔇 Additional comments (3)
services/workflows-service/src/workflow/workflow.controller.external.intg.test.ts (3)

290-317: Enhance successful workflow creation test validation

While the test validates the basic response structure, consider adding more comprehensive validation of the created workflow.


55-55: ⚠️ Potential issue

Uninitialized 'assignee' variable may cause issues

The variable assignee is declared but never initialized before being used in the middleware.

Also applies to: 112-112


191-191: ⚠️ Potential issue

Hard-coded API key in test

Using hard-coded values for sensitive data like API keys is not recommended.

@tomer-shvadron tomer-shvadron merged commit 4def82c into dev Dec 15, 2024
10 checks passed
@tomer-shvadron tomer-shvadron deleted the bal-3144 branch December 15, 2024 12:07
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