Skip to content

Add defensive checks and tests for single-array JSON spatial query responses#206

Merged
SvenVw merged 3 commits into
developmentfrom
FDM205
Jul 29, 2025
Merged

Add defensive checks and tests for single-array JSON spatial query responses#206
SvenVw merged 3 commits into
developmentfrom
FDM205

Conversation

@SvenVw
Copy link
Copy Markdown
Collaborator

@SvenVw SvenVw commented Jul 29, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of field location checks to prevent errors when processing empty or irregular data responses.
  • Tests
    • Added test cases verifying behavior for fields inside or outside designated areas, including scenarios with specific data formats and farm derogation status.

Closes #205

@SvenVw SvenVw self-assigned this Jul 29, 2025
@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Jul 29, 2025

⚠️ No Changeset found

Latest commit: e12f2af

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 29, 2025

Walkthrough

A defensive check was added to two functions handling spatial queries to prevent crashes when unexpected single-array JSON responses are received instead of nested arrays. Corresponding test cases were introduced to verify correct behavior when the response structure varies, particularly for edge cases outside designated areas.

Changes

Cohort / File(s) Change Summary
Defensive checks in spatial query helpers
fdm-calculator/src/norms/nl/2025/dierlijke-mest-gebruiksnorm.ts, fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.ts
Added checks to ensure JSON responses are non-empty arrays before accessing nested elements, preventing runtime errors when receiving unexpected response structures.
Test coverage for edge-case responses
fdm-calculator/src/norms/nl/2025/dierlijke-mest-gebruiksnorm.test.ts, fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.test.ts
Introduced new tests to verify correct function behavior when receiving single-array JSON responses, confirming no crashes and correct boolean outcomes.

Sequence Diagram(s)

sequenceDiagram
    participant TestSuite
    participant HelperFunction
    participant GeoJSONResponse

    TestSuite->>HelperFunction: Call with centroid (edge case)
    HelperFunction->>GeoJSONResponse: Query for spatial area inclusion
    GeoJSONResponse-->>HelperFunction: Return single array or nested array
    HelperFunction->>HelperFunction: Check if response is non-empty array
    alt Non-empty and nested
        HelperFunction->>TestSuite: Return true
    else Empty or single array
        HelperFunction->>TestSuite: Return false
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Assessment against linked issues

Objective Addressed Explanation
Defensive checks for single vs. double array JSON responses in spatial query helpers (isFieldInGWGBebied, isFieldInsideNVGebied) [#205]
Prevent crashes when receiving unexpected empty or single array responses in spatial query functions [#205]

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes identified.

Possibly related PRs

Suggested reviewers

  • gerardhros

Poem

A hop and a skip through the code we go,
Guarding our arrays from a runtime woe.
With tests in tow and checks in place,
No more crashes—just a safer space!
🐇✨

— A rabbit who loves robust code

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b6bf9b7 and e12f2af.

📒 Files selected for processing (1)
  • fdm-calculator/src/norms/nl/2025/dierlijke-mest-gebruiksnorm.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • fdm-calculator/src/norms/nl/2025/dierlijke-mest-gebruiksnorm.test.ts
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch FDM205

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@codecov
Copy link
Copy Markdown

codecov Bot commented Jul 29, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.04%. Comparing base (47248dc) to head (e12f2af).
⚠️ Report is 4 commits behind head on development.

Additional details and impacted files
@@             Coverage Diff              @@
##           development     #206   +/-   ##
============================================
  Coverage        94.04%   94.04%           
============================================
  Files               85       85           
  Lines            12628    12632    +4     
  Branches          1290     1291    +1     
============================================
+ Hits             11876    11880    +4     
  Misses             750      750           
  Partials             2        2           
Flag Coverage Δ
fdm-calculator 94.96% <100.00%> (+<0.01%) ⬆️
fdm-core 93.38% <ø> (ø)
fdm-data 94.21% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot changed the title @coderabbitai Add defensive checks and tests for single-array JSON spatial query responses Jul 29, 2025
Copy link
Copy Markdown
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

🧹 Nitpick comments (1)
fdm-calculator/src/norms/nl/2025/dierlijke-mest-gebruiksnorm.test.ts (1)

83-83: Fix typo in test description.

There's a spelling error: "responce" should be "response".

-    it("should return the default norm value for derogation outside Grondwaterbeschermingsgebied and inside NV-gebied, but with single array responce (see #205)", async () => {
+    it("should return the default norm value for derogation outside Grondwaterbeschermingsgebied and inside NV-gebied, but with single array response (see #205)", async () => {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 47248dc and b6bf9b7.

📒 Files selected for processing (4)
  • fdm-calculator/src/norms/nl/2025/dierlijke-mest-gebruiksnorm.test.ts (1 hunks)
  • fdm-calculator/src/norms/nl/2025/dierlijke-mest-gebruiksnorm.ts (1 hunks)
  • fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.test.ts (1 hunks)
  • fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (4)
fdm-calculator/src/norms/nl/2025/dierlijke-mest-gebruiksnorm.test.ts (2)

Learnt from: SvenVw
PR: #156
File: fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.ts:295-303
Timestamp: 2025-07-21T12:06:07.070Z
Learning: Functions in the fdm-calculator with "NL2025" in their names are specifically designed for Netherlands 2025 agricultural norms calculation and hardcoded 2025 dates are appropriate in this context, as different years would have separate calculation modules.

Learnt from: SvenVw
PR: #9
File: fdm-data/src/cultivations/index.test.ts:57-59
Timestamp: 2024-11-27T12:15:36.425Z
Learning: In fdm-data/src/cultivations/index.test.ts, the fdm object created by drizzle does not have an .end() method. Cleanup code should not attempt to call fdm.end();.

fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.ts (2)

Learnt from: SvenVw
PR: #156
File: fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.ts:295-303
Timestamp: 2025-07-21T12:06:07.070Z
Learning: Functions in the fdm-calculator with "NL2025" in their names are specifically designed for Netherlands 2025 agricultural norms calculation and hardcoded 2025 dates are appropriate in this context, as different years would have separate calculation modules.

Learnt from: SvenVw
PR: #67
File: fdm-app/app/routes/farm.create.$b_id_farm.fields.$b_id.tsx:601-610
Timestamp: 2025-01-31T15:05:14.310Z
Learning: The updateField function in fdm-core has optional parameters after fdm and b_id. The TypeScript definitions might show 8 required parameters due to a potential version mismatch.

fdm-calculator/src/norms/nl/2025/dierlijke-mest-gebruiksnorm.ts (3)

Learnt from: SvenVw
PR: #156
File: fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.ts:295-303
Timestamp: 2025-07-21T12:06:07.070Z
Learning: Functions in the fdm-calculator with "NL2025" in their names are specifically designed for Netherlands 2025 agricultural norms calculation and hardcoded 2025 dates are appropriate in this context, as different years would have separate calculation modules.

Learnt from: SvenVw
PR: #9
File: fdm-data/src/cultivations/index.test.ts:57-59
Timestamp: 2024-11-27T12:15:36.425Z
Learning: In fdm-data/src/cultivations/index.test.ts, the fdm object created by drizzle does not have an .end() method. Cleanup code should not attempt to call fdm.end();.

Learnt from: SvenVw
PR: #9
File: fdm-data/src/cultivations/catalogues/brp.ts:9-19
Timestamp: 2024-11-27T10:28:18.683Z
Learning: When importing JSON data like brp.json that is fully typed and controlled within the codebase, and TypeScript's static analysis is sufficient, additional runtime validation may not be necessary.

fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.test.ts (1)

Learnt from: SvenVw
PR: #156
File: fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.ts:295-303
Timestamp: 2025-07-21T12:06:07.070Z
Learning: Functions in the fdm-calculator with "NL2025" in their names are specifically designed for Netherlands 2025 agricultural norms calculation and hardcoded 2025 dates are appropriate in this context, as different years would have separate calculation modules.

🧬 Code Graph Analysis (2)
fdm-calculator/src/norms/nl/2025/dierlijke-mest-gebruiksnorm.test.ts (1)
fdm-calculator/src/norms/nl/2025/dierlijke-mest-gebruiksnorm.ts (1)
  • getNL2025DierlijkeMestGebruiksNorm (73-102)
fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.test.ts (1)
fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.ts (1)
  • isFieldInNVGebied (25-52)
🔇 Additional comments (4)
fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.test.ts (1)

24-28: LGTM! Good test coverage for the single array response edge case.

This test case properly verifies the defensive check added to handle issue #205, ensuring that isFieldInNVGebied returns false when the API returns a single array response for coordinates outside the NV Gebied. The test follows the established pattern and includes a helpful reference to the issue number.

fdm-calculator/src/norms/nl/2025/dierlijke-mest-gebruiksnorm.ts (1)

35-40: Excellent defensive programming to handle API response variations.

The added check prevents runtime errors when the external API returns a single array instead of the expected nested array structure. This implementation correctly handles the edge case described in issue #205 by:

  1. Verifying the response array has elements before accessing nested properties
  2. Safely accessing json[0][0] only when the array is non-empty
  3. Returning false when the expected nested structure is not present

The solution is consistent with the similar fix applied to isFieldInNVGebied.

fdm-calculator/src/norms/nl/2025/dierlijke-mest-gebruiksnorm.test.ts (1)

84-96: LGTM! Good integration test for the defensive check.

This test case effectively verifies that the defensive logic added to handle single array responses works correctly within the full norm calculation flow. The expected values (190 for derogation in NV Gebied) align with the business logic, and the test includes a helpful reference to issue #205.

fdm-calculator/src/norms/nl/2025/stikstofgebruiksnorm.ts (1)

41-47: Excellent defensive check implementation addressing issue #205.

The added length validation prevents runtime errors when the external API returns a single array instead of the expected nested array structure. This implementation:

  1. Safely checks array length before accessing nested elements
  2. Only attempts to access json[0][0] when the array is non-empty
  3. Returns false when the expected nested feature is not present

This change complements the identical fix in isFieldInGWGBGebied and provides consistent error handling across both geographical query functions.

@SvenVw SvenVw requested a review from BoraIneviNMI July 29, 2025 11:03
Copy link
Copy Markdown
Collaborator

@BoraIneviNMI BoraIneviNMI 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. I have checked it and the issue seems to be fixed now.

@SvenVw SvenVw merged commit 26d1142 into development Jul 29, 2025
10 checks passed
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.

isFieldInGWGBebied can crash if it gets unexpectedly an single array instead of double array

2 participants