Skip to content

feat(tests): test authentication #19

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

Merged
merged 3 commits into from
Jun 27, 2025
Merged

feat(tests): test authentication #19

merged 3 commits into from
Jun 27, 2025

Conversation

jeandemeusy
Copy link
Owner

@jeandemeusy jeandemeusy commented Jun 27, 2025

Summary by CodeRabbit

  • New Features

    • Added a new authenticated API endpoint for testing authentication handling.
    • Introduced a test to verify authenticated and unauthenticated API access.
  • Bug Fixes

    • Improved API client to handle cases where no authentication token is provided, preventing potential errors.
  • Chores

    • Switched test configurations to use hardcoded constants for server connection details.
    • Removed unused environment variable loading and related dependency.
    • Cleaned up whitespace and removed unused fixtures in test files.
    • Updated test setup and fixtures to reflect new authentication handling.

@jeandemeusy jeandemeusy self-assigned this Jun 27, 2025
Copy link

coderabbitai bot commented Jun 27, 2025

Walkthrough

The changes make the token parameter optional in the ApiLib class and update its usage to handle missing tokens safely. Tests and fixtures are refactored to accommodate this, including new tests for authenticated endpoints. Unused fixtures and dotenv dependency are removed, and some whitespace is cleaned up in test files.

Changes

File(s) Change Summary
api_lib/api_lib.py Made token optional in ApiLib constructor and updated _call to handle missing token safely.
test/config/rest_api.py Added /authenticated endpoint; updated run_server to accept host/port arguments.
test/conftest.py Removed dotenv, hardcoded config constants, refactored fixtures, added api_not_authenticated fixture.
test/test_api_lib.py Added test_authenticated_call to verify authenticated vs unauthenticated API calls.
test/test_headers/test_accept.py Removed trailing blank line.
test/test_objects/test_request.py Removed request_object fixture; instantiate RequestClass directly in each test.
test/test_objects/test_response.py Removed trailing blank lines from several test functions.
pyproject.toml Removed "dotenv" from development dependencies.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Function
    participant ApiLib as ApiLib Instance
    participant Server as REST API Server

    Test->>ApiLib: Create instance (with or without token)
    Test->>ApiLib: Call _call("/authenticated")
    ApiLib->>Server: HTTP GET /authenticated (with/without Authorization header)
    Server-->>ApiLib: 200 OK (if authorized) or 401 Unauthorized (if not)
    ApiLib-->>Test: Return response
Loading

Possibly related PRs

Poem

In the warren of code, a token may hide,
Now optional, it hops at your side.
Tests check the gate—are you friend or unknown?
With headers and fixtures, new pathways are shown.
Dotenv is gone, but the carrots remain—
🥕 Auth or not, the API runs just the same!


📜 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 ebd3ad7 and 4edcf1a.

⛔ Files ignored due to path filters (1)
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • pyproject.toml (0 hunks)
  • test/conftest.py (1 hunks)
💤 Files with no reviewable changes (1)
  • pyproject.toml
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/conftest.py
✨ Finishing Touches
  • 📝 Generate Docstrings

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (5)
test/.env (2)

3-3: Fix the typo in the environment variable name.

The variable name REST_API_TOKN appears to be missing the 'E' in TOKEN. Consider renaming it to REST_API_TOKEN for consistency and clarity.

-REST_API_TOKN="test_token"
+REST_API_TOKEN="test_token"

1-3: Consider adding a comment about the test-only nature of these credentials.

While this is clearly in a test directory, adding a comment clarifying that these are test-only credentials would improve clarity and prevent accidental misuse.

+# Test environment configuration - DO NOT use in production
 REST_API_HOST="localhost"
 REST_API_PORT="5001"
 REST_API_TOKN="test_token"
test/config/rest_api.py (1)

10-16: Consider enhancing the authentication validation.

The current implementation only checks for the presence of an Authorization header but doesn't validate its content. For more realistic testing, consider validating the token value against the expected test token.

 @app.route("/authenticated", methods=["GET"])
 def authenticated():
     token = request.headers.get("Authorization")
-    if not token:
+    if not token or token != "Bearer test_token":
         return jsonify({"error": "Unauthorized"}), 401
     return jsonify({"message": "Authenticated successfully"}), 200
test/test_api_lib.py (1)

91-97: Consider testing response content for completeness.

While status code verification is essential, consider also asserting the response content to ensure the endpoint returns expected messages.

 @pytest.mark.asyncio
 async def test_authenticated_call(api: ApiLib, api_not_authenticated: ApiLib):
     status, resp = await api._call(Method.GET, "/authenticated")
     assert status == 200
+    assert resp["message"] == "Authenticated successfully"

     status, resp = await api_not_authenticated._call(Method.GET, "/authenticated")
     assert status == 401
+    assert resp["error"] == "Unauthorized"
test/test_objects/test_request.py (1)

5-5: Consider extracting test values as constants for maintainability.

While direct instantiation is good, the repeated hardcoded values across tests could be improved by extracting them as constants at the module level.

+# Test constants
+TEST_FIELD_VALUE = "test_value"
+TEST_PATH_VALUE = "path_value"
+
 def test_request_data_as_dict():
-    request_object = RequestClass("test_value", "path_value")
+    request_object = RequestClass(TEST_FIELD_VALUE, TEST_PATH_VALUE)

Apply similar changes to other test functions for consistency.

Also applies to: 17-17, 22-22, 27-27

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e560a16 and ebd3ad7.

📒 Files selected for processing (8)
  • api_lib/api_lib.py (2 hunks)
  • test/.env (1 hunks)
  • test/config/rest_api.py (2 hunks)
  • test/conftest.py (2 hunks)
  • test/test_api_lib.py (1 hunks)
  • test/test_headers/test_accept.py (0 hunks)
  • test/test_objects/test_request.py (2 hunks)
  • test/test_objects/test_response.py (0 hunks)
💤 Files with no reviewable changes (2)
  • test/test_headers/test_accept.py
  • test/test_objects/test_response.py
🧰 Additional context used
🧬 Code Graph Analysis (3)
test/test_api_lib.py (3)
test/conftest.py (2)
  • api (21-22)
  • api_not_authenticated (31-32)
api_lib/api_lib.py (2)
  • ApiLib (14-201)
  • _call (28-57)
api_lib/method.py (1)
  • Method (4-9)
api_lib/api_lib.py (1)
api_lib/headers/authorization.py (1)
  • Authorization (4-5)
test/test_objects/test_request.py (2)
test/config/request.py (1)
  • RequestClass (13-16)
api_lib/objects/request.py (2)
  • as_header_string (26-27)
  • as_query_parameters (30-31)
🔇 Additional comments (9)
test/config/rest_api.py (2)

4-4: LGTM: Import addition is appropriate.

The addition of request to the Flask imports is correct and necessary for the new authenticated endpoint.


57-59: LGTM: Function parameterization improves flexibility.

The updated run_server function with host and port parameters provides better configurability for the test infrastructure.

api_lib/api_lib.py (3)

20-20: LGTM: Type annotation correctly reflects optional token.

The change to Optional[Authorization] with default None properly supports unauthenticated API clients.


44-44: LGTM: Safe token header access prevents AttributeError.

The use of getattr(self.token, "header", {}) correctly handles the case when self.token is None, providing an empty dictionary as fallback headers.


20-25: Verify consistency with the typo in environment variable name.

The constructor accepts an Authorization token, but the test environment file uses REST_API_TOKN (missing 'E'). Ensure the environment variable name is corrected to maintain consistency.

#!/bin/bash
# Description: Check if the environment variable typo affects other files

# Search for usage of the misspelled environment variable name
rg "REST_API_TOKN" --type py

# Search for the correct spelling to see if there's inconsistency
rg "REST_API_TOKEN" --type py
test/test_api_lib.py (1)

91-97: LGTM: Comprehensive authentication test with both positive and negative cases.

The test correctly verifies that:

  • Authenticated requests to /authenticated endpoint return 200 status
  • Unauthenticated requests return 401 status

This provides good coverage for the new optional authentication feature.

test/test_objects/test_request.py (1)

4-5: LGTM: Direct instantiation simplifies test setup.

The change from fixture-based to direct instantiation of RequestClass is clear and reduces unnecessary test dependencies.

test/conftest.py (2)

31-32: LGTM! Good addition of unauthenticated fixture.

The api_not_authenticated fixture is well-implemented and provides a clean way to test API calls without authentication tokens.


37-43: Verify the server startup time reduction.

The server startup wait time was reduced from 1 second to 0.2 seconds. While this improves test performance, ensure this is sufficient for reliable server startup across different environments.

Consider running tests multiple times to verify 0.2 seconds is consistently adequate:

#!/bin/bash
# Description: Test server startup reliability with reduced wait time
# Expected: All tests should pass consistently

for i in {1..10}; do
  echo "Test run $i:"
  python -m pytest test/ -v --tb=short
  if [ $? -ne 0 ]; then
    echo "Test failed on run $i"
    break
  fi
done

@jeandemeusy jeandemeusy merged commit f60d83f into master Jun 27, 2025
2 checks passed
@jeandemeusy jeandemeusy deleted the test-authentication branch June 27, 2025 12:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant