Skip to content

Comments

add test for utils#2672

Merged
hayescode merged 1 commit intoChainlit:mainfrom
codomposer:feat/test_utils
Nov 20, 2025
Merged

add test for utils#2672
hayescode merged 1 commit intoChainlit:mainfrom
codomposer:feat/test_utils

Conversation

@codomposer
Copy link
Contributor

@codomposer codomposer commented Nov 20, 2025

Add Comprehensive Test Suite for Utils Module

Overview

Adds comprehensive test coverage for utility functions in the utils module, including datetime formatting, function wrapping, module management, and file validation.

Changes

New Test File

  • tests/test_utils.py - 40 tests covering core utility functions

Test Coverage

DateTime Functions (11 tests)

  • utc_now() - Current UTC timestamp in ISO format
    • String format validation
    • ISO format with Z suffix
    • Current time accuracy
    • Format consistency
  • timestamp_utc() - Convert Unix timestamp to ISO format
    • Epoch handling (0, negative timestamps)
    • Fractional seconds
    • Large timestamps (far future)

Function Wrapping (9 tests)

  • wrap_user_function() - Wraps user functions with error handling
    • Sync and async function support
    • Task management integration
    • Exception handling
    • Function metadata preservation
    • Default arguments support

Module Management (6 tests)

  • make_module_getattr() - Lazy module imports (PEP 562)
  • check_module_version() - Version compatibility checking
    • Installed vs required versions
    • Nonexistent modules
    • Builtin modules without version

File Validation (7 tests)

  • check_file() - Validate Python file paths
    • Valid extensions (.py, .py3)
    • Invalid extensions
    • Missing extensions
    • Nonexistent files
    • Relative and absolute paths

Edge Cases (7 tests)

  • Multiple exception types
  • Empty registries
  • Special characters in paths
  • Large timestamps

Key Features Tested

DateTime Utilities

# Current UTC time in ISO format
utc_now()  # Returns: "2024-11-19T22:30:45.123456Z"

# Convert timestamp to ISO format
timestamp_utc(1234567890.0)  # Returns: "2009-02-13T23:31:30Z"

Function Wrapping

# Wrap user function with error handling and task management
@wrap_user_function(user_func, with_task=True)
async def wrapped_func(*args):
    # Automatically handles:
    # - Parameter mapping
    # - Task start/end events
    # - Exception logging
    # - Async/sync function support

Module Validation

# Check if module meets version requirement
check_module_version("pytest", "7.0.0")  # Returns: True/False

# Lazy module imports
registry = {"MyClass": "my.module"}
getattr_func = make_module_getattr(registry)

File Validation

# Validate Python file before loading
check_file("app.py")  # OK
check_file("app.txt")  # Raises BadArgumentUsage
check_file("missing.py")  # Raises BadParameter

Test Statistics

  • Total Tests: 40
  • Test Classes: 6
  • Coverage: DateTime, function wrapping, module management, file validation, edge cases

Related Files

  • chainlit/utils.py - Utility functions implementation
  • chainlit/context.py - Context management for wrapped functions
  • chainlit/logger.py - Logging integration

Contribution by Gittensor, learn more at https://gittensor.io/

@dosubot dosubot bot added size:L This PR changes 100-499 lines, ignoring generated files. backend Pertains to the Python backend. labels Nov 20, 2025
@hayescode hayescode enabled auto-merge November 20, 2025 03:48
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

2 issues found across 1 file

Prompt for AI agents (all 2 issues)

Understand the root cause of the following 2 issues and fix them.


<file name="backend/tests/test_utils.py">

<violation number="1" location="backend/tests/test_utils.py:55">
`test_utc_now_multiple_calls` never asserts the two timestamps differ, so it provides no coverage for the scenario it claims to check.</violation>

<violation number="2" location="backend/tests/test_utils.py:291">
`test_check_module_version_with_builtin_module` asserts that `check_module_version` raises instead of returning a boolean, contradicting the function’s documented contract and locking in incorrect behavior.</violation>
</file>

Reply to cubic to teach it or ask questions. Re-run a review with @cubic-dev-ai review this PR

def test_check_module_version_with_builtin_module(self):
"""Test with a builtin module that has no __version__."""
# os module doesn't have __version__
with pytest.raises(AttributeError):
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Nov 20, 2025

Choose a reason for hiding this comment

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

test_check_module_version_with_builtin_module asserts that check_module_version raises instead of returning a boolean, contradicting the function’s documented contract and locking in incorrect behavior.

Prompt for AI agents
Address the following comment on backend/tests/test_utils.py at line 291:

<comment>`test_check_module_version_with_builtin_module` asserts that `check_module_version` raises instead of returning a boolean, contradicting the function’s documented contract and locking in incorrect behavior.</comment>

<file context>
@@ -0,0 +1,449 @@
+    def test_check_module_version_with_builtin_module(self):
+        &quot;&quot;&quot;Test with a builtin module that has no __version__.&quot;&quot;&quot;
+        # os module doesn&#39;t have __version__
+        with pytest.raises(AttributeError):
+            check_module_version(&quot;os&quot;, &quot;1.0.0&quot;)
+
</file context>
Fix with Cubic

or before <= result_dt <= after
)

def test_utc_now_multiple_calls(self):
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Nov 20, 2025

Choose a reason for hiding this comment

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

test_utc_now_multiple_calls never asserts the two timestamps differ, so it provides no coverage for the scenario it claims to check.

Prompt for AI agents
Address the following comment on backend/tests/test_utils.py at line 55:

<comment>`test_utc_now_multiple_calls` never asserts the two timestamps differ, so it provides no coverage for the scenario it claims to check.</comment>

<file context>
@@ -0,0 +1,449 @@
+            or before &lt;= result_dt &lt;= after
+        )
+
+    def test_utc_now_multiple_calls(self):
+        &quot;&quot;&quot;Test that multiple calls to utc_now return different values.&quot;&quot;&quot;
+        result1 = utc_now()
</file context>
Fix with Cubic

@hayescode hayescode added this pull request to the merge queue Nov 20, 2025
Merged via the queue into Chainlit:main with commit 535bed7 Nov 20, 2025
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Pertains to the Python backend. size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants