Skip to content

feat: Add typing and split fake client code#2438

Merged
rnetser merged 7 commits intomainfrom
typing-and-fixes
Jul 10, 2025
Merged

feat: Add typing and split fake client code#2438
rnetser merged 7 commits intomainfrom
typing-and-fixes

Conversation

@myakove
Copy link
Collaborator

@myakove myakove commented Jul 9, 2025

FakeClient:

  1. add typing
  2. split to files
  3. fix many cases

Summary by CodeRabbit

  • New Features

    • Introduced a modular and extensible fake Kubernetes client with components for resource management, dynamic client simulation, in-memory storage, realistic status generation, and exception handling.
    • Added support for registering custom resources and simulating common Kubernetes API behaviors and errors.
    • Included detailed resource discovery, CRUD operations, and namespace management in the fake client.
  • Bug Fixes

    • Improved handling and simulation of Kubernetes exceptions for better compatibility.
  • Documentation

    • Major updates to documentation for the fake Kubernetes client, including clearer usage instructions, examples, and streamlined guidance.
    • Added new README section highlighting the fake Kubernetes client features.
  • Chores

    • Updated configuration and versioning files.
    • Adjusted pre-commit and linting settings for new and excluded files.
  • Refactor

    • Removed the previous monolithic fake dynamic client implementation and replaced it with a modular structure, improving maintainability and clarity.
  • Revert

    • Deprecated and removed outdated factory functions and version strings from the public API.

@coderabbitai
Copy link

coderabbitai bot commented Jul 9, 2025

Walkthrough

This change refactors the fake Kubernetes client by splitting its previous monolithic implementation into multiple focused modules, reorganizes public exports, updates documentation, and makes minor configuration adjustments. It introduces new classes and files for configuration, dynamic client, resource management, storage, exceptions, and status generation, while removing the old single-file implementation.

Changes

Files/Paths Change Summary
.flake8, .pre-commit-config.yaml Updated flake8 exclusions to add shutil; pre-commit config updated to exclude a specific JSON file from detect-secrets scan.
README.md, fake_kubernetes_client/README.md Added a section about the fake Kubernetes client in the main README; extensively revised the fake client README for clarity, updated examples, and removed outdated or redundant sections.
class_generator/cluster_version.txt Updated cluster version from v1.32.3 to v1.32.5.
class_generator/class_generator.py Added a step to copy the resource mappings JSON file to the fake client directory, using shutil.copy2 with error handling.
fake_kubernetes_client/init.py Reorganized imports and exports, removed factory functions and version string, updated __all__ to match new modular structure.
fake_kubernetes_client/configuration.py New file: Implements FakeConfiguration class simulating Kubernetes client configuration.
fake_kubernetes_client/dynamic_client.py New file: Implements FakeDynamicClient class, providing dynamic client interface, resource registration, and access methods.
fake_kubernetes_client/exceptions.py New file: Defines exception classes and aliases compatible with Kubernetes client error handling.
fake_kubernetes_client/fake_dynamic_client.py Deleted: Removed the previous monolithic fake Kubernetes client implementation, including all related classes and utility functions.
fake_kubernetes_client/kubernetes_client.py New file: Implements FakeKubernetesClient class simulating the Kubernetes API client interface.
fake_kubernetes_client/resource_field.py New file: Implements FakeResourceField class for attribute and dict-like access to resource data.
fake_kubernetes_client/resource_instance.py New file: Implements FakeResourceInstance class for CRUD and watch operations on fake resources, including realistic event and error handling.
fake_kubernetes_client/resource_manager.py New file: Implements FakeResourceManager class for resource discovery and retrieval logic.
fake_kubernetes_client/resource_registry.py New file: Implements FakeResourceRegistry class for managing resource definitions, registration, and search.
fake_kubernetes_client/resource_storage.py New file: Implements FakeResourceStorage class for in-memory resource storage with filtering capabilities.
fake_kubernetes_client/status_schema_parser.py New file: Implements StatusSchemaParser for generating dynamic status objects from resource schemas.
fake_kubernetes_client/status_templates.py New file: Provides functions for adding realistic or schema-driven status fields to resources.
fake_kubernetes_client/types.py New file: Added a module-level docstring for type definitions (no functional code).

Possibly related PRs

Suggested labels

verified, can-be-merged, approved-rnetser

Suggested reviewers

  • dbasunag
  • rnetser

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4fd9906 and 2f05af3.

📒 Files selected for processing (12)
  • fake_kubernetes_client/README.md (1 hunks)
  • fake_kubernetes_client/dynamic_client.py (1 hunks)
  • fake_kubernetes_client/exceptions.py (1 hunks)
  • fake_kubernetes_client/kubernetes_client.py (1 hunks)
  • fake_kubernetes_client/resource_instance.py (1 hunks)
  • fake_kubernetes_client/resource_manager.py (1 hunks)
  • fake_kubernetes_client/resource_registry.py (1 hunks)
  • fake_kubernetes_client/resource_storage.py (1 hunks)
  • fake_kubernetes_client/status_schema_parser.py (1 hunks)
  • fake_kubernetes_client/status_templates.py (1 hunks)
  • tests/scripts/generate_pytest_test.py (6 hunks)
  • tests/test_resource.py (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/scripts/generate_pytest_test.py
🚧 Files skipped from review as they are similar to previous changes (4)
  • fake_kubernetes_client/exceptions.py
  • fake_kubernetes_client/README.md
  • fake_kubernetes_client/kubernetes_client.py
  • fake_kubernetes_client/resource_storage.py
🧰 Additional context used
🧠 Learnings (3)
tests/test_resource.py (2)
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2232
File: tests/test_resources.py:21-23
Timestamp: 2024-12-15T08:13:40.715Z
Learning: In the `pod` fixture in `tests/test_resources.py`, it is expected that there will always be at least one pod available, and the test should fail if there are none.
Learnt from: EdDev
PR: RedHatQE/openshift-python-wrapper#2291
File: ocp_resources/resource.py:126-126
Timestamp: 2025-01-28T07:25:19.573Z
Learning: The environment variable `OPENSHIFT_PYTHON_WRAPPER_CLIENT_USE_PROXY` must be set and not empty to override the `use_proxy` parameter in the `get_client` function.
fake_kubernetes_client/status_templates.py (3)
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2232
File: tests/test_resources.py:21-23
Timestamp: 2024-12-15T08:13:40.715Z
Learning: In the `pod` fixture in `tests/test_resources.py`, it is expected that there will always be at least one pod available, and the test should fail if there are none.
Learnt from: tarukumar
PR: RedHatQE/openshift-python-wrapper#2151
File: ocp_resources/serving_runtime.py:130-134
Timestamp: 2024-10-09T13:40:48.030Z
Learning: In the `ServingRuntime` class in `ocp_resources/serving_runtime.py`, the `nodeSelector` key is correctly used in camelCase within the `_spec` dictionary. Avoid flagging this as an issue in future reviews.
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2152
File: class_generator/tests/manifests/ServingRuntime/serving_runtime.py:96-160
Timestamp: 2024-10-09T14:25:49.618Z
Learning: The code in the `class_generator/tests/manifests/ServingRuntime/serving_runtime.py` file is auto-generated. Avoid suggesting refactoring changes to auto-generated code in this path.
fake_kubernetes_client/resource_instance.py (1)
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2209
File: ocp_resources/volume_snapshot_class.py:0-0
Timestamp: 2024-12-03T08:02:11.880Z
Learning: In generated code files like `ocp_resources/volume_snapshot_class.py`, avoid suggesting adding validation checks or modifications, as generated code should not be manually altered.
🧬 Code Graph Analysis (3)
tests/test_resource.py (1)
fake_kubernetes_client/resource_instance.py (1)
  • patch (307-356)
fake_kubernetes_client/resource_manager.py (6)
fake_kubernetes_client/resource_field.py (2)
  • FakeResourceField (7-120)
  • get (85-89)
fake_kubernetes_client/resource_instance.py (2)
  • FakeResourceInstance (23-469)
  • get (236-278)
fake_kubernetes_client/dynamic_client.py (3)
  • FakeDynamicClient (14-149)
  • get (137-149)
  • version (50-62)
tests/test_resource.py (1)
  • client (25-26)
tests/test_resources/test_group.py (1)
  • group (13-18)
fake_kubernetes_client/resource_registry.py (4)
  • get_resource_definition (355-376)
  • get_resource_definition_by_plural (378-386)
  • get_resource_definitions (351-353)
  • search (316-349)
fake_kubernetes_client/status_schema_parser.py (3)
fake_kubernetes_client/resource_manager.py (1)
  • get (21-70)
fake_kubernetes_client/resource_instance.py (2)
  • get (236-278)
  • replace (358-428)
fake_kubernetes_client/resource_field.py (2)
  • get (85-89)
  • items (103-112)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: can-be-merged
  • GitHub Check: can-be-merged
  • GitHub Check: conventional-title
  • GitHub Check: python-module-install
  • GitHub Check: tox
🔇 Additional comments (19)
tests/test_resource.py (2)

42-42: Good addition for testing pod readiness states.

The annotation "fake-client.io/ready": "false" correctly creates a pod with Ready status FALSE, which aligns well with the enhanced status handling in the new fake client architecture.


131-131: Correct fix for HTTPS proxy URL.

The HTTPS_PROXY environment variable now correctly uses an https URL, ensuring distinct values for HTTP and HTTPS proxies in the proxy precedence tests.

fake_kubernetes_client/resource_manager.py (1)

55-65: Simple and effective version preference logic.

The logic to prefer stable versions (v1 over beta/alpha) when preferred=True is straightforward and aligns with Kubernetes API versioning practices.

fake_kubernetes_client/resource_registry.py (2)

77-82: Good approach for handling known schema issues.

Having a centralized place for corrections to incorrect schema data is maintainable. Consider documenting where these corrections come from (e.g., which version of the schema has these issues) for future reference.


27-37: Well-implemented pluralization logic.

The plural form generation correctly handles standard Kubernetes naming conventions including special cases for words ending with 'y', 'sh', 'ch', 'x', and 'z'.

fake_kubernetes_client/status_schema_parser.py (1)

221-236: Excellent design for configurable resource readiness.

The ability to control resource readiness via the fake-client.io/ready annotation provides great flexibility for testing different resource states.

fake_kubernetes_client/dynamic_client.py (1)

84-135: Well-documented and flexible resource registration.

The register_resources method provides excellent documentation and examples. The flexibility to register single or multiple resources with sensible defaults makes this API user-friendly.

fake_kubernetes_client/status_templates.py (5)

9-42: Well-designed centralized configuration function.

The _get_ready_status_config function provides a clean, centralized way to determine ready status from annotations or spec fields, with sensible defaults. The priority order (annotations → spec → defaults) is logical and well-implemented.


45-68: Excellent fallback strategy for status generation.

The add_realistic_status function uses a well-structured approach: hardcoded templates for known resource types, dynamic schema-based generation when mappings are available, and generic templates as fallback. This provides both realism and flexibility.


85-189: Pod status template addresses previous configurability concerns.

The Pod status template now provides extensive configurability through annotations (fake-client.io/pod-ready, fake-client.io/ready) and spec fields (readyStatus), successfully addressing the previous review comment about hardcoded values. The implementation correctly handles both ready and not-ready states with realistic container statuses.


192-252: Deployment status template correctly reflects resource state.

The deployment status template appropriately adjusts replica counts, conditions, and availability based on the ready status configuration. The distinction between ready and not-ready states is well-implemented with realistic Kubernetes deployment status fields.


261-306: Namespace status template handles lifecycle states appropriately.

The namespace status template correctly transitions between "Active" and "Terminating" phases based on ready status, with appropriate conditions for each state. This mimics real Kubernetes namespace behavior during deletion.

fake_kubernetes_client/resource_instance.py (7)

17-21: Good defensive programming for optional dependencies.

The try/except block for importing K8sApiException with a fallback to None is a good practice for handling optional dependencies. This allows the fake client to work even when the full Kubernetes client library isn't available.


41-60: Robust error handling with Kubernetes-style exceptions.

The error creation methods properly handle both cases where K8sApiException is available and when it's not, providing appropriate fallbacks. The error messages and status codes match Kubernetes API conventions.


70-150: Comprehensive resource creation with realistic metadata.

The create method handles all the necessary aspects of resource creation: validation, conflict checking, metadata generation, status addition, and special case handling for ProjectRequest. The implementation correctly simulates Kubernetes resource creation behavior.


129-136: Excellent OpenShift ProjectRequest simulation.

The special handling for ephemeral ProjectRequest resources that create corresponding Project resources matches real OpenShift behavior. This is a thoughtful implementation detail that enhances testing fidelity.


185-234: Realistic event generation for resource operations.

The _generate_resource_events method creates realistic Kubernetes events with proper metadata, timestamps, and references. This adds valuable testing capabilities for scenarios that depend on resource events.


382-394: Proper optimistic concurrency control implementation.

The resource version conflict checking in the replace method correctly simulates Kubernetes' optimistic concurrency control, including appropriate error messages and status codes. This is essential for testing scenarios that rely on resource version conflicts.


462-469: Simple but effective merge patch implementation.

The _merge_patch method provides a straightforward recursive merge implementation that handles nested dictionaries correctly. This is appropriate for the fake client's testing purposes.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch typing-and-fixes

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

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.

@redhat-qe-bot1
Copy link

Report bugs in Issues

Welcome! 🎉

This pull request will be automatically processed with the following features:

🔄 Automatic Actions

  • Reviewer Assignment: Reviewers are automatically assigned based on the OWNERS file in the repository root
  • Size Labeling: PR size labels (XS, S, M, L, XL, XXL) are automatically applied based on changes
  • Issue Creation: A tracking issue is created for this PR and will be closed when the PR is merged or closed
  • Pre-commit Checks: pre-commit runs automatically if .pre-commit-config.yaml exists
  • Branch Labeling: Branch-specific labels are applied to track the target branch
  • Auto-verification: Auto-verified users have their PRs automatically marked as verified

📋 Available Commands

PR Status Management

  • /wip - Mark PR as work in progress (adds WIP: prefix to title)
  • /wip cancel - Remove work in progress status
  • /hold - Block PR merging (approvers only)
  • /hold cancel - Unblock PR merging
  • /verified - Mark PR as verified
  • /verified cancel - Remove verification status

Review & Approval

  • /lgtm - Approve changes (looks good to me)
  • /approve - Approve PR (approvers only)
  • /automerge - Enable automatic merging when all requirements are met (maintainers and approvers only)
  • /assign-reviewers - Assign reviewers based on OWNERS file
  • /assign-reviewer @username - Assign specific reviewer
  • /check-can-merge - Check if PR meets merge requirements

Testing & Validation

  • /retest tox - Run Python test suite with tox
  • /retest python-module-install - Test Python package installation
  • /retest conventional-title - Validate commit message format
  • /retest all - Run all available tests

Container Operations

  • /build-and-push-container - Build and push container image (tagged with PR number)
    • Supports additional build arguments: /build-and-push-container --build-arg KEY=value

Cherry-pick Operations

  • /cherry-pick <branch> - Schedule cherry-pick to target branch when PR is merged
    • Multiple branches: /cherry-pick branch1 branch2 branch3

Label Management

  • /<label-name> - Add a label to the PR
  • /<label-name> cancel - Remove a label from the PR

✅ Merge Requirements

This PR will be automatically approved when the following conditions are met:

  1. Approval: /approve from at least one approver
  2. LGTM Count: Minimum 0 /lgtm from reviewers
  3. Status Checks: All required status checks must pass
  4. No Blockers: No WIP, hold, or conflict labels
  5. Verified: PR must be marked as verified (if verification is enabled)

📊 Review Process

Approvers and Reviewers

Approvers:

  • myakove
  • rnetser

Reviewers:

  • dbasunag
  • myakove
  • rnetser
Available Labels
  • hold
  • verified
  • wip
  • lgtm
  • approve
  • automerge

💡 Tips

  • WIP Status: Use /wip when your PR is not ready for review
  • Verification: The verified label is automatically removed on each new commit
  • Cherry-picking: Cherry-pick labels are processed when the PR is merged
  • Container Builds: Container images are automatically tagged with the PR number
  • Permission Levels: Some commands require approver permissions
  • Auto-verified Users: Certain users have automatic verification and merge privileges

For more information, please refer to the project documentation or contact the maintainers.

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

🧹 Nitpick comments (13)
fake_kubernetes_client/types.py (1)

1-2: Placeholder file adds no value yet—consider fleshing it out or omitting it until needed.

Right now the module contains only a docstring. If no shared type aliases or protocols are actually consumed by the new sub-modules, shipping an empty file clutters the package surface and invites dead-code drift. Either:

  1. Populate it with the concrete TypedDict, Protocol, or Literal definitions the other modules will import, or
  2. Delete it for now and re-add once you have real content.

Also, if you decide to keep it, end the docstring with a period to satisfy common docstring-lint rules.

class_generator/class_generator.py (1)

244-250: Consider logging a warning when copy fails.

While the silent failure approach prevents breaking the entire schema update process, it could lead to the fake client operating with stale resource mappings. Consider adding a warning log when the copy fails to help with debugging potential issues.

 # Copy the resources mapping file to fake_kubernetes_client for the fake client to use
 fake_client_mappings = Path("fake_kubernetes_client/__resources-mappings.json")
 try:
     shutil.copy2(RESOURCES_MAPPING_FILE, fake_client_mappings)
-except (OSError, IOError):
+except (OSError, IOError) as exp:
     # Don't fail the entire process if copy fails
-    pass
+    LOGGER.warning(f"Failed to copy resources mapping file to fake client: {exp}")
fake_kubernetes_client/resource_storage.py (1)

98-115: Consider documenting the limited label selector support.

The current implementation only supports equality (key=value), inequality (key!=value), and key presence checks. It doesn't support Kubernetes set-based selectors like in, notin, exists, or doesnotexist.

Consider adding a docstring note about these limitations or expanding support in the future.

Would you like me to generate an implementation that supports the full Kubernetes label selector syntax?

fake_kubernetes_client/README.md (2)

201-217: Use proper markdown heading instead of emphasis.

-**1. Testing CRDs (Custom Resource Definitions)**
+### 1. Testing CRDs (Custom Resource Definitions)

219-239: Use proper markdown heading instead of emphasis.

-**2. Multi-Version Resources**
+### 2. Multi-Version Resources
fake_kubernetes_client/kubernetes_client.py (1)

17-18: Use pipe syntax for union types.

Since the codebase uses modern Python typing, consider using the pipe syntax for better readability.

Apply this diff to use the newer pipe syntax:

-        configuration: Union[FakeConfiguration, None] = None,
-        dynamic_client: Union["FakeDynamicClient", None] = None,
+        configuration: FakeConfiguration | None = None,
+        dynamic_client: "FakeDynamicClient" | None = None,
fake_kubernetes_client/resource_field.py (1)

36-72: Reduce code duplication between __getattr__ and __getitem__.

The value wrapping logic is duplicated between __getattr__ (lines 52-60) and __getitem__ (lines 63-71). Consider extracting this into a helper method.

Apply this diff to reduce duplication:

+    def _wrap_value(self, value: Any) -> Any:
+        """Wrap value based on its type"""
+        if value is None:
+            return FakeResourceField(data={})
+        elif isinstance(value, dict):
+            return FakeResourceField(data=value)
+        elif isinstance(value, list):
+            return [FakeResourceField(data=item) if isinstance(item, dict) else item for item in value]
+        else:
+            return value
+
     def __getattr__(self, name: str) -> Any:
         # This is called ONLY when __getattribute__ raises AttributeError
         # Handle all dynamic attribute access here
 
         # Direct access to _data without using hasattr (avoids recursion)
         try:
             data = object.__getattribute__(self, "_data")
         except AttributeError:
             data = {}
 
         # For resource definition access, return simple values for common attributes
         # This ensures compatibility with ocp_resources code that expects strings
         if name in ["api_version", "group_version", "kind", "plural", "singular", "group", "version"]:
             return data.get(name, "")
 
         # Handle general data access
         value = data.get(name)
-        if value is None:
-            return FakeResourceField(data={})
-        elif isinstance(value, dict):
-            return FakeResourceField(data=value)
-        elif isinstance(value, list):
-            return [FakeResourceField(data=item) if isinstance(item, dict) else item for item in value]
-        else:
-            return value
+        return self._wrap_value(value)
 
     def __getitem__(self, key: str) -> Any:
         value = self._data.get(key)
-        if value is None:
-            return FakeResourceField(data={})
-        elif isinstance(value, dict):
-            return FakeResourceField(data=value)
-        elif isinstance(value, list):
-            return [FakeResourceField(data=item) if isinstance(item, dict) else item for item in value]
-        else:
-            return value
+        return self._wrap_value(value)
fake_kubernetes_client/status_schema_parser.py (1)

233-233: Consider making random IP generation deterministic for tests.

Random IP addresses could cause test flakiness if tests expect consistent values. Consider adding an option for deterministic generation.

You could add a seed parameter or use a deterministic approach:

         elif field_name.endswith("IP"):
-            return f"10.0.0.{random.randint(1, 254)}"
+            # Use a hash of the field name for deterministic IPs
+            import hashlib
+            hash_val = int(hashlib.md5(field_name.encode()).hexdigest()[:2], 16) % 254 + 1
+            return f"10.0.0.{hash_val}"
fake_kubernetes_client/resource_manager.py (1)

50-60: Enhance preferred version selection logic.

The current implementation only checks for "v1" specifically. Consider supporting other stable versions (v2, v3, etc.) and using a more robust version comparison.

-                if preferred:
-                    # Simple logic: prefer stable versions (v1 > v1beta1 > v1alpha1)
-                    for def_ in definitions:
-                        if def_["version"] == "v1":
-                            resource_def = def_
-                            break
-                    if not resource_def:
-                        resource_def = definitions[0]
+                if preferred:
+                    # Prefer stable versions: v1, v2, etc. > v1beta1 > v1alpha1
+                    stable_versions = []
+                    beta_versions = []
+                    alpha_versions = []
+                    
+                    for def_ in definitions:
+                        version = def_["version"]
+                        if version.startswith("v") and version[1:].isdigit():
+                            stable_versions.append((int(version[1:]), def_))
+                        elif "beta" in version:
+                            beta_versions.append(def_)
+                        elif "alpha" in version:
+                            alpha_versions.append(def_)
+                    
+                    if stable_versions:
+                        # Sort by version number and pick the highest
+                        resource_def = max(stable_versions, key=lambda x: x[0])[1]
+                    elif beta_versions:
+                        resource_def = beta_versions[0]
+                    elif alpha_versions:
+                        resource_def = alpha_versions[0]
+                    else:
+                        resource_def = definitions[0]
fake_kubernetes_client/dynamic_client.py (1)

130-142: Consider improving type annotations for better type safety.

The method uses Any types extensively, which reduces type safety. Consider using more specific types or Union types.

-    def get(self, resource: Any, *args: Any, **kwargs: Any) -> Any:
+    def get(
+        self, 
+        resource: Union[FakeResourceField, dict[str, Any]], 
+        *args: Any, 
+        **kwargs: Any
+    ) -> FakeResourceField:
         """Get resources based on resource definition"""
         # Extract resource definition from FakeResourceField if needed
         if hasattr(resource, "data"):
             resource_def = resource.data
         else:
             resource_def = resource

         # Create a resource instance for this resource type
         resource_instance = FakeResourceInstance(resource_def=resource_def, storage=self.storage, client=self)

         # Call get on the resource instance to list resources
         return resource_instance.get(*args, **kwargs)
fake_kubernetes_client/resource_instance.py (3)

93-95: Consider making default namespace configurable.

The default namespace is hardcoded to "default". Consider making this configurable or obtaining it from the client configuration.

         resource_namespace = (
-            body["metadata"].get("namespace", "default") if self.resource_def.get("namespaced") else None
+            body["metadata"].get("namespace") or self._get_default_namespace() if self.resource_def.get("namespaced") else None
         )

Add a helper method:

def _get_default_namespace(self) -> str:
    """Get default namespace from configuration or return 'default'"""
    if self.client and hasattr(self.client, 'configuration'):
        return getattr(self.client.configuration, 'default_namespace', 'default')
    return 'default'

70-150: Extract helper methods to improve readability.

The create method is quite long (80 lines). Consider extracting some logic into helper methods for better maintainability.

Extract metadata generation into a helper method:

def _generate_create_metadata(self, body: dict[str, Any]) -> None:
    """Generate metadata fields for resource creation"""
    body["metadata"].update({
        "uid": str(uuid.uuid4()),
        "resourceVersion": self._generate_resource_version(),
        "creationTimestamp": self._generate_timestamp(),
        "generation": 1,
        "labels": body["metadata"].get("labels", {}),
        "annotations": body["metadata"].get("annotations", {}),
    })

Then use it in the create method:

-        # Add generated metadata
-        body["metadata"].update({
-            "uid": str(uuid.uuid4()),
-            "resourceVersion": self._generate_resource_version(),
-            "creationTimestamp": self._generate_timestamp(),
-            "generation": 1,
-            "labels": body["metadata"].get("labels", {}),
-            "annotations": body["metadata"].get("annotations", {}),
-        })
+        # Add generated metadata
+        self._generate_create_metadata(body)

397-399: Preserve API version and kind from body if provided.

The method unconditionally sets apiVersion and kind, potentially overriding values provided in the body. Consider preserving user-provided values.

         # Set API version and kind
-        body["apiVersion"] = self.resource_def["api_version"]
-        body["kind"] = self.resource_def["kind"]
+        # Set API version and kind if not provided
+        body.setdefault("apiVersion", self.resource_def["api_version"])
+        body.setdefault("kind", self.resource_def["kind"])
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d76c4d4 and 84b3c45.

⛔ Files ignored due to path filters (75)
  • class_generator/schema/__not-kind.txt is excluded by !class_generator/schema/**
  • class_generator/schema/__resources-mappings.json is excluded by !class_generator/schema/**
  • class_generator/schema/_definitions.json is excluded by !class_generator/schema/**
  • class_generator/schema/alertmanager.json is excluded by !class_generator/schema/**
  • class_generator/schema/all.json is excluded by !class_generator/schema/**
  • class_generator/schema/apiresource.json is excluded by !class_generator/schema/**
  • class_generator/schema/apiresourcelist.json is excluded by !class_generator/schema/**
  • class_generator/schema/backup.json is excluded by !class_generator/schema/**
  • class_generator/schema/backuplist.json is excluded by !class_generator/schema/**
  • class_generator/schema/cephblockpool.json is excluded by !class_generator/schema/**
  • class_generator/schema/cephbuckettopic.json is excluded by !class_generator/schema/**
  • class_generator/schema/cephconnection.json is excluded by !class_generator/schema/**
  • class_generator/schema/cephobjectstoreuser.json is excluded by !class_generator/schema/**
  • class_generator/schema/clientprofile.json is excluded by !class_generator/schema/**
  • class_generator/schema/clientprofilemapping.json is excluded by !class_generator/schema/**
  • class_generator/schema/clusteruserdefinednetwork.json is excluded by !class_generator/schema/**
  • class_generator/schema/console.json is excluded by !class_generator/schema/**
  • class_generator/schema/consoleplugin.json is excluded by !class_generator/schema/**
  • class_generator/schema/consolepluginlist.json is excluded by !class_generator/schema/**
  • class_generator/schema/controlplanemachineset.json is excluded by !class_generator/schema/**
  • class_generator/schema/database.json is excluded by !class_generator/schema/**
  • class_generator/schema/databaselist.json is excluded by !class_generator/schema/**
  • class_generator/schema/driver.json is excluded by !class_generator/schema/**
  • class_generator/schema/gateway.json is excluded by !class_generator/schema/**
  • class_generator/schema/gatewayclass.json is excluded by !class_generator/schema/**
  • class_generator/schema/gatewayclasslist.json is excluded by !class_generator/schema/**
  • class_generator/schema/gatewaylist.json is excluded by !class_generator/schema/**
  • class_generator/schema/grpcroute.json is excluded by !class_generator/schema/**
  • class_generator/schema/grpcroutelist.json is excluded by !class_generator/schema/**
  • class_generator/schema/helmchartrepository.json is excluded by !class_generator/schema/**
  • class_generator/schema/host.json is excluded by !class_generator/schema/**
  • class_generator/schema/httproute.json is excluded by !class_generator/schema/**
  • class_generator/schema/httproutelist.json is excluded by !class_generator/schema/**
  • class_generator/schema/hyperconverged.json is excluded by !class_generator/schema/**
  • class_generator/schema/localvolume.json is excluded by !class_generator/schema/**
  • class_generator/schema/localvolumediscovery.json is excluded by !class_generator/schema/**
  • class_generator/schema/localvolumeset.json is excluded by !class_generator/schema/**
  • class_generator/schema/machineosbuild.json is excluded by !class_generator/schema/**
  • class_generator/schema/machineosbuildlist.json is excluded by !class_generator/schema/**
  • class_generator/schema/machineosconfig.json is excluded by !class_generator/schema/**
  • class_generator/schema/machineosconfiglist.json is excluded by !class_generator/schema/**
  • class_generator/schema/migration.json is excluded by !class_generator/schema/**
  • class_generator/schema/networkfence.json is excluded by !class_generator/schema/**
  • class_generator/schema/networkmap.json is excluded by !class_generator/schema/**
  • class_generator/schema/noobaa.json is excluded by !class_generator/schema/**
  • class_generator/schema/operatorconfig.json is excluded by !class_generator/schema/**
  • class_generator/schema/persistentvolumeclaimvolumesource.json is excluded by !class_generator/schema/**
  • class_generator/schema/plan.json is excluded by !class_generator/schema/**
  • class_generator/schema/projecthelmchartrepository.json is excluded by !class_generator/schema/**
  • class_generator/schema/prometheus.json is excluded by !class_generator/schema/**
  • class_generator/schema/provider.json is excluded by !class_generator/schema/**
  • class_generator/schema/referencegrant.json is excluded by !class_generator/schema/**
  • class_generator/schema/referencegrantlist.json is excluded by !class_generator/schema/**
  • class_generator/schema/route.json is excluded by !class_generator/schema/**
  • class_generator/schema/routelist.json is excluded by !class_generator/schema/**
  • class_generator/schema/storageautoscaler.json is excluded by !class_generator/schema/**
  • class_generator/schema/storageautoscalerlist.json is excluded by !class_generator/schema/**
  • class_generator/schema/storagecluster.json is excluded by !class_generator/schema/**
  • class_generator/schema/storageconsumer.json is excluded by !class_generator/schema/**
  • class_generator/schema/storagemap.json is excluded by !class_generator/schema/**
  • class_generator/schema/subscription.json is excluded by !class_generator/schema/**
  • class_generator/schema/subscriptionlist.json is excluded by !class_generator/schema/**
  • class_generator/schema/thanosruler.json is excluded by !class_generator/schema/**
  • class_generator/schema/user.json is excluded by !class_generator/schema/**
  • class_generator/schema/userlist.json is excluded by !class_generator/schema/**
  • class_generator/schema/virtualmachine.json is excluded by !class_generator/schema/**
  • class_generator/schema/virtualmachineclusterpreference.json is excluded by !class_generator/schema/**
  • class_generator/schema/virtualmachineinstance.json is excluded by !class_generator/schema/**
  • class_generator/schema/virtualmachineinstancepreset.json is excluded by !class_generator/schema/**
  • class_generator/schema/virtualmachineinstancereplicaset.json is excluded by !class_generator/schema/**
  • class_generator/schema/virtualmachinepool.json is excluded by !class_generator/schema/**
  • class_generator/schema/virtualmachinepreference.json is excluded by !class_generator/schema/**
  • class_generator/schema/virtualmachinesnapshotcontent.json is excluded by !class_generator/schema/**
  • class_generator/schema/vspherexcopyvolumepopulator.json is excluded by !class_generator/schema/**
  • class_generator/schema/vspherexcopyvolumepopulatorlist.json is excluded by !class_generator/schema/**
📒 Files selected for processing (20)
  • .flake8 (1 hunks)
  • .pre-commit-config.yaml (1 hunks)
  • README.md (1 hunks)
  • class_generator/__cluster_version__.txt (1 hunks)
  • class_generator/class_generator.py (1 hunks)
  • fake_kubernetes_client/README.md (5 hunks)
  • fake_kubernetes_client/__init__.py (1 hunks)
  • fake_kubernetes_client/configuration.py (1 hunks)
  • fake_kubernetes_client/dynamic_client.py (1 hunks)
  • fake_kubernetes_client/exceptions.py (1 hunks)
  • fake_kubernetes_client/fake_dynamic_client.py (0 hunks)
  • fake_kubernetes_client/kubernetes_client.py (1 hunks)
  • fake_kubernetes_client/resource_field.py (1 hunks)
  • fake_kubernetes_client/resource_instance.py (1 hunks)
  • fake_kubernetes_client/resource_manager.py (1 hunks)
  • fake_kubernetes_client/resource_registry.py (1 hunks)
  • fake_kubernetes_client/resource_storage.py (1 hunks)
  • fake_kubernetes_client/status_schema_parser.py (1 hunks)
  • fake_kubernetes_client/status_templates.py (1 hunks)
  • fake_kubernetes_client/types.py (1 hunks)
💤 Files with no reviewable changes (1)
  • fake_kubernetes_client/fake_dynamic_client.py
🧰 Additional context used
🧠 Learnings (4)
README.md (1)
Learnt from: EdDev
PR: RedHatQE/openshift-python-wrapper#2291
File: ocp_resources/resource.py:126-126
Timestamp: 2025-01-28T07:25:19.573Z
Learning: The environment variable `OPENSHIFT_PYTHON_WRAPPER_CLIENT_USE_PROXY` must be set and not empty to override the `use_proxy` parameter in the `get_client` function.
class_generator/__cluster_version__.txt (2)
Learnt from: sbahar619
PR: RedHatQE/openshift-python-wrapper#2126
File: ocp_resources/user_defined_network.py:19-19
Timestamp: 2024-10-08T23:43:22.342Z
Learning: When reviewing code generated by the class generator, avoid suggesting changes that would alter its automatic version.
Learnt from: sbahar619
PR: RedHatQE/openshift-python-wrapper#2126
File: ocp_resources/user_defined_network.py:19-19
Timestamp: 2024-09-29T12:43:09.926Z
Learning: When reviewing code generated by the class generator, avoid suggesting changes that would alter its automatic version.
class_generator/class_generator.py (5)
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2181
File: class_generator/class_generator.py:226-229
Timestamp: 2024-10-27T13:29:34.775Z
Learning: In the `update_kind_schema()` function in `class_generator.py`, the `tmp_schema_dir` directory contains only JSON files without subdirectories, so preserving the directory structure when copying files is unnecessary.
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2181
File: class_generator/schema/manualapprovalgatelist.json:12-18
Timestamp: 2024-10-27T14:07:35.575Z
Learning: All files under `class_generator/schema/` are auto-generated.
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2209
File: ocp_resources/volume_snapshot_class.py:0-0
Timestamp: 2024-12-03T08:02:11.880Z
Learning: In generated code files like `ocp_resources/volume_snapshot_class.py`, avoid suggesting adding validation checks or modifications, as generated code should not be manually altered.
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2152
File: class_generator/tests/manifests/ServingRuntime/serving_runtime.py:96-160
Timestamp: 2024-10-09T14:25:49.618Z
Learning: The code in the `class_generator/tests/manifests/ServingRuntime/serving_runtime.py` file is auto-generated. Avoid suggesting refactoring changes to auto-generated code in this path.
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2154
File: ocp_resources/serving_runtime.py:110-160
Timestamp: 2024-10-09T18:44:29.284Z
Learning: In `ocp_resources/serving_runtime.py`, the code is auto-generated and should not be manually modified.
fake_kubernetes_client/README.md (1)
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2232
File: tests/test_resources.py:21-23
Timestamp: 2024-12-15T08:13:40.715Z
Learning: In the `pod` fixture in `tests/test_resources.py`, it is expected that there will always be at least one pod available, and the test should fail if there are none.
🧬 Code Graph Analysis (4)
fake_kubernetes_client/status_schema_parser.py (1)
fake_kubernetes_client/resource_instance.py (2)
  • get (236-278)
  • replace (351-418)
fake_kubernetes_client/resource_storage.py (4)
fake_kubernetes_client/dynamic_client.py (2)
  • resources (28-30)
  • get (130-142)
fake_kubernetes_client/resource_instance.py (1)
  • get (236-278)
fake_kubernetes_client/resource_field.py (1)
  • get (85-89)
fake_kubernetes_client/resource_manager.py (1)
  • get (21-65)
fake_kubernetes_client/status_templates.py (2)
fake_kubernetes_client/status_schema_parser.py (3)
  • StatusSchemaParser (8-339)
  • get_status_schema_for_resource (15-39)
  • generate_status_from_schema (151-164)
fake_kubernetes_client/resource_instance.py (1)
  • get (236-278)
fake_kubernetes_client/resource_field.py (3)
fake_kubernetes_client/dynamic_client.py (1)
  • get (130-142)
fake_kubernetes_client/resource_instance.py (1)
  • get (236-278)
fake_kubernetes_client/resource_manager.py (1)
  • get (21-65)
🪛 markdownlint-cli2 (0.17.2)
fake_kubernetes_client/README.md

202-202: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


219-219: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: can-be-merged
  • GitHub Check: conventional-title
  • GitHub Check: tox
  • GitHub Check: python-module-install
🔇 Additional comments (9)
class_generator/__cluster_version__.txt (1)

1-1: Version update acknowledged.

The version has been updated from v1.32.3 to v1.32.5 as part of the class generator process.

.flake8 (1)

70-70: LGTM - Appropriate flake8 exclusion.

Adding shutil to the exclusion list is correct and aligns with the new usage of shutil.copy2 in the class generator code.

README.md (1)

44-46: Excellent documentation addition.

The new section clearly introduces the fake Kubernetes client feature and provides appropriate reference to detailed documentation. This will help users discover and understand the testing capabilities.

.pre-commit-config.yaml (1)

45-45: Appropriate exclusion for generated content.

Adding the exclusion for fake_kubernetes_client/__resources-mappings.json is correct since this is generated/copied content that shouldn't be scanned for secrets.

fake_kubernetes_client/configuration.py (1)

1-23: LGTM!

The FakeConfiguration class provides a clean mock implementation with appropriate default values for testing scenarios.

fake_kubernetes_client/__init__.py (1)

1-30: Well-structured module exports!

The refactored imports and exports properly expose the new modular architecture, providing a clean public API for the fake Kubernetes client.

fake_kubernetes_client/README.md (1)

141-199: Excellent documentation for the new resource registration API!

The examples and parameter table provide clear guidance for users migrating to the new register_resources() method. The comprehensive parameter documentation is particularly helpful.

fake_kubernetes_client/dynamic_client.py (1)

77-128: Well-documented resource registration method.

The register_resources method is excellently documented with clear examples and parameter descriptions. The delegation pattern to the registry is appropriate.

fake_kubernetes_client/resource_instance.py (1)

448-455: Clean implementation of merge patch logic.

The recursive merge patch implementation correctly handles nested dictionaries and follows the JSON merge patch semantics.

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

♻️ Duplicate comments (5)
fake_kubernetes_client/resource_storage.py (1)

129-146: String conversion in field selector matching may cause issues.

Converting field values to strings (lines 138, 144) might not work correctly for all data types:

  • Booleans: Python's True becomes "True" instead of "true"
  • None/null values: None becomes "None" instead of being handled as missing
  • Numbers: Potential precision issues with floats

Consider implementing type-aware comparison:

 def _matches_field_selector(self, resource: dict[str, Any], selector: str) -> bool:
     """Check if resource matches field selector"""
     # Handle simple field selectors (field.path=value or field.path==value)
     parts = selector.split(",")
     for part in parts:
         if "==" in part:
             # Handle double equals
             field_path, value = part.split("==", 1)
             field_value = self._get_field_value(resource, field_path.strip())
-            if str(field_value) != value.strip():
+            if not self._compare_field_value(field_value, value.strip()):
                 return False
         elif "=" in part:
             # Handle single equals
             field_path, value = part.split("=", 1)
             field_value = self._get_field_value(resource, field_path.strip())
-            if str(field_value) != value.strip():
+            if not self._compare_field_value(field_value, value.strip()):
                 return False
     return True
+
+def _compare_field_value(self, field_value: Any, expected: str) -> bool:
+    """Compare field value with expected string value"""
+    if field_value is None:
+        return expected.lower() in ("", "null", "none")
+    elif isinstance(field_value, bool):
+        return str(field_value).lower() == expected.lower()
+    else:
+        return str(field_value) == expected
fake_kubernetes_client/status_schema_parser.py (2)

41-52: Complete the reference resolution implementation.

The comment indicates this is a placeholder implementation. Without proper reference resolution, the schema parser may not work correctly for resources with $ref in their status definitions.

Would you like me to help implement proper $ref resolution that follows JSON Schema references?


256-259: Remove unreachable return statement.

Line 258 contains an unreachable return statement after the else block already returns.

Apply this diff to remove the dead code:

         else:
             return 1
-        return 1
fake_kubernetes_client/resource_instance.py (2)

333-334: Replace assert with proper error handling.

Using assert for type narrowing is not ideal as assertions can be disabled with Python's -O flag. Consider explicit checking.

-        # Type assertion - at this point existing cannot be None
-        assert existing is not None
+        # Existing cannot be None at this point due to the check above
+        if existing is None:
+            # This should never happen, but handle it gracefully
+            self._create_not_found_error(name)
+            return FakeResourceField(data={})  # unreachable, but satisfies type checker

381-382: Replace assert with proper error handling in replace method.

Same issue as in the patch method - assertions can be disabled.

-        # Type assertion - at this point existing cannot be None
-        assert existing is not None
+        # Existing cannot be None at this point due to the check above
+        if existing is None:
+            # This should never happen, but handle it gracefully
+            self._create_not_found_error(name)
+            return FakeResourceField(data={})  # unreachable, but satisfies type checker
🧹 Nitpick comments (3)
fake_kubernetes_client/resource_storage.py (1)

102-119: Consider documenting label selector limitations.

The current implementation only supports simple equality (key=value), inequality (key!=value), and key existence checks. It doesn't support Kubernetes set-based selectors like key in (value1,value2), key notin (value1,value2), or the !key syntax for non-existence.

Consider adding a docstring note about supported selector syntax:

 def _matches_label_selector(self, labels: dict[str, str], selector: str) -> bool:
-    """Check if labels match selector (simplified implementation)"""
+    """Check if labels match selector (simplified implementation).
+    
+    Supports:
+    - Equality: key=value
+    - Inequality: key!=value  
+    - Existence: key
+    
+    Does not support:
+    - Set-based: key in (value1,value2)
+    - Non-existence: !key
+    """
fake_kubernetes_client/resource_manager.py (1)

51-58: Enhance version preference logic for better stability ordering.

The current logic only checks for "v1" and doesn't handle other stable versions like "v2" or properly order beta/alpha versions.

Consider a more comprehensive version ordering:

                 if preferred:
                     # Simple logic: prefer stable versions (v1 > v1beta1 > v1alpha1)
-                    for def_ in definitions:
-                        if def_["version"] == "v1":
-                            resource_def = def_
-                            break
-                    if not resource_def:
-                        resource_def = definitions[0]
+                    # Sort by version stability
+                    def version_priority(def_: dict[str, Any]) -> tuple[int, str]:
+                        version = def_["version"]
+                        if version.startswith("v") and version[1:].isdigit():
+                            return (0, version)  # Stable versions first
+                        elif "beta" in version:
+                            return (1, version)
+                        elif "alpha" in version:
+                            return (2, version)
+                        else:
+                            return (3, version)
+                    
+                    resource_def = min(definitions, key=version_priority)
fake_kubernetes_client/resource_instance.py (1)

62-64: Consider adding uniqueness to resource version generation.

The current timestamp-based approach could theoretically produce collisions with rapid operations.

Consider adding a counter or random component:

+    def __init__(self, ...):
+        # ... existing init code ...
+        self._version_counter = 0
+
     def _generate_resource_version(self) -> str:
         """Generate unique resource version"""
-        return str(int(time.time() * 1000))
+        self._version_counter += 1
+        return f"{int(time.time() * 1000)}-{self._version_counter}"
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 84b3c45 and 4fd9906.

📒 Files selected for processing (10)
  • fake_kubernetes_client/dynamic_client.py (1 hunks)
  • fake_kubernetes_client/exceptions.py (1 hunks)
  • fake_kubernetes_client/kubernetes_client.py (1 hunks)
  • fake_kubernetes_client/resource_field.py (1 hunks)
  • fake_kubernetes_client/resource_instance.py (1 hunks)
  • fake_kubernetes_client/resource_manager.py (1 hunks)
  • fake_kubernetes_client/resource_registry.py (1 hunks)
  • fake_kubernetes_client/resource_storage.py (1 hunks)
  • fake_kubernetes_client/status_schema_parser.py (1 hunks)
  • fake_kubernetes_client/status_templates.py (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • fake_kubernetes_client/resource_registry.py
  • fake_kubernetes_client/dynamic_client.py
🚧 Files skipped from review as they are similar to previous changes (4)
  • fake_kubernetes_client/exceptions.py
  • fake_kubernetes_client/kubernetes_client.py
  • fake_kubernetes_client/status_templates.py
  • fake_kubernetes_client/resource_field.py
🧰 Additional context used
🧠 Learnings (2)
fake_kubernetes_client/resource_storage.py (1)
Learnt from: tarukumar
PR: RedHatQE/openshift-python-wrapper#2151
File: ocp_resources/serving_runtime.py:130-134
Timestamp: 2024-10-09T13:40:48.030Z
Learning: In the `ServingRuntime` class in `ocp_resources/serving_runtime.py`, the `nodeSelector` key is correctly used in camelCase within the `_spec` dictionary. Avoid flagging this as an issue in future reviews.
fake_kubernetes_client/resource_instance.py (1)
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2209
File: ocp_resources/volume_snapshot_class.py:0-0
Timestamp: 2024-12-03T08:02:11.880Z
Learning: In generated code files like `ocp_resources/volume_snapshot_class.py`, avoid suggesting adding validation checks or modifications, as generated code should not be manually altered.
🧬 Code Graph Analysis (2)
fake_kubernetes_client/status_schema_parser.py (4)
fake_kubernetes_client/resource_field.py (2)
  • get (85-89)
  • items (103-112)
fake_kubernetes_client/dynamic_client.py (1)
  • get (130-142)
fake_kubernetes_client/resource_manager.py (1)
  • get (21-65)
fake_kubernetes_client/resource_instance.py (1)
  • get (236-278)
fake_kubernetes_client/resource_storage.py (5)
fake_kubernetes_client/dynamic_client.py (2)
  • resources (28-30)
  • get (130-142)
ocp_resources/resource.py (2)
  • kind (671-672)
  • labels (1158-1165)
fake_kubernetes_client/resource_field.py (1)
  • get (85-89)
fake_kubernetes_client/resource_manager.py (1)
  • get (21-65)
fake_kubernetes_client/resource_instance.py (1)
  • get (236-278)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: can-be-merged
  • GitHub Check: can-be-merged
  • GitHub Check: can-be-merged
  • GitHub Check: conventional-title
  • GitHub Check: tox
  • GitHub Check: python-module-install
🔇 Additional comments (2)
fake_kubernetes_client/resource_manager.py (1)

36-37: API version construction handles empty groups correctly.

The current implementation correctly handles empty group strings for core resources. When group is an empty string, it evaluates to False and returns just the version, which is the expected behavior for core Kubernetes resources.

fake_kubernetes_client/resource_instance.py (1)

129-136: Good implementation of ProjectRequest semantics.

The code correctly implements OpenShift's ProjectRequest behavior where it's an ephemeral resource that triggers Project creation without being persisted itself. This matches real cluster behavior.

@myakove
Copy link
Collaborator Author

myakove commented Jul 9, 2025

/verified
/approve

@rnetser
Copy link
Collaborator

rnetser commented Jul 10, 2025

/lgtm

@rnetser rnetser enabled auto-merge (squash) July 10, 2025 07:03
@rnetser rnetser merged commit 5bb085b into main Jul 10, 2025
7 checks passed
@rnetser rnetser deleted the typing-and-fixes branch July 10, 2025 07:38
@coderabbitai coderabbitai bot mentioned this pull request Jul 16, 2025
myakove added a commit that referenced this pull request Aug 11, 2025
* feat: Add typing and split fake client code

* feat: Add typing and split fake client code

* feat: Add typing and split fake client code

* feat: Add typing and split fake client code

* Use Union for type

* Use Union for type

* improve the client code
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.

6 participants