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

Improving Test coverage #365

Merged
merged 18 commits into from
Oct 19, 2024

Conversation

apurvabanka
Copy link
Contributor

@apurvabanka apurvabanka commented Oct 12, 2024

Name Stmts Miss Branch BrPart Cover
fastkml/init.py 27 0 0 0 100%
fastkml/about.py 1 0 0 0 100%
fastkml/atom.py 65 0 0 0 100%
fastkml/base.py 75 0 14 0 100%
fastkml/config.py 23 0 4 0 100%
fastkml/containers.py 60 0 4 0 100%
fastkml/data.py 110 4 2 0 96%
fastkml/enums.py 81 0 30 0 100%
fastkml/exceptions.py 5 0 0 0 100%
fastkml/features.py 141 3 4 0 98%
fastkml/geometry.py 268 1 68 0 99%
fastkml/gx.py 139 2 52 0 99%
fastkml/helpers.py 184 0 72 0 100%
fastkml/kml.py 69 0 10 1 99%
fastkml/kml_base.py 22 0 0 0 100%
fastkml/links.py 46 0 0 0 100%
fastkml/mixins.py 18 0 0 0 100%
fastkml/overlays.py 158 6 0 0 96%
fastkml/registry.py 45 0 8 2 96%
fastkml/styles.py 196 4 4 0 98%
fastkml/times.py 103 3 30 6 93%
fastkml/types.py 13 0 0 0 100%
fastkml/views.py 125 5 0 0 96%

@cleder Coverage Report

Related Issue #352

Summary by Sourcery

Enhance test coverage by adding new test cases across multiple modules, focusing on error handling and utility functions.

Tests:

  • Add new test cases to improve coverage for various modules, including containers, kml, geometries, gx, styles, overlays, and views.
  • Introduce tests for handling GeometryError exceptions in multiple geometry-related modules.
  • Add tests for helper functions in a new helper_test.py file to ensure proper functionality of utility methods.
  • Add tests for geometry functions in a new functions_test.py file to validate error handling and coordinate processing.

Summary by CodeRabbit

  • New Features

    • Enhanced test coverage for the PhotoOverlay class, ensuring correct initialization and attribute validation.
    • Introduced new tests for KML container functionalities, including feature appending and style URL retrieval.
    • Added tests for error handling in boundary geometry classes.
    • Established a comprehensive testing framework for geometry-related functions, addressing invalid geometries.
    • Introduced a new test for the Track class to validate the etree_element method.
    • Improved assertions in the MultiTrack and Region tests for better validation of object states.
  • Bug Fixes

    • Corrected assertions in various tests to ensure accurate validation of attributes.
  • Documentation

    • Updated comments for clarity in test methods related to the Region class.

Copy link

semanticdiff-com bot commented Oct 12, 2024

Review changes with SemanticDiff.

Analyzed 13 of 13 files.

Overall, the semantic diff is 1% smaller than the GitHub diff.

Filename Status
✔️ tests/containers_test.py Analyzed
✔️ tests/gx_test.py Analyzed
✔️ tests/helper_test.py Analyzed
✔️ tests/kml_test.py Analyzed
✔️ tests/overlays_test.py Analyzed
✔️ tests/styles_test.py Analyzed
✔️ tests/views_test.py Analyzed
✔️ tests/geometries/boundaries_test.py Analyzed
✔️ tests/geometries/functions_test.py Analyzed
✔️ tests/geometries/linestring_test.py 0.56% smaller
✔️ tests/geometries/multigeometry_test.py 0.22% smaller
✔️ tests/geometries/point_test.py 0.23% smaller
✔️ tests/geometries/polygon_test.py Analyzed

Copy link
Contributor

sourcery-ai bot commented Oct 12, 2024

Reviewer's Guide by Sourcery

This pull request focuses on improving test coverage for the fastkml library. The changes include adding new test cases, expanding existing tests, and introducing error handling scenarios across various modules. The modifications aim to increase the overall test coverage and robustness of the library.

No diagrams generated as the changes look simple and do not need a visual representation.

File-Level Changes

Change Details Files
Added new test cases for container and document classes
  • Implemented tests for container creation and feature appending
  • Added a test for document container style URL retrieval
  • Introduced error handling test for appending a container to itself
tests/containers_test.py
Enhanced KML parsing and element creation tests
  • Added test for KML etree element creation
  • Implemented test for KML append method with error handling
  • Created a new test class for parsing KML with None namespace
tests/kml_test.py
Expanded geometry-related tests
  • Added tests for geometry error handling in boundaries, point, linestring, multigeometry, and polygon classes
  • Implemented new test cases for Track and MultiTrack classes
  • Enhanced existing tests with additional assertions
tests/geometries/boundaries_test.py
tests/geometries/point_test.py
tests/gx_test.py
tests/geometries/linestring_test.py
tests/geometries/multigeometry_test.py
tests/geometries/polygon_test.py
Added tests for styles, overlays, and views
  • Implemented test for StyleMap none case
  • Added assertions for PhotoOverlay and Region boolean checks
  • Enhanced existing tests with additional assertions
tests/styles_test.py
tests/overlays_test.py
tests/views_test.py
Created new test files for helpers and geometry functions
  • Implemented tests for various helper functions including attribute and subelement operations
  • Added tests for geometry-related functions such as error handling and coordinate processing
tests/helper_test.py
tests/geometries/functions_test.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

coderabbitai bot commented Oct 12, 2024

Walkthrough

This pull request introduces new test methods and assertions in the fastkml library's test suite. It enhances the testing capabilities for KML container functionalities by adding tests for container creation, feature appending, and error handling in geometry classes. Additionally, existing tests in various classes are improved with new assertions to verify the correct initialization and behavior of various attributes, thereby improving overall test coverage.

Changes

File Change Summary
tests/containers_test.py Added three methods to TestStdLibrary: test_container_creation, test_container_feature_append, and test_document_container_get_style_url.
tests/geometries/boundaries_test.py Added two methods to TestBoundaries: test_outer_boundary_geometry_error and test_inner_boundary_geometry_error; corrected spelling in method names.
tests/geometries/functions_test.py Introduced new test suite TestGeometryFunctions with methods for handling invalid geometries and validating coordinate subelements.
tests/gx_test.py Added test_track_etree_element to validate etree_element method; updated assertions in test_from_multilinestring.
tests/overlays_test.py Enhanced test_create_photo_overlay_with_all_optional_parameters with assertions for view_volume and image_pyramid; updated test_read_photo_overlay for comprehensive attribute validation.
tests/views_test.py Added assertion in test_region_with_all_optional_parameters to check truthiness of region; corrected indentation in assertions.

Possibly related PRs

  • Fix inner boundaries for polygon #355 #356: The changes in this PR involve modifications to the InnerBoundaryIs and Polygon classes, which are related to the handling of geometries. The main PR enhances tests for KML container functionalities, which may include interactions with these geometry classes.
  • 216 add output verbosity #360: This PR introduces verbosity control for XML serialization and modifies various geometry classes, including Polygon. The main PR's focus on testing KML container functionalities may intersect with the changes made in this PR regarding geometry handling and serialization.

Suggested labels

Review effort [1-5]: 4

Poem

🐇 Hopping through the code so bright,
With tests that shine and errors in sight.
New methods and checks, all put to the test,
Ensuring our KML functions are truly the best!
So let’s celebrate with a joyful cheer,
For robust coverage is finally here! 🎉


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.

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.

@pep8speaks
Copy link

pep8speaks commented Oct 12, 2024

Hello @apurvabanka! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

Line 36:13: E124 closing bracket does not match visual indentation

Comment last updated at 2024-10-13 18:46:43 UTC

Copy link

what-the-diff bot commented Oct 12, 2024

PR Summary

  • Enhancement of Testing for Container Functionalities
    • Introduction of tests to authenticate the process of creation and appending features to containers.
  • Additions to Boundary Testing
    • Inclusion of specific tests designed to handle errors related to geometrical boundaries.
  • New File Generation for Testing Geometry Functions
    • Execution of tests on various functions aimed at handling and coordinating sub-elements of invalid geometrical errors.
  • Implementation of Geometry Error Testing Across Files
    • Enrichment of error handling through introduction of tests in multiple geometry-related files to validate and manage Geometry Errors.
  • Broadening of Test Coverage for KML Parsing
    • Implementation of new tests for creation and validation of KML elements, even when dealing with empty or incorrect references.
  • Expansion of Helper Features Testing Function
    • Induction of functionalities to test helper methods, inclusive of various attribute checks.
  • Assertion of New Attributes' Authenticity
    • Verification process conducted on newly added attributes of overlay and region objects.
  • Improvement of Style Map Testing
    • Addition of scenarios to check the behavior when there is an absence of a style map.

Copy link

qodo-merge-pro bot commented Oct 12, 2024

PR Reviewer Guide 🔍

(Review updated until commit 589a00f)

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Possible Bug
The test_container_feature_append function is appending a feature to the container but not verifying if it was actually added. Consider adding an assertion to check if the feature was successfully appended.

Code Smell
The test_coordinates_subelement_getattr function is not actually testing the getattr functionality. It's calling the coordinates_subelement function with obj=None, which doesn't test the getattr behavior. Consider modifying this test to actually test the getattr functionality.

Incomplete Test
The test_attribute_enum_kwarg function is not fully testing the attribute_enum_kwarg function. It only tests the case where the attribute is None. Consider adding more test cases to cover different scenarios, such as when a valid enum value is provided.

Copy link

Persistent review updated to latest commit 589a00f

Copy link

Preparing review...

1 similar comment
Copy link

Preparing review...

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

👍 Looks good to me! Reviewed everything up to 589a00f in 44 seconds

More details
  • Looked at 565 lines of code in 13 files
  • Skipped 0 files when reviewing.
  • Skipped posting 8 drafted comments based on config settings.
1. tests/containers_test.py:69
  • Draft comment:
    Consider using consistent naming conventions for test functions. For example, use underscores to separate words in function names, such as test_container_creation and test_container_feature_append.
  • Reason this comment was not posted:
    Confidence changes required: 50%
    The test function names are inconsistent in their use of underscores. Some functions use underscores to separate words, while others do not. Consistent naming conventions improve readability and maintainability.
2. tests/geometries/boundaries_test.py:46
  • Draft comment:
    Consider using consistent naming conventions for test functions. For example, use underscores to separate words in function names, such as test_outer_boundary_geometry_error.
  • Reason this comment was not posted:
    Confidence changes required: 50%
    The test function names are inconsistent in their use of underscores. Some functions use underscores to separate words, while others do not. Consistent naming conventions improve readability and maintainability.
3. tests/geometries/functions_test.py:24
  • Draft comment:
    Consider using consistent naming conventions for test functions. For example, use underscores to separate words in function names, such as test_coordinates_subelement_exception.
  • Reason this comment was not posted:
    Confidence changes required: 50%
    The test function names are inconsistent in their use of underscores. Some functions use underscores to separate words, while others do not. Consistent naming conventions improve readability and maintainability.
4. tests/geometries/linestring_test.py:41
  • Draft comment:
    Consider using consistent naming conventions for test functions. For example, use underscores to separate words in function names, such as test_geometry_error.
  • Reason this comment was not posted:
    Confidence changes required: 50%
    The test function names are inconsistent in their use of underscores. Some functions use underscores to separate words, while others do not. Consistent naming conventions improve readability and maintainability.
5. tests/geometries/multigeometry_test.py:294
  • Draft comment:
    Consider using consistent naming conventions for test functions. For example, use underscores to separate words in function names, such as test_geometry_error.
  • Reason this comment was not posted:
    Confidence changes required: 50%
    The test function names are inconsistent in their use of underscores. Some functions use underscores to separate words, while others do not. Consistent naming conventions improve readability and maintainability.
6. tests/geometries/point_test.py:43
  • Draft comment:
    Consider using consistent naming conventions for test functions. For example, use underscores to separate words in function names, such as test_geometry_error.
  • Reason this comment was not posted:
    Confidence changes required: 50%
    The test function names are inconsistent in their use of underscores. Some functions use underscores to separate words, while others do not. Consistent naming conventions improve readability and maintainability.
7. tests/geometries/polygon_test.py:132
  • Draft comment:
    Consider using consistent naming conventions for test functions. For example, use underscores to separate words in function names, such as test_geometry_error.
  • Reason this comment was not posted:
    Confidence changes required: 50%
    The test function names are inconsistent in their use of underscores. Some functions use underscores to separate words, while others do not. Consistent naming conventions improve readability and maintainability.
8. tests/gx_test.py:54
  • Draft comment:
    Consider using consistent naming conventions for test functions. For example, use underscores to separate words in function names, such as test_track_etree_element.
  • Reason this comment was not posted:
    Confidence changes required: 50%
    The test function names are inconsistent in their use of underscores. Some functions use underscores to separate words, while others do not. Consistent naming conventions improve readability and maintainability.

Workflow ID: wflow_VNRZxhmsnbRt51Mj


You can customize Ellipsis with 👍 / 👎 feedback, review rules, user-specific overrides, quiet mode, and more.

Copy link

qodo-merge-pro bot commented Oct 12, 2024

PR Code Suggestions ✨

Latest suggestions up to 589a00f
Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Score
Enhancement
Use pytest.mark.parametrize to test multiple scenarios in a single test function

Use pytest.mark.parametrize to test handle_invalid_geometry_error with both True and
False strict values in a single test function, reducing code duplication.

tests/geometries/functions_test.py [14-22]

+@pytest.mark.parametrize("strict,expected", [
+    (True, pytest.raises(KMLParseError)),
+    (False, None)
+])
 @patch('fastkml.config.etree.tostring')
-def test_handle_invalid_geometry_error_true(self, mock_to_string) -> None:
+def test_handle_invalid_geometry_error(self, mock_to_string, strict, expected) -> None:
     mock_element = Mock()
-    with pytest.raises(KMLParseError):
-        handle_invalid_geometry_error(error=ValueError, element=mock_element, strict=True)
+    if expected is None:
+        assert handle_invalid_geometry_error(error=ValueError, element=mock_element, strict=strict) is None
+    else:
+        with expected:
+            handle_invalid_geometry_error(error=ValueError, element=mock_element, strict=strict)
 
-@patch('fastkml.config.etree.tostring')
-def test_handle_invalid_geometry_error_false(self, mock_to_string) -> None:
-    mock_element = Mock()
-    assert handle_invalid_geometry_error(error=ValueError, element=mock_element, strict=False) is None
-
  • Apply this suggestion
Suggestion importance[1-10]: 8

Why: Using pytest.mark.parametrize to combine tests for different strict values into a single function is an effective way to reduce duplication and improve test clarity. This suggestion is well-aligned with best practices in testing.

8
Use parametrized tests to reduce duplication in similar test functions

Use pytest.mark.parametrize to test multiple helper functions with similar
structures in a single parametrized test, reducing code duplication and improving
test coverage.

tests/helper_test.py [57-87]

-def test_subelement_int_kwarg(self):
+@pytest.mark.parametrize("func", [
+    subelement_int_kwarg,
+    subelement_float_kwarg
+])
+def test_subelement_kwarg(self, func):
     node = Node()
     node.text = None
     element = Mock()
     element.find.return_value = node
-    res = subelement_int_kwarg(
-            element=element,
-            ns="ns",
-            name_spaces="name",
-            node_name="node",
-            kwarg="kwarg",
-            classes=None,
-            strict=False
-        )
+    res = func(
+        element=element,
+        ns="ns",
+        name_spaces="name",
+        node_name="node",
+        kwarg="kwarg",
+        classes=None,
+        strict=False
+    )
     assert res == {}
 
-def test_subelement_float_kwarg(self):
-    node = Node()
-    node.text = None
-    element = Mock()
-    element.find.return_value = node
-    res = subelement_float_kwarg(
-            element=element,
-            ns="ns",
-            name_spaces="name",
-            node_name="node",
-            kwarg="kwarg",
-            classes=None,
-            strict=False
-        )
-    assert res == {}
-
  • Apply this suggestion
Suggestion importance[1-10]: 8

Why: The suggestion to use pytest.mark.parametrize for similar helper function tests is beneficial as it reduces code duplication and enhances test coverage. This approach is efficient and maintains clarity in testing.

8
Use pytest fixtures to reduce code duplication in tests

Use pytest.fixture to create a reusable _Container object for multiple tests,
reducing code duplication and improving test maintainability.

tests/containers_test.py [69-88]

-def test_container_creation(self)->None:
-    container = containers._Container(
+@pytest.fixture
+def container():
+    return containers._Container(
         ns="ns",
         id="id",
         target_id="target_id",
         name="name"
     )
+
+def test_container_creation(self, container)->None:
     assert container.ns == "ns"
     assert container.name == "name"
-def test_container_feature_append(self)->None:
-    container = containers._Container(
-        ns="ns",
-        id="id",
-        target_id="target_id",
-        name="name"
-    )
+
+def test_container_feature_append(self, container)->None:
     feature = features._Feature(name="new_feature")
     assert container.append(feature) is None
     with pytest.raises(ValueError):
         container.append(container)
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why: The suggestion to use pytest fixtures is valid as it reduces code duplication and improves maintainability by creating a reusable _Container object. This change enhances the test structure without affecting functionality.

7
Best practice
Improve exception testing by using context manager and checking exception message

Use a context manager with pytest.raises to ensure that the exception is raised in
the correct part of the code, providing better test isolation and error reporting.

tests/kml_test.py [189-195]

 def test_kml_append(self) -> None:
     empty_placemark = KMLFILEDIR / "emptyPlacemarkWithoutId.xml"
 
     doc = kml.KML.parse(empty_placemark)
 
-    with pytest.raises(ValueError):
+    with pytest.raises(ValueError) as excinfo:
         doc.append(doc)
+    assert "Cannot append" in str(excinfo.value)
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why: The suggestion to use a context manager with pytest.raises and check the exception message provides better test isolation and error reporting. It is a good practice to ensure the exception is raised as expected.

7

💡 Need additional feedback ? start a PR chat


Previous suggestions

✅ Suggestions up to commit 589a00f
CategorySuggestion                                                                                                                                    Score
Enhancement
Refactor similar test functions using parametrization to reduce code duplication and improve maintainability

Use parametrized tests to reduce code duplication and improve test coverage for
similar functions.

tests/helper_test.py [57-87]

-def test_subelement_int_kwarg(self):
+@pytest.mark.parametrize("func", [subelement_int_kwarg, subelement_float_kwarg])
+def test_subelement_kwarg(self, func):
     node = Node()
     node.text = None
     element = Mock()
     element.find.return_value = node
-    res = subelement_int_kwarg(
-            element=element,
-            ns="ns",
-            name_spaces="name",
-            node_name="node",
-            kwarg="kwarg",
-            classes=None,
-            strict=False
-        )
+    res = func(
+        element=element,
+        ns="ns",
+        name_spaces="name",
+        node_name="node",
+        kwarg="kwarg",
+        classes=None,
+        strict=False
+    )
     assert res == {}
 
-def test_subelement_float_kwarg(self):
-    node = Node()
-    node.text = None
-    element = Mock()
-    element.find.return_value = node
-    res = subelement_float_kwarg(
-            element=element,
-            ns="ns",
-            name_spaces="name",
-            node_name="node",
-            kwarg="kwarg",
-            classes=None,
-            strict=False
-        )
-    assert res == {}
-
Suggestion importance[1-10]: 8

Why: This suggestion effectively reduces code duplication and enhances maintainability by using parameterized tests, which is a good practice for testing similar functionalities.

8
Improve the assertion for comparing etree elements by using a more specific comparison method

Use a more specific assertion to check the equality of the etree elements instead of
using the default equality check.

tests/kml_test.py [187]

-assert doc.etree_element() == config.etree.Element( f"{doc.ns}{doc.get_tag_name()}", nsmap={None: doc.ns[1:-1]},)
+from lxml.etree import tostring
+assert tostring(doc.etree_element()) == tostring(config.etree.Element(f"{doc.ns}{doc.get_tag_name()}", nsmap={None: doc.ns[1:-1]}))
Suggestion importance[1-10]: 6

Why: Using tostring for comparing etree elements is more precise than the default equality check, improving the accuracy of the test assertions.

6
Best practice
✅ Improve test readability and specificity by using a context manager with an expected error message
Suggestion Impact:The commit added an expected error message to the pytest.raises context manager, improving test readability and specificity.

code diff:

+        container.append(feature)
+        assert feature in container.features
+        with pytest.raises(ValueError, match="Cannot append self"):
             container.append(container)

Use a context manager for the pytest.raises() assertion to make the test more
explicit and easier to read.

tests/containers_test.py [87-88]

-with pytest.raises(ValueError):
+with pytest.raises(ValueError, match="Cannot append a container to itself"):
     container.append(container)
Suggestion importance[1-10]: 7

Why: The suggestion improves test readability and specificity by adding an expected error message to the pytest.raises context manager, which makes the test more explicit and informative.

7
Use more specific assertion methods for comparing with None to improve test readability and error reporting

Use assertIsNone() instead of comparing directly to None for better readability and
more informative error messages.

tests/styles_test.py [616-617]

-assert sm.normal is None
-assert sm.highlight is None
+self.assertIsNone(sm.normal)
+self.assertIsNone(sm.highlight)
Suggestion importance[1-10]: 5

Why: The suggestion to use assertIsNone improves readability and provides more informative error messages, although the improvement is minor in this context.

5

Copy link
Contributor

@sourcery-ai sourcery-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.

Hey @apurvabanka - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟡 Testing: 3 issues found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 78 to 88
def test_container_feature_append(self)->None:
container = containers._Container(
ns="ns",
id="id",
target_id="target_id",
name="name"
)
feature = features._Feature(name="new_feature")
assert container.append(feature) is None
with pytest.raises(ValueError):
container.append(container)
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Good test for appending features and handling invalid appends

This test covers both successful append and the error case. Consider adding an assertion to check if the feature was actually appended to the container.

Suggested change
def test_container_feature_append(self)->None:
container = containers._Container(
ns="ns",
id="id",
target_id="target_id",
name="name"
)
feature = features._Feature(name="new_feature")
assert container.append(feature) is None
with pytest.raises(ValueError):
container.append(container)
def test_container_feature_append(self) -> None:
container = containers._Container(
ns="ns", id="id", target_id="target_id", name="name"
)
feature = features._Feature(name="new_feature")
container.append(feature)
assert feature in container.features
with pytest.raises(ValueError):
container.append(container)

Comment on lines 46 to 55
def test_outer_boundry_geometry_error(self) -> None:
"""Test GeometryError."""
p = geo.Point(1, 2)
coords = ((1, 2), (2, 0), (0, 0), (1, 2))

with pytest.raises(GeometryError):
OuterBoundaryIs(
kml_geometry=LinearRing(kml_coordinates=Coordinates(coords=coords)),
geometry=p
)
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Good test for GeometryError in OuterBoundaryIs

This test effectively checks for the GeometryError. Consider adding a similar test for other geometry types to ensure consistent error handling.

Suggested change
def test_outer_boundry_geometry_error(self) -> None:
"""Test GeometryError."""
p = geo.Point(1, 2)
coords = ((1, 2), (2, 0), (0, 0), (1, 2))
with pytest.raises(GeometryError):
OuterBoundaryIs(
kml_geometry=LinearRing(kml_coordinates=Coordinates(coords=coords)),
geometry=p
)
def test_outer_boundary_geometry_error(self) -> None:
"""Test GeometryError for different geometry types."""
geometries = [geo.Point(1, 2), geo.LineString([(0, 0), (1, 1)]), geo.Polygon([(0, 0), (1, 1), (1, 0)])]
coords = ((1, 2), (2, 0), (0, 0), (1, 2))
kml_geometry = LinearRing(kml_coordinates=Coordinates(coords=coords))
for geometry in geometries:
with pytest.raises(GeometryError):
OuterBoundaryIs(kml_geometry=kml_geometry, geometry=geometry)

Comment on lines 10 to 60
class TestGeometryFunctions(StdLibrary):
"""Test functions in Geometry"""

@patch('fastkml.config.etree.tostring')
def test_handle_invalid_geometry_error_true(self, mock_to_string) -> None:
mock_element = Mock()
with pytest.raises(KMLParseError):
handle_invalid_geometry_error(error=ValueError, element=mock_element, strict=True)

@patch('fastkml.config.etree.tostring')
def test_handle_invalid_geometry_error_false(self, mock_to_string) -> None:
mock_element = Mock()
assert handle_invalid_geometry_error(error=ValueError, element=mock_element, strict=False) is None

def test_coordinates_subelement_exception(self) -> None:
obj = Mock()
setattr(obj, 'coordinates', [(1.123456, 2.654321, 3.111111, 4.222222)]) # Invalid 4D coordinates

element = Mock()

precision = None
attr_name = 'coordinates'

with pytest.raises(KMLWriteError):
coordinates_subelement(
obj=obj,
attr_name=attr_name,
node_name=None,
element=element,
precision=precision,
verbosity=None,
default=None
)
def test_coordinates_subelement_getattr(self) -> None:
obj = Mock()
setattr(obj, 'coordinates', [(1.123456, 2.654321), (3.123456, 4.654321)])

element = Mock()

precision = 4
attr_name = 'coordinates'

assert coordinates_subelement(
obj=None,
attr_name=attr_name,
node_name=None,
element=element,
precision=precision,
verbosity=None,
default=None
) is None
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Good addition of tests for geometry functions

These tests cover important geometry functions. Consider adding more test cases for different types of geometries and edge cases to ensure comprehensive coverage.

class TestGeometryFunctions(StdLibrary):
    """Test functions in Geometry"""

    @pytest.mark.parametrize("strict, expected", [(True, pytest.raises(KMLParseError)), (False, None)])
    @patch('fastkml.config.etree.tostring')
    def test_handle_invalid_geometry_error(self, mock_to_string, strict, expected):
        mock_element = Mock()
        with expected:
            result = handle_invalid_geometry_error(error=ValueError, element=mock_element, strict=strict)
            if not strict:
                assert result is None

    @pytest.mark.parametrize("coordinates, precision, expected", [
        ([(1.123456, 2.654321, 3.111111, 4.222222)], None, pytest.raises(KMLWriteError)),
        ([(1.123456, 2.654321), (3.123456, 4.654321)], 4, None)
    ])
    def test_coordinates_subelement(self, coordinates, precision, expected):
        obj = Mock(coordinates=coordinates)
        element = Mock()
        with expected:
            result = coordinates_subelement(obj, 'coordinates', None, element, precision, None, None)
            if expected is None:
                assert result is None

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

🧹 Outside diff range and nitpick comments (23)
tests/geometries/functions_test.py (4)

1-12: Add a module-level docstring

The imports and class declaration look good. However, it's recommended to add a module-level docstring to provide an overview of the test suite's purpose.

Consider adding a docstring at the beginning of the file, like this:

"""
Unit tests for geometry-related functions in the fastkml library.

This module contains test cases for various geometry functions, including
error handling and coordinate processing.
"""
🧰 Tools
🪛 Ruff

1-1: Missing docstring in public module

(D100)


8-8: First line should end with a period

Add period

(D400)


8-8: First line should end with a period, question mark, or exclamation point

Add closing punctuation

(D415)


11-11: Missing type annotation for function argument mock_to_string

(ANN001)


11-11: Unused method argument: mock_to_string

(ARG002)


13-17: LGTM with a minor suggestion

The test case correctly verifies the behavior of handle_invalid_geometry_error when strict=True. Good use of patch for isolation.

Consider removing the unused mock_to_string argument or use it in the test if needed:

@patch('fastkml.config.etree.tostring')
def test_handle_invalid_geometry_error_true(self, _) -> None:
    # Rest of the test remains the same
🧰 Tools
🪛 Ruff

14-14: Line too long (94 > 88)

(E501)


17-17: Missing type annotation for function argument mock_to_string

(ANN001)


17-17: Unused method argument: mock_to_string

(ARG002)


19-22: LGTM with the same minor suggestion

This test case correctly verifies the behavior of handle_invalid_geometry_error when strict=False. The consistency in using patch is good.

As with the previous test, consider removing the unused mock_to_string argument:

@patch('fastkml.config.etree.tostring')
def test_handle_invalid_geometry_error_false(self, _) -> None:
    # Rest of the test remains the same
🧰 Tools
🪛 Ruff

19-19: Line too long (106 > 88)

(E501)


24-42: LGTM with a suggestion for improved readability

This test case effectively verifies the behavior of coordinates_subelement when given invalid 4D coordinates. Good job on covering this important edge case.

To improve readability, consider using a dictionary for the function arguments:

def test_coordinates_subelement_exception(self) -> None:
    obj = Mock()
    setattr(obj, 'coordinates', [(1.123456, 2.654321, 3.111111, 4.222222)])  # Invalid 4D coordinates
    element = Mock()

    with pytest.raises(KMLWriteError):
        coordinates_subelement(
            **{
                'obj': obj,
                'attr_name': 'coordinates',
                'node_name': None,
                'element': element,
                'precision': None,
                'verbosity': None,
                'default': None
            }
        )

This approach makes it easier to add or modify arguments in the future.

tests/containers_test.py (3)

69-77: LGTM! Consider expanding attribute checks.

The test correctly verifies the creation of a _Container object and checks some of its attributes. However, to improve coverage, consider adding assertions for the id and target_id attributes as well.

Here's a suggested improvement:

def test_container_creation(self) -> None:
    container = containers._Container(
        ns="ns",
        id="id",
        target_id="target_id",
        name="name"
    )
    assert container.ns == "ns"
    assert container.name == "name"
    assert container.id == "id"
    assert container.target_id == "target_id"

78-88: LGTM! Consider specifying the error message in pytest.raises.

The test effectively verifies the behavior of appending features to a container and the error case of appending a container to itself. However, to make the test more robust and specific, consider adding an expected error message to the pytest.raises assertion.

Here's a suggested improvement:

def test_container_feature_append(self) -> None:
    container = containers._Container(
        ns="ns",
        id="id",
        target_id="target_id",
        name="name"
    )
    feature = features._Feature(name="new_feature")
    assert container.append(feature) is None
    with pytest.raises(ValueError, match="Cannot append a container to itself"):
        container.append(container)

This change addresses the static analysis hint by specifying an expected error message, making the test more precise.

🧰 Tools
🪛 Ruff

87-87: pytest.raises(ValueError) is too broad, set the match parameter or use a more specific exception

(PT011)


90-96: LGTM! Consider adding more test cases.

The test correctly verifies that get_style_by_url returns None for a given style URL. However, to improve coverage and robustness, consider adding more test cases:

  1. Test with a non-existent style URL.
  2. Test with a Document that has multiple styles.
  3. Test the behavior when no style URL is set.

Here's a suggested expansion of the test:

def test_document_container_get_style_url(self) -> None:
    document = containers.Document(
        name="Document",
        ns="ns",
        style_url="www.styleurl.com"
    )
    assert document.get_style_by_url(style_url="www.styleurl.com") is None
    assert document.get_style_by_url(style_url="non_existent_url") is None
    
    # Add a style to the document
    style = kml.Style(id="style1")
    document.append_style(style)
    assert document.get_style_by_url("#style1") == style
    
    # Test with no style URL set
    document_no_style = containers.Document(name="NoStyleDocument")
    assert document_no_style.get_style_by_url(style_url="any_url") is None

This expansion covers more scenarios and provides a more comprehensive test of the get_style_by_url method.

tests/helper_test.py (8)

1-14: Add a module-level docstring

Please add a module-level docstring to describe the purpose of this test file. This will improve code documentation and address the D100 linter warning.

Example:

"""
Unit tests for the helper functions in the fastkml library.

This module contains test cases for various helper functions,
including node_text, float_attribute, enum_attribute, and others.
"""

The import statements and helper class definitions look good.

🧰 Tools
🪛 Ruff

1-1: Missing docstring in public module

(D100)


2-2: Line too long (184 > 88)

(E501)


15-27: Add type annotation for mock_get_value parameter

The test method looks good and covers a valid scenario. To improve type hinting, please add a type annotation for the mock_get_value parameter:

def test_node_text(self, mock_get_value: Mock) -> None:

This will address the ANN001 linter warning and improve code readability.

🧰 Tools
🪛 Ruff

15-15: Missing type annotation for function argument mock_get_value

(ANN001)


29-41: Add type annotation for mock_get_value parameter

The test method for float_attribute is well-structured and tests a valid scenario. To improve type hinting, please add a type annotation for the mock_get_value parameter:

def test_float_attribute(self, mock_get_value: Mock) -> None:

This will address the ANN001 linter warning and improve code readability.

🧰 Tools
🪛 Ruff

29-29: Missing type annotation for function argument mock_get_value

(ANN001)


43-55: Add type annotation for mock_get_value parameter

The test method for enum_attribute is well-implemented and covers a valid scenario. To improve type hinting, please add a type annotation for the mock_get_value parameter:

def test_enum_attribute(self, mock_get_value: Mock) -> None:

This will address the ANN001 linter warning and improve code readability.

🧰 Tools
🪛 Ruff

43-43: Missing type annotation for function argument mock_get_value

(ANN001)


57-71: Add return type annotation

The test method for subelement_int_kwarg is well-structured and tests a valid scenario. To improve type hinting, please add a return type annotation to the method:

def test_subelement_int_kwarg(self) -> None:

This will address the ANN201 linter warning and improve code readability.


73-87: Add return type annotation

The test method for subelement_float_kwarg is well-implemented and covers a valid scenario. To improve type hinting, please add a return type annotation to the method:

def test_subelement_float_kwarg(self) -> None:

This will address the ANN201 linter warning and improve code readability.


89-103: Add type annotation for mock_handle_error parameter

The test method for attribute_float_kwarg is well-structured and tests a valid scenario. To improve type hinting, please add a type annotation for the mock_handle_error parameter:

def test_attribute_float_kwarg(self, mock_handle_error: Mock) -> None:

This will address the ANN001 linter warning and improve code readability.

🧰 Tools
🪛 Ruff

89-89: Missing type annotation for function argument mock_handle_error

(ANN001)


1-134: Overall: Well-structured and comprehensive test suite

This test file provides a thorough set of unit tests for the helper functions in the fastkml library. The tests are well-structured, use mocking effectively, and cover various scenarios. To further improve the code quality:

  1. Add a module-level docstring to describe the purpose of the test file.
  2. Add missing type annotations for mock parameters and return types as suggested in previous comments.
  3. Consider addressing the E501 (line too long) warning for line 2 by breaking it into multiple lines or using line continuation.

Great job on improving the test coverage for the FastKML project!

🧰 Tools
🪛 Ruff

1-1: Missing docstring in public module

(D100)


2-2: Line too long (184 > 88)

(E501)


15-15: Missing type annotation for function argument mock_get_value

(ANN001)


29-29: Missing type annotation for function argument mock_get_value

(ANN001)


43-43: Missing type annotation for function argument mock_get_value

(ANN001)


56-56: Missing return type annotation for public function test_subelement_int_kwarg

Add return type annotation: None

(ANN201)


72-72: Missing return type annotation for public function test_subelement_float_kwarg

Add return type annotation: None

(ANN201)


89-89: Missing type annotation for function argument mock_handle_error

(ANN001)

tests/geometries/linestring_test.py (1)

41-47: LGTM: New test method enhances error handling coverage.

The test_geometry_error method is a valuable addition that verifies the correct handling of incompatible geometry and coordinates in the LineString constructor.

Consider adding a more descriptive error message to the pytest.raises context manager for better test failure diagnostics:

with pytest.raises(GeometryError, match="Expected LineString geometry, got Point"):
    LineString(geometry=p, kml_coordinates=q)
tests/kml_test.py (3)

179-187: LGTM: Well-structured test for etree_element method. Consider adding type annotation.

The new test method test_kml_etree_element is well-structured and effectively tests the etree_element method of the KML object. The use of mocking is appropriate for isolating the test.

Consider adding a type annotation for the mock_etree parameter:

def test_kml_etree_element(self, mock_etree: MagicMock) -> None:

This will improve type checking and code readability.

🧰 Tools
🪛 Ruff

180-180: Missing type annotation for function argument mock_etree

(ANN001)


187-187: Line too long (120 > 88)

(E501)


189-195: LGTM: Good test for append method. Consider specifying the exception message.

The new test method test_kml_append effectively verifies that appending a KML document to itself raises a ValueError. This is a good edge case to test.

To make the test more robust, consider specifying the expected error message in the pytest.raises call:

with pytest.raises(ValueError, match="Cannot append a KML document to itself"):
    doc.append(doc)

This ensures that not only the correct exception type is raised but also that the error message is as expected.

🧰 Tools
🪛 Ruff

194-194: pytest.raises(ValueError) is too broad, set the match parameter or use a more specific exception

(PT011)


179-203: Great improvements to test coverage. Consider adding more edge cases.

The additions to this test file significantly enhance the test coverage for the KML class. New tests cover important aspects such as:

  1. Parsing with different namespaces
  2. etree element creation
  3. Append method behavior

These additions align well with the PR objective of improving test coverage.

To further improve the test suite, consider:

  1. Adding tests for other edge cases, such as parsing malformed KML files.
  2. Testing the KML class with larger, more complex KML structures.
  3. Adding performance tests for parsing large KML files.

These additions would make the test suite even more comprehensive and robust.

🧰 Tools
🪛 Ruff

180-180: Missing type annotation for function argument mock_etree

(ANN001)


187-187: Line too long (120 > 88)

(E501)


194-194: pytest.raises(ValueError) is too broad, set the match parameter or use a more specific exception

(PT011)

tests/geometries/point_test.py (1)

43-49: LGTM: New test method enhances error handling coverage.

The test_geometry_error method is a valuable addition to the test suite. It verifies that the Point class correctly raises a GeometryError when incompatible geometry and coordinate objects are provided.

Consider adding a brief comment explaining why combining geo.Point and Coordinates is expected to raise a GeometryError. This would enhance the test's readability and provide context for future maintainers. For example:

def test_geometry_error(self) -> None:
    """Test GeometryError when incompatible geometry and coordinates are provided."""
    p = geo.Point(1, 2)
    q = Coordinates(ns="ns")

    # Combining geo.Point and Coordinates should raise a GeometryError
    with pytest.raises(GeometryError):
        Point(geometry=p, kml_coordinates=q)
tests/geometries/polygon_test.py (1)

132-138: LGTM: New test method added correctly.

The new test method test_geometry_error is well-structured and correctly tests for the GeometryError exception when creating a Polygon with invalid parameters. This is an important edge case to cover.

Consider expanding the docstring to provide more context about the specific scenario being tested. For example:

def test_geometry_error(self) -> None:
    """Test that a GeometryError is raised when creating a Polygon with both a geometry and an outer boundary."""
tests/overlays_test.py (1)

252-253: LGTM! Consider adding more specific assertions.

The new assertions are a good addition to ensure that view_volume and image_pyramid attributes are properly initialized. They complement the existing checks in this comprehensive test case.

To make the test even more robust, consider adding more specific assertions for these attributes. For example:

assert photo_overlay.view_volume.left_fov == -60
assert photo_overlay.view_volume.right_fov == 60
assert photo_overlay.view_volume.bottom_fov == -45
assert photo_overlay.view_volume.top_fov == 45
assert photo_overlay.view_volume.near == 1

assert photo_overlay.image_pyramid.tile_size == 256
assert photo_overlay.image_pyramid.max_width == 2048
assert photo_overlay.image_pyramid.max_height == 2048
assert photo_overlay.image_pyramid.grid_origin == enums.GridOrigin.lower_left

This would provide more detailed validation of these complex attributes.

tests/geometries/multigeometry_test.py (1)

294-300: LGTM: Good addition of error handling test

This new test method effectively verifies that MultiGeometry raises a GeometryError when given invalid input. The use of pytest's raises context manager is a good practice for testing exceptions.

Consider adding a more descriptive error message to the pytest.raises call to make the test's intention clearer:

with pytest.raises(GeometryError, match="Expected error message"):
    MultiGeometry(geometry=p, kml_geometries=q)

Replace "Expected error message" with the actual error message you expect to be raised.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b9812da and 589a00f.

📒 Files selected for processing (13)
  • tests/containers_test.py (2 hunks)
  • tests/geometries/boundaries_test.py (3 hunks)
  • tests/geometries/functions_test.py (1 hunks)
  • tests/geometries/linestring_test.py (2 hunks)
  • tests/geometries/multigeometry_test.py (2 hunks)
  • tests/geometries/point_test.py (2 hunks)
  • tests/geometries/polygon_test.py (2 hunks)
  • tests/gx_test.py (2 hunks)
  • tests/helper_test.py (1 hunks)
  • tests/kml_test.py (2 hunks)
  • tests/overlays_test.py (1 hunks)
  • tests/styles_test.py (1 hunks)
  • tests/views_test.py (1 hunks)
🧰 Additional context used
🪛 Ruff
tests/containers_test.py

87-87: pytest.raises(ValueError) is too broad, set the match parameter or use a more specific exception

(PT011)

tests/geometries/functions_test.py

1-1: Missing docstring in public module

(D100)


8-8: First line should end with a period

Add period

(D400)


8-8: First line should end with a period, question mark, or exclamation point

Add closing punctuation

(D415)


11-11: Missing type annotation for function argument mock_to_string

(ANN001)


11-11: Unused method argument: mock_to_string

(ARG002)


14-14: Line too long (94 > 88)

(E501)


17-17: Missing type annotation for function argument mock_to_string

(ANN001)


17-17: Unused method argument: mock_to_string

(ARG002)


19-19: Line too long (106 > 88)

(E501)


23-23: Line too long (94 > 88)

(E501)

tests/helper_test.py

1-1: Missing docstring in public module

(D100)


2-2: Line too long (184 > 88)

(E501)


15-15: Missing type annotation for function argument mock_get_value

(ANN001)


29-29: Missing type annotation for function argument mock_get_value

(ANN001)


43-43: Missing type annotation for function argument mock_get_value

(ANN001)


56-56: Missing return type annotation for public function test_subelement_int_kwarg

Add return type annotation: None

(ANN201)


72-72: Missing return type annotation for public function test_subelement_float_kwarg

Add return type annotation: None

(ANN201)


89-89: Missing type annotation for function argument mock_handle_error

(ANN001)

tests/kml_test.py

180-180: Missing type annotation for function argument mock_etree

(ANN001)


187-187: Line too long (120 > 88)

(E501)


194-194: pytest.raises(ValueError) is too broad, set the match parameter or use a more specific exception

(PT011)

🔇 Additional comments (22)
tests/geometries/functions_test.py (1)

1-60: Overall assessment: Good test coverage with minor improvements needed

This new test file provides a comprehensive suite of tests for geometry-related functions in the fastkml library. The tests cover important scenarios including error handling and coordinate processing.

Key points:

  1. Good use of mocking and patching to isolate tests.
  2. Effective coverage of both normal and edge cases.
  3. Clear and logical test structure.

Areas for improvement:

  1. Add a module-level docstring.
  2. Remove unused mock arguments in the first two tests.
  3. Consider using a dictionary for function arguments in test_coordinates_subelement_exception for improved readability.
  4. Fix the discrepancy in test_coordinates_subelement_getattr to ensure the correct object is being tested.

Overall, these tests will significantly contribute to the reliability of the fastkml library's geometry functions. After addressing the mentioned issues, the test suite will be even more robust and maintainable.

🧰 Tools
🪛 Ruff

1-1: Missing docstring in public module

(D100)


8-8: First line should end with a period

Add period

(D400)


8-8: First line should end with a period, question mark, or exclamation point

Add closing punctuation

(D415)


11-11: Missing type annotation for function argument mock_to_string

(ANN001)


11-11: Unused method argument: mock_to_string

(ARG002)


14-14: Line too long (94 > 88)

(E501)


17-17: Missing type annotation for function argument mock_to_string

(ANN001)


17-17: Unused method argument: mock_to_string

(ARG002)


19-19: Line too long (106 > 88)

(E501)


23-23: Line too long (94 > 88)

(E501)

tests/containers_test.py (1)

Line range hint 20-97: Overall, great additions to the test suite!

The new test methods significantly improve the coverage of container functionality in the fastkml library. They test important aspects such as container creation, feature appending, and style URL retrieval. The suggested improvements will further enhance the robustness and comprehensiveness of these tests.

Great job on improving the test coverage! These additions will help ensure the reliability of the container-related features in the library.

🧰 Tools
🪛 Ruff

87-87: pytest.raises(ValueError) is too broad, set the match parameter or use a more specific exception

(PT011)

tests/helper_test.py (1)

106-134: LGTM: Well-structured test methods

The test methods for subelement_enum_kwarg and attribute_enum_kwarg are well-implemented and cover valid scenarios. The mocking is done correctly, and the assertions are appropriate. Good job on including type annotations for these methods.

tests/geometries/boundaries_test.py (1)

19-20: LGTM: Import statement added correctly.

The import of GeometryError from fastkml.exceptions is necessary for the new test methods and is placed appropriately with other imports.

tests/geometries/linestring_test.py (3)

24-25: LGTM: Import statements updated appropriately.

The addition of GeometryError and Coordinates imports aligns with the new test method and enhances the overall test coverage.


40-40: LGTM: Improved readability with proper spacing.

The added blank line between test methods enhances code readability and adheres to PEP 8 style guidelines.


Line range hint 1-291: Overall assessment: Changes improve test coverage and maintain code quality.

The modifications to this file, including the new imports, the additional test method, and the improved spacing, all contribute positively to the PR's objective of enhancing test coverage. The changes are well-structured and maintain the existing code quality standards.

tests/kml_test.py (2)

20-23: LGTM: New imports are appropriate for the added tests.

The addition of pytest and patch from unittest.mock is appropriate for the new test methods. These imports enable better testing capabilities, including exception handling and mocking.


197-203: LGTM: Good addition of test for parsing KML with "None" namespace.

The new test class TestParseKMLNone and its method test_kml_parse effectively verify the behavior of parsing a KML file with a "None" namespace. This is a good edge case to test and ensures that the KML.parse method handles different namespace scenarios correctly.

tests/geometries/point_test.py (2)

23-25: LGTM: Import statements updated appropriately.

The addition of GeometryError to the import statement and the new import for Coordinates are consistent with the requirements of the new test method. These changes enhance the test file's capability to handle geometry-related errors and coordinate objects.


Line range hint 1-50: Overall assessment: Excellent addition to the test suite.

The changes in this file align well with the PR objective of improving test coverage. The new test method for GeometryError enhances the robustness of the Point class tests. The code is well-structured, follows best practices, and contributes to the overall quality of the test suite.

tests/views_test.py (3)

212-212: LGTM! Improved test coverage for Region's LOD.

The added assertion assert region.lod.__bool__() is True enhances the test by verifying that the lod attribute of the region object is not only present but also evaluates to True. This ensures that the Lod object contains valid data, strengthening the overall test coverage for the Region class.


Line range hint 253-253: LGTM! Improved test documentation.

The updated comment "Region object can be initialized with empty LatLonAltBox object." provides a clearer and more accurate description of the test's purpose. This change enhances the readability and maintainability of the test suite by explicitly stating what aspect of the Region class is being tested.


Line range hint 1-283: Summary: Enhancements to test coverage and documentation

The changes in this file contribute positively to the PR's objective of improving test coverage. The additional assertion in test_region_with_all_optional_parameters strengthens the validation of the Region class, while the updated comment in test_initialized_with_empty_lat_lon_alt_box improves the clarity of the test's purpose. These modifications, although small, significantly enhance the quality and maintainability of the test suite.

tests/geometries/polygon_test.py (2)

20-20: LGTM: Import statement added correctly.

The new import statement for GeometryError is correctly placed and necessary for the new test method.


Line range hint 19-138: Overall assessment: Changes improve test coverage as intended.

The additions to this file, including the new import statement and the test_geometry_error method, contribute positively to the PR's objective of improving test coverage. The new test case covers an important edge case for the Polygon class, enhancing the robustness of the test suite.

tests/geometries/multigeometry_test.py (2)

18-19: LGTM: Good addition of imports for improved testing

The addition of pytest and GeometryError imports enhances the testing capabilities. Using pytest is a good practice, and importing GeometryError allows for more specific error handling tests.


Line range hint 1-437: Overall assessment: Excellent improvements to test coverage

The changes in this file significantly enhance the test suite for the MultiGeometry class. The addition of error handling tests and the use of pytest improve the robustness of the test coverage. These changes align well with the PR objectives of improving test coverage for the FastKML project.

Great job on these improvements!

tests/gx_test.py (3)

54-59: LGTM: New test method added to verify Track initialization

The new test method test_track_etree_element is a good addition. It verifies that a newly created Track instance maintains an empty track_items list after calling etree_element(). This helps ensure the integrity of the Track class implementation.


340-341: LGTM: New assertion added to verify MultiTrack truthiness

The new assertion assert mt.__bool__() is True is a valuable addition to the test_from_multilinestring method. It verifies that a non-empty MultiTrack instance evaluates to True when converted to a boolean, ensuring the correct implementation of the __bool__ method.


54-59: Overall assessment: Improved test coverage

The changes in this file enhance the test coverage of the fastkml library. Both additions (the new test_track_etree_element method and the assertion in test_from_multilinestring) are well-implemented and contribute to verifying the correct behavior of the Track and MultiTrack classes. These changes align well with the PR objective of improving test coverage.

Also applies to: 340-341

tests/styles_test.py (1)

613-617: LGTM! Good addition of a test case for default StyleMap behavior.

This test case is a valuable addition as it verifies the default behavior of StyleMap when instantiated without parameters. It ensures that both normal and highlight attributes are None by default, which is important for maintaining consistent behavior in edge cases.

Comment on lines 43 to 60
def test_coordinates_subelement_getattr(self) -> None:
obj = Mock()
setattr(obj, 'coordinates', [(1.123456, 2.654321), (3.123456, 4.654321)])

element = Mock()

precision = 4
attr_name = 'coordinates'

assert coordinates_subelement(
obj=None,
attr_name=attr_name,
node_name=None,
element=element,
precision=precision,
verbosity=None,
default=None
) is None
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix discrepancy between setup and function call

The test case is well-structured, but there's a discrepancy between the setup and the function call that needs to be addressed.

The obj is set up with valid coordinates, but it's not used in the coordinates_subelement function call. Instead, None is passed as the obj argument. This doesn't test the intended behavior. To fix this, replace:

assert coordinates_subelement(
    obj=None,
    # ... other arguments ...
) is None

with:

assert coordinates_subelement(
    obj=obj,
    # ... other arguments ...
) is None

This change ensures that the test actually uses the mock object with the valid coordinates you've set up.

Comment on lines 88 to 97
def test_inner_boundry_geometry_error(self) -> None:
"""Test GeometryError."""
p = geo.Point(1, 2)
coords = ((1, 2), (2, 0), (0, 0), (1, 2))

with pytest.raises(GeometryError):
InnerBoundaryIs(
kml_geometry=LinearRing(kml_coordinates=Coordinates(coords=coords)),
geometry=p
)
Copy link
Contributor

@coderabbitai coderabbitai bot Oct 12, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Fix typo in method name, improve docstring, and consider refactoring.

This test method is a good addition, but there are some improvements to be made:

  1. Fix the typo in the method name: "boundry" should be "boundary".
  2. The docstring could be more descriptive to explain the purpose of the test.
  3. Consider refactoring to reduce code duplication with test_outer_boundary_geometry_error.

Here's a suggested improvement for the method signature and docstring:

-    def test_inner_boundry_geometry_error(self) -> None:
-        """Test GeometryError."""
+    def test_inner_boundary_geometry_error(self) -> None:
+        """Test that InnerBoundaryIs raises GeometryError with invalid geometry."""

To reduce code duplication, consider creating a helper method that both test_outer_boundary_geometry_error and test_inner_boundary_geometry_error can use. For example:

def _test_boundary_geometry_error(self, boundary_class):
    p = geo.Point(1, 2)
    coords = ((1, 2), (2, 0), (0, 0), (1, 2))

    with pytest.raises(GeometryError):
        boundary_class(
            kml_geometry=LinearRing(kml_coordinates=Coordinates(coords=coords)),
            geometry=p
        )

def test_outer_boundary_geometry_error(self):
    """Test that OuterBoundaryIs raises GeometryError with invalid geometry."""
    self._test_boundary_geometry_error(OuterBoundaryIs)

def test_inner_boundary_geometry_error(self):
    """Test that InnerBoundaryIs raises GeometryError with invalid geometry."""
    self._test_boundary_geometry_error(InnerBoundaryIs)

This refactoring would make the tests more maintainable and reduce redundancy.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

implemented

Copy link
Contributor

Choose a reason for hiding this comment

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

@apurvabanka, thank you for implementing the changes!

(^.^/)


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Comment on lines 46 to 55
def test_outer_boundry_geometry_error(self) -> None:
"""Test GeometryError."""
p = geo.Point(1, 2)
coords = ((1, 2), (2, 0), (0, 0), (1, 2))

with pytest.raises(GeometryError):
OuterBoundaryIs(
kml_geometry=LinearRing(kml_coordinates=Coordinates(coords=coords)),
geometry=p
)
Copy link
Contributor

@coderabbitai coderabbitai bot Oct 12, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in method name and improve docstring.

The new test method is a good addition, but there are a couple of improvements to be made:

  1. Fix the typo in the method name: "boundry" should be "boundary".
  2. The docstring could be more descriptive to explain the purpose of the test.

Here's a suggested improvement:

-    def test_outer_boundry_geometry_error(self) -> None:
-        """Test GeometryError."""
+    def test_outer_boundary_geometry_error(self) -> None:
+        """Test that OuterBoundaryIs raises GeometryError with invalid geometry."""

The rest of the test implementation looks good and correctly checks for the GeometryError exception.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def test_outer_boundry_geometry_error(self) -> None:
"""Test GeometryError."""
p = geo.Point(1, 2)
coords = ((1, 2), (2, 0), (0, 0), (1, 2))
with pytest.raises(GeometryError):
OuterBoundaryIs(
kml_geometry=LinearRing(kml_coordinates=Coordinates(coords=coords)),
geometry=p
)
def test_outer_boundary_geometry_error(self) -> None:
"""Test that OuterBoundaryIs raises GeometryError with invalid geometry."""
p = geo.Point(1, 2)
coords = ((1, 2), (2, 0), (0, 0), (1, 2))
with pytest.raises(GeometryError):
OuterBoundaryIs(
kml_geometry=LinearRing(kml_coordinates=Coordinates(coords=coords)),
geometry=p
)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

implemented

Copy link
Contributor

Choose a reason for hiding this comment

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

@apurvabanka, thank you for making the changes!

(^.^)/


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Copy link

Preparing review...

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

🧹 Outside diff range and nitpick comments (3)
tests/containers_test.py (3)

69-77: LGTM! Consider expanding assertions for comprehensive testing.

The test method correctly creates a _Container object and verifies some of its attributes. However, to ensure all parameters are correctly set, consider adding assertions for 'id' and 'target_id' as well.

Here's a suggested improvement:

def test_container_creation(self) -> None:
    container = containers._Container(
        ns="ns",
        id="id",
        target_id="target_id",
        name="name"
    )
    assert container.ns == "ns"
    assert container.name == "name"
    assert container.id == "id"
    assert container.target_id == "target_id"

78-88: LGTM! Consider implementing suggested improvements.

The test method correctly verifies the append behavior and error handling. However, there are a couple of improvements that can be made:

  1. As suggested in the past review, add an assertion to check if the feature was actually appended to the container.
  2. Address the static analysis hint by either using a more specific exception or setting the 'match' parameter in pytest.raises().

Here's a suggested improvement incorporating both points:

def test_container_feature_append(self) -> None:
    container = containers._Container(
        ns="ns",
        id="id",
        target_id="target_id",
        name="name"
    )
    feature = features._Feature(name="new_feature")
    assert container.append(feature) is None
    assert feature in container.features  # Check if feature was actually appended
    with pytest.raises(ValueError, match="Cannot append a container to itself"):
        container.append(container)

This improvement ensures that the feature is actually appended and provides a more specific error message for the ValueError.

🧰 Tools
🪛 Ruff

87-87: pytest.raises(ValueError) is too broad, set the match parameter or use a more specific exception

(PT011)


90-96: LGTM! Consider expanding test coverage and clarifying method name.

The test method correctly verifies that get_style_by_url returns None when no style is present. However, there are a couple of improvements that can be made:

  1. Add a test case where a style is actually present to ensure the method works correctly in both scenarios.
  2. Consider renaming the test method to test_document_container_get_style_by_url to accurately reflect the method being tested.

Here's a suggested improvement:

def test_document_container_get_style_by_url(self) -> None:
    document = containers.Document(
        name="Document",
        ns="ns",
        style_url="www.styleurl.com"
    )
    assert document.get_style_by_url(style_url="www.styleurl.com") is None

    # Add a style to the document
    style = kml.Style(id="style_id")
    document.append_style(style)

    # Test retrieving an existing style
    assert document.get_style_by_url(style_url="#style_id") == style

    # Test retrieving a non-existent style
    assert document.get_style_by_url(style_url="#non_existent_style") is None

This improvement tests both the case where no style is present and the case where a style exists, providing more comprehensive coverage of the get_style_by_url method.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 589a00f and 712587e.

📒 Files selected for processing (1)
  • tests/containers_test.py (2 hunks)
🧰 Additional context used
🪛 Ruff
tests/containers_test.py

87-87: pytest.raises(ValueError) is too broad, set the match parameter or use a more specific exception

(PT011)

Copy link

Preparing review...

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

🧹 Outside diff range and nitpick comments (9)
tests/geometries/functions_test.py (3)

1-10: Improve documentation with proper docstrings

Please consider adding a module-level docstring at the beginning of the file to describe its purpose. Additionally, update the class docstring to end with a period for better readability and to comply with documentation standards.

Here's a suggested improvement for the class docstring:

class TestGeometryFunctions(StdLibrary):
    """Test functions in Geometry module."""
🧰 Tools
🪛 Ruff

1-1: Missing docstring in public module

(D100)


10-10: First line should end with a period

Add period

(D400)


10-10: First line should end with a period, question mark, or exclamation point

Add closing punctuation

(D415)


12-20: Add type annotation and consider removing unused parameter

The test method looks good, but there are a couple of minor improvements we can make:

  1. Add a type annotation for the mock_to_string parameter.
  2. Since mock_to_string is unused, consider removing it if it's not needed for the test setup.

Here's a suggested improvement:

from unittest.mock import Mock, patch

@patch('fastkml.config.etree.tostring')
def test_handle_invalid_geometry_error_true(self, mock_to_string: Mock) -> None:
    mock_element = Mock()
    with pytest.raises(KMLParseError):
        handle_invalid_geometry_error(
            error=ValueError,
            element=mock_element,
            strict=True
        )

If mock_to_string is not needed at all, you can simplify further:

@patch('fastkml.config.etree.tostring')
def test_handle_invalid_geometry_error_true(self) -> None:
    mock_element = Mock()
    with pytest.raises(KMLParseError):
        handle_invalid_geometry_error(
            error=ValueError,
            element=mock_element,
            strict=True
        )
🧰 Tools
🪛 Ruff

13-13: Missing type annotation for function argument mock_to_string

(ANN001)


13-13: Unused method argument: mock_to_string

(ARG002)


22-29: Add type annotation and consider removing unused parameter

Similar to the previous test method, we can make the following improvements:

  1. Add a type annotation for the mock_to_string parameter.
  2. Consider removing the unused mock_to_string parameter if it's not needed for the test setup.

Here's a suggested improvement:

@patch('fastkml.config.etree.tostring')
def test_handle_invalid_geometry_error_false(self, mock_to_string: Mock) -> None:
    mock_element = Mock()
    assert handle_invalid_geometry_error(
        error=ValueError,
        element=mock_element,
        strict=False
    ) is None

If mock_to_string is not needed at all, you can simplify further:

@patch('fastkml.config.etree.tostring')
def test_handle_invalid_geometry_error_false(self) -> None:
    mock_element = Mock()
    assert handle_invalid_geometry_error(
        error=ValueError,
        element=mock_element,
        strict=False
    ) is None
🧰 Tools
🪛 Ruff

23-23: Missing type annotation for function argument mock_to_string

(ANN001)


23-23: Unused method argument: mock_to_string

(ARG002)

tests/containers_test.py (1)

69-77: Enhance test coverage for container creation

The test verifies the ns and name attributes of the created _Container object. Consider extending the test to verify all attributes, including id and target_id, for comprehensive coverage.

Here's a suggested improvement:

def test_container_creation(self) -> None:
    container = containers._Container(
        ns="ns",
        id="id",
        target_id="target_id",
        name="name"
    )
    assert container.ns == "ns"
    assert container.name == "name"
    assert container.id == "id"
    assert container.target_id == "target_id"
tests/helper_test.py (3)

1-11: Add a module-level docstring for better documentation.

Consider adding a module-level docstring at the beginning of the file to describe the purpose of these tests and provide an overview of what's being tested.

Example:

"""
This module contains unit tests for the helper functions in the fastkml library.
It tests various utility functions related to attribute handling, enum operations,
and value conversions used throughout the FastKML project.
"""
🧰 Tools
🪛 Ruff

1-1: Missing docstring in public module

(D100)


14-15: Add a docstring to the Node class.

The purpose of the Node class is not immediately clear. Consider adding a docstring to explain its role in the tests.

Example:

class Node:
    """
    A simple class representing a node with text content.
    Used as a mock object in tests to simulate XML elements.
    """
    text: str

18-19: Consider expanding the Color enum for more comprehensive testing.

The Color enum currently only contains one color (RED). To ensure more thorough testing of enum-related functions, consider adding more colors.

Example:

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

This would allow testing of multiple enum values and edge cases in the helper functions.

tests/kml_test.py (2)

179-192: LGTM: Well-structured test method for etree_element.

The new test method test_kml_etree_element is well-implemented and effectively verifies the behavior of the etree_element method. The use of mocking is appropriate for isolating the test.

Consider adding a type annotation for the mock_etree parameter:

def test_kml_etree_element(self, mock_etree: MagicMock) -> None:

Don't forget to import MagicMock from unittest.mock if you add this type annotation.

🧰 Tools
🪛 Ruff

180-180: Missing type annotation for function argument mock_etree

(ANN001)


194-200: LGTM: Good test for edge case in append method.

The test_kml_append method effectively tests an important edge case where appending a KML document to itself should raise a ValueError.

To make the test more specific and robust, consider adding a match parameter to the pytest.raises call:

with pytest.raises(ValueError, match="Cannot append a KML document to itself"):
    doc.append(doc)

This ensures that not only is a ValueError raised, but it also contains the expected error message.

🧰 Tools
🪛 Ruff

199-199: pytest.raises(ValueError) is too broad, set the match parameter or use a more specific exception

(PT011)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 712587e and c106b2c.

📒 Files selected for processing (10)
  • tests/containers_test.py (2 hunks)
  • tests/geometries/boundaries_test.py (3 hunks)
  • tests/geometries/functions_test.py (1 hunks)
  • tests/geometries/linestring_test.py (2 hunks)
  • tests/geometries/multigeometry_test.py (2 hunks)
  • tests/geometries/point_test.py (2 hunks)
  • tests/geometries/polygon_test.py (2 hunks)
  • tests/gx_test.py (2 hunks)
  • tests/helper_test.py (1 hunks)
  • tests/kml_test.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • tests/geometries/boundaries_test.py
  • tests/geometries/linestring_test.py
  • tests/geometries/multigeometry_test.py
  • tests/geometries/point_test.py
  • tests/geometries/polygon_test.py
  • tests/gx_test.py
🧰 Additional context used
🪛 Ruff
tests/containers_test.py

88-88: pytest.raises(ValueError) is too broad, set the match parameter or use a more specific exception

(PT011)

tests/geometries/functions_test.py

1-1: Missing docstring in public module

(D100)


10-10: First line should end with a period

Add period

(D400)


10-10: First line should end with a period, question mark, or exclamation point

Add closing punctuation

(D415)


13-13: Missing type annotation for function argument mock_to_string

(ANN001)


13-13: Unused method argument: mock_to_string

(ARG002)


23-23: Missing type annotation for function argument mock_to_string

(ANN001)


23-23: Unused method argument: mock_to_string

(ARG002)

tests/helper_test.py

1-1: Missing docstring in public module

(D100)


24-24: Missing type annotation for function argument mock_get_value

(ANN001)


38-38: Missing type annotation for function argument mock_get_value

(ANN001)


52-52: Missing type annotation for function argument mock_get_value

(ANN001)


65-65: Missing return type annotation for public function test_subelement_int_kwarg

Add return type annotation: None

(ANN201)


81-81: Missing return type annotation for public function test_subelement_float_kwarg

Add return type annotation: None

(ANN201)


98-98: Missing type annotation for function argument mock_handle_error

(ANN001)

tests/kml_test.py

180-180: Missing type annotation for function argument mock_etree

(ANN001)


199-199: pytest.raises(ValueError) is too broad, set the match parameter or use a more specific exception

(PT011)

🔇 Additional comments (7)
tests/geometries/functions_test.py (3)

31-52: Well-structured test for invalid coordinates

This test method is well-implemented and covers an important edge case. It correctly sets up a mock object with invalid 4D coordinates and verifies that a KMLWriteError is raised when processing these coordinates.

The test effectively ensures that the coordinates_subelement function handles invalid input as expected.


1-71: Overall assessment of the test file

This test file provides good coverage for the geometry-related functions in the fastkml library. It includes tests for both normal operation and edge cases, which is commendable. However, there are a few areas for improvement:

  1. Add module and class-level docstrings for better documentation.
  2. Address type annotations and unused parameters in the first two test methods.
  3. Fix the discrepancy in the test_coordinates_subelement_getattr method to ensure it's testing the intended behavior.

Addressing these points will enhance the overall quality and effectiveness of your test suite.

Despite the issues mentioned, the core functionality of the tests is sound. Once these improvements are made, this will be a robust set of tests for the geometry functions.

🧰 Tools
🪛 Ruff

1-1: Missing docstring in public module

(D100)


10-10: First line should end with a period

Add period

(D400)


10-10: First line should end with a period, question mark, or exclamation point

Add closing punctuation

(D415)


13-13: Missing type annotation for function argument mock_to_string

(ANN001)


13-13: Unused method argument: mock_to_string

(ARG002)


23-23: Missing type annotation for function argument mock_to_string

(ANN001)


23-23: Unused method argument: mock_to_string

(ARG002)


54-71: ⚠️ Potential issue

Fix discrepancy between setup and function call

There's an important issue in this test method that needs to be addressed. The test sets up a mock object with valid coordinates, but then passes None as the obj parameter in the coordinates_subelement function call. This doesn't test the intended behavior.

To fix this, replace:

assert coordinates_subelement(
    obj=None,
    # ... other arguments ...
) is None

with:

assert coordinates_subelement(
    obj=obj,
    # ... other arguments ...
) is None

This change ensures that the test actually uses the mock object with the valid coordinates you've set up, allowing for a proper test of the coordinates_subelement function's behavior with valid input.

tests/helper_test.py (1)

1-141: LGTM with minor suggestions for improvement.

Overall, this test file is well-structured and provides good coverage for the helper functions in the fastkml library. The use of mocking and various test scenarios is commendable. To further improve the file:

  1. Add a module-level docstring explaining the purpose of these tests.
  2. Enhance the Node and Color classes with docstrings and additional enum values respectively.
  3. Add type annotations to test method arguments.
  4. Expand test coverage in some methods to include more edge cases.
  5. Improve assertions in certain test methods to verify not just the result but also the correct usage of mocked objects.

These changes will enhance the documentation, type safety, and overall robustness of the test suite.

🧰 Tools
🪛 Ruff

1-1: Missing docstring in public module

(D100)


24-24: Missing type annotation for function argument mock_get_value

(ANN001)


38-38: Missing type annotation for function argument mock_get_value

(ANN001)


52-52: Missing type annotation for function argument mock_get_value

(ANN001)


65-65: Missing return type annotation for public function test_subelement_int_kwarg

Add return type annotation: None

(ANN201)


81-81: Missing return type annotation for public function test_subelement_float_kwarg

Add return type annotation: None

(ANN201)


98-98: Missing type annotation for function argument mock_handle_error

(ANN001)

tests/kml_test.py (3)

20-26: LGTM: New imports are correctly added.

The new imports for unittest.mock.patch, pytest, and fastkml.config are necessary for the newly added test methods and are correctly placed at the top of the file.


203-209: LGTM: New test class for parsing KML with 'None' namespace.

The TestParseKMLNone class and its test_kml_parse method effectively verify the behavior of parsing a KML file with a specified namespace of "None". This is a good addition to ensure correct handling of different namespace scenarios.


179-209: Great job on improving test coverage!

The additions to this file significantly enhance the test coverage for the KML class. The new tests cover important aspects such as:

  1. XML element generation with correct namespaces
  2. Error handling for invalid operations (appending a document to itself)
  3. Parsing KML with a 'None' namespace

These additions align well with the PR objective of improving test coverage and help ensure the robustness of the FastKML library.

🧰 Tools
🪛 Ruff

180-180: Missing type annotation for function argument mock_etree

(ANN001)


199-199: pytest.raises(ValueError) is too broad, set the match parameter or use a more specific exception

(PT011)

Comment on lines 79 to 89
def test_container_feature_append(self) -> None:
container = containers._Container(
ns="ns",
id="id",
target_id="target_id",
name="name"
)
feature = features._Feature(name="new_feature")
assert container.append(feature) is None
with pytest.raises(ValueError):
container.append(container)
Copy link
Contributor

@coderabbitai coderabbitai bot Oct 12, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve test_container_feature_append method

  1. Consider adding an assertion to verify that the feature was actually appended to the container, as suggested in the previous review.
  2. The pytest.raises(ValueError) assertion is too broad. Specify the expected error message using the match parameter for more precise testing.

Here's a suggested improvement:

def test_container_feature_append(self) -> None:
    container = containers._Container(
        ns="ns",
        id="id",
        target_id="target_id",
        name="name"
    )
    feature = features._Feature(name="new_feature")
    assert container.append(feature) is None
    assert feature in container.features  # Verify the feature was appended
    with pytest.raises(ValueError, match="Cannot append a container to itself"):
        container.append(container)
🧰 Tools
🪛 Ruff

88-88: pytest.raises(ValueError) is too broad, set the match parameter or use a more specific exception

(PT011)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

implemented

Copy link
Contributor

Choose a reason for hiding this comment

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

@apurvabanka, great! Glad to hear that you've implemented the suggested improvements.

(_/)
( ^.^)
('')('')


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Comment on lines +91 to +97
def test_document_container_get_style_url(self) -> None:
document = containers.Document(
name="Document",
ns="ns",
style_url="www.styleurl.com"
)
assert document.get_style_by_url(style_url="www.styleurl.com") is None
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Expand test coverage for get_style_by_url method

The current test verifies that get_style_by_url returns None for a valid style_url. However, it's unclear if this is the expected behavior. Consider the following improvements:

  1. Clarify why get_style_by_url returns None for a valid style_url. Is this the intended behavior?
  2. Add a test case for an invalid style_url to ensure the method behaves correctly in both scenarios.
  3. If possible, add a test case where get_style_by_url returns a non-None value to demonstrate when it successfully retrieves a style.

Here's a suggested improvement:

def test_document_container_get_style_url(self) -> None:
    document = containers.Document(
        name="Document",
        ns="ns",
        style_url="www.styleurl.com"
    )
    # Assuming None is the correct return value for a valid but non-existent style
    assert document.get_style_by_url(style_url="www.styleurl.com") is None
    
    # Test with an invalid style_url
    assert document.get_style_by_url(style_url="invalid_url") is None
    
    # If possible, add a test case where get_style_by_url returns a non-None value
    # This might require setting up a style in the document first
    # document.styles.append(some_style)
    # assert document.get_style_by_url(style_url="some_style_url") is not None

Comment on lines +22 to +141
element="ele",
attr_name="a",
node_name="n",
precision=0,
verbosity=0,
default="default"
)
assert res is None

@patch('fastkml.helpers.get_value')
def test_enum_attribute(self, mock_get_value) -> None:
mock_get_value.return_value = None
res = enum_attribute(
obj=None,
element="ele",
attr_name="a",
node_name="n",
precision=0,
verbosity=0,
default="default"
)
assert res is None

def test_subelement_int_kwarg(self):
node = Node()
node.text = None
element = Mock()
element.find.return_value = node
res = subelement_int_kwarg(
element=element,
ns="ns",
name_spaces="name",
node_name="node",
kwarg="kwarg",
classes=None,
strict=False
)
assert res == {}

def test_subelement_float_kwarg(self):
node = Node()
node.text = None
element = Mock()
element.find.return_value = node
res = subelement_float_kwarg(
element=element,
ns="ns",
name_spaces="name",
node_name="node",
kwarg="kwarg",
classes=None,
strict=False
)
assert res == {}

@patch('fastkml.helpers.handle_error')
def test_attribute_float_kwarg(self, mock_handle_error) -> None:
element = Mock()
element.get.return_value = "abcd"
mock_handle_error.return_value = None
res = attribute_float_kwarg(
element=element,
ns="ns",
name_spaces="name",
node_name="node",
kwarg="a",
classes=None,
strict=True
)
assert res == {}

def test_subelement_enum_kwarg(self) -> None:
node = Node()
node.text = None
element = Mock()
element.find.return_value = node
res = subelement_enum_kwarg(
element=element,
ns="ns",
name_spaces="name",
node_name="node",
kwarg="a",
classes=[Color],
strict=True
)
assert res == {}

def test_attribute_enum_kwarg(self) -> None:
element = Mock()
element.get.return_value = None
res = attribute_enum_kwarg(
element=element,
ns="ns",
name_spaces="name",
node_name="node",
kwarg="a",
classes=[Color],
strict=True
)
assert res == {}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test methods with type annotations and expanded coverage.

  1. Add type annotations to function arguments in test methods. For example:

    def test_node_text(self, mock_get_value: Mock) -> None:
  2. Consider expanding test coverage in methods like test_float_attribute and test_enum_attribute. Test with different input values and edge cases.

  3. Improve assertions in methods like test_subelement_int_kwarg and test_subelement_float_kwarg. Assert not just that the result is an empty dict, but also that the mocked methods were called with expected arguments.

Example for test_subelement_int_kwarg:

def test_subelement_int_kwarg(self) -> None:
    node = Node()
    node.text = None
    element = Mock()
    element.find.return_value = node
    res = subelement_int_kwarg(
        element=element,
        ns="ns",
        name_spaces="name",
        node_name="node",
        kwarg="kwarg",
        classes=None,
        strict=False
    )
    assert res == {}
    element.find.assert_called_once_with("nsnode")

These changes will improve type safety, increase test coverage, and make the tests more robust.

🧰 Tools
🪛 Ruff

24-24: Missing type annotation for function argument mock_get_value

(ANN001)


38-38: Missing type annotation for function argument mock_get_value

(ANN001)


52-52: Missing type annotation for function argument mock_get_value

(ANN001)


65-65: Missing return type annotation for public function test_subelement_int_kwarg

Add return type annotation: None

(ANN201)


81-81: Missing return type annotation for public function test_subelement_float_kwarg

Add return type annotation: None

(ANN201)


98-98: Missing type annotation for function argument mock_handle_error

(ANN001)

Copy link

codecov bot commented Oct 13, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 98.92%. Comparing base (04ec3d7) to head (200bcb5).
Report is 19 commits behind head on 352-improve-test-coverage.

Additional details and impacted files
@@                      Coverage Diff                      @@
##           352-improve-test-coverage     #365      +/-   ##
=============================================================
+ Coverage                      98.12%   98.92%   +0.80%     
=============================================================
  Files                             50       52       +2     
  Lines                           4848     5027     +179     
  Branches                         148      148              
=============================================================
+ Hits                            4757     4973     +216     
+ Misses                            63       44      -19     
+ Partials                          28       10      -18     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Owner

@cleder cleder left a comment

Choose a reason for hiding this comment

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

Hey, nice work 👍
I left some comments and 👍 or 👎 on the AI generated reviews.

tests/gx_test.py Outdated Show resolved Hide resolved
tests/overlays_test.py Outdated Show resolved Hide resolved
tests/views_test.py Outdated Show resolved Hide resolved
name="name"
)
feature = features._Feature(name="new_feature")
assert container.append(feature) is None
Copy link
Owner

Choose a reason for hiding this comment

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

I don't think this line is needed, as .append always returns None

Copy link
Contributor Author

Choose a reason for hiding this comment

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

changed

apurvabanka and others added 3 commits October 13, 2024 13:39
Co-authored-by: Christian Ledermann <[email protected]>
Co-authored-by: Christian Ledermann <[email protected]>
Co-authored-by: Christian Ledermann <[email protected]>
@apurvabanka
Copy link
Contributor Author

Hey, nice work 👍 I left some comments and 👍 or 👎 on the AI generated reviews.

@cleder Thanks for the review. Just to clarify, does 👍 mean we are good with the changes or should I go ahead and make the change suggested by the AI bot?

@cleder
Copy link
Owner

cleder commented Oct 13, 2024

Sorry @apurvabanka a 👎 on a bot review means not needed, a 👍 means, it is a good suggestion.

@apurvabanka apurvabanka requested a review from cleder October 13, 2024 18:48
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: 1

🧹 Outside diff range and nitpick comments (7)
tests/geometries/functions_test.py (4)

1-10: Add a module docstring for better documentation.

Consider adding a module-level docstring at the beginning of the file to describe the purpose of these tests. This will improve the overall documentation and address the D100 linter warning.

Here's a suggested docstring:

"""
Unit tests for geometry-related functions in the fastkml library.

This module contains test cases for handle_invalid_geometry_error and coordinates_subelement functions.
"""
🧰 Tools
🪛 Ruff

1-1: Missing docstring in public module

(D100)


10-10: First line should end with a period

Add period

(D400)


10-10: First line should end with a period, question mark, or exclamation point

Add closing punctuation

(D415)


12-20: LGTM! Consider adding type annotation for mock_to_string.

The test logic is correct and effectively checks the behavior of handle_invalid_geometry_error when strict=True. To improve type hinting, consider adding a type annotation for the mock_to_string parameter:

@patch('fastkml.config.etree.tostring')
def test_handle_invalid_geometry_error_true(self, mock_to_string: Mock) -> None:
🧰 Tools
🪛 Ruff

13-13: Missing type annotation for function argument mock_to_string

(ANN001)


13-13: Unused method argument: mock_to_string

(ARG002)


22-29: LGTM! Consider adding type annotation for mock_to_string.

The test logic is correct and effectively checks the behavior of handle_invalid_geometry_error when strict=False. To improve type hinting, consider adding a type annotation for the mock_to_string parameter:

@patch('fastkml.config.etree.tostring')
def test_handle_invalid_geometry_error_false(self, mock_to_string: Mock) -> None:
🧰 Tools
🪛 Ruff

23-23: Missing type annotation for function argument mock_to_string

(ANN001)


23-23: Unused method argument: mock_to_string

(ARG002)


31-52: LGTM! Fix indentation for better readability.

The test logic is correct and effectively checks the behavior of coordinates_subelement with invalid 4D coordinates. However, there's a minor indentation issue that should be fixed:

 setattr(obj,
         'coordinates',
-        [(1.123456, 2.654321, 3.111111, 4.222222)]
-    )
+        [(1.123456, 2.654321, 3.111111, 4.222222)])

This change will improve code readability and consistency.

tests/geometries/boundaries_test.py (3)

78-86: LGTM: Helper method for boundary geometry error tests

The _test_boundary_geometry_error method effectively encapsulates the common logic for testing both OuterBoundaryIs and InnerBoundaryIs classes. It correctly uses pytest.raises to check for the GeometryError.

To improve type safety and code readability, consider adding type annotations:

def _test_boundary_geometry_error(self, boundary_class: Type[Union[OuterBoundaryIs, InnerBoundaryIs]]) -> None:

Don't forget to import Type and Union from the typing module if they're not already imported.

🧰 Tools
🪛 Ruff

78-78: Missing return type annotation for private function _test_boundary_geometry_error

Add return type annotation: None

(ANN202)


78-78: Missing type annotation for function argument boundary_class

(ANN001)


88-90: LGTM: Test method for OuterBoundaryIs geometry error

The test_outer_boundary_geometry_error method correctly tests the OuterBoundaryIs class for GeometryError. The docstring accurately describes the test's purpose.

To improve type safety, consider adding a return type annotation:

def test_outer_boundary_geometry_error(self) -> None:
🧰 Tools
🪛 Ruff

88-88: Missing return type annotation for public function test_outer_boundary_geometry_error

Add return type annotation: None

(ANN201)


92-94: LGTM: Test method for InnerBoundaryIs geometry error

The test_inner_boundary_geometry_error method correctly tests the InnerBoundaryIs class for GeometryError. The docstring accurately describes the test's purpose.

To improve type safety, consider adding a return type annotation:

def test_inner_boundary_geometry_error(self) -> None:
🧰 Tools
🪛 Ruff

92-92: Missing return type annotation for public function test_inner_boundary_geometry_error

Add return type annotation: None

(ANN201)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5ad43b6 and 200bcb5.

📒 Files selected for processing (3)
  • tests/containers_test.py (2 hunks)
  • tests/geometries/boundaries_test.py (2 hunks)
  • tests/geometries/functions_test.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/containers_test.py
🧰 Additional context used
🪛 Ruff
tests/geometries/boundaries_test.py

78-78: Missing return type annotation for private function _test_boundary_geometry_error

Add return type annotation: None

(ANN202)


78-78: Missing type annotation for function argument boundary_class

(ANN001)


88-88: Missing return type annotation for public function test_outer_boundary_geometry_error

Add return type annotation: None

(ANN201)


92-92: Missing return type annotation for public function test_inner_boundary_geometry_error

Add return type annotation: None

(ANN201)

tests/geometries/functions_test.py

1-1: Missing docstring in public module

(D100)


10-10: First line should end with a period

Add period

(D400)


10-10: First line should end with a period, question mark, or exclamation point

Add closing punctuation

(D415)


13-13: Missing type annotation for function argument mock_to_string

(ANN001)


13-13: Unused method argument: mock_to_string

(ARG002)


23-23: Missing type annotation for function argument mock_to_string

(ANN001)


23-23: Unused method argument: mock_to_string

(ARG002)

🔇 Additional comments (3)
tests/geometries/functions_test.py (1)

1-71: Overall assessment: Good test coverage with room for minor improvements.

This new test file provides good coverage for the geometry-related functions in the fastkml library. The tests are well-structured and cover important scenarios. Here's a summary of the suggested improvements:

  1. Add a module-level docstring for better documentation.
  2. Add type annotations for the mock_to_string parameters in the patched methods.
  3. Fix the indentation issue in the test_coordinates_subelement_exception method.
  4. Address the discrepancy in the test_coordinates_subelement_getattr method by using the correct obj parameter.

Implementing these suggestions will further enhance the quality and effectiveness of these tests.

🧰 Tools
🪛 Ruff

1-1: Missing docstring in public module

(D100)


10-10: First line should end with a period

Add period

(D400)


10-10: First line should end with a period, question mark, or exclamation point

Add closing punctuation

(D415)


13-13: Missing type annotation for function argument mock_to_string

(ANN001)


13-13: Unused method argument: mock_to_string

(ARG002)


23-23: Missing type annotation for function argument mock_to_string

(ANN001)


23-23: Unused method argument: mock_to_string

(ARG002)

tests/geometries/boundaries_test.py (2)

20-20: LGTM: New import for GeometryError

The import of GeometryError from fastkml.exceptions is correctly added and necessary for the new test methods.


Line range hint 19-95: Summary: Improved error handling tests for boundary classes

These changes significantly enhance the test coverage for error handling in the OuterBoundaryIs and InnerBoundaryIs classes. The addition of a helper method _test_boundary_geometry_error promotes code reuse and maintainability. The new test methods effectively verify that both boundary classes raise GeometryError when instantiated with invalid geometry.

The code is well-structured, follows good testing practices, and aligns with the PR objective of improving test coverage. The minor suggestions for adding type annotations will further improve code quality and maintainability.

Great job on these improvements!

🧰 Tools
🪛 Ruff

78-78: Missing return type annotation for private function _test_boundary_geometry_error

Add return type annotation: None

(ANN202)


78-78: Missing type annotation for function argument boundary_class

(ANN001)


88-88: Missing return type annotation for public function test_outer_boundary_geometry_error

Add return type annotation: None

(ANN201)


92-92: Missing return type annotation for public function test_inner_boundary_geometry_error

Add return type annotation: None

(ANN201)

Comment on lines +54 to +71
def test_coordinates_subelement_getattr(self) -> None:
obj = Mock()
setattr(obj, 'coordinates', [(1.123456, 2.654321), (3.123456, 4.654321)])

element = Mock()

precision = 4
attr_name = 'coordinates'

assert coordinates_subelement(
obj=None,
attr_name=attr_name,
node_name=None,
element=element,
precision=precision,
verbosity=None,
default=None
) is None
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix discrepancy between setup and function call.

There's an important issue in this test that needs to be addressed. The test sets up a mock object with valid 2D coordinates, but then passes None as the obj parameter in the coordinates_subelement call. This means the test is not actually using the mock object with the valid coordinates you've set up.

To fix this, replace:

assert coordinates_subelement(
    obj=None,
    # ... other arguments ...
) is None

with:

assert coordinates_subelement(
    obj=obj,
    # ... other arguments ...
) is None

This change ensures that the test actually uses the mock object with the valid coordinates you've set up, making the test more effective and meaningful.

@cleder cleder changed the base branch from develop to 352-improve-test-coverage October 14, 2024 08:54
@apurvabanka
Copy link
Contributor Author

@cleder Are there any pending items for this PR?

@cleder cleder merged commit 537c518 into cleder:352-improve-test-coverage Oct 19, 2024
28 of 32 checks passed
@cleder
Copy link
Owner

cleder commented Oct 19, 2024

you did not see that mypy failed?

tests/kml_test.py:180: error: Function is missing a type annotation for one or more arguments  [no-untyped-def]
tests/kml_test.py:200: error: Argument 1 to "append" of "KML" has incompatible type "KML"; expected "Folder | Document | Placemark | GroundOverlay | PhotoOverlay"  [arg-type]
tests/helper_test.py:24: error: Function is missing a type annotation for one or more arguments  [no-untyped-def]
tests/helper_test.py:26: error: "node_text" does not return a value (it only ever returns None)  [func-returns-value]
tests/helper_test.py:27: error: Argument "obj" to "node_text" has incompatible type "None"; expected "_XMLObject"  [arg-type]
tests/helper_test.py:28: error: Argument "element" to "node_text" has incompatible type "None"; expected "Element"  [arg-type]
tests/helper_test.py:32: error: Argument "verbosity" to "node_text" has incompatible type "int"; expected "Verbosity"  [arg-type]
tests/helper_test.py:38: error: Function is missing a type annotation for one or more arguments  [no-untyped-def]
tests/helper_test.py:40: error: "float_attribute" does not return a value (it only ever returns None)  [func-returns-value]
tests/helper_test.py:41: error: Argument "obj" to "float_attribute" has incompatible type "None"; expected "_XMLObject"  [arg-type]
tests/helper_test.py:42: error: Argument "element" to "float_attribute" has incompatible type "str"; expected "Element"  [arg-type]
tests/helper_test.py:46: error: Argument "verbosity" to "float_attribute" has incompatible type "int"; expected "Verbosity"  [arg-type]
tests/helper_test.py:47: error: Argument "default" to "float_attribute" has incompatible type "str"; expected "float | None"  [arg-type]
tests/helper_test.py:52: error: Function is missing a type annotation for one or more arguments  [no-untyped-def]
tests/helper_test.py:54: error: "enum_attribute" does not return a value (it only ever returns None)  [func-returns-value]
tests/helper_test.py:55: error: Argument "obj" to "enum_attribute" has incompatible type "None"; expected "_XMLObject"  [arg-type]
tests/helper_test.py:56: error: Argument "element" to "enum_attribute" has incompatible type "str"; expected "Element"  [arg-type]
tests/helper_test.py:60: error: Argument "verbosity" to "enum_attribute" has incompatible type "int"; expected "Verbosity"  [arg-type]
tests/helper_test.py:61: error: Argument "default" to "enum_attribute" has incompatible type "str"; expected "Enum | None"  [arg-type]
tests/helper_test.py:65: error: Function is missing a return type annotation  [no-untyped-def]
tests/helper_test.py:65: note: Use "-> None" if function does not return a value
tests/helper_test.py:81: error: Function is missing a return type annotation  [no-untyped-def]
tests/helper_test.py:81: note: Use "-> None" if function does not return a value
tests/helper_test.py:98: error: Function is missing a type annotation for one or more arguments  [no-untyped-def]
tests/helper_test.py:105: error: Argument "name_spaces" to "attribute_float_kwarg" has incompatible type "str"; expected "dict[str, str]"  [arg-type]
tests/helper_test.py:108: error: Argument "classes" to "attribute_float_kwarg" has incompatible type "None"; expected "tuple[type[_XMLObject] | type[Enum] | type[bool] | type[int] | type[str] | type[float], ...]"  [arg-type]
tests/helper_test.py:115: error: Incompatible types in assignment (expression has type "None", variable has type "str")  [assignment]
tests/helper_test.py:[12](https://github.com/cleder/fastkml/actions/runs/11316861155/job/31488710465#step:5:13)1: error: Argument "name_spaces" to "subelement_enum_kwarg" has incompatible type "str"; expected "dict[str, str]"  [arg-type]
tests/helper_test.py:124: error: Argument "classes" to "subelement_enum_kwarg" has incompatible type "list[type[Color]]"; expected "tuple[type[_XMLObject] | type[Enum] | type[bool] | type[int] | type[str] | type[float], ...]"  [arg-type]
tests/helper_test.py:[13](https://github.com/cleder/fastkml/actions/runs/11316861155/job/31488710465#step:5:14)5: error: Argument "name_spaces" to "attribute_enum_kwarg" has incompatible type "str"; expected "dict[str, str]"  [arg-type]
tests/helper_test.py:138: error: Argument "classes" to "attribute_enum_kwarg" has incompatible type "list[type[Color]]"; expected "tuple[type[_XMLObject] | type[Enum] | type[bool] | type[int] | type[str] | type[float], ...]"  [arg-type]
tests/containers_test.py:96: error: Argument "style_url" to "Document" has incompatible type "str"; expected "StyleUrl | None"  [arg-type]
tests/geometries/multigeometry_test.py:306: error: Argument "geometry" to "MultiGeometry" has incompatible type "Point"; expected "MultiPoint | MultiLineString | MultiPolygon | GeometryCollection | None"  [arg-type]
tests/geometries/multigeometry_test.py:306: error: Argument "kml_geometries" to "MultiGeometry" has incompatible type "Coordinates"; expected "Iterable[Point | LineString | Polygon | LinearRing | MultiGeometry] | None"  [arg-type]
tests/geometries/linestring_test.py:47: error: Argument "geometry" to "LineString" has incompatible type "Point"; expected "LineString | None"  [arg-type]
tests/geometries/functions_test.py:13: error: Function is missing a type annotation for one or more arguments  [no-untyped-def]
tests/geometries/functions_test.py:[17](https://github.com/cleder/fastkml/actions/runs/11316861155/job/31488710465#step:5:18): error: Argument "error" to "handle_invalid_geometry_error" has incompatible type "type[ValueError]"; expected "Exception"  [arg-type]
tests/geometries/functions_test.py:23: error: Function is missing a type annotation for one or more arguments  [no-untyped-def]
tests/geometries/functions_test.py:25: error: "handle_invalid_geometry_error" does not return a value (it only ever returns None)  [func-returns-value]
tests/geometries/functions_test.py:26: error: Argument "error" to "handle_invalid_geometry_error" has incompatible type "type[ValueError]"; expected "Exception"  [arg-type]
tests/geometries/functions_test.py:47: error: Argument "node_name" to "coordinates_subelement" has incompatible type "None"; expected "str"  [arg-type]
tests/geometries/functions_test.py:63: error: "coordinates_subelement" does not return a value (it only ever returns None)  [func-returns-value]
tests/geometries/functions_test.py:64: error: Argument "obj" to "coordinates_subelement" has incompatible type "None"; expected "_XMLObject"  [arg-type]
tests/geometries/functions_test.py:66: error: Argument "node_name" to "coordinates_subelement" has incompatible type "None"; expected "str"  [arg-type]
tests/geometries/boundaries_test.py:78: error: Function is missing a type annotation  [no-untyped-def]
tests/geometries/boundaries_test.py:88: error: Function is missing a return type annotation  [no-untyped-def]
tests/geometries/boundaries_test.py:88: note: Use "-> None" if function does not return a value
tests/geometries/boundaries_test.py:92: error: Function is missing a return type annotation  [no-untyped-def]
tests/geometries/boundaries_test.py:92: note: Use "-> None" if function does not return a value
Found 45 errors in 7 files (checked 56 source files)

It took me a couple of hours to sort this all out: 18e6b5b

@cleder
Copy link
Owner

cleder commented Oct 19, 2024

I also had to improve some test, so they were asserting something non-trivial, and removed tests that were not of value

@apurvabanka
Copy link
Contributor Author

@cleder For my PR I just ran the Test Coverage for the pytest. I might have missed some setup steps. How do you run mypy?

@cleder
Copy link
Owner

cleder commented Oct 20, 2024

See contributing.rst

mypy fastkml tests

or

pre-commit run --all

@cleder cleder linked an issue Oct 20, 2024 that may be closed by this pull request
@coderabbitai coderabbitai bot mentioned this pull request Oct 22, 2024
This was referenced Nov 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Improve test coverage
3 participants