Skip to content

Add unit tests for untested utility functions#11

Open
niconiconi wants to merge 1 commit intomainfrom
claude/implement-todo-item-FyJKw
Open

Add unit tests for untested utility functions#11
niconiconi wants to merge 1 commit intomainfrom
claude/implement-todo-item-FyJKw

Conversation

@niconiconi
Copy link
Copy Markdown
Contributor

Cover isHexStrict, toBigintOrThrow, stableStringify, bigintReplacer,
signalTimeout, and signalAny — all previously had zero dedicated tests.

https://claude.ai/code/session_01CwAhCXrYxQAdL7Vdy6DW7U

Cover isHexStrict, toBigintOrThrow, stableStringify, bigintReplacer,
signalTimeout, and signalAny — all previously had zero dedicated tests.

https://claude.ai/code/session_01CwAhCXrYxQAdL7Vdy6DW7U
@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the robustness and reliability of several core utility functions by introducing dedicated unit tests. These tests cover various edge cases and expected behaviors for functions related to hexadecimal validation, BigInt conversion and serialization, stable JSON stringification, and AbortSignal management, ensuring their correct operation and preventing future regressions.

Highlights

  • Unit Tests for isHexStrict: Added comprehensive unit tests for the isHexStrict utility function to validate its behavior with various inputs, including valid hex strings, non-string types, incorrect prefixes, odd lengths, and non-hex characters, also covering the minBytes option.
  • Unit Tests for toBigintOrThrow: Implemented unit tests for the toBigintOrThrow utility function to ensure correct conversion of bigint values, numeric strings, and finite numbers, and proper error handling for invalid inputs with detailed error messages.
  • Unit Tests for JSON Utilities: Introduced unit tests for bigintReplacer, serializeBigInt, and stableStringify to verify bigint serialization, stable JSON stringification with sorted keys, handling of nested objects, arrays, undefined values, nulls, and primitives.
  • Unit Tests for Signal Utilities: Created unit tests for signalTimeout and signalAny to confirm AbortSignal creation, timeout functionality, and correct combination of multiple signals, including pre-aborted states.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • tests/bigint.test.ts
    • Added new test file to cover toBigintOrThrow utility.
  • tests/hex.test.ts
    • Added new test file to cover isHexStrict utility.
  • tests/json.test.ts
    • Added new test file to cover bigintReplacer, serializeBigInt, and stableStringify utilities.
  • tests/signal.test.ts
    • Added new test file to cover signalTimeout and signalAny utilities.
Activity
  • No activity has occurred on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request adds much-needed unit tests for several utility functions, significantly improving code coverage. The new tests are generally well-structured. I've identified a few areas for improvement in the tests themselves to make them more robust and accurately reflect the behavior they are testing. Additionally, I've found a potential memory leak in the signalAny polyfill that the new tests are for. My detailed comments provide suggestions for these points.

Comment on lines +28 to +37
it('aborts when any input signal aborts', () => {
const c1 = new AbortController();
const c2 = new AbortController();
const combined = signalAny([c1.signal, c2.signal]);
expect(combined).toBeDefined();
expect(combined!.aborted).toBe(false);

c1.abort(new Error('first'));
expect(combined!.aborted).toBe(true);
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

While this test correctly verifies that the combined signal aborts, it doesn't cover a potential memory leak in the signalAny polyfill. The current implementation does not remove event listeners from the other source signals after one has aborted. This can lead to memory leaks if signalAny is used frequently with signals that have longer lifecycles.

A more robust implementation would clean up all listeners once the combined signal is aborted. While this is difficult to test without mocking, it's a significant issue in the underlying implementation that these tests are covering.

Comment on lines +30 to +38
it('includes field name in error message', () => {
try {
toBigintOrThrow('bad', ctx);
} catch (err) {
expect(err).toBeInstanceOf(SdkError);
expect((err as SdkError).message).toContain('amount');
expect((err as SdkError).code).toBe('CONFIG');
}
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Using a try...catch block to assert on thrown errors can be brittle. If toBigintOrThrow('bad', ctx) doesn't throw, this test will pass silently, which is incorrect. It's better to use vitest's expect().toThrow() with an error object matcher for a more robust and concise test.

  it('includes field name in error message', () => {
    expect(() => toBigintOrThrow('bad', ctx)).toThrow(
      expect.objectContaining({
        message: expect.stringContaining('amount'),
        code: 'CONFIG',
      }),
    );
  });

Comment on lines +31 to +35
it('handles nested objects with sorted keys', () => {
const result = stableStringify({ b: { d: 1, c: 2 }, a: 3 });
const keys = Object.keys(JSON.parse(result));
expect(keys).toEqual(['a', 'b']);
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

This test case only verifies that the top-level keys are sorted. It doesn't check if the keys of nested objects are also sorted, which is part of the function's intended behavior. To properly test this, you should compare the stringified output of objects with differently ordered nested keys or assert against the exact expected string output.

Suggested change
it('handles nested objects with sorted keys', () => {
const result = stableStringify({ b: { d: 1, c: 2 }, a: 3 });
const keys = Object.keys(JSON.parse(result));
expect(keys).toEqual(['a', 'b']);
});
it('handles nested objects with sorted keys', () => {
const a = stableStringify({ b: { d: 1, c: 2 }, a: 3 });
const b = stableStringify({ a: 3, b: { c: 2, d: 1 } });
expect(a).toBe(b);
expect(a).toBe('{"a":3,"b":{"c":2,"d":1}}');
});

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