Skip to content

Add tests for FaceDetectorYN#1828

Merged
shimat merged 1 commit intomainfrom
FaceDetectorYN_test
Feb 28, 2026
Merged

Add tests for FaceDetectorYN#1828
shimat merged 1 commit intomainfrom
FaceDetectorYN_test

Conversation

@shimat
Copy link
Owner

@shimat shimat commented Feb 28, 2026

Summary by CodeRabbit

  • Tests
    • Added comprehensive test suite for face detection functionality, including validation of detector creation, parameter configuration, detection accuracy, threshold behavior, and resource management.

@shimat shimat self-assigned this Feb 28, 2026
@coderabbitai
Copy link

coderabbitai bot commented Feb 28, 2026

📝 Walkthrough

Walkthrough

Adds a comprehensive test suite for OpenCV's FaceDetectorYN (YuNet) face detection functionality. The test class includes model provisioning, constructor validation, disposal handling, and detection tests across various scenarios and threshold configurations.

Changes

Cohort / File(s) Summary
FaceDetectorYN Test Suite
test/OpenCvSharp.Tests/objdetect/FaceDetectorYNTest.cs
New test class with static model provisioning, constructor tests (basic and parameterized), disposal verification, and detection tests covering Lenna image detection, blank image handling, repeated calls consistency, and threshold sensitivity analysis. Validates output shape (15 columns: 14 landmarks + score) and confidence scoring.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

🚥 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 'Add tests for FaceDetectorYN' is clear, specific, and directly describes the main change—adding a comprehensive test suite for the FaceDetectorYN functionality.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch FaceDetectorYN_test

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

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

🧹 Nitpick comments (2)
test/OpenCvSharp.Tests/objdetect/FaceDetectorYNTest.cs (2)

131-136: Strengthen multi-call consistency check to include values.

This currently validates only result count and matrix shape. Comparing detection values (with tolerance) would better validate deterministic behavior.

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

In `@test/OpenCvSharp.Tests/objdetect/FaceDetectorYNTest.cs` around lines 131 -
136, The test only asserts matching return counts and matrix shapes for two
calls to detector.Detect but doesn't verify the actual detected values; update
the test in FaceDetectorYNTest to compare the contents of faces1 and faces2
(e.g., iterate elements or use a matrix-equality helper) with a small tolerance
for floating-point differences after calling detector.Detect(image, faces1) and
detector.Detect(image, faces2) and also assert result1 == result2; reference the
Detect method and the faces1/faces2 Mats when adding the element-wise (or
row-wise) comparisons with an asserted tolerance.

82-90: Make Lenna detection count assertion less brittle.

Line 82 currently requires exactly one detection. That can be unstable across environments; asserting at least one face keeps intent while reducing flakiness.

Suggested assertion update
-        Assert.Equal(1, result);
+        Assert.True(result >= 1, $"Expected at least one face, got {result}");
         Assert.False(faces.Empty());
@@
-        Assert.True(faces.Rows > 0, "Expected at least one detected face");
+        Assert.True(faces.Rows > 0, "Expected at least one detected face");
+        Assert.Equal(result, faces.Rows);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/OpenCvSharp.Tests/objdetect/FaceDetectorYNTest.cs` around lines 82 - 90,
Replace the brittle exact-count assertion in the FaceDetectorYNTest by asserting
at least one detection: change the Assert.Equal(1, result) check to an assertion
that result is >= 1 (e.g., Assert.True(result >= 1, "Expected at least one
detected face")), referencing the result variable (and you may rely on the
existing faces.Rows > 0 check) so the test requires one-or-more detections
instead of exactly one.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@test/OpenCvSharp.Tests/objdetect/FaceDetectorYNTest.cs`:
- Around line 16-23: The static constructor FaceDetectorYNTest() currently
writes ModelPath without ensuring its parent directory exists and may throw
during static initialization; modify the provisioning to first ensure the
directory for ModelPath exists (use Path.GetDirectoryName(ModelPath) +
Directory.CreateDirectory) before calling File.WriteAllBytes, and wrap the
download/write (FileDownloader.DownloadData(new Uri(ModelUrl)) and
File.WriteAllBytes) in a try/catch that converts/propagates errors outside the
static constructor (e.g., perform provisioning in a OneTimeSetUp method or
rethrow a clearer exception) to avoid TypeInitializationException for the whole
test class.

---

Nitpick comments:
In `@test/OpenCvSharp.Tests/objdetect/FaceDetectorYNTest.cs`:
- Around line 131-136: The test only asserts matching return counts and matrix
shapes for two calls to detector.Detect but doesn't verify the actual detected
values; update the test in FaceDetectorYNTest to compare the contents of faces1
and faces2 (e.g., iterate elements or use a matrix-equality helper) with a small
tolerance for floating-point differences after calling detector.Detect(image,
faces1) and detector.Detect(image, faces2) and also assert result1 == result2;
reference the Detect method and the faces1/faces2 Mats when adding the
element-wise (or row-wise) comparisons with an asserted tolerance.
- Around line 82-90: Replace the brittle exact-count assertion in the
FaceDetectorYNTest by asserting at least one detection: change the
Assert.Equal(1, result) check to an assertion that result is >= 1 (e.g.,
Assert.True(result >= 1, "Expected at least one detected face")), referencing
the result variable (and you may rely on the existing faces.Rows > 0 check) so
the test requires one-or-more detections instead of exactly one.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 259904d and 997a63f.

📒 Files selected for processing (1)
  • test/OpenCvSharp.Tests/objdetect/FaceDetectorYNTest.cs

Comment on lines +16 to +23
static FaceDetectorYNTest()
{
if (!File.Exists(ModelPath))
{
var contents = FileDownloader.DownloadData(new Uri(ModelUrl));
File.WriteAllBytes(ModelPath, contents);
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Harden model provisioning to avoid class-initialization failures.

Line 21 writes to a nested relative path without ensuring the directory exists, and any download/write error in the static constructor will surface as a TypeInitializationException for the whole test class.

Proposed reliability fix
 static FaceDetectorYNTest()
 {
     if (!File.Exists(ModelPath))
     {
-        var contents = FileDownloader.DownloadData(new Uri(ModelUrl));
-        File.WriteAllBytes(ModelPath, contents);
+        var dir = Path.GetDirectoryName(ModelPath);
+        if (!string.IsNullOrEmpty(dir))
+            Directory.CreateDirectory(dir);
+
+        try
+        {
+            var contents = FileDownloader.DownloadData(new Uri(ModelUrl));
+            File.WriteAllBytes(ModelPath, contents);
+        }
+        catch (Exception ex)
+        {
+            throw new Xunit.Sdk.XunitException(
+                $"Failed to provision YuNet model at '{ModelPath}' from '{ModelUrl}': {ex.Message}");
+        }
     }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/OpenCvSharp.Tests/objdetect/FaceDetectorYNTest.cs` around lines 16 - 23,
The static constructor FaceDetectorYNTest() currently writes ModelPath without
ensuring its parent directory exists and may throw during static initialization;
modify the provisioning to first ensure the directory for ModelPath exists (use
Path.GetDirectoryName(ModelPath) + Directory.CreateDirectory) before calling
File.WriteAllBytes, and wrap the download/write (FileDownloader.DownloadData(new
Uri(ModelUrl)) and File.WriteAllBytes) in a try/catch that converts/propagates
errors outside the static constructor (e.g., perform provisioning in a
OneTimeSetUp method or rethrow a clearer exception) to avoid
TypeInitializationException for the whole test class.

@shimat shimat merged commit 95f438e into main Feb 28, 2026
9 checks passed
@shimat shimat deleted the FaceDetectorYN_test branch February 28, 2026 08:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant