Skip to content

refactor: shopify source tracker - #4230

Merged
koladilip merged 1 commit into
developfrom
refactor/shopify-source-tracker
Apr 8, 2025
Merged

koladilip merged 1 commit into
developfrom
refactor/shopify-source-tracker

Conversation

@koladilip

@koladilip koladilip commented Apr 3, 2025 •

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

Refactor Shopify Tracker Logic and Improve Test Coverage

Changes

  • Refactored Shopify tracker transform logic: Improved the structure and organization of the transformation code to make it more maintainable
  • Added comprehensive test coverage: Created new test files and expanded existing ones to ensure proper test coverage
  • Consolidated test files: Removed redundant test files and consolidated testing logic
  • Implemented table tests: Used table-driven tests for better test organization and maintainability

Files Changed

  • src/sources/shopify/tracker/shopify.util.test.js: Enhanced existing utility tests
  • src/sources/shopify/tracker/transform.js: Refactored transformation logic
  • src/sources/shopify/tracker/transform.test.js: Added new tests for the transform functionality
  • src/sources/shopify/utils.test.js: Expanded utility tests
  • Removed src/sources/shopify/webpixelTransformations/pixelTransform.redisCartToken.test.js: Consolidated with other tests
  • Added src/sources/shopify/webpixelTransformations/pixelTransform.test.js: New comprehensive tests for pixel transformations

Resolves INT-3427

Please explain the objectives of your changes below

Put down any required details on the broader aspect of your changes. If there are any dependent changes, mandatorily mention them here

Any changes to existing capabilities/behaviour, mention the reason & what are the changes ?

N/A

Any new dependencies introduced with this change?

N/A

Any new generic utility introduced or modified. Please explain the changes.

N/A

Any technical or performance related pointers to consider with the change?

N/A

@coderabbitai review


Developer checklist

  • My code follows the style guidelines of this project

  • No breaking changes are being introduced.

  • All related docs linked with the PR?

  • All changes manually tested?

  • Any documentation changes needed with this change?

  • Is the PR limited to 10 file changes?

  • Is the PR limited to one linear task?

  • Are relevant unit and component test-cases added in new readability format?

Reviewer checklist

  • Is the type of change in the PR title appropriate as per the changes?

  • Verified that there are no credentials or confidential data exposed with the changes.

@koladilip
koladilip requested a review from sivashanmukh as a code owner April 3, 2025 05:52
@koladilip
koladilip requested a review from a team April 3, 2025 05:52
@coderabbitai

coderabbitai Bot commented Apr 3, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features
    • Enhanced the transformation and enrichment of e-commerce events for more accurate cart and user tracking.
  • Refactor
    • Streamlined processing flows and caching integration, ensuring more consistent handling of Shopify events.
  • Tests
    • Expanded coverage across event and data handling scenarios to ensure robust performance and improved error management.

These improvements help deliver a more reliable and consistent experience when processing shopping cart updates and user interactions.

Walkthrough

The changes refactor various Shopify tracker and utility modules, primarily streamlining Redis integration and event processing. The modifications remove reliance on the useRedisDatabase configuration variable, update control flows in functions handling cart updates and identifier events, and adjust error handling. Several test suites have been added or removed to reflect these code changes, ensuring that payload builders, event processors, and Redis operations are adequately verified. New tests for pixel transformation and utility functions have been introduced while obsolete tests for certain functionalities have been removed.

Changes

File(s) Summary of Changes
src/sources/shopify/tracker/shopify.util.test.js Removed test suite for getShopifyTopic covering various error and success scenarios.
src/sources/shopify/tracker/transform.js Updated config import; removed useRedisDatabase; refactored handleCartsUpdate, processEvent, and processIdentifierEvent; added methods: createMessageForEvent, handleCartsUpdate, enrichMessage, enrichNonIdentifyMessage.
src/sources/shopify/tracker/transform.test.js Introduced new comprehensive tests for payload builders and processing functions, including handling of Redis data.
src/sources/shopify/utils.test.js Removed isIdentifierEvent tests; updated tests for processIdentifierEvent and updateAnonymousIdToUserIdInRedis with modified event structures.
src/sources/shopify/webpixelTransformations/pixelTransform.redisCartToken.test.js Deleted the test file for extractCartToken and handleCartTokenRedisOperations.
src/sources/shopify/webpixelTransformations/pixelTransform.test.js Added new test suite for the pixelTransform module, covering extraction and processing of cart tokens and event enrichment.
src/sources/shopify/tracker/util.test.js Added comprehensive tests for Shopify utility functions (topics, product lists, cart operations, user identification, email extraction, etc.).
src/sources/shopify/tracker/config.js Removed the useRedisDatabase configuration variable and its export.
src/sources/shopify/tracker/util.js Streamlined getAnonymousIdAndSessionId by removing the useRedisDatabase check and simplifying Redis data handling.
src/sources/shopify/tracker/util.redis.test.js Removed mock config and environment variable setup for Redis; corrected typos in test descriptions.
src/util/redis/redisConnector.js Removed conditional checks based on the USE_REDIS_DB environment variable in both initialization and disconnection, ensuring the Redis client always initializes and disconnects unconditionally.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Event Source
    participant PE as processEvent
    participant HC as handleCartsUpdate
    participant EM as enrichMessage

    Client->>PE: Send event (e.g., carts_update)
    PE->>HC: Call handleCartsUpdate(event)
    HC-->>PE: Return redisData
    PE->>EM: Call enrichMessage(event, redisData)
    EM-->>PE: Return enriched message
    PE-->>Client: Return final message
Loading

Suggested reviewers

  • sivashanmukh
  • krishna2020
  • yashasvibajpai
  • ItsSudip

Suggestions for Improvements:

  • Ensure that the removal of test cases does not leave any uncovered edge cases, particularly for error handling related to topic retrieval.
  • Review the refactored control flows for consistency in error logging and handling to maintain clarity across modules.
  • Confirm that the new tests provide comprehensive coverage for the updated Redis integration and event enrichment logic.
  • Consider adding comments in the code where logic transitions occur, such as in the refactored functions in transform.js, to better aid future maintainers.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@koladilip
koladilip force-pushed the refactor/shopify-source-tracker branch from cc4234e to 49a097e Compare April 3, 2025 05:53

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/sources/shopify/tracker/shopify.util.test.js (2)

256-286: Good verification of user identification logic.

The getAnonymousIdAndSessionId tests cover important cases:

  1. Cart token-based identification
  2. Note attributes-based identification

Consider adding a test case for admin-only events to fully cover the logic path where anonymousId and sessionId are returned without modifications.


315-333: Cart token extraction tests could be more comprehensive.

The getCartToken tests cover basic scenarios but miss testing the case where the event is 'carts_update' and properties.id or properties.token is used, as shown in the relevant code snippet.

Consider adding a test case like:

it('should extract id or token for carts_update event', () => {
  const message = {
    event: 'carts/update',
    properties: {
      id: 'cart_id_123'
    }
  };
  expect(getCartToken(message)).toBe('cart_id_123');
});
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c82d934 and 49a097e8b7a7fd630182ff3f0a325aa21f178cb2.

📒 Files selected for processing (6)
  • src/sources/shopify/tracker/shopify.util.test.js (2 hunks)
  • src/sources/shopify/tracker/transform.js (5 hunks)
  • src/sources/shopify/tracker/transform.test.js (1 hunks)
  • src/sources/shopify/utils.test.js (1 hunks)
  • src/sources/shopify/webpixelTransformations/pixelTransform.redisCartToken.test.js (0 hunks)
  • src/sources/shopify/webpixelTransformations/pixelTransform.test.js (1 hunks)
💤 Files with no reviewable changes (1)
  • src/sources/shopify/webpixelTransformations/pixelTransform.redisCartToken.test.js
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.js`: Focus on ESLint errors (max 3) and warnings (max 5).

**/*.js: Focus on ESLint errors (max 3) and warnings (max 5).

  • src/sources/shopify/webpixelTransformations/pixelTransform.test.js
  • src/sources/shopify/utils.test.js
  • src/sources/shopify/tracker/transform.js
  • src/sources/shopify/tracker/shopify.util.test.js
  • src/sources/shopify/tracker/transform.test.js
🧬 Code Definitions (5)
src/sources/shopify/webpixelTransformations/pixelTransform.test.js (3)
src/sources/shopify/utils.test.js (2)
  • require (1-4)
  • require (5-5)
src/sources/shopify/tracker/transform.test.js (4)
  • require (1-11)
  • require (12-12)
  • require (13-13)
  • require (16-16)
src/sources/shopify/tracker/shopify.util.test.js (2)
  • require (1-10)
  • require (11-11)
src/sources/shopify/utils.test.js (1)
src/sources/shopify/utils.js (5)
  • event (37-37)
  • event (55-55)
  • processIdentifierEvent (36-51)
  • updateAnonymousIdToUserIdInRedis (17-27)
  • stats (2-2)
src/sources/shopify/tracker/transform.js (3)
src/sources/shopify/tracker/transform.test.js (5)
  • config (15-15)
  • require (1-11)
  • require (12-12)
  • require (13-13)
  • require (16-16)
src/sources/shopify/tracker/util.js (1)
  • redisData (29-29)
src/sources/shopify/tracker/shopify_redis.util.test.js (1)
  • metricMetadata (32-35)
src/sources/shopify/tracker/shopify.util.test.js (1)
src/sources/shopify/tracker/util.js (10)
  • stats (6-6)
  • getShopifyTopic (57-71)
  • lineItems (98-98)
  • getProductsListFromLineItems (83-95)
  • inputEvent (257-257)
  • checkAndUpdateCartItems (242-267)
  • getHashLineItems (72-77)
  • getAnonymousIdAndSessionId (154-208)
  • extractEmailFromPayload (106-118)
  • getCartToken (120-126)
src/sources/shopify/tracker/transform.test.js (1)
src/sources/shopify/tracker/transform.js (22)
  • require (4-4)
  • require (6-15)
  • require (17-17)
  • require (18-18)
  • require (20-20)
  • Message (19-19)
  • identifyPayloadBuilder (41-50)
  • ecomPayloadBuilder (52-85)
  • trackPayloadBuilder (87-127)
  • shopifyTopic (228-228)
  • createMessageForEvent (129-142)
  • metricMetadata (327-330)
  • redisData (149-149)
  • redisData (245-245)
  • handleCartsUpdate (144-165)
  • message (42-42)
  • message (53-53)
  • message (88-88)
  • message (256-256)
  • enrichMessage (191-224)
  • event (227-227)
  • process (326-336)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Code Coverage
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: ingestion-service-test
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (32)
src/sources/shopify/webpixelTransformations/pixelTransform.test.js (4)

1-8: Well structured imports and mocks

The test file properly imports the functions to be tested and correctly mocks the necessary dependencies with Jest. This setup ensures isolated testing environment.


14-56: Good use of table-driven testing for extractCartToken

The test cases for extractCartToken are well-structured using Jest's table-driven approach. This pattern efficiently tests multiple scenarios while maintaining readability. The test cases cover valid paths, invalid event types, and malformed paths, providing comprehensive coverage.


58-99: Comprehensive testing of processPixelWebEvents

The test cases for processPixelWebEvents handle both valid events and invalid events. The expectations are well-defined with proper assertions.


100-114: Good Redis integration test

This test case properly checks that the userId is attached from Redis when available. The mocking of RedisDB.getVal with the userId is well-implemented.

src/sources/shopify/tracker/transform.test.js (8)

1-17: Well-structured imports and comprehensive mocking

The file correctly imports all necessary functions for testing and sets up appropriate mocks for Redis and other dependencies. This organization ensures isolated and predictable test execution.


18-31: Effective mock configuration

Good approach to mocking Redis and controlling the useRedisDatabase configuration. The use of jest.requireActual to preserve other configuration settings while overriding specific values is a good practice.


32-116: Well-structured payload builder tests

The tests for the payload builders effectively use table-driven testing to cover different scenarios. Each test case clearly defines inputs and expected outputs, making the tests easy to understand and maintain.


118-146: Good coverage for createMessageForEvent

The tests properly verify that the createMessageForEvent function returns the correct message type based on the input event and Shopify topic. The test cases cover the main paths through the function.


148-203: Comprehensive tests for handleCartsUpdate

The tests thoroughly cover the different scenarios for handleCartsUpdate, including when Redis is disabled, handling new cart items, and detecting unchanged items. The mocking and setup are clean and effective.


205-272: Thorough tests for enrichMessage

The tests for enrichMessage properly verify that messages are enriched with the expected properties based on the event type and available Redis data. Both identify and track message types are covered.


274-341: Good coverage for process and processEvent

The tests cover the main scenarios for processing different types of events, including identifier events, valid Shopify events, and unsupported events. The expected outputs are well-defined.


343-368: Appropriate error handling tests

The error handling tests verify that Redis errors are properly caught and transformed into RedisError instances with the correct status code. This ensures that the system fails gracefully when Redis operations fail.

src/sources/shopify/utils.test.js (6)

8-14: Improved Redis mocking

The Redis mocking setup has been improved with more specific mock implementations for setVal and getVal. This allows for more precise control of the mock behavior in individual tests.


20-26: Good test setup with clear mock resets

The beforeEach function properly clears all mocks and resets mock implementations, ensuring test isolation and preventing test interference.


28-51: Well-structured test for processIdentifierEvent

The test for processing a valid identifier event is well-structured with clear expectations. It verifies both the return value and the correct interaction with Redis.


53-74: Good edge case handling for missing cart token

The test properly verifies that processIdentifierEvent handles the case when the cart token is missing but the user ID mapping action is present.


77-92: Clear test for updateAnonymousIdToUserIdInRedis

The test verifies both the Redis interaction and the stats increment, ensuring the function works as expected.


94-100: Good edge case testing for missing parameters

The test properly verifies that the function doesn't call Redis when either the anonymousId or userId is null, preventing unnecessary Redis operations.

src/sources/shopify/tracker/transform.js (5)

21-22: Improved configuration import

The change to import the config module at the beginning of the file and use destructuring to access the configuration constants improves code organization and maintainability. This centralized approach is more consistent with best practices.

Also applies to: 31-32


144-147: Refactored handleCartsUpdate for better Redis handling

The function now returns { redisData: undefined } when Redis is disabled, which is more consistent with the function's return signature across all branches. This change improves the function's clarity and maintainability.


245-253: Improved cart update handling in processEvent

The code now properly extracts redisData from the result of handleCartsUpdate and uses it later in the function. This change improves the flow of data through the function and makes the code more maintainable.


257-257: Enhanced enrichMessage call with redisData

The enrichMessage function is now called with the redisData parameter, ensuring that Redis information is properly utilized in the message enrichment process. This improves the integration of Redis data into the event processing flow.


344-347: Expanded module exports

The module now exports additional functions, making them available for testing and reuse. This improves the module's API and enables better unit testing, as evidenced by the comprehensive test coverage in the new test files.

src/sources/shopify/tracker/shopify.util.test.js (9)

1-13: Well-structured imports with clear organization.

The file properly imports all necessary utility functions from the util module and sets up the required dependencies for Redis and stats. This establishes a clear foundation for the test cases that follow.


15-18: Good use of mocking for external dependencies.

The mocks for ioredis and stats are appropriately implemented, ensuring tests run in isolation without requiring actual Redis connections or stats reporting.


20-22: Proper test isolation with beforeEach.

Using clearAllMocks in the beforeEach hook ensures that each test starts with a clean slate, preventing cross-test contamination of mock data.


80-88: Comprehensive test case for topic extraction.

This test case complements the existing tests by verifying a specific use case with 'checkouts_update' as the topic value, improving the overall test coverage.


90-145: Well-structured product list transformation tests.

The test suite for getProductsListFromLineItems covers various scenarios including happy path, empty arrays, null inputs, and missing fields. The assertions are clear and verify both the structure and content of the transformed data.


147-229: Thorough tests for cart item operations with Redis integration.

The checkAndUpdateCartItems tests effectively verify:

  1. New cart item detection
  2. Duplicate cart item handling
  3. Redis error handling with appropriate stats tracking

I particularly appreciate the detailed setup for simulating Redis operations and error conditions.


231-253: Complete coverage of hash generation for line items.

The getHashLineItems tests properly verify all scenarios:

  1. Hash generation for valid items
  2. Empty cart handling
  3. Invalid input handling (null or empty objects)

This comprehensive testing ensures the hashing mechanism is robust against all possible inputs.


288-313: Effective email extraction test cases.

The extractEmailFromPayload tests verify extraction from different object structures and properly handle cases where no email is found.


335-364: Appropriate e-commerce property creation tests.

The createPropertiesForEcomEvent tests verify property creation for product events and handle missing fields correctly. The assertions confirm both the structure and content of the generated properties.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@codecov

codecov Bot commented Apr 3, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 97.61905% with 1 line in your changes missing coverage. Please review.

Project coverage is 91.15%. Comparing base (322ddbc) to head (6913dfe).
Report is 15 commits behind head on develop.

Files with missing lines Patch % Lines
src/util/redis/redisConnector.js 94.11% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4230      +/-   ##
===========================================
+ Coverage    91.05%   91.15%   +0.10%     
===========================================
  Files          627      630       +3     
  Lines        33049    33050       +1     
  Branches      7818     7819       +1     
===========================================
+ Hits         30092    30126      +34     
+ Misses        2710     2709       -1     
+ Partials       247      215      -32     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

yashasvibajpai
yashasvibajpai previously approved these changes Apr 3, 2025
@koladilip
koladilip force-pushed the refactor/shopify-source-tracker branch from 49a097e to 119871e Compare April 4, 2025 05:38

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/sources/shopify/tracker/shopify.util.test.js (1)

335-364: Good test coverage for createPropertiesForEcomEvent

Tests verify property creation for product events and correct handling of missing fields. However, there's a discrepancy between the implementation and the test.

In the implementation from the relevant code snippets, createPropertiesForEcomEvent only takes one parameter (message), but the tests are calling it with two parameters (payload and 'product'). Consider updating either the tests or the implementation to match.

-const result = createPropertiesForEcomEvent(payload, 'product');
+const result = createPropertiesForEcomEvent(payload);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 49a097e8b7a7fd630182ff3f0a325aa21f178cb2 and 119871e2c8f1b1f02a8c6e17f9c595a8a6501763.

📒 Files selected for processing (6)
  • src/sources/shopify/tracker/shopify.util.test.js (2 hunks)
  • src/sources/shopify/tracker/transform.js (5 hunks)
  • src/sources/shopify/tracker/transform.test.js (1 hunks)
  • src/sources/shopify/utils.test.js (1 hunks)
  • src/sources/shopify/webpixelTransformations/pixelTransform.redisCartToken.test.js (0 hunks)
  • src/sources/shopify/webpixelTransformations/pixelTransform.test.js (1 hunks)
💤 Files with no reviewable changes (1)
  • src/sources/shopify/webpixelTransformations/pixelTransform.redisCartToken.test.js
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/sources/shopify/tracker/transform.test.js
  • src/sources/shopify/webpixelTransformations/pixelTransform.test.js
  • src/sources/shopify/tracker/transform.js
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.js`: Focus on ESLint errors (max 3) and warnings (max 5).

**/*.js: Focus on ESLint errors (max 3) and warnings (max 5).

  • src/sources/shopify/utils.test.js
  • src/sources/shopify/tracker/shopify.util.test.js
🧬 Code Definitions (1)
src/sources/shopify/tracker/shopify.util.test.js (1)
src/sources/shopify/tracker/util.js (11)
  • stats (6-6)
  • getShopifyTopic (57-71)
  • lineItems (98-98)
  • getProductsListFromLineItems (83-95)
  • inputEvent (257-257)
  • checkAndUpdateCartItems (242-267)
  • getHashLineItems (72-77)
  • getAnonymousIdAndSessionId (154-208)
  • extractEmailFromPayload (106-118)
  • getCartToken (120-126)
  • createPropertiesForEcomEvent (97-104)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: ingestion-service-test
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (16)
src/sources/shopify/utils.test.js (6)

8-14: Good implementation of Redis mocking

The Redis module mock implementation is clean and follows best practices. The mock includes both required methods (setVal and getVal) with appropriate default return values.


20-26: Good test setup with proper mock cleanup

The beforeEach hook properly clears mocks and resets mock implementations before each test, ensuring test isolation. This is a good testing practice.


28-51: Test case looks good for valid identifier events

The test properly verifies that processIdentifierEvent handles valid events correctly. It validates both the return value and that RedisDB.setVal is called with the correct parameters.


53-74: Test case handles missing cart token correctly

This test properly verifies the behavior when a cart token is missing but userId is present. The assertions correctly check that RedisDB.setVal is called with the alternative key pattern.


77-92: Good test for successful mapping update

The test verifies that updateAnonymousIdToUserIdInRedis correctly calls RedisDB.setVal with the proper arguments and that the stats are incremented appropriately.


94-100: Good edge case handling for missing parameters

The test verifies that updateAnonymousIdToUserIdInRedis correctly handles missing parameters (null values) and doesn't call RedisDB.setVal in these cases, which prevents potential errors.

src/sources/shopify/tracker/shopify.util.test.js (10)

1-10: Imports look good with comprehensive utility functions

All necessary utility functions are imported correctly. This allows for thorough testing of the Shopify utility functions.


15-17: Stats mock is correctly implemented

The mock for the stats module appropriately mocks the increment function, which will allow tests to verify it's called correctly.


20-22: Good test isolation with beforeEach

The beforeEach hook ensures that mocks are cleared before each test, maintaining test isolation and preventing test pollution.


80-87: Good additional test case for getShopifyTopic

This test case adds coverage for the successful extraction of the topic from query parameters, which complements the existing test cases.


90-144: Comprehensive test suite for getProductsListFromLineItems

The tests cover various scenarios including normal operation, empty arrays, null inputs, and missing fields. This ensures the function is robust against different inputs.


147-228: Thorough testing of checkAndUpdateCartItems function

The tests properly verify the function's behavior with new cart items, duplicate cart items, and Redis errors. The expected behavior is correctly validated in each case.


231-253: Good coverage of getHashLineItems edge cases

Tests verify hash generation for valid line items and correctly handle empty or invalid cart objects. The tests ensure the function behaves as expected in all scenarios.


256-286: Good testing of getAnonymousIdAndSessionId scenarios

Tests verify the function correctly handles events with cart tokens and note attributes. The expected behavior is properly validated.


288-313: Comprehensive email extraction testing

Tests verify that extractEmailFromPayload correctly extracts emails from different payload structures and returns undefined when no email is found.


315-333: Good getCartToken tests

Tests verify the function correctly extracts the cart token from properties and returns null when the token is not present. This ensures the function handles different inputs correctly.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 119871e2c8f1b1f02a8c6e17f9c595a8a6501763 and 0429f89ddf862c1f8ea0a37e555fc0e3543f385c.

📒 Files selected for processing (7)
  • src/sources/shopify/tracker/shopify.util.test.js (2 hunks)
  • src/sources/shopify/tracker/transform.js (5 hunks)
  • src/sources/shopify/tracker/transform.redis.test.js (1 hunks)
  • src/sources/shopify/tracker/transform.test.js (1 hunks)
  • src/sources/shopify/utils.test.js (1 hunks)
  • src/sources/shopify/webpixelTransformations/pixelTransform.redisCartToken.test.js (0 hunks)
  • src/sources/shopify/webpixelTransformations/pixelTransform.test.js (1 hunks)
💤 Files with no reviewable changes (1)
  • src/sources/shopify/webpixelTransformations/pixelTransform.redisCartToken.test.js
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/sources/shopify/tracker/transform.test.js
  • src/sources/shopify/webpixelTransformations/pixelTransform.test.js
  • src/sources/shopify/tracker/transform.js
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.js`: Focus on ESLint errors (max 3) and warnings (max 5).

**/*.js: Focus on ESLint errors (max 3) and warnings (max 5).

  • src/sources/shopify/tracker/transform.redis.test.js
  • src/sources/shopify/utils.test.js
  • src/sources/shopify/tracker/shopify.util.test.js
🧠 Learnings (1)
src/sources/shopify/utils.test.js (1)
Learnt from: anantjain45823
PR: rudderlabs/rudder-transformer#2842
File: src/v1/sources/shopify/identifierEventsLayer.test.js:5-40
Timestamp: 2025-04-04T05:14:37.680Z
Learning: The `processIdentifierEvent` function in `identifierEventsLayer.test.js` is designed to succeed for any input, hence no negative test cases are required.
🧬 Code Definitions (1)
src/sources/shopify/tracker/shopify.util.test.js (1)
src/sources/shopify/tracker/util.js (11)
  • stats (6-6)
  • getShopifyTopic (57-71)
  • lineItems (98-98)
  • getProductsListFromLineItems (83-95)
  • inputEvent (257-257)
  • checkAndUpdateCartItems (242-267)
  • getHashLineItems (72-77)
  • getAnonymousIdAndSessionId (154-208)
  • extractEmailFromPayload (106-118)
  • getCartToken (120-126)
  • createPropertiesForEcomEvent (97-104)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: test_and_publish
  • GitHub Check: ingestion-service-test
  • GitHub Check: Analyze (go)
🔇 Additional comments (19)
src/sources/shopify/tracker/transform.redis.test.js (3)

1-14: Well-structured test setup with correct mocking sequence.

The test setup correctly mocks the configuration and Redis connector before importing the modules under test. This ensures the mocked versions are used throughout the tests.


19-30: Good test organization and proper beforeEach cleanup.

The test structure follows best practices with a clear describe block and beforeEach hook to reset mocks between tests.


31-44: Comprehensive test for Redis-disabled functionality.

This test properly verifies that when Redis is disabled, the function returns the expected result and doesn't call Redis methods.

src/sources/shopify/utils.test.js (6)

8-14: Good Redis mock implementation.

The Redis mock setup is clean and includes both necessary methods with appropriate default return values.


20-26: Proper test cleanup with beforeEach.

The beforeEach hook correctly clears all mocks and resets mock implementations, ensuring test isolation.


28-51: Test correctly verifies identifier event processing with cart token.

This test checks that processIdentifierEvent handles the rudderIdentifier event properly and calls Redis with the right parameters.


53-74: Good edge case testing for missing cart token.

The test properly verifies the behavior when cart token is missing but anonymousId is present.


77-92: Verify Redis mapping update is tested correctly.

This test confirms that anonymousId and userId are mapped correctly in Redis with the appropriate TTL.


94-100: Good null parameter handling test.

The test properly verifies that setVal is not called when either parameter is null, preventing potential errors.

src/sources/shopify/tracker/shopify.util.test.js (10)

1-12: Comprehensive import of utility functions for testing.

The test file correctly imports all the utility functions that will be tested.


14-17: Proper mocking of dependencies.

The test correctly mocks the stats module for tracking increment calls.


19-22: Good test isolation with beforeEach.

Using clearAllMocks in beforeEach ensures each test runs with a clean state.


80-88: Added test for topic extraction.

This test enhances coverage by testing successful topic extraction with a specific topic.


90-144: Comprehensive tests for product list transformation.

The tests for getProductsListFromLineItems cover all edge cases including transformation, empty arrays, null inputs, and missing fields.


147-229: Thorough testing of cart operations.

The tests for checkAndUpdateCartItems properly verify new cart detection, duplicate detection, and graceful error handling from Redis failures.


231-253: Good hash generation tests.

The tests for getHashLineItems verify proper hash generation and handling of edge cases.


256-286: User identification tests cover key scenarios.

The tests verify handling of order updates with cart tokens and events with note attributes.


288-313: Email extraction tests are thorough.

Tests cover extraction from different object structures and handle missing email cases.


315-333: Cart token extraction tests are appropriate.

The tests verify extraction from properties and handle cases where tokens are missing.

@koladilip
koladilip force-pushed the refactor/shopify-source-tracker branch 4 times, most recently from 6566418 to cad6bb5 Compare April 4, 2025 06:12
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@koladilip
koladilip force-pushed the refactor/shopify-source-tracker branch from cad6bb5 to 56b71d0 Compare April 7, 2025 04:33
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@yashasvibajpai
yashasvibajpai self-requested a review April 7, 2025 04:57
yashasvibajpai
yashasvibajpai previously approved these changes Apr 7, 2025
add more shopify source tests
@koladilip
koladilip force-pushed the refactor/shopify-source-tracker branch from 56b71d0 to 6913dfe Compare April 8, 2025 07:51
@koladilip
koladilip requested review from a team as code owners April 8, 2025 07:51

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (4)
src/sources/shopify/tracker/util.redis.test.js (2)

28-28: Corrected spelling in test description.

The test case description now uses the correct spelling "retrieved" instead of "retreived", improving readability.


43-43: Corrected spelling in test description.

Another instance of the spelling correction from "retreived" to "retrieved" for consistency.

src/sources/shopify/tracker/util.test.js (2)

24-88: Consider using Jest's .toThrow() matcher for exception tests

The current try-catch pattern works but using Jest's .toThrow() matcher would be more idiomatic and provide better failure messages when tests fail.

-    it('Invalid Topic Test', () => {
-      const input = {
-        query_parameters: {},
-      };
-      const expectedOutput = {
-        error: 'Invalid topic in query_parameters',
-      };
-      try {
-        getShopifyTopic(input);
-      } catch (error) {
-        expect(error.message).toEqual(expectedOutput.error);
-      }
-    });
+    it('Invalid Topic Test', () => {
+      const input = {
+        query_parameters: {},
+      };
+      expect(() => getShopifyTopic(input)).toThrow('Invalid topic in query_parameters');
+    });

231-242: Verify the actual hash value instead of just truthy check

The current test only checks that the hash is truthy, but it would be better to verify either the exact hash value or at least the format/pattern of the generated hash.

      it('should generate hash for valid line items', () => {
        const cart = {
          line_items: [
            {
              id: '1',
              product_id: 'prod1',
            },
          ],
        };
-        expect(getHashLineItems(cart)).toBeTruthy();
+        const hash = getHashLineItems(cart);
+        expect(typeof hash).toBe('string');
+        expect(hash).not.toBe('EMPTY');
+        expect(hash.length).toBeGreaterThan(0);
      });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 56b71d0ab0eeb31d6ac471b9db868b1790402a85 and 6913dfe.

📒 Files selected for processing (11)
  • src/sources/shopify/tracker/config.js (0 hunks)
  • src/sources/shopify/tracker/shopify.util.test.js (0 hunks)
  • src/sources/shopify/tracker/transform.js (4 hunks)
  • src/sources/shopify/tracker/transform.test.js (1 hunks)
  • src/sources/shopify/tracker/util.js (1 hunks)
  • src/sources/shopify/tracker/util.redis.test.js (2 hunks)
  • src/sources/shopify/tracker/util.test.js (1 hunks)
  • src/sources/shopify/utils.test.js (1 hunks)
  • src/sources/shopify/webpixelTransformations/pixelTransform.redisCartToken.test.js (0 hunks)
  • src/sources/shopify/webpixelTransformations/pixelTransform.test.js (1 hunks)
  • src/util/redis/redisConnector.js (2 hunks)
💤 Files with no reviewable changes (3)
  • src/sources/shopify/tracker/config.js
  • src/sources/shopify/webpixelTransformations/pixelTransform.redisCartToken.test.js
  • src/sources/shopify/tracker/shopify.util.test.js
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/sources/shopify/webpixelTransformations/pixelTransform.test.js
  • src/sources/shopify/tracker/transform.test.js
  • src/sources/shopify/tracker/transform.js
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.js`: Focus on ESLint errors (max 3) and warnings (max 5).

**/*.js: Focus on ESLint errors (max 3) and warnings (max 5).

  • src/sources/shopify/tracker/util.redis.test.js
  • src/sources/shopify/tracker/util.js
  • src/util/redis/redisConnector.js
  • src/sources/shopify/tracker/util.test.js
  • src/sources/shopify/utils.test.js
🧬 Code Definitions (3)
src/sources/shopify/tracker/util.js (4)
src/v0/util/index.js (1)
  • isDefinedAndNotNull (49-49)
src/sources/shopify/tracker/transform.js (9)
  • redisData (144-144)
  • redisData (240-240)
  • message (41-41)
  • message (52-52)
  • message (87-87)
  • message (251-251)
  • cartToken (258-259)
  • metricMetadata (320-323)
  • event (222-222)
src/sources/shopify/webhookTransformations/serverSideTransform.js (8)
  • redisData (155-155)
  • message (36-36)
  • message (84-84)
  • message (100-100)
  • message (122-122)
  • metricMetadata (181-184)
  • event (123-123)
  • event (124-124)
src/sources/shopify/webhookTransformations/serverSideUtlis.js (3)
  • redisData (102-102)
  • cartToken (75-75)
  • cartToken (94-94)
src/util/redis/redisConnector.js (6)
src/sources/shopify/tracker/transform.js (3)
  • process (319-329)
  • stats (5-5)
  • logger (16-16)
src/v0/destinations/klaviyo/transform.js (1)
  • process (321-324)
src/sources/shopify/utils.test.js (1)
  • stats (6-6)
src/sources/shopify/tracker/util.test.js (1)
  • stats (12-12)
src/v0/destinations/braze/util.js (2)
  • stats (5-5)
  • logger (4-4)
src/adapters/network.js (2)
  • stats (9-9)
  • logger (15-15)
src/sources/shopify/tracker/util.test.js (1)
src/sources/shopify/tracker/util.js (10)
  • getShopifyTopic (56-70)
  • lineItems (97-97)
  • getProductsListFromLineItems (82-94)
  • inputEvent (254-254)
  • checkAndUpdateCartItems (239-264)
  • getHashLineItems (71-76)
  • getAnonymousIdAndSessionId (153-205)
  • extractEmailFromPayload (105-117)
  • getCartToken (119-125)
  • createPropertiesForEcomEvent (96-103)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: ingestion-service-test
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (9)
src/sources/shopify/tracker/util.js (1)

182-189: Streamlined Redis data retrieval logic.

The code has been simplified by removing the check for useRedisDatabase and directly checking if redisData is defined. This refactoring makes the code more straightforward while maintaining the same functionality.

-  if (useRedisDatabase && !isDefinedAndNotNull(redisData)) {
+  if (!isDefinedAndNotNull(redisData)) {
     const { event } = message;
     // eslint-disable-next-line no-param-reassign
     redisData = await getDataFromRedis(cartToken, metricMetadata, event);
-  }
-  
-  if (useRedisDatabase) {
-    anonymousId = redisData?.anonymousId;
-    sessionId = redisData?.sessionId;
   }
+  anonymousId = redisData?.anonymousId;
+  sessionId = redisData?.sessionId;
src/util/redis/redisConnector.js (2)

12-38: Simplified Redis initialization logic.

The conditional check for USE_REDIS_DB environment variable has been removed, making the Redis client initialization unconditional. This simplifies the code and ensures Redis is always available for use.

Before, the Redis client would only initialize if USE_REDIS_DB was set and not equal to 'false'. Now, it always initializes with the configuration settings.


130-131: Simplified Redis disconnection logic.

Similar to the initialization changes, the disconnection logic now runs unconditionally without checking the USE_REDIS_DB environment variable. This ensures consistent behavior when shutting down the Redis connection.

src/sources/shopify/utils.test.js (6)

8-14: Improved Redis mock implementation.

The Redis mock has been simplified and enhanced with clear mock implementations for setVal and getVal methods. This makes the tests more predictable and easier to understand.


20-26: Added proper test setup with beforeEach.

The addition of a beforeEach block to clear mocks and reset implementations improves test isolation and prevents test state from leaking between test cases.


28-51: Refactored processIdentifierEvent test for better clarity.

The test for processing valid identifier events has been rewritten to be more focused on the core functionality. The test now verifies that Redis setVal is called with the correct parameters and the expected response is returned.


53-74: Added test case for handling missing cart token.

A new test case has been added to verify the behavior when a cart token is missing. This improves test coverage and ensures the function handles edge cases correctly.


77-92: Refactored updateAnonymousIdToUserIdInRedis test for clarity.

The test for updating mappings has been simplified and focuses on verifying that Redis setVal is called with the correct parameters and the stats are incremented properly.


94-100: Added test case for handling missing parameters.

A new test case verifies that setVal is not called when either the anonymousId or userId is null. This improves error handling coverage and ensures the function behaves correctly with invalid inputs.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@sonarqubecloud

sonarqubecloud Bot commented Apr 8, 2025

Copy link
Copy Markdown

@koladilip
koladilip merged commit fd392dc into develop Apr 8, 2025
@koladilip
koladilip deleted the refactor/shopify-source-tracker branch April 8, 2025 09:00
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.

4 participants