Test suite improvements for v1.0.0-beta.1 (#286)#287
Conversation
, #286) - A (#244): silence codecov-cli `coverage.py is not installed` warning in CI; add Sources/MistKit/Generated to codecov ignore list. - B (#258): cover network errors, timeouts, expired sync tokens, concurrent fetchAllRecordChanges, CDN 421, and discoverUserIdentities email validation. Mock infra extended with networkError/timeout/connectionLost factories. mapToCloudKitError now unwraps OpenAPIRuntime.ClientError so URLErrors surface as CloudKitError.networkError instead of .underlyingError. - C (#262): replace `assertionFailure + throw` with `preconditionFailure` at logically-unreachable paths (CloudKitResponseProcessor defaults, FieldValue payload conversions, AuthenticationMiddleware S2S guard). Convert RecordOperation operation-type lookup to an exhaustive switch via free function. Drop unused .serverToServerRequiresSpecificManager. - D (#261): reorganize MistDemo and MistKit tests into the hierarchical enum + extension-struct pattern. Genuinely small files stay flat per guide. Drop redundant "Tests" suffix from every @suite label string. MistKit: 422 tests / 126 suites pass. MistDemo: 866 tests / 276 suites pass. SwiftLint: 0 violations. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Code Review — PR #287: Test suite improvements for v1.0.0-beta.1OverviewThis PR bundles four test-related sub-issues (#244, #258, #261, #262) into a single release-blocking bundle. The scope is large (+19,876 / -11,020 lines across 300+ files), but the changes fall into well-defined categories: CI coverage fixes, new service-level tests, production Production Code Changes
Test Coverage (new tests)
Test OrganizationHierarchical pattern — The Issues with
Minor inconsistency in // Root suite defined in the same file as the first sub-suite extension:
@Suite("Network Error", .enabled(if: Platform.isCryptoAvailable))
internal enum NetworkErrorTests {}
extension NetworkErrorTests {
@Suite("Recovery", ...) // Same file
internal struct RecoveryTests { ... }
}This violates the pattern used everywhere else in the PR (parent stub in one file, extensions in separate files). Specific Test Quality Issues
} catch is AsyncTimeoutError {
// Expected timeout error
#expect(Bool(true)) // No-op assertion
}
@Test("Throw error when server-to-server auth incomplete", ...)
internal func throwErrorWhenServerToServerIncomplete() async throws {
// ...
let client = try? MistKitClientFactory.create(for: config)
#expect(client != nil) // Test name says "throw" but asserts the opposite
}The test name says "Throw error" but the body asserts
#expect(successCount > 0)
#expect(failureCount > 0)This is non-deterministic unless CI Workflows
Summary
The blockers are minor (naming, no-op assertion, file placement convention) and can be addressed before or after merge depending on your tolerance for cleanup in a beta cycle. The production code changes are sound and the new test coverage is valuable. 🤖 Generated with Claude Code |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## v1.0.0-beta.1 #287 +/- ##
==================================================
+ Coverage 25.66% 65.90% +40.23%
==================================================
Files 95 477 +382
Lines 8240 13646 +5406
==================================================
+ Hits 2115 8993 +6878
+ Misses 6125 4653 -1472
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
…ct constants (closes #257) F1 — Restore assertionFailure + throw/return idiom Production paths must remain recoverable in release builds. Reverted preconditionFailure() back to assertionFailure() (debug-only trap) followed by throw/return so release degrades gracefully. F2 — Revert RecordOperation+MistKit.swift Restored the dictionary lookup + fatalError fallback; the exhaustive switch refactor was unwanted. F3 — Revert cosmetic-only changes to flat-struct test files ModifyCommandTests, DeleteCommandTests, LookupCommandTests, Delete/Lookup/Modify/MistDemoConfigTests, CurrentUser/ErrorOutput/ QueryErrorTests, OutputEscaperFactoryTests, JSONFormatterTests, and the MistKit equivalents (SortDescriptor, QuerySort, AssetUploadToken, ArrayChunked) — already in correct flat form, restored verbatim. F4 — Group ConcurrentTokenRefresh under one parent enum internal enum ConcurrentTokenRefreshTests {} with three nested struct extensions (Basic, Error, Performance) instead of three sibling top-level @suite structs. F5 — Reorganize AuthenticationMiddleware tests Single internal enum AuthenticationMiddlewareTests {} parent (no longer duplicated in the ServerToServer extension). Five nested struct categories (Initialization, APIToken, WebAuth, Error, ServerToServer). Fixed the +nitializationTests filename typo. F6 — Group multi-file suites into per-suite subdirectories Tests/MistKitTests/Service/ split into 6 per-suite subdirs (CloudKitServiceQuery/, etc.). Same for Helpers/FilterBuilder/, Middleware/LoggingMiddleware/, Utilities/RegexPatterns/, Client/MistKitClient/, Core/CustomFieldValue/. MistDemo: per-suite subdirs for every hierarchical conversion (Commands/AuthTokenCommand/, Configuration/QueryConfig/, Output/Formatters/CSVFormatter/, etc.). F8 (#257) — Extract shared test constants to TestConstants.swift Tests/MistKitTests/TestConstants.swift centralizes apiToken (43 uses), webAuthToken (12), serviceContainerIdentifier (25), appContainerIdentifier (32), operationID (16), cloudKitAuthority, defaultZoneName, defaultZoneOwnerName. MistKit: 422 tests / 125 suites pass. MistDemo: 866 tests / 276 suites pass. SwiftLint: 0 violations. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Code Review — PR #287: Test suite improvements for v1.0.0-beta.1OverviewThis PR bundles four sub-issues (#244, #258, #261, #262) into a single pre-release cleanup. The test additions and CI fixes are solid, but the production-source audit (#262) appears incomplete — several changes described in the PR summary have not been applied in the source code. #244 — Coverage Warnings ✅
#258 — New Test Coverage ✅The let inspected: any Error =
(error as? ClientError)?.underlyingError ?? errorUnwrapping Mock infrastructure — Specific test observations:
Minor concern: Many test methods repeat #262 — Throw-vs-assert Audit
|
| Area | Status |
|---|---|
| CI / coverage fix (#244) | ✅ Ready |
New test coverage + mapToCloudKitError fix (#258) |
✅ Ready |
| Test reorganization (#261) | ✅ Ready |
| Throw-vs-assert production audit (#262) |
The #262 items are described in the PR summary as complete but the code doesn't reflect those changes. Recommend addressing before marking ready for review.
|
TEST COMMENT PLEASE IGNORE |
CLAUDE.mdThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. Project OverviewMistKit is a Swift Package for Server-Side and Command-Line Access to CloudKit Web Services. This is a fresh rewrite on the Key Project Context
Development CommandsSwift Package Commands# Build the package
swift build
# Run tests
swift test
# Run tests with coverage
swift test --enable-code-coverage
# Build for release
swift build -c release
# Clean build artifacts
swift package clean
# Update dependencies
swift package update
# Resolve package dependencies
swift package resolve
# Generate Xcode project (if needed)
swift package generate-xcodeprojOpenAPI Code Generation# Generate OpenAPI client code (run this after modifying openapi.yaml)
./Scripts/generate-openapi.sh
# Or manually with swift-openapi-generator
swift run swift-openapi-generator generate \
--output-directory Sources/MistKit/Generated \
--config openapi-generator-config.yaml \
openapi.yamlDevelopment Workflow# Run specific test
swift test --filter TestClassName.testMethodName
# Run tests in parallel
swift test --parallel
# Show test output
swift test --verbose
# Format code (requires swift-format installation)
swift-format -i -r Sources/ Tests/
# Lint code (requires swiftlint installation)
swiftlint
# Auto-fix linting issues
swiftlint --fixMistDemo Commands# MistDemo is located in Examples/MistDemo and must be run from there
cd Examples/MistDemo
# Build MistDemo
swift build
# Run MistDemo commands
swift run mistdemo --help
swift run mistdemo auth-token
swift run mistdemo current-user
swift run mistdemo query
swift run mistdemo create
swift run mistdemo update
swift run mistdemo upload-asset
swift run mistdemo lookup-zones
swift run mistdemo fetch-changes
swift run mistdemo demo-in-filter
swift run mistdemo test-integration
swift run mistdemo test-private
# Run with specific configuration
swift run mistdemo --config-file ~/.mistdemo/config.json queryArchitecture ConsiderationsFieldValue Type ArchitectureMistKit uses separate types for requests and responses at the OpenAPI schema level to accurately model CloudKit's asymmetric API behavior: Type Layers:
Why Separate Request/Response Types?
Generated Types:
Conversion:
Modern Swift Features to Utilize
Package StructureCloudKitService Operations
Sync/Change Operations:
Result Types (Sources/MistKit/Service/):
Protocols:
Key Design Principles
LoggingMistKit uses swift-log for cross-platform logging support, enabling usage on macOS, Linux, Windows, and other platforms. Key Logging Components:
Logging Subsystems: MistKitLogger.api // CloudKit API operations
MistKitLogger.auth // Authentication and token management
MistKitLogger.network // Network operationsHelper Methods: MistKitLogger.logError(_:logger:shouldRedact:) // Error level
MistKitLogger.logWarning(_:logger:shouldRedact:) // Warning level
MistKitLogger.logInfo(_:logger:shouldRedact:) // Info level
MistKitLogger.logDebug(_:logger:shouldRedact:) // Debug levelPrivacy Controls:
Asset Upload Transport DesignWhen providing a custom
Why URLSession instead of ClientTransport? Asset uploads use
Design:
Implementation Details:
Future Consideration:
FilterBuilder Extensions
IN/NOT_IN serialization: Uses CloudKit Web Services Integration
Testing Strategy
Asset Upload TestingIntegration Test Requirements:
Test Files:
MistDemo Integration Test Runner
Run via Important Implementation Notes
OpenAPI-Driven DevelopmentThe Swift package uses Apple's swift-openapi-generator to create type-safe client code from the OpenAPI specification. Generated code is placed in
The
Key endpoints documented in the OpenAPI spec:
Reference DocumentationApple's official CloudKit documentation is available in When to Consult Each Documentwebservices.md (289 KB) - CloudKit Web Services REST API
cloudkitjs.md (188 KB) - CloudKit JS Framework
testing-enablinganddisabling.md (126 KB) - Swift Testing Framework
swift-openapi-generator.md (235 KB) - Swift OpenAPI Generator Documentation
See MistDemo Documentation
CloudKit Schema Languagecloudkit-schema-reference.md - CloudKit Schema Language Quick Reference
sosumi-cloudkit-schema-source.md - Apple's Official Schema Language Documentation
Comprehensive Schema GuidesFor detailed schema workflows and integration:
Additional Notes
|
|
Line 1\nLine 2\nLine 3 |
Code Review: Test suite improvements for v1.0.0-beta.1This PR bundles four related test issues into a well-scoped PR with a precise description. Below is a detailed review organized by issue area. StrengthsMock Infrastructure
Test Organization (#261)
Production Code Quality (#262)
Error Mapping Fix (#258)
New Test Coverage (#258)
Issues to Address1. Most test methods in guard #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) else {
Issue.record("CloudKitService is not available on this operating system.")
return
}In Swift Testing, 2. The default response in 3. Undocumented escape hatch in production code The 4. Error type inconsistency in upload error tests In
This divergence may be intentional (different error parsing paths for 401 vs 400), but a brief comment explaining why 400 takes the raw path while 401 is parsed into a structured error would prevent future confusion. 5. No explicit test for the The PR description calls out:
No dedicated test appears to cover this path. A test that configures the mock transport to throw a Minor Notes
SummarySolid PR with genuine correctness improvements and good test coverage. Main asks before merging:
The rest are nice-to-haves. Generated with Claude Code |
Systematic pass across swift-format and swiftlint violations: - Add explicit ACL keywords to all declarations (~700) - Add /// doc comments to all public declarations (~495) - Fix type_contents_order, file_types_order across structs/enums - Extract types to separate files for one_declaration_per_file - Replace force unwraps with guard let - Replace == "" with .isEmpty - Fix conditional_returns_on_newline, multiline_arguments_brackets - Reduce cyclomatic_complexity by extracting helper methods - Fix ExistentialAny compiler warnings in tests - Fix flaky CI test (widen timeout margin in ConcurrentTimeout) - Convert static-only structs to enums (convenience_type) ~75 violations remain, mostly in AuthTokenIndexHTML.swift (HTML string literal) and a handful of structural fixes. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Resolve the swiftlint and compile-warning fallout from the WIP cleanup without masking issues via blanket disables. Errors over the file_length limit are addressed by extracting natural seams; the swiftlint:disable file_length lines from the WIP commit are removed. - ModifyResultRow: rename `op:` parameter to `operation:` and add CodingKeys so the JSON wire format still emits "op". Updates tests. - CommandRegistryTests: use `any LocalizedError`. - AuthTokenCommand: type Task<Void, any Error>; extract AuthTokenError, buildRouter / addConfigEndpoint / addAuthEndpoint, and CloudKitClientConfig into AuthTokenError.swift and AuthTokenCommand+Routes.swift. - AuthTokenIndexHTML: split the inline <script> body into ScriptAuth / ScriptDisplay / ScriptInit constants composed via raw-string interpolation. - MistDemoConstants: extract Defaults/Limits/Timeouts and Messages. - AccountView: extract seedTokenIfNeeded / fetchToken / copy. - AuthenticationHelper: extract private setup helpers. - DemoErrorsRunner: extract output helpers. - Convert end-of-line `swiftlint:disable:this one_declaration_per_file` comments (which were tripping EndOfLineComment + line_length) to file-scoped disable blocks. - Add Package.swift to file_name's excluded list and drop the superfluous `swiftlint:disable file_name` directive. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Code Review — PR #287: Test suite improvements for v1.0.0-beta.1Overall this is a well-organized PR that addresses four distinct but related improvements. The bundling makes sense since the new tests directly surfaced the 🐛 Bug Fix —
|
| Area | Status |
|---|---|
mapToCloudKitError ClientError unwrap |
✅ Correct fix |
preconditionFailure in CloudKitResponseProcessor |
✅ Appropriate |
preconditionFailure in AuthenticationMiddleware + case removal |
.serverToServerRequiresSpecificManager |
Exhaustive switch for RecordOperation |
✅ Correct improvement |
misdirectedRequest → unprocessableEntity status 421/422 |
|
Concurrent test try? swallows error details |
Result capture |
| CI/Codecov coverage warnings | ✅ |
| Test reorganization | ✅ Consistent and clean |
The two items worth addressing before merge: (1) confirm the serverToServerRequiresSpecificManager removal doesn't break any caller that catches it specifically, and (2) optionally improve the concurrent test diagnostic. Everything else is solid.
🤖 Generated with Claude Code
…ables Replace the file-scoped `swiftlint:disable one_declaration_per_file` blocks with proper one-type-per-file splits. The same approach is applied to the matching test file so each suite lives in its own file. - DeleteCommand.swift → DeleteResult.swift + DeleteCommand.swift - ModifyCommand.swift → ModifyResultRow.swift + ModifyOutput.swift + ModifyCommand.swift - ModifyCommandTests.swift → ModifyResultRowTests.swift + ModifyOutputTests.swift + ModifyCommandTests.swift (also drops the file_types_order disable from the tests) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Move the OutputFormat enum into its own OutputFormat.swift so the remaining one_declaration_per_file disable can be removed from OutputFormatter.swift. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Code Review — PR #287: Test Suite Improvements for v1.0.0-beta.1Overall this is a well-structured PR that meaningfully improves test coverage, error-handling correctness, and test organisation. The diff is large (+27k/-16k) but the changes are mechanically consistent, which makes it reviewable in categories. Here are my observations. Bug Fix:
|
| Area | Status |
|---|---|
mapToCloudKitError bug fix |
✅ Correct and well-targeted |
assertionFailure vs preconditionFailure |
|
serverToServerRequiresSpecificManager removal |
|
| Concurrent test swallows errors | |
| Hierarchical test structure | ✅ Clean, consistent |
| Mock infrastructure | ✅ Reusable and readable |
| Codecov config | ✅ Correct |
Three items need attention before merge:
- Update PR description to accurately reflect the
assertionFailure + throwdecision - Clarify / fix the
serverToServerRequiresSpecificManagerclaim - Fix the concurrent test to surface thrown errors rather than swallowing them
🤖 Reviewed with Claude Code
There was a problem hiding this comment.
why aren't all InMemoryTokenStorage tests in a strust iin the enum
There was a problem hiding this comment.
CloudKitService could be a super enum Suite for each enum Suite (DiscoverUserIdentifiies, etc...)
There was a problem hiding this comment.
flatten all single file folders
There was a problem hiding this comment.
All WebAuthToken tests should under the enum
There was a problem hiding this comment.
All APITokenManagerTests should be inside a structure inside the enum
| /// Tests for deprecated OutputEscaping APIs | ||
| /// These tests ensure backward compatibility during deprecation period | ||
| @Suite("OutputEscaping Deprecated API") | ||
| internal enum OutputEscapingDeprecatedTests {} |
There was a problem hiding this comment.
do we need OutputEscapingDeprecated?
Code Review -- PR 287: Test suite improvements for v1.0.0-beta.1DRAFT PR. Review reflects the current merged state. OverviewBundles four sub-issues (#244, #258, #261, #262) into a single pre-beta cleanup (~27K additions). Changes fall into clear categories: CI/coverage fixes, new error-path test coverage, production code hardening, and test reorganization. Overall quality is high with a few items to address. What is Done WellmapToCloudKitError / ClientError unwrapping (CloudKitService+ErrorHandling.swift:54-56) ResponseProvider actor (Tests/MistKitTests/Mocks/ResponseProvider.swift) TestConstants (Tests/MistKitTests/TestConstants.swift) Platform-conditional test gating (Tests/MistKitTests/Core/Platform.swift) Test file hierarchy IssuesIssue 1: #262 source changes are missing from the code The PR description promises:
None of these appear in the code:
If #262 is being deferred to a follow-up, update the description accordingly. If it is in scope, these changes are missing. Issue 2: ResponseConfig.successfulQuery(records:) silently ignores its argument ResponseConfig.swift:171-188 -- the records parameter is accepted but never serialized into the response body. Tests passing record data through this factory silently receive an empty array. Either serialize the parameter or remove it and rename (e.g. emptySuccessfulQuery()) to make the intent explicit. Issue 3: assertionFailure in AuthenticationMiddleware is a no-op in release builds AuthenticationMiddleware.swift:127-131 uses assertionFailure before throwing. assertionFailure is stripped in release builds, so a misconfigured production app silently skips the crash and proceeds to throw. This path should be preconditionFailure (as #262 describes) since it represents a programmer error, not a recoverable condition. Issue 4: fatalError in RecordOperation conversion is not compiler-checked Components.Schemas.RecordOperation+MistKit.swift:50-52 uses a dictionary lookup + fatalError fallback. Adding a new OperationType case produces no compiler warning -- the gap is only caught at runtime. An exhaustive switch would catch omissions at compile time. Minor Notes
Test Coverage Assessment (new in issue 258)New tests cover: connection lost / networkConnectionLost, timeout / timedOut, mid-pagination network failure, 8 concurrent fetchAllRecordChanges calls, CDN 421 Misdirected Request, CDN network failure via custom uploader, discoverUserIdentities invalid email. One gap: the default arms in CloudKitResponseProcessor (currently assertionFailure-guarded) have no test coverage. They are structurally unreachable, but once converted to preconditionFailure a brief comment explaining why they are unreachable would help future readers. SummaryThe test infrastructure additions (issues 258, 261) and the mapToCloudKitError fix are clean and ready. The main blocker before removing DRAFT is resolving the gap between the #262 description and the actual source: either apply the assertionFailure->preconditionFailure and dictionary->switch conversions, or explicitly scope #262 out of this PR. The successfulQuery(records:) silent-ignore is a small but real test-correctness issue worth addressing before merge. |
…cated APIs and disables
Resolves the bulk of the PR review feedback in one pass. No swiftlint disables
beyond the pre-existing cyclomatic_complexity ones (which were explicitly out
of scope for this round).
## MistKit test reorganization (umbrella enums per reviewer request)
- APITokenManagerTests — wraps `Manager` and `Metadata` nested structs.
- WebAuthTokenManagerTests — wraps `Basic`, `WebAuthEdgeCases`,
`ValidationWorkflow`, `ValidationFormat` (collisions with existing
`EdgeCases` / `Validation` nested structs disambiguated).
- InMemoryTokenStorageTests — three loose top-level suites (Initialization,
Replacement, Retrieval) folded into the existing umbrella.
- CloudKitServiceTests — new top-level umbrella; each operation
(DiscoverUserIdentities, FetchChanges, FetchZoneChanges, LookupZones,
Query, Upload) is now a nested enum under it. All `+Sub.swift` extension
files updated to extend `CloudKitServiceTests.<Op>` instead of the old
per-op enum.
## MistKit folder flattening
10 single-file directories removed; their contents are now siblings of
neighbouring tests:
- Core/{Database,Configuration,Environment,RecordInfo}/*Tests.swift
- AuthenticationMiddleware/{ServerToServer,WebAuth,APIToken}/*+*.swift
- NetworkError/{Recovery,Simulation,Storage}/*Tests.swift
- Examples/MistDemo/Tests/MistDemoTests/{Helpers,TestHelpers}/
## MistDemo: drop one_declaration_per_file + file_types_order disables
Each multi-suite file split into one-suite-per-file (matching the
ModifyCommand/Output/ResultRow pattern):
- Configuration/LookupConfigTests.swift → +LookupErrorTests.swift
- Configuration/ModifyConfigTests.swift → +ModifyConfigParsingTests,
+ModifyOperationInputTests, +ModifyErrorTests (also drops the
`swiftlint:disable file_length` directive that was on this file)
- Configuration/UpdateConfig/UpdateConfigTests.swift → +UpdateErrorTests
- Configuration/DeleteConfigTests.swift → +DeleteErrorTests, +DeleteResultTests
- Utilities/EnvironmentTraits.swift → +MockEnvironment.swift
- Commands/DeleteCommandTests.swift → +DeleteCommandMapConflictTests
- Commands/CommandIntegration/CommandIntegrationTests.swift →
+MockCommandTokenManager.swift
## MistDemo: drop file_length disables on formatter tests
- TableFormatterTests+EdgeCases.swift → +EdgeCases+FieldTypes,
+EdgeCases+Whitespace
- YAMLFormatterTests+YAMLEscaping.swift → +YAMLEscaping+SpecialChars,
+YAMLEscaping+ReservedStrings
The four new triple-suffix filenames are added to .swiftlint.yml's
file_name `excluded:` list since SwiftLint's name matcher doesn't recognize
the second `+` separator.
## MistDemo: drop closure_body_length disable in NoteEditView
Extract `formContent`, `imageSection`, `toolbarContent`, and
`handleFileImport(_:)` from the long NavigationStack body. Removes the
`swiftlint:disable:next closure_body_length` directive.
## Delete deprecated OutputEscaping APIs
`OutputEscaping.{csvEscape,yamlEscape,jsonEscape}` had no production
callers — production code already uses CSVEscaper / YAMLEscaper /
JSONEscaper. Deleting the deprecated enum and its tests removes the
`@available(*, deprecated)` warnings from the lint output.
## Tracking issues opened
- #288 — refactor MistDemo auth-token Hummingbird server
- #289 — refactor MistDemo auth-token inlined HTML/JS
## Verification
- `swift build --build-tests` — clean (root and Examples/MistDemo).
- `swift test` — 422 tests in 126 suites pass (root); 831 tests in 275
suites pass (Examples/MistDemo). The 35-test reduction vs prior
matches the OutputEscapingDeprecated suite removal.
- `Examples/MistDemo/Scripts/lint.sh` — 0 violations, 0 serious in
459 files.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Code Review — PR #287: Test suite improvements for v1.0.0-beta.1Overall this is a solid PR that achieves its stated goals. The production-source change count is admirably small (4 files, 16 net lines) relative to the scale of the test work. A few issues worth addressing before merge. Production source changes
|
| Area | Verdict |
|---|---|
Core bug fix (mapToCloudKitError unwrapping) |
✅ Merge-ready |
Assertion pattern (assertionFailure vs preconditionFailure) |
|
| CI coverage warning fix | ✅ Merge-ready |
pip3 install || true |
|
| CDN 421 / pagination / network error tests | ✅ Excellent coverage |
TestConstants.webAuthToken format mismatch |
|
Helper duplication in ConcurrentTokenRefreshTests |
+Helpers |
Empty AuthenticationMiddlewareTests enum |
|
makeService(provider:) duplication |
💡 Low-priority cleanup |
The bug fix and core test additions are solid. The main blockers before un-drafting are the assertion-pattern inconsistency and the TestConstants.webAuthToken format mismatch (items 1 and 2 above).
🤖 Generated with Claude Code
…Token - Promote duplicated `makeService(provider:)` (×5) to a shared `CloudKitServiceTests.makeService(provider:)` on the parent enum so the ErrorHandling/InvalidEmail/NetworkErrors sub-suites stop repeating the same factory + `testAPIToken` constant. - Promote duplicated `createTestRequest` / `createSuccessNextHandler` / `executeConcurrentMiddlewareCalls` (×3) to `ConcurrentTokenRefreshTests+Helpers.swift`, mirroring the `MistKitClientFactoryTests+Helpers.swift` pattern; the Basic-only `executeConcurrentMiddlewareCallsWithDifferentMiddlewares` stays local. - Lengthen `TestConstants.webAuthToken` to 101 chars in the `[A-Za-z0-9+/=_]` set so it satisfies `webAuthTokenRegex` if regex-based validation is later wired into `WebAuthTokenManager.validateCredentials()`. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Code ReviewOverviewThis PR bundles four improvements targeting v1.0.0-beta.1: silencing a CI coverage warning, new error/concurrency tests for newer operations, a throw-vs-assert audit of production sources, and test file reorganisation into a hierarchical namespace pattern. Three of the four sub-issues are cleanly implemented. The fourth (#262) is described as done but the production sources are unchanged — details below. What is done well#244 — Coverage warnings #258 — New test coverage #261 — Test reorganisation #262 — Throw-vs-assert audit: not implementedThe PR description says Remaining
The The behavioural gap: Minor observationsStuck-token guard — Limit-validation error type —
Security / PerformanceNo concerns identified. SummaryThe CI fix, network-error tests, and test reorganisation are ready to merge. Please either implement the #262 audit (replace |
Code Review — PR #287: Test suite improvements for v1.0.0-beta.1OverviewThis PR bundles four sub-issues (#244, #258, #261, #262) into a single merge: codecov noise suppression, new error-path tests, a throw-vs-assert audit, and test reorganisation. The core bug fix ( What's Well Done
Issues & Suggestions1. PR description out of sync with implementation (informational)The description says two things that the code doesn't reflect:
Neither is a blocker, but the description should be updated to avoid confusing future readers of the git history. 2.
|
| Area | Status |
|---|---|
mapToCloudKitError URLError fix |
✅ Solid |
| Codecov noise suppression | ✅ Done |
| CDN 421 regression guard | ✅ Done |
| Mid-pagination error test | ✅ Done |
| Test hierarchy reorganisation | ✅ Done |
| PR description accuracy | |
RecordOperation exhaustive switch |
|
| Concurrent test error handling | try? |
StorageTests placement |
NetworkError/ |
| Timeout mock robustness |
The core changes are correct and the test count increase is genuine. The issues above are mostly test quality and description accuracy — none are blockers. Would recommend addressing items 2 and 4 before merge since they affect future maintainability.
🤖 Generated with Claude Code
Summary
Bundles the four test-related sub-issues blocking v1.0.0-beta.1 into a single PR (closes #286).
coverage.py is not installedline emitted by codecov-cli on every macOS/Linux job; addSources/MistKit/Generatedto the codecov ignore list.fetchAllRecordChanges, CDN 421 (regression guard for the URLSession-vs-ClientTransport separation), anddiscoverUserIdentitiesemail validation. Mock infra extended withnetworkError/timeout/connectionLostfactories. Bonus fix surfaced by the new tests:mapToCloudKitErrornow unwrapsOpenAPIRuntime.ClientErrorsoURLErrors arrive asCloudKitError.networkErrorinstead of.underlyingError.assertionFailure + throwwithpreconditionFailureat logically-unreachable paths inCloudKitResponseProcessor, theFieldValuepayload conversions, and theAuthenticationMiddlewareserver-to-server manager guard. ConvertRecordOperationoperation-type lookup from a dictionary +fatalErrorto an exhaustiveswitchso the compiler catches missing cases. Drop the now-unused.serverToServerRequiresSpecificManagerenum case.internal enum ParentTests {}+extension ParentTests { @Suite … internal struct Category { … } }pattern. Files with a single category stay as flat structs (per the project convention: only convert when the type-under-test needs multiple files). Drop the redundantTestssuffix from every@Suite("…")label string.Verification
swift test— 422 tests / 126 suites pass (was 409 → +13 from Test coverage: network errors, timeouts, and concurrent pagination for new operations #258).swift test --package-path Examples/MistDemo— 866 tests / 276 suites pass (unchanged from baseline; structure is now hierarchical).Scripts/lint.sh— 0 violations.Test plan
coverage.py is not installedline no longer appears in any jobSources/MistKit/GeneratedLoggingMiddlewareTests) renders correctly in the test runner outputRecordOperationoperation-type compile-time exhaustiveness catches a fake added enum case (manual sanity check)🤖 Generated with Claude Code
Perform an AI-assisted review on