Skip to content

[432] Improve app.js for better testing#23

Merged
VitalyyP merged 2 commits intomainfrom
432-feature/improve-app.js-for-testing
Apr 22, 2025
Merged

[432] Improve app.js for better testing#23
VitalyyP merged 2 commits intomainfrom
432-feature/improve-app.js-for-testing

Conversation

@VitalyyP
Copy link
Contributor

@VitalyyP VitalyyP commented Apr 22, 2025

  • Refactor app.js for better testing
  • Add app.test.js for testing configuration

Summary by CodeRabbit

  • Refactor

    • Improved application initialization by modularizing configuration setup and exporting a configuration function.
  • Tests

    • Added tests to verify that configuration values are correctly set based on environment variables and defaults.

- Refactor app.js for better testing
- Add app.test.js for testing configuration
@VitalyyP VitalyyP self-assigned this Apr 22, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 22, 2025

Walkthrough

The changes refactor the ApostropheCMS application initialization in website/app.js by encapsulating the configuration logic within a new createAposConfig function, which is now exported for external use. The session store configuration for Redis is simplified and always included. The application startup is now conditional, running only if the module is executed directly. Additionally, a new test suite website/app.test.js is introduced to verify that createAposConfig correctly handles environment variables and defaults, using Jest to mock the Redis connector and isolate the configuration logic.

Changes

File(s) Change Summary
website/app.js Refactored ApostropheCMS initialization into an exported createAposConfig function; simplified and standardized Redis session store configuration; made app startup conditional on direct execution.
website/app.test.js Added Jest-based tests for createAposConfig, including environment variable handling and Redis store mocking.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant app.js
    participant RedisStore
    participant Apostrophe

    Caller->>app.js: import { createAposConfig }
    Note right of app.js: (Optionally) set env variables
    Caller->>app.js: createAposConfig()
    app.js->>RedisStore: Initialize Redis session store with URL
    app.js-->>Caller: Return config object

    alt If run directly (node app.js)
        app.js->>Apostrophe: Start with createAposConfig()
    end
Loading
sequenceDiagram
    participant TestRunner
    participant app.test.js
    participant app.js
    participant RedisStore

    TestRunner->>app.test.js: Run tests
    app.test.js->>app.js: import { createAposConfig }
    app.test.js->>RedisStore: Mock RedisStore
    app.test.js->>app.js: createAposConfig() (with/without env vars)
    app.js->>RedisStore: Initialize Redis store (mocked)
    app.js-->>app.test.js: Return config object
    app.test.js-->>TestRunner: Assert config correctness
Loading
✨ 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 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: 0

🧹 Nitpick comments (4)
website/app.test.js (2)

12-27: Consider using assignment instead of delete for environment variables.

While the test correctly verifies default configuration values, using the delete operator on process.env properties may impact performance as flagged by static analysis.

-    delete process.env.BASE_URL;
-    delete process.env.SESSION_SECRET;
-    delete process.env.REDIS_URI;
+    process.env.BASE_URL = undefined;
+    process.env.SESSION_SECRET = undefined;
+    process.env.REDIS_URI = undefined;
🧰 Tools
🪛 Biome (1.9.4)

[error] 13-13: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 14-14: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 15-15: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


1-44: Consider adding a test for partial environment configuration.

The current tests verify either all default values or all environment values. Adding a test with only some environment variables set would ensure the function correctly handles mixed scenarios.

test('handles partial environment configuration', () => {
  process.env.BASE_URL = 'http://partial-test.com';
  process.env.SESSION_SECRET = undefined;
  process.env.REDIS_URI = undefined;
  
  const config = createAposConfig();
  
  expect(config.baseUrl).toBe('http://partial-test.com');
  expect(
    config.modules['@apostrophecms/express'].options.session.secret,
  ).toBe('changeme');
  expect(
    config.modules['@apostrophecms/express'].options.session.store,
  ).toEqual({
    connect: mockConnectRedis,
    options: { url: 'redis://localhost:6379' },
  });
});
🧰 Tools
🪛 Biome (1.9.4)

[error] 13-13: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 14-14: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 15-15: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

website/app.js (2)

51-54: Remove commented code.

There's commented-out widget declarations that appear to be duplicates of active configurations (lines 41-42). Commented code can create confusion and should be removed.

-      /*
-       * 'links-buttons-widget': {},
-       * 'team-carousel-widget': {},
-       */

1-85: Consider adding JSDoc comments for the exported function.

Adding JSDoc comments would improve documentation and provide better IDE support for users of this function.

+/**
+ * Creates the Apostrophe CMS configuration object
+ * @returns {Object} The complete Apostrophe configuration object
+ */
function createAposConfig() {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 80d790c and b363671.

📒 Files selected for processing (2)
  • website/app.js (1 hunks)
  • website/app.test.js (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
website/app.js (2)
website/app.test.js (1)
  • require (1-1)
website/modules/@apostrophecms/form/index.js (1)
  • require (1-1)
🪛 Biome (1.9.4)
website/app.test.js

[error] 13-13: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 14-14: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 15-15: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: unit-tests
  • GitHub Check: security-scan
🔇 Additional comments (6)
website/app.test.js (3)

1-3: Well-structured test setup with good module mocking.

The test file correctly imports the createAposConfig function and mocks the Redis connector to isolate your tests from external dependencies. This is a good practice for unit testing.


4-11: Excellent environment variable management.

Properly saving and restoring the original environment variables between tests ensures test isolation and prevents test pollution. This is a good testing practice.


28-44: Good test for environment variable overrides.

This test effectively verifies that the configuration properly uses environment variables when they're set, which is crucial for different deployment environments.

website/app.js (3)

3-80: Great refactoring for testability and configuration isolation.

Extracting the configuration into a separate function makes it reusable and testable, which is exactly what you're doing with the new test file. The configuration is well-structured and properly uses environment variables with sensible defaults.


81-84: Good use of conditional execution.

The conditional check to only run the application when directly executed is a good practice that enables importing the configuration without starting the app. The istanbul ignore comment also correctly excludes this from code coverage.


85-85: Clean exports implementation.

Exporting the createAposConfig function with a named export makes the API clear and easy to use in other modules.

@github-actions
Copy link

github-actions bot commented Apr 22, 2025

🔍 Vulnerabilities of apostrophe-cms:test

📦 Image Reference apostrophe-cms:test
digestsha256:19c023f1bca706a166abff441511776e62e11ce9b75628c4930df583a00fbbca
vulnerabilitiescritical: 1 high: 2 medium: 0 low: 0
platformlinux/amd64
size643 MB
packages1447
📦 Base Image node:23-bullseye
also known as
  • 23.11-bullseye
  • 23.11.0-bullseye
  • bullseye
  • current-bullseye
digestsha256:128067b8c33d5ad2834513ed3351f29803280407037c2cc66957f0e5d1b3ddd1
vulnerabilitiescritical: 1 high: 0 medium: 6 low: 192 unspecified: 5
critical: 1 high: 0 medium: 0 low: 0 wget 1.21-1+deb11u1 (deb)

pkg:deb/debian/wget@1.21-1%2Bdeb11u1?os_distro=bullseye&os_name=debian&os_version=11

critical : CVE--2024--38428

Affected range<1.21-1+deb11u2
Fixed version1.21-1+deb11u2
EPSS Score0.265%
EPSS Percentile50th percentile
Description

url.c in GNU Wget through 1.24.5 mishandles semicolons in the userinfo subcomponent of a URI, and thus there may be insecure behavior in which data that was supposed to be in the userinfo subcomponent is misinterpreted to be part of the host subcomponent.


critical: 0 high: 1 medium: 0 low: 0 async 1.5.2 (npm)

pkg:npm/async@1.5.2

high 7.8: CVE--2021--43138 OWASP Top Ten 2017 Category A9 - Using Components with Known Vulnerabilities

Affected range<2.6.4
Fixed version2.6.4, 3.2.2
CVSS Score7.8
CVSS VectorCVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H
EPSS Score0.915%
EPSS Percentile75th percentile
Description

A vulnerability exists in Async through 3.2.1 (fixed in 3.2.2), which could let a malicious user obtain privileges via the mapValues() method.

critical: 0 high: 1 medium: 0 low: 0 async 0.9.2 (npm)

pkg:npm/async@0.9.2

high 7.8: CVE--2021--43138 OWASP Top Ten 2017 Category A9 - Using Components with Known Vulnerabilities

Affected range<2.6.4
Fixed version2.6.4, 3.2.2
CVSS Score7.8
CVSS VectorCVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H
EPSS Score0.915%
EPSS Percentile75th percentile
Description

A vulnerability exists in Async through 3.2.1 (fixed in 3.2.2), which could let a malicious user obtain privileges via the mapValues() method.

Copy link
Contributor

@yuramax yuramax left a comment

Choose a reason for hiding this comment

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

Looks great!

Screenshot 2025-04-22 at 17 20 54

Copy link
Collaborator

@killev killev left a comment

Choose a reason for hiding this comment

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

LGTM. Approved

Copy link
Contributor

@Anton-88 Anton-88 left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Contributor

@IhorMasechko IhorMasechko left a comment

Choose a reason for hiding this comment

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

LGTM

@sonarqubecloud
Copy link

@VitalyyP VitalyyP merged commit f2ae279 into main Apr 22, 2025
11 checks passed
@VitalyyP VitalyyP deleted the 432-feature/improve-app.js-for-testing branch April 22, 2025 15:46
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.

5 participants