Skip to content

test(files): add unit tests for Shallow Scan - #181

Merged
NityamPareek merged 1 commit into
files-shallow-scanfrom
test/shallow-scan-unit-tests
Sep 21, 2026
Merged

NityamPareek merged 1 commit into
files-shallow-scanfrom
test/shallow-scan-unit-tests

Conversation

@NityamPareek

Copy link
Copy Markdown
Collaborator

Summary of Changes

Adds 36 fixture-free unit tests for the OneDrive and SharePoint Shallow Scan path introduced in #180. All test data is defined inline, so the suite runs in about two seconds from a clean checkout with no fixture generation step.

Test architecture

Organised in four layers, each mocking at a different seam so a failure points at exactly one thing:

Layer Under test Mocked at
1 _split_library_endpoint Nothing — pure function, no I/O
2 SpRestConnector cert_token_manager.get_session()
3 _build_library_targets, _scan_document_libraries SpRestConnector._execute_get
4 calculate_resource_metrics MockUrlInvoker + _execute_get

Layer 2 deliberately mocks the session rather than the connector, so the real retry, throttle and HTTP status handling executes. Those tests construct SpRestConnector(mgr, max_retries=1) so the backoff loop never actually sleeps.

Success coverage

  • OneDrive endpoint URLs are asserted byte-identical to strings reproduced verbatim from the pre-refactor implementation.
  • Encoded spaces, subsite webs rooted at their own _api, OData apostrophe escaping, system libraries, trailing slashes.
  • folderCount = ItemCount - TotalFileCount, resourceCount = max(item_count, folders + files), OData string integers.
  • Multiple libraries accumulating onto one site rather than overwriting.
  • Subsite libraries rolling up to the root site collection.
  • Per-library driveMetrics holding each library's own numbers.
  • Large and Warning thresholds at DL, Subsite and Site with correct parents, and that the boundary is strict (exactly at the limit does not breach).
  • Tenant totals equalling the sum of site rows, N/A preservation, isShallowScan, site classification.

Failure coverage

  • HTTP 403, 404, 401, 429 and 500, including 429-then-success honouring Retry-After and 401 triggering an inline token refresh.
  • All-or-nothing invariant: if ItemCount succeeds but StorageMetrics fails, the library contributes nothing rather than partial counts. This encodes the behaviour chosen during design and is the case most likely to be accidentally "optimised" into partial credit later.
  • A failing library not corrupting its siblings, and the failed tally staying exact.
  • Unresolvable site and library URLs being skipped and recorded.
  • Site discovery failure, empty target list, hard stop, and unexpected exceptions returning {}.

Parametrised cases use subTest to keep the file compact — for example all six endpoint shapes are a single test, as are the three failure-type mappings.

Shared fakes

Added to tests/files/mocks.py, following the existing convention of centralising mocks for the files suites:

  • MockSpSession — thread-safe session keyed by URL fragment, supporting response sequences so retry paths can be exercised. Thread safety matters because _scan_document_libraries drives it from a ThreadPoolExecutor.
  • MockCertTokenManager — domain-keyed token manager that records refresh calls.
  • MockResponse — gains optional text and headers, which SpRestConnector reads on its 403, 429 and 500 paths. text is a lazy property, so bodies are only serialised if a caller actually reads them and existing callers are completely unaffected.

Test discovery

Empty tests/__init__.py and tests/files/__init__.py are added. Discovery previously failed outright for every pattern:

python3 -m unittest discover -s tests -t . -p "*_test.py"
  -> ImportError: Start directory is not importable

It now works for tests/files. Bringing the remaining suites into discovery is intentionally left out of scope.

Validation

  • python3 -m unittest tests.files.shallow_estimator_test -v → 36 tests, OK, 2.0s
  • python3 -m unittest discover -s tests -t . -p "*_test.py" → 36 tests, OK
  • python3 -m compileall -q tests → clean

Passing tests prove little on their own, so the suite was validated by mutating the production code and confirming each mutation is caught:

Mutation applied to shallow_file_estimator.py Result
s_meta["fileCount"] += changed to = FAILED (3 tests)
Warning threshold > changed to >= FAILED (1 test)
Roll up to owning site instead of top-level site FAILED (2 tests)
Remove the owning == top_level subsite guard FAILED (2 tests)

The file was restored identical afterwards and the suite returned to OK.

Out of scope

This PR only adds tests and does not change any production code. Two pre-existing test problems were found while verifying and are deliberately left for a follow-up:

  1. tests/files/load_tests.py fails on largeResourceCount by exactly one. data_state_creator.py appends the SITE COLLECTION entry to tenantLevelLargeResources but never increments the site's own largeResourceCount, whereas file_estimator.py does. Reproduces on a freshly generated fixture, so it is a genuine generator/estimator disagreement rather than a stale fixture.
  2. tests/eo_in_place_archives/ has seven failures, all the same 0 != N signature in calculate_resource_count. Unrelated to files.

Neither is caused by this change: both were reproduced with the committed mocks.py swapped back in and with the new __init__.py files removed.

Adds 36 fixture-free unit tests for the OneDrive and SharePoint Shallow
Scan path. All test data is defined inline, so the suite runs in about
two seconds from a clean checkout with no fixture generation step.

The tests are organised in four layers, each mocking at a different seam
so a failure points at one thing:

  1. _split_library_endpoint    pure, no I/O. Endpoint string correctness
                                including OneDrive parity with the
                                pre-refactor implementation, encoded
                                spaces, subsite webs and OData escaping.
  2. SpRestConnector            mocks the session so the real retry,
                                throttle and status handling executes.
                                Covers 200, 403, 404, 401, 429 and 500.
  3. _scan_document_libraries   patches _execute_get so aggregation and
                                threshold logic runs without sleeping.
                                Covers multi-library roll-up, subsite
                                roll-up, DL/Subsite/Site thresholds and
                                failure isolation.
  4. calculate_resource_metrics full orchestration over the Graph mock.

Failure scenarios are covered alongside success, including the
all-or-nothing invariant: if ItemCount succeeds but StorageMetrics
fails, the library must contribute nothing rather than partial counts.

Parametrised cases use subTest to keep the file compact.

Shared fakes are added to tests/files/mocks.py, following the existing
convention of centralising mocks for the files suites:
  - MockSpSession, a thread-safe session keyed by URL fragment that
    supports response sequences so retry paths can be exercised.
  - MockCertTokenManager, a domain-keyed token manager that records
    refresh calls.
  - MockResponse gains optional text and headers, which SpRestConnector
    reads on its 403, 429 and 500 paths. Both are lazy and optional, so
    existing callers are unaffected.

Empty tests/__init__.py and tests/files/__init__.py are added so
`python3 -m unittest discover` can import the package. Discovery
previously failed with ImportError for every pattern.

Run with:
  python3 -m unittest tests.files.shallow_estimator_test -v
@NityamPareek
NityamPareek merged commit ef14f58 into files-shallow-scan Sep 21, 2026
1 check passed
@NityamPareek
NityamPareek deleted the test/shallow-scan-unit-tests branch September 21, 2026 09:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant