Skip to content

chore: clean up files created during testing#11844

Merged
Adam-Aghili merged 2 commits intomainfrom
aka/clean-saved-test-files
Mar 2, 2026
Merged

chore: clean up files created during testing#11844
Adam-Aghili merged 2 commits intomainfrom
aka/clean-saved-test-files

Conversation

@Adam-Aghili
Copy link
Collaborator

@Adam-Aghili Adam-Aghili commented Feb 20, 2026

modified test_save_file_component.py to clean up generated test files once tests are done

Added files after runing make unit_tests
Before
Screenshot 2026-02-20 at 5 09 01 PM

After
Screenshot 2026-02-20 at 5 02 27 PM

Summary by CodeRabbit

Release Notes

  • Tests
    • Improved test cleanup procedures to ensure proper resource management during test execution.

Note: This release contains internal testing infrastructure improvements with no direct impact on end-user functionality.

modified test_save_file_component.py to clean up generated test files once tests are done
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 20, 2026

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

A class-scoped pytest fixture was added to clean up test output files generated by TestSaveToFileComponent tests. The fixture uses contextlib.suppress() to safely remove files after test execution, preventing test artifacts from lingering.

Changes

Cohort / File(s) Summary
Test Fixture Addition
src/backend/tests/unit/components/processing/test_save_file_component.py
Added class-scoped cleanup_test_files fixture that removes test output files after tests complete, with import of contextlib module for exception suppression during cleanup.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

🚥 Pre-merge checks | ✅ 7
✅ Passed checks (7 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and accurately summarizes the main change: adding cleanup logic for test files created during testing in the test_save_file_component.py file.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Test Coverage For New Implementations ✅ Passed PR adds only a cleanup fixture to existing test infrastructure; no new components, features, or bug fixes requiring test coverage are introduced.
Test Quality And Coverage ✅ Passed This PR adds a cleanup fixture to existing tests, not new functionality requiring test coverage evaluation.
Test File Naming And Structure ✅ Passed The test file test_save_file_component.py fully adheres to all custom check requirements with proper pytest structure, 21 descriptive test methods, logical organization, class-scoped cleanup fixture, and comprehensive coverage of positive and negative scenarios.
Excessive Mock Usage Warning ✅ Passed Test file demonstrates appropriate and targeted use of mocks with only external dependencies mocked while core logic uses real objects; approximately 50% of tests use no mocks at all, indicating intentional well-structured design.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch aka/clean-saved-test-files

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.

@github-actions
Copy link
Contributor

github-actions bot commented Feb 20, 2026

Frontend Unit Test Coverage Report

Coverage Summary

Lines Statements Branches Functions
Coverage: 23%
22.87% (7981/34889) 15.45% (4224/27334) 15.6% (1147/7348)

Unit Test Results

Tests Skipped Failures Errors Time
2611 0 💤 0 ❌ 0 🔥 43.916s ⏱️

@codecov
Copy link

codecov bot commented Feb 20, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 37.05%. Comparing base (d46f3a6) to head (b5f2fcd).
⚠️ Report is 2 commits behind head on main.

❌ Your project status has failed because the head coverage (41.50%) is below the target coverage (60.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main   #11844   +/-   ##
=======================================
  Coverage   37.05%   37.05%           
=======================================
  Files        1588     1588           
  Lines       77959    77959           
  Branches    11800    11800           
=======================================
+ Hits        28885    28886    +1     
  Misses      47455    47455           
+ Partials     1619     1618    -1     
Flag Coverage Δ
backend 57.31% <ø> (ø)
frontend 20.49% <ø> (ø)
lfx 41.50% <ø> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.
see 7 files with indirect coverage changes

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
src/backend/tests/unit/components/processing/test_save_file_component.py (2)

14-24: Preferred fix: redirect file creation to a temp dir rather than cleaning up CWD artifacts

The cleanup fixture treats the symptom (leftover CWD files) rather than the root cause. The coding guidelines explicitly require using tmp_path / tmp_path_factory so test files never land in the working tree. A class-scoped tmp_path_factory fixture combined with a monkeypatch of Path (or the component's output directory) eliminates the need for any explicit cleanup and works regardless of which directory pytest is invoked from.

♻️ Suggested approach
+import os
 import contextlib
 from pathlib import Path
 ...

 class TestSaveToFileComponent(ComponentTestBaseWithoutClient):
-    `@pytest.fixture`(scope="class", autouse=True)
-    def cleanup_test_files(self):
-        """Clean up test files after all tests in the class complete."""
-        yield
-        # Clean up test files created during tests
-        test_files = ["test_data.json", "test_message.txt", "test_output.csv"]
-        for filename in test_files:
-            filepath = Path(filename)
-            if filepath.exists():
-                with contextlib.suppress(Exception):
-                    filepath.unlink()
+    `@pytest.fixture`(scope="class")
+    def test_output_dir(self, tmp_path_factory):
+        """Provide a dedicated temp directory for all file-output tests."""
+        return tmp_path_factory.mktemp("save_file_tests")

Then pass test_output_dir into the individual tests that exercise local-file output and set file_name to str(test_output_dir / "test_output"), etc., so files land in the temp directory that pytest cleans up automatically.

Based on learnings: "Use aiofiles and anyio.Path for async file operations in tests; create temporary test files using tmp_path fixture and verify file existence and content"

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

In `@src/backend/tests/unit/components/processing/test_save_file_component.py`
around lines 14 - 24, The cleanup_test_files fixture is masking the real issue
by deleting CWD artifacts; replace it with a class-scoped tmp_path_factory-based
temp directory and update tests to write into that temp directory instead of the
CWD. Create a class-scoped fixture (using tmp_path_factory) that yields
test_output_dir and monkeypatch the component's output directory or Path usage
so functions under test (e.g., save file code paths that accept file_name/output
dir) write to str(test_output_dir / "test_output..."); remove cleanup_test_files
and update tests to use aiofiles/anyio.Path or pytest's tmp_path for async file
operations and assert file existence/content in the temp dir so pytest cleans up
automatically.

14-24: Minor fixture implementation nits

Three small clean-ups for the current approach (if kept):

  1. try/finally — per project conventions, fixture teardown should use try/finally instead of relying on implicit post-yield execution.
  2. Redundant existence checkfilepath.exists() is unnecessary because contextlib.suppress already swallows FileNotFoundError.
  3. Overly broad exception suppressioncontextlib.suppress(Exception) silences all errors; OSError (which covers FileNotFoundError and PermissionError) is the appropriate type for filesystem operations.
♻️ Proposed fix
     `@pytest.fixture`(scope="class", autouse=True)
     def cleanup_test_files(self):
         """Clean up test files after all tests in the class complete."""
-        yield
-        # Clean up test files created during tests
-        test_files = ["test_data.json", "test_message.txt", "test_output.csv"]
-        for filename in test_files:
-            filepath = Path(filename)
-            if filepath.exists():
-                with contextlib.suppress(Exception):
-                    filepath.unlink()
+        try:
+            yield
+        finally:
+            test_files = ["test_data.json", "test_message.txt", "test_output.csv"]
+            for filename in test_files:
+                with contextlib.suppress(OSError):
+                    Path(filename).unlink()

Based on learnings: "Use async fixtures with proper cleanup using try/finally blocks to ensure resources are properly released after tests complete"

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

In `@src/backend/tests/unit/components/processing/test_save_file_component.py`
around lines 14 - 24, The fixture cleanup_test_files should perform teardown in
an explicit try/finally block rather than relying on post-yield execution: wrap
the test body in try and move the file-removal loop into the finally block;
remove the redundant filepath.exists() check inside that loop; and narrow
exception suppression to filesystem errors by using contextlib.suppress(OSError)
when calling filepath.unlink() (refer to the cleanup_test_files fixture and the
test_files list).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/backend/tests/unit/components/processing/test_save_file_component.py`:
- Around line 14-24: The cleanup_test_files fixture is masking the real issue by
deleting CWD artifacts; replace it with a class-scoped tmp_path_factory-based
temp directory and update tests to write into that temp directory instead of the
CWD. Create a class-scoped fixture (using tmp_path_factory) that yields
test_output_dir and monkeypatch the component's output directory or Path usage
so functions under test (e.g., save file code paths that accept file_name/output
dir) write to str(test_output_dir / "test_output..."); remove cleanup_test_files
and update tests to use aiofiles/anyio.Path or pytest's tmp_path for async file
operations and assert file existence/content in the temp dir so pytest cleans up
automatically.
- Around line 14-24: The fixture cleanup_test_files should perform teardown in
an explicit try/finally block rather than relying on post-yield execution: wrap
the test body in try and move the file-removal loop into the finally block;
remove the redundant filepath.exists() check inside that loop; and narrow
exception suppression to filesystem errors by using contextlib.suppress(OSError)
when calling filepath.unlink() (refer to the cleanup_test_files fixture and the
test_files list).

@github-actions github-actions bot added the lgtm This PR has been approved by a maintainer label Feb 22, 2026
@github-actions
Copy link
Contributor

github-actions bot commented Feb 24, 2026

Build successful! ✅
Deploying docs draft.
Deploy successful! View draft

@Adam-Aghili Adam-Aghili force-pushed the aka/clean-saved-test-files branch from d3a5ab3 to b5f2fcd Compare March 2, 2026 20:42
@Adam-Aghili Adam-Aghili added this pull request to the merge queue Mar 2, 2026
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks Mar 2, 2026
@Adam-Aghili Adam-Aghili added this pull request to the merge queue Mar 2, 2026
Merged via the queue into main with commit ca9ba72 Mar 2, 2026
95 of 96 checks passed
@Adam-Aghili Adam-Aghili deleted the aka/clean-saved-test-files branch March 2, 2026 21:39
HimavarshaVS pushed a commit that referenced this pull request Mar 10, 2026
modified test_save_file_component.py to clean up generated test files once tests are done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ignore-for-release lgtm This PR has been approved by a maintainer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants