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

feat: ensure user home dirs are expanded in paths #7

Merged
merged 2 commits into from
Nov 14, 2024

Conversation

clintval
Copy link
Owner

@clintval clintval commented Nov 13, 2024

Summary by CodeRabbit

  • New Features

    • Added tests for handling old-style optional types in both CSV reading and writing processes.
  • Bug Fixes

    • Updated file handling in the CSV reader and writer to correctly interpret user directory shortcuts, enhancing file accessibility.
  • Tests

    • Introduced test_reader_can_read_old_style_optional_types to validate reading optional types.
    • Introduced test_writer_can_write_old_style_optional_types to validate writing optional types.
    • Enhanced type handling capabilities with the new is_union function.

Copy link

coderabbitai bot commented Nov 13, 2024

Walkthrough

This pull request introduces new test functions in the tests/test_reader.py and tests/test_writer.py files to verify the handling of old-style optional types in dataclasses by the CsvRecordReader and CsvRecordWriter. Additionally, it modifies the from_path methods in the DelimitedRecordReader and DelimitedRecordWriter classes to use expanduser() for handling file paths with user directory shortcuts. The existing tests remain unchanged, ensuring that the overall functionality is preserved.

Changes

File Path Change Summary
tests/test_reader.py - Added test_reader_can_read_old_style_optional_types to test CsvRecordReader with optional types.
- Imported Optional from typing.
tests/test_writer.py - Added test_writer_can_write_old_style_optional_types to test CsvRecordWriter with optional types.
- Imported Optional from typing.
typeline/_reader.py - Modified from_path to use expanduser() for file path handling.
- Updated _decode to use is_union for union type checks.
- Adjusted handling of empty strings and "null".
typeline/_writer.py - Modified from_path to use expanduser() for file path handling.
typeline/init.py - Added is_union to the module's public interface.
typeline/_data_types.py - Introduced is_union function to check if a type is a union.

Possibly related PRs

  • feat: add dataclass delimited data readers/writers #1: The changes in this PR involve adding a new test function for the CsvRecordWriter that handles old-style optional types, which is directly related to the new test function in the main PR that verifies the CsvRecordReader's handling of old-style optional types.

  • feat: remove static methods and make state-based #3: This PR modifies the test suite for CSV and TSV readers, enhancing error handling and adding tests for various edge cases, which aligns with the main PR's focus on testing the CsvRecordReader for optional types.

  • feat: refactor to a cleaner API #5: This PR refactors the parameters of the from_path methods in the CsvStructReader and TsvStructReader, which are relevant to the functionality being tested in the main PR regarding reading CSV data into dataclasses.

  • feat: use msgspec JSON encoder #6: This PR introduces modifications to the test cases for CSV and TSV record readers, including enhancements to error handling and custom decoding, which are relevant to the main PR's focus on testing the CsvRecordReader.

🐇 In the fields where data flows,
Old-style types in CSVs grow.
With tests that check both read and write,
Our records shine, all clear and bright!
Expand those paths, let shortcuts play,
For rabbits hop in a data ballet! 🥕✨


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 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

@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

🧹 Outside diff range and nitpick comments (4)
typeline/_writer.py (1)

Line range hint 119-127: Document the path expansion behavior.

Consider adding a note in the docstring about the automatic expansion of user home directories (e.g., ~).

     """Construct a delimited data writer from a file path.

     Args:
         path: the path to the file to write delimited data to.
+            Supports expansion of user home directory (e.g., "~/data/file.csv").
         record_type: the type of the object we will be writing.
     """
typeline/_reader.py (2)

219-219: LGTM! Good addition of home directory expansion.

The addition of expanduser() is a good practice that makes the API more user-friendly by supporting common path shortcuts like ~.

Consider also supporting environment variables in paths using expandvars():

-        handle = Path(path).expanduser().open("r")
+        handle = Path(path).expanduser().expandvars().open("r")

Line range hint 208-220: Document the path expansion behavior.

The docstring should mention that the path supports user home directory expansion.

Add this information to the path parameter description:

         Args:
-            path: the path to the file to read delimited data from.
+            path: the path to the file to read delimited data from. Supports user home directory expansion (e.g., '~').
             record_type: the type of the object we will be writing.
             header: whether we expect the first line to be a header or not.
             comment_prefixes: skip lines that have any of these string prefixes.
tests/test_reader.py (1)

289-304: LGTM! Consider adding more edge cases

The test effectively verifies the handling of old-style optional types with good coverage of regular values, null values, and nested structures.

Consider enhancing the test coverage with additional cases:

  1. Invalid data (e.g., string where int is expected)
  2. Empty string vs null handling
  3. Type hints for the function parameters (tmp_path: Path)

Here's a suggested enhancement:

-def test_reader_can_read_old_style_optional_types(tmp_path: Path) -> None:
+def test_reader_can_read_old_style_optional_types(tmp_path: Path) -> None:
     """Test that the reader can read old style optional types."""
 
     @dataclass
     class MyMetric:
         field1: float
         field2: Optional[int]
         field3: Optional[list[int]]
 
-    (tmp_path / "test.txt").write_text("0.1,1,null\n0.2,null,'[1,2,3]'\n")
+    (tmp_path / "test.txt").write_text(
+        "0.1,1,null\n"
+        "0.2,null,'[1,2,3]'\n"
+        "0.3,,null\n"  # Empty string case
+        "0.4,invalid,null\n"  # Invalid int case
+    )
 
     with CsvRecordReader.from_path(tmp_path / "test.txt", MyMetric, header=False) as reader:
-        record1, record2 = list(iter(reader))
+        records = list(iter(reader))
+        assert len(records) == 2  # Should only get valid records
 
-    assert record1 == MyMetric(0.1, 1, None)
-    assert record2 == MyMetric(0.2, None, [1, 2, 3])
+        assert records[0] == MyMetric(0.1, 1, None)
+        assert records[1] == MyMetric(0.2, None, [1, 2, 3])
+
+        # Verify invalid records raise appropriate exceptions
+        with pytest.raises(ValidationError):
+            list(CsvRecordReader.from_path(
+                tmp_path / "test.txt",
+                MyMetric,
+                header=False,
+                skip_errors=False
+            ))
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 373b417 and 3299a49.

📒 Files selected for processing (4)
  • tests/test_reader.py (2 hunks)
  • tests/test_writer.py (2 hunks)
  • typeline/_reader.py (1 hunks)
  • typeline/_writer.py (1 hunks)
🔇 Additional comments (4)
tests/test_writer.py (2)

4-4: LGTM!

The Optional import is correctly placed with other typing imports and is necessary for the new test function.


140-153: LGTM! Well-structured test implementation

The test is well-implemented with:

  • Clear test cases covering both None and non-None scenarios for different Optional types
  • Proper assertions verifying the CSV output format
  • Good documentation
typeline/_writer.py (1)

128-128: LGTM! Verify consistent behavior with reader.

The addition of expanduser() correctly implements user home directory expansion, matching the behavior in DelimitedRecordReader.

Let's verify the consistent implementation across reader/writer:

✅ Verification successful

Path expansion implementation verified as consistent

The verification confirms that both DelimitedRecordReader and DelimitedRecordWriter consistently use expanduser() for handling user home directory paths:

  • typeline/_reader.py: Path(path).expanduser().open("r")
  • typeline/_writer.py: Path(path).expanduser().open("w")
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent path handling between reader and writer
# Expected: Both should use expanduser() in from_path method

# Check for expanduser usage in reader and writer
rg "expanduser\(\)" --type py

Length of output: 191

tests/test_reader.py (1)

4-4: LGTM!

The Optional import is correctly placed with other typing imports and is necessary for the new test function.

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: 0

🧹 Outside diff range and nitpick comments (1)
typeline/_data_types.py (1)

37-39: Enhance the docstring with more details

The implementation looks good and properly handles both old and new-style unions. Consider enhancing the docstring with:

  • Parameter description
  • Return value description
  • Examples of usage
 def is_union(_type: type | str | Any) -> bool:
-    """Return if this type is a union of types or not."""
+    """Check if the given type is a union of types.
+
+    Args:
+        _type: The type to check. Can be a type object, string representation
+              of a type, or Any.
+
+    Returns:
+        bool: True if the type is a union (either UnionType or _UnionGenericAlias),
+              False otherwise.
+
+    Examples:
+        >>> is_union(int | str)
+        True
+        >>> is_union(int)
+        False
+    """
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3299a49 and 1311054.

📒 Files selected for processing (4)
  • tests/test_reader.py (2 hunks)
  • typeline/__init__.py (2 hunks)
  • typeline/_data_types.py (2 hunks)
  • typeline/_reader.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/test_reader.py
  • typeline/_reader.py
🔇 Additional comments (3)
typeline/__init__.py (2)

3-3: LGTM! Import statement follows consistent style

The new import follows the established pattern and is properly grouped with related type-handling imports.


20-20: Verify the usage of newly exposed is_union function

The addition to __all__ properly exposes the function. Let's verify its usage pattern across the codebase to ensure it's being used as intended.

typeline/_data_types.py (1)

8-10: Verify the necessity of using internal typing API

The use of _UnionGenericAlias (an internal typing API) might make the code brittle across Python versions. Consider if there's a more stable public API alternative.

@clintval clintval merged commit 02bb0ae into main Nov 14, 2024
7 checks passed
@clintval clintval deleted the cv_expanduser_tests branch November 14, 2024 16:59
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.

1 participant