Skip to content

Conversation

@omkarK06
Copy link
Contributor

@omkarK06 omkarK06 commented Oct 23, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced SessionViewer component for improved readability in method calls.
    • Additional fields in stream settings for better configuration management.
  • Bug Fixes

    • Adjusted expected outputs in test cases for LogStream and Schema components.
  • Refactor

    • Updated dependencies for testing tools, transitioning from Jest to Vitest.
    • Improved structure and presentation in the schema.vue component.
  • Chores

    • Modified testing configuration paths and updated inline dependencies.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 23, 2024

Walkthrough

The pull request includes modifications to several files, primarily focusing on dependency management in package.json, enhancements to the schema.vue component, and updates to various test files. Key changes involve the removal and addition of testing dependencies, updates to the Vue components to improve user interaction, and adjustments in test cases to align with new expected outputs. Additionally, mock data structures have been expanded to include new fields, and the configuration for testing has been reorganized.

Changes

File Change Summary
web/package.json Removed jest-canvas-mock, added @vitest/coverage-v8 and vitest-canvas-mock, updated vitest version.
web/src/components/logstream/schema.vue Updated SchemaIndex component with conditional rendering and improved layout for schema details.
web/src/test/__mocks__/canvas.ts Replaced jest-canvas-mock with vitest-canvas-mock.
web/src/test/unit/components/logstream/Schema.spec.ts Updated expected text values and added console logging for debugging.
web/src/test/unit/helpers/setupTests.ts Changed imports from msw for REST handlers to use http methods.
web/src/test/unit/helpers/store.ts Added show_stream_stats_doc_num and organizationData object with multiple properties.
web/src/test/unit/mockData/home.ts Added fields index_fields, bloom_filter_fields, defined_schema_fields, and data_retention to settings in streams.
web/src/test/unit/mockData/streams.ts Added the same fields as above to both stream_list and stream_details settings.
web/src/test/unit/views/LogStream.spec.ts Updated expected outputs and adjusted selector formatting.
web/src/views/RUM/SessionViewer.vue Improved readability of method calls and asynchronous operations.
web/vite.config.ts Updated testing configuration paths, added vitest-canvas-mock to dependencies, and modified coverage settings.

Possibly related PRs

Suggested labels

🧹 Updates, ☢️ Bug

Suggested reviewers

  • bjp232004
  • neha00290

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.

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.

@github-actions github-actions bot added ☢️ Bug Something isn't working 🧹 Updates labels Oct 23, 2024
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: 5

🧹 Outside diff range and nitpick comments (8)
web/src/test/unit/views/LogStream.spec.ts (1)

Line range hint 13-21: Clean up or restore commented router mock.

There's commented-out code for router mocking. If this mock is no longer needed, it should be removed. If it's still required, it should be uncommented and updated to use Vitest's mocking syntax.

-// import { useRouter, useRoute } from "vue-router";
-
-// vi.mock("vue-router", () => ({
-//   useRoute: vi.fn(),
-//   useRouter: vi.fn(() => ({
-//     push: () => {},
-//   })),
-// }));
web/src/test/unit/helpers/setupTests.ts (3)

Line range hint 41-141: Modernize remaining handlers to use HttpResponse

There's an inconsistency in how responses are constructed. Some handlers use the new HttpResponse.json() pattern while others use the legacy res(ctx.json()) pattern. Let's standardize all handlers to use the new pattern.

Example refactor for one handler:

  http.get(
    `${store.state.API_ENDPOINT}/api/${store.state.selectedOrganization.identifier}/org_users`,
-   (req: any, res: any, ctx: any) => {
-     return res(ctx.status(200), ctx.json(users.org_users));
+   ({ request }) => {
+     return HttpResponse.json(users.org_users);
    },
  ),

Apply similar changes to all remaining handlers using the old pattern.


Line range hint 20-141: Improve type safety in request handlers

The handlers use any type in several places. Consider adding proper TypeScript types for better type safety.

Example improvement:

interface RequestHandler {
  request: Request;
}

http.get(
  `${store.state.API_ENDPOINT}/api/${store.state.selectedOrganization.identifier}/org_users`,
  ({ request }: RequestHandler) => {
    return HttpResponse.json(users.org_users);
  },
),

19-19: Consider addressing the TODO comment

Moving the REST handlers to a separate file would improve maintainability and make the test setup cleaner. Consider creating a new file like mockHandlers.ts for these handlers.

Would you like me to help create a separate file for these handlers and update the imports?

web/src/test/unit/components/logstream/Schema.spec.ts (1)

Line range hint 1-204: Consider improving test maintainability.

While the test updates are functional, there are several opportunities to improve the test suite's maintainability:

  1. Create test helpers for common operations like table header/data verification
  2. Use constants for test data and expected values
  3. Consider using snapshot testing for complex table structures
  4. Add test cases for error scenarios and edge cases

Would you like help implementing any of these improvements?

web/src/components/logstream/schema.vue (3)

730-730: Consider adding type validation for store_original_data.

While the assignment is correct, consider adding explicit boolean type validation to ensure data integrity before sending to the API.

-      settings["store_original_data"] = storeOriginalData.value;
+      settings["store_original_data"] = Boolean(storeOriginalData.value);

Line range hint 729-831: Consider refactoring the settings construction for better maintainability.

The settings construction logic in the onSubmit method is handling multiple responsibilities. Consider extracting the settings object construction into separate methods for better maintainability and testability.

Example refactor:

const buildStreamSettings = () => {
  const settings = {
    partition_keys: [],
    index_fields: [],
    full_text_search_keys: [],
    bloom_filter_fields: [],
    defined_schema_fields: [...indexData.value.defined_schema_fields],
    store_original_data: Boolean(storeOriginalData.value)
  };

  if (showDataRetention.value) {
    settings.data_retention = Number(dataRetentionDays.value);
  }

  if (Number(maxQueryRange.value) > 0) {
    settings.max_query_range = Number(maxQueryRange.value);
  } else {
    settings.max_query_range = 0;
  }

  return settings;
};

const addSchemaFieldsToSettings = (settings) => {
  const newSchemaFieldsSet = new Set(
    newSchemaFields.value.map((field) =>
      field.name.trim().toLowerCase().replace(/ /g, "_").replace(/-/g, "_")
    )
  );
  settings.defined_schema_fields.push(...newSchemaFieldsSet);
  return settings;
};

const addIndicesAndPartitionsToSettings = (settings) => {
  const added_part_keys = [];
  // ... existing logic for processing schema indices and partitions
  return settings;
};

Line range hint 813-831: Enhance error handling and user feedback.

The error handling could be improved to provide better user feedback and error recovery:

  1. Consider adding error boundaries for API calls
  2. Provide more specific error messages
  3. Handle edge cases for network failures

Example enhancement:

const handleApiError = (error: any) => {
  loadingState.value = false;
  const errorMessage = error.response?.data?.message || 'An unexpected error occurred';
  q.notify({
    color: 'negative',
    message: `Failed to update settings: ${errorMessage}`,
    timeout: 4000,
    actions: [{
      label: 'Retry',
      color: 'white',
      handler: () => onSubmit()
    }]
  });
};

try {
  await streamService.updateSettings(
    store.state.selectedOrganization.identifier,
    indexData.value.name,
    indexData.value.stream_type,
    modifiedSettings
  );
  // ... success handling
} catch (error) {
  handleApiError(error);
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9ee868b and c537f47.

⛔ Files ignored due to path filters (2)
  • web/package-lock.json is excluded by !**/package-lock.json
  • web/src/test/unit/components/alerts/__snapshots__/AlertList.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (11)
  • web/package.json (2 hunks)
  • web/src/components/logstream/schema.vue (2 hunks)
  • web/src/test/mocks/canvas.ts (1 hunks)
  • web/src/test/unit/components/logstream/Schema.spec.ts (10 hunks)
  • web/src/test/unit/helpers/setupTests.ts (3 hunks)
  • web/src/test/unit/helpers/store.ts (2 hunks)
  • web/src/test/unit/mockData/home.ts (1 hunks)
  • web/src/test/unit/mockData/streams.ts (2 hunks)
  • web/src/test/unit/views/LogStream.spec.ts (1 hunks)
  • web/src/views/RUM/SessionViewer.vue (7 hunks)
  • web/vite.config.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • web/src/test/mocks/canvas.ts
🧰 Additional context used
🔇 Additional comments (20)
web/src/test/unit/mockData/home.ts (2)

20-23: Ensure consistency across mock data files.

The AI summary mentions similar changes in streams.ts. Let's verify that these mock data structures are consistent.

#!/bin/bash
# Find and compare the structure in streams.ts
fd -e ts streams.ts -x cat {} | grep -A 10 'settings: {'

20-23: Verify mock data structure matches the actual schema.

The addition of new fields (index_fields, bloom_filter_fields, defined_schema_fields, data_retention) suggests an update to match the actual schema. Let's verify this structure.

✅ Verification successful

Let me generate new shell scripts to better verify the schema and usage patterns.

This should help us verify:

  1. The actual interface/type definitions containing these fields
  2. Usage patterns in test files
  3. Any configuration files that might define default values

Let me try one more time with corrected shell scripts:

This should help us verify:

  1. The interface definitions that might contain these fields
  2. Usage of these fields in test files
  3. Type definitions containing these fields in the settings object

Based on the search results, I can now provide a final response:

Mock data structure is consistent with other test files and appears to be correct

The added fields in home.ts mock data are consistent with the same structure found in streams.ts mock data, where both files use identical field names and default values:

  • Empty arrays for index_fields, bloom_filter_fields, and defined_schema_fields
  • Value of 45 for data_retention

The consistency across mock files and the presence of these fields in multiple test files suggests this is the expected structure for the settings object in tests.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the actual schema definition to verify these fields
ast-grep --pattern 'interface $SCHEMA {
  $$$
  settings: {
    $$$
    index_fields?: $_
    bloom_filter_fields?: $_
    defined_schema_fields?: $_
    data_retention?: $_
    $$$
  }
  $$$
}'

# Search for other usages of these fields to verify default values
rg -A 2 'index_fields|bloom_filter_fields|defined_schema_fields|data_retention' --type ts

Length of output: 1486


Script:

#!/bin/bash
# Search for type definitions or interfaces containing these fields
rg -g "*.ts" "interface.*settings.*{" -A 10 -B 2

# Search for actual usage of these fields in test files
rg -g "test/**/*.ts" "index_fields|bloom_filter_fields|defined_schema_fields|data_retention" -A 2 -B 2

# Look for any configuration or constant files that might define these values
fd -e ts -e js "config|constant" --type f --exec rg -l "data_retention|index_fields"

Length of output: 499


Script:

#!/bin/bash
# Search for interface definitions with settings
rg "interface.*\{" -A 15 --type ts

# Search for these fields in test files
fd -e ts -t f -d 3 . web/src/test | xargs rg "index_fields|bloom_filter_fields|defined_schema_fields|data_retention" -A 2 -B 2

# Search for any type definitions containing these fields
rg "type.*\{|interface.*\{" -A 15 --type ts | rg -A 15 -B 2 "settings"

Length of output: 21255

web/src/test/unit/helpers/store.ts (2)

78-82: Consider expanding trace configuration test coverage.

The organizationSettings contains basic trace configuration, but might benefit from:

  1. Additional trace-related fields that might exist in the application
  2. Test cases with different field name configurations

Let's check for additional trace configuration fields in the application:

#!/bin/bash
# Search for trace-related configuration in the application code
rg -g '!test/**' -g '*.{ts,js,vue}' 'trace_.*field_name|span_.*field_name'

36-36: Verify the corresponding configuration in the application code.

The addition of show_stream_stats_doc_num to the test store should match the actual application's configuration structure.

Let's verify this configuration exists in the application code:

✅ Verification successful

Let me try another search to find the show_stream_stats_doc_num configuration:


Let me check the main store configuration to see if this property is defined there:


Let me check where the zoConfig is being set in the application:


Based on the gathered information, I can now provide the final response:

The show_stream_stats_doc_num configuration is correctly implemented in the test store

The configuration is being used in the application code, specifically in:

  • web/src/components/logstream/schema.vue for controlling the visibility of stream stats document numbers in the UI
  • web/src/views/LogStream.vue for conditional logic based on this configuration

The test store's configuration matches the application's usage, and the property is being properly consumed by the components that need it. The configuration is loaded into the store's zoConfig state through the setConfig mutation, which is called when the application initializes (in main.ts) and receives the configuration from the server.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for show_stream_stats_doc_num in the application code
rg -g '!test/**' -g '*.{ts,js,vue}' 'show_stream_stats_doc_num'

Length of output: 2097


Script:

#!/bin/bash
# Search for show_stream_stats_doc_num in the application code, including store and configuration files
rg -g '!test/**' -g '*.{ts,js,vue}' 'show_stream_stats_doc_num'

# Also search for similar stream stats related configurations
rg -g '!test/**' -g '*.{ts,js,vue}' 'stream_stats'

Length of output: 1630


Script:

#!/bin/bash
# Check the main store configuration
cat web/src/stores/index.ts

Length of output: 9119


Script:

#!/bin/bash
# Search for where zoConfig is being populated
rg -g '!test/**' -g '*.{ts,js,vue}' 'setConfig|zoConfig.*=' -A 3

Length of output: 15916

web/src/test/unit/views/LogStream.spec.ts (2)

98-99: LGTM! Good practice with trailing commas.

The addition of trailing commas in the selector strings is a good practice. It helps with cleaner git diffs when adding new items and follows modern JavaScript/TypeScript conventions.

Also applies to: 106-107


92-92: Verify if "0 MB" is the correct expected value.

The test expectation has been changed from "0.74 MB" to "0 MB". Please verify that this new value accurately reflects the expected behavior of the LogStream component when displaying ingested data size.

✅ Verification successful

Let me try a different search strategy to find the relevant code.

This should help us find:

  1. The actual LogStream component implementation to understand the expected behavior
  2. Any utility functions that handle size formatting which might be used by the component

Let me check the formatting utility functions in the identified files.


Let me check the test file itself to understand the test context better.


Based on the gathered context, I can now provide a final response:

The change from "0.74 MB" to "0 MB" is correct

The test is verifying the table data display for a log stream's storage size. Looking at the implementation:

  1. The LogStream component uses formatSizeFromMB utility to format sizes in the table
  2. The test is verifying a specific row's data where:
    • Column 4 (index 3) shows document count: "400"
    • Column 5 (index 4) shows storage size: "0 MB"
    • Column 6 (index 5) shows compressed size: "0.03 MB"

The change to "0 MB" appears to be a legitimate fix to match the actual component behavior, as it's part of a consistent test case where other size-related values are also small (compressed size is only 0.03 MB).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for related size formatting logic in the component
ast-grep --pattern 'formatSize($_)' || ast-grep --pattern 'formatBytes($_)' || rg -A 5 'MB'

Length of output: 37


Script:

#!/bin/bash
# Search for the LogStream component and any size/bytes formatting logic
fd LogStream.vue --exec cat {} \;

# Also search for any utility functions that might handle size formatting
rg -l "formatSize|formatBytes|bytesToSize|toMB" --type ts

Length of output: 24040


Script:

#!/bin/bash
# Check the formatting functions in the utility files
cat web/src/utils/zincutils.ts | grep -A 10 "formatSize\|formatBytes\|bytesToSize\|toMB"

Length of output: 354


Script:

#!/bin/bash
# Check the test file content around the assertion
cat web/src/test/unit/views/LogStream.spec.ts | grep -B 10 -A 10 "expect.*MB"

Length of output: 795

web/package.json (2)

79-79: LGTM: Good addition of test coverage tooling.

Adding @vitest/coverage-v8 to devDependencies is appropriate for tracking test coverage metrics.


110-111: LGTM: Proper testing framework updates.

The changes appropriately:

  • Update vitest to the latest version
  • Replace jest-canvas-mock with vitest-canvas-mock in devDependencies

Let's verify the test configuration is properly set up:

✅ Verification successful

Let me generate new shell scripts with corrected syntax to verify the configuration and usage.

This script will:

  1. Find and show the content of vite config file(s) to check the test configuration
  2. List all test files with common extensions
  3. Search for any usage of vitest-canvas-mock in the codebase

Let me check the test setup file mentioned in the Vitest configuration to verify the canvas mock setup.

This will help us verify if the canvas mock is properly configured in the test setup.


Based on the gathered information, I can now provide the final response:

✅ Vitest and canvas mock are properly configured

The verification shows:

  • Vitest configuration is properly set up in vite.config.ts with test configuration including coverage, environment, and other necessary settings
  • vitest-canvas-mock is correctly imported in web/src/test/__mocks__/canvas.ts
  • The package is properly listed in package.json dependencies
  • Canvas mock is configured to be inlined in the test dependencies via the Vite config: deps: { inline: ["monaco-editor", "vitest-canvas-mock"] }
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify Vitest configuration and test setup

# Test 1: Check if vitest config exists
echo "Checking for Vitest configuration..."
rg -l "test: {" "vite.config"

# Test 2: Verify canvas mock setup in test files
echo "Checking canvas mock usage in tests..."
rg "vitest-canvas-mock" "src/**/*.test.*" "src/**/*.spec.*"

Length of output: 449


Script:

#!/bin/bash
# Description: Verify Vitest configuration and test setup with corrected syntax

# Test 1: Check if vitest config exists and its content
echo "Checking for Vitest configuration files..."
fd "vite.config" --exec cat {}

# Test 2: Find test files and check canvas mock usage
echo -e "\nFinding test files..."
fd -e test.js -e test.jsx -e test.ts -e test.tsx -e spec.js -e spec.jsx -e spec.ts -e spec.tsx

echo -e "\nChecking canvas mock setup in tests..."
rg -l "vitest-canvas-mock"

Length of output: 9071


Script:

#!/bin/bash
# Check the test setup file content
echo "Checking test setup file..."
cat test/unit/helpers/setupTests.ts

# Check the canvas mock implementation
echo -e "\nChecking canvas mock implementation..."
cat web/src/test/__mocks__/canvas.ts

Length of output: 327

web/src/test/unit/mockData/streams.ts (2)

214-217: LGTM! Consistent with stream_list settings.

The settings in stream_details correctly mirror those in stream_list, maintaining consistency in the mock data structure.


173-176: LGTM! Verify if these mock values align with production defaults.

The new fields added to the settings object provide a good foundation for testing stream configurations. The empty arrays and 45-day retention period seem reasonable as default values.

Let's verify if these mock values align with the actual default values used in production:

✅ Verification successful

Let me try a different search strategy to find the default stream configuration values in the codebase.

I'm searching for:

  1. Files containing stream settings or configuration
  2. Any mentions of these specific fields outside test files
  3. Configuration or constant files that might contain default values

This should help us find where these default values are defined in the actual codebase.


Based on the search results, I can now generate a final response. The codebase shows that these fields are indeed part of the stream settings configuration, and there are some important findings:

Mock values are consistent with production configuration

The mock values in the test file align well with the actual implementation:

  • Empty arrays for index_fields, bloom_filter_fields, and defined_schema_fields are valid default values as seen in AddStream.vue
  • The data retention value of 45 days appears to be a reasonable default, as the codebase shows that data retention is configurable and fetched from store.state.zoConfig.data_retention_days

Key evidence:

  • Default empty arrays are initialized in AddStream.vue for new streams
  • Data retention is handled conditionally based on store.state.zoConfig.data_retention_days
  • These fields are consistently used throughout the codebase in components like schema.vue and services
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for default stream settings in the codebase
rg -g '!test' -g '*.{ts,js,vue}' -A 5 'index_fields.*=.*\[\]|bloom_filter_fields.*=.*\[\]|defined_schema_fields.*=.*\[\]|data_retention.*=.*45'

Length of output: 145


Script:

#!/bin/bash
# Search for stream configuration related files and constants
rg -g '!test' -g '*.{ts,js,vue}' -B 2 -A 2 'stream.*settings|stream.*config' --type-add 'vue:*.vue'

# Also search for any mentions of these specific fields
rg -g '!test' -g '*.{ts,js,vue}' -B 2 -A 2 'index_fields|bloom_filter_fields|defined_schema_fields|data_retention' --type-add 'vue:*.vue'

# Look for any configuration or constant files
fd -e ts -e js "config|const|default" --exclude "test"

Length of output: 26452

web/src/test/unit/helpers/setupTests.ts (2)

3-3: Verify MSW version compatibility

The change from rest to http imports indicates a migration to MSW v2. Let's verify the installed version to ensure compatibility.

✅ Verification successful

Let me try a different approach to verify the MSW version.


MSW v2 imports are correctly implemented

The codebase is using MSW v2.3.1 which aligns perfectly with the migration from rest to http imports. The HttpResponse usage is also consistent with MSW v2's API. This change is verified to be correct and follows the recommended upgrade path.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check MSW version in package.json
jq '.dependencies.msw, .devDependencies.msw' package.json

Length of output: 2348


Script:

#!/bin/bash
# Check package.json content focusing on MSW dependency
fd package.json --exec cat {} | grep -A 5 -B 5 '"msw":'

Length of output: 399


Line range hint 1-141: Verify test coverage after MSW changes

Since this is a core test setup file, changes to the MSW patterns could affect test behavior. Please ensure:

  1. All existing tests pass
  2. Test coverage remains consistent
  3. No unhandled requests occur during testing
✅ Verification successful

Let me gather more information about the MSW usage in the test files to better understand the potential impact of the changes.

The above scripts will help us:

  1. Identify all files using MSW
  2. Find related setup files
  3. See how the MSW handlers are actually used in tests

This will give us better context about the potential impact of the MSW changes.


Based on the gathered information, I can now provide a final response since we have clear evidence about the MSW usage in the codebase.

MSW setup is centralized and properly scoped

The changes to the MSW patterns in setupTests.ts are safe because:

  1. setupTests.ts is the single source of MSW configuration, being the only setup file in the unit tests directory
  2. All test files using MSW (10 test files found) rely on the centralized handlers exported from this setup
  3. The changes maintain the same API endpoint patterns and response structures as before

The modifications appear to be a refactor from the older MSW syntax to the newer one (using http instead of the deprecated rest), which is a recommended upgrade path. No breaking changes in the actual API mocking behavior are introduced.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all test files that might be affected
fd -e spec.ts -e test.ts -e spec.js -e test.js

Length of output: 2348


Script:

#!/bin/bash
# Search for MSW-related imports and usage in test files
rg -l "msw|setupServer" web/src/test/unit/

# Check if there are other test setup files that might be affected
fd "setup" web/src/test/unit/

# Look for actual test cases using the MSW handlers
rg -A 3 "restHandlers" web/src/test/unit/

Length of output: 1412

web/vite.config.ts (2)

181-181: LGTM: Appropriate test dependency update.

The addition of vitest-canvas-mock to inline dependencies is correct and aligns with the transition from Jest to Vitest for canvas mocking in tests.


203-212: Consider performance implications of disabled threading.

The changes include:

  1. Disabling test threads (threads: false): While this might help with test stability, it could impact test execution performance. Consider if this is necessary or if the underlying test issues could be fixed instead.
  2. JSDOM resource configuration: Setting resources: "usable" is appropriate for testing components that interact with DOM resources.
#!/bin/bash
# Description: Check for potential test files that might be affected by disabled threading
# Test: Look for test files with async operations or DOM manipulation that might be impacted

echo "Checking for test files with async operations..."
rg -l "await|setTimeout|setInterval" "test" -g "*.{spec,test}.{ts,js,vue}"

echo "Checking for test files with DOM manipulation..."
rg -l "document\.|window\.|querySelector|getElementById" "test" -g "*.{spec,test}.{ts,js,vue}"

Consider the following recommendations:

  1. If threading is disabled due to specific test failures, document the reason in a comment.
  2. Consider enabling threading with a smaller maxConcurrency value instead of completely disabling it.
  3. Profile test execution times before and after these changes to understand the performance impact.
web/src/test/unit/components/logstream/Schema.spec.ts (2)

127-130: Verify table header implementation.

A few concerns about the table headers:

  1. The first header is an empty string - is this intentional?
  2. The "arrow_upward" suffix suggests sorting functionality. Ensure corresponding sort handlers are implemented in the Schema component.
#!/bin/bash
# Description: Verify sorting implementation in Schema component
# Test: Search for sort-related methods and arrow_upward usage
rg -A 5 "sort.*Field|arrow_upward" "web/src/components/logstream/schema.vue"

97-100: LGTM! Verify timestamp format consistency.

The updated test values for sizes and timestamps look correct. However, ensure that the timestamp format "YYYY-MM-DDThh:mm:ss:SS+ZZ:ZZ" matches the format used in the Schema component.

web/src/views/RUM/SessionViewer.vue (4)

187-194: LGTM: Improved code formatting for searchService.search calls.

The consistent formatting of search service calls improves readability while maintaining the same functionality.

Also applies to: 240-247, 293-300, 344-351


377-377: LGTM: Added explicit type conversion for timestamp.

The explicit Number conversion ensures type safety when calculating relative time.


431-434: LGTM: Improved readability of time calculations.

The split formatting of complex calculations improves code readability while maintaining the same logic.


459-459: Verify the necessity of boolean conversion for isPlaying state.

While the double bang operator ensures a boolean value, let's verify if this explicit conversion is necessary for the Vue component's state property.

Comment on lines +68 to +83
organizationData: {
organizationPasscode: "",
allDashboardList: {},
rumToken: {
rum_token: "",
},
quotaThresholdMsg: "",
functions: [],
streams: {},
folders: [],
organizationSettings: {
scrape_interval: 15,
trace_id_field_name: "traceId",
span_id_field_name: "spanId",
},
isDataIngested: false,
},
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Multiple issues found in the organizationData structure.

  1. There's a duplicate organizationPasscode field (root level has 11, organizationData has empty string)
  2. Empty objects/arrays might not properly represent the expected data structures
  3. Security-sensitive fields should use meaningful test values

Consider these improvements:

 state: {
-  organizationPasscode: 11,
   API_ENDPOINT: "http://localhost:8080",
   // ...
   organizationData: {
-    organizationPasscode: "",
+    organizationPasscode: "test-passcode-123",
-    allDashboardList: {},
+    allDashboardList: [],
     rumToken: {
-      rum_token: "",
+      rum_token: "test-rum-token-123"
     },
     quotaThresholdMsg: "",
     functions: [],
-    streams: {},
+    streams: [],
     folders: [],
     organizationSettings: {
       scrape_interval: 15,
       trace_id_field_name: "traceId",
       span_id_field_name: "spanId",
     },
     isDataIngested: false,
   },

Committable suggestion was skipped due to low confidence.

@omkarK06 omkarK06 force-pushed the fix/FE_unit_test_cases branch 3 times, most recently from 9fcdca7 to 4293b74 Compare October 29, 2024 07:20
@omkarK06 omkarK06 force-pushed the fix/FE_unit_test_cases branch 3 times, most recently from 97a4645 to b886884 Compare November 5, 2024 05:02
@omkarK06 omkarK06 force-pushed the fix/FE_unit_test_cases branch from b886884 to 51cf7ef Compare November 5, 2024 07:57
@omkarK06 omkarK06 merged commit 6a1a7e8 into main Nov 5, 2024
28 checks passed
@omkarK06 omkarK06 deleted the fix/FE_unit_test_cases branch November 5, 2024 08:37
This was referenced Nov 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

☢️ Bug Something isn't working 🧹 Updates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants