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

Implements flight route tests #41

Merged
merged 3 commits into from
Dec 14, 2024
Merged

Implements flight route tests #41

merged 3 commits into from
Dec 14, 2024

Conversation

GabrielBarberini
Copy link
Collaborator

@GabrielBarberini GabrielBarberini commented Dec 7, 2024

Implements flight route tests

==================================================================== test session starts =====================================================================
platform darwin -- Python 3.13.0, pytest-8.3.3, pluggy-1.5.0
rootdir: /Users/gabriel.barberini/Documents/Projects/Infinity-API
configfile: pyproject.toml
plugins: anyio-4.6.2.post1
collected 94 items

tests/test_routes/test_environments_route.py ...................                                                                                       [ 20%]
tests/test_routes/test_flights_route.py .......................                                                                                        [ 44%]
tests/test_routes/test_motors_route.py ..........................                                                                                      [ 72%]
tests/test_routes/test_rockets_route.py ..........................                                                                                     [100%]
============================================================== 94 passed, 314 warnings in 1.43s ==============================================================

Summary by CodeRabbit

  • New Features
    • Updated API endpoints for retrieving model summaries and Rocketpy models to use GET requests.
  • Bug Fixes
    • Removed obsolete test fixtures to streamline testing setup.
  • Documentation
    • Revised API documentation in the README to reflect changes in endpoint structure.
  • Chores
    • Incremented project version to 2.3.0 and updated pylint rules in the configuration.

@GabrielBarberini GabrielBarberini changed the title Refactor tests Implements flight route tests Dec 7, 2024
Copy link
Contributor

coderabbitai bot commented Dec 7, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces several changes across multiple files, including the removal of the test_routes directory and its contents, indicating a shift in testing strategy. The API documentation in README.md is updated to reflect a new endpoint structure for retrieving Rocketpy models. Additionally, the Rocket class in lib/models/rocket.py is enhanced with new required and optional parameters. The pyproject.toml file is updated to version 2.3.0, with new pylint rules added to the disabled list. Various test fixtures related to motors and tanks are removed or modified in the test files.

Changes

File Change Summary
README.md - Updated API endpoints from POST to GET for /summary/model/:id and /model/:id/rocketpy.
- Removed test_routes directory.
lib/models/rocket.py - Modified Rocket class to include new required and optional parameters, and enhanced flexibility of inertia.
pyproject.toml - Updated project version to 2.3.0.
- Added new pylint rules to the disabled list.
tests/test_routes/conftest.py - Added multiple pytest fixtures for testing rocket components (e.g., stub_env, stub_motor).
tests/test_routes/test_environments_route.py - Removed stub_env fixture affecting multiple test functions.
tests/test_routes/test_flights_route.py - Introduced new tests for flight-related routes.
tests/test_routes/test_motors_route.py - Removed several motor and tank-related fixtures.
tests/test_routes/test_rockets_route.py - Removed multiple fixtures and updated test_read_rocket function to handle motor information differently.

Possibly related PRs

  • API Refactoring #20: The changes in the main PR regarding the API endpoint modifications and the removal of the test_routes directory relate to the overall refactoring of the API in the retrieved PR, which includes updates to method signatures and error handling in the RocketController, FlightController, and other related classes.

Suggested reviewers

  • Lucas-Prates
  • MateusStano
  • BitKnigth
  • luimot
  • phmbressan
  • aasitvora99
  • Gui-FernandesBR

Poem

In the land of rockets, we soar so high,
With models and tests, we touch the sky.
The paths have shifted, new routes we find,
With fixtures removed, we leave old ways behind.
So here’s to the changes, both bold and bright,
A journey of rockets, taking flight! 🚀✨

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. This feature will be included in our Pro Plan when released.


📜 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 1e58b4a and 8a8e680.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • lib/models/rocket.py (1 hunks)
  • tests/test_routes/test_flights_route.py (1 hunks)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
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: 5

🧹 Outside diff range and nitpick comments (4)
pyproject.toml (1)

46-49: Consider more targeted rule suppressions

While some of these new pylint suppressions make sense in a testing context (particularly redefined-outer-name for pytest fixtures), others might be masking potential code quality issues:

  1. too-many-arguments and too-many-positional-arguments: These rules typically flag functions that might benefit from refactoring. Consider:

    • Using dataclasses or parameter objects for complex parameter sets
    • Breaking down complex functions into smaller ones
  2. import-error: This should only be needed if you have conditional imports or complex import paths. Consider:

    • Adding proper path configurations
    • Using try/except for conditional imports instead of globally disabling the check

Instead of globally disabling these rules, consider:

  1. Using inline suppressions (# pylint: disable=rule-name) only where necessary
  2. Creating a separate pylint configuration for test files
  3. Refactoring complex functions to address the root cause

Would you like assistance in implementing any of these suggestions?

lib/models/rocket.py (1)

21-24: Consider refining the implementation of the __eq__ method

The custom __eq__ method compares the dictionaries of two Rocket instances using self.dict() == other.dict(). While this works for simple comparisons, it may not account for differences in fields that contain mutable data types or nested models, which could lead to unexpected behavior.

Consider leveraging Pydantic's built-in comparison methods or ensure that all fields are comparable and immutable. Alternatively, you might want to define the __hash__ method if instances of Rocket need to be used in hashed collections.

tests/test_routes/test_rockets_route.py (1)

107-115: Simplify nested context managers for better readability

You can improve code readability by combining the nested with statements into a single line:

with patch.object(RocketController, 'create_rocket', return_value=RocketCreated(rocket_id='123')) as mock_create_rocket, \
     patch.object(Motor, 'set_motor_kind', side_effect=None) as mock_set_motor_kind:
    # Rest of the code

This reduces indentation and makes the code cleaner.

lib/routes/rocket.py (1)

Documentation update needed for API endpoint change

The route path change is reflected in the test files, but the API documentation in the README.md needs to be updated. The sequence diagram still shows the old pattern /model/:id instead of the new /:id/model pattern.

  • Update the sequence diagram in README.md that shows:
    User ->> API: POST /model/:id/rocketpy
    
    Loading
    to match the new pattern:
    User ->> API: POST /:id/rocketpy
    
    Loading
🔗 Analysis chain

Line range hint 80-89: LGTM: Route path follows RESTful conventions

The updated route path better follows RESTful conventions by using the resource/id/format pattern. This breaking change is acceptable as per previous team decisions.

Let's verify that all documentation is updated to reflect this change:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any outdated route references
rg -i "rocketpy/\{.*id\}" --type md
rg -i "rocketpy/.*id" --type rst

Length of output: 221


Script:

#!/bin/bash
# Search for any documentation files first
fd -e md -e rst -e txt

# Then search for the old route pattern in all text files
rg -t txt -t md -t rst "rocketpy/[^/]+" 

# Also search for potential API documentation
fd -g "*api*" -g "*doc*" -g "*swagger*" -g "*openapi*" -e yaml -e json -e md -e rst

Length of output: 440


Script:

#!/bin/bash
# Check contents of README and other docs for any API references
cat README.md
cat CONTRIBUTING.md

# Look for API specs or documentation in common locations
fd . -t f -e yaml -e json | grep -i "api\|swagger\|openapi"

# Search for any test files that might reference the API endpoint
fd -e py -e json | xargs rg "rocketpy"

Length of output: 22322

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f3e0f56 and 89d0c3c.

📒 Files selected for processing (15)
  • .github/workflows/pylint.yml (1 hunks)
  • Makefile (2 hunks)
  • README.md (1 hunks)
  • lib/controllers/flight.py (1 hunks)
  • lib/controllers/rocket.py (1 hunks)
  • lib/models/aerosurfaces.py (1 hunks)
  • lib/models/rocket.py (2 hunks)
  • lib/routes/flight.py (2 hunks)
  • lib/routes/rocket.py (1 hunks)
  • pyproject.toml (1 hunks)
  • tests/test_routes/conftest.py (1 hunks)
  • tests/test_routes/test_environments_route.py (0 hunks)
  • tests/test_routes/test_flights_route.py (1 hunks)
  • tests/test_routes/test_motors_route.py (0 hunks)
  • tests/test_routes/test_rockets_route.py (1 hunks)
💤 Files with no reviewable changes (2)
  • tests/test_routes/test_environments_route.py
  • tests/test_routes/test_motors_route.py
✅ Files skipped from review due to trivial changes (1)
  • .github/workflows/pylint.yml
🧰 Additional context used
📓 Learnings (1)
lib/routes/rocket.py (1)
Learnt from: GabrielBarberini
PR: RocketPy-Team/Infinity-API#38
File: lib/routes/motor.py:75-75
Timestamp: 2024-11-15T15:12:21.314Z
Learning: When modifying API route paths in `lib/routes/motor.py`, changing from `/rocketpy/{motor_id}` to `/{motor_id}/rocketpy` is acceptable when no external consumers are affected. It's acceptable to introduce this breaking change if the team has decided to adopt the new approach, provided that the `README` and related documentation are updated accordingly.
🔇 Additional comments (10)
pyproject.toml (1)

Line range hint 2-3: Verify semantic versioning compliance

The version bump to 2.3.0 suggests a minor feature addition. Given this PR is primarily about test refactoring, please verify if this version increment aligns with semantic versioning principles.

Makefile (1)

1-2: LGTM! Good separation of formatting and linting tasks.

The separation of format and lint targets is a good practice as it clearly distinguishes between:

  • Formatting tools (black, ruff) that automatically fix code style
  • Linting tools (flake8, pylint) that check for potential errors
tests/test_routes/test_rockets_route.py (2)

174-175: Avoid modifying shared fixtures in place to prevent side effects

In test_create_generic_motor_rocket, you update the stub_rocket fixture in place:

stub_rocket.update({'motor': stub_motor})

Modifying the shared stub_rocket fixture can affect other tests that rely on it. To prevent unintended side effects, make a copy of the fixture before updating it.


198-199: Avoid modifying shared fixtures in place to prevent side effects

Similar to previous comments, in test_create_liquid_motor_level_tank_rocket, you're modifying stub_motor and stub_rocket fixtures directly:

stub_motor.update({'tanks': [stub_level_tank]})
stub_rocket.update({'motor': stub_motor})

Create copies before making these updates to avoid side effects in other tests.

lib/models/aerosurfaces.py (1)

6-12: Parachute model is well-defined with proper validations

The Parachute class is correctly defined using Pydantic BaseModel, with appropriate use of Field to enforce validations on cd_s, sampling_rate, and lag. The use of type hints and constraints ensures data integrity.

lib/routes/rocket.py (1)

76-76: LGTM: Parameter ordering aligns with controller interface

The updated parameter order in the controller call matches the controller's interface, maintaining consistency across the codebase.

lib/routes/flight.py (2)

Line range hint 62-89: LGTM: Consistent route path structure

The route path change maintains consistency with the rocket routes and follows the same RESTful conventions.


149-149: LGTM: Consistent parameter ordering

The parameter ordering in the controller call maintains consistency with the rocket routes and matches the controller's interface.

lib/controllers/rocket.py (1)

173-173: Parameter reordering improves API consistency

The parameter reordering in update_rocket_by_id makes the method signature more consistent with REST API conventions and other methods in the class where ID is the first parameter.

Let's verify all callers of this method have been updated:

✅ Verification successful

Let me analyze the method signatures more carefully by getting the full context of these calls.


Parameter reordering is correctly implemented across the codebase

The parameter reordering in update_rocket_by_id has been properly handled across all its usages:

  • In lib/routes/rocket.py, the method is called with correct parameter order: RocketController.update_rocket_by_id(rocket_id, rocket)
  • In lib/repositories/rocket.py, the repository method has a different signature as it's not the same method, just similar name
  • In lib/controllers/rocket.py, the internal call to repository's method is correct as it only passes rocket_id
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for calls to update_rocket_by_id to ensure they match the new signature
rg -A 2 "update_rocket_by_id\(" --type py

Length of output: 852


Script:

#!/bin/bash
# Get more context around the update_rocket_by_id calls
rg -B 5 -A 10 "update_rocket_by_id\(" --type py

Length of output: 3658

lib/controllers/flight.py (1)

186-186: Parameter reordering aligns with class conventions

The parameter reordering in update_flight_by_id improves consistency by:

  1. Matching the pattern of other update methods in the class (update_env_by_flight_id, update_rocket_by_flight_id)
  2. Following the same convention as RocketController

Let's verify all callers of this method have been updated:

✅ Verification successful

Let me verify the implementation details of the repository method to ensure compatibility.


Let me try a different approach to check the repository implementation.


Let me check the route implementation to verify the parameter order in the controller call.


Parameter reordering is correctly implemented across the codebase

The verification shows that:

  1. The controller's update_flight_by_id method has been updated to accept parameters as (cls, flight_id: str, flight: Flight).
  2. The route handler in lib/routes/flight.py correctly calls the controller with the new parameter order: FlightController.update_flight_by_id(flight_id, flight).
  3. The repository's update_flight_by_id method has a compatible signature that accepts flight_id as its parameter, with the flight data being accessed through the instance property.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for calls to update_flight_by_id to ensure they match the new signature
rg -A 2 "update_flight_by_id\(" --type py

Length of output: 852


Script:

#!/bin/bash
# Check the implementation of update_flight_by_id in the repository
ast-grep --pattern 'async def update_flight_by_id($$$)'

Length of output: 57


Script:

#!/bin/bash
# Get the content of the repository file to check the method signature
cat lib/repositories/flight.py

Length of output: 6605


Script:

#!/bin/bash
# Get the content of the routes file to check how the controller is called
cat lib/routes/flight.py

Length of output: 4256

Makefile Outdated Show resolved Hide resolved
tests/test_routes/test_flights_route.py Show resolved Hide resolved
tests/test_routes/test_rockets_route.py Outdated Show resolved Hide resolved
tests/test_routes/conftest.py Show resolved Hide resolved
README.md Outdated Show resolved Hide resolved
@phmbressan phmbressan self-requested a review December 13, 2024 20:03
Comment on lines 21 to 24
def __eq__(self, other):
if not isinstance(other, Rocket):
return False
return self.dict() == other.dict()
Copy link

@phmbressan phmbressan Dec 13, 2024

Choose a reason for hiding this comment

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

Just to clear some things up for me: Why the override of the equality operator? In which situations will this equality check be used?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Truth be said this is actually a hack to make this pass:

mock_update_flight.assert_called_once_with(
            '123', rocket=Rocket(**stub_rocket)
        )

But definitely should be refactored.
I'll try to think in a non-verbose yet functional way to overcome that, thanks for bringing this.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

patched here 8a8e680

tests/test_routes/conftest.py Show resolved Hide resolved
tests/test_routes/test_flights_route.py Show resolved Hide resolved
phmbressan
phmbressan previously approved these changes Dec 13, 2024
@GabrielBarberini GabrielBarberini merged commit a03a578 into master Dec 14, 2024
2 checks passed
@GabrielBarberini GabrielBarberini deleted the refactor_tests branch December 14, 2024 12:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants