Skip to content

chore(tests): increase code coverage for low-coverage modules#134

Open
shrutu0929 wants to merge 4 commits intoRefactron-ai:mainfrom
shrutu0929:chore-increase-coverage-final
Open

chore(tests): increase code coverage for low-coverage modules#134
shrutu0929 wants to merge 4 commits intoRefactron-ai:mainfrom
shrutu0929:chore-increase-coverage-final

Conversation

@shrutu0929
Copy link
Copy Markdown

@shrutu0929 shrutu0929 commented Mar 26, 2026

In this task, I increased the code coverage for the Refactron library by implementing a new test suite for the refactron/core/device_auth.py module, which had a low initial coverage of 32%. I created the tests/test_device_auth.py
file, adding eight targeted test cases that use mocking to verify URL normalization, secure JSON posting, device authorization initiation, and the token polling logic, including handling for success, timeouts, and expired codes. These additions significantly boosted the module's coverage to approximately 88%. During the process, I also conducted an extensive search for the 0% coverage modules symbol_table.py and inference.py identified in the initial report; however, I discovered they are currently absent from the codebase and Git history, which I have documented for further clarification. Finally, I consolidated these changes into a single commit on a new branch named chore-tests-increase-code-coverage and pushed it to the GitHub repository as requested.

Summary by CodeRabbit

  • Tests
    • Added comprehensive tests for device authentication (polling, timeouts, expired codes, and error handling), workspace management (create/list/remove, detection from repo paths), and CLI repository commands (list, connect, disconnect); tests mock network/time behavior and avoid heavy imports during CLI tests.
  • Refactor
    • Made workspace data parsing more tolerant of missing or inconsistent fields to reduce errors during lookup and syncing.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 26, 2026

📝 Walkthrough

Walkthrough

Added new tests for device-code authentication and CLI repository/workspace commands; updated WorkspaceMapping.from_dict to tolerate missing fields and derive repo_name from repo_full_name when absent.

Changes

Cohort / File(s) Summary
Device Authentication Tests
tests/test_device_auth.py
New tests for refactron.core.device_auth: base-URL normalization; mocked _post_json success and urllib.error.HTTPError error extraction; start_device_authorization()DeviceAuthorization construction and error path; poll_for_token() multi-step polling, patched time.sleep, timeout and expired-device-code error cases.
Workspace Management Tests
tests/test_workspace.py
New tests for WorkspaceManager and WorkspaceMapping: config fixture, to_dict/from_dict round-trip, add/get/list/remove semantics, lookups by full/short repo name and local path, and git remote detection via mock .git/config (HTTPS and SSH).
Workspace Core Change
refactron/core/workspace.py
WorkspaceMapping.from_dict made defensive: uses data.get() for optional fields, derives repo_name from repo_full_name when missing, and falls back to "unknown".
CLI Repo Tests
tests/test_cli_repo.py
Tests updated to fetch Click group at call-time; added/adjusted tests for repo list, repo connect --path (including auth banner patching and heavy-import stubs), and repo disconnect failure/success paths; extensive mocking of workspace/indexer interactions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰
I nudged the tests with a gentle hop,
Device codes ticking, repos that pop.
Mocks in my pouch and time patched so fine,
I celebrate changes with a carrot and rhyme. 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main objective of the PR: adding test coverage to low-coverage modules. Multiple test files were added (test_device_auth.py, test_workspace.py, test_cli_repo.py) with coverage improvements, matching the title's goal.
Docstring Coverage ✅ Passed Docstring coverage is 91.18% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (1)
tests/test_workspace.py (1)

105-106: Remove redundant @patch decorators from both test methods.

The detect_repository() method uses directory or Path.cwd(), so when called with an explicit repo_dir argument (as both tests do), the patched cwd is never used. The decorators can be safely removed.

Suggested changes
-@patch("pathlib.Path.cwd")
-def test_detect_repository_https(mock_cwd, tmp_path):
+def test_detect_repository_https(tmp_path):
     """Test repository detection from HTTPS URL."""
-@patch("pathlib.Path.cwd")
-def test_detect_repository_ssh(mock_cwd, tmp_path):
+def test_detect_repository_ssh(tmp_path):
     """Test repository detection from SSH URL."""
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_workspace.py` around lines 105 - 106, Both tests (e.g.,
test_detect_repository_https) have redundant `@patch`("pathlib.Path.cwd")
decorators and the corresponding mock parameter (mock_cwd) even though
detect_repository is called with an explicit repo_dir; remove the `@patch`
decorator from both test_detect_repository_https and its counterpart (e.g.,
test_detect_repository_ssh) and delete the unused mock_cwd parameter from their
function signatures so the tests call detect_repository(repo_dir=...) directly
without the unnecessary patch.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/test_device_auth.py`:
- Line 3: Remove the unused top-level import statement "import json" from the
test module; simply delete the line containing "import json" so the file no
longer imports json unnecessarily and the CI unused-import error is resolved.
- Around line 90-96: The test patches time.sleep but poll_for_token binds
time.sleep as the default argument sleep_fn at import time, so the patch doesn't
take effect; update the test to either patch the function at the use site (patch
"refactron.core.device_auth.time.sleep") or call poll_for_token with an explicit
mock sleep_fn (e.g., poll_for_token("dev_123", sleep_fn=mock_sleep)) so the
sleep call is intercepted; target the poll_for_token function and its sleep_fn
default to ensure the mock is used.

In `@tests/test_workspace.py`:
- Around line 3-6: Remove the unused imports causing flake8 F401 in
tests/test_workspace.py: delete the unused symbols "os", "Path" (from pathlib),
and "MagicMock" (from unittest.mock) from the import list, leaving only the
actually used imports (e.g., json, patch) or alternatively import them where
they are used; ensure the top-of-file import line(s) reference only active
symbols such as "json" and "patch".
- Around line 42-48: The test assigns an unused local variable `manager` in
test_manager_initialization which triggers flake8 F841; either remove the
assignment and just call WorkspaceManager(config_path=temp_config) or use the
variable (e.g., assert isinstance(manager, WorkspaceManager)) so the created
object is used; update the test function (referencing
test_manager_initialization and WorkspaceManager) accordingly to eliminate the
unused `manager` variable.

---

Nitpick comments:
In `@tests/test_workspace.py`:
- Around line 105-106: Both tests (e.g., test_detect_repository_https) have
redundant `@patch`("pathlib.Path.cwd") decorators and the corresponding mock
parameter (mock_cwd) even though detect_repository is called with an explicit
repo_dir; remove the `@patch` decorator from both test_detect_repository_https and
its counterpart (e.g., test_detect_repository_ssh) and delete the unused
mock_cwd parameter from their function signatures so the tests call
detect_repository(repo_dir=...) directly without the unnecessary patch.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3c9ae927-1cca-40f8-a63a-be9e8a8ce8a1

📥 Commits

Reviewing files that changed from the base of the PR and between 11720b7 and 89292dc.

📒 Files selected for processing (2)
  • tests/test_device_auth.py
  • tests/test_workspace.py

@@ -0,0 +1,116 @@
"""Tests for device-code authentication helpers."""

import json
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Remove unused import json.

The pipeline reports this import is unused. Remove it to fix the CI failure.

Proposed fix
-import json
📝 Committable suggestion

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

Suggested change
import json
🧰 Tools
🪛 GitHub Actions: Pre-commit

[error] 3-3: flake8 F401: 'json' imported but unused

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_device_auth.py` at line 3, Remove the unused top-level import
statement "import json" from the test module; simply delete the line containing
"import json" so the file no longer imports json unnecessarily and the CI
unused-import error is resolved.

Comment on lines +90 to +96
# Mock sleep to avoid waiting
with patch("time.sleep"):
token = poll_for_token("dev_123")
assert isinstance(token, TokenResponse)
assert token.access_token == "token_123"
assert token.email == "test@example.com"
assert token.plan == "pro"
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check how poll_for_token handles sleep - look for the function signature and sleep usage
ast-grep --pattern 'def poll_for_token($$$) {
  $$$
}'

# Also search for how sleep_fn is defined/used
rg -n "sleep_fn|time\.sleep" --type py -C3

Repository: Refactron-ai/Refactron_lib

Length of output: 8930


🏁 Script executed:

#!/bin/bash
# Check test file structure and imports
head -50 tests/test_device_auth.py

# Check if there's a conftest.py with shared fixtures
find . -name "conftest.py" -type f

# Look for the specific test function
grep -n "def test_poll_for_token_success" tests/test_device_auth.py -A 30

Repository: Refactron-ai/Refactron_lib

Length of output: 2852


🏁 Script executed:

#!/bin/bash
# Check for conftest.py
cat conftest.py 2>/dev/null || echo "No conftest.py at root"

# Check in tests directory
ls -la tests/conftest.py 2>/dev/null || echo "No conftest.py in tests/"

# Look for any module reload or import mechanics
rg -n "reload|importlib" tests/test_device_auth.py

Repository: Refactron-ai/Refactron_lib

Length of output: 117


Patch target time.sleep won't intercept the default bound reference.

The function signature has sleep_fn: Callable[[float], None] = time.sleep, which binds time.sleep at module import time. Patching the global time.sleep afterward won't affect this bound default. Either patch at the use site with patch("refactron.core.device_auth.time.sleep") or pass a mock sleep_fn parameter: poll_for_token("dev_123", sleep_fn=mock_sleep).

🧰 Tools
🪛 Ruff (0.15.7)

[error] 94-94: Possible hardcoded password assigned to: "access_token"

(S105)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_device_auth.py` around lines 90 - 96, The test patches time.sleep
but poll_for_token binds time.sleep as the default argument sleep_fn at import
time, so the patch doesn't take effect; update the test to either patch the
function at the use site (patch "refactron.core.device_auth.time.sleep") or call
poll_for_token with an explicit mock sleep_fn (e.g., poll_for_token("dev_123",
sleep_fn=mock_sleep)) so the sleep call is intercepted; target the
poll_for_token function and its sleep_fn default to ensure the mock is used.

Comment on lines +3 to +6
import json
import os
from pathlib import Path
from unittest.mock import MagicMock, patch
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Remove unused imports to fix failing lint checks.

Line [4], Line [5], and Line [6] include unused imports (os, Path, MagicMock), which currently fail pre-commit (flake8 F401).

Proposed fix
 import json
-import os
-from pathlib import Path
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
📝 Committable suggestion

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

Suggested change
import json
import os
from pathlib import Path
from unittest.mock import MagicMock, patch
import json
from unittest.mock import patch
🧰 Tools
🪛 GitHub Actions: Pre-commit

[error] 4-4: flake8 F401: 'os' imported but unused


[error] 5-5: flake8 F401: 'pathlib.Path' imported but unused


[error] 6-6: flake8 F401: 'unittest.mock.MagicMock' imported but unused

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_workspace.py` around lines 3 - 6, Remove the unused imports
causing flake8 F401 in tests/test_workspace.py: delete the unused symbols "os",
"Path" (from pathlib), and "MagicMock" (from unittest.mock) from the import
list, leaving only the actually used imports (e.g., json, patch) or
alternatively import them where they are used; ensure the top-of-file import
line(s) reference only active symbols such as "json" and "patch".

Comment on lines +42 to +48
def test_manager_initialization(temp_config):
"""Test that manager ensures config directory exists."""
manager = WorkspaceManager(config_path=temp_config)
assert temp_config.exists()
# Should contain empty dict
with open(temp_config, "r") as f:
assert json.load(f) == {}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Drop unused local variable in initialization test.

Line [44] assigns manager but never uses it (flake8 F841).

Proposed fix
 def test_manager_initialization(temp_config):
     """Test that manager ensures config directory exists."""
-    manager = WorkspaceManager(config_path=temp_config)
+    WorkspaceManager(config_path=temp_config)
     assert temp_config.exists()
📝 Committable suggestion

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

Suggested change
def test_manager_initialization(temp_config):
"""Test that manager ensures config directory exists."""
manager = WorkspaceManager(config_path=temp_config)
assert temp_config.exists()
# Should contain empty dict
with open(temp_config, "r") as f:
assert json.load(f) == {}
def test_manager_initialization(temp_config):
"""Test that manager ensures config directory exists."""
WorkspaceManager(config_path=temp_config)
assert temp_config.exists()
# Should contain empty dict
with open(temp_config, "r") as f:
assert json.load(f) == {}
🧰 Tools
🪛 GitHub Actions: Pre-commit

[error] 44-44: flake8 F841: local variable 'manager' is assigned to but never used

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_workspace.py` around lines 42 - 48, The test assigns an unused
local variable `manager` in test_manager_initialization which triggers flake8
F841; either remove the assignment and just call
WorkspaceManager(config_path=temp_config) or use the variable (e.g., assert
isinstance(manager, WorkspaceManager)) so the created object is used; update the
test function (referencing test_manager_initialization and WorkspaceManager)
accordingly to eliminate the unused `manager` variable.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@refactron/core/workspace.py`:
- Line 49: The current use of data.get("repo_id") can yield None and violate
WorkspaceMapping.repo_id: int; change the assignment to validate and coerce the
value (e.g., read via data["repo_id"] and cast to int) or explicitly check and
raise a clear error if missing/invalid. Update the code that constructs
WorkspaceMapping (replace data.get("repo_id") with int(data["repo_id"]) wrapped
in a try/except or an explicit if not present check) so repo_id is always an int
or a descriptive exception is raised.

In `@tests/test_cli_repo.py`:
- Around line 143-152: Update the test so it asserts remove_workspace is called
with the full repository identifier returned by the mocked
WorkspaceManager.get_workspace mapping rather than the short name; specifically,
when patching WorkspaceManager.get_workspace (variable mapping) and mocking
WorkspaceManager.remove_workspace (mock_remove), change the expectation from
mock_remove.assert_called_once_with("test-repo") to assert it was called with
the full repo name from mapping (use the mapping key/value that represents the
full repo identifier) so the disconnect command is validated against the real
key used by remove_workspace.
- Around line 7-14: The test currently mutates sys.modules globally by assigning
mock_torch and mock_st (MagicMock) at import time, which can leak across tests;
change this to a fixture-scoped patch using pytest's monkeypatch (e.g., in a
fixture or before-test setup) and call monkeypatch.setitem(sys.modules, "torch",
mock_torch) and monkeypatch.setitem(sys.modules, "sentence_transformers",
mock_st) instead of direct assignment, ensuring the mocks (mock_torch, mock_st)
are created inside the fixture/function and cleanup is automatic after each
test; update any references to the existing top-level mock_torch/mock_st to use
the fixture-provided mocks.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ad606ee9-3b63-4b6b-bfac-5617e9571254

📥 Commits

Reviewing files that changed from the base of the PR and between 89292dc and c550e2a.

📒 Files selected for processing (2)
  • refactron/core/workspace.py
  • tests/test_cli_repo.py

repo_full_name=data["repo_full_name"],
local_path=data["local_path"],
connected_at=data["connected_at"],
repo_id=data.get("repo_id"),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

repo_id can silently become None despite int annotation.

At Line 49, data.get("repo_id") returns None when missing, which breaks the WorkspaceMapping.repo_id: int contract and can propagate invalid state.

Proposed fix
+        raw_repo_id = data.get("repo_id", 0)
+        try:
+            repo_id = int(raw_repo_id)
+        except (TypeError, ValueError):
+            repo_id = 0
+
         return cls(
-            repo_id=data.get("repo_id"),
+            repo_id=repo_id,
             repo_name=repo_name,
             repo_full_name=repo_full_name,
             local_path=data.get("local_path", ""),
             connected_at=data.get("connected_at", ""),
         )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@refactron/core/workspace.py` at line 49, The current use of
data.get("repo_id") can yield None and violate WorkspaceMapping.repo_id: int;
change the assignment to validate and coerce the value (e.g., read via
data["repo_id"] and cast to int) or explicitly check and raise a clear error if
missing/invalid. Update the code that constructs WorkspaceMapping (replace
data.get("repo_id") with int(data["repo_id"]) wrapped in a try/except or an
explicit if not present check) so repo_id is always an int or a descriptive
exception is raised.

Comment on lines +143 to +152
with patch("refactron.cli.repo.WorkspaceManager.get_workspace", return_value=mapping):
with patch("refactron.cli.repo.WorkspaceManager.remove_workspace") as mock_remove:
result = runner.invoke(
__import__("refactron.cli.repo", fromlist=["repo"]).repo,
["disconnect", "test-repo"],
catch_exceptions=False,
)
assert result.exit_code == 0
assert "Removed workspace mapping" in result.output
mock_remove.assert_called_once_with("test-repo")
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Disconnect assertion validates the wrong identifier.

At Line 152, the test asserts remove_workspace("test-repo"), but remove_workspace is keyed by full repo name. This can let a broken disconnect implementation pass.

Proposed fix
-            mock_remove.assert_called_once_with("test-repo")
+            mock_remove.assert_called_once_with("user/test-repo")
📝 Committable suggestion

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

Suggested change
with patch("refactron.cli.repo.WorkspaceManager.get_workspace", return_value=mapping):
with patch("refactron.cli.repo.WorkspaceManager.remove_workspace") as mock_remove:
result = runner.invoke(
__import__("refactron.cli.repo", fromlist=["repo"]).repo,
["disconnect", "test-repo"],
catch_exceptions=False,
)
assert result.exit_code == 0
assert "Removed workspace mapping" in result.output
mock_remove.assert_called_once_with("test-repo")
with patch("refactron.cli.repo.WorkspaceManager.get_workspace", return_value=mapping):
with patch("refactron.cli.repo.WorkspaceManager.remove_workspace") as mock_remove:
result = runner.invoke(
__import__("refactron.cli.repo", fromlist=["repo"]).repo,
["disconnect", "test-repo"],
catch_exceptions=False,
)
assert result.exit_code == 0
assert "Removed workspace mapping" in result.output
mock_remove.assert_called_once_with("user/test-repo")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_cli_repo.py` around lines 143 - 152, Update the test so it asserts
remove_workspace is called with the full repository identifier returned by the
mocked WorkspaceManager.get_workspace mapping rather than the short name;
specifically, when patching WorkspaceManager.get_workspace (variable mapping)
and mocking WorkspaceManager.remove_workspace (mock_remove), change the
expectation from mock_remove.assert_called_once_with("test-repo") to assert it
was called with the full repo name from mapping (use the mapping key/value that
represents the full repo identifier) so the disconnect command is validated
against the real key used by remove_workspace.

@shrutu0929 shrutu0929 force-pushed the chore-increase-coverage-final branch from a101022 to adf2306 Compare March 26, 2026 17:22
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
refactron/core/workspace.py (1)

47-58: ⚠️ Potential issue | 🔴 Critical

Remove duplicated keyword arguments in WorkspaceMapping(...) call (syntax blocker).

The constructor call on lines 47–58 repeats five keyword arguments: repo_id, repo_name, repo_full_name, local_path, and connected_at are each specified twice with different values. Lines 48–52 establish the correct values; lines 53–57 are duplicate entries that must be removed to fix the syntax error.

Proposed fix
         return cls(
             repo_id=data.get("repo_id"),
             repo_name=repo_name,
             repo_full_name=repo_full_name,
             local_path=data.get("local_path", ""),
             connected_at=data.get("connected_at", ""),
-            repo_name=data["repo_name"],
-            repo_full_name=data["repo_full_name"],
-            local_path=data["local_path"],
-            connected_at=data["connected_at"],
-            repo_id=data.get("repo_id"),
         )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@refactron/core/workspace.py` around lines 47 - 58, The cls(...) constructor
call currently passes duplicate keyword arguments (repo_id, repo_name,
repo_full_name, local_path, connected_at) twice which causes a syntax error;
remove the second set of duplicates (the entries from
repo_name=data["repo_name"] through repo_id=data.get("repo_id") at the end) and
keep the first set using data.get(...) or default values
(repo_id=data.get("repo_id"), repo_name=repo_name,
repo_full_name=repo_full_name, local_path=data.get("local_path", ""),
connected_at=data.get("connected_at", "")) so the cls(...) invocation has each
keyword only once.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@refactron/core/workspace.py`:
- Around line 47-58: The cls(...) constructor call currently passes duplicate
keyword arguments (repo_id, repo_name, repo_full_name, local_path, connected_at)
twice which causes a syntax error; remove the second set of duplicates (the
entries from repo_name=data["repo_name"] through repo_id=data.get("repo_id") at
the end) and keep the first set using data.get(...) or default values
(repo_id=data.get("repo_id"), repo_name=repo_name,
repo_full_name=repo_full_name, local_path=data.get("local_path", ""),
connected_at=data.get("connected_at", "")) so the cls(...) invocation has each
keyword only once.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5bb2b97b-4a17-4d79-833d-601e304dc7e4

📥 Commits

Reviewing files that changed from the base of the PR and between c550e2a and a101022.

📒 Files selected for processing (2)
  • refactron/core/workspace.py
  • tests/test_cli_repo.py
✅ Files skipped from review due to trivial changes (1)
  • tests/test_cli_repo.py

@shrutu0929 shrutu0929 force-pushed the chore-increase-coverage-final branch 2 times, most recently from 0b67c4e to adf2306 Compare March 26, 2026 18:10
@shrutu0929 shrutu0929 force-pushed the chore-increase-coverage-final branch from a1bf978 to 760202e Compare March 26, 2026 18:30
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

♻️ Duplicate comments (2)
tests/test_cli_repo.py (2)

10-17: ⚠️ Potential issue | 🟠 Major

Avoid import-time global sys.modules mutation.

Line 13 and Line 17 patch sys.modules globally at import time, which can leak across unrelated tests and make execution order matter.

Proposed fix
-# Mock torch BEFORE any refactron imports to prevent DLL crash on Windows
-mock_torch = MagicMock()
-mock_torch.__spec__ = MagicMock()
-sys.modules["torch"] = mock_torch
-
-mock_st = MagicMock()
-mock_st.__spec__ = MagicMock()
-sys.modules["sentence_transformers"] = mock_st
+@pytest.fixture(autouse=True)
+def mock_heavy_deps(monkeypatch):
+    """Isolate heavy dependency mocks per test."""
+    mock_torch = MagicMock()
+    mock_torch.__spec__ = MagicMock()
+    monkeypatch.setitem(sys.modules, "torch", mock_torch)
+
+    mock_st = MagicMock()
+    mock_st.__spec__ = MagicMock()
+    monkeypatch.setitem(sys.modules, "sentence_transformers", mock_st)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_cli_repo.py` around lines 10 - 17, The current test injects
mock_torch and mock_st into sys.modules at import time (mock_torch, mock_st and
sys.modules["torch"/"sentence_transformers"]), which leaks globally; instead,
make the mocks temporary inside the test using a fixture such as pytest's
monkeypatch (e.g., monkeypatch.setitem(sys.modules, "torch", mock_torch) and
monkeypatch.setitem(sys.modules, "sentence_transformers", mock_st)) or use
unittest.mock.patch.dict around the import, so the replacement of "torch" and
"sentence_transformers" is applied only during the test/import and removed
afterward.

122-127: ⚠️ Potential issue | 🟠 Major

Re-check canonical identifier used in disconnect assertion.

Line 127 still asserts the short name. Given workspace mappings are stored by full repo name (repo_full_name), this test may validate the wrong key path and miss a disconnect bug.

#!/bin/bash
set -euo pipefail

# Verify key contract used by workspace CRUD and disconnect flow
rg -n -C4 'def add_workspace|def get_workspace|def remove_workspace' refactron/core/workspace.py
rg -n -C4 'def repo_disconnect|remove_workspace\(' refactron/cli/repo.py
rg -n -C4 'test_repo_disconnect_success|assert_called_once_with' tests/test_cli_repo.py

Expected verification: remove_workspace contract should clearly show whether canonical full name is required. If yes, assert using mapping.repo_full_name.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_cli_repo.py` around lines 122 - 127, The test is asserting that
WorkspaceManager.remove_workspace was called with the short name ("test-repo")
but workspace mappings use the canonical full repo identifier; update the
assertion in the test to use the mapping's canonical id by replacing
mock_remove.assert_called_once_with("test-repo") with
mock_remove.assert_called_once_with(mapping.repo_full_name), keeping the rest of
the invocation (runner.invoke(..., ["disconnect", "test-repo"])) and output
check intact; ensure you reference WorkspaceManager.get_workspace /
WorkspaceManager.remove_workspace and the mapping variable so the test verifies
the correct key is used.
🧹 Nitpick comments (1)
tests/test_cli_repo.py (1)

130-134: Remove or convert unused helper to fixture.

temp_workspace is currently unused in this file, which adds noise and confusion.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_cli_repo.py` around lines 130 - 134, The helper temp_workspace is
unused and should be removed or converted into a pytest fixture: either delete
the temp_workspace function entirely to remove dead code, or change it into a
fixture by renaming it (e.g., `@pytest.fixture` def temp_workspace(tmp_path):) and
keeping the body that creates config_path and returns
WorkspaceManager(config_path=config_path) so tests can depend on it; reference
the temp_workspace function and WorkspaceManager class when making the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@tests/test_cli_repo.py`:
- Around line 10-17: The current test injects mock_torch and mock_st into
sys.modules at import time (mock_torch, mock_st and
sys.modules["torch"/"sentence_transformers"]), which leaks globally; instead,
make the mocks temporary inside the test using a fixture such as pytest's
monkeypatch (e.g., monkeypatch.setitem(sys.modules, "torch", mock_torch) and
monkeypatch.setitem(sys.modules, "sentence_transformers", mock_st)) or use
unittest.mock.patch.dict around the import, so the replacement of "torch" and
"sentence_transformers" is applied only during the test/import and removed
afterward.
- Around line 122-127: The test is asserting that
WorkspaceManager.remove_workspace was called with the short name ("test-repo")
but workspace mappings use the canonical full repo identifier; update the
assertion in the test to use the mapping's canonical id by replacing
mock_remove.assert_called_once_with("test-repo") with
mock_remove.assert_called_once_with(mapping.repo_full_name), keeping the rest of
the invocation (runner.invoke(..., ["disconnect", "test-repo"])) and output
check intact; ensure you reference WorkspaceManager.get_workspace /
WorkspaceManager.remove_workspace and the mapping variable so the test verifies
the correct key is used.

---

Nitpick comments:
In `@tests/test_cli_repo.py`:
- Around line 130-134: The helper temp_workspace is unused and should be removed
or converted into a pytest fixture: either delete the temp_workspace function
entirely to remove dead code, or change it into a fixture by renaming it (e.g.,
`@pytest.fixture` def temp_workspace(tmp_path):) and keeping the body that creates
config_path and returns WorkspaceManager(config_path=config_path) so tests can
depend on it; reference the temp_workspace function and WorkspaceManager class
when making the change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3f30845b-6a15-4e0a-ade7-c1c6d83f8984

📥 Commits

Reviewing files that changed from the base of the PR and between a101022 and 760202e.

📒 Files selected for processing (3)
  • refactron/core/workspace.py
  • tests/test_cli_repo.py
  • tests/test_workspace.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/test_workspace.py
  • refactron/core/workspace.py

@github-actions
Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had recent activity for 14 days.

If you believe this PR is still relevant, please:

  • Add a comment explaining why
  • Remove the stale label
  • Or simply comment to keep it active

This helps us keep the repository focused on active contributions. Thank you! 🙏

@github-actions github-actions bot added the stale label Apr 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant