Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

test(config): Add unit tests for config utilities; Update test files ESLint config to extend from eslint-config-yscope/jest. #135

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

junhaoliao
Copy link
Collaborator

@junhaoliao junhaoliao commented Nov 28, 2024

Description

  1. Add unit tests for config utilities.
  2. Add dev dependency jest-environment-jsdom.
  3. Update test files ESLint config to extend from eslint-config-yscope/jest.
  4. Enforce 100% branches / functions / lines coverage on file src/utils/config.ts.
  5. Exclude coverage for unreachable lines / branches in file src/utils/config.ts.

Validation performed

  1. Ran all tests and ensured all test cases passed with no coverage threshold failure.

Summary by CodeRabbit

  • New Features

    • Added a new dependency for Jest testing environment.
    • Introduced a new test suite for configuration utilities, covering various scenarios.
    • Exported a new variable, MAX_PAGE_SIZE, for configuration management.
  • Bug Fixes

    • Enhanced error handling consistency for configuration management.
  • Documentation

    • Improved comments in the configuration utility functions for clarity.
  • Chores

    • Updated Jest configuration to include a new coverage threshold for a specific file.

Copy link

coderabbitai bot commented Nov 28, 2024

Walkthrough

This pull request introduces several changes across multiple files. The Jest configuration in jest.config.ts now includes a 100% coverage threshold for src/utils/config.ts. The package.json file has been updated to add a new dependency, jest-environment-jsdom, and the ESLint configuration has been modified to extend from yscope/jest. Additionally, the src/utils/config.ts file has been updated for improved error handling related to the THEME configuration key and now exports a new variable, MAX_PAGE_SIZE. A new test suite in test/utils/config.test.ts has been created to validate the configuration utilities.

Changes

File Change Summary
jest.config.ts Added a coverage threshold of 100% for branches, functions, and lines for src/utils/config.ts.
package.json Added dependency: "jest-environment-jsdom": "^29.7.0"; updated ESLint config to extend from yscope/jest.
src/utils/config.ts Improved error handling for THEME key in testConfig, setConfig, and getConfig; added variable MAX_PAGE_SIZE.
test/utils/config.test.ts Introduced unit tests for testConfig, setConfig, and getConfig, covering various valid and invalid scenarios.

Possibly related PRs

Suggested reviewers

  • davemarco

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 25e245c and 44b6196.

📒 Files selected for processing (1)
  • test/utils/config.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/utils/config.test.ts

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@junhaoliao junhaoliao requested a review from davemarco November 28, 2024 10:10
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (5)
src/utils/config.ts (2)

106-111: Consider removing unreachable code

Since testConfig throws an error for the THEME key, this case in the switch statement is unreachable. Consider removing it to improve code maintainability.

-        /* c8 ignore start */
-        case CONFIG_KEY.THEME:
-            // Unexpected execution path.
-            break;
-        /* c8 ignore end */
         /* c8 ignore next */
         default: break;

58-60: Consider extracting the error message to a constant

The error message "${key}" cannot be managed using these utilities is duplicated. Consider extracting it to a constant to maintain consistency and ease future updates.

+const UNMANAGEABLE_CONFIG_ERROR = (key: string) => 
+    `"${key}" cannot be managed using these utilities.`;

 // In testConfig
-            throw new Error(`"${key}" cannot be managed using these utilities.`);
+            throw new Error(UNMANAGEABLE_CONFIG_ERROR(key));

 // In getConfig
-            throw new Error(`"${key}" cannot be managed using these utilities.`);
+            throw new Error(UNMANAGEABLE_CONFIG_ERROR(key));

Also applies to: 149-151

test/utils/config.test.ts (3)

21-75: Consider centralizing error messages and test constants.

While the test constants are well-defined, consider moving error messages and validation constants to a shared constants file to maintain consistency across the codebase.

Consider creating a new file src/constants/errors.ts:

export const CONFIG_ERRORS = {
    EMPTY_TIMESTAMP_KEY: 'Timestamp key cannot be empty.',
    EMPTY_LOG_LEVEL_KEY: 'Log level key cannot be empty.',
    INVALID_PAGE_SIZE: (maxSize: number) => 
        `Page size must be greater than 0 and less than ${maxSize + 1}.`,
    UNMANAGED_THEME: (key: string) => 
        `"${key}" cannot be managed using these utilities.`
} as const;

76-104: Enhance type safety in the test helper function.

The helper function could benefit from more explicit type definitions and error handling.

Consider this improvement:

-const runNegativeCases = (func: (input: ConfigUpdate) => Nullable<string>) => {
+type TestFunction = (input: ConfigUpdate) => Nullable<string>;
+type TestCase = {
+    input: ConfigUpdate | ConfigUpdate[];
+    expected?: Nullable<string | string[]>;
+    throwable?: Error;
+};
+
+const runNegativeCases = (func: TestFunction) => {
+    const runSingleCase = (
+        testInput: ConfigUpdate,
+        expectedResult?: Nullable<string>
+    ) => {
+        const result = func(testInput);
+        expect(result).toBe(expectedResult);
+    };

105-242: Consider improving test descriptions for clarity.

While the test coverage is comprehensive, some test descriptions could be more specific about the scenarios they're testing.

Consider these improvements:

  • Line 108: "should return null for valid decoder options" -> "should validate decoder options with all required fields"
  • Line 180: "should log an error for invalid page size" -> "should log an error when page size is negative"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 82e677e and 25e245c.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • jest.config.ts (1 hunks)
  • package.json (2 hunks)
  • src/utils/config.ts (4 hunks)
  • test/utils/config.test.ts (1 hunks)
🔇 Additional comments (8)
jest.config.ts (2)

34-38: LGTM! Coverage threshold aligns with testing standards.

The addition of 100% coverage threshold for src/utils/config.ts maintains consistency with other utility files like math.ts.


34-38: Verify test coverage implementation.

Let's ensure the new coverage requirements are achievable and properly implemented.

✅ Verification successful

100% test coverage requirement is achievable and properly implemented

The test coverage requirements are reasonable and achievable based on the following evidence:

  1. The implementation in config.ts is well-structured with clear, distinct code paths
  2. The test file config.test.ts demonstrates comprehensive coverage:
    • Tests all config operations (get, set, test) for each config key
    • Includes negative test cases for invalid inputs
    • Verifies error conditions and edge cases
    • Tests default values and localStorage interactions
  3. The only excluded code paths are properly marked with /* c8 ignore */ comments for unreachable defensive code

The existing test suite adequately covers:

  • All branches in switch statements
  • Validation logic for all config types
  • Error handling scenarios
  • Default value fallbacks
  • Type conversions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of test file and its coverage

# Check if test file exists
echo "Checking for config test file..."
fd "config.test.ts" test/utils/

# Check test coverage implementation
echo "Checking test coverage implementation..."
rg -A 5 "describe|test|it" test/utils/config.test.ts

# Check for any uncovered code markers
echo "Checking for coverage exclusion markers..."
rg "istanbul ignore" src/utils/config.ts

Length of output: 5580


Script:

#!/bin/bash
# Let's check the actual implementation to verify coverage feasibility

# Check the implementation of config.ts
echo "Checking config.ts implementation..."
cat src/utils/config.ts

# Check for any complex logic or edge cases
echo "Checking for complex patterns..."
ast-grep --pattern 'function $FNAME($$$) { $$$ }' src/utils/config.ts

# Check for conditional statements that might affect coverage
echo "Checking conditional statements..."
rg "if|switch|try" src/utils/config.ts

Length of output: 6619

package.json (2)

58-58: LGTM: Jest environment dependency added correctly

The addition of jest-environment-jsdom at version ^29.7.0 aligns perfectly with your existing Jest version and is essential for testing React components in a simulated browser environment.


101-101: LGTM: ESLint configuration simplified

The ESLint configuration for test files has been streamlined by extending from yscope/jest, which is a more maintainable approach than managing environment settings directly.

src/utils/config.ts (3)

58-60: LGTM: Clear and consistent error handling for theme configuration

The error handling for the THEME key is well-implemented and follows the function's documented behaviour.


149-151: LGTM: Consistent error handling pattern

The error handling for the THEME key maintains consistency with the pattern established in testConfig.


177-177: LGTM: Appropriate export of validation constant

Exporting MAX_PAGE_SIZE is appropriate as it represents a validation boundary that consumers might need to reference.

test/utils/config.test.ts (1)

1-20: LGTM! Environment and imports are well-structured.

The test environment and imports are properly configured for testing browser-specific functionality.

Comment on lines 231 to 235
it("should retrieve page size once set", () => {
setConfig({key: CONFIG_KEY.PAGE_SIZE, value: VALID_PAGE_SIZE});
const result = getConfig(CONFIG_KEY.PAGE_SIZE);
expect(result).toBe(VALID_PAGE_SIZE);
});
Copy link

@coderabbitai coderabbitai bot Nov 28, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove duplicate test case.

This test case is a duplicate of the one at lines 219-223.

Remove this duplicate test case:

-    it("should retrieve page size once set", () => {
-        setConfig({key: CONFIG_KEY.PAGE_SIZE, value: VALID_PAGE_SIZE});
-        const result = getConfig(CONFIG_KEY.PAGE_SIZE);
-        expect(result).toBe(VALID_PAGE_SIZE);
-    });

Copy link
Contributor

Choose a reason for hiding this comment

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

I agree with rabbit on this one

Copy link

Choose a reason for hiding this comment

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

@davemarco, thank you for confirming.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

good catch. fixed now

Copy link

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@junhaoliao
Copy link
Collaborator Author

discussed offline with @davemarco and he will review this later in the evening

Copy link
Contributor

@davemarco davemarco left a comment

Choose a reason for hiding this comment

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

Sorry for delay. I've never used this framework before so just reading through docs. I posted some general questions

case CONFIG_KEY.THEME:
// Unexpected execution path.
break;
/* c8 ignore end */
Copy link
Contributor

Choose a reason for hiding this comment

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

Is it better to do this? Or just allow a few lines to be excluded from coverage? Personally i don't know, just want to hear your thoughts

Copy link
Collaborator Author

@junhaoliao junhaoliao Dec 4, 2024

Choose a reason for hiding this comment

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

just allow a few lines to be excluded from coverage?

Do you mean /* c8 ignore next 2 */ for example? I think that can be cleaner indeed

Copy link
Contributor

Choose a reason for hiding this comment

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

Oh i was thinking just lowering the coverage to like 99 for this file to avoid this ugly comment.. But ignore this comment for now. If we change the logic for setting the theme, this branch is reachable, and this comment is irrelevant.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

/**
* Negative test cases for `testConfig` and `setConfig` function.
*/
const NEGATIVE_CONFIG_CASES: Record<string, {
Copy link
Contributor

@davemarco davemarco Dec 4, 2024

Choose a reason for hiding this comment

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

Why do this when we could just run them like positive cases?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

That's an attempt to deduplicate the test code for testConfig and setConfig, since everything that fails testConfig would also fail setConfig

Copy link
Contributor

Choose a reason for hiding this comment

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

I see. I think the code is a bit hard to read. I suggest two options.

Option 1: Only run all the tests for testConfig() (and write them like normal jest tests), and then just have a single negative test for setConfig(). I think this will still get "100% coverage", but slightly less accurate since we are not testing all errors in setConfig().

Options 2: Try to refactor current code. There may be a cleaner approach something like below where all the tests are defined in a standard jest format, but I have not yet attempted myself.

const defineConfigTests = (func) => {
    it('test1', () => {
      expect(func(input1).toBe('number');
    });

    it('test2', () => {
      expect(func(input2)).toBeGreaterThan(0);
    });

    etc...
};

Copy link
Contributor

@davemarco davemarco left a comment

Choose a reason for hiding this comment

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

I took a deeper look

case CONFIG_KEY.PAGE_SIZE:
if (0 >= value || MAX_PAGE_SIZE < value) {
result = `Page size must be greater than 0 and less than ${MAX_PAGE_SIZE + 1}.`;
}
break;
case CONFIG_KEY.THEME:
Copy link
Contributor

Choose a reason for hiding this comment

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

Question why do we not just let user set the theme in local storage? Would this not be simpler? See suggestion in setConfig()

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This was considered an impossible code path (i.e., calling testConfig or setConfig with CONFIG_KEY.THEME at any place would constitute an implementation error) because only JoyUI should have direct access on the theme config. We only created the theme-related types and localStorage keys to avoid type and key conflicts. With that said, i do see that we could be calling setConfig to set the theme once we implement the profile system, where we could be restoring theme name settings from a profile.
If you agree, we can implement CONFIG_KEY.THEME in the config utilities in preparation of the config profile system.

case CONFIG_KEY.PAGE_SIZE:
if (0 >= value || MAX_PAGE_SIZE < value) {
result = `Page size must be greater than 0 and less than ${MAX_PAGE_SIZE + 1}.`;
}
break;
case CONFIG_KEY.THEME:
throw new Error(`"${key}" cannot be managed using these utilities.`);
/* c8 ignore next */
Copy link
Contributor

Choose a reason for hiding this comment

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

You can actually remove this and will still get 100% coverage

Suggested change
/* c8 ignore next */

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

That seems to be required to achieve 100% branch coverage. With this exclusion removed, do you see below error when you run npm run test?

Jest: "src/utils/config.ts" coverage threshold for branches (100%) not met: 97.14%
...
Ran all test suites.

Process finished with exit code 1

case CONFIG_KEY.THEME:
// Unexpected execution path.
break;
/* c8 ignore end */
Copy link
Contributor

Choose a reason for hiding this comment

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

Oh i was thinking just lowering the coverage to like 99 for this file to avoid this ugly comment.. But ignore this comment for now. If we change the logic for setting the theme, this branch is reachable, and this comment is irrelevant.

// Unexpected execution path.
break;
/* c8 ignore end */
/* c8 ignore next */
Copy link
Contributor

Choose a reason for hiding this comment

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

You can remove this and still get 100% coverage

Suggested change
/* c8 ignore next */

case CONFIG_KEY.PAGE_SIZE:
value = window.localStorage.getItem(LOCAL_STORAGE_KEY.PAGE_SIZE);
break;
case CONFIG_KEY.THEME:
throw new Error(`"${key}" cannot be managed using these utilities.`);
/* c8 ignore next */
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
/* c8 ignore next */

} from "../../src/utils/config";


const VALID_DECODER_OPTIONS: DecoderOptions = {
Copy link
Contributor

Choose a reason for hiding this comment

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

I think you should add brief doc strings here like

Suggested change
const VALID_DECODER_OPTIONS: DecoderOptions = {
/**
* Sample decoder options that are expected to pass validation.
*/
const VALID_DECODER_OPTIONS: DecoderOptions = {

Same for definitions below.

/**
* Negative test cases for `testConfig` and `setConfig` function.
*/
const NEGATIVE_CONFIG_CASES: Record<string, {
Copy link
Contributor

Choose a reason for hiding this comment

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

I see. I think the code is a bit hard to read. I suggest two options.

Option 1: Only run all the tests for testConfig() (and write them like normal jest tests), and then just have a single negative test for setConfig(). I think this will still get "100% coverage", but slightly less accurate since we are not testing all errors in setConfig().

Options 2: Try to refactor current code. There may be a cleaner approach something like below where all the tests are defined in a standard jest format, but I have not yet attempted myself.

const defineConfigTests = (func) => {
    it('test1', () => {
      expect(func(input1).toBe('number');
    });

    it('test2', () => {
      expect(func(input2)).toBeGreaterThan(0);
    });

    etc...
};

});

it("should log an error for invalid page size", () => {
const consoleSpy = jest.spyOn(console, "error").mockImplementation();
Copy link
Contributor

Choose a reason for hiding this comment

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

What is the point of this mock? Does it do anything? If not I would remove and just make it simpler.

Copy link
Contributor

Choose a reason for hiding this comment

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

Like is the

expect(result).toBe(
            `Page size must be greater than 0 and less than ${MAX_PAGE_SIZE + 1}.` );

enough by itself for this unit test?

Copy link
Collaborator Author

@junhaoliao junhaoliao Dec 9, 2024

Choose a reason for hiding this comment

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

My mistake here. The mockImplementation() call should be called with a dummy jest.fn() (i.e., it should be jest.spyOn(console, "error").mockImplementation(jest.fn()) so that the error message doesn't get printed in the console. When it does show, it shows up with a stack trace in jest's output. I mistakenly thought that argument was fine to be removed when I ran the tests with PyCharm.

Like is the ... enough by itself for this unit test?

Sure, if we treat those as debug messages that only concern us developers (sounds right to me). Do you think it would be a good idea to check expect(consoleSpy).toHaveBeenCalled() or expect(consoleSpy).toHaveBeenCalledTimes(1) so that we are not blindly suppressing the console errors? That way we can be notified about such expectation changes when our implementation accidentally / intentionally removes a console error log.

Comment on lines 231 to 235
it("should retrieve page size once set", () => {
setConfig({key: CONFIG_KEY.PAGE_SIZE, value: VALID_PAGE_SIZE});
const result = getConfig(CONFIG_KEY.PAGE_SIZE);
expect(result).toBe(VALID_PAGE_SIZE);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

I agree with rabbit on this one

case CONFIG_KEY.PAGE_SIZE:
window.localStorage.setItem(LOCAL_STORAGE_KEY.PAGE_SIZE, value.toString());
break;
/* c8 ignore start */
case CONFIG_KEY.THEME:
// Unexpected execution path.
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
// Unexpected execution path.
window.localStorage.setItem(LOCAL_STORAGE_KEY.THEME, value.toString());

Copy link
Contributor

Choose a reason for hiding this comment

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

Why dont we save the theme selection to local storage?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Discussed at https://github.com/y-scope/yscope-log-viewer/pull/135/files#r1876734225 : we allocate the types and enums for theme config only to avoid name conflicts and we expected only JoyUI to read / write into localStorage, which might subject to change in the future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants