diff --git a/AGENTS.md b/AGENTS.md index 73c6000405..19a4db2d7a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -196,6 +196,7 @@ Build complete, long-term solutions, not MVPs or local workarounds. A broad chan - **New Hypervel-owned code and packages must be Laravel-style** — Design new packages and public surfaces as if they were first-party Laravel packages ported to and enhanced for Hypervel. APIs, naming, class responsibilities, code patterns, and directory structure must be ergonomic, intuitive, and immediately familiar to Laravel developers, while internals remain coroutine-safe and optimized for Hypervel's long-lived Swoole runtime and high-performance requirements. Apply the requirements under [Audit changes during modification and code review](#audit-changes-during-modification-and-code-review) from initial design onward. - **Reserve `assert*` methods for testing APIs** — Use prefixes such as `ensure*` or `validate*` for runtime guards. - **Modern PHP 8.4+ with full typing** — use constructor property promotion, readonly properties, enums, match expressions, named arguments, and attributes where they fit. Every file declares `strict_types=1`; parameters, return types, properties, and class constants are natively typed wherever PHP and the inherited API permit (e.g. `resource` cannot be represented as a native PHP type). PHP does not allow return types on `__construct()` or `__destruct()`. +- **Keep contracts complete** — A contract should declare the documented public API that every conforming implementation must provide, so code that type-hints the contract can use it. Add missing methods when found, even when the omission is inherited from Laravel. Put optional driver capabilities on separate capability interfaces, such as LockProvider. Implementation-specific methods and internal helpers do not belong on contracts. Follow the existing approval rules for Laravel API changes. - **Contract signature dependencies are lazy** — contract signatures may natively reference types from optional split packages without a reverse Composer dependency. Do not remove these types or add cyclic dependencies solely for split-package isolation. - **Dependency access in new packages** — Inject framework service contracts through constructors or methods rather than using helpers, facades, or direct instantiation. Where injection is impractical, such as static contexts or framework-constructed objects, use `Container::getInstance()->make(...)`. Helpers are fine in route and config files. - **Dependency access within existing packages** — Follow the established style of surrounding classes with the same role, including when adding new classes to a ported package. Preserve upstream’s helper, facade and instantiation style where it keeps updates straightforward. A class being newly written is not, by itself, a reason to use a different style. Change dependency access only for a concrete correctness, lifetime, testability or maintainability benefit, and keep related code internally consistent without rewriting unrelated classes. @@ -772,11 +773,10 @@ Run full PHPStan checks with `composer analyse`. During implementation, use targ 2. **Don't make the code worse or more convoluted just to satisfy PHPStan.** Fix real issues in the code, but don't add awkward wrappers, fake branches, casts, or wider types just to silence PHPStan. A type-only fix must not change runtime behavior, add overhead, or introduce new edge cases. A genuine runtime bug that PHPStan exposes is fixed through the normal bug-fix workflow. If you cannot satisfy PHPStan within those constraints, reach consensus on a compliant solution through a second-opinion loop with your peer agent. If the code is correct and PHPStan cannot understand it, follow the source-first rule below. 3. **Check the supported runtime contract before removing guards.** Preserve necessary validation of caller input, consumer configuration and external data. Remove checks that only repeat guarantees the code already enforces; PHPDoc types and facts inferred from the booted application are not such guarantees. 4. **Don't change contract/concrete boundaries to fix phpstan.** Swapping a contract for a concrete (or vice versa) to satisfy a type check diverges from Laravel's API. Only do this when Laravel's typing is genuinely incorrect. -5. **Methods can be added to contracts only if they represent behavior any conforming implementation must provide.** Implementation-specific methods, internal helpers, or driver-specific features don't belong on contracts — find another fix even if adding them would satisfy phpstan. -6. **Type decisions must be evidence-based.** See Development Conventions — check Laravel/Hyperf signatures and docblocks, then trace real control flow. Don't guess. -7. **Fix types at their source.** Correct signatures, PHPDoc, generics, stubs or extensions. Use `assert()` only for genuine invariants; assertions may be disabled and cannot replace required validation. A truthful inline `@var` is a last resort. For verified analysis limitations, use `@phpstan-ignore identifier (reason)`, always including a meaningful reason; never use identifier-less ignores. For a confirmed PHPStan bug, start the reason with `@TODO: Remove once PHPStan` and describe the needed fix; do not add a `docs/todo.md` entry. NEON ignores require approval under the global-ignore rule. -8. **Don't add patterns to `phpstan.neon.dist` on your own.** The neon file's global ignores cover fundamental framework patterns (Eloquent magic, generics, `new static`). Fix new phpstan errors at the source, not by masking them with new neon rules. Global suppression is a rare exception. First, reach consensus through a second-opinion loop with your peer agent that the error cannot be fixed at the source or narrowed locally, and that the pattern is frequent enough to justify global suppression. Then STOP, explain the reason and recommended suppression to the owner, and wait for approval before adding it. -9. **Environment reads outside config files.** Framework source reads the environment outside config files only for a deliberate infrastructure need, such as reads before configuration loads, process transport like `__HYPERVEL_CONTEXT`, or test infrastructure like worker tokens. Use `Env::get()` with an inline `@phpstan-ignore hypervel.noEnvCallsOutsideOfConfig (reason)` stating that need. `Env::get()` is the convention for these intentional reads; switching from `env()` does not fix a read in the wrong place. Do not add directory, path or class-wide exemptions. +5. **Type decisions must be evidence-based.** See Development Conventions — check Laravel/Hyperf signatures and docblocks, then trace real control flow. Don't guess. +6. **Fix types at their source.** Correct signatures, PHPDoc, generics, stubs or extensions. Use `assert()` only for genuine invariants; assertions may be disabled and cannot replace required validation. A truthful inline `@var` is a last resort. For verified analysis limitations, use `@phpstan-ignore identifier (reason)`, always including a meaningful reason; never use identifier-less ignores. For a confirmed PHPStan bug, start the reason with `@TODO: Remove once PHPStan` and describe the needed fix; do not add a `docs/todo.md` entry. NEON ignores require approval under the global-ignore rule. +7. **Don't add patterns to `phpstan.neon.dist` on your own.** The neon file's global ignores cover fundamental framework patterns (Eloquent magic, generics, `new static`). Fix new phpstan errors at the source, not by masking them with new neon rules. Global suppression is a rare exception. First, reach consensus through a second-opinion loop with your peer agent that the error cannot be fixed at the source or narrowed locally, and that the pattern is frequent enough to justify global suppression. Then STOP, explain the reason and recommended suppression to the owner, and wait for approval before adding it. +8. **Environment reads outside config files.** Framework source reads the environment outside config files only for a deliberate infrastructure need, such as reads before configuration loads, process transport like `__HYPERVEL_CONTEXT`, or test infrastructure like worker tokens. Use `Env::get()` with an inline `@phpstan-ignore hypervel.noEnvCallsOutsideOfConfig (reason)` stating that need. `Env::get()` is the convention for these intentional reads; switching from `env()` does not fix a read in the wrong place. Do not add directory, path or class-wide exemptions. ## Porting Packages diff --git a/composer.json b/composer.json index 6e0c0bb427..ff19c6d836 100644 --- a/composer.json +++ b/composer.json @@ -37,7 +37,7 @@ "ext-pcntl": "*", "ext-pdo": "*", "ext-posix": "*", - "ext-redis": "^6.1", + "ext-redis": "^6.3", "ext-session": "*", "ext-simplexml": "*", "ext-sockets": "*", diff --git a/docs/plans/todo/phpredis-6.3-minimum.md b/docs/plans/todo/phpredis-6.3-minimum.md new file mode 100644 index 0000000000..57d09bf8e2 --- /dev/null +++ b/docs/plans/todo/phpredis-6.3-minimum.md @@ -0,0 +1,77 @@ +# Framework-wide PhpRedis 6.3 minimum + +## Status and purpose + +Deferred; obtain authorization before implementing. Development and tests already require PhpRedis `^6.3` in the components root manifest. Published packages continue supporting their existing client versions, including the separate requirements for hash-field expiration. + +Adopt one PhpRedis minimum across installed applications to remove obsolete client-version branches. Hash-field expiration is used by Redis cache tagging and user-session tracking; the native test doubles also need the methods declared by PhpRedis 6.3. Do not replace those native methods with test fixtures or add compatibility shims. + +Redis remains optional for applications that do not use it. A Composer conflict rejects an installed extension below 6.3 even when that application does not use Redis; users must upgrade or unload it. Document PIE as an installation option, not a framework dependency. Before implementation, check current package availability and the current code against this plan. + +## Metadata and installation + +- Keep root `composer.json` at `ext-redis: ^6.3`; update `src/horizon/composer.json` to the same requirement. +- In `src/redis/composer.json`, retain the optional extension suggestion and add `"conflict": {"ext-redis": "<6.3"}`. Framework, Foundation, Cache, Session and Queue already require this package, so do not duplicate the conflict in their manifests or require Redis for every application. +- Update the Redis, Cache and Session extension suggestions to one `^6.3` requirement, removing feature-specific client clauses. +- Use Composer commands for root dependency changes. Split-package manifests have no lockfiles and are edited directly. Never commit the components root lockfile. +- Composer's conflict behavior was verified with a disposable local package: an absent extension and version 6.3 resolve; version 6.2 fails. Repeat this focused check against the final metadata rather than building a permanent Composer test harness. + +## Shared requirement and diagnostics + +In `src/redis/src/RedisRequirements.php`: + +- Set `MINIMUM_PHPREDIS_VERSION` to `6.3.0` and remove its separate-feature qualification. +- Remove `HASH_FIELD_EXPIRATION_PHPREDIS_VERSION` and `hashFieldExpirationClientError()`. +- Add `clientError(string|false $version): ?string`, accepting `phpversion('redis')` directly. Return null for supported clients; report the required and installed versions otherwise. For false, say the extension is not installed rather than presenting a fictitious version zero. Include `pie install phpredis/phpredis` as the installation/upgrade instruction. +- Preserve the Redis and Valkey server constants and `hashFieldExpirationServerError()`. + +Use the shared client check in both diagnostics: + +- `src/cache/src/Redis/Console/Doctor/Checks/PhpRedisCheck.php`: remove the tag-mode constructor parameter and private version-selection method. Update construction in `DoctorCommand.php`. Retain missing-extension detection and useful install/upgrade instructions. Use the spelling `PhpRedis` consistently in the touched output and matching tests. +- `src/doctor/src/Diagnostics/RedisSupportsConfiguredFeatures.php`: check the client once, then check servers only for configured features requiring hash-field expiration. Remove the second, feature-specific client check and the `?: '0'` conversion. Retain inactive-service skipping, real connection failures and cancellation handling. + +Do not add production test seams to diagnostics. Test version decisions through the existing plain-input requirement test and retain existing diagnostic integration coverage. + +## Remove obsolete client branches + +- In `RedisConnection::setOptions()`, remove the pre-6.2 `OPT_PACK_IGNORE_NUMBERS` availability guard. Keep the option mapping and normal invalid-option validation. Remove the stale PhpRedis 6.0 qualification from `pack()`. +- In `Foundation/Testing/Concerns/RequiresHashFieldExpiration`, remove the client branch and `detectedPhpredisVersion()`. Keep server detection, memoization, skip reasons and `flushHashFieldExpirationState()`. +- Remove corresponding old-client test cases and version-dependent skips. Preserve supported behavior assertions and server-capability tests. + +### Boundaries that stay + +- Ordinary Redis server 6.2+ and Valkey 7.2+ remain supported. Features using hash-field expiration still require Redis 8+ or Valkey 9+. +- Keep cache doctor's `RedisVersionCheck` and `HashFieldExpirationCheck`, including the actual command probe. A supported PHP client does not establish server or command availability. +- Keep optional serializer/compression build checks and Cluster-specific limitations such as TCP keepalive behavior. +- Keep service opt-in skips in reusable integration-test traits. A configured but unusable Redis connection must still fail. +- The hash-expiry call-site audit covers native calls and Lua in AnyTag `Add`, `Put`, `PutMany`, `Touch`, `Increment`, `Decrement` and `Forever`, plus `RedisSessionHandler` and cache doctor checks. Their remaining branches select topology, TTL, configured tag mode, tracking or metadata behavior; they are not old-client fallbacks and must not be removed for this bump. Facade annotations and telemetry command names need no change. + +## Tests to update + +- `tests/Composer/PackageManifestConsistencyTest.php`: remove the `ext-redis` subset exception and its unused imports and parser; exact equality applies again once the development and published requirements match. +- `tests/Redis/RedisRequirementsTest.php`: move existing client cases to `clientError()`, use false for the missing extension, and retain older/prerelease/minimum/newer version cases and all server cases. +- `tests/Redis/PackageMetadataTest.php`: preserve the optional-extension assertions; add the conflict assertion to that existing test. +- `tests/Session/PackageMetadataTest.php`: update the exact extension-suggestion assertion. Horizon's metadata test already checks the dependency's presence. +- `tests/Foundation/Testing/Concerns/RequiresHashFieldExpirationTest.php`: remove the old-client skip case, version stub property, assignments and override; retain server failures and memoization coverage. +- `tests/Cache/Redis/Console/DoctorCommandTest.php`: replace the tag-mode client-version dataset with the single-baseline check; remove the old-client skip from the zero-named-store case and update changed diagnostic text. +- `tests/Doctor/Feature/Diagnostics/RedisSupportsConfiguredFeaturesTest.php`: remove obsolete version attributes and the unsupported-client-only integration test; the shared requirement test covers that decision. +- Remove `OPT_PACK_IGNORE_NUMBERS` skips in `tests/Redis/RedisConnectionTest.php`, `tests/Redis/PhpRedisClusterConnectionTest.php`, `tests/Integration/Cache/Redis/RedisStoreTest.php` and `tests/Integration/Cache/Redis/SerializationIntegrationTest.php`. Delete the standalone test expecting the old-client availability exception. +- Remove redundant Redis extension-presence attributes from `tests/Integration/Horizon/Feature/SupervisorTest.php` and `tests/Integration/Queue/Redis/{RedisQueueDriverTest,RedisQueueTest,ThrottlesExceptionsRedisStoreTest,RateLimitedRedisStoreTest}.php`: the development root requires the extension. Remove unused imports; do not remove service configuration checks. + +## Documentation and CI + +- Update the root README and `src/docs/installation.md` minimum. State 6.3 and show `pie install phpredis/phpredis` in `src/docs/redis.md` installation guidance. +- Amend the existing Redis sentence in `src/docs/porting-from-laravel.md` with the minimum and an installation link; do not add a duplicate section. +- Remove redundant client-version qualifiers from `src/docs/cache.md`, `src/docs/session.md`, the `pack_ignore_numbers` documentation, and `RedisStore::setTagMode()`. Preserve server requirements and explain Redis **or** Valkey, not both together. +- Update foundation `config/cache.php` and `config/session.php`, plus both application skeleton mirrors, to describe only the additional server requirements for the relevant features. +- Update stale client-skip comments in `tests/Integration/Cache/Redis/RedisCacheIntegrationTestCase.php` and `tests/Integration/Auth/Redis/EloquentUserProviderCacheTagsTest.php`. +- Remove the two feature-specific PhpRedis comments in `.github/workflows/redis.yml`. The CI Dockerfile already installs and validates 6.3: retain those build checks and change the validation error's rationale from integration coverage to the framework minimum. No new installation workflow, installer dependency or manually pinned binary is needed. +- Leave historical plans and the factual INCREX note in `docs/todo.md` unchanged. Do not update consumer lockfiles merely to replace suggestion text. + +## Verification and completion + +Search all source, tests, manifests, configuration, CI and docs for the removed symbols and client-version requirements, including raw hash-expiry commands in Lua. Check private package/application consumers under the normal consumer-check rules; none referenced the removed helpers at investigation time. + +Run each edited test file immediately. Exercise existing cache hash-expiry and Redis session-tracking integration coverage with an isolated Redis service; rely on CI for the full Redis/Valkey/Cluster matrix. Validate Composer metadata and optional-extension conflict behavior, run source analysis and formatting, then self-review and obtain code review before committing and publishing. + +The final change must contain no obsolete client branches, test stubs, skips or explanatory text. Preserve the server/build/topology checks above. This is a requirement and maintenance improvement, with no new hot-path work or changes to application-facing Redis operations. diff --git a/src/auth/src/Access/Gate.php b/src/auth/src/Access/Gate.php index 59abac0352..ee92b1ed9b 100644 --- a/src/auth/src/Access/Gate.php +++ b/src/auth/src/Access/Gate.php @@ -592,7 +592,9 @@ protected function dispatchGateEvaluatedEvent(mixed $user, string $ability, arra */ protected function resolveAuthCallback(mixed $user, string $ability, array $arguments): callable { + // Gates also accept plain data; only classes and objects can identify a policy. if (isset($arguments[0]) + && (is_object($arguments[0]) || is_string($arguments[0])) && ! is_null($policy = $this->getPolicyFor($arguments[0])) && $callback = $this->resolvePolicyCallback($user, $ability, $arguments, $policy)) { return $callback; @@ -628,8 +630,20 @@ public function getPolicyFor(object|string $class): mixed return $this->resolvePolicy($this->policies[$class]); } - $this->policyClassCache ??= new ArrayObject; - $policyClass = $this->policyClassCache[$class] ??= $this->resolvePolicyClass($class); + $policyClass = $this->policyClassCache[$class] ?? null; + + if ($policyClass === null) { + // Only declared model names are cached. Other inputs may be user data, so their + // policy guesses are normalized to avoid unbounded worker state. For those inputs, + // register policies explicitly when relying on container configuration for PHP class aliases. + $isDeclaredClass = class_exists($class) && (new ReflectionClass($class))->getName() === $class; + $policyClass = $this->resolvePolicyClass($class, $isDeclaredClass); + + if ($isDeclaredClass) { + $this->policyClassCache ??= new ArrayObject; + $this->policyClassCache[$class] = $policyClass; + } + } return $policyClass !== false ? $this->resolvePolicy($policyClass) @@ -645,7 +659,7 @@ public function getPolicyFor(object|string $class): mixed * * @return class-string|false */ - private function resolvePolicyClass(string $class): string|false + private function resolvePolicyClass(string $class, bool $isDeclaredClass): string|false { $policy = $this->getPolicyFromAttribute($class); @@ -655,7 +669,7 @@ private function resolvePolicyClass(string $class): string|false foreach ($this->guessPolicyName($class) as $guessedPolicy) { if (class_exists($guessedPolicy)) { - return $guessedPolicy; + return $isDeclaredClass ? $guessedPolicy : (new ReflectionClass($guessedPolicy))->getName(); } } diff --git a/src/cache/src/Console/ClearCommand.php b/src/cache/src/Console/ClearCommand.php index ddd12c3e83..4d7b908035 100644 --- a/src/cache/src/Console/ClearCommand.php +++ b/src/cache/src/Console/ClearCommand.php @@ -60,7 +60,6 @@ public function handle(): int [$this->argument('store'), $this->tags()] ); - /** @phpstan-ignore method.notFound (flush() is on TaggedCache or via __call to the store) */ $successful = $this->cache()->flush(); $this->flushProxies(); diff --git a/src/cache/src/Repository.php b/src/cache/src/Repository.php index d283b0b580..3de9ec527d 100644 --- a/src/cache/src/Repository.php +++ b/src/cache/src/Repository.php @@ -148,7 +148,9 @@ public function get(array|UnitEnum|string $key, mixed $default = null): mixed /** * Retrieve multiple items from the cache by key. - * Items not found in the cache will have a null value. + * + * Numeric entries are requested keys, while string-keyed entries use their + * values as defaults. Missing keys without a default resolve to null. */ public function many(array $keys): array { @@ -880,6 +882,15 @@ public function deleteMultiple(iterable $keys): bool return $result; } + /** + * Remove all items from the cache. + */ + public function flush(): bool + { + // Forward through clear() so flush() emits the same events instead of bypassing them via __call(). + return $this->clear(); + } + /** * Remove all items from the cache. */ diff --git a/src/contracts/src/Cache/Repository.php b/src/contracts/src/Cache/Repository.php index bd46871b80..d981952d94 100644 --- a/src/contracts/src/Cache/Repository.php +++ b/src/contracts/src/Cache/Repository.php @@ -7,9 +7,13 @@ use Closure; use DateInterval; use DateTimeInterface; +use InvalidArgumentException; use Psr\SimpleCache\CacheInterface; use UnitEnum; +/** + * Includes the shared public cache operations omitted by Laravel's contract so callers can depend on this interface. + */ interface Repository extends CacheInterface { /** @@ -20,6 +24,53 @@ interface Repository extends CacheInterface */ public function get(array|UnitEnum|string $key, mixed $default = null): mixed; + /** + * Retrieve a string item from the cache. + * + * @param null|(Closure(): (null|string))|string $default + * + * @throws InvalidArgumentException + */ + public function string(UnitEnum|string $key, callable|string|null $default = null): string; + + /** + * Retrieve an integer item from the cache. + * + * @param null|(Closure(): (null|int))|int $default + * + * @throws InvalidArgumentException + */ + public function integer(UnitEnum|string $key, callable|int|null $default = null): int; + + /** + * Retrieve a float item from the cache. + * + * @param null|(Closure(): (null|float))|float $default + * + * @throws InvalidArgumentException + */ + public function float(UnitEnum|string $key, callable|float|null $default = null): float; + + /** + * Retrieve a boolean item from the cache. + * + * @param null|bool|(Closure(): (null|bool)) $default + * + * @throws InvalidArgumentException + */ + public function boolean(UnitEnum|string $key, callable|bool|null $default = null): bool; + + /** + * Retrieve an array item from the cache. + * + * @param null|array|(Closure(): (null|array)) $default + * + * @return array + * + * @throws InvalidArgumentException + */ + public function array(UnitEnum|string $key, callable|array|null $default = null): array; + /** * Store an item in the cache. */ @@ -30,6 +81,14 @@ public function set(UnitEnum|string $key, mixed $value, DateInterval|DateTimeInt */ public function delete(UnitEnum|string $key): bool; + /** + * Retrieve multiple items from the cache by key. + * + * Numeric entries are requested keys, while string-keyed entries use their + * values as defaults. Missing keys without a default resolve to null. + */ + public function many(array $keys): array; + /** * Retrieve multiple items from the cache by key. * @@ -55,6 +114,11 @@ public function deleteMultiple(iterable $keys): bool; */ public function has(array|UnitEnum|string $key): bool; + /** + * Determine if an item doesn't exist in the cache. + */ + public function missing(UnitEnum|string $key): bool; + /** * Retrieve an item from the cache and delete it. */ @@ -65,6 +129,11 @@ public function pull(UnitEnum|string $key, mixed $default = null): mixed; */ public function put(array|UnitEnum|string $key, mixed $value, DateInterval|DateTimeInterface|int|null $ttl = null): bool; + /** + * Store multiple items in the cache for a given number of seconds. + */ + public function putMany(array $values, DateInterval|DateTimeInterface|int|null $ttl = null): bool; + /** * Store an item in the cache if the key does not exist. */ @@ -182,6 +251,11 @@ public function touch(UnitEnum|string $key, DateInterval|DateTimeInterface|int $ */ public function forget(array|UnitEnum|string $key): bool; + /** + * Remove all items from the cache. + */ + public function flush(): bool; + /** * Get the cache store implementation. */ diff --git a/src/docs/deployment.md b/src/docs/deployment.md index 1cb101a0be..94bf0ddc50 100644 --- a/src/docs/deployment.md +++ b/src/docs/deployment.md @@ -13,6 +13,7 @@ - [Caching Events](#caching-events) - [Caching Routes](#optimizing-route-loading) - [Caching Views](#optimizing-view-loading) + - [Autoloader Optimization](#autoloader-optimization) - [Reloading Services](#reloading-services) - [Debug Mode](#debug-mode) - [The Health Route](#the-health-route) @@ -218,6 +219,25 @@ php artisan view:cache This command precompiles all your Blade views so they are not compiled on demand, improving the performance of each request that returns a view. + +### Autoloader Optimization + +When deploying to production, install your dependencies with an authoritative Composer class map: + +```shell +composer install --no-dev --classmap-authoritative +``` + +Composer will then load classes only from its generated class map. This avoids filesystem searches for missing classes and stops long-running workers from keeping a record of every missing class name they look up, including names taken from request data. Classes added after the map is built can't be loaded until it is rebuilt. Hypervel's generated AOP proxies and class map overrides use their own loaders and are not affected. Leave this option off during local development so new classes load without rebuilding the map. + +To check this during deployment, install [Doctor](/docs/{{version}}/doctor#installation) without `--dev`, run the following command against the built release in its production environment, and stop the deployment if it fails: + +```shell +php artisan doctor --only=ComposerAutoloadIsAuthoritative --no-interaction +``` + +The check is skipped when Doctor runs in a [local environment](/docs/{{version}}/doctor#environment-modes). + ## Reloading Services diff --git a/src/docs/doctor.md b/src/docs/doctor.md index 717f5d6993..6c14826b6a 100644 --- a/src/docs/doctor.md +++ b/src/docs/doctor.md @@ -193,7 +193,7 @@ The `pass` and `warn` methods build results from the diagnostic's named messages Doctor ships with a focused suite of diagnostics that cover common configuration, environment, dependency, database, queue, and storage problems. The default suite includes: - **Environment** — the selected environment file, `APP_KEY`, PHP version constraints, and required and recommended PHP extensions. -- **Composer** — installed dependencies, optimized autoload validation, lock-file consistency, and local repairs for eligible dependency problems. +- **Composer** — installed dependencies, optimized autoload validation, an [authoritative class map in production](/docs/{{version}}/deployment#autoloader-optimization), lock-file consistency, and local repairs for eligible dependency problems. - **Configuration** — configuration files can be loaded and cached, configuration values required by the active drivers are set, and bootstrap cache files are reported when their presence does not match the current environment. - **Database** — the default connection is reachable, including its selectable read and write records. Explicit `::read` or `::write` defaults check that role. Doctor also checks the selected SQLite database file and can apply pending migrations automatically in local environments. - **Cache, queue, scheduler, and session** — selected drivers and active Redis data and lock connections are reachable, degraded failover capacity is reported, `sync` queues are flagged outside local environments, and scheduled tasks prompt advice to keep `schedule:run` running. Background and deferred queues run in coroutines and need no external worker; null queues intentionally discard jobs. diff --git a/src/docs/porting-from-laravel.md b/src/docs/porting-from-laravel.md index 1d97d7ddd5..e9843e7bf2 100644 --- a/src/docs/porting-from-laravel.md +++ b/src/docs/porting-from-laravel.md @@ -1031,6 +1031,8 @@ Do not replace the Hypervel skeleton's `composer.json`, `bootstrap/app.php`, `co Hypervel runs its Swoole HTTP server using `php artisan serve` and does not use `public/index.php` as its HTTP entry point. Review the [deployment documentation](/docs/{{version}}/deployment) before adapting web server or process-monitor configuration. +Build production releases with `composer install --no-dev --classmap-authoritative` instead of `--optimize-autoloader`; Doctor fails production checks without an authoritative class map. See [Autoloader Optimization](/docs/{{version}}/deployment#autoloader-optimization). + Hypervel uses Vite for frontend assets and does not provide Laravel Mix or the `mix()` helper. Keep or migrate assets to the Vite integration described in the [Vite documentation](/docs/{{version}}/vite). Hypervel does not include support for Laravel Cloud, which is built for Laravel applications. For a managed platform built for Hypervel applications and their long-running services, use [SonicStack](https://sonicstack.io), the Hypervel team's deployment platform. See [Deploying With SonicStack](/docs/{{version}}/deployment#deploying-with-sonicstack). diff --git a/src/doctor/README.md b/src/doctor/README.md index 50f3147aa3..1579745733 100644 --- a/src/doctor/README.md +++ b/src/doctor/README.md @@ -9,4 +9,6 @@ Documentation: https://hypervel.org/docs/doctor Use `EnvironmentMode::fromHypervelEnvironment()` in place of `fromLaravelEnvironment()`. +`ComposerAutoloadIsAuthoritative` fails in production unless Composer uses an [authoritative class map](https://hypervel.org/docs/deployment#autoloader-optimization). + Ported from: https://github.com/laravel/doctor diff --git a/src/doctor/src/Diagnostics/ComposerAutoloadIsAuthoritative.php b/src/doctor/src/Diagnostics/ComposerAutoloadIsAuthoritative.php new file mode 100644 index 0000000000..9242d30b5b --- /dev/null +++ b/src/doctor/src/Diagnostics/ComposerAutoloadIsAuthoritative.php @@ -0,0 +1,50 @@ + + */ + protected function messages(): array + { + return [ + 'local' => 'Authoritative autoloading is not required during development.', + 'authoritative' => 'Composer uses an authoritative class map.', + 'not-authoritative' => Message::make( + summary: 'Composer does not use an authoritative class map in production.', + remediation: 'Build the release with `composer install --no-dev --classmap-authoritative`, then restart the workers.', + )->link(Link::docs('deployment', 'autoloader-optimization')), + ]; + } + + /** + * Run the diagnostic. + */ + public function check(): DiagnosticResult + { + if (! EnvironmentMode::current()->isProduction()) { + return $this->skip('local'); + } + + return Composer::getLoader()->isClassMapAuthoritative() + ? $this->pass('authoritative') + : $this->fail('not-authoritative'); + } +} diff --git a/src/doctor/src/Diagnostics/ComposerAutoloadIsValid.php b/src/doctor/src/Diagnostics/ComposerAutoloadIsValid.php index 8bd116d2ad..47c78c0a54 100644 --- a/src/doctor/src/Diagnostics/ComposerAutoloadIsValid.php +++ b/src/doctor/src/Diagnostics/ComposerAutoloadIsValid.php @@ -11,6 +11,7 @@ use Hypervel\Doctor\Results\Message; use Hypervel\Doctor\Support\Composer; use Hypervel\Foundation\PackageManifest; +use Hypervel\Support\Composer as ComposerSupport; use Hypervel\Support\Facades\Process; class ComposerAutoloadIsValid extends Diagnostic implements Fixable @@ -26,14 +27,16 @@ class ComposerAutoloadIsValid extends Diagnostic implements Fixable */ protected function messages(): array { + $command = 'composer dump-autoload ' . $this->autoloadOptimizationOption(); + return [ 'composer-missing' => 'The application does not have a composer.json file.', 'dependencies-missing' => 'Composer dependencies are not installed.', 'valid' => 'Composer can generate optimized autoload files.', 'invalid' => Message::make( summary: 'Composer cannot generate valid autoload files.', - remediation: 'Regenerate Composer autoload files with `composer dump-autoload`.', - confirmation: 'Regenerate Composer autoload files using `composer dump-autoload`?', + remediation: "Regenerate Composer autoload files with `{$command}`.", + confirmation: "Regenerate Composer autoload files using `{$command}`?", ), 'regeneration-failed' => 'Composer autoload files could not be regenerated.', 'regenerated' => 'Composer autoload files were regenerated.', @@ -81,7 +84,7 @@ public function fix(DiagnosticResult $result, ?string $option = null): FixResult $process = Process::path(base_path())->forever()->run([ ...Composer::command(), 'dump-autoload', - '--optimize', + $this->autoloadOptimizationOption(), '--strict-psr', '--strict-ambiguous', '--no-interaction', @@ -94,4 +97,13 @@ public function fix(DiagnosticResult $result, ?string $option = null): FixResult return $this->fixed('regenerated'); } + + /** + * Get the optimization option that preserves the current autoloader mode. + */ + private function autoloadOptimizationOption(): string + { + // Unlike upstream's optimize-only repair, preserve authoritative class lookup when enabled. + return ComposerSupport::getLoader()->isClassMapAuthoritative() ? '--classmap-authoritative' : '--optimize'; + } } diff --git a/src/doctor/src/DoctorServiceProvider.php b/src/doctor/src/DoctorServiceProvider.php index 8ed6deac53..963196b7aa 100644 --- a/src/doctor/src/DoctorServiceProvider.php +++ b/src/doctor/src/DoctorServiceProvider.php @@ -11,6 +11,7 @@ use Hypervel\Doctor\Diagnostics\BootstrapCacheMatchesEnvironment; use Hypervel\Doctor\Diagnostics\CacheStoreIsReachable; use Hypervel\Doctor\Diagnostics\ComposerAuditPasses; +use Hypervel\Doctor\Diagnostics\ComposerAutoloadIsAuthoritative; use Hypervel\Doctor\Diagnostics\ComposerAutoloadIsValid; use Hypervel\Doctor\Diagnostics\ComposerLockIsFresh; use Hypervel\Doctor\Diagnostics\ConfigurationCanBeCached; @@ -54,6 +55,7 @@ public function register(): void RecommendedPhpExtensionsAreLoaded::class, // ApplicationTimezoneIsValid is omitted: Hypervel rejects invalid timezones during boot. ComposerAutoloadIsValid::class, + ComposerAutoloadIsAuthoritative::class, ComposerLockIsFresh::class, ConfigurationFilesCanBeLoaded::class, ConfigurationCanBeCached::class, diff --git a/src/phpstan/src/Collectors/SwallowedCancellationCollector.php b/src/phpstan/src/Collectors/SwallowedCancellationCollector.php index dcac1a833d..0abce8a574 100644 --- a/src/phpstan/src/Collectors/SwallowedCancellationCollector.php +++ b/src/phpstan/src/Collectors/SwallowedCancellationCollector.php @@ -836,9 +836,7 @@ private function getOperation(CallLike $call, array $statements, Scope $scope, b $declaringClass = $method->getDeclaringClass()->getName(); // The class using a trait declares its methods, so an application model's SoftDeletes methods are matched by their trait. - // The Redis classes' own trait methods, such as RedisProxy's pipeline(), are matched by the class. if (! isset(self::OPERATIONS[$declaringClass]) - && ! in_array($declaringClass, self::REDIS_CLASSES, true) // @phpstan-ignore phpstanApi.instanceofAssumption (Only PhpMethodReflection exposes a native method's declaring trait. The SoftDeletes test fails if that changes.) && $method instanceof PhpMethodReflection && $method->getDeclaringTrait() !== null) { diff --git a/src/redis/src/RedisConnection.php b/src/redis/src/RedisConnection.php index 4d730b9ff3..4bf9f7ea30 100644 --- a/src/redis/src/RedisConnection.php +++ b/src/redis/src/RedisConnection.php @@ -1943,10 +1943,8 @@ public function pack(array $values): array /** * Get the underlying Redis client instance. - * - * @return Redis|RedisCluster */ - public function client(): mixed + public function client(): Redis|RedisCluster|null { return $this->connection; } diff --git a/src/redis/src/RedisProxy.php b/src/redis/src/RedisProxy.php index 7e6d49b503..c71ff7939e 100644 --- a/src/redis/src/RedisProxy.php +++ b/src/redis/src/RedisProxy.php @@ -18,11 +18,11 @@ use Hypervel\Redis\Limiters\DurationLimiterBuilder; use Hypervel\Redis\Pool\PoolManager; use Hypervel\Redis\Subscriber\Subscriber; -use Hypervel\Redis\Traits\MultiExec; use Hypervel\Support\Arr; use Hypervel\Support\Attributes\BootOnly; use Hypervel\Support\Attributes\BootOrTestsOnly; use Redis; +use RedisCluster; use RedisException; use Swoole\Coroutine\CanceledException; use Throwable; @@ -40,8 +40,6 @@ */ class RedisProxy implements ConnectionContract { - use MultiExec; - /** * Methods that must be called while explicitly holding a pool connection. * @@ -186,6 +184,80 @@ public function sScan(mixed $key, mixed $cursor, mixed ...$arguments): mixed return $this->__call('sScan', [$key, $cursor, ...$arguments]); } + /** + * Execute commands in a pipeline. + * + * @return ($callback is null ? Redis : array|false) + */ + public function pipeline(?callable $callback = null): Redis|array|bool + { + return $this->executeMultiExec('pipeline', $callback); + } + + /** + * Execute commands in a transaction. + * + * @return ($callback is null ? Redis|RedisCluster : array|false) + */ + public function transaction(?callable $callback = null): Redis|RedisCluster|array|bool + { + return $this->executeMultiExec('multi', $callback); + } + + /** + * Execute multi-exec commands with optional callback. + * + * @return ($callback is null + * ? ($command is 'pipeline' ? Redis : Redis|RedisCluster) + * : array|false) + */ + private function executeMultiExec(string $command, ?callable $callback = null): Redis|RedisCluster|array|bool + { + if (is_null($callback)) { + return $this->__call($command, []); + } + + $hasExistingConnection = CoroutineContext::has($this->getContextKey()); + $instance = $this->__call($command, []); + $result = null; + $operationFailure = null; + $cleanupFailure = null; + + try { + $result = tap($instance, $callback)->exec(); + + if ($command === 'multi' && $hasExistingConnection) { + $connection = CoroutineContext::get($this->getContextKey()); + + if ($connection instanceof RedisConnection) { + $connection->clearWatchState(); + } + } + } catch (Throwable $exception) { + $operationFailure = RedisCancellation::cancellationFrom( + $exception, + 'Executing the Redis transaction was canceled.', + ) ?? $exception; + $connection = CoroutineContext::get($this->getContextKey()); + + if ($connection instanceof RedisConnection) { + $connection->invalidate(); + } + } + + if (! $hasExistingConnection) { + try { + $this->releaseContextConnection(); + } catch (Throwable $exception) { + $cleanupFailure = $exception; + } + } + + RedisCancellation::throwOperationOrCleanupFailure($operationFailure, $cleanupFailure); + + return $result; + } + /** * Pass dynamic method calls to a pooled Redis connection. */ diff --git a/src/redis/src/Traits/MultiExec.php b/src/redis/src/Traits/MultiExec.php deleted file mode 100644 index c72ee246c0..0000000000 --- a/src/redis/src/Traits/MultiExec.php +++ /dev/null @@ -1,92 +0,0 @@ -|false) - */ - public function pipeline(?callable $callback = null) - { - return $this->executeMultiExec('pipeline', $callback); - } - - /** - * Execute commands in a transaction. - * - * @return ($callback is null ? Redis|RedisCluster : array|false) - */ - public function transaction(?callable $callback = null) - { - return $this->executeMultiExec('multi', $callback); - } - - /** - * Execute multi-exec commands with optional callback. - * - * @return ($callback is null - * ? ($command is 'pipeline' ? Redis : Redis|RedisCluster) - * : array|false) - */ - private function executeMultiExec(string $command, ?callable $callback = null) - { - if (is_null($callback)) { - return $this->__call($command, []); - } - - $hasExistingConnection = CoroutineContext::has($this->getContextKey()); - $instance = $this->__call($command, []); - $result = null; - $operationFailure = null; - $cleanupFailure = null; - - try { - $result = tap($instance, $callback)->exec(); - - if ($command === 'multi' && $hasExistingConnection) { - $connection = CoroutineContext::get($this->getContextKey()); - - if ($connection instanceof RedisConnection) { - $connection->clearWatchState(); - } - } - } catch (Throwable $exception) { - $operationFailure = RedisCancellation::cancellationFrom( - $exception, - 'Executing the Redis transaction was canceled.', - ) ?? $exception; - $connection = CoroutineContext::get($this->getContextKey()); - - if ($connection instanceof RedisConnection) { - $connection->invalidate(); - } - } - - if (! $hasExistingConnection) { - try { - $this->releaseContextConnection(); - } catch (Throwable $exception) { - $cleanupFailure = $exception; - } - } - - RedisCancellation::throwOperationOrCleanupFailure($operationFailure, $cleanupFailure); - - return $result; - } -} diff --git a/src/support/src/Facades/Cache.php b/src/support/src/Facades/Cache.php index d292cd3fc2..83cb4dbabf 100644 --- a/src/support/src/Facades/Cache.php +++ b/src/support/src/Facades/Cache.php @@ -34,6 +34,7 @@ * @method static mixed flexible(\UnitEnum|string $key, array $ttl, callable $callback, null|array $lock = null, bool $alwaysDefer = false) * @method static mixed flexibleNullable(\UnitEnum|string $key, array $ttl, callable $callback, null|array $lock = null, bool $alwaysDefer = false) * @method static float float(\UnitEnum|string $key, null|\Closure|float $default = null) + * @method static bool flush() * @method static bool flushLocks() * @method static void flushMacros() * @method static void flushState() @@ -76,7 +77,6 @@ * @method static \Hypervel\Cache\TaggedCache tags(mixed $names) * @method static bool touch(\UnitEnum|string $key, \DateInterval|\DateTimeInterface|int $ttl) * @method static mixed withoutOverlapping(\UnitEnum|string $key, callable $callback, int $lockFor = 0, int $waitFor = 10, string|null $owner = null) - * @method static bool flush() * @method static string getPrefix() * @method static \Hypervel\Contracts\Cache\Lock lock(string $name, int $seconds = 0, string|null $owner = null) * @method static \Hypervel\Contracts\Cache\Lock restoreLock(string $name, string $owner) diff --git a/src/validation/src/Rules/Can.php b/src/validation/src/Rules/Can.php index 193472b2b0..0bffc63862 100644 --- a/src/validation/src/Rules/Can.php +++ b/src/validation/src/Rules/Can.php @@ -32,11 +32,8 @@ public function __construct( */ public function passes(string $attribute, mixed $value): bool { - $arguments = $this->arguments; - - $model = array_shift($arguments); - - return Gate::allows($this->ability, array_filter([$model, ...$arguments, $value])); + // Keep falsey authorization data, and drop argument names so Gate receives positional values. + return Gate::allows($this->ability, [...array_values($this->arguments), $value]); } /** diff --git a/tests/Auth/AuthAccessGateTest.php b/tests/Auth/AuthAccessGateTest.php index 63e0563755..e62a4e7dc3 100644 --- a/tests/Auth/AuthAccessGateTest.php +++ b/tests/Auth/AuthAccessGateTest.php @@ -25,6 +25,7 @@ use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestWith; use stdClass; class AuthAccessGateTest extends TestCase @@ -494,6 +495,21 @@ public function testASingleArgumentCanBePassedWhenCheckingAbilities(): void $this->assertTrue($gate->check('foo', $dummy)); } + #[TestWith([0])] + #[TestWith([false])] + #[TestWith([['tenant' => 7]])] + public function testGateCallbacksAcceptNonModelArguments(mixed $value): void + { + $gate = $this->getBasicGate(); + $gate->define('check-data', function ($user, mixed $argument) use ($value): bool { + $this->assertSame($value, $argument); + + return true; + }); + + $this->assertTrue($gate->allows('check-data', [$value])); + } + public function testMultipleArgumentsCanBePassedWhenCheckingAbilities(): void { $gate = $this->getBasicGate(); @@ -673,17 +689,16 @@ public function testForUserMethodAttachesANewUserToANewGateInstanceWithGuessCall ++$counter; }; $gate->guessPolicyNamesUsing($guesserCallback); - $gate->getPolicyFor('fooClassA'); + $gate->getPolicyFor('fooClass'); $this->assertSame(1, $counter); - // The guesser callback should be present on the new gate as well. - // Each call uses a unique class name to avoid the static policy cache. + // now the guesser callback should be present on the new gate as well $newGate = $gate->forUser((object) ['id' => 1]); - $newGate->getPolicyFor('fooClassB'); + $newGate->getPolicyFor('fooClass'); $this->assertSame(2, $counter); - $newGate->getPolicyFor('fooClassC'); + $newGate->getPolicyFor('fooClass'); $this->assertSame(3, $counter); } @@ -1651,14 +1666,14 @@ public function testPolicyCacheIsClearedWhenGuessCallbackChanges(): void }; $gate->guessPolicyNamesUsing($guesser); - $gate->getPolicyFor('SomeClassA'); - $gate->getPolicyFor('SomeClassA'); + $gate->getPolicyFor(AccessGateTestDummy::class); + $gate->getPolicyFor(AccessGateTestDummy::class); $this->assertSame(1, $counter); // After the guesser changes, the same class should be guessed again $gate->guessPolicyNamesUsing($guesser); - $gate->getPolicyFor('SomeClassA'); + $gate->getPolicyFor(AccessGateTestDummy::class); $this->assertSame(2, $counter); } @@ -1687,7 +1702,9 @@ public function testPolicyCacheIsNotSharedBetweenGatesWithDifferentPolicies(): v $this->assertInstanceOf(DummyWithUsePolicyPolicy::class, $unregistered->getPolicyFor(ChildOfDummyWithUsePolicy::class)); } - public function testPolicyCacheStoresNullForClassWithNoPolicy(): void + #[TestWith([AccessGateTestDummy::class])] + #[TestWith([GateTestUnitEnum::class])] + public function testPolicyCacheStoresNullForClassWithNoPolicy(string $class): void { $gate = $this->getBasicGate(); @@ -1698,11 +1715,11 @@ public function testPolicyCacheStoresNullForClassWithNoPolicy(): void }); // First call — resolves and caches "no policy" - $this->assertNull($gate->getPolicyFor('NonExistentModel')); + $this->assertNull($gate->getPolicyFor($class)); $this->assertSame(1, $counter); // Second call — returns cached "no policy" without calling guesser - $this->assertNull($gate->getPolicyFor('NonExistentModel')); + $this->assertNull($gate->getPolicyFor($class)); $this->assertSame(1, $counter); } diff --git a/tests/Auth/GatePolicyResolutionTest.php b/tests/Auth/GatePolicyResolutionTest.php index 4c64e53a49..6b01e38cc0 100644 --- a/tests/Auth/GatePolicyResolutionTest.php +++ b/tests/Auth/GatePolicyResolutionTest.php @@ -46,6 +46,55 @@ public function testPolicyCanBeGuessedUsingClassConventions(): void ); } + public function testGuessedPoliciesReuseTheDeclaredClassBinding(): void + { + $policy = new AuthTestUserPolicy; + $this->app->instance(AuthTestUserPolicy::class, $policy); + + foreach ([ + ModelAuthTestUser::class, + strtolower(ModelAuthTestUser::class), + '\\' . ModelAuthTestUser::class, + str_replace('Models\AuthTestUser', 'Unmapped\aUtHtEsTuSeR', ModelAuthTestUser::class), + ] as $class) { + $this->assertSame($policy, Gate::getPolicyFor($class)); + } + } + + public function testGuessedPolicyAliasesHonorContainerExtenders(): void + { + $alias = __NAMESPACE__ . '\ConfiguredPolicyAlias'; + + if (! class_exists($alias, false)) { + class_alias(AuthTestUserPolicy::class, $alias); + } + + $policy = new AuthTestUserPolicy; + $this->app->extend($alias, fn (): AuthTestUserPolicy => $policy); + Gate::guessPolicyNamesUsing(fn (): string => $alias); + + $this->assertSame($policy, Gate::getPolicyFor(ModelAuthTestUser::class)); + } + + public function testPolicyCacheDoesNotRetainAlternativeClassSpellings(): void + { + $received = []; + Gate::guessPolicyNamesUsing(function (string $class) use (&$received): string { + $received[] = $class; + + return $class === ModelAuthTestUser::class ? PostPolicy::class : AudioPostPolicy::class; + }); + + $variant = strtolower(ModelAuthTestUser::class); + + for ($attempt = 0; $attempt < 2; ++$attempt) { + $this->assertInstanceOf(PostPolicy::class, Gate::getPolicyFor(ModelAuthTestUser::class)); + $this->assertInstanceOf(AudioPostPolicy::class, Gate::getPolicyFor($variant)); + } + + $this->assertSame([ModelAuthTestUser::class, $variant, $variant], $received); + } + public function testPolicyCanBeGuessedForParallelClassHierarchies(): void { $this->assertInstanceOf( diff --git a/tests/Benchmarks/PooledConnections/benchmark.php b/tests/Benchmarks/PooledConnections/benchmark.php index a0f21a451a..775137f2c0 100644 --- a/tests/Benchmarks/PooledConnections/benchmark.php +++ b/tests/Benchmarks/PooledConnections/benchmark.php @@ -3,6 +3,8 @@ declare(strict_types=1); use Ably\AblyRest; +use Ably\Channel; +use Ably\Channels; use Algolia\AlgoliaSearch\Algolia; use Algolia\AlgoliaSearch\Http\GuzzleHttpClient; use Aws\S3\S3Client; @@ -68,15 +70,15 @@ use Hypervel\Tests\Saloon\Fixtures\Requests\UserRequest; use Hypervel\Tests\Saloon\RateLimit\Fixtures\Connectors\TestConnector as RateLimitedConnector; use Hypervel\Tests\Socialite\Fixtures\GenericTestProviderStub; +use JMac\Testing\Double; use League\Flysystem\Filesystem; use League\Flysystem\Local\LocalFilesystemAdapter; use Meilisearch\Client as MeilisearchClient; -use Mockery as m; use Psr\Http\Message\ResponseInterface; use Pusher\Pusher; use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\HttpClient\Response\MockResponse; -use Symfony\Component\Mercure\Jwt\TokenProviderInterface; +use Symfony\Component\Mercure\Jwt\StaticTokenProvider; use Symfony\Component\Mercure\Update; use Symfony\Component\Process\InputStream; use Typesense\Client as TypesenseClient; @@ -318,8 +320,8 @@ function createOperation(string $case, ApplicationContract $app, array $settings case 'pusher-release': // Controlled waits isolate the release boundary, not provider throughput. - $client = m::mock(Pusher::class); - $client->shouldReceive('trigger')->andReturnUsing(static function () use (&$deliveries): object { + $client = Double::for(Pusher::class)->strict(); + $client->allows('trigger')->resolves(static function () use (&$deliveries): object { usleep(20_000); ++$deliveries; return (object) []; @@ -331,16 +333,16 @@ function createOperation(string $case, ApplicationContract $app, array $settings }, null]; case 'ably-release': - $client = m::mock(AblyRest::class); - $channel = m::mock(); - $channel->shouldReceive('publish')->andReturnUsing(static function () use (&$deliveries): void { + $client = new AblyRest('abcd:efg'); + $channel = Double::for(Channel::class)->strict(); + $channel->allows('publish')->resolves(static function () use (&$deliveries): void { usleep(20_000); ++$deliveries; }); - $channel->shouldReceive('getCipherParams')->andReturnNull(); - $client->channels = m::mock(); - $client->channels->shouldReceive('get')->andReturn($channel); - $client->channels->shouldReceive('release'); + $channel->allows('getCipherParams')->returns(null); + $client->channels = Double::for(Channels::class)->strict(); + $client->channels->allows('get')->returns($channel); + $client->channels->allows('release'); $broadcaster = new AblyBroadcaster($app, $client); return [static function () use ($broadcaster): void { @@ -348,8 +350,7 @@ function createOperation(string $case, ApplicationContract $app, array $settings }, null]; case 'mercure-release': - $token = m::mock(TokenProviderInterface::class); - $token->shouldReceive('getJwt')->andReturn('test.token.signature'); + $token = new StaticTokenProvider('test.token.signature'); $hub = new Hub( new PoolDefinition('benchmark:mercure', 'mercure', 'test', PoolOptions::fromArray(['max_objects' => $settings['concurrency']])), static fn (): MockHttpClient => new MockHttpClient(static function (): MockResponse { @@ -778,7 +779,6 @@ function waitForRelease(Closure $wait, Closure $release): void ], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR), "\n"; } finally { $objects?->purgeAll(); - m::close(); $app?->terminate(); unlink($path); } diff --git a/tests/Broadcasting/Fixtures/RedisBroadcasterConnection.php b/tests/Broadcasting/Fixtures/RedisBroadcasterConnection.php new file mode 100644 index 0000000000..d9be251505 --- /dev/null +++ b/tests/Broadcasting/Fixtures/RedisBroadcasterConnection.php @@ -0,0 +1,21 @@ +expects('isCluster')->returns(true); $connection->expects('publish')->with('test-channel-1', Argument::type('string')); $connection->expects('publish')->with('test-channel-2', Argument::type('string')); @@ -269,7 +269,7 @@ public function testBroadcastUsesPublishPerChannelOnCluster(): void public function testClusterBroadcastWrapsRedisClusterException(): void { - $connection = Double::for(RedisBroadcasterTestConnection::class); + $connection = Double::for(RedisBroadcasterConnection::class); $connection->expects('isCluster')->returns(true); $connection->expects('publish') ->with('test-channel', Argument::type('string')) @@ -286,7 +286,7 @@ public function testClusterBroadcastWrapsRedisClusterException(): void public function testBroadcastUsesEvalOnNonCluster(): void { - $connection = Double::for(RedisBroadcasterTestConnection::class); + $connection = Double::for(RedisBroadcasterConnection::class); $connection->expects('isCluster')->returns(false); $connection->expects('eval'); $connection->expects('publish')->never(); @@ -306,7 +306,7 @@ public function testClusterBroadcastLeavesRedisPrefixToNativePublishAfterFormatt ), ); - $connection = Double::for(RedisBroadcasterTestConnection::class); + $connection = Double::for(RedisBroadcasterConnection::class); $connection->expects('isCluster')->returns(true); $connection->expects('publish') ->with('application.orders', Argument::type('string')); @@ -329,7 +329,7 @@ public function testLuaBroadcastAddsRedisPrefixAfterFormattingChannels(): void ), ); - $connection = Double::for(RedisBroadcasterTestConnection::class); + $connection = Double::for(RedisBroadcasterConnection::class); $connection->expects('isCluster')->returns(false); $connection->expects('eval') ->with( @@ -353,7 +353,7 @@ public function testBroadcastThrowsWhenPayloadCannotBeEncoded(): void $this->expectException(JsonException::class); $this->redis->expects('connection')->returns( - Double::for(RedisBroadcasterTestConnection::class) + Double::for(RedisBroadcasterConnection::class) ); $this->broadcaster->broadcast( @@ -365,7 +365,7 @@ public function testBroadcastThrowsWhenPayloadCannotBeEncoded(): void public function testBroadcastPayloadDoesNotDuplicateSocketInData(): void { - $connection = Double::for(RedisBroadcasterTestConnection::class); + $connection = Double::for(RedisBroadcasterConnection::class); $connection->allows('isCluster')->returns(false); $connection->expects('eval')->with(Argument::all(function (string $script, int $numberOfKeys, string $payload): bool { $decoded = json_decode($payload, true); @@ -419,17 +419,3 @@ protected function getMockRequestWithoutUserForChannel(string $channel): Request return Request::create('/', 'POST', ['channel_name' => $channel]); } } - -// Declare the proxy's dynamic commands so Double can reflect their signatures. -abstract class RedisBroadcasterTestConnection extends RedisProxy -{ - /** - * Publish a message to a channel. - */ - abstract public function publish(string $channel, string $message): int|false; - - /** - * Evaluate a Lua script. - */ - abstract public function eval(string $script, int $numberOfKeys, mixed ...$arguments): mixed; -} diff --git a/tests/Cache/CacheEventsTest.php b/tests/Cache/CacheEventsTest.php index 0e2bf47c3f..dc4fb598a5 100644 --- a/tests/Cache/CacheEventsTest.php +++ b/tests/Cache/CacheEventsTest.php @@ -36,6 +36,7 @@ use JMac\Testing\Double; use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; use Throwable; @@ -419,6 +420,7 @@ public static function repositoryCancellationOperations(): iterable 'forever' => ['forever', ['foo', 'bar'], 'forever', ['foo', 'bar'], WritingKey::class], 'forget' => ['forget', ['foo'], 'forget', ['foo'], ForgettingKey::class], 'clear' => ['flush', [], 'clear', [], CacheFlushing::class], + 'flush' => ['flush', [], 'flush', [], CacheFlushing::class], 'flush locks' => ['flushLocks', [], 'flushLocks', [], CacheLocksFlushing::class], ]; @@ -592,12 +594,14 @@ public function testForgetDoesTriggerFailedEventOnFailure(): void $this->assertSame([], $this->dispatchedEvents); } - public function testFlushTriggersEvents(): void + #[TestWith(['clear'])] + #[TestWith(['flush'])] + public function testFlushTriggersEvents(string $method): void { $dispatcher = $this->getDispatcher(); $repository = $this->getRepository($dispatcher); - $this->assertTrue($repository->clear()); + $this->assertTrue($repository->{$method}()); $this->assertEventDispatched(CacheFlushing::class, ['storeName' => 'array']); $this->assertEventDispatched(CacheFlushed::class, ['storeName' => 'array']); @@ -620,7 +624,9 @@ public function testEmptyTaggedFlushIsIdempotentAndDispatchesSuccessEvents(): vo ], array_map(get_class(...), $events)); } - public function testFlushDispatchesFailureEventWithExactException(): void + #[TestWith(['clear'])] + #[TestWith(['flush'])] + public function testFlushDispatchesFailureEventWithExactException(string $method): void { $exception = new RuntimeException('The cache flush failed.'); $store = Double::for(Store::class); @@ -630,7 +636,7 @@ public function testFlushDispatchesFailureEventWithExactException(): void $repository->setEventDispatcher($this->getCapturingDispatcher($events)); try { - $repository->clear(); + $repository->{$method}(); $this->fail('Expected the cache flush exception to be rethrown.'); } catch (RuntimeException $caught) { $this->assertSame($exception, $caught); @@ -676,7 +682,9 @@ public function testFlushLocksDispatchesFailureEventWithExactException(): void $this->assertSame($exception, $events[1]->exception); } - public function testFlushFailureDoesDispatchEvent(): void + #[TestWith(['clear'])] + #[TestWith(['flush'])] + public function testFlushFailureDoesDispatchEvent(string $method): void { $dispatcher = $this->getDispatcher(); @@ -687,7 +695,7 @@ public function testFlushFailureDoesDispatchEvent(): void $repository = new Repository($failingStore, ['store' => 'array']); $repository->setEventDispatcher($dispatcher); - $this->assertFalse($repository->clear()); + $this->assertFalse($repository->{$method}()); $this->assertEventDispatched(CacheFlushing::class, ['storeName' => 'array']); $this->assertEventDispatched(CacheFlushFailed::class, ['storeName' => 'array', 'exception' => null]); diff --git a/tests/Composer/PackageManifestConsistencyTest.php b/tests/Composer/PackageManifestConsistencyTest.php index c4d8319759..18104dda44 100644 --- a/tests/Composer/PackageManifestConsistencyTest.php +++ b/tests/Composer/PackageManifestConsistencyTest.php @@ -4,6 +4,8 @@ namespace Hypervel\Tests\Composer; +use Composer\Semver\Intervals; +use Composer\Semver\VersionParser; use Hypervel\Support\DefaultProviders; use Hypervel\Tests\TestCase; use JsonException; @@ -22,6 +24,7 @@ public function testSplitPackageRequirementsAreDeclaredConsistentlyInRootManifes { $rootComposer = $this->decodeManifest(__DIR__ . '/../../composer.json'); $splitPackages = array_column(array_map($this->decodeManifest(...), $this->splitManifests()), null, 'name'); + $versionParser = new VersionParser; foreach ($splitPackages as $package => $composer) { foreach (['require', 'require-dev'] as $section) { @@ -44,6 +47,21 @@ public function testSplitPackageRequirementsAreDeclaredConsistentlyInRootManifes ?? null; $this->assertNotNull($rootConstraint, "{$message}, but it is absent from the root manifest."); + + if ($dependency === 'ext-redis') { + // Native test doubles require a newer development client than published packages. + // Remove this exception with docs/plans/todo/phpredis-6.3-minimum.md. + $this->assertTrue( + Intervals::isSubsetOf( + $versionParser->parseConstraints($rootConstraint), + $versionParser->parseConstraints($constraint), + ), + "{$message} with a root constraint outside the package range.", + ); + + continue; + } + $this->assertSame($constraint, $rootConstraint, "{$message} with a different root constraint."); } } diff --git a/tests/Console/Fixtures/ComponentsFactory.php b/tests/Console/Fixtures/ComponentsFactory.php index 437e7defca..9bc2e56857 100644 --- a/tests/Console/Fixtures/ComponentsFactory.php +++ b/tests/Console/Fixtures/ComponentsFactory.php @@ -5,6 +5,7 @@ namespace Hypervel\Tests\Console\Fixtures; use Hypervel\Console\View\Components\Factory; +use Stringable; use Symfony\Component\Console\Output\OutputInterface; // Declare the dynamically dispatched component methods so Double can verify their arguments and calls. @@ -39,4 +40,14 @@ abstract public function error(string $string, int $verbosity = OutputInterface: * Prompt for a hidden answer. */ abstract public function secret(string $question, bool $fallback = true): mixed; + + /** + * Render a task and its result. + */ + abstract public function task(string $description, ?callable $task = null, int $verbosity = OutputInterface::VERBOSITY_NORMAL): void; + + /** + * Render two columns of detail. + */ + abstract public function twoColumnDetail(Stringable|string|int|float $first, Stringable|string|int|float|null $second = null, int $verbosity = OutputInterface::VERBOSITY_NORMAL): void; } diff --git a/tests/Doctor/Feature/Diagnostics/ComposerAutoloadIsAuthoritativeTest.php b/tests/Doctor/Feature/Diagnostics/ComposerAutoloadIsAuthoritativeTest.php new file mode 100644 index 0000000000..c7fbfab849 --- /dev/null +++ b/tests/Doctor/Feature/Diagnostics/ComposerAutoloadIsAuthoritativeTest.php @@ -0,0 +1,45 @@ +app->detectEnvironment(fn (): string => $environment); + $loader = new ClassLoader; + $loader->setClassMapAuthoritative($authoritative); + Composer::setLoader($loader); + + $output = new BufferedOutput; + $actualExitCode = $this->app->make(Kernel::class)->call('doctor', [ + '--only' => 'ComposerAutoloadIsAuthoritative', + '--format' => 'json', + ], $output); + $report = json_decode($output->fetch(), true, flags: JSON_THROW_ON_ERROR); + + $this->assertSame($exitCode, $actualExitCode); + $this->assertCount(1, $report['diagnostics']); + $this->assertSame($status, $report['diagnostics'][0]['status']); + + if ($status === 'fail') { + $this->assertStringContainsString('composer install --no-dev --classmap-authoritative', $report['diagnostics'][0]['remediation']); + } + } +} diff --git a/tests/Doctor/Feature/Diagnostics/ComposerAutoloadIsValidTest.php b/tests/Doctor/Feature/Diagnostics/ComposerAutoloadIsValidTest.php index 3d1767e884..980758870e 100644 --- a/tests/Doctor/Feature/Diagnostics/ComposerAutoloadIsValidTest.php +++ b/tests/Doctor/Feature/Diagnostics/ComposerAutoloadIsValidTest.php @@ -4,15 +4,18 @@ namespace Hypervel\Tests\Doctor\Feature\Diagnostics; +use Composer\Autoload\ClassLoader; use Hypervel\Doctor\Diagnostics\ComposerAutoloadIsValid; use Hypervel\Doctor\Results\DiagnosticResult; use Hypervel\Foundation\PackageManifest; use Hypervel\Process\PendingProcess; +use Hypervel\Support\Composer; use Hypervel\Support\Facades\File; use Hypervel\Support\Facades\Process; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Doctor\TestCase; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestWith; class ComposerAutoloadIsValidTest extends TestCase { @@ -43,8 +46,11 @@ protected function tearDown(): void } #[DataProvider('vendorDirectories')] - public function testChecksComposerAutoloadValidityWithAStrictDryRun(string $directory): void + public function testChecksComposerAutoloadValidityWithAStrictDryRun(string $directory, bool $authoritative, string $option): void { + $loader = new ClassLoader; + $loader->setClassMapAuthoritative($authoritative); + Composer::setLoader($loader); $basePath = $this->basePath; mkdir($basePath . '/' . $directory); file_put_contents($basePath . '/composer.json', '{}'); @@ -74,20 +80,29 @@ public function testChecksComposerAutoloadValidityWithAStrictDryRun(string $dire $this->assertSame('fail', $result->status->value); $this->assertStringContainsString('does not comply with psr-4', $result->details); - $this->assertSame('Regenerate Composer autoload files using `composer dump-autoload`?', $result->confirmation); - $this->assertSame('Regenerate Composer autoload files with `composer dump-autoload`.', $result->remediation); + $this->assertSame("Regenerate Composer autoload files using `composer dump-autoload {$option}`?", $result->confirmation); + $this->assertSame("Regenerate Composer autoload files with `composer dump-autoload {$option}`.", $result->remediation); } /** - * Provide conventional and relocated vendor directories. + * Provide vendor directories and current autoloader modes. */ public static function vendorDirectories(): array { - return [['vendor'], ['dependencies']]; + return [ + ['vendor', false, '--optimize'], + ['dependencies', false, '--optimize'], + ['vendor', true, '--classmap-authoritative'], + ]; } - public function testRegeneratesComposerAutoloadFilesWhenFixed(): void + #[TestWith([false, '--optimize'])] + #[TestWith([true, '--classmap-authoritative'])] + public function testRegeneratesComposerAutoloadFilesWhenFixed(bool $authoritative, string $option): void { + $loader = new ClassLoader; + $loader->setClassMapAuthoritative($authoritative); + Composer::setLoader($loader); $basePath = $this->basePath; file_put_contents($basePath . '/composer.json', '{}'); @@ -100,7 +115,7 @@ public function testRegeneratesComposerAutoloadFilesWhenFixed(): void Process::assertRan(fn (PendingProcess $process): bool => $process->command === [ 'composer', 'dump-autoload', - '--optimize', + $option, '--strict-psr', '--strict-ambiguous', '--no-interaction', diff --git a/tests/Doctor/Feature/DoctorServiceProviderTest.php b/tests/Doctor/Feature/DoctorServiceProviderTest.php index 078289bcee..8efc8f8f65 100644 --- a/tests/Doctor/Feature/DoctorServiceProviderTest.php +++ b/tests/Doctor/Feature/DoctorServiceProviderTest.php @@ -12,6 +12,7 @@ use Hypervel\Doctor\Diagnostics\BootstrapCacheMatchesEnvironment; use Hypervel\Doctor\Diagnostics\CacheStoreIsReachable; use Hypervel\Doctor\Diagnostics\ComposerAuditPasses; +use Hypervel\Doctor\Diagnostics\ComposerAutoloadIsAuthoritative; use Hypervel\Doctor\Diagnostics\ComposerAutoloadIsValid; use Hypervel\Doctor\Diagnostics\ComposerLockIsFresh; use Hypervel\Doctor\Diagnostics\ConfigurationCanBeCached; @@ -1108,6 +1109,7 @@ public function testBindsTheDoctorServiceAndFacade(): void RequiredPhpExtensionsAreLoaded::class, RecommendedPhpExtensionsAreLoaded::class, ComposerAutoloadIsValid::class, + ComposerAutoloadIsAuthoritative::class, ComposerLockIsFresh::class, ConfigurationFilesCanBeLoaded::class, ConfigurationCanBeCached::class, @@ -1142,6 +1144,7 @@ public function testRegistersTheDefaultDiagnostics(): void RequiredPhpExtensionsAreLoaded::class, RecommendedPhpExtensionsAreLoaded::class, ComposerAutoloadIsValid::class, + ComposerAutoloadIsAuthoritative::class, ComposerLockIsFresh::class, ConfigurationFilesCanBeLoaded::class, ConfigurationCanBeCached::class, diff --git a/tests/Grpc/BaseClientTest.php b/tests/Grpc/BaseClientTest.php index 3f09288fe6..ae0f38709a 100644 --- a/tests/Grpc/BaseClientTest.php +++ b/tests/Grpc/BaseClientTest.php @@ -36,8 +36,9 @@ use Hypervel\Tests\Grpc\Fixtures\ClientCallClientFactory; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use ReflectionClass; @@ -50,6 +51,8 @@ class BaseClientTest extends TestCase { + use VerifiesDoubles; + /** @var list */ private array $clients = []; @@ -321,8 +324,8 @@ static function ( $client = $this->newClient(); $cancellation = new CanceledException; $failure = $cleanupThrows ? new RuntimeException('Release cleanup failed.', previous: $cancellation) : $cancellation; - $lease = m::mock(ConnectionLease::class); - $lease->shouldReceive('releaseIfIdle')->once()->andThrow($failure); + $lease = Double::for(ConnectionLease::class)->strict(); + $lease->expects('releaseIfIdle')->throws($failure); CoroutineContext::set('__grpc.test.connection_lease', $lease); try { diff --git a/tests/Grpc/ConnectionTest.php b/tests/Grpc/ConnectionTest.php index 5b62fc2461..4261a25bcf 100644 --- a/tests/Grpc/ConnectionTest.php +++ b/tests/Grpc/ConnectionTest.php @@ -29,8 +29,9 @@ use Hypervel\Grpc\Protocol\Timeout; use Hypervel\Grpc\StatusCode; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; use ReflectionProperty; use RuntimeException; @@ -41,6 +42,8 @@ class ConnectionTest extends TestCase { + use VerifiesDoubles; + /** @var list */ private array $connections = []; @@ -1173,12 +1176,12 @@ private function connection( */ private function expectReported(?Throwable $failure): void { - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); if ($failure === null) { - $handler->shouldNotReceive('report'); + $handler->expects('report')->never(); } else { - $handler->shouldReceive('report')->once()->with($failure); + $handler->expects('report')->with($failure); } $container = new Container; diff --git a/tests/Grpc/ExceptionMapperTest.php b/tests/Grpc/ExceptionMapperTest.php index 4fc8cf70a9..c3f670f58a 100644 --- a/tests/Grpc/ExceptionMapperTest.php +++ b/tests/Grpc/ExceptionMapperTest.php @@ -12,16 +12,19 @@ use Hypervel\Grpc\StatusCode; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Swoole\Coroutine\CanceledException; class ExceptionMapperTest extends TestCase { + use VerifiesDoubles; + public function testPreservesExpectedRpcFailuresWithoutReportingThem(): void { - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); $mapper = new ExceptionMapper($handler); $failure = (new RpcException(StatusCode::NotFound, 'missing')) ->withTrailingMetadata(['x-reason' => 'absent']); @@ -31,8 +34,8 @@ public function testPreservesExpectedRpcFailuresWithoutReportingThem(): void public function testMapsProtocolFailuresToInternalWithoutReportingThem(): void { - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); $failure = new ProtocolException('The request contains a malformed gRPC frame.'); $mapped = (new ExceptionMapper($handler))->map($failure); @@ -43,9 +46,9 @@ public function testMapsProtocolFailuresToInternalWithoutReportingThem(): void public function testReportsUnexpectedFailuresAndDoesNotExposeTheirMessage(): void { - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $failure = new RuntimeException('database credentials leaked'); - $handler->shouldReceive('report')->once()->with($failure); + $handler->expects('report')->with($failure); $mapped = (new ExceptionMapper($handler))->map($failure); @@ -56,9 +59,9 @@ public function testReportsUnexpectedFailuresAndDoesNotExposeTheirMessage(): voi public function testReportsInvalidServiceResponsesAsInternal(): void { - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $failure = new RuntimeException('The stream yielded a string.'); - $handler->shouldReceive('report')->once()->with($failure); + $handler->expects('report')->with($failure); $mapped = (new ExceptionMapper($handler))->invalidResponse($failure); @@ -68,8 +71,8 @@ public function testReportsInvalidServiceResponsesAsInternal(): void public function testPreservesCancellationPassedAsAnInvalidResponse(): void { - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); $cancellation = new CanceledException; $this->expectExceptionObject($cancellation); @@ -81,8 +84,8 @@ public function testPreservesCancellationRaisedByTheReporter(): void { $failure = new RuntimeException('service failed'); $cancellation = new CanceledException; - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($failure)->andThrow($cancellation); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($failure)->throws($cancellation); $this->expectExceptionObject($cancellation); @@ -98,12 +101,11 @@ public function testReporterFailureFallsBackWithoutChangingTheMappedStatus(): vo $previousErrorLog = ini_set('error_log', $errorLog); try { - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $failure = new RuntimeException('The original service failure.'); - $handler->shouldReceive('report') - ->once() + $handler->expects('report') ->with($failure) - ->andThrow(new RuntimeException('The exception reporter failed.')); + ->throws(new RuntimeException('The exception reporter failed.')); $mapped = (new ExceptionMapper($handler))->map($failure); $contents = file_get_contents($errorLog); @@ -123,8 +125,8 @@ public function testReporterFailureFallsBackWithoutChangingTheMappedStatus(): vo public function testPreservesCoroutineCancellationForTheOwningCallLifecycle(): void { - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); $failure = new CanceledException; $this->expectExceptionObject($failure); diff --git a/tests/Grpc/GrpcOperationRunnerTest.php b/tests/Grpc/GrpcOperationRunnerTest.php index 5b4953d3da..d8aec38b70 100644 --- a/tests/Grpc/GrpcOperationRunnerTest.php +++ b/tests/Grpc/GrpcOperationRunnerTest.php @@ -18,8 +18,9 @@ use Hypervel\Grpc\Status; use Hypervel\Grpc\StatusCode; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -27,6 +28,8 @@ class GrpcOperationRunnerTest extends TestCase { + use VerifiesDoubles; + public function testClientObserversReplaceMetadataInRegistrationOrder(): void { $runner = new GrpcOperationRunner; @@ -121,7 +124,7 @@ function () use ($startingFailure): never { throw $startingFailure; }, )); - $this->bindReportingHandler()->shouldReceive('report')->once()->with($completionFailure); + $this->bindReportingHandler()->expects('report')->with($completionFailure); try { $runner->start($this->clientOperation()); @@ -160,7 +163,7 @@ function () use (&$finished, $secondFailure): never { )); $handle = $runner->start($this->clientOperation()); $result = new GrpcOperationResult(new Status(StatusCode::Ok), null, 2); - $this->bindReportingHandler()->shouldReceive('report')->once()->with($secondFailure); + $this->bindReportingHandler()->expects('report')->with($secondFailure); try { $handle->finish($result); @@ -193,7 +196,7 @@ function () use (&$finished, $observerFailure): never { throw $observerFailure; }, )); - $this->bindReportingHandler()->shouldReceive('report')->once()->with($observerFailure); + $this->bindReportingHandler()->expects('report')->with($observerFailure); $runner->start($this->clientOperation())->finish($result); @@ -212,7 +215,7 @@ function (GrpcOperation $operation, mixed $token, GrpcOperationResult $result): }, )); $reported = []; - $this->bindReportingHandler()->shouldReceive('report')->andReturnUsing(function (Throwable $throwable) use (&$reported): void { + $this->bindReportingHandler()->allows('report')->resolves(function (Throwable $throwable) use (&$reported): void { $reported[] = $throwable; }); @@ -301,7 +304,7 @@ function () use ($observerFailure): never { throw $observerFailure; }, )); - $this->bindReportingHandler()->shouldReceive('report')->once()->with($observerFailure); + $this->bindReportingHandler()->expects('report')->with($observerFailure); $handle = $runner->start($this->clientOperation()); $handle->finish(new GrpcOperationResult(null, new CanceledException, 1)); @@ -330,11 +333,11 @@ private function observer(Closure $starting, ?Closure $finished = null): GrpcOpe /** * Bind a mocked exception handler for displaced failure reports. */ - private function bindReportingHandler(): MockInterface + private function bindReportingHandler(): ExceptionHandler&DoubleInterface { $container = new Container; Container::setInstance($container); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $container->instance(ExceptionHandler::class, $handler); return $handler; diff --git a/tests/Grpc/GrpcRouterTest.php b/tests/Grpc/GrpcRouterTest.php index a1bf416f5c..3d079c5ec3 100644 --- a/tests/Grpc/GrpcRouterTest.php +++ b/tests/Grpc/GrpcRouterTest.php @@ -29,13 +29,16 @@ use Hypervel\Tests\Grpc\Fixtures\TestRequest; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\PreserveGlobalState; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use RuntimeException; class GrpcRouterTest extends TestCase { + use VerifiesDoubles; + public function testValidatesEverySupportedActionShapeBeforeCompilation(): void { [$router, $registrar] = $this->router(); @@ -223,10 +226,10 @@ public function testRetainsMandatoryCallHandlingWhenUserMiddlewareIsDisabled(): public function testGrpcPipelineMapsTheClosestFailureOnce(): void { $container = new Container; - $mapper = m::mock(ExceptionMapper::class); + $mapper = Double::for(ExceptionMapper::class)->strict(); $failure = new RuntimeException('service failed'); $mapped = new RpcException(StatusCode::Unknown, 'mapped'); - $mapper->shouldReceive('map')->once()->with($failure)->andReturn($mapped); + $mapper->expects('map')->with($failure)->returns($mapped); $container->instance(ExceptionMapper::class, $mapper); $pipeline = new Pipeline($container); @@ -245,11 +248,11 @@ static function () use ($failure): never { public function testResponsePreparationIsIdempotent(): void { $container = new Container; - $factory = m::mock(ResponseFactory::class); + $factory = Double::for(ResponseFactory::class)->strict(); $request = Request::create('/testing.Service/Call', 'POST'); $expected = new GrpcHttpResponse('', ['grpc-status' => '0'], [], []); $value = new GPBEmpty; - $factory->shouldReceive('make')->once()->with($request, $value)->andReturn($expected); + $factory->expects('make')->with($request, $value)->returns($expected); $container->instance(ResponseFactory::class, $factory); $router = new GrpcRouter(new Dispatcher($container), $container); diff --git a/tests/Grpc/HandleCallTest.php b/tests/Grpc/HandleCallTest.php index 93edf8d496..ac002430b0 100644 --- a/tests/Grpc/HandleCallTest.php +++ b/tests/Grpc/HandleCallTest.php @@ -23,8 +23,11 @@ use Hypervel\Http\Request; use Hypervel\Routing\Route; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -32,7 +35,9 @@ class HandleCallTest extends TestCase { - private ExceptionMapper $exceptions; + use VerifiesDoubles; + + private ExceptionMapper&DoubleInterface $exceptions; /** * Set up the exception mapper. @@ -41,7 +46,7 @@ protected function setUp(): void { parent::setUp(); - $this->exceptions = m::mock(ExceptionMapper::class); + $this->exceptions = Double::for(ExceptionMapper::class)->strict(); } public function testDecodesTheRequestAndScopesItsCallContext(): void @@ -169,12 +174,11 @@ public function testRejectsMalformedTimeoutAndPreviousAttemptHeaders(): void public function testRegistersAndClearsOneDeadlineTimer(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after') - ->once() - ->with(m::type('float'), m::type(Closure::class)) - ->andReturn(41); - $timer->shouldReceive('clear')->once()->with(41); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after') + ->with(Argument::type('float'), Argument::type(Closure::class)) + ->returns(41); + $timer->expects('clear')->with(41); $contexts = new CallContextStore; $handler = new HandleCall($contexts, $timer, $this->exceptions, 1024, Compression::Identity); $request = $this->request(new GPBEmpty, server: ['HTTP_GRPC_TIMEOUT' => '1S']); @@ -192,9 +196,9 @@ public function testRegistersAndClearsOneDeadlineTimer(): void public function testForgetsTheCallContextWhenDeadlineTimerRegistrationFails(): void { $failure = new LogicException('Unable to register the deadline timer.'); - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->andThrow($failure); - $timer->shouldNotReceive('clear'); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->throws($failure); + $timer->expects('clear')->never(); $contexts = new CallContextStore; $handler = new HandleCall($contexts, $timer, $this->exceptions, 1024, Compression::Identity); $request = $this->request(new GPBEmpty, server: ['HTTP_GRPC_TIMEOUT' => '1S']); @@ -212,9 +216,9 @@ public function testForgetsTheCallContextWhenDeadlineTimerRegistrationFails(): v public function testRechecksTheDeadlineAfterNonYieldingServiceWork(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->andReturn(42); - $timer->shouldReceive('clear')->once()->with(42); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->returns(42); + $timer->expects('clear')->with(42); $handler = new HandleCall(new CallContextStore, $timer, $this->exceptions, 1024, Compression::Identity); // Setup counts against the deadline, so leave headroom under suite load while the service work still outlasts it. $request = $this->request(new GPBEmpty, server: ['HTTP_GRPC_TIMEOUT' => '100m']); @@ -235,9 +239,9 @@ public function testDeadlineCancellationReportsCleanupFailuresAndKeepsDeadlineSt { $cleanupException = new RuntimeException('Service cleanup failed.'); if ($cleanupThrows) { - $this->exceptions->shouldReceive('report')->once()->with($cleanupException); + $this->exceptions->expects('report')->with($cleanupException); } else { - $this->exceptions->shouldNotReceive('report'); + $this->exceptions->expects('report')->never(); } $handler = new HandleCall(new CallContextStore, new Timer, $this->exceptions, 1024, Compression::Identity); $request = $this->request(new GPBEmpty, server: ['HTTP_GRPC_TIMEOUT' => '100m']); diff --git a/tests/Grpc/ResponseFactoryTest.php b/tests/Grpc/ResponseFactoryTest.php index c3e2158150..a4cb9e490c 100644 --- a/tests/Grpc/ResponseFactoryTest.php +++ b/tests/Grpc/ResponseFactoryTest.php @@ -25,7 +25,9 @@ use Hypervel\Tests\TestCase; use InvalidArgumentException; use Iterator; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -34,6 +36,8 @@ class ResponseFactoryTest extends TestCase { + use VerifiesDoubles; + public function testBuildsUnaryResponseWithFramingCompressionAndMetadata(): void { [$factory] = $this->factory(); @@ -150,8 +154,8 @@ public function testPreservesCancellationWhilePrimingAStream(): void #[DataProvider('throwingIteratorMethods')] public function testMapsCustomIteratorPrimingFailuresWithinTheGeneratorRewind(string $method): void { - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with(m::type(RuntimeException::class)); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with(Argument::type(RuntimeException::class)); [$factory] = $this->factory($handler); $request = $this->request(serverStreaming: true); $value = GrpcResponse::stream(new ResponseFactoryThrowingIterator($method)) @@ -237,13 +241,13 @@ public function testMapsMidStreamExpectedFailureToFinalTrailers(): void #[TestWith([true, true])] public function testPreservesCancellationWhileAdvancingAStream(bool $deadlineExpired, bool $cleanupThrows): void { - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $cancellation = new CanceledException; $cleanupException = new RuntimeException('Stream cleanup failed.'); if ($deadlineExpired && $cleanupThrows) { - $handler->shouldReceive('report')->once()->with($cleanupException); + $handler->expects('report')->with($cleanupException); } else { - $handler->shouldNotReceive('report'); + $handler->expects('report')->never(); } [$factory, $contexts] = $this->factory($handler); $now = 0; @@ -282,8 +286,8 @@ public function testPreservesCancellationWhileAdvancingAStream(bool $deadlineExp public function testReportsInvalidUnaryAndStreamedServiceValues(): void { - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->twice(); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->times(2); [$factory] = $this->factory($handler); $unary = $factory->make($this->request(serverStreaming: false), 'invalid'); @@ -300,8 +304,8 @@ public function testReportsInvalidUnaryAndStreamedServiceValues(): void public function testFinalizationRejectsProtocolStateMutation(): void { - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once(); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report'); [$factory] = $this->factory($handler); $response = $factory->make($this->request(serverStreaming: false), new GPBEmpty); $response->headers->set('x-injected', 'middleware'); @@ -315,8 +319,8 @@ public function testFinalizationRejectsProtocolStateMutation(): void public function testFinalizationRejectsAReplacementHttpResponse(): void { - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once(); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report'); [$factory] = $this->factory($handler); $final = $factory->finalizeForEmission(new Response('not grpc')); @@ -408,7 +412,7 @@ private function factory( ?ExceptionHandler $handler = null, int $maxMetadataSize = 8192, ): array { - $handler ??= m::mock(ExceptionHandler::class); + $handler ??= Double::for(ExceptionHandler::class)->strict(); $contexts = new CallContextStore; $contexts->set(new ServerCallContext( Metadata::make(), diff --git a/tests/Grpc/ServerTest.php b/tests/Grpc/ServerTest.php index 8967683406..768a934391 100644 --- a/tests/Grpc/ServerTest.php +++ b/tests/Grpc/ServerTest.php @@ -39,8 +39,9 @@ use Hypervel\Routing\Contracts\CallableDispatcher as CallableDispatcherContract; use Hypervel\Routing\Router; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use Psr\Log\LogLevel; @@ -54,6 +55,8 @@ class ServerTest extends TestCase { + use VerifiesDoubles; + /** * Mark the worker as started inside the test coroutine. */ @@ -468,8 +471,8 @@ private function environment( 4 * 1024 * 1024, Compression::Identity, ); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('bootstrap')->once(); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('bootstrap'); $container->instance(KernelContract::class, $kernel); $container->instance( @@ -535,7 +538,7 @@ private function request( ], ?string $body = null, ): SwooleRequest { - $request = m::mock(SwooleRequest::class); + $request = Double::for(SwooleRequest::class)->strict(); $request->server = [ 'server_protocol' => $protocol, 'request_method' => $method, @@ -551,7 +554,7 @@ private function request( $request->post = []; $request->cookie = []; $request->files = []; - $request->shouldReceive('rawContent')->andReturn( + $request->allows('rawContent')->returns( $body ?? (new FrameEncoder(1024))->encode((new GPBEmpty)->serializeToString()), ); @@ -566,37 +569,37 @@ private function request( private function response(): array { $capture = new ServerResponseCapture; - $response = m::mock(SwooleResponse::class); - $response->shouldReceive('status')->zeroOrMoreTimes()->andReturnUsing( + $response = Double::for(SwooleResponse::class)->strict(); + $response->allows('status')->resolves( static function (int $status) use ($capture): bool { $capture->status = $status; return true; }, ); - $response->shouldReceive('header')->zeroOrMoreTimes()->andReturnUsing( + $response->allows('header')->resolves( static function (string $name, string|array $value) use ($capture): bool { $capture->headers[strtolower($name)] = $value; return true; }, ); - $response->shouldReceive('cookie')->zeroOrMoreTimes()->andReturnTrue(); - $response->shouldReceive('trailer')->zeroOrMoreTimes()->andReturnUsing( + $response->allows('cookie')->returns(true); + $response->allows('trailer')->resolves( static function (string $name, string $value) use ($capture): bool { $capture->trailers[strtolower($name)] = $value; return true; }, ); - $response->shouldReceive('write')->zeroOrMoreTimes()->andReturnUsing( + $response->allows('write')->resolves( static function (string $chunk) use ($capture): bool { $capture->writes[] = $chunk; return $capture->writeResult; }, ); - $response->shouldReceive('end')->zeroOrMoreTimes()->andReturnUsing( + $response->allows('end')->resolves( static function (...$arguments) use ($capture): bool { if ($capture->endFailure !== null) { throw $capture->endFailure; @@ -607,7 +610,7 @@ static function (...$arguments) use ($capture): bool { return true; }, ); - $response->shouldReceive('isWritable')->zeroOrMoreTimes()->andReturnUsing( + $response->allows('isWritable')->resolves( static fn (): bool => $capture->writable, ); diff --git a/tests/Hashing/HashFacadeTest.php b/tests/Hashing/HashFacadeTest.php index 2e61ff506f..bd910a914e 100644 --- a/tests/Hashing/HashFacadeTest.php +++ b/tests/Hashing/HashFacadeTest.php @@ -5,13 +5,17 @@ namespace Hypervel\Tests\Hashing; use Hypervel\Container\Container; +use Hypervel\Contracts\Hashing\Hasher; use Hypervel\Support\Facades\Hash; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class HashFacadeTest extends TestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -22,18 +26,17 @@ protected function setUp(): void public function testDynamicCallsForwardTheirMethodArgumentsAndReturnValue(): void { - $root = m::mock(); - $root->shouldReceive('probe') - ->once() - ->with('value', 42) - ->andReturn('result'); + $root = Double::for(Hasher::class)->strict(); + $root->expects('make') + ->with('value', ['rounds' => 4]) + ->returns('result'); $app = new Container; $app->instance('hash', $root); Hash::setFacadeApplication($app); - $this->assertSame('result', Hash::probe('value', 42)); + $this->assertSame('result', Hash::make('value', ['rounds' => 4])); } public function testDynamicCallsWithoutAFacadeRootThrowTheBaseException(): void diff --git a/tests/Hashing/HasherTest.php b/tests/Hashing/HasherTest.php index 25c5d80408..7a4ab61b77 100644 --- a/tests/Hashing/HasherTest.php +++ b/tests/Hashing/HasherTest.php @@ -5,7 +5,7 @@ namespace Hypervel\Tests\Hashing; use Hypervel\Config\Repository as ConfigRepository; -use Hypervel\Contracts\Container\Container; +use Hypervel\Container\Container; use Hypervel\Contracts\Hashing\Hasher as HasherContract; use Hypervel\Hashing\Argon2IdHasher; use Hypervel\Hashing\ArgonHasher; @@ -13,12 +13,15 @@ use Hypervel\Hashing\HashManager; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\Depends; use RuntimeException; class HasherTest extends TestCase { + use VerifiesDoubles; + public HashManager $hashManager; protected function setUp(): void @@ -211,11 +214,10 @@ public function testBasicArgon2idNotSupported(): void public function testIsHashedUsesTheConfiguredDriversInfoMethod(): void { - $driver = m::mock(HasherContract::class); - $driver->shouldReceive('info') - ->once() + $driver = Double::for(HasherContract::class)->strict(); + $driver->expects('info') ->with('custom-hash') - ->andReturn(['algo' => 'custom']); + ->returns(['algo' => 'custom']); $manager = new HashManager($this->getContainer(['driver' => 'custom'])); $manager->extend('custom', fn () => $driver); @@ -249,12 +251,10 @@ protected function getContainer(?array $hashing = null): Container ], ]; - $container = m::mock(Container::class); - $container->shouldReceive('make') - ->with('config') - ->andReturn(new ConfigRepository([ - 'hashing' => $hashing, - ])); + $container = new Container; + $container->instance('config', new ConfigRepository([ + 'hashing' => $hashing, + ])); return $container; } diff --git a/tests/Head/Feature/Schema/SchemaTest.php b/tests/Head/Feature/Schema/SchemaTest.php index 7bae7f6e68..1c1d1ee581 100644 --- a/tests/Head/Feature/Schema/SchemaTest.php +++ b/tests/Head/Feature/Schema/SchemaTest.php @@ -14,12 +14,15 @@ use Hypervel\Head\Schema\SchemaObject; use Hypervel\Tests\Head\Fixtures\JobPosting; use Hypervel\Tests\Head\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Psr\Log\LoggerInterface; class SchemaTest extends TestCase { + use VerifiesDoubles; + public function testRendersBuiltInSchemaObjectsAsJsonLd(): void { Head::schema( @@ -238,8 +241,8 @@ public function testLogsInvalidSchemasAndContinuesRenderingInProduction(): void { $this->app->detectEnvironment(fn (): string => 'production'); $schema = ['@context' => 'https://schema.org', '@type' => 'WebPage', 'name' => '']; - $logger = m::mock(LoggerInterface::class); - $logger->shouldReceive('warning')->once()->with( + $logger = Double::for(LoggerInterface::class)->strict(); + $logger->expects('warning')->with( 'JSON-LD schemas may not contain null or empty string values.', ['schema' => $schema], ); diff --git a/tests/Horizon/Console/HorizonRestartStrategyTest.php b/tests/Horizon/Console/HorizonRestartStrategyTest.php index 39dde9e8be..b54c2159b8 100644 --- a/tests/Horizon/Console/HorizonRestartStrategyTest.php +++ b/tests/Horizon/Console/HorizonRestartStrategyTest.php @@ -11,7 +11,8 @@ use Hypervel\Support\Env; use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use RuntimeException; @@ -20,6 +21,8 @@ class HorizonRestartStrategyTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('environments')] #[RunInSeparateProcess] public function testStartsHorizonFromTheApplicationDirectoryWithTheConfiguredEnvironment(string $environment): void @@ -75,11 +78,13 @@ public function testStartupFailureIncludesAvailableProcessDetails( string $errorOutput, string $expectedMessage, ): void { - $process = m::mock(Process::class); - $process->expects('start')->once(); - $process->expects('isTerminated')->once()->andReturnTrue(); - $process->expects('getExitCode')->once()->andReturn($exitCode); - $process->expects('getErrorOutput')->once()->andReturn($errorOutput); + $process = Double::for(Process::class)->strict(); + // Symfony's destructor stops the process with a zero timeout. + $process->allows('stop')->with(0.0); + $process->expects('start'); + $process->expects('isTerminated')->returns(true); + $process->expects('getExitCode')->returns($exitCode); + $process->expects('getErrorOutput')->returns($errorOutput); $strategy = new class($this->app, new NullOutput, null, $process) extends HorizonRestartStrategy { public function __construct( @@ -124,10 +129,11 @@ public function testStartAndRestartReloadTheConfiguredEnvironmentBeforeCreatingT $this->app->loadEnvironmentFrom('.env.custom'); DotenvManager::safeLoad([$tempDir], '.env.custom'); - $process = m::mock(Process::class); - $process->shouldReceive('start')->twice(); - $process->shouldReceive('isTerminated')->twice()->andReturnFalse(); - $process->shouldReceive('isRunning')->once()->andReturnFalse(); + $process = Double::for(Process::class)->strict(); + $process->allows('stop')->with(0.0); + $process->expects('start')->times(2); + $process->expects('isTerminated')->times(2)->returns(false); + $process->expects('isRunning')->returns(false); $strategy = new class($this->app, new NullOutput, null, $process) extends HorizonRestartStrategy { /** @var list */ @@ -182,10 +188,10 @@ private function createTemporaryApplication(string $name, string $script): array $files->put($applicationPath . '/.env', ''); $files->put($applicationPath . '/artisan', $script); - $application = m::mock(ApplicationContract::class); - $application->expects('environmentFilePath')->andReturn($applicationPath . '/.env'); - $application->expects('basePath')->andReturn($applicationPath); + $application = Double::for(ApplicationContract::class, override: true)->strict(); + $application->expects('environmentFilePath')->returns($applicationPath . '/.env'); + $application->expects('basePath')->returns($applicationPath); - return [$files, $applicationPath, $application]; + return [$files, $applicationPath, $application->instance()]; } } diff --git a/tests/Horizon/Console/InstallCommandTest.php b/tests/Horizon/Console/InstallCommandTest.php index 91a13d8849..910a7f23fb 100644 --- a/tests/Horizon/Console/InstallCommandTest.php +++ b/tests/Horizon/Console/InstallCommandTest.php @@ -11,12 +11,15 @@ use Hypervel\Horizon\HorizonServiceProvider; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Testing\Fixtures\CleanupActions; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\Console\Command\Command as SymfonyCommand; class InstallCommandTest extends TestCase { + use VerifiesDoubles; + protected ?string $originalProvidersContents = null; protected function setUp(): void @@ -163,8 +166,8 @@ public function testInstallCommandFailsWhenProviderReplacementFails(): void $this->originalProvidersContents, ); - $files = m::mock(Filesystem::class); - $files->shouldReceive('replace')->once()->andThrow(new RuntimeException('replace failed')); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('replace')->throws(new RuntimeException('replace failed')); $this->app->instance(Filesystem::class, $files); $this->artisan('horizon:install') diff --git a/tests/Horizon/Console/SnapshotCommandTest.php b/tests/Horizon/Console/SnapshotCommandTest.php index 4c92a22069..d596911987 100644 --- a/tests/Horizon/Console/SnapshotCommandTest.php +++ b/tests/Horizon/Console/SnapshotCommandTest.php @@ -10,10 +10,13 @@ use Hypervel\Horizon\HorizonServiceProvider; use Hypervel\Horizon\Lock; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class SnapshotCommandTest extends TestCase { + use VerifiesDoubles; + protected function getPackageProviders(ApplicationContract $app): array { return [ @@ -23,15 +26,15 @@ protected function getPackageProviders(ApplicationContract $app): array public function testDefaultSnapshotLockLeavesAThirtySecondSafetyMargin(): void { - $lock = m::mock(Lock::class); - $lock->shouldReceive('get')->once()->with( + $lock = Double::for(Lock::class)->strict(); + $lock->expects('get')->with( 'metrics:snapshot', 270, - )->andReturnFalse(); + )->returns(false); $this->app->make(SnapshotCommand::class)->handle( $lock, - m::mock(MetricsRepository::class), + Double::for(MetricsRepository::class)->strict(), ); } @@ -41,15 +44,15 @@ public function testSnapshotLockUsesItsDefaultWhenMetricsConfigurationIsReplaced 'trim_snapshots' => ['job' => 12, 'queue' => 12], ]]); - $lock = m::mock(Lock::class); - $lock->shouldReceive('get')->once()->with( + $lock = Double::for(Lock::class)->strict(); + $lock->expects('get')->with( 'metrics:snapshot', 270, - )->andReturnFalse(); + )->returns(false); $this->app->make(SnapshotCommand::class)->handle( $lock, - m::mock(MetricsRepository::class), + Double::for(MetricsRepository::class)->strict(), ); } } diff --git a/tests/Horizon/Console/WorkCommandTest.php b/tests/Horizon/Console/WorkCommandTest.php index 4ad3078755..94eda71115 100644 --- a/tests/Horizon/Console/WorkCommandTest.php +++ b/tests/Horizon/Console/WorkCommandTest.php @@ -10,10 +10,14 @@ use Hypervel\Queue\Worker; use Hypervel\Queue\WorkerOptions; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class WorkCommandTest extends TestCase { + use VerifiesDoubles; + protected function getPackageProviders(ApplicationContract $app): array { return [ @@ -23,24 +27,19 @@ protected function getPackageProviders(ApplicationContract $app): array public function testOncePassesEveryWorkerOptionAndAcceptsTheWorkersNullResult(): void { - $worker = m::mock(Worker::class); - $worker->shouldReceive('setName') - ->once() - ->with('default') - ->andReturnSelf(); - $worker->shouldReceive('setCache') - ->once() - ->andReturnSelf(); - $worker->shouldReceive('runNextJob') - ->once() - ->withArgs(function (string $connection, string $queue, WorkerOptions $options): bool { + $worker = Double::for(Worker::class)->strict(); + $worker->expects('setName') + ->with('default'); + $worker->expects('setCache'); + $worker->expects('runNextJob') + ->with(Argument::all(function (string $connection, string $queue, WorkerOptions $options): bool { $this->assertSame('sync', $connection); $this->assertSame('default', $queue); $this->assertSame(7, $options->stopWhenEmptyFor); return true; - }) - ->andReturnNull(); + })) + ->returns(null); $this->app->instance(Worker::class, $worker); diff --git a/tests/Horizon/HorizonConfigTest.php b/tests/Horizon/HorizonConfigTest.php index 52b743f238..72b00d8e6c 100644 --- a/tests/Horizon/HorizonConfigTest.php +++ b/tests/Horizon/HorizonConfigTest.php @@ -12,10 +12,13 @@ use Hypervel\Horizon\Repositories\RedisJobRepository; use Hypervel\Support\ServiceProvider; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class HorizonConfigTest extends TestCase { + use VerifiesDoubles; + public function testCanonicalDefaultsAreDeclared(): void { $config = $this->withEnvironmentValues( @@ -54,12 +57,12 @@ public function testApplicationMetricsConfigurationReplacesPackageDefaults(): vo ], ], ]); - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturnFalse(); - $app->shouldReceive('make')->with('config')->andReturn($config); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->andReturn(new ConfigMutationTracker); + $app = Double::for(Application::class, override: true)->passthru(); + $app->allows('configurationIsCached')->returns(false); + $app->allows('make')->with('config')->returns($config); + $app->allows('make')->with(ConfigMutationTracker::class)->returns(new ConfigMutationTracker); - (new HorizonConfigServiceProvider($app))->register(); + (new HorizonConfigServiceProvider($app->instance()))->register(); $this->assertSame([ 'trim_snapshots' => ['job' => 12, 'queue' => 12], @@ -73,12 +76,12 @@ public function testOnlyMissingAndBlankNamesUseTheApplicationName(): void 'app' => ['name' => 'Hypervel'], 'horizon' => ['name' => $name], ]); - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturnFalse(); - $app->shouldReceive('make')->with('config')->andReturn($config); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->andReturn(new ConfigMutationTracker); + $app = Double::for(Application::class, override: true)->passthru(); + $app->allows('configurationIsCached')->returns(false); + $app->allows('make')->with('config')->returns($config); + $app->allows('make')->with(ConfigMutationTracker::class)->returns(new ConfigMutationTracker); - (new HorizonServiceProviderForTesting($app))->normalize(); + (new HorizonServiceProviderForTesting($app->instance()))->normalize(); $this->assertSame($name === '0' ? '0' : 'Hypervel', $config->get('horizon.name')); } @@ -92,12 +95,12 @@ public function testApplicationNameFallbackIsComputedAgainAgainstTheRebuiltConfi ]); $tracker = new ConfigMutationTracker; $tracker->observe($masterConfig); - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturnFalse(); - $app->shouldReceive('make')->with('config')->andReturn($masterConfig); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->andReturn($tracker); + $app = Double::for(Application::class, override: true)->passthru(); + $app->allows('configurationIsCached')->returns(false); + $app->allows('make')->with('config')->returns($masterConfig); + $app->allows('make')->with(ConfigMutationTracker::class)->returns($tracker); - (new HorizonServiceProviderForTesting($app))->normalize(); + (new HorizonServiceProviderForTesting($app->instance()))->normalize(); $this->assertSame('Old Name', $masterConfig->get('horizon.name')); @@ -129,15 +132,15 @@ public function testRedisConnectionIsComputedAgainAgainstTheRebuiltConfiguration $tracker->observe($masterConfig); // Horizon::use() reads the application's configuration, which a rebuild refreshes in place. $currentConfig = $masterConfig; - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturnFalse(); - $app->shouldReceive('make')->with('config')->andReturnUsing(static function () use (&$currentConfig): ConfigRepository { + $app = Double::for(Application::class, override: true)->passthru(); + $app->allows('configurationIsCached')->returns(false); + $app->allows('make')->with('config')->resolves(static function () use (&$currentConfig): ConfigRepository { return $currentConfig; }); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->andReturn($tracker); - Container::setInstance($app); + $app->allows('make')->with(ConfigMutationTracker::class)->returns($tracker); + Container::setInstance($app->instance()); - (new HorizonServiceProviderForTesting($app))->configureForTest(); + (new HorizonServiceProviderForTesting($app->instance()))->configureForTest(); $this->assertSame('old-host', $masterConfig->get('database.redis.horizon.host')); $this->assertSame('old_horizon:', $masterConfig->get('database.redis.horizon.prefix')); diff --git a/tests/Horizon/Unit/FailedJobsControllerTest.php b/tests/Horizon/Unit/FailedJobsControllerTest.php index f7cc0e42c8..597870877e 100644 --- a/tests/Horizon/Unit/FailedJobsControllerTest.php +++ b/tests/Horizon/Unit/FailedJobsControllerTest.php @@ -9,20 +9,20 @@ use Hypervel\Horizon\Http\Controllers\FailedJobsController; use Hypervel\Http\Request; use Hypervel\Tests\Horizon\UnitTestCase; -use Mockery as m; +use JMac\Testing\Double; use PHPUnit\Framework\Attributes\TestWith; class FailedJobsControllerTest extends UnitTestCase { public function testLiteralZeroTagFiltersFailedJobs(): void { - $jobs = m::mock(JobRepository::class); - $jobs->shouldReceive('getJobs')->once()->with(['job-id'], 0)->andReturn(collect()); - $jobs->shouldReceive('countFailed')->never(); + $jobs = Double::for(JobRepository::class)->strict(); + $jobs->expects('getJobs')->with(['job-id'], 0)->returns(collect()); + $jobs->expects('countFailed')->never(); - $tags = m::mock(TagRepository::class); - $tags->shouldReceive('paginate')->once()->with('failed:0', 0, 50)->andReturn(['job-id']); - $tags->shouldReceive('count')->once()->with('failed:0')->andReturn(1); + $tags = Double::for(TagRepository::class)->strict(); + $tags->expects('paginate')->with('failed:0', 0, 50)->returns(['job-id']); + $tags->expects('count')->with('failed:0')->returns(1); $result = (new FailedJobsController($jobs, $tags))->index( Request::create('/?tag=0'), @@ -33,13 +33,13 @@ public function testLiteralZeroTagFiltersFailedJobs(): void public function testEmptyTagUsesTheUnfilteredFailedJobList(): void { - $jobs = m::mock(JobRepository::class); - $jobs->shouldReceive('getFailed')->once()->with(-1)->andReturn(collect()); - $jobs->shouldReceive('countFailed')->once()->andReturn(2); + $jobs = Double::for(JobRepository::class)->strict(); + $jobs->expects('getFailed')->with(-1)->returns(collect()); + $jobs->expects('countFailed')->returns(2); - $tags = m::mock(TagRepository::class); - $tags->shouldReceive('paginate')->never(); - $tags->shouldReceive('count')->never(); + $tags = Double::for(TagRepository::class)->strict(); + $tags->expects('paginate')->never(); + $tags->expects('count')->never(); $result = (new FailedJobsController($jobs, $tags))->index( Request::create('/?tag='), @@ -54,12 +54,12 @@ public function testEmptyTagUsesTheUnfilteredFailedJobList(): void #[TestWith(['49', 50])] public function testTaggedPaginationUsesTheSameStartForSelectionAndRowIndices(?string $cursor, int $startingAt): void { - $jobs = m::mock(JobRepository::class); - $jobs->shouldReceive('getJobs')->once()->with(['job-id'], $startingAt)->andReturn(collect()); + $jobs = Double::for(JobRepository::class)->strict(); + $jobs->expects('getJobs')->with(['job-id'], $startingAt)->returns(collect()); - $tags = m::mock(TagRepository::class); - $tags->shouldReceive('paginate')->once()->with('failed:example', $startingAt, 50)->andReturn(['job-id']); - $tags->shouldReceive('count')->once()->with('failed:example')->andReturn(1); + $tags = Double::for(TagRepository::class)->strict(); + $tags->expects('paginate')->with('failed:example', $startingAt, 50)->returns(['job-id']); + $tags->expects('count')->with('failed:example')->returns(1); (new FailedJobsController($jobs, $tags))->index(Request::create('/', 'GET', array_filter([ 'tag' => 'example', diff --git a/tests/Horizon/Unit/LockTest.php b/tests/Horizon/Unit/LockTest.php index c288acf23d..87e1ab7bb9 100644 --- a/tests/Horizon/Unit/LockTest.php +++ b/tests/Horizon/Unit/LockTest.php @@ -6,24 +6,22 @@ use Hypervel\Contracts\Redis\Factory; use Hypervel\Horizon\Lock; -use Hypervel\Redis\RedisConnection; -use Hypervel\Redis\RedisProxy; use Hypervel\Tests\Horizon\UnitTestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use RuntimeException; class LockTest extends UnitTestCase { public function testGetAcquiresTheLockWithOneAtomicCommand(): void { - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('set') - ->once() - ->with('metrics', '1', 'EX', 60, 'NX') - ->andReturnTrue(); - $connection->shouldNotReceive('setNx'); - $connection->shouldNotReceive('expire'); + [$connection, $client] = $this->redisConnection(); + $client->expects('set') + ->with('metrics', '1', ['NX', 'EX' => 60]) + ->returns(true); + $client->expects('setNx')->never(); + $client->expects('expire')->never(); $lock = new Lock($this->redisFactory($connection)); @@ -32,8 +30,8 @@ public function testGetAcquiresTheLockWithOneAtomicCommand(): void public function testGetRejectsNonPositiveLifetimesBeforeConnecting(): void { - $redis = m::mock(Factory::class); - $redis->shouldNotReceive('connection'); + $redis = Double::for(Factory::class)->strict(); + $redis->expects('connection')->never(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('Horizon lock [metrics] requires a positive lifetime; 0 given.'); @@ -43,8 +41,8 @@ public function testGetRejectsNonPositiveLifetimesBeforeConnecting(): void public function testWithRejectsNonPositiveLifetimesBeforeConnecting(): void { - $redis = m::mock(Factory::class); - $redis->shouldNotReceive('connection'); + $redis = Double::for(Factory::class)->strict(); + $redis->expects('connection')->never(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('Horizon lock [metrics] requires a positive lifetime; -1 given.'); @@ -56,18 +54,12 @@ public function testWithRejectsNonPositiveLifetimesBeforeConnecting(): void public function testCallbackFailureRemainsPrimaryWhenOwnedReleaseFails(): void { $callbackFailure = new RuntimeException('callback failed'); - $rawConnection = m::mock(RedisConnection::class); - $rawConnection->shouldReceive('pack')->once()->andReturn(['packed-owner']); - $rawConnection->shouldReceive('eval')->once()->andThrow(new RuntimeException('release failed')); - - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('set') - ->once() - ->with('metrics', m::type('string'), 'EX', 60, 'NX') - ->andReturnTrue(); - $connection->shouldReceive('withConnection') - ->once() - ->andReturnUsing(static fn (callable $callback): mixed => $callback($rawConnection)); + [$connection, $client, $rawConnection] = $this->redisConnection(); + $rawConnection->expects('pack')->returns(['packed-owner']); + $client->expects('eval')->throws(new RuntimeException('release failed')); + $client->expects('set') + ->with('metrics', Argument::type('string'), ['NX', 'EX' => 60]) + ->returns(true); try { (new Lock($this->redisFactory($connection)))->with( @@ -78,5 +70,7 @@ public function testCallbackFailureRemainsPrimaryWhenOwnedReleaseFails(): void } catch (RuntimeException $thrown) { $this->assertSame($callbackFailure, $thrown); } + + $connection->received('withConnection')->times(1); } } diff --git a/tests/Horizon/Unit/RedisConnectorTest.php b/tests/Horizon/Unit/RedisConnectorTest.php index 5f6b660611..2df86089de 100644 --- a/tests/Horizon/Unit/RedisConnectorTest.php +++ b/tests/Horizon/Unit/RedisConnectorTest.php @@ -9,13 +9,13 @@ use Hypervel\Horizon\RedisQueue; use Hypervel\Support\ClassInvoker; use Hypervel\Tests\Horizon\UnitTestCase; -use Mockery as m; +use JMac\Testing\Double; class RedisConnectorTest extends UnitTestCase { public function testConnectUsesOptionalMemberDefaultsWhenOmitted(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); $connector = new RedisConnector($redis, 'queue'); $queue = $connector->connect([ @@ -33,7 +33,7 @@ public function testConnectUsesOptionalMemberDefaultsWhenOmitted(): void public function testConnectUsesConfiguredMigrationBatchSize(): void { - $queue = (new RedisConnector(m::mock(Redis::class)))->connect([ + $queue = (new RedisConnector(Double::for(Redis::class)->strict()))->connect([ 'queue' => 'default', 'migration_batch_size' => 100, ]); diff --git a/tests/Horizon/Unit/RedisHorizonCommandQueueTest.php b/tests/Horizon/Unit/RedisHorizonCommandQueueTest.php index 4724053cd8..12e7757c19 100644 --- a/tests/Horizon/Unit/RedisHorizonCommandQueueTest.php +++ b/tests/Horizon/Unit/RedisHorizonCommandQueueTest.php @@ -6,9 +6,8 @@ use Hypervel\Contracts\Redis\Factory; use Hypervel\Horizon\RedisHorizonCommandQueue; -use Hypervel\Redis\RedisProxy; use Hypervel\Tests\Horizon\UnitTestCase; -use Mockery as m; +use JMac\Testing\Double; class RedisHorizonCommandQueueTest extends UnitTestCase { @@ -28,24 +27,16 @@ public function testPendingUsesTransactionOnRedisCluster(): void private function createQueue(bool $cluster, string $method): RedisHorizonCommandQueue { - $pipeline = m::mock(); - $pipeline->shouldReceive('lRange')->once()->with('commands:master', 0, 0); - $pipeline->shouldReceive('lTrim')->once()->with('commands:master', 1, -1); - - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('lLen')->once()->with('commands:master')->andReturn(1); - $connection->shouldReceive('isCluster')->once()->andReturn($cluster); - $connection->shouldReceive($method) - ->once() - ->andReturnUsing(function (callable $callback) use ($pipeline): array { - $callback($pipeline); - - return [[json_encode(['command' => 'pause', 'options' => []])], true]; - }); - $connection->shouldNotReceive($method === 'pipeline' ? 'transaction' : 'pipeline'); - - $redis = m::mock(Factory::class); - $redis->shouldReceive('connection')->twice()->with('horizon')->andReturn($connection); + [$connection, $client] = $this->redisConnection($cluster); + $client->expects('lLen')->with('commands:master')->returns(1); + $connection->expects($method === 'pipeline' ? 'transaction' : 'pipeline')->never(); + $client->expects($cluster ? 'multi' : 'pipeline')->returns($client); + $client->expects('lRange')->with('commands:master', 0, 0)->returns($client); + $client->expects('lTrim')->with('commands:master', 1, -1)->returns($client); + $client->expects('exec')->returns([[json_encode(['command' => 'pause', 'options' => []])], true]); + + $redis = Double::for(Factory::class)->strict(); + $redis->expects('connection')->times(2)->with('horizon')->returns($connection); return new RedisHorizonCommandQueue($redis); } diff --git a/tests/Horizon/Unit/RedisMasterSupervisorRepositoryTest.php b/tests/Horizon/Unit/RedisMasterSupervisorRepositoryTest.php index 31d495953b..f34205fe48 100644 --- a/tests/Horizon/Unit/RedisMasterSupervisorRepositoryTest.php +++ b/tests/Horizon/Unit/RedisMasterSupervisorRepositoryTest.php @@ -8,19 +8,19 @@ use Hypervel\Horizon\Repositories\RedisMasterSupervisorRepository; use Hypervel\Redis\RedisProxy; use Hypervel\Tests\Horizon\UnitTestCase; -use Mockery as m; +use JMac\Testing\Double; class RedisMasterSupervisorRepositoryTest extends UnitTestCase { public function testFindIgnoresNonArrayHmgetResponses(): void { // Redis can answer pipelined commands with false while it is still starting. - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('isCluster')->once()->andReturn(false); - $connection->shouldReceive('pipeline')->once()->andReturn([false]); + $connection = Double::for(RedisProxy::class)->strict(); + $connection->expects('isCluster')->returns(false); + $connection->expects('pipeline')->returns([false]); - $redis = m::mock(Factory::class); - $redis->shouldReceive('connection')->with('horizon')->andReturn($connection); + $redis = Double::for(Factory::class)->strict(); + $redis->allows('connection')->with('horizon')->returns($connection); $this->assertNull((new RedisMasterSupervisorRepository($redis))->find('master')); } diff --git a/tests/Horizon/Unit/RedisMetricsRepositoryTest.php b/tests/Horizon/Unit/RedisMetricsRepositoryTest.php index 4c3c957ec2..8ecdf9c40c 100644 --- a/tests/Horizon/Unit/RedisMetricsRepositoryTest.php +++ b/tests/Horizon/Unit/RedisMetricsRepositoryTest.php @@ -5,42 +5,32 @@ namespace Hypervel\Tests\Horizon\Unit; use Hypervel\Horizon\Repositories\RedisMetricsRepository; -use Hypervel\Redis\RedisConnection; use Hypervel\Redis\RedisProxy; use Hypervel\Tests\Horizon\UnitTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; class RedisMetricsRepositoryTest extends UnitTestCase { public function testClearUsesOneRawConnectionLeaseForTheWholeSweep(): void { - $rawConnection = m::mock(RedisConnection::class); - $rawConnection->shouldReceive('del') - ->once() + [$connection, $client, $rawConnection] = $this->redisConnection(); + $client->expects('del') ->with('last_snapshot_at', 'measured_jobs', 'measured_queues', 'metrics:snapshot'); - $rawConnection->shouldReceive('flushByPattern')->once()->with('queue:*'); - $rawConnection->shouldReceive('flushByPattern')->once()->with('job:*'); - $rawConnection->shouldReceive('flushByPattern')->once()->with('snapshot:*'); - - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('withConnection') - ->once() - ->withArgs(function (callable $callback, bool $transform) use ($rawConnection): bool { - $this->assertFalse($transform); - $callback($rawConnection); - - return true; - }); + $rawConnection->expects('flushByPattern')->with('queue:*'); + $rawConnection->expects('flushByPattern')->with('job:*'); + $rawConnection->expects('flushByPattern')->with('snapshot:*'); (new RedisMetricsRepository($this->redisFactory($connection)))->clear(); + + $connection->received('withConnection')->with(Argument::type('callable'), false)->times(1); } public function testMissingSnapshotHashFieldsRemainFalse(): void { - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('transaction') - ->once() - ->andReturn([[ + $connection = Double::for(RedisProxy::class)->strict(); + $connection->expects('transaction') + ->returns([[ 'throughput' => false, 'runtime' => false, ], 0]); diff --git a/tests/Horizon/Unit/RedisQueueTest.php b/tests/Horizon/Unit/RedisQueueTest.php index cedf4c54b5..1a98968b78 100644 --- a/tests/Horizon/Unit/RedisQueueTest.php +++ b/tests/Horizon/Unit/RedisQueueTest.php @@ -23,9 +23,10 @@ use Hypervel\Queue\Events\JobQueueingFailed; use Hypervel\Queue\LuaScripts; use Hypervel\Redis\RedisProxy; +use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\Horizon\UnitTestCase; use Hypervel\Tests\Queue\Fixtures\IntegerQueueName; -use Mockery as m; +use JMac\Testing\Double; use PHPUnit\Framework\Attributes\TestWith; use RedisException; use RuntimeException; @@ -145,13 +146,12 @@ public function testPostPushCancellationStillPublishesTheQueuedOutcome(): void public function testReadyNowReadsTheClusterSafeQueueKey(): void { - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('isCluster')->once()->andReturnTrue(); - $connection->shouldReceive('lLen')->once()->with('queues:{critical}')->andReturn(3); - $connection->shouldReceive('lLen')->once()->with('queues:{0}')->andReturn(4); + [$connection, $client] = $this->redisConnection(cluster: true); + $client->expects('lLen')->with('queues:{critical}')->returns(3); + $client->expects('lLen')->with('queues:{0}')->returns(4); - $redis = m::mock(Factory::class); - $redis->shouldReceive('connection')->times(3)->with('default')->andReturn($connection); + $redis = Double::for(Factory::class)->strict(); + $redis->expects('connection')->times(3)->with('default')->returns($connection); $queue = new RedisQueue($redis, 'default', 'default'); @@ -163,21 +163,20 @@ public function testReadyNowReadsTheClusterSafeQueueKey(): void #[TestWith(['{critical}'])] public function testMigrationEventsReportTheQueueNameOnCluster(string $name): void { + CarbonImmutable::setTestNow($now = CarbonImmutable::create(2026, 1, 1)); $key = 'queues:{critical}'; - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('isCluster')->andReturnTrue(); - $connection->shouldReceive('eval') - ->twice() - ->with(LuaScripts::migrateExpiredJobs(), 3, $key . ':delayed', $key, $key . ':notify', m::type('int'), m::type('int')) - ->andReturn([]); - $connection->shouldReceive('eval') - ->once() - ->with(LuaScripts::migrateExpiredJobs(), 3, $key . ':reserved', $key, $key . ':notify', m::type('int'), m::type('int')) - ->andReturn([]); - $connection->shouldReceive('eval') - ->once() - ->with(LuaScripts::pop(), 3, $key, $key . ':reserved', $key . ':notify', m::type('int')) - ->andReturn([]); + [$connection, $client] = $this->redisConnection(cluster: true); + $client->allows('clearLastError')->returns(true); + $client->expects('eval') + ->times(2) + ->with(LuaScripts::migrateExpiredJobs(), [$key . ':delayed', $key, $key . ':notify', $now->getTimestamp(), RedisQueue::DEFAULT_MIGRATION_BATCH_SIZE], 3) + ->returns([]); + $client->expects('eval') + ->with(LuaScripts::migrateExpiredJobs(), [$key . ':reserved', $key, $key . ':notify', $now->getTimestamp(), RedisQueue::DEFAULT_MIGRATION_BATCH_SIZE], 3) + ->returns([]); + $client->expects('eval') + ->with(LuaScripts::pop(), [$key, $key . ':reserved', $key . ':notify', $now->getTimestamp() + RedisQueue::DEFAULT_RETRY_AFTER], 3) + ->returns([]); $queues = []; $queue = $this->queueRecordingMigrations($connection, $queues); @@ -191,9 +190,9 @@ public function testMigrationEventsReportTheQueueNameOnCluster(string $name): vo public function testConcurrentPopsReportTheirOwnQueueNames(): void { - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('isCluster')->andReturnTrue(); - $connection->shouldReceive('eval')->andReturnUsing(function (): array { + [$connection, $client] = $this->redisConnection(cluster: true); + $client->allows('clearLastError')->returns(true); + $client->allows('eval')->resolves(function (): array { usleep(5000); return []; @@ -212,17 +211,16 @@ public function testConcurrentPopsReportTheirOwnQueueNames(): void public function testFailedPopDoesNotLeakItsQueueNameIntoLaterMigrations(): void { + CarbonImmutable::setTestNow($now = CarbonImmutable::create(2026, 1, 1)); $exception = new RedisException('Connection lost'); - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('isCluster')->andReturnFalse(); - $connection->shouldReceive('eval') - ->once() - ->with(LuaScripts::migrateExpiredJobs(), 3, 'queues:critical:delayed', 'queues:critical', 'queues:critical:notify', m::type('int'), m::type('int')) - ->andThrow($exception); - $connection->shouldReceive('eval') - ->once() - ->with(LuaScripts::migrateExpiredJobs(), 3, 'queues:low:delayed', 'queues:low', 'queues:low:notify', m::type('int'), m::type('int')) - ->andReturn([]); + [$connection, $client] = $this->redisConnection(); + $client->allows('getLastError')->returns(null); + $client->expects('eval') + ->with(LuaScripts::migrateExpiredJobs(), ['queues:critical:delayed', 'queues:critical', 'queues:critical:notify', $now->getTimestamp(), RedisQueue::DEFAULT_MIGRATION_BATCH_SIZE], 3) + ->throws($exception); + $client->expects('eval') + ->with(LuaScripts::migrateExpiredJobs(), ['queues:low:delayed', 'queues:low', 'queues:low:notify', $now->getTimestamp(), RedisQueue::DEFAULT_MIGRATION_BATCH_SIZE], 3) + ->returns([]); $queues = []; $queue = $this->queueRecordingMigrations($connection, $queues); @@ -244,8 +242,8 @@ public function testFailedPopDoesNotLeakItsQueueNameIntoLaterMigrations(): void */ private function queueRecordingMigrations(RedisProxy $connection, array &$queues): RedisQueue { - $redis = m::mock(Factory::class); - $redis->shouldReceive('connection')->with('default')->andReturn($connection); + $redis = Double::for(Factory::class)->strict(); + $redis->allows('connection')->with('default')->returns($connection); $container = new Container; $events = new Dispatcher($container); @@ -268,9 +266,8 @@ private function queueRecordingMigrations(RedisProxy $connection, array &$queues */ private function publishingQueue(array &$stored, ?RuntimeException $failure = null): array { - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('isCluster')->andReturnFalse(); - $connection->expects('evalWithShaCache')->andReturnUsing(static function (string $script, array $keys, array $arguments) use (&$stored, $failure): int { + [$connection, , $rawConnection] = $this->redisConnection(); + $rawConnection->expects('evalWithShaCache')->resolves(static function (string $script, array $keys, array $arguments) use (&$stored, $failure): int { if ($failure !== null) { throw $failure; } @@ -287,8 +284,8 @@ private function publishingQueue(array &$stored, ?RuntimeException $failure = nu return 1; }); - $redis = m::mock(Factory::class); - $redis->shouldReceive('connection')->with('default')->andReturn($connection); + $redis = Double::for(Factory::class)->strict(); + $redis->allows('connection')->with('default')->returns($connection); $container = new Container; Container::setInstance($container); $container->instance('config', new ConfigRepository); diff --git a/tests/Horizon/Unit/RedisTagRepositoryTest.php b/tests/Horizon/Unit/RedisTagRepositoryTest.php index 7ae4019814..bd89258b4f 100644 --- a/tests/Horizon/Unit/RedisTagRepositoryTest.php +++ b/tests/Horizon/Unit/RedisTagRepositoryTest.php @@ -7,14 +7,14 @@ use Hypervel\Contracts\Redis\Factory; use Hypervel\Horizon\Repositories\RedisTagRepository; use Hypervel\Tests\Horizon\UnitTestCase; -use Mockery as m; +use JMac\Testing\Double; class RedisTagRepositoryTest extends UnitTestCase { public function testUntaggedJobsDoNotQueryMonitoredTags(): void { - $redis = m::mock(Factory::class); - $redis->shouldNotReceive('connection'); + $redis = Double::for(Factory::class)->strict(); + $redis->expects('connection')->never(); $this->assertSame([], (new RedisTagRepository($redis))->monitored([])); } diff --git a/tests/Horizon/Unit/RedisWorkloadRepositoryTest.php b/tests/Horizon/Unit/RedisWorkloadRepositoryTest.php index 5b3d2fd715..4bc8cfefbb 100644 --- a/tests/Horizon/Unit/RedisWorkloadRepositoryTest.php +++ b/tests/Horizon/Unit/RedisWorkloadRepositoryTest.php @@ -12,25 +12,25 @@ use Hypervel\Horizon\WaitTimeCalculator; use Hypervel\Support\Collection; use Hypervel\Tests\Horizon\UnitTestCase; -use Mockery as m; +use JMac\Testing\Double; class RedisWorkloadRepositoryTest extends UnitTestCase { public function testSplitQueueWorkloadsKeepNumericQueueNames(): void { - $queue = m::mock(RedisQueue::class); - $queue->shouldReceive('readyNow')->with('1')->andReturn(2); - $queue->shouldReceive('readyNow')->with('2')->andReturn(3); + $queue = Double::for(RedisQueue::class)->strict(); + $queue->allows('readyNow')->with('1')->returns(2); + $queue->allows('readyNow')->with('2')->returns(3); - $queueFactory = m::mock(QueueFactory::class); - $queueFactory->shouldReceive('connection')->with('redis')->andReturn($queue); + $queueFactory = Double::for(QueueFactory::class)->strict(); + $queueFactory->allows('connection')->with('redis')->returns($queue); - $supervisors = m::mock(SupervisorRepository::class); - $supervisors->shouldReceive('all')->andReturn([(object) ['processes' => ['redis:1,2' => 1]]]); + $supervisors = Double::for(SupervisorRepository::class)->strict(); + $supervisors->allows('all')->returns([(object) ['processes' => ['redis:1,2' => 1]]]); - $metrics = m::mock(MetricsRepository::class); - $metrics->shouldReceive('runtimeForQueue')->with('1')->andReturn(1000.0); - $metrics->shouldReceive('runtimeForQueue')->with('2')->andReturn(2000.0); + $metrics = Double::for(MetricsRepository::class)->strict(); + $metrics->allows('runtimeForQueue')->with('1')->returns(1000.0); + $metrics->allows('runtimeForQueue')->with('2')->returns(2000.0); $repository = new RedisWorkloadRepository( $queueFactory, diff --git a/tests/Horizon/Unit/ScaleCommandTest.php b/tests/Horizon/Unit/ScaleCommandTest.php index e90070c48e..bfcbd313c6 100644 --- a/tests/Horizon/Unit/ScaleCommandTest.php +++ b/tests/Horizon/Unit/ScaleCommandTest.php @@ -7,14 +7,14 @@ use Hypervel\Horizon\Supervisor; use Hypervel\Horizon\SupervisorCommands\Scale; use Hypervel\Tests\Horizon\UnitTestCase; -use Mockery as m; +use JMac\Testing\Double; class ScaleCommandTest extends UnitTestCase { public function testScaleCommandTellsSupervisorToScale(): void { - $supervisor = m::mock(Supervisor::class); - $supervisor->shouldReceive('scale')->once()->with(3); + $supervisor = Double::for(Supervisor::class)->strict(); + $supervisor->expects('scale')->with(3); $scale = new Scale; $scale->process($supervisor, ['scale' => 3]); } diff --git a/tests/Horizon/Unit/UpdateJobMetricsTest.php b/tests/Horizon/Unit/UpdateJobMetricsTest.php index 36b8eb096b..9fdd83ba01 100644 --- a/tests/Horizon/Unit/UpdateJobMetricsTest.php +++ b/tests/Horizon/Unit/UpdateJobMetricsTest.php @@ -10,7 +10,7 @@ use Hypervel\Horizon\Stopwatch; use Hypervel\Queue\Jobs\RedisJob; use Hypervel\Tests\Horizon\UnitTestCase; -use Mockery as m; +use JMac\Testing\Double; use RuntimeException; class UpdateJobMetricsTest extends UnitTestCase @@ -18,13 +18,13 @@ class UpdateJobMetricsTest extends UnitTestCase public function testQueueMetricFailureStillReleasesTheStopwatchEntry(): void { $exception = new RuntimeException('queue metrics failed'); - $metrics = m::mock(MetricsRepository::class); - $metrics->shouldReceive('incrementQueue')->once()->with('critical', 1.5)->andThrow($exception); - $metrics->shouldNotReceive('incrementJob'); + $metrics = Double::for(MetricsRepository::class)->strict(); + $metrics->expects('incrementQueue')->with('critical', 1.5)->throws($exception); + $metrics->expects('incrementJob')->never(); - $watch = m::mock(Stopwatch::class); - $watch->shouldReceive('check')->once()->with('job-id')->andReturn(1.5); - $watch->shouldReceive('forget')->once()->with('job-id'); + $watch = Double::for(Stopwatch::class)->strict(); + $watch->expects('check')->with('job-id')->returns(1.5); + $watch->expects('forget')->with('job-id'); try { (new UpdateJobMetrics($metrics, $watch))->handle($this->event()); @@ -37,13 +37,13 @@ public function testQueueMetricFailureStillReleasesTheStopwatchEntry(): void public function testJobMetricFailureStillReleasesTheStopwatchEntry(): void { $exception = new RuntimeException('job metrics failed'); - $metrics = m::mock(MetricsRepository::class); - $metrics->shouldReceive('incrementQueue')->once()->with('critical', 1.5); - $metrics->shouldReceive('incrementJob')->once()->with('ExampleJob', 1.5)->andThrow($exception); + $metrics = Double::for(MetricsRepository::class)->strict(); + $metrics->expects('incrementQueue')->with('critical', 1.5); + $metrics->expects('incrementJob')->with('ExampleJob', 1.5)->throws($exception); - $watch = m::mock(Stopwatch::class); - $watch->shouldReceive('check')->once()->with('job-id')->andReturn(1.5); - $watch->shouldReceive('forget')->once()->with('job-id'); + $watch = Double::for(Stopwatch::class)->strict(); + $watch->expects('check')->with('job-id')->returns(1.5); + $watch->expects('forget')->with('job-id'); try { (new UpdateJobMetrics($metrics, $watch))->handle($this->event()); @@ -55,9 +55,9 @@ public function testJobMetricFailureStillReleasesTheStopwatchEntry(): void private function event(): JobDeleted { - $job = m::mock(RedisJob::class); - $job->shouldReceive('hasFailed')->once()->andReturnFalse(); - $job->shouldReceive('getQueue')->once()->andReturn('critical'); + $job = Double::for(RedisJob::class)->strict(); + $job->expects('hasFailed')->returns(false); + $job->expects('getQueue')->returns('critical'); return new JobDeleted( $job, diff --git a/tests/Horizon/Unit/UsesClusterAwarePipelineTest.php b/tests/Horizon/Unit/UsesClusterAwarePipelineTest.php index 29048fcd00..bc7537f542 100644 --- a/tests/Horizon/Unit/UsesClusterAwarePipelineTest.php +++ b/tests/Horizon/Unit/UsesClusterAwarePipelineTest.php @@ -7,16 +7,16 @@ use Hypervel\Horizon\Repositories\UsesClusterAwarePipeline; use Hypervel\Redis\RedisProxy; use Hypervel\Tests\Horizon\UnitTestCase; -use Mockery as m; +use JMac\Testing\Double; class UsesClusterAwarePipelineTest extends UnitTestCase { public function testStandaloneConnectionUsesPipeline(): void { - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('isCluster')->once()->andReturnFalse(); - $connection->shouldReceive('pipeline')->once()->andReturn(['pipeline']); - $connection->shouldNotReceive('transaction'); + $connection = Double::for(RedisProxy::class)->strict(); + $connection->expects('isCluster')->returns(false); + $connection->expects('pipeline')->returns(['pipeline']); + $connection->expects('transaction')->never(); $this->assertSame( ['pipeline'], @@ -27,10 +27,10 @@ public function testStandaloneConnectionUsesPipeline(): void public function testClusterConnectionUsesTransaction(): void { - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('isCluster')->once()->andReturnTrue(); - $connection->shouldReceive('transaction')->once()->andReturn(['transaction']); - $connection->shouldNotReceive('pipeline'); + $connection = Double::for(RedisProxy::class)->strict(); + $connection->expects('isCluster')->returns(true); + $connection->expects('transaction')->returns(['transaction']); + $connection->expects('pipeline')->never(); $this->assertSame( ['transaction'], diff --git a/tests/Horizon/UnitTestCase.php b/tests/Horizon/UnitTestCase.php index 4b8d375fd1..6024248f77 100644 --- a/tests/Horizon/UnitTestCase.php +++ b/tests/Horizon/UnitTestCase.php @@ -4,20 +4,60 @@ namespace Hypervel\Tests\Horizon; +use Hypervel\Container\Container; use Hypervel\Contracts\Redis\Factory; +use Hypervel\Redis\Pool\PoolManager; +use Hypervel\Redis\Pool\RedisPool; +use Hypervel\Redis\RedisConnection; use Hypervel\Redis\RedisProxy; +use Hypervel\Redis\RedisSentinelFactory; +use Hypervel\Tests\Redis\Fixtures\PhpRedisClusterConnectionStub; +use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use Redis; +use RedisCluster; abstract class UnitTestCase extends TestCase { + use VerifiesDoubles; + + /** + * Create a real Redis forwarding path with an isolated native client. + * + * @return array{DoubleInterface&RedisProxy, (DoubleInterface&Redis)|(DoubleInterface&RedisCluster), DoubleInterface&RedisConnection} + */ + protected function redisConnection(bool $cluster = false): array + { + $client = Double::for($cluster ? RedisCluster::class : Redis::class)->strict(); + $client->allows('getMode')->returns(Redis::ATOMIC); + + $connection = Double::for( + ($cluster ? new PhpRedisClusterConnectionStub : new PhpRedisConnectionStub)->setActiveConnection($client), + )->passthru(); + $connection->allows('release'); + + $pool = Double::for(RedisPool::class)->strict(); + $pool->allows('borrow')->returns($connection); + $pool->allows('getConfig')->returns(['cluster' => ['enabled' => $cluster]]); + + $manager = Double::for(new PoolManager(new Container))->passthru(); + $manager->allows('pool')->with('horizon')->returns($pool); + + $proxy = Double::for(new RedisProxy($manager, 'horizon', new RedisSentinelFactory))->passthru(); + + return [$proxy, $client, $connection]; + } + /** * Create a Redis factory for the given Horizon connection. */ protected function redisFactory(RedisProxy $connection): Factory { - $redis = m::mock(Factory::class); - $redis->shouldReceive('connection')->once()->with('horizon')->andReturn($connection); + $redis = Double::for(Factory::class)->strict(); + $redis->expects('connection')->with('horizon')->returns($connection); return $redis; } diff --git a/tests/Http/Client/CurlStreamingHandlerTest.php b/tests/Http/Client/CurlStreamingHandlerTest.php index 3cf455a7f7..ab80a3b5d8 100644 --- a/tests/Http/Client/CurlStreamingHandlerTest.php +++ b/tests/Http/Client/CurlStreamingHandlerTest.php @@ -18,7 +18,8 @@ use Hypervel\Http\Client\RequestException; use Hypervel\Tests\Http\Fixtures\LoopbackHttpServer; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; @@ -33,6 +34,8 @@ class CurlStreamingHandlerTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('ambiguousHosts')] public function testAmbiguousHostsAreRejectedBeforeConnecting(string $url, array $headers, string $message): void { @@ -230,8 +233,8 @@ public function testPreHeaderRetryDoesNotRecheckTheDeadlineAfterTheReplacementCa $server = LoopbackHttpServer::start([['body' => ''], ['body' => 'retried']]); $nativeFactory = new CurlFactory(0); $first = true; - $factory = m::mock(CurlFactoryInterface::class); - $factory->shouldReceive('create')->andReturnUsing(static function (RequestInterface $request, array $options) use ($nativeFactory, &$first): EasyHandle { + $factory = Double::for(CurlFactoryInterface::class)->strict(); + $factory->allows('create')->resolves(static function (RequestInterface $request, array $options) use ($nativeFactory, &$first): EasyHandle { $easy = $nativeFactory->create($request, $options); if ($first) { @@ -242,7 +245,7 @@ public function testPreHeaderRetryDoesNotRecheckTheDeadlineAfterTheReplacementCa return $easy; }); - $factory->shouldReceive('release')->andReturnUsing($nativeFactory->release(...)); + $factory->allows('release')->resolves($nativeFactory->release(...)); $handler = new CurlStreamingHandler; (new ReflectionProperty($handler, 'factory'))->setValue($handler, $factory); $callbacks = 0; diff --git a/tests/Http/Client/Guzzle/CoroutineStateTest.php b/tests/Http/Client/Guzzle/CoroutineStateTest.php index a606c3dbd8..810d7f47da 100644 --- a/tests/Http/Client/Guzzle/CoroutineStateTest.php +++ b/tests/Http/Client/Guzzle/CoroutineStateTest.php @@ -20,7 +20,8 @@ use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Http\Client\Guzzle\Fixtures\HttpServer; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -32,6 +33,8 @@ class CoroutineStateTest extends TestCase { + use VerifiesDoubles; + protected ?HttpServer $server = null; /** @@ -148,8 +151,8 @@ public function testThrowingExitTaskReportsAndCancelsTransfersWithoutSkippingEar { $url = $this->startServer(); $failure = new RuntimeException('exit callback failed'); - $reporter = m::mock(ExceptionHandler::class); - $reporter->shouldReceive('report')->once()->with($failure); + $reporter = Double::for(ExceptionHandler::class)->strict(); + $reporter->expects('report')->with($failure); $this->app->instance(ExceptionHandler::class, $reporter); $transfer = null; $earlierDeferRan = false; diff --git a/tests/Http/HttpClientTest.php b/tests/Http/HttpClientTest.php index 5598a97ba4..fa10e3446c 100644 --- a/tests/Http/HttpClientTest.php +++ b/tests/Http/HttpClientTest.php @@ -60,9 +60,11 @@ use Hypervel\Tests\Http\Fixtures\LoopbackHttpServer; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use JsonException; use JsonSerializable; -use Mockery as m; use OutOfBoundsException; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\Attributes\DataProvider; @@ -83,6 +85,8 @@ class HttpClientTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; protected Factory $factory; @@ -1773,8 +1777,8 @@ public static function emptyJsonReadMethodProvider(): array public function testEmptyRequestDataIsDecodedOnlyOnce(): void { - $body = m::mock(StreamInterface::class); - $body->expects('__toString')->andReturn('[]'); + $body = Double::for(StreamInterface::class)->strict(); + $body->expects('__toString')->returns('[]'); $request = new Request(new GuzzleRequest( 'POST', 'https://example.test', @@ -3698,11 +3702,11 @@ public function testOnHeadersFailuresOnFakedResponsesFailLikeATransport(bool $as public function testAsyncResponseBearingFailuresCanRetryWithoutReportingAConnectionFailure(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->andReturnTrue(); - $events->shouldReceive('dispatch')->with(m::type(RequestSending::class))->twice(); - $events->shouldReceive('dispatch')->with(m::type(ResponseReceived::class))->once(); - $events->shouldNotReceive('dispatch')->with(m::type(ConnectionFailedEvent::class)); + $events = Double::for(Dispatcher::class)->strict(); + $events->allows('hasListeners')->returns(true); + $events->expects('dispatch')->with(Argument::type(RequestSending::class))->times(2); + $events->expects('dispatch')->with(Argument::type(ResponseReceived::class)); + $events->expects('dispatch')->never()->with(Argument::type(ConnectionFailedEvent::class)); $factory = new Factory($events); $factory->fakeSequence()->push('first')->push('second'); $seen = 0; @@ -3803,10 +3807,10 @@ public function testPsrSinkRewindFailureIsPropagated(): void { $this->factory->fakeSequence()->push('abc123'); $failure = new RuntimeException('Unable to rewind PSR stream'); - $stream = m::mock(StreamInterface::class); - $stream->expects('write')->with('abc123')->andReturn(6); - $stream->expects('isSeekable')->andReturnTrue(); - $stream->expects('rewind')->andThrow($failure); + $stream = Double::for(StreamInterface::class)->strict(); + $stream->expects('write')->with('abc123')->returns(6); + $stream->expects('isSeekable')->returns(true); + $stream->expects('rewind')->throws($failure); try { $this->factory->sink($stream)->get('https://example.com'); @@ -4557,10 +4561,10 @@ public function testClonedClientsWorkSuccessfullyWithTheRequestObject(): void public function testRequestEventsAreNotDispatchedWithoutListeners(): void { - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(RequestSending::class)->andReturn(false); - $events->expects('hasListeners')->with(ResponseReceived::class)->andReturn(false); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(RequestSending::class)->returns(false); + $events->expects('hasListeners')->with(ResponseReceived::class)->returns(false); + $events->expects('dispatch')->never(); $factory = new Factory($events); $factory->fake(); @@ -4570,11 +4574,11 @@ public function testRequestEventsAreNotDispatchedWithoutListeners(): void public function testTheConnectionFailedEventIsFiredWhenARequestFailsToConnect(): void { - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(RequestSending::class)->andReturn(true); - $events->expects('hasListeners')->with(ConnectionFailedEvent::class)->andReturn(true); - $events->expects('dispatch')->with(m::type(RequestSending::class)); - $events->expects('dispatch')->with(m::type(ConnectionFailedEvent::class)); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(RequestSending::class)->returns(true); + $events->expects('hasListeners')->with(ConnectionFailedEvent::class)->returns(true); + $events->expects('dispatch')->with(Argument::type(RequestSending::class)); + $events->expects('dispatch')->with(Argument::type(ConnectionFailedEvent::class)); $factory = new Factory($events); $factory->fake($factory::failedConnection('Fake')); @@ -4796,9 +4800,9 @@ public function testResponseBearingTransportFailurePreservesChainedCancellation( $failure = new RuntimeException('Sink cleanup failed.', previous: new CanceledException('Request canceled.')); $attempts = 0; $policyCalled = false; - $sink = m::mock(StreamInterface::class); - $sink->shouldReceive('isWritable')->andReturnTrue(); - $sink->shouldReceive('write')->andReturnUsing(function () use (&$attempts, $failure): never { + $sink = Double::for(StreamInterface::class)->strict(); + $sink->allows('isWritable')->returns(true); + $sink->allows('write')->resolves(function () use (&$attempts, $failure): never { ++$attempts; throw $failure; @@ -7085,21 +7089,20 @@ public function testTheTransferStatsAreCustomizable(): void { $onStatsFunctionCalled = false; - $client = m::mock(ClientInterface::class); + $client = Double::for(ClientInterface::class)->strict(); $client->expects('request') - ->withArgs(function ($method, $url, $options) { + ->with('GET', 'https://example.com', Argument::type('array')) + ->resolves(function ($method, $url, $options) { $options['on_stats'](new TransferStats( - new \GuzzleHttp\Psr7\Request($method, $url), + new GuzzleRequest($method, $url), new Psr7Response(200, [], 'ok'), 0.123, null, ['original' => 'value'], )); - return $method === 'GET' - && $url === 'https://example.com'; - }) - ->andReturn(new Psr7Response(200, [], 'ok')); + return new Psr7Response(200, [], 'ok'); + }); $stats = (new PendingRequest($this->factory)) ->setClient($client) diff --git a/tests/Http/HttpRequestTest.php b/tests/Http/HttpRequestTest.php index bf3278fece..fff2270826 100644 --- a/tests/Http/HttpRequestTest.php +++ b/tests/Http/HttpRequestTest.php @@ -14,7 +14,8 @@ use Hypervel\Tests\Database\Fixtures\Models\Money\Price; use Hypervel\Tests\Support\Concerns\TestsInteractsWithDataContract; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException; @@ -26,6 +27,7 @@ class HttpRequestTest extends TestCase { use TestsInteractsWithDataContract; + use VerifiesDoubles; public function testInstanceMethod(): void { @@ -1212,11 +1214,11 @@ public function testOldMethodCanGetDefaultValueFromModelByKey(): void public function testOldMethodReturnsNonStringInputAndDefaults(): void { $request = Request::create('/'); - $model = m::mock(Price::class); - $model->expects('getAttribute')->with('stock')->andReturn(7); - $session = m::mock(Store::class); - $session->expects('getOldInput')->with('quantity', 0)->andReturn(3); - $session->expects('getOldInput')->with('stock', 7)->andReturn(7); + $model = Double::for(Price::class)->strict(); + $model->expects('getAttribute')->with('stock')->returns(7); + $session = Double::for(Store::class)->strict(); + $session->expects('getOldInput')->with('quantity', 0)->returns(3); + $session->expects('getOldInput')->with('stock', 7)->returns(7); $request->setHypervelSession($session); $this->assertSame(3, $request->old('quantity', 0)); diff --git a/tests/Http/HttpServiceProviderTest.php b/tests/Http/HttpServiceProviderTest.php index 2915665243..7bc5d31f3e 100644 --- a/tests/Http/HttpServiceProviderTest.php +++ b/tests/Http/HttpServiceProviderTest.php @@ -13,48 +13,49 @@ use Hypervel\Support\Facades\Event; use Hypervel\Support\Facades\Http; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Swoole\Server; class HttpServiceProviderTest extends TestCase { + use VerifiesDoubles; + public function testBeforeForkClearsResolvedConnectionHandlers(): void { $listeners = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('listen') - ->once() - ->andReturnUsing(function (string $event, callable $listener) use (&$listeners): void { + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('listen') + ->resolves(function (string $event, callable $listener) use (&$listeners): void { $listeners[$event] = $listener; }); - $factory = m::mock(Factory::class); - $factory->shouldReceive('forgetConnectionHandlers')->once()->andReturnSelf(); - $application = m::mock(Application::class); - $application->shouldReceive('make')->once()->with('events')->andReturn($events); - $application->shouldReceive('resolved')->once()->with(Factory::class)->andReturnTrue(); - $application->shouldReceive('make')->once()->with(Factory::class)->andReturn($factory); + $factory = Double::for(Factory::class)->strict(); + $factory->expects('forgetConnectionHandlers'); + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('make')->with('events')->returns($events); + $application->expects('resolved')->with(Factory::class)->returns(true); + $application->expects('make')->with(Factory::class)->returns($factory); - (new HttpServiceProvider($application))->boot(); + (new HttpServiceProvider($application->instance()))->boot(); - $listeners[BeforeServerFork::class](new BeforeServerFork(m::mock(Server::class))); + $listeners[BeforeServerFork::class](new BeforeServerFork(Double::for(Server::class)->strict())); } public function testBeforeForkDoesNotResolveAnUnusedFactory(): void { $listeners = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('listen') - ->once() - ->andReturnUsing(function (string $event, callable $listener) use (&$listeners): void { + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('listen') + ->resolves(function (string $event, callable $listener) use (&$listeners): void { $listeners[$event] = $listener; }); - $application = m::mock(Application::class); - $application->shouldReceive('make')->once()->with('events')->andReturn($events); - $application->shouldReceive('resolved')->once()->with(Factory::class)->andReturnFalse(); + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('make')->with('events')->returns($events); + $application->expects('resolved')->with(Factory::class)->returns(false); - (new HttpServiceProvider($application))->boot(); + (new HttpServiceProvider($application->instance()))->boot(); - $listeners[BeforeServerFork::class](new BeforeServerFork(m::mock(Server::class))); + $listeners[BeforeServerFork::class](new BeforeServerFork(Double::for(Server::class)->strict())); } public function testAScopedEventFakeReachesTheResolvedFactoryAndIsRemovedAfterwards(): void diff --git a/tests/Http/IterableStreamedResponseTest.php b/tests/Http/IterableStreamedResponseTest.php index 96a9084185..2d6873345a 100644 --- a/tests/Http/IterableStreamedResponseTest.php +++ b/tests/Http/IterableStreamedResponseTest.php @@ -8,11 +8,14 @@ use Hypervel\Contracts\Debug\ExceptionHandler; use Hypervel\Http\IterableStreamedResponse; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class IterableStreamedResponseTest extends TestCase { + use VerifiesDoubles; + public function testSendContentConsumesLazyChunksOnce(): void { $iterations = 0; @@ -90,8 +93,8 @@ public function testStreamToPreservesWriterFailureWhenReleasingChunksAlsoFails() $response = new IterableStreamedResponse($chunks); unset($chunks); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($releaseFailure); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($releaseFailure); Container::getInstance()->instance(ExceptionHandler::class, $handler); try { @@ -121,8 +124,8 @@ public function testSendContentPreservesOutputFailureWhenReleasingChunksAlsoFail $response = new IterableStreamedResponse($chunks); unset($chunks); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($releaseFailure); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($releaseFailure); Container::getInstance()->instance(ExceptionHandler::class, $handler); $level = ob_get_level(); diff --git a/tests/HttpServer/RequestBridgeTest.php b/tests/HttpServer/RequestBridgeTest.php index 27865bae99..c2476548d7 100644 --- a/tests/HttpServer/RequestBridgeTest.php +++ b/tests/HttpServer/RequestBridgeTest.php @@ -10,7 +10,8 @@ use Hypervel\HttpServer\RequestBridge; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionProperty; use Swoole\Http\Request as SwooleRequest; @@ -18,6 +19,8 @@ class RequestBridgeTest extends TestCase { + use VerifiesDoubles; + protected string $tempDirectory; protected function setUp(): void @@ -639,14 +642,14 @@ private function createSwooleRequest( ?array $files = null, string|false $rawContent = false, ): SwooleRequest { - $swooleRequest = m::mock(SwooleRequest::class); + $swooleRequest = Double::for(SwooleRequest::class)->strict(); $swooleRequest->server = $server; $swooleRequest->header = $header; $swooleRequest->get = $get; $swooleRequest->post = $post; $swooleRequest->cookie = $cookie; $swooleRequest->files = $files; - $swooleRequest->shouldReceive('rawContent')->andReturn($rawContent); + $swooleRequest->allows('rawContent')->returns($rawContent); return $swooleRequest; } diff --git a/tests/HttpServer/ResponseBridgeTest.php b/tests/HttpServer/ResponseBridgeTest.php index d0ba5acf9a..8a559bc1e9 100644 --- a/tests/HttpServer/ResponseBridgeTest.php +++ b/tests/HttpServer/ResponseBridgeTest.php @@ -14,7 +14,10 @@ use Hypervel\Server\ResponseCancellation; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionProperty; use RuntimeException; @@ -31,6 +34,8 @@ class ResponseBridgeTest extends TestCase { + use VerifiesDoubles; + protected string $tempDirectory; protected function setUp(): void @@ -54,9 +59,9 @@ public function testSendPlainResponse(): void $response = new Response('Hello World', 200, ['X-Custom' => 'value']); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->with(200)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->atLeast()->once()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->with('Hello World')->andReturnTrue(); + $swooleResponse->expects('status')->with(200)->returns(true); + $swooleResponse->expects('header')->times(minimum: 1)->returns(true); + $swooleResponse->expects('end')->with('Hello World')->returns(true); ResponseBridge::send($response, $swooleResponse); } @@ -66,9 +71,9 @@ public function testSendStatusCode(): void $response = new Response('Not Found', 404); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->with(404)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->with('Not Found')->andReturnTrue(); + $swooleResponse->expects('status')->with(404)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end')->with('Not Found')->returns(true); ResponseBridge::send($response, $swooleResponse); } @@ -83,13 +88,13 @@ public function testSendHeaders(): void $swooleResponse = $this->mockSwooleResponse(); $sentHeaders = []; - $swooleResponse->shouldReceive('status')->once()->with(200)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->andReturnUsing(function (string $name, string|array $value) use (&$sentHeaders): bool { + $swooleResponse->expects('status')->with(200)->returns(true); + $swooleResponse->allows('header')->resolves(function (string $name, string|array $value) use (&$sentHeaders): bool { $sentHeaders[$name] = $value; return true; }); - $swooleResponse->shouldReceive('end')->once()->andReturnTrue(); + $swooleResponse->expects('end')->returns(true); ResponseBridge::send($response, $swooleResponse); @@ -102,9 +107,10 @@ public function testSendHeaders(): void public function testSendNumericOnlyHeaderNameAsString(string $name): void { $response = new Response('OK', headers: [$name => 'value']); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'end'); - $swooleResponse->shouldReceive('header')->once()->with($name, 'value')->andReturnTrue(); + $swooleResponse->allows('header')->with(Argument::not($name), Argument::any())->returns(true); + $swooleResponse->expects('header')->with($name, 'value')->returns(true); ResponseBridge::send($response, $swooleResponse); } @@ -124,13 +130,13 @@ public function testSendCookies(): void $swooleResponse = $this->mockSwooleResponse(); $sentCookies = []; - $swooleResponse->shouldReceive('status')->once()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturn(true); - $swooleResponse->shouldReceive('cookie')->andReturnUsing(function (...$args) use (&$sentCookies) { + $swooleResponse->expects('status')->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->allows('cookie')->resolves(function (...$args) use (&$sentCookies) { $sentCookies[] = $args; return true; }); - $swooleResponse->shouldReceive('end')->once()->andReturnTrue(); + $swooleResponse->expects('end')->returns(true); ResponseBridge::send($response, $swooleResponse); @@ -145,10 +151,10 @@ public function testSendRawPartitionedCookie(): void $response->headers->setCookie( Cookie::create('raw', 'a%2Fb')->withRaw()->withPartitioned() ); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header', 'end'); - $swooleResponse->shouldNotReceive('cookie'); - $swooleResponse->shouldReceive('rawcookie')->once()->with( + $swooleResponse->expects('cookie')->never(); + $swooleResponse->expects('rawcookie')->with( 'raw', 'a%2Fb', 0, @@ -159,7 +165,7 @@ public function testSendRawPartitionedCookie(): void 'lax', '', true, - )->andReturnTrue(); + )->returns(true); ResponseBridge::send($response, $swooleResponse); } @@ -169,9 +175,9 @@ public function testSendWithoutBodyForHeadRequest(): void $response = new Response('This body should not be sent', 200, ['Content-Length' => '28']); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->with(200)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); + $swooleResponse->expects('status')->with(200)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end')->with()->returns(true); ResponseBridge::send($response, $swooleResponse, withBody: false); } @@ -181,9 +187,9 @@ public function testSendNonStreamedHypervelResponse(): void $response = new HypervelResponse('Normal content', 200); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->with(200)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->with('Normal content')->andReturnTrue(); + $swooleResponse->expects('status')->with(200)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end')->with('Normal content')->returns(true); ResponseBridge::send($response, $swooleResponse); } @@ -194,9 +200,9 @@ public function testSendBinaryFileResponse(): void $response = new BinaryFileResponse($path); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('sendfile')->once()->with($path, 0, 0)->andReturnTrue(); + $swooleResponse->expects('status')->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('sendfile')->with($path, 0, 0)->returns(true); ResponseBridge::send($response, $swooleResponse); } @@ -206,12 +212,12 @@ public function testPreparedBinaryRangeUsesBoundedNativeSendfileArgumentsForHttp $path = $this->temporaryFile(); $response = new BinaryFileResponse($path); $response->prepare(Request::create('/', 'GET', server: ['HTTP_RANGE' => 'bytes=2-5'])); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('header'); - $swooleResponse->shouldReceive('status')->once()->with(206)->andReturnTrue(); - $swooleResponse->shouldReceive('sendfile')->once()->with($path, 2, 4)->andReturnTrue(); - $swooleResponse->shouldNotReceive('write'); - $swooleResponse->shouldNotReceive('end'); + $swooleResponse->expects('status')->with(206)->returns(true); + $swooleResponse->expects('sendfile')->with($path, 2, 4)->returns(true); + $swooleResponse->expects('write')->never(); + $swooleResponse->expects('end')->never(); ResponseBridge::send($response, $swooleResponse); } @@ -223,26 +229,26 @@ public function testHttpTwoBinaryResponseStreamsBoundedChunksWithoutConflictingF $response->setChunkSize(4); $response->prepare(Request::create('/')); $response->headers->set('Transfer-Encoding', 'chunked'); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status'); $headers = []; $chunks = []; - $swooleResponse->shouldReceive('header')->andReturnUsing( + $swooleResponse->allows('header')->resolves( static function (string $name, string|array $value) use (&$headers): bool { $headers[strtolower($name)] = $value; return true; } ); - $swooleResponse->shouldReceive('sendfile')->never(); - $swooleResponse->shouldReceive('write')->times(4)->andReturnUsing( + $swooleResponse->expects('sendfile')->never(); + $swooleResponse->expects('write')->times(4)->resolves( static function (string $chunk) use (&$chunks): bool { $chunks[] = $chunk; return true; } ); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); + $swooleResponse->expects('end')->with()->returns(true); ResponseBridge::send($response, $swooleResponse, protocol: 'HTTP/2'); @@ -257,18 +263,18 @@ public function testHttpTwoBinaryRangeStreamsOnlyThePreparedBytes(): void $response = new BinaryFileResponse($path); $response->setChunkSize(2); $response->prepare(Request::create('/', 'GET', server: ['HTTP_RANGE' => 'bytes=5-8'])); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); $chunks = []; - $swooleResponse->shouldReceive('sendfile')->never(); - $swooleResponse->shouldReceive('write')->twice()->andReturnUsing( + $swooleResponse->expects('sendfile')->never(); + $swooleResponse->expects('write')->times(2)->resolves( static function (string $chunk) use (&$chunks): bool { $chunks[] = $chunk; return true; } ); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); + $swooleResponse->expects('end')->with()->returns(true); ResponseBridge::send($response, $swooleResponse, protocol: 'HTTP/2'); @@ -282,18 +288,18 @@ public function testTemporaryBinaryResponseUsesBoundedStreaming(): void $response = new BinaryFileResponse($file); $response->setChunkSize(4); $response->prepare(Request::create('/')); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); $chunks = []; - $swooleResponse->shouldReceive('sendfile')->never(); - $swooleResponse->shouldReceive('write')->andReturnUsing( + $swooleResponse->expects('sendfile')->never(); + $swooleResponse->allows('write')->resolves( static function (string $chunk) use (&$chunks): bool { $chunks[] = $chunk; return true; } ); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); + $swooleResponse->expects('end')->with()->returns(true); ResponseBridge::send($response, $swooleResponse); @@ -307,26 +313,26 @@ public function testDeleteAfterSendStreamsBeforeDeletingAndRemovesConflictingHea $response->setChunkSize(4); $response->deleteFileAfterSend(); $response->prepare(Request::create('/')); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status'); $headers = []; $chunks = []; - $swooleResponse->shouldReceive('header')->andReturnUsing( + $swooleResponse->allows('header')->resolves( static function (string $name, string|array $value) use (&$headers): bool { $headers[strtolower($name)] = $value; return true; } ); - $swooleResponse->shouldReceive('sendfile')->never(); - $swooleResponse->shouldReceive('write')->andReturnUsing( + $swooleResponse->expects('sendfile')->never(); + $swooleResponse->allows('write')->resolves( static function (string $chunk) use (&$chunks): bool { $chunks[] = $chunk; return true; } ); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); + $swooleResponse->expects('end')->with()->returns(true); ResponseBridge::send($response, $swooleResponse); @@ -342,10 +348,10 @@ public function testDeleteAfterSendPreservesWriteFailureAndStillEndsAndDeletes() $response = new BinaryFileResponse($path); $response->deleteFileAfterSend(); $response->prepare(Request::create('/')); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('write')->once()->andReturnFalse(); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnFalse(); + $swooleResponse->expects('write')->returns(false); + $swooleResponse->expects('end')->with()->returns(false); try { ResponseBridge::send($response, $swooleResponse); @@ -365,10 +371,10 @@ public function testDeleteAfterSendPreservesEarlyEofFailureAndStillDeletes(): vo $response->prepare(Request::create('/', 'GET', server: ['HTTP_RANGE' => 'bytes=0-11'])); file_put_contents($path, 'short'); clearstatcache(true, $path); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('write')->once()->with('short')->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); + $swooleResponse->expects('write')->with('short')->returns(true); + $swooleResponse->expects('end')->with()->returns(true); try { ResponseBridge::send($response, $swooleResponse, protocol: 'HTTP/2'); @@ -389,10 +395,10 @@ public function testDeleteAfterSendPropagatesEndFailureAfterDeleting(): void $response = new BinaryFileResponse($path); $response->deleteFileAfterSend(); $response->prepare(Request::create('/')); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('write')->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnFalse(); + $swooleResponse->allows('write')->returns(true); + $swooleResponse->expects('end')->with()->returns(false); try { ResponseBridge::send($response, $swooleResponse); @@ -412,10 +418,10 @@ public function testDeleteAfterSendPreservesStatusFailureAndStillEndsAndDeletes( $response->prepare(Request::create('/')); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->andReturnFalse(); - $swooleResponse->shouldNotReceive('header'); - $swooleResponse->shouldNotReceive('write'); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnFalse(); + $swooleResponse->expects('status')->returns(false); + $swooleResponse->expects('header')->never(); + $swooleResponse->expects('write')->never(); + $swooleResponse->expects('end')->with()->returns(false); try { ResponseBridge::send($response, $swooleResponse); @@ -433,8 +439,8 @@ public function testDeleteAfterSendPropagatesDeletionFailureAfterSuccessfulEmiss $response = new BinaryFileResponse($path); $response->deleteFileAfterSend(); $response->prepare(Request::create('/')); - $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); + $swooleResponse = $this->mockSwooleResponse('status', 'header', 'write'); + $swooleResponse->expects('end')->with()->returns(true); $exception = null; try { @@ -460,11 +466,11 @@ public function testHeadDeleteAfterSendSuppressesTheBodyAndStillDeletes(): void $response = new BinaryFileResponse($path); $response->deleteFileAfterSend(); $response->prepare($request); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldNotReceive('sendfile'); - $swooleResponse->shouldNotReceive('write'); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); + $swooleResponse->expects('sendfile')->never(); + $swooleResponse->expects('write')->never(); + $swooleResponse->expects('end')->with()->returns(true); ResponseBridge::send($response, $swooleResponse, withBody: false, request: $request); @@ -481,11 +487,11 @@ public function testDeleteAfterSendDeletesResponsesWithoutBodies(int $status): v $response = new BinaryFileResponse($path, $status); $response->deleteFileAfterSend(); $response->prepare(Request::create('/')); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldNotReceive('sendfile'); - $swooleResponse->shouldNotReceive('write'); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); + $swooleResponse->expects('sendfile')->never(); + $swooleResponse->expects('write')->never(); + $swooleResponse->expects('end')->with()->returns(true); ResponseBridge::send($response, $swooleResponse); @@ -513,12 +519,13 @@ public function testDelegatedXSendfilePreservesDeleteAfterSendSource(): void $response = new BinaryFileResponse($path); $response->deleteFileAfterSend(); $response->prepare($request); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status'); - $swooleResponse->shouldNotReceive('sendfile'); - $swooleResponse->shouldNotReceive('write'); - $swooleResponse->shouldReceive('header')->with('X-Sendfile', $path)->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); + $swooleResponse->expects('sendfile')->never(); + $swooleResponse->expects('write')->never(); + $swooleResponse->allows('header')->with(Argument::not('X-Sendfile'), Argument::any())->returns(true); + $swooleResponse->expects('header')->with('X-Sendfile', $path)->returns(true); + $swooleResponse->expects('end')->with()->returns(true); ResponseBridge::send($response, $swooleResponse, request: $request); @@ -542,12 +549,13 @@ public function testDelegatedXSendfileHeadPreservesDeleteAfterSendSource(): void $response = new BinaryFileResponse($path); $response->deleteFileAfterSend(); $response->prepare($request); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status'); - $swooleResponse->shouldNotReceive('sendfile'); - $swooleResponse->shouldNotReceive('write'); - $swooleResponse->shouldReceive('header')->with('X-LIGHTTPD-send-file', $path)->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); + $swooleResponse->expects('sendfile')->never(); + $swooleResponse->expects('write')->never(); + $swooleResponse->allows('header')->with(Argument::not('X-LIGHTTPD-send-file'), Argument::any())->returns(true); + $swooleResponse->expects('header')->with('X-LIGHTTPD-send-file', $path)->returns(true); + $swooleResponse->expects('end')->with()->returns(true); ResponseBridge::send($response, $swooleResponse, withBody: false, request: $request); @@ -566,14 +574,14 @@ public function testSendStreamedResponse(): void }); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('write')->andReturnUsing(function (string $chunk) use (&$chunks): bool { + $swooleResponse->expects('status')->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->allows('write')->resolves(function (string $chunk) use (&$chunks): bool { $chunks[] = $chunk; return true; }); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnFalse(); + $swooleResponse->expects('end')->with()->returns(false); ResponseBridge::send($response, $swooleResponse); @@ -598,10 +606,10 @@ public function testIterableStreamedResponseStopsAfterAFailedWrite(): void $response = new IterableStreamedResponse($chunks); unset($chunks); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('write')->once()->with('first')->andReturnFalse(); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnFalse(); + $swooleResponse->expects('status')->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('write')->with('first')->returns(false); + $swooleResponse->expects('end')->with()->returns(false); ResponseBridge::send($response, $swooleResponse); @@ -622,10 +630,10 @@ public function testIterableStreamedResponsePreservesWriteFailureAndStillEnds(): $response = new IterableStreamedResponse($chunks); unset($chunks); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('write')->once()->andThrow(new RuntimeException('write failed')); - $swooleResponse->shouldReceive('end')->once()->andThrow(new RuntimeException('end failed')); + $swooleResponse->expects('status')->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('write')->throws(new RuntimeException('write failed')); + $swooleResponse->expects('end')->throws(new RuntimeException('end failed')); try { ResponseBridge::send($response, $swooleResponse); @@ -646,10 +654,10 @@ public function testOrdinaryStreamedResponseStopsWritingAfterDisconnect(): void $callbackCompleted = true; }); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('write')->once()->with('first')->andReturnFalse(); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnFalse(); + $swooleResponse->expects('status')->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('write')->with('first')->returns(false); + $swooleResponse->expects('end')->with()->returns(false); ResponseBridge::send($response, $swooleResponse); @@ -662,10 +670,10 @@ public function testOrdinaryStreamedResponsePreservesWriteFailureAndStillEnds(): echo 'first'; }); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('write')->once()->andThrow(new RuntimeException('write failed')); - $swooleResponse->shouldReceive('end')->once()->andThrow(new RuntimeException('end failed')); + $swooleResponse->expects('status')->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('write')->throws(new RuntimeException('write failed')); + $swooleResponse->expects('end')->throws(new RuntimeException('end failed')); try { ResponseBridge::send($response, $swooleResponse); @@ -685,14 +693,14 @@ public function testStreamedResponseRemovesConflictingHeaders(): void $swooleResponse = $this->mockSwooleResponse(); $sentHeaders = []; - $swooleResponse->shouldReceive('status')->once()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->andReturnUsing(function (string $name, string|array $value) use (&$sentHeaders): bool { + $swooleResponse->expects('status')->returns(true); + $swooleResponse->allows('header')->resolves(function (string $name, string|array $value) use (&$sentHeaders): bool { $sentHeaders[$name] = $value; return true; }); - $swooleResponse->shouldReceive('write')->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->andReturnFalse(); + $swooleResponse->allows('write')->returns(true); + $swooleResponse->expects('end')->returns(false); ResponseBridge::send($response, $swooleResponse); @@ -708,10 +716,10 @@ public function testStreamedResponseCleansUpOutputBufferOnException(): void }); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('write')->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->andReturnFalse(); + $swooleResponse->expects('status')->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->allows('write')->returns(true); + $swooleResponse->expects('end')->returns(false); $levelBefore = ob_get_level(); @@ -733,14 +741,14 @@ public function testSendMultipleCookies(): void $swooleResponse = $this->mockSwooleResponse(); $cookieNames = []; - $swooleResponse->shouldReceive('status')->once()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('cookie')->andReturnUsing(function (string $name) use (&$cookieNames): bool { + $swooleResponse->expects('status')->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->allows('cookie')->resolves(function (string $name) use (&$cookieNames): bool { $cookieNames[] = $name; return true; }); - $swooleResponse->shouldReceive('end')->once()->andReturnTrue(); + $swooleResponse->expects('end')->returns(true); ResponseBridge::send($response, $swooleResponse); @@ -753,9 +761,9 @@ public function testSendEmptyBodyResponse(): void $response = new Response('', 204); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->with(204)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->with('')->andReturnTrue(); + $swooleResponse->expects('status')->with(204)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end')->with('')->returns(true); ResponseBridge::send($response, $swooleResponse); } @@ -778,17 +786,17 @@ function () use (&$trailerCalls): array { }, ); $response->headers->set('Content-Length', '4'); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status'); $headers = []; - $swooleResponse->shouldReceive('header')->andReturnUsing(function (string $name, string|array $value) use (&$headers): bool { + $swooleResponse->allows('header')->resolves(function (string $name, string|array $value) use (&$headers): bool { $headers[strtolower($name)] = $value; return true; }); - $swooleResponse->shouldNotReceive('write'); - $swooleResponse->shouldNotReceive('trailer'); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); + $swooleResponse->expects('write')->never(); + $swooleResponse->expects('trailer')->never(); + $swooleResponse->expects('end')->with()->returns(true); ResponseBridge::send($response, $swooleResponse, withBody: false); @@ -803,9 +811,9 @@ public function testBinaryFileResponseWithTrailersIsRejectedBeforeEmission(): vo $response = new ResponseBridgeTrailerBinaryFileResponse($this->temporaryFile()); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldNotReceive('status'); - $swooleResponse->shouldNotReceive('header'); - $swooleResponse->shouldNotReceive('sendfile'); + $swooleResponse->expects('status')->never(); + $swooleResponse->expects('header')->never(); + $swooleResponse->expects('sendfile')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Binary file responses cannot emit trailers.'); @@ -827,24 +835,24 @@ function () use (&$operations): array { ); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->andReturnUsing(function () use (&$operations): bool { + $swooleResponse->expects('status')->resolves(function () use (&$operations): bool { $operations[] = 'status'; return true; }); - $swooleResponse->shouldReceive('header')->andReturnUsing(function (string $name) use (&$operations): bool { + $swooleResponse->allows('header')->resolves(function (string $name) use (&$operations): bool { if (strtolower($name) === 'trailer') { $operations[] = 'announce'; } return true; }); - $swooleResponse->shouldReceive('trailer')->once()->with('x-final', 'value')->andReturnUsing(function () use (&$operations): bool { + $swooleResponse->expects('trailer')->with('x-final', 'value')->resolves(function () use (&$operations): bool { $operations[] = 'trailer'; return true; }); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnUsing(function () use (&$operations): bool { + $swooleResponse->expects('end')->with()->resolves(function () use (&$operations): bool { $operations[] = 'end'; return true; @@ -859,10 +867,10 @@ public function testTrailerAnnouncementMergesNormalizesAndDeduplicatesNames(): v { $response = new ResponseBridgeTrailerResponse('body', ['X-Known', 'x-new'], []); $response->headers->set('Trailer', 'X-Existing, x-known'); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'end', 'trailer'); $announcement = null; - $swooleResponse->shouldReceive('header')->andReturnUsing(function (string $name, string|array $value) use (&$announcement): bool { + $swooleResponse->allows('header')->resolves(function (string $name, string|array $value) use (&$announcement): bool { if (strtolower($name) === 'trailer') { $announcement = $value; } @@ -881,8 +889,8 @@ public function testInvalidAnnouncedTrailerNameFailsBeforeEmission(string $name, $response = new ResponseBridgeTrailerResponse('body', [$name], []); $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldNotReceive('status'); - $swooleResponse->shouldNotReceive('header'); + $swooleResponse->expects('status')->never(); + $swooleResponse->expects('header')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs($message); @@ -898,7 +906,7 @@ public function testInvalidFinalTrailerNameFailsAtTrailerBoundary(string $name, $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs($message); - ResponseBridge::send($response, $this->mockSwooleResponse()); + ResponseBridge::send($response, $this->mockSwooleResponse('status', 'header')); } public static function invalidTrailerNames(): array @@ -923,17 +931,18 @@ public function testFinalTrailerNamesMustBeUniqueAfterNormalization(): void $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Response trailer names must be unique after normalization.'); - ResponseBridge::send($response, $this->mockSwooleResponse()); + ResponseBridge::send($response, $this->mockSwooleResponse('status', 'header')); } #[DataProvider('numericOnlyFieldNames')] public function testNumericOnlyFinalTrailerNameIsEmittedAsString(string $name): void { $response = new ResponseBridgeTrailerResponse('body', [$name], [$name => 'value']); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'end'); - $swooleResponse->shouldReceive('header')->once()->with('Trailer', $name)->andReturnTrue(); - $swooleResponse->shouldReceive('trailer')->once()->with($name, 'value')->andReturnTrue(); + $swooleResponse->allows('header')->with(Argument::not('Trailer'), Argument::any())->returns(true); + $swooleResponse->expects('header')->with('Trailer', $name)->returns(true); + $swooleResponse->expects('trailer')->with($name, 'value')->returns(true); ResponseBridge::send($response, $swooleResponse); } @@ -945,7 +954,7 @@ public function testFinalTrailerValuesMustBeStrings(): void $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Response trailer values must be strings.'); - ResponseBridge::send($response, $this->mockSwooleResponse()); + ResponseBridge::send($response, $this->mockSwooleResponse('status', 'header')); } public function testFinalTrailerValuesCannotContainLineBreaks(): void @@ -955,7 +964,7 @@ public function testFinalTrailerValuesCannotContainLineBreaks(): void $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Response trailer values cannot contain line breaks.'); - ResponseBridge::send($response, $this->mockSwooleResponse()); + ResponseBridge::send($response, $this->mockSwooleResponse('status', 'header')); } #[DataProvider('trailerChunkCases')] @@ -1044,19 +1053,19 @@ function () use (&$operations): array { return ['x-status' => 'ok']; }, ); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('write')->once()->with('one')->andReturnUsing(function () use (&$operations): bool { + $swooleResponse->expects('write')->with('one')->resolves(function () use (&$operations): bool { $operations[] = 'write-one'; return true; }); - $swooleResponse->shouldReceive('trailer')->once()->andReturnUsing(function () use (&$operations): bool { + $swooleResponse->expects('trailer')->resolves(function () use (&$operations): bool { $operations[] = 'trailer'; return true; }); - $swooleResponse->shouldReceive('end')->once()->with('two')->andReturnUsing(function () use (&$operations): bool { + $swooleResponse->expects('end')->with('two')->resolves(function () use (&$operations): bool { $operations[] = 'end-two'; return true; @@ -1095,11 +1104,11 @@ public function testTrailerIterableWriteFailureStopsProducerWithoutTrailersOrEnd ['x-status'], ['x-status' => 'ok'], ); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('write')->once()->with('one')->andReturnFalse(); - $swooleResponse->shouldNotReceive('trailer'); - $swooleResponse->shouldNotReceive('end'); + $swooleResponse->expects('write')->with('one')->returns(false); + $swooleResponse->expects('trailer')->never(); + $swooleResponse->expects('end')->never(); try { ResponseBridge::send($response, $swooleResponse); @@ -1128,11 +1137,11 @@ public function testTrailerIterableWriteExceptionStopsProducerWithoutTrailersOrE ['x-status'], ['x-status' => 'ok'], ); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('write')->once()->with('one')->andThrow($writeFailure); - $swooleResponse->shouldNotReceive('trailer'); - $swooleResponse->shouldNotReceive('end'); + $swooleResponse->expects('write')->with('one')->throws($writeFailure); + $swooleResponse->expects('trailer')->never(); + $swooleResponse->expects('end')->never(); try { ResponseBridge::send($response, $swooleResponse); @@ -1155,11 +1164,11 @@ static function (): void { ['x-status'], ['x-status' => 'ok'], ); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('write')->once()->with('rejected')->andReturnFalse(); - $swooleResponse->shouldNotReceive('trailer'); - $swooleResponse->shouldNotReceive('end'); + $swooleResponse->expects('write')->with('rejected')->returns(false); + $swooleResponse->expects('trailer')->never(); + $swooleResponse->expects('end')->never(); ob_start(); @@ -1187,9 +1196,9 @@ function () use ($producerFailure): void { ['x-status'], ['x-status' => 'ok'], ); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('write')->once()->andReturnFalse(); + $swooleResponse->expects('write')->returns(false); try { ResponseBridge::send($response, $swooleResponse); @@ -1212,9 +1221,9 @@ static function (): void { ['x-status'], ['x-status' => 'ok'], ); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('write')->once()->andThrow($writeFailure); + $swooleResponse->expects('write')->throws($writeFailure); try { ResponseBridge::send($response, $swooleResponse); @@ -1228,8 +1237,8 @@ public function testStatusFailureThrowsBeforeHeaders(): void { $swooleResponse = $this->mockSwooleResponse(); - $swooleResponse->shouldReceive('status')->once()->andReturnFalse(); - $swooleResponse->shouldNotReceive('header'); + $swooleResponse->expects('status')->returns(false); + $swooleResponse->expects('header')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to set the response status.'); @@ -1253,12 +1262,12 @@ public function testDisconnectCancelsAllActiveStreamsOnOnlyThatConnection(bool $ $closed[] = $producer; } })()); - $native = $this->mockSwooleResponse(); + $native = $this->mockSwooleResponse('status', 'header', 'end', 'write'); $native->fd = $connection; if ($cancel) { $response->cancelOnDisconnect(); - $native->expects('isWritable')->andReturnTrue(); + $native->expects('isWritable')->returns(true); } try { @@ -1319,9 +1328,9 @@ public function testDisconnectAfterProductionDoesNotCancelLaterRequestWork(): vo $results = parallel([ 'producer' => function () use ($sent, $continue): mixed { $response = (new IterableStreamedResponse(['body']))->cancelOnDisconnect(); - $native = $this->mockSwooleResponse(); + $native = $this->mockSwooleResponse('status', 'header', 'end', 'write'); $native->fd = 10; - $native->expects('isWritable')->andReturnTrue(); + $native->expects('isWritable')->returns(true); ResponseBridge::send($response, $native); $sent->push(true); @@ -1349,9 +1358,9 @@ public function testAlreadyDisconnectedClientDoesNotStartAnOptedInProducer(): vo $started = true; yield 'body'; })()))->cancelOnDisconnect(); - $native = $this->mockSwooleResponse(); - $native->expects('isWritable')->andReturnFalse(); - $native->shouldNotReceive('write'); + $native = $this->mockSwooleResponse('status', 'header', 'end'); + $native->expects('isWritable')->returns(false); + $native->expects('write')->never(); try { ResponseBridge::send($response, $native); @@ -1363,10 +1372,11 @@ public function testAlreadyDisconnectedClientDoesNotStartAnOptedInProducer(): vo public function testHeaderFailureThrowsBeforeBody(): void { - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status'); - $swooleResponse->shouldReceive('header')->with('X-Fail', 'value')->andReturnFalse(); - $swooleResponse->shouldNotReceive('end'); + $swooleResponse->allows('header')->with(Argument::not('X-Fail'), Argument::any())->returns(true); + $swooleResponse->allows('header')->with('X-Fail', 'value')->returns(false); + $swooleResponse->expects('end')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to set a response header.'); @@ -1378,10 +1388,10 @@ public function testCookieFailureThrowsBeforeBody(): void { $response = new Response('body'); $response->headers->setCookie(Cookie::create('failed', 'value')); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('cookie')->once()->andReturnFalse(); - $swooleResponse->shouldNotReceive('end'); + $swooleResponse->expects('cookie')->returns(false); + $swooleResponse->expects('end')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to set a response cookie.'); @@ -1392,10 +1402,10 @@ public function testCookieFailureThrowsBeforeBody(): void public function testTrailerFailureThrowsBeforeEnd(): void { $response = new ResponseBridgeTrailerResponse('body', ['x-value'], ['x-value' => 'value']); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('trailer')->once()->andReturnFalse(); - $swooleResponse->shouldNotReceive('end'); + $swooleResponse->expects('trailer')->returns(false); + $swooleResponse->expects('end')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to set a response trailer.'); @@ -1405,9 +1415,9 @@ public function testTrailerFailureThrowsBeforeEnd(): void public function testFixedResponseEndFailureThrows(): void { - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('end')->once()->andReturnFalse(); + $swooleResponse->expects('end')->returns(false); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to complete the response.'); @@ -1417,9 +1427,9 @@ public function testFixedResponseEndFailureThrows(): void public function testHeadResponseEndFailureThrows(): void { - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnFalse(); + $swooleResponse->expects('end')->with()->returns(false); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to complete the response.'); @@ -1430,9 +1440,9 @@ public function testHeadResponseEndFailureThrows(): void public function testTrailerResponseEndFailureThrows(): void { $response = new ResponseBridgeTrailerResponse('body', ['x-value'], ['x-value' => 'value']); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header', 'trailer'); - $swooleResponse->shouldReceive('end')->once()->with('body')->andReturnFalse(); + $swooleResponse->expects('end')->with('body')->returns(false); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to complete the response.'); @@ -1443,9 +1453,9 @@ public function testTrailerResponseEndFailureThrows(): void public function testSendFileFailureThrows(): void { $path = $this->temporaryFile(); - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status', 'header'); - $swooleResponse->shouldReceive('sendfile')->once()->with($path, 0, 0)->andReturnFalse(); + $swooleResponse->expects('sendfile')->with($path, 0, 0)->returns(false); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to send the response file.'); @@ -1453,19 +1463,18 @@ public function testSendFileFailureThrows(): void ResponseBridge::send(new BinaryFileResponse($path), $swooleResponse); } - private function mockSwooleResponse(): SwooleResponse + /** + * Create a strict response double with only incidental successful operations stubbed. + */ + private function mockSwooleResponse(string ...$successfulMethods): SwooleResponse&DoubleInterface { - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->byDefault()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->byDefault()->andReturnTrue(); - $swooleResponse->shouldReceive('cookie')->byDefault()->andReturnTrue(); - $swooleResponse->shouldReceive('rawcookie')->byDefault()->andReturnTrue(); - $swooleResponse->shouldReceive('write')->byDefault()->andReturnTrue(); - $swooleResponse->shouldReceive('trailer')->byDefault()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->byDefault()->andReturnTrue(); - $swooleResponse->shouldReceive('sendfile')->byDefault()->andReturnTrue(); + $response = Double::for(SwooleResponse::class)->strict(); + + foreach ($successfulMethods as $method) { + $response->allows($method)->returns(true); + } - return $swooleResponse; + return $response; } private function temporaryFile(): string @@ -1483,30 +1492,30 @@ private function temporaryFile(): string */ private function sendTrailerStream(Response $response): array { - $swooleResponse = $this->mockSwooleResponse(); + $swooleResponse = $this->mockSwooleResponse('status'); $writes = []; $endContent = null; $announcement = null; $trailers = []; - $swooleResponse->shouldReceive('header')->andReturnUsing(function (string $name, string|array $value) use (&$announcement): bool { + $swooleResponse->allows('header')->resolves(function (string $name, string|array $value) use (&$announcement): bool { if (strtolower($name) === 'trailer') { $announcement = $value; } return true; }); - $swooleResponse->shouldReceive('write')->andReturnUsing(function (string $chunk) use (&$writes): bool { + $swooleResponse->allows('write')->resolves(function (string $chunk) use (&$writes): bool { $writes[] = $chunk; return true; }); - $swooleResponse->shouldReceive('trailer')->andReturnUsing(function (string $name, string $value) use (&$trailers): bool { + $swooleResponse->allows('trailer')->resolves(function (string $name, string $value) use (&$trailers): bool { $trailers[$name] = $value; return true; }); - $swooleResponse->shouldReceive('end')->once()->andReturnUsing(function (...$arguments) use (&$endContent): bool { + $swooleResponse->expects('end')->resolves(function (...$arguments) use (&$endContent): bool { $endContent = $arguments[0] ?? null; return true; diff --git a/tests/HttpServer/ServerTest.php b/tests/HttpServer/ServerTest.php index 1d975f14ff..11098c9fea 100644 --- a/tests/HttpServer/ServerTest.php +++ b/tests/HttpServer/ServerTest.php @@ -26,8 +26,10 @@ use Hypervel\Routing\Router; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use ReflectionProperty; @@ -43,6 +45,8 @@ class ServerTest extends TestCase { + use VerifiesDoubles; + protected string $tempDirectory; protected function setUp(): void @@ -64,18 +68,18 @@ protected function tearDown(): void public function testBootstrapForServerResolvesKernelAndBootstraps(): void { - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('bootstrap')->once(); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('bootstrap'); - $router = m::mock(Router::class); - $router->shouldReceive('compileAndWarm')->once(); + $router = Double::for(Router::class)->strict(); + $router->expects('compileAndWarm'); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); - $container->shouldReceive('make')->with(KernelContract::class)->andReturn($kernel); - $container->shouldReceive('make')->with('router')->andReturn($router); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(false); + $container->allows('make')->with(KernelContract::class)->returns($kernel); + $container->allows('make')->with('router')->returns($router); - $server = new Server($container); + $server = new Server($container->instance()); $server->bootstrapForServer('http'); $this->assertSame('http', $server->getServerName()); @@ -85,24 +89,23 @@ public function testOnRequestDelegatestoKernelAndSendsResponse(): void { CoordinatorManager::until(Constants::WORKER_START)->resume(); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle') - ->once() - ->with(m::type(Request::class)) - ->andReturn(new Response('Hello World', 200)); - $kernel->shouldReceive('terminate')->once(); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle') + ->with(Argument::type(Request::class)) + ->returns(new Response('Hello World', 200)); + $kernel->expects('terminate'); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(false); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); $swooleRequest = $this->createSwooleRequest(); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->once()->with(200)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->with('Hello World')->andReturnTrue(); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->with(200)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end')->with('Hello World')->returns(true); $server->onRequest($swooleRequest, $swooleResponse); } @@ -111,23 +114,23 @@ public function testOnRequestWaitsForWorkerStartOnlyOnce(): void { CoordinatorManager::until(Constants::WORKER_START)->resume(); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle') - ->twice() - ->with(m::type(Request::class)) - ->andReturn(new Response('OK')); - $kernel->shouldReceive('terminate')->twice(); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle') + ->times(2) + ->with(Argument::type(Request::class)) + ->returns(new Response('OK')); + $kernel->expects('terminate')->times(2); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(false); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->twice()->with(200)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->twice()->with('OK')->andReturnTrue(); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->times(2)->with(200)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end')->times(2)->with('OK')->returns(true); wait(fn () => $server->onRequest($this->createSwooleRequest(), $swooleResponse)); @@ -141,28 +144,19 @@ public function testOnRequestWaitsForWorkerStartOnlyOnce(): void public function testOnRequestRetriesWorkerStartAfterNonThrowingCancellation(): void { - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle') - ->once() - ->with(m::type(Request::class)) - ->andReturn(new Response('OK')); - $kernel->shouldReceive('terminate')->once(); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle') + ->with(Argument::type(Request::class)) + ->returns(new Response('OK')); + $kernel->expects('terminate'); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(false); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); - $responseEmittedForCanceledRequest = false; - $canceledResponse = m::mock(SwooleResponse::class); - $canceledResponse->shouldReceive('status', 'header', 'end') - ->zeroOrMoreTimes() - ->andReturnUsing(function () use (&$responseEmittedForCanceledRequest): bool { - $responseEmittedForCanceledRequest = true; - - return true; - }); + $canceledResponse = Double::for(SwooleResponse::class)->strict(); $cancellation = null; $canceledRequest = EngineCoroutine::create(function () use ($server, $canceledResponse, &$cancellation): void { @@ -176,13 +170,13 @@ public function testOnRequestRetriesWorkerStartAfterNonThrowingCancellation(): v $this->assertTrue(EngineCoroutine::cancelById($canceledRequest->getId())); $this->assertInstanceOf(CanceledException::class, $cancellation); $this->assertSame('Waiting for the HTTP worker to start was canceled.', $cancellation->getMessage()); - $this->assertFalse($responseEmittedForCanceledRequest); + $canceledResponse->unused(); $handled = false; - $response = m::mock(SwooleResponse::class); - $response->shouldReceive('status')->once()->with(200)->andReturnTrue(); - $response->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $response->shouldReceive('end')->once()->with('OK')->andReturnTrue(); + $response = Double::for(SwooleResponse::class)->strict(); + $response->expects('status')->with(200)->returns(true); + $response->allows('header')->returns(true); + $response->expects('end')->with('OK')->returns(true); EngineCoroutine::create(function () use ($server, $response, &$handled): void { $server->onRequest($this->createSwooleRequest(), $response); @@ -206,16 +200,15 @@ public function testOnRequestKeepsRequestInContextThroughDeferredTermination(): $handlingCoroutineId = null; $terminationCoroutineId = null; - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle') - ->once() - ->andReturnUsing(function (Request $request) use (&$capturedRequest, &$handlingCoroutineId): Response { + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle') + ->resolves(function (Request $request) use (&$capturedRequest, &$handlingCoroutineId): Response { $capturedRequest = RequestContext::get(); $handlingCoroutineId = EngineCoroutine::id(); return new Response('OK'); }); - $kernel->shouldReceive('terminate')->once(); + $kernel->expects('terminate'); $events = new Dispatcher; $events->listen(RequestTerminated::class, function (RequestTerminated $event) use (&$terminatedRequest, &$eventRequest, &$terminationCoroutineId): void { @@ -224,19 +217,19 @@ public function testOnRequestKeepsRequestInContextThroughDeferredTermination(): $terminationCoroutineId = EngineCoroutine::id(); }); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($events); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($events); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); $this->setServerName($server, 'http'); $swooleRequest = $this->createSwooleRequest(); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->withAnyArgs()->andReturnTrue(); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->allows('status')->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->allows('end')->returns(true); wait(fn () => $server->onRequest($swooleRequest, $swooleResponse)); @@ -252,11 +245,10 @@ public function testOnRequestReturns500OnKernelException(): void CoordinatorManager::until(Constants::WORKER_START)->resume(); $failure = new RuntimeException('Fatal error'); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle') - ->once() - ->andThrow($failure); - $kernel->shouldReceive('terminate')->once(); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle') + ->throws($failure); + $kernel->expects('terminate'); $handledEvent = null; $events = new Dispatcher; @@ -264,19 +256,19 @@ public function testOnRequestReturns500OnKernelException(): void $handledEvent = $event; }); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($events); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($events); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); $this->setServerName($server, 'http'); $swooleRequest = $this->createSwooleRequest(); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->once()->with(500)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->with('Internal Server Error')->andReturnTrue(); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->with(500)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end')->with('Internal Server Error')->returns(true); try { $server->onRequest($swooleRequest, $swooleResponse); @@ -303,14 +295,13 @@ public function testOnRequestPreservesOperationFailureAcrossExhaustiveFinalizati $handler->expects('report')->with($sendFailure)->ordered(); $handler->expects('report')->with($terminateFailure)->ordered(); - $kernel = m::mock(KernelContract::class); - $kernel->shouldNotReceive('handle'); - $kernel->shouldReceive('terminate') - ->once() - ->with(m::type(Request::class), m::on( + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle')->never(); + $kernel->expects('terminate') + ->with(Argument::type(Request::class), Argument::satisfies( fn (Response $response): bool => $response->getStatusCode() === 500 )) - ->andThrow($terminateFailure); + ->throws($terminateFailure); $terminatedEvent = null; $events = new Dispatcher; @@ -320,18 +311,18 @@ public function testOnRequestPreservesOperationFailureAcrossExhaustiveFinalizati $terminatedEvent = $event; }); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($events); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($events); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); $this->setServerName($server, 'http'); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->once()->with(500)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->with('Internal Server Error')->andThrow($sendFailure); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->with(500)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end')->with('Internal Server Error')->throws($sendFailure); try { wait(fn () => $server->onRequest($this->createSwooleRequest(), $swooleResponse)); @@ -355,9 +346,9 @@ public function testOnRequestFinalizationIsExhaustiveAndPreservesTheFirstFailure $handler = $this->bindReportingHandler(); $handler->expects('report')->with($sendFailure)->ordered(); $handler->expects('report')->with($terminateFailure)->ordered(); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle')->once()->andReturn(new Response('OK')); - $kernel->shouldReceive('terminate')->once()->andThrow($terminateFailure); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle')->returns(new Response('OK')); + $kernel->expects('terminate')->throws($terminateFailure); $terminatedEvent = null; $events = new Dispatcher; @@ -366,18 +357,18 @@ public function testOnRequestFinalizationIsExhaustiveAndPreservesTheFirstFailure $terminatedEvent = $event; }); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($events); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($events); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); $this->setServerName($server, 'http'); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->once()->with(200)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->with('OK')->andThrow($sendFailure); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->with(200)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end')->with('OK')->throws($sendFailure); try { wait(fn () => $server->onRequest($this->createSwooleRequest(), $swooleResponse)); @@ -397,9 +388,9 @@ public function testRequestTerminatedObservesSendFailureBeforeLaterTerminationFa $terminateFailure = new RuntimeException('terminate failed'); $this->bindReportingHandler()->expects('report')->with($terminateFailure); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle')->once()->andReturn(new Response('OK')); - $kernel->shouldReceive('terminate')->once()->andThrow($terminateFailure); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle')->returns(new Response('OK')); + $kernel->expects('terminate')->throws($terminateFailure); $sentEvent = null; $terminatedEvent = null; @@ -411,18 +402,18 @@ public function testRequestTerminatedObservesSendFailureBeforeLaterTerminationFa $terminatedEvent = $event; }); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($events); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($events); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); $this->setServerName($server, 'http'); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->once()->with(200)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->with('OK')->andThrow($sendFailure); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->with(200)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end')->with('OK')->throws($sendFailure); try { wait(fn () => $server->onRequest($this->createSwooleRequest(), $swooleResponse)); @@ -442,9 +433,9 @@ public function testRequestTerminatedObservesTerminationFailure(): void CoordinatorManager::until(Constants::WORKER_START)->resume(); $terminateFailure = new RuntimeException('terminate failed'); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle')->once()->andReturn(new Response('OK')); - $kernel->shouldReceive('terminate')->once()->andThrow($terminateFailure); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle')->returns(new Response('OK')); + $kernel->expects('terminate')->throws($terminateFailure); $terminatedEvent = null; $events = new Dispatcher; @@ -452,18 +443,18 @@ public function testRequestTerminatedObservesTerminationFailure(): void $terminatedEvent = $event; }); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($events); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($events); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); $this->setServerName($server, 'http'); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->once()->with(200)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->with('OK')->andReturnTrue(); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->with(200)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end')->with('OK')->returns(true); try { wait(fn () => $server->onRequest($this->createSwooleRequest(), $swooleResponse)); @@ -480,24 +471,23 @@ public function testOnRequestSuppressesBodyForHeadRequests(): void { CoordinatorManager::until(Constants::WORKER_START)->resume(); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle') - ->once() - ->andReturn(new Response('This should not be sent', 200)); - $kernel->shouldReceive('terminate')->once(); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle') + ->returns(new Response('This should not be sent', 200)); + $kernel->expects('terminate'); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(false); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); $swooleRequest = $this->createSwooleRequest(method: 'head'); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->once()->with(200)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->with(200)->returns(true); + $swooleResponse->allows('header')->returns(true); // end() with no args — body suppressed for HEAD - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); + $swooleResponse->expects('end')->with()->returns(true); $server->onRequest($swooleRequest, $swooleResponse); } @@ -508,22 +498,22 @@ public function testOnRequestForwardsHttp2ProtocolToBinaryResponseEmission(): vo $path = $this->tempDirectory . '/http2-response.txt'; file_put_contents($path, 'HTTP/2 body'); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle')->once()->andReturn(new BinaryFileResponse($path)); - $kernel->shouldReceive('terminate')->once(); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle')->returns(new BinaryFileResponse($path)); + $kernel->expects('terminate'); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(false); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->once()->with(200)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('write')->once()->with('HTTP/2 body')->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->withNoArgs()->andReturnTrue(); - $swooleResponse->shouldNotReceive('sendfile'); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->with(200)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('write')->with('HTTP/2 body')->returns(true); + $swooleResponse->expects('end')->with()->returns(true); + $swooleResponse->expects('sendfile')->never(); $server->onRequest( $this->createSwooleRequest(protocol: 'HTTP/2'), @@ -537,10 +527,10 @@ public function testOnRequestDispatchesLifecycleEventsWhenListenersAreRegistered $response = new Response('OK'); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle')->andReturn($response); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->allows('handle')->returns($response); $order = []; - $kernel->shouldReceive('terminate')->andReturnUsing(function () use (&$order): void { + $kernel->allows('terminate')->resolves(function () use (&$order): void { $order[] = 'terminate'; }); @@ -553,19 +543,19 @@ public function testOnRequestDispatchesLifecycleEventsWhenListenersAreRegistered }); } - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($events); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($events); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); $this->setServerName($server, 'http'); $swooleRequest = $this->createSwooleRequest(); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->withAnyArgs()->andReturnTrue(); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->allows('status')->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->allows('end')->returns(true); wait(fn () => $server->onRequest($swooleRequest, $swooleResponse)); @@ -596,9 +586,9 @@ public function testOnRequestSkipsFallbackEmissionAndTerminationAfterCancellatio $cancellation = new RuntimeException('cleanup failed', previous: $cancellation); } - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle')->once()->andThrow($cancellation); - $kernel->shouldNotReceive('terminate'); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle')->throws($cancellation); + $kernel->expects('terminate')->never(); $dispatchedEvents = []; $events = new Dispatcher; @@ -608,16 +598,18 @@ public function testOnRequestSkipsFallbackEmissionAndTerminationAfterCancellatio }); } - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($events); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($events); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); $this->setServerName($server, 'http'); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status', 'header', 'cookie', 'rawcookie', 'write', 'sendfile', 'end')->never(); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + foreach (['status', 'header', 'cookie', 'rawcookie', 'write', 'sendfile', 'end'] as $method) { + $swooleResponse->expects($method)->never(); + } $caughtCancellation = null; $completed = new Channel(1); @@ -666,11 +658,11 @@ public function testOnRequestStopsAtCancellationDuringFinalization( $order = []; - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle')->once()->andReturn(new Response('OK')); - $kernel->shouldReceive('terminate') + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle')->returns(new Response('OK')); + $kernel->expects('terminate') ->times($stage === 'terminate' ? 1 : 0) - ->andReturnUsing(function () use ($stage, &$order, $cancellation): void { + ->resolves(function () use ($stage, &$order, $cancellation): void { $order[] = 'terminate'; if ($stage === 'terminate') { @@ -702,25 +694,26 @@ public function testOnRequestStopsAtCancellationDuringFinalization( $canceled = $event; }); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($events); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($events); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); $this->setServerName($server, 'http'); - $swooleResponse = m::mock(SwooleResponse::class); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); if ($stage === 'handled') { - $swooleResponse->shouldReceive('status', 'header', 'cookie', 'rawcookie', 'write', 'sendfile', 'end')->never(); + foreach (['status', 'header', 'cookie', 'rawcookie', 'write', 'sendfile', 'end'] as $method) { + $swooleResponse->expects($method)->never(); + } } else { - $swooleResponse->shouldReceive('status')->once()->with(200)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end') - ->once() + $swooleResponse->expects('status')->with(200)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end') ->with('OK') - ->andReturnUsing(function () use ($stage, $cancellation): bool { + ->resolves(function () use ($stage, $cancellation): bool { if ($stage === 'send') { throw $cancellation; } @@ -768,9 +761,9 @@ public function testCancellationReportsTheHeldFailureAndCanceledListenerFailures $handler->expects('report')->with($listenerFailure)->ordered(); $handler->expects('report')->with($heldFailure)->ordered(); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle')->once()->andReturn(new Response('OK')); - $kernel->shouldNotReceive('terminate'); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle')->returns(new Response('OK')); + $kernel->expects('terminate')->never(); $events = new Dispatcher; $events->listen(RequestHandled::class, static fn () => throw $heldFailure); @@ -782,18 +775,18 @@ public function testCancellationReportsTheHeldFailureAndCanceledListenerFailures throw $listenerFailure; }); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($events); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($events); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); $this->setServerName($server, 'http'); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->once()->with(200)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->with('OK')->andReturnTrue(); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->with(200)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end')->with('OK')->returns(true); try { $server->onRequest($this->createSwooleRequest(), $swooleResponse); @@ -810,39 +803,39 @@ public function testOnRequestSkipsLifecycleEventDispatchWhenNoListenersAreRegist { CoordinatorManager::until(Constants::WORKER_START)->resume(); - $eventDispatcher = m::mock(EventDispatcherContract::class); - $eventDispatcher->shouldReceive('hasListeners')->once()->with(RequestReceived::class)->andReturn(false); - $eventDispatcher->shouldReceive('hasListeners')->once()->with(RequestTerminated::class)->andReturn(false); - $eventDispatcher->shouldReceive('hasListeners')->once()->with(RequestHandled::class)->andReturn(false); - $eventDispatcher->shouldReceive('hasListeners')->once()->with(ResponseSent::class)->andReturn(false); - $eventDispatcher->shouldNotReceive('dispatch'); + $eventDispatcher = Double::for(EventDispatcherContract::class)->strict(); + $eventDispatcher->expects('hasListeners')->with(RequestReceived::class)->returns(false); + $eventDispatcher->expects('hasListeners')->with(RequestTerminated::class)->returns(false); + $eventDispatcher->expects('hasListeners')->with(RequestHandled::class)->returns(false); + $eventDispatcher->expects('hasListeners')->with(ResponseSent::class)->returns(false); + $eventDispatcher->expects('dispatch')->never(); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle')->andReturn(new Response('OK')); - $kernel->shouldReceive('terminate'); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->allows('handle')->returns(new Response('OK')); + $kernel->allows('terminate'); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($eventDispatcher); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($eventDispatcher); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); $swooleRequest = $this->createSwooleRequest(); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->withAnyArgs()->andReturnTrue(); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->allows('status')->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->allows('end')->returns(true); $server->onRequest($swooleRequest, $swooleResponse); } public function testSetAndGetServerName(): void { - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(false); - $server = new Server($container); + $server = new Server($container->instance()); $result = $server->setServerName('custom'); $this->assertSame($server, $result); @@ -851,14 +844,14 @@ public function testSetAndGetServerName(): void public function testConstructorResolvesEventDispatcherWhenAvailable(): void { - $eventDispatcher = m::mock(EventDispatcherContract::class); + $eventDispatcher = Double::for(EventDispatcherContract::class)->strict(); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($eventDispatcher); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($eventDispatcher); // Should not throw — event dispatcher is resolved - $server = new Server($container); + $server = new Server($container->instance()); $this->assertInstanceOf(Server::class, $server); } @@ -873,26 +866,25 @@ public function testOnRequestHandlesMalformedMethodOverrideAfterOverrideEnabled( Request::enableHttpMethodParameterOverride(); try { - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('handle') - ->once() - ->andReturn(new Response('Bad Request', 400)); - $kernel->shouldReceive('terminate')->once(); + $kernel = Double::for(KernelContract::class)->strict(); + $kernel->expects('handle') + ->returns(new Response('Bad Request', 400)); + $kernel->expects('terminate'); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(false); - $server = new Server($container); + $server = new Server($container->instance()); $this->setKernel($server, $kernel); // Raw POST with malicious _method override — should not throw before kernel $swooleRequest = $this->createSwooleRequest(method: 'post'); $swooleRequest->post = ['_method' => '__construct']; - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->once()->with(400)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $swooleResponse->shouldReceive('end')->once()->andReturnTrue(); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->with(400)->returns(true); + $swooleResponse->allows('header')->returns(true); + $swooleResponse->expects('end')->returns(true); // Should not throw SuspiciousOperationException — the raw method // decision uses $swooleRequest->server['request_method'], not @@ -905,11 +897,11 @@ public function testOnRequestHandlesMalformedMethodOverrideAfterOverrideEnabled( public function testConstructorSkipsEventDispatcherWhenNotAvailable(): void { - $container = m::mock(Container::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); - $container->shouldNotReceive('make')->with('events'); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(false); + $container->expects('make')->never()->with('events'); - $server = new Server($container); + $server = new Server($container->instance()); $this->assertInstanceOf(Server::class, $server); } @@ -921,7 +913,7 @@ private function createSwooleRequest( string $uri = '/', string $protocol = 'HTTP/1.1', ): SwooleRequest { - $swooleRequest = m::mock(SwooleRequest::class); + $swooleRequest = Double::for(SwooleRequest::class)->strict(); $swooleRequest->server = [ 'request_method' => $method, 'request_uri' => $uri, @@ -932,7 +924,7 @@ private function createSwooleRequest( $swooleRequest->post = null; $swooleRequest->cookie = null; $swooleRequest->files = null; - $swooleRequest->shouldReceive('rawContent')->andReturn(false); + $swooleRequest->allows('rawContent')->returns(false); return $swooleRequest; } @@ -940,11 +932,11 @@ private function createSwooleRequest( /** * Bind a mocked exception handler for displaced failure reports. */ - private function bindReportingHandler(): MockInterface + private function bindReportingHandler(): ExceptionHandler&DoubleInterface { $container = new BaseContainer; BaseContainer::setInstance($container); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $container->instance(ExceptionHandler::class, $handler); return $handler; diff --git a/tests/Image/Drivers/InterventionDriverTest.php b/tests/Image/Drivers/InterventionDriverTest.php index 50203334b1..1a2d2f6da8 100644 --- a/tests/Image/Drivers/InterventionDriverTest.php +++ b/tests/Image/Drivers/InterventionDriverTest.php @@ -10,11 +10,14 @@ use Hypervel\Image\ImageException; use Hypervel\Tests\TestCase; use Intervention\Image\Interfaces\ImageManagerInterface; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class InterventionDriverTest extends TestCase { + use VerifiesDoubles; + public function testRequirementsAreCheckedBeforeManagerCreation(): void { $managerCreated = false; @@ -33,7 +36,7 @@ public function testRequirementsAreCheckedBeforeManagerCreation(): void public function testTransformationHandlersPersistOnTheDriver(): void { - $driver = new InspectableInterventionDriver(m::mock(ImageManagerInterface::class)); + $driver = new InspectableInterventionDriver(Double::for(ImageManagerInterface::class)->strict()); $callback = static function (): void { }; diff --git a/tests/Image/ImageTest.php b/tests/Image/ImageTest.php index df72ebabe2..2f93a81038 100644 --- a/tests/Image/ImageTest.php +++ b/tests/Image/ImageTest.php @@ -36,7 +36,9 @@ use Imagick; use ImagickException; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RequiresPhpExtension; use ReflectionProperty; @@ -47,6 +49,8 @@ class ImageTest extends TestCase { + use VerifiesDoubles; + public function testCoverReturnsNewInstance(): void { $image = $this->makeImage(); @@ -452,8 +456,8 @@ public function testDimensionsDefersToTheDriverForJxlImages(): void { // A JXL signature is recognized by fileinfo but cannot be read by getimagesizefromstring(). $contents = "\xff\x0a\x00\x00"; - $driver = m::mock(Driver::class); - $driver->expects('dimensions')->once()->with($contents)->andReturn([123, 45]); + $driver = Double::for(Driver::class)->strict(); + $driver->expects('dimensions')->with($contents)->returns([123, 45]); $this->registerDrivers(['fake' => $driver]); $image = (new Image($contents))->using('fake'); @@ -466,11 +470,10 @@ public function testDimensionsDefersToTheDriverForJxlImages(): void public function testDimensionsPreservesDriverFailureForHeic(): void { $driverException = new ImageException('The driver cannot decode this image.'); - $driver = m::mock(Driver::class); + $driver = Double::for(Driver::class)->strict(); $driver->expects('process') - ->once() - ->andReturn("\x00\x00\x00\x18ftypheic\x00\x00\x00\x00mif1heic"); - $driver->expects('dimensions')->once()->andThrow($driverException); + ->returns("\x00\x00\x00\x18ftypheic\x00\x00\x00\x00mif1heic"); + $driver->expects('dimensions')->throws($driverException); $this->registerDrivers(['fake' => $driver]); try { @@ -502,9 +505,9 @@ public function testDimensionsDoesNotRelabelUnsupportedDriverForHeic(): void public function testDimensionsDoesNotMaskDriverTypeErrorsForHeic(): void { $contents = "\x00\x00\x00\x18ftypheic\x00\x00\x00\x00mif1heic"; - $driver = m::mock(Driver::class); - $driver->expects('process')->once()->andReturn($contents); - $driver->expects('dimensions')->once()->andThrow(new TypeError('broken dimensions')); + $driver = Double::for(Driver::class)->strict(); + $driver->expects('process')->returns($contents); + $driver->expects('dimensions')->throws(new TypeError('broken dimensions')); $this->registerDrivers(['fake' => $driver]); $this->expectExceptionObject(new TypeError('broken dimensions')); @@ -516,8 +519,8 @@ public function testDimensionsPreservesDriverCancellationForHeic(): void { $contents = "\x00\x00\x00\x18ftypheic\x00\x00\x00\x00mif1heic"; $cancellation = new CanceledException('Inspecting the image was canceled.'); - $driver = m::mock(Driver::class); - $driver->expects('dimensions')->once()->with($contents)->andThrow($cancellation); + $driver = Double::for(Driver::class)->strict(); + $driver->expects('dimensions')->with($contents)->throws($cancellation); $this->registerDrivers(['fake' => $driver]); try { @@ -530,15 +533,13 @@ public function testDimensionsPreservesDriverCancellationForHeic(): void public function testDominantColorReusesProcessedBytes(): void { - $driver = m::mock(Driver::class); + $driver = Double::for(Driver::class)->strict(); $driver->expects('process') - ->once() - ->with('source image', m::type(ImagePipeline::class)) - ->andReturn('processed image'); + ->with('source image', Argument::type(ImagePipeline::class)) + ->returns('processed image'); $driver->expects('dominantColor') - ->once() ->with('processed image') - ->andReturn('#123456'); + ->returns('#123456'); $this->registerDrivers(['fake' => $driver]); $image = (new Image('source image'))->using('fake')->blur(); @@ -948,8 +949,8 @@ public function testWrappedExceptionPreservesOriginal(): void public function testProcessingDoesNotMaskDriverTypeErrors(): void { - $driver = m::mock(Driver::class); - $driver->expects('process')->once()->andThrow(new TypeError('broken process')); + $driver = Double::for(Driver::class)->strict(); + $driver->expects('process')->throws(new TypeError('broken process')); $this->registerDrivers(['fake' => $driver]); $this->expectExceptionObject(new TypeError('broken process')); @@ -969,11 +970,10 @@ public function testToBytesReturnsSameResultOnMultipleCalls(): void public function testToBytesProcessesARecipeOnlyOnce(): void { - $driver = m::mock(Driver::class); + $driver = Double::for(Driver::class)->strict(); $driver->expects('process') - ->once() - ->with('source image', m::type(ImagePipeline::class)) - ->andReturn('processed image'); + ->with('source image', Argument::type(ImagePipeline::class)) + ->returns('processed image'); $this->registerDrivers(['fake' => $driver]); $image = (new Image('source image'))->using('fake')->blur(); @@ -1021,9 +1021,9 @@ public function testHashNameIsConsistentOnSameInstance(): void public function testInstanceMetadataIsCachedAndInvalidatedOnClones(): void { $contents = $this->fakeImageContents(300, 200); - $driver = m::mock(Driver::class); - $driver->expects('process')->once()->andReturn($contents); - $driver->expects('dominantColor')->once()->with($contents)->andReturn('#123456'); + $driver = Double::for(Driver::class)->strict(); + $driver->expects('process')->returns($contents); + $driver->expects('dominantColor')->with($contents)->returns('#123456'); $this->registerDrivers(['fake' => $driver]); $image = (new Image('source image'))->using('fake')->blur(); @@ -1511,10 +1511,10 @@ public function testThreeVariantsFromSameSource(): void public function testMaterializedCloneReprocessesTheOriginalSourceWithTheFullRecipe(): void { $recipes = []; - $driver = m::mock(Driver::class); + $driver = Double::for(Driver::class)->strict(); $driver->expects('process') - ->twice() - ->andReturnUsing(static function (string $contents, ImagePipeline $pipeline) use (&$recipes): string { + ->times(2) + ->resolves(static function (string $contents, ImagePipeline $pipeline) use (&$recipes): string { $recipes[] = [ $contents, array_map( @@ -1552,21 +1552,17 @@ public function testUsingSetsDriverString(): void public function testSwitchingDriversReprocessesTheRetainedRecipe(): void { - $firstDriver = m::mock(Driver::class); + $firstDriver = Double::for(Driver::class)->strict(); $firstDriver->expects('process') - ->once() - ->withArgs(static fn (string $contents, ImagePipeline $pipeline): bool => $contents === 'source image' - && count($pipeline->transformations) === 1 - && $pipeline->transformations[0] instanceof Blur) - ->andReturn('first output'); + ->with('source image', Argument::satisfies(static fn (ImagePipeline $pipeline): bool => count($pipeline->transformations) === 1 + && $pipeline->transformations[0] instanceof Blur)) + ->returns('first output'); - $secondDriver = m::mock(Driver::class); + $secondDriver = Double::for(Driver::class)->strict(); $secondDriver->expects('process') - ->once() - ->withArgs(static fn (string $contents, ImagePipeline $pipeline): bool => $contents === 'source image' - && count($pipeline->transformations) === 1 - && $pipeline->transformations[0] instanceof Blur) - ->andReturn('second output'); + ->with('source image', Argument::satisfies(static fn (ImagePipeline $pipeline): bool => count($pipeline->transformations) === 1 + && $pipeline->transformations[0] instanceof Blur)) + ->returns('second output'); $this->registerDrivers(['first' => $firstDriver, 'second' => $secondDriver], 'first'); @@ -1680,15 +1676,15 @@ protected function expectImageStored( array $options, bool|string $result = true, ): void { - $filesystem = m::mock(FilesystemContract::class); + $filesystem = Double::for(FilesystemContract::class)->strict(); $filesystem->expects('put') ->with($path, $contents, $options) - ->andReturn($result); + ->returns($result); - $factory = m::mock(FilesystemFactory::class); + $factory = Double::for(FilesystemFactory::class)->strict(); $factory->expects('disk') ->with($diskName) - ->andReturn($filesystem); + ->returns($filesystem); $container = new Container; $container->instance(FilesystemFactory::class, $factory); diff --git a/tests/Inertia/Commands/CheckSsrTest.php b/tests/Inertia/Commands/CheckSsrTest.php index 6a8fd4cc5d..6c741cf41e 100644 --- a/tests/Inertia/Commands/CheckSsrTest.php +++ b/tests/Inertia/Commands/CheckSsrTest.php @@ -7,14 +7,17 @@ use Hypervel\Inertia\Ssr\Gateway; use Hypervel\Inertia\Ssr\HasHealthCheck; use Hypervel\Tests\Inertia\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class CheckSsrTest extends TestCase { + use VerifiesDoubles; + public function testSuccessOnHealthySsrServer(): void { - $mock = m::mock(Gateway::class, HasHealthCheck::class); - $mock->shouldReceive('isHealthy')->andReturn(true); + $mock = Double::for(Gateway::class, HasHealthCheck::class)->strict(); + $mock->allows('isHealthy')->returns(true); $this->app->instance(Gateway::class, $mock); $this->artisan('inertia:check-ssr') @@ -24,8 +27,8 @@ public function testSuccessOnHealthySsrServer(): void public function testFailureOnUnhealthySsrServer(): void { - $mock = m::mock(Gateway::class, HasHealthCheck::class); - $mock->shouldReceive('isHealthy')->andReturn(false); + $mock = Double::for(Gateway::class, HasHealthCheck::class)->strict(); + $mock->allows('isHealthy')->returns(false); $this->app->instance(Gateway::class, $mock); $this->artisan('inertia:check-ssr') diff --git a/tests/Inertia/Commands/StartSsrTest.php b/tests/Inertia/Commands/StartSsrTest.php index 6613c94931..ab7317f94e 100644 --- a/tests/Inertia/Commands/StartSsrTest.php +++ b/tests/Inertia/Commands/StartSsrTest.php @@ -10,13 +10,17 @@ use Hypervel\Inertia\Ssr\HttpGateway; use Hypervel\Inertia\Ssr\SsrException; use Hypervel\Tests\Inertia\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionProperty; use RuntimeException; use Symfony\Component\Process\Process; class StartSsrTest extends TestCase { + use VerifiesDoubles; + /** @var null|list */ protected ?array $processCommand = null; @@ -162,9 +166,9 @@ public function testSsrServerIsStoppedBeforeStartingByDefault(): void { $this->fakeProcess(); - $mock = m::mock(HttpGateway::class); - $mock->shouldReceive('checkHealth')->once()->andReturnTrue(); - $mock->shouldReceive('shutdown')->once()->andReturnTrue(); + $mock = Double::for(HttpGateway::class)->strict(); + $mock->expects('checkHealth')->returns(true); + $mock->expects('shutdown')->returns(true); $this->app->instance(HttpGateway::class, $mock); $this->artisan('inertia:start-ssr')->assertExitCode(0); @@ -174,9 +178,9 @@ public function testSsrServerIsNotStoppedWhenTheNoStopBeforeStartOptionIsUsed(): { $this->fakeProcess(); - $mock = m::mock(HttpGateway::class); - $mock->shouldNotReceive('checkHealth'); - $mock->shouldNotReceive('shutdown'); + $mock = Double::for(HttpGateway::class)->strict(); + $mock->expects('checkHealth')->never(); + $mock->expects('shutdown')->never(); $this->app->instance(HttpGateway::class, $mock); $this->artisan('inertia:start-ssr', ['--no-stop-before-start' => true])->assertExitCode(0); @@ -216,11 +220,10 @@ public function testRegistersTerminationSignalsThroughTheCommandRegistry(): void { $this->fakeProcess(); - $registry = m::mock(SignalRegistry::class); - $registry->shouldReceive('register') - ->once() - ->with(m::type(StartSsr::class), [SIGINT, SIGQUIT, SIGTERM], m::type('callable')); - $registry->shouldReceive('unregister')->once()->with(m::type(StartSsr::class), null); + $registry = Double::for(SignalRegistry::class)->strict(); + $registry->expects('register') + ->with(Argument::type(StartSsr::class), [SIGINT, SIGQUIT, SIGTERM], Argument::type('callable')); + $registry->expects('unregister')->with(Argument::type(StartSsr::class), null); $command = $this->app->make(StartSsr::class); (new ReflectionProperty($command, 'signalRegistry'))->setValue($command, $registry); diff --git a/tests/Inertia/DevTools/EntriesRepositoryTest.php b/tests/Inertia/DevTools/EntriesRepositoryTest.php index 0cf82fc655..309f95eae8 100644 --- a/tests/Inertia/DevTools/EntriesRepositoryTest.php +++ b/tests/Inertia/DevTools/EntriesRepositoryTest.php @@ -11,12 +11,15 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Inertia\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Swoole\Coroutine\CanceledException; class EntriesRepositoryTest extends TestCase { + use VerifiesDoubles; + protected string $storagePath; /** @@ -109,8 +112,8 @@ public function testGetRethrowsCancellationWhileReadingTheEntry(): void $this->makeRepository()->save($id, $payload); $cancellation = new CanceledException('canceled'); - $files = m::mock(Filesystem::class)->makePartial(); - $files->shouldReceive('get')->andThrow($cancellation); + $files = Double::for(Filesystem::class)->passthru(); + $files->allows('get')->throws($cancellation); $repo = new EntriesRepository(path: $this->storagePath, files: $files); diff --git a/tests/Inertia/DirectiveTest.php b/tests/Inertia/DirectiveTest.php index 4bf44845c8..21f6646907 100644 --- a/tests/Inertia/DirectiveTest.php +++ b/tests/Inertia/DirectiveTest.php @@ -4,35 +4,20 @@ namespace Hypervel\Tests\Inertia; -use Hypervel\Filesystem\Filesystem; -use Hypervel\Inertia\Directive; use Hypervel\Inertia\Ssr\Gateway; use Hypervel\Support\Facades\Blade; use Hypervel\Support\Facades\Config; use Hypervel\Tests\Inertia\Fixtures\FakeGateway; -use Hypervel\View\Compilers\BladeCompiler; use Hypervel\View\ViewException; use JsonException; -use Mockery as m; class DirectiveTest extends TestCase { - private Filesystem|m\MockInterface $filesystem; - - protected BladeCompiler $compiler; - protected function setUp(): void { parent::setUp(); $this->app->bind(Gateway::class, FakeGateway::class); - $this->filesystem = m::mock(Filesystem::class); - - /** @var Filesystem $filesystem */ - $filesystem = $this->filesystem; - $this->compiler = new BladeCompiler($filesystem, __DIR__ . '/cache/views'); - $this->compiler->directive('inertia', [Directive::class, 'compile']); - $this->compiler->directive('inertiaHead', [Directive::class, 'compileHead']); } /** diff --git a/tests/Inertia/InertiaServiceProviderTest.php b/tests/Inertia/InertiaServiceProviderTest.php index cddf8cb74c..a5dacc0299 100644 --- a/tests/Inertia/InertiaServiceProviderTest.php +++ b/tests/Inertia/InertiaServiceProviderTest.php @@ -22,10 +22,13 @@ use Hypervel\View\Compilers\BladeCompiler; use Hypervel\View\ViewFinderInterface; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class InertiaServiceProviderTest extends TestCase { + use VerifiesDoubles; + public function testBladeDirectiveIsRegistered(): void { $this->assertArrayHasKey('inertia', Blade::getCustomDirectives()); @@ -112,7 +115,7 @@ public function testInertiaViewFinderIsSharedAndCanBeRebound(): void $this->assertSame($finder, $this->app->make('inertia.view-finder')); - $replacement = m::mock(ViewFinderInterface::class); + $replacement = Double::for(ViewFinderInterface::class)->strict(); $this->app->bind('inertia.view-finder', fn () => $replacement); $this->assertSame($replacement, $this->app->make('inertia.view-finder')); @@ -123,8 +126,8 @@ public function testInertiaViewFinderReusesSuccessfulLookupsWithConfiguredPathsA config()->set('inertia.pages.paths', ['/inertia-pages']); config()->set('inertia.pages.extensions', ['vue']); - $files = m::mock(Filesystem::class); - $files->shouldReceive('exists')->once()->with('/inertia-pages/Dashboard.vue')->andReturn(true); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('exists')->with('/inertia-pages/Dashboard.vue')->returns(true); $this->app->instance('files', $files); $finder = $this->app->make('inertia.view-finder'); @@ -138,8 +141,8 @@ public function testInertiaViewFinderDoesNotCacheMisses(): void config()->set('inertia.pages.paths', ['/inertia-pages']); config()->set('inertia.pages.extensions', ['vue']); - $files = m::mock(Filesystem::class); - $files->shouldReceive('exists')->twice()->with('/inertia-pages/Missing.vue')->andReturn(false); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('exists')->times(2)->with('/inertia-pages/Missing.vue')->returns(false); $this->app->instance('files', $files); $finder = $this->app->make('inertia.view-finder'); @@ -156,15 +159,11 @@ public function testInertiaViewFinderDoesNotCacheMisses(): void public function testRedirectMiddlewareRegistersThroughTheKernelContract(): void { - $kernel = m::mock(HttpKernelContract::class); - $kernel->shouldReceive('pushMiddleware') - ->once() - ->with(EnsureGetOnRedirect::class) - ->andReturnSelf(); - $kernel->shouldReceive('prependMiddleware') - ->once() - ->with(EnsureDeferredCallbacksRun::class) - ->andReturnSelf(); + $kernel = Double::for(HttpKernelContract::class)->strict(); + $kernel->expects('pushMiddleware') + ->with(EnsureGetOnRedirect::class); + $kernel->expects('prependMiddleware') + ->with(EnsureDeferredCallbacksRun::class); $this->app->instance(HttpKernelContract::class, $kernel); (new InspectableInertiaServiceProvider($this->app)) diff --git a/tests/Inertia/ResponseTest.php b/tests/Inertia/ResponseTest.php index 89c695ce8d..ffe74ae1fe 100644 --- a/tests/Inertia/ResponseTest.php +++ b/tests/Inertia/ResponseTest.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\Inertia; +use GuzzleHttp\Promise\FulfilledPromise; use Hypervel\Context\RequestContext; use Hypervel\Contracts\Support\Arrayable; use Hypervel\Http\JsonResponse; @@ -27,7 +28,6 @@ use Hypervel\Tests\Inertia\Fixtures\FakeResource; use Hypervel\Tests\Inertia\Fixtures\MergeWithSharedProp; use Hypervel\View\View; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; class ResponseTest extends TestCase @@ -898,10 +898,7 @@ public function testPromisePropsAreResolved(): void $user = (object) ['name' => 'Jonathan']; - $promise = m::mock('GuzzleHttp\Promise\PromiseInterface') - ->shouldReceive('wait') - ->andReturn($user) - ->getMock(); + $promise = new FulfilledPromise($user); $response = new Response('User/Edit', [], ['user' => $promise], 'app', '123'); /** @var JsonResponse $response */ diff --git a/tests/Integration/Ai/Database/ConversationConcurrencyTestCase.php b/tests/Integration/Ai/Database/ConversationConcurrencyTestCase.php index bc184ebaf3..04e500f889 100644 --- a/tests/Integration/Ai/Database/ConversationConcurrencyTestCase.php +++ b/tests/Integration/Ai/Database/ConversationConcurrencyTestCase.php @@ -22,13 +22,15 @@ use Hypervel\Foundation\Testing\DatabaseTruncation; use Hypervel\Support\Facades\DB; use Hypervel\Tests\Ai\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use function Hypervel\Coroutine\parallel; abstract class ConversationConcurrencyTestCase extends TestCase { use DatabaseTruncation; + use VerifiesDoubles; /** * Give concurrent requests separate pooled sessions with committed setup data. @@ -61,7 +63,7 @@ public function testOverlappingTurnsDoNotDeadlockWhenTouchingTheirConversation() DB::table('agent_conversations')->where('id', $conversationId)->update(['updated_at' => '2020-01-01 00:00:00']); $arrived = new Channel(2); $release = new Channel(2); - $provider = m::mock(TextProvider::class); + $provider = Double::for(TextProvider::class)->strict(); $sessionIds = []; $write = function (string $text) use ($store, $conversationId, $arrived, $release, $provider, &$sessionIds): StoredTurn { @@ -113,7 +115,7 @@ public function testConcurrentResumesAcquireOnlyOneClaim(): void { $store = new DatabaseConversationStore; $conversationId = $store->storeConversation(null, null, 'Approval'); - $prompt = new AgentPrompt(new AnonymousAgent('', [], []), 'Send an email', [], m::mock(TextProvider::class), 'model'); + $prompt = new AgentPrompt(new AnonymousAgent('', [], []), 'Send an email', [], Double::for(TextProvider::class)->strict(), 'model'); $response = (new AgentResponse('invocation', '', new TextUsage, new Meta('test', 'model'))) ->withSteps(collect([ new Step('', [new ToolCall('call-1', 'send_email', [])], [], FinishReason::ToolCalls, new TextUsage, new Meta, '', []), diff --git a/tests/Integration/Ai/Database/ConversationStorageTestCase.php b/tests/Integration/Ai/Database/ConversationStorageTestCase.php index 6da1983d95..c92c27a85d 100644 --- a/tests/Integration/Ai/Database/ConversationStorageTestCase.php +++ b/tests/Integration/Ai/Database/ConversationStorageTestCase.php @@ -22,11 +22,13 @@ use Hypervel\Foundation\Testing\RefreshDatabase; use Hypervel\Support\Str; use Hypervel\Tests\Ai\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; abstract class ConversationStorageTestCase extends TestCase { use RefreshDatabase; + use VerifiesDoubles; /** * Use the configured integration database. @@ -61,7 +63,7 @@ public function testToolPayloadsPreserveNullBytesAndObjectKeyOrder(): void $conversationId = $store->storeConversation(null, null, 'Read a file'); $arguments = ['encoding' => 'UTF-8', 'path' => 'example.txt']; $contents = "Hello\0world"; - $prompt = new AgentPrompt(new AnonymousAgent('', [], []), 'Read the file', [], m::mock(TextProvider::class), 'model'); + $prompt = new AgentPrompt(new AnonymousAgent('', [], []), 'Read the file', [], Double::for(TextProvider::class)->strict(), 'model'); $response = (new AgentResponse('invocation', 'File read', new TextUsage, new Meta('test', 'model'))) ->withSteps(collect([ new Step('', [new ToolCall('call-1', 'read_file', $arguments)], [new ToolResult('call-1', 'read_file', $arguments, $contents)], FinishReason::ToolCalls, new TextUsage, new Meta, '', []), diff --git a/tests/Integration/Auth/EloquentUserProviderCacheTest.php b/tests/Integration/Auth/EloquentUserProviderCacheTest.php index b8fe614083..a937c266b1 100644 --- a/tests/Integration/Auth/EloquentUserProviderCacheTest.php +++ b/tests/Integration/Auth/EloquentUserProviderCacheTest.php @@ -27,8 +27,10 @@ use Hypervel\Testbench\Attributes\DefineEnvironment; use Hypervel\Testbench\Attributes\WithMigration; use Hypervel\Testbench\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use ReflectionClass; @@ -40,22 +42,23 @@ class EloquentUserProviderCacheTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; protected const string DEFAULT_KEY_PREFIX = EloquentUserProvider::DEFAULT_CACHE_PREFIX; protected CacheManager $realCacheManager; - protected MockInterface $cacheManager; + protected CacheManager&DoubleInterface $cacheManager; - protected MockInterface $cacheCoordinator; + protected ModelCacheCoordinator&DoubleInterface $cacheCoordinator; protected function setUp(): void { parent::setUp(); $this->realCacheManager = $this->app->make(CacheManager::class); - $this->cacheManager = m::mock(CacheManager::class); - $this->cacheCoordinator = m::mock(ModelCacheCoordinator::class); + $this->cacheManager = Double::for(CacheManager::class)->strict(); + $this->cacheCoordinator = Double::for(ModelCacheCoordinator::class)->strict(); $this->app->instance('cache', $this->cacheManager); $this->app->instance(ModelCacheCoordinator::class, $this->cacheCoordinator); } @@ -147,7 +150,7 @@ public function testCacheIsClearedOnUserSave(): void $expectedKey = $this->buildKey($user->getAuthIdentifier()); $repo = $this->stubCache(); - $this->cacheCoordinator->shouldReceive('invalidate')->once()->with($repo, $expectedKey); + $this->cacheCoordinator->expects('invalidate')->with(Argument::same($repo), $expectedKey); $this->makeCachedProvider(); @@ -161,7 +164,7 @@ public function testCacheIsClearedOnUserDelete(): void $expectedKey = $this->buildKey($user->getAuthIdentifier()); $repo = $this->stubCache(); - $this->cacheCoordinator->shouldReceive('invalidate')->once()->with($repo, $expectedKey); + $this->cacheCoordinator->expects('invalidate')->with(Argument::same($repo), $expectedKey); $this->makeCachedProvider(); @@ -172,9 +175,8 @@ public function testCacheIsClearedOnlyAfterUserSaveCommits(): void { $user = User::query()->firstOrFail(); $repo = $this->stubCache(); - $this->cacheCoordinator->shouldReceive('invalidate') - ->once() - ->with($repo, $this->buildKey($user->getAuthIdentifier())); + $this->cacheCoordinator->expects('invalidate') + ->with(Argument::same($repo), $this->buildKey($user->getAuthIdentifier())); $this->makeCachedProvider(); @@ -182,7 +184,7 @@ public function testCacheIsClearedOnlyAfterUserSaveCommits(): void $user->name = 'Updated'; $user->save(); - $this->cacheCoordinator->shouldNotHaveReceived('invalidate'); + $this->cacheCoordinator->unused(); }); } @@ -190,16 +192,15 @@ public function testCacheIsClearedOnlyAfterUserDeleteCommits(): void { $user = User::query()->firstOrFail(); $repo = $this->stubCache(); - $this->cacheCoordinator->shouldReceive('invalidate') - ->once() - ->with($repo, $this->buildKey($user->getAuthIdentifier())); + $this->cacheCoordinator->expects('invalidate') + ->with(Argument::same($repo), $this->buildKey($user->getAuthIdentifier())); $this->makeCachedProvider(); DB::transaction(function () use ($user): void { $user->delete(); - $this->cacheCoordinator->shouldNotHaveReceived('invalidate'); + $this->cacheCoordinator->unused(); }); } @@ -207,7 +208,7 @@ public function testCacheInvalidationIsDiscardedWhenUserSaveRollsBack(): void { $user = User::query()->firstOrFail(); $repo = $this->stubCache(); - $this->cacheCoordinator->shouldNotReceive('invalidate'); + $this->cacheCoordinator->expects('invalidate')->never(); $this->makeCachedProvider(); @@ -227,9 +228,8 @@ public function testCacheInvalidationFollowsTheUserConnectionTransaction(): void { $user = User::query()->firstOrFail(); $repo = $this->stubCache(); - $this->cacheCoordinator->shouldReceive('invalidate') - ->once() - ->with($repo, $this->buildKey($user->getAuthIdentifier())); + $this->cacheCoordinator->expects('invalidate') + ->with(Argument::same($repo), $this->buildKey($user->getAuthIdentifier())); $default = DB::connection(); $secondary = DB::connection('auth_secondary'); @@ -242,7 +242,7 @@ public function testCacheInvalidationFollowsTheUserConnectionTransaction(): void $this->fireUserEvent('saved', $user); $secondary->commit(); - $this->cacheCoordinator->shouldNotHaveReceived('invalidate'); + $this->cacheCoordinator->unused(); $default->commit(); } finally { @@ -261,7 +261,7 @@ public function testCacheInvalidationRunsImmediatelyWithoutManagerOrTransaction( $user = (new User)->setConnection('auth_secondary'); $user->setRawAttributes(['id' => 1], true); $repo = $this->stubCache(); - $this->cacheCoordinator->shouldReceive('invalidate')->once()->with($repo, $this->buildKey(1)); + $this->cacheCoordinator->expects('invalidate')->with(Argument::same($repo), $this->buildKey(1)); $connection = DB::connection('auth_secondary'); $manager = $connection->getTransactionManager(); @@ -280,7 +280,7 @@ public function testCacheInvalidationFailsClosedWithoutManagerDuringTransaction( $user = (new User)->setConnection('auth_secondary'); $user->setRawAttributes(['id' => 1], true); $this->stubCache(); - $this->cacheCoordinator->shouldNotReceive('invalidate'); + $this->cacheCoordinator->expects('invalidate')->never(); $connection = DB::connection('auth_secondary'); $manager = $connection->getTransactionManager(); @@ -312,12 +312,10 @@ public function testCacheInvalidationCapturesTheEventKeyAndReadsDescriptorsAtCom }); $repo = $this->stubCache(); - $this->cacheCoordinator->shouldReceive('invalidate') - ->once() - ->with($repo, self::DEFAULT_KEY_PREFIX . ':' . User::class . ':before:' . $user->getAuthIdentifier()); - $this->cacheCoordinator->shouldReceive('invalidate') - ->once() - ->with($repo, 'admin_users:' . User::class . ':before:' . $user->getAuthIdentifier()); + $this->cacheCoordinator->expects('invalidate') + ->with(Argument::same($repo), self::DEFAULT_KEY_PREFIX . ':' . User::class . ':before:' . $user->getAuthIdentifier()); + $this->cacheCoordinator->expects('invalidate') + ->with(Argument::same($repo), 'admin_users:' . User::class . ':before:' . $user->getAuthIdentifier()); $this->makeCachedProvider(); @@ -348,9 +346,9 @@ public function testModelEventInvalidationProvidesProviderModelAndUser(): void }); $repo = $this->stubCache(); - $this->cacheCoordinator->shouldReceive('invalidate') - ->twice() - ->with($repo, self::DEFAULT_KEY_PREFIX . ':' . User::class . ':owner:' . $user->getKey()); + $this->cacheCoordinator->expects('invalidate') + ->times(2) + ->with(Argument::same($repo), self::DEFAULT_KEY_PREFIX . ':' . User::class . ':owner:' . $user->getKey()); $this->makeCachedProvider(); @@ -392,8 +390,8 @@ public function testModelEventInvalidatesAllDescriptorsForSameModel(): void $keyA = self::DEFAULT_KEY_PREFIX . ':' . User::class . ':' . $user->getAuthIdentifier(); $keyB = 'admin_users:' . User::class . ':' . $user->getAuthIdentifier(); - $this->cacheCoordinator->shouldReceive('invalidate')->once()->with($repoA, $keyA); - $this->cacheCoordinator->shouldReceive('invalidate')->once()->with($repoB, $keyB); + $this->cacheCoordinator->expects('invalidate')->with(Argument::same($repoA), $keyA); + $this->cacheCoordinator->expects('invalidate')->with(Argument::same($repoB), $keyB); $providerA = new EloquentUserProvider($this->app->make('hash'), User::class); $providerA->enableCache('redis-a'); @@ -416,8 +414,8 @@ public function testModelEventInvalidationExhaustsDescriptorsAndPreservesTheEarl $earliest = new RuntimeException('first store failed'); $later = new RuntimeException('second store failed'); - $this->cacheCoordinator->shouldReceive('invalidate')->once()->with($repoA, $keyA)->andThrow($earliest); - $this->cacheCoordinator->shouldReceive('invalidate')->once()->with($repoB, $keyB)->andThrow($later); + $this->cacheCoordinator->expects('invalidate')->with(Argument::same($repoA), $keyA)->throws($earliest); + $this->cacheCoordinator->expects('invalidate')->with(Argument::same($repoB), $keyB)->throws($later); $providerA = new EloquentUserProvider($this->app->make('hash'), User::class); $providerA->enableCache('redis-a'); @@ -450,13 +448,13 @@ public function testModelEventInvalidationStopsOnCancellationAfterAnOrdinaryFail foreach (['first', 'second', 'third'] as $name) { $repository = $this->stubCache($name); - $expectation = $this->cacheCoordinator->shouldReceive('invalidate') - ->with($repository, $this->buildKey($user->getAuthIdentifier())); + $expectation = $this->cacheCoordinator->expects('invalidate') + ->with(Argument::same($repository), $this->buildKey($user->getAuthIdentifier())); if ($name === 'third') { $expectation->never(); } else { - $expectation->once()->andThrow($name === 'first' ? new RuntimeException('Store unavailable.') : $failure); + $expectation->throws($name === 'first' ? new RuntimeException('Store unavailable.') : $failure); } (new EloquentUserProvider($this->app->make('hash'), User::class))->enableCache($name); @@ -479,12 +477,10 @@ public function testChangingProviderModelKeepsBothModelKeyspacesInvalidatable(): $user = User::query()->firstOrFail(); $alternateUser = AuthCacheAlternateUser::query()->firstOrFail(); $repo = $this->stubCache(); - $this->cacheCoordinator->shouldReceive('invalidate') - ->once() - ->with($repo, $this->buildKey($user->getAuthIdentifier())); - $this->cacheCoordinator->shouldReceive('invalidate') - ->once() - ->with($repo, self::DEFAULT_KEY_PREFIX . ':' . AuthCacheAlternateUser::class . ':' . $alternateUser->getAuthIdentifier()); + $this->cacheCoordinator->expects('invalidate') + ->with(Argument::same($repo), $this->buildKey($user->getAuthIdentifier())); + $this->cacheCoordinator->expects('invalidate') + ->with(Argument::same($repo), self::DEFAULT_KEY_PREFIX . ':' . AuthCacheAlternateUser::class . ':' . $alternateUser->getAuthIdentifier()); $provider = new EloquentUserProvider($this->app->make('hash'), User::class); $provider->enableCache(null); @@ -501,8 +497,8 @@ public function testModelEventListenersRegisteredOnlyOnce(): void { // Two distinct providers with different configs. If the save/deleted // listeners were attached per-enableCache, the single save below would - // invoke forget 4 times (2 listeners × 2 descriptors). We expect - // exactly 2 forget calls — one listener, iterating 2 descriptors. + // invoke invalidate 4 times (2 listeners × 2 descriptors). We expect + // exactly 2 invalidate calls — one listener, iterating 2 descriptors. $repoA = $this->stubCache('redis-a'); $repoB = $this->stubCache('redis-b'); @@ -510,8 +506,8 @@ public function testModelEventListenersRegisteredOnlyOnce(): void $keyA = self::DEFAULT_KEY_PREFIX . ':' . User::class . ':' . $user->getAuthIdentifier(); $keyB = 'admin_users:' . User::class . ':' . $user->getAuthIdentifier(); - $this->cacheCoordinator->shouldReceive('invalidate')->once()->with($repoA, $keyA); - $this->cacheCoordinator->shouldReceive('invalidate')->once()->with($repoB, $keyB); + $this->cacheCoordinator->expects('invalidate')->with(Argument::same($repoA), $keyA); + $this->cacheCoordinator->expects('invalidate')->with(Argument::same($repoB), $keyB); $providerA = new EloquentUserProvider($this->app->make('hash'), User::class); $providerA->enableCache('redis-a'); @@ -533,7 +529,7 @@ public function testUpdateRememberTokenClearsCache(): void $expectedKey = $this->buildKey($user->getAuthIdentifier()); $repo = $this->stubCache(); - $this->cacheCoordinator->shouldReceive('invalidate')->once()->with($repo, $expectedKey); + $this->cacheCoordinator->expects('invalidate')->with(Argument::same($repo), $expectedKey); $provider = $this->makeCachedProvider(); @@ -546,7 +542,7 @@ public function testRehashPasswordClearsCache(): void $expectedKey = $this->buildKey($user->getAuthIdentifier()); $repo = $this->stubCache(); - $this->cacheCoordinator->shouldReceive('invalidate')->once()->with($repo, $expectedKey); + $this->cacheCoordinator->expects('invalidate')->with(Argument::same($repo), $expectedKey); $provider = $this->makeCachedProvider(); @@ -590,21 +586,21 @@ public function testRetrieveByIdCachesResultWithEagerLoadedRelations(): void $expectedKey = $this->buildKey($user->getAuthIdentifier()); $repo = $this->stubCache(); - $this->cacheCoordinator->shouldReceive('fill') - ->twice() + $fills = 0; + $this->cacheCoordinator->expects('fill') + ->times(2) ->with( $repo, - m::type(Closure::class), + Argument::type(Closure::class), $expectedKey, 300, - m::type(Closure::class), + Argument::type(Closure::class), true, - m::type(Closure::class), + Argument::type(Closure::class), ) - ->andReturnUsing( - fn (CacheRepository $cache, Closure $source, string $key, int $ttl, Closure $read) => $read(), - fn () => $user, - ); + ->resolves(function (CacheRepository $cache, Closure $source, string $key, int $ttl, Closure $read) use (&$fills, $user): Authenticatable { + return ++$fills === 1 ? $read() : $user; + }); $withQueryInvocations = 0; $provider = new EloquentUserProvider($this->app->make('hash'), User::class); @@ -856,11 +852,11 @@ protected function countQueriesForTable(string $table): int )); } - protected function stubCache(?string $name = null): MockInterface + protected function stubCache(?string $name = null): CacheRepository&DoubleInterface { - $repo = m::mock(CacheRepository::class); - $repo->shouldReceive('getStore')->andReturn(m::mock(FileStore::class)); - $this->cacheManager->shouldReceive('store')->with($name)->andReturn($repo); + $repo = Double::for(CacheRepository::class)->strict(); + $repo->allows('getStore')->returns(Double::for(FileStore::class)->strict()); + $this->cacheManager->allows('store')->with($name)->returns($repo); return $repo; } diff --git a/tests/Integration/Broadcasting/BroadcastManagerTest.php b/tests/Integration/Broadcasting/BroadcastManagerTest.php index e4fb2b45e8..d4d7588bbe 100644 --- a/tests/Integration/Broadcasting/BroadcastManagerTest.php +++ b/tests/Integration/Broadcasting/BroadcastManagerTest.php @@ -39,13 +39,14 @@ use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\Contracts\Debug\ExceptionHandler; use Hypervel\Contracts\Events\Dispatcher as EventDispatcher; -use Hypervel\Contracts\Foundation\CachesRoutes; use Hypervel\Contracts\ObjectPool\Factory as PoolFactory; use Hypervel\Contracts\Queue\Factory as QueueFactory; use Hypervel\Contracts\Queue\ShouldQueueViaOutbox; use Hypervel\Contracts\Redis\Factory as Redis; use Hypervel\Contracts\Routing\UrlGenerator as UrlGeneratorContract; use Hypervel\Database\DatabaseTransactionsManager; +use Hypervel\Events\Dispatcher; +use Hypervel\Foundation\Application; use Hypervel\Foundation\Http\Middleware\PreventRequestForgery; use Hypervel\Http\Request; use Hypervel\ObjectPool\PoolManager; @@ -54,9 +55,8 @@ use Hypervel\Queue\FailoverQueue; use Hypervel\Queue\QueueManager; use Hypervel\Queue\SyncQueue; -use Hypervel\Redis\RedisProxy; -use Hypervel\Routing\Route; use Hypervel\Routing\RouteCollection; +use Hypervel\Routing\Router; use Hypervel\Routing\UrlGenerator; use Hypervel\Support\Facades\Broadcast; use Hypervel\Support\Facades\Bus; @@ -65,8 +65,11 @@ use Hypervel\Support\Facades\Queue; use Hypervel\Support\Testing\Fakes\QueueFake; use Hypervel\Testbench\TestCase; +use Hypervel\Tests\Broadcasting\Fixtures\RedisBroadcasterConnection; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use Pusher\Pusher; @@ -78,6 +81,8 @@ class BroadcastManagerTest extends TestCase { + use VerifiesDoubles; + public function testEventCanBeBroadcastNow(): void { Bus::fake(); @@ -148,8 +153,8 @@ public function testEventsCanBeBroadcastUsingQueueRoutes(): void { Bus::fake(); // QueueFake ignores connection names, so verify selection separately from its push assertions. - $queue = m::mock(QueueFake::class, [$this->app])->makePartial(); - $queue->shouldReceive('connection')->once()->with('broadcast-connection')->andReturnSelf(); + $queue = Double::for(new QueueFake($this->app))->passthru(); + $queue->expects('connection')->with('broadcast-connection')->returns($queue); Queue::swap($queue); Queue::route(TestEvent::class, 'broadcast-queue', 'broadcast-connection'); @@ -162,8 +167,8 @@ public function testEventsCanBeBroadcastUsingQueueRoutes(): void public function testEventsCanBeBroadcastWhenForwardingQueue(): void { Bus::fake(); - $queue = m::mock(QueueFake::class, [$this->app])->makePartial(); - $queue->shouldReceive('connection')->once()->with('broadcast-connection')->andReturnSelf(); + $queue = Double::for(new QueueFake($this->app))->passthru(); + $queue->expects('connection')->with('broadcast-connection')->returns($queue); Queue::swap($queue); Queue::forward('broadcast-queue', 'events', 'broadcast-connection'); @@ -177,8 +182,8 @@ public function testEventsCanBeBroadcastWhenForwardingQueue(): void #[TestWith(['explicit', 'explicit'])] public function testForwardedConnectionUsesTheBroadcastQueue(?string $connection, string $expectedConnection): void { - $queue = m::mock(QueueFake::class, [$this->app])->makePartial(); - $queue->shouldReceive('connection')->once()->with($expectedConnection)->andReturnSelf(); + $queue = Double::for(new QueueFake($this->app))->passthru(); + $queue->expects('connection')->with($expectedConnection)->returns($queue); Queue::swap($queue); Queue::forward('broadcast-queue', 'unused', 'wrong-connection'); Queue::forward('updates', 'events', 'cloud'); @@ -228,12 +233,12 @@ public function testUniqueEventsCanBeBroadcast(): void Queue::fake(); $lockKey = 'laravel_unique_job:' . hash('xxh128', TestEventUnique::class) . ':'; - $lock = m::mock(Lock::class); - $lock->shouldReceive('get')->once()->andReturn(true); - $lock->shouldReceive('owner')->once()->andReturn('unique-lock-owner'); - $cache = m::mock(Cache::class); - $cache->shouldReceive('getStore')->once()->andReturn(m::mock(CacheStore::class, LockProvider::class)); - $cache->shouldReceive('lock')->with($lockKey, 0)->andReturn($lock); + $lock = Double::for(Lock::class)->strict(); + $lock->expects('get')->returns(true); + $lock->expects('owner')->returns('unique-lock-owner'); + $store = Double::for(CacheStore::class, LockProvider::class)->strict(); + $store->allows('lock')->with($lockKey, 0)->returns($lock); + $cache = new CacheRepository($store); $this->app->singleton(Cache::class, fn () => $cache); Broadcast::queue(new TestEventUnique); @@ -248,12 +253,12 @@ public function testUniqueEnumEventCanBeQueuedWithoutCloning(): void Queue::fake(); $lockKey = 'laravel_unique_job:' . hash('xxh128', TestEventUniqueEnum::class) . ':'; - $lock = m::mock(Lock::class); - $lock->shouldReceive('get')->once()->andReturn(true); - $lock->shouldReceive('owner')->once()->andReturn('unique-lock-owner'); - $cache = m::mock(Cache::class); - $cache->shouldReceive('getStore')->once()->andReturn(m::mock(CacheStore::class, LockProvider::class)); - $cache->shouldReceive('lock')->with($lockKey, 0)->andReturn($lock); + $lock = Double::for(Lock::class)->strict(); + $lock->expects('get')->returns(true); + $lock->expects('owner')->returns('unique-lock-owner'); + $store = Double::for(CacheStore::class, LockProvider::class)->strict(); + $store->allows('lock')->with($lockKey, 0)->returns($lock); + $cache = new CacheRepository($store); $this->app->singleton(Cache::class, fn () => $cache); Broadcast::queue(TestEventUniqueEnum::Created); @@ -271,12 +276,12 @@ public function testUniqueEventConstructsOnlyTheSelectedWrapper(): void CloneCountingUniqueBroadcastEvent::$clones = 0; $lockKey = 'laravel_unique_job:' . hash('xxh128', CloneCountingUniqueBroadcastEvent::class) . ':'; - $lock = m::mock(Lock::class); - $lock->shouldReceive('get')->once()->andReturn(true); - $lock->shouldReceive('owner')->once()->andReturn('unique-lock-owner'); - $cache = m::mock(Cache::class); - $cache->shouldReceive('getStore')->once()->andReturn(m::mock(CacheStore::class, LockProvider::class)); - $cache->shouldReceive('lock')->with($lockKey, 0)->andReturn($lock); + $lock = Double::for(Lock::class)->strict(); + $lock->expects('get')->returns(true); + $lock->expects('owner')->returns('unique-lock-owner'); + $store = Double::for(CacheStore::class, LockProvider::class)->strict(); + $store->allows('lock')->with($lockKey, 0)->returns($lock); + $cache = new CacheRepository($store); $this->app->singleton(Cache::class, fn () => $cache); Broadcast::queue(new CloneCountingUniqueBroadcastEvent); @@ -362,18 +367,18 @@ public function testUniqueBroadcastPreparationHonorsRescue(string $phase, bool $ $failure = new RuntimeException('Broadcast preparation failed.', previous: $cancellation ? new CanceledException : null); $event = $rescued ? new TestEventUniqueRescue : new TestEventUnique; - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $this->app->instance(ExceptionHandler::class, $handler); if ($rescued && ! $cancellation) { $handler->expects('report')->with($failure, []); } else { - $handler->shouldNotReceive('report'); + $handler->expects('report')->never(); } if ($phase === 'lock') { - $store = m::mock(ArrayStore::class)->makePartial(); - $store->expects('lock')->andThrow($failure); + $store = Double::for(new ArrayStore)->passthru(); + $store->expects('lock')->throws($failure); $this->app->instance(Cache::class, new CacheRepository($store)); } else { Broadcast::queue($event); @@ -406,13 +411,13 @@ public function testUniqueForAttributeDoesNotMakeEventsUniqueWithoutTheContract( public function testUniqueEventLockIsReleasedWhenQueueResolutionFails(): void { $cache = new CacheRepository(new ArrayStore); - $queue = m::mock(QueueFactory::class); + $queue = Double::for(QueueFactory::class)->strict(); $failure = new Exception('Queue unavailable.'); $lockKey = 'laravel_unique_job:' . hash('xxh128', TestEventUnique::class) . ':'; $this->app->instance(Cache::class, $cache); $this->app->instance(QueueFactory::class, $queue); - $queue->shouldReceive('connection')->once()->andThrow($failure); + $queue->expects('connection')->throws($failure); try { Broadcast::queue(new TestEventUnique); @@ -430,12 +435,12 @@ public function testUniqueEventLockIsReleasedWhenQueueResolutionFails(): void public function testRescuedUniqueEventPublicationFailureReleasesItsLock(): void { $cache = new CacheRepository(new ArrayStore); - $queue = m::mock(QueueFactory::class); + $queue = Double::for(QueueFactory::class)->strict(); $lockKey = 'laravel_unique_job:' . hash('xxh128', TestEventUniqueRescue::class) . ':'; $this->app->instance(Cache::class, $cache); $this->app->instance(QueueFactory::class, $queue); - $queue->shouldReceive('connection')->once()->andThrow(new Exception('Queue unavailable.')); + $queue->expects('connection')->throws(new Exception('Queue unavailable.')); Broadcast::queue(new TestEventUniqueRescue); @@ -454,8 +459,8 @@ public function testDeferredQueueFailuresHonorBroadcastRescueAndReleaseLocks(str { config(['cache.default' => 'array', 'broadcasting.default' => 'log']); $failure = $mode === 'cancellation' ? new CanceledException : new RuntimeException('Queue unavailable.'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->with($failure, [])->times($mode === 'cancellation' ? 0 : 1); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($failure, [])->times($mode === 'cancellation' ? 0 : 1); $this->app->instance(ExceptionHandler::class, $handler); if ($mode === 'rollback') { @@ -473,15 +478,15 @@ public function testDeferredQueueFailuresHonorBroadcastRescueAndReleaseLocks(str $queue->setAfterCommitDispatcher(static fn () => throw $failure); if (str_starts_with($mode, 'failover')) { - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->with('deferred')->andReturn($queue); + $manager = Double::for(QueueManager::class)->strict(); + $manager->allows('connection')->with('deferred')->returns($queue); $queue = new FailoverQueue($manager, $this->app->make(EventDispatcher::class), ['deferred'], $mode === 'failover'); $queue->setContainer($this->app); $queue->setConnectionName('failover'); } - $factory = m::mock(QueueFactory::class); - $factory->shouldReceive('connection')->andReturn($queue); + $factory = Double::for(QueueFactory::class)->strict(); + $factory->allows('connection')->returns($queue); $this->app->instance(QueueFactory::class, $factory); $lock = $this->app->make(Cache::class)->lock('laravel_unique_job:' . hash('xxh128', TestDeferredRescuedBroadcast::class) . ':'); @@ -605,22 +610,20 @@ public function testRedisDriverUsesCanonicalPrefixPrecedence( 'connection' => 'broadcasting', ]); - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('isCluster')->once()->andReturnFalse(); - $connection->shouldReceive('eval') - ->once() + $connection = Double::for(RedisBroadcasterConnection::class)->strict(); + $connection->expects('isCluster')->returns(false); + $connection->expects('eval') ->with( - m::type('string'), + Argument::type('string'), 0, - m::type('string'), + Argument::type('string'), $expectedPrefix . 'orders', ); - $redis = m::mock(Redis::class); - $redis->shouldReceive('connection') - ->once() + $redis = Double::for(Redis::class)->strict(); + $redis->expects('connection') ->with('broadcasting') - ->andReturn($connection); + ->returns($connection); $this->app->instance('redis', $redis); $manager = new BroadcastManager($this->app); @@ -666,71 +669,41 @@ public static function redisPrefixConfigurations(): array public function testRoutesExcludesCsrfMiddleware(): void { - $route = m::mock(Route::class); - $route->shouldReceive('withoutMiddleware') - ->once() - ->with([PreventRequestForgery::class]) - ->andReturnSelf(); - - $router = m::mock('router'); - $router->shouldReceive('group') - ->once() - ->withArgs(function ($attributes, $callback) use ($router) { - $this->assertSame(['middleware' => ['web']], $attributes); - $callback($router); - return true; - }); - $router->shouldReceive('match') - ->once() - ->withArgs(function ($methods, $path) { - return $methods === ['get', 'post'] && $path === '/broadcasting/auth'; - }) - ->andReturn($route); + $app = new Container; + $router = new Router(new Dispatcher, $app); + $app->instance('router', $router); - $app = m::mock(Container::class); - $app->shouldReceive('make')->with('router')->andReturn($router); + (new BroadcastManager($app))->routes(); - $broadcastManager = new BroadcastManager($app); - $broadcastManager->routes(); + $route = $router->getRoutes()->match(Request::create('/broadcasting/auth', 'POST')); + + $this->assertSame(['GET', 'POST', 'HEAD'], $route->methods()); + $this->assertSame(['web'], $route->middleware()); + $this->assertSame([PreventRequestForgery::class], $route->excludedMiddleware()); } public function testUserRoutesExcludesCsrfMiddleware(): void { - $route = m::mock(Route::class); - $route->shouldReceive('withoutMiddleware') - ->once() - ->with([PreventRequestForgery::class]) - ->andReturnSelf(); - - $router = m::mock('router'); - $router->shouldReceive('group') - ->once() - ->withArgs(function ($attributes, $callback) use ($router) { - $this->assertSame(['middleware' => ['web']], $attributes); - $callback($router); - return true; - }); - $router->shouldReceive('match') - ->once() - ->withArgs(function ($methods, $path) { - return $methods === ['get', 'post'] && $path === '/broadcasting/user-auth'; - }) - ->andReturn($route); + $app = new Container; + $router = new Router(new Dispatcher, $app); + $app->instance('router', $router); - $app = m::mock(Container::class); - $app->shouldReceive('make')->with('router')->andReturn($router); + (new BroadcastManager($app))->userRoutes(); - $broadcastManager = new BroadcastManager($app); - $broadcastManager->userRoutes(); + $route = $router->getRoutes()->match(Request::create('/broadcasting/user-auth', 'POST')); + + $this->assertSame(['GET', 'POST', 'HEAD'], $route->methods()); + $this->assertSame(['web'], $route->middleware()); + $this->assertSame([PreventRequestForgery::class], $route->excludedMiddleware()); } public function testRoutesAreNotRegisteredWhenCached(): void { - $app = m::mock(Container::class . ',' . CachesRoutes::class); - $app->shouldReceive('routesAreCached')->once()->andReturnTrue(); - $app->shouldNotReceive('make')->with('router'); + $app = Double::for(Application::class, override: true)->strict(); + $app->expects('routesAreCached')->returns(true); + $app->expects('make')->never()->with('router'); - $broadcastManager = new BroadcastManager($app); + $broadcastManager = new BroadcastManager($app->instance()); $broadcastManager->routes(); } @@ -846,7 +819,7 @@ public function testBuiltInSdkDriversResolveDirectlyWithoutDefaultPools(): void $this->assertSame([], $app->make(PoolFactory::class)->getPools()); $this->assertSame([], $manager->getPoolableDrivers()); - $replacementPusher = m::mock(Pusher::class); + $replacementPusher = Double::for(Pusher::class)->strict(); $manager->setDefaultDriver('pusher'); $manager->setPusher($replacementPusher); $this->assertSame($replacementPusher, $manager->getPusher()); @@ -862,8 +835,8 @@ public function testAblyDriverAcceptsAnSdkOneClientFromAnOverriddenFactory(): vo $config = ['driver' => 'ably', 'key' => 'abcd:efg']; $app = $this->poolingApplication(['ably' => $config]); $ably = new AblyRest($config); - $manager = m::mock(BroadcastManager::class, [$app])->makePartial(); - $manager->shouldReceive('ably')->once()->with($config)->andReturn($ably); + $manager = Double::for(new BroadcastManager($app))->passthru(); + $manager->expects('ably')->with($config)->returns($ably); $broadcaster = $manager->connection('ably'); @@ -982,7 +955,7 @@ public function testCustomDriverClosureBoundObjectIsBroadcastManager(): void $broadcastManager->extend('custom', function () use (&$boundInstance) { $boundInstance = $this; - return m::mock(Broadcaster::class); + return Double::for(Broadcaster::class)->strict(); }); $broadcastManager->connection('test'); @@ -999,7 +972,7 @@ public function testCustomDriverStaticClosure(): void ], ], ])); - $driver = m::mock(Broadcaster::class); + $driver = Double::for(Broadcaster::class)->strict(); $manager = new BroadcastManager($app); $manager->extend('custom', static fn () => $driver); @@ -1017,7 +990,7 @@ public function testInvokableObjectDriverClosure(): void ], ], ])); - $driver = m::mock(Broadcaster::class); + $driver = Double::for(Broadcaster::class)->strict(); $manager = new BroadcastManager($app); $creator = new ManagerCustomBroadcastCreator($driver); @@ -1058,7 +1031,7 @@ public function testBroadcastManagerCanResolveBackedEnumConnection(): void ], ])); - $driver = m::mock(Broadcaster::class); + $driver = Double::for(Broadcaster::class)->strict(); $manager = new BroadcastManager($app); $manager->extend('log', static fn () => $driver); @@ -1077,7 +1050,7 @@ public function testBroadcastManagerCanResolveBackedEnumDriver(): void ], ])); - $driver = m::mock(Broadcaster::class); + $driver = Double::for(Broadcaster::class)->strict(); $manager = new BroadcastManager($app); $manager->extend('log', static fn () => $driver); @@ -1113,7 +1086,7 @@ public function testPurgeAcceptsBackedEnum(): void ])); $manager = new BroadcastManager($app); - $manager->extend('log', static fn () => m::mock(Broadcaster::class)); + $manager->extend('log', static fn () => Double::for(Broadcaster::class)->strict()); $instance1 = $manager->connection(BroadcastConnectionName::Log); $manager->purge(BroadcastConnectionName::Log); @@ -1262,7 +1235,7 @@ public function testSynchronousMercurePreservesNonSerializableEvents(bool $after public function testDeferredMercureRescuesPublicationAndLockCleanupFailures(string $phase): void { $failure = new RuntimeException('Broadcast operation failed.'); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $handler->expects('report')->with($failure, []); $this->app->instance(ExceptionHandler::class, $handler); $published = 0; @@ -1611,8 +1584,8 @@ protected function mercureClaims(array $config): array public function testMercureAcceptsAUrlGeneratorContractImplementation(): void { $application = $this->getApp([]); - $urls = m::mock(UrlGeneratorContract::class); - $urls->shouldReceive('to')->with('/.well-known/mercure')->andReturn('https://hub.test/events'); + $urls = Double::for(UrlGeneratorContract::class)->strict(); + $urls->allows('to')->with('/.well-known/mercure')->returns('https://hub.test/events'); $application->instance('url', $urls); $hub = (new BroadcastManager($application))->mercure($this->mercureConfig(['url' => '/.well-known/mercure'])); @@ -1625,8 +1598,8 @@ public function testMercureAcceptsAUrlGeneratorContractImplementation(): void public function testExplicitMercureTokenAudienceDoesNotResolveTheDefaultUrl(): void { $application = $this->getApp([]); - $urls = m::mock(UrlGeneratorContract::class); - $urls->shouldNotReceive('to'); + $urls = Double::for(UrlGeneratorContract::class)->strict(); + $urls->expects('to')->never(); $application->instance('url', $urls); $hub = (new BroadcastManager($application))->mercure($this->mercureConfig(['url' => '/.well-known/mercure'])); @@ -1688,7 +1661,7 @@ public function testMercureKeepsPoolControlsAndCustomCreatorsDoNotReceiveThem(): $this->assertSame(2, $hub->getDefinition()->options->maxObjects); $manager->forgetDrivers(); - $driver = m::mock(Broadcaster::class); + $driver = Double::for(Broadcaster::class)->strict(); $received = null; $manager->extend('mercure', static function (ContainerContract $app, array $config) use (&$received, $driver): Broadcaster { $received = $config; @@ -1710,8 +1683,8 @@ protected function synchronousMercureManager(Closure $publish): BroadcastManager 'broadcasting.default' => 'mercure', 'broadcasting.connections.mercure' => ['driver' => 'mercure', 'async' => false], ]); - $broadcaster = m::mock(Broadcaster::class); - $broadcaster->shouldReceive('broadcast')->andReturnUsing($publish); + $broadcaster = Double::for(Broadcaster::class)->strict(); + $broadcaster->allows('broadcast')->resolves($publish); $manager = $this->app->make(BroadcastManager::class); $manager->extend('mercure', static fn () => $broadcaster); diff --git a/tests/Integration/Broadcasting/SendingBroadcastsViaAnonymousEventTest.php b/tests/Integration/Broadcasting/SendingBroadcastsViaAnonymousEventTest.php index 3405c59da4..e9680345e5 100644 --- a/tests/Integration/Broadcasting/SendingBroadcastsViaAnonymousEventTest.php +++ b/tests/Integration/Broadcasting/SendingBroadcastsViaAnonymousEventTest.php @@ -12,7 +12,6 @@ use Hypervel\Support\Facades\Broadcast; use Hypervel\Support\Facades\Event; use Hypervel\Testbench\TestCase; -use Mockery as m; use ReflectionClass; class SendingBroadcastsViaAnonymousEventTest extends TestCase @@ -132,9 +131,8 @@ public function testSendToOthersOnly(): void { Event::fake(); - $request = m::mock(Request::class); - $request->shouldReceive('header')->with('X-Socket-ID')->andReturn('12345'); - $request->shouldReceive('setUserResolver')->andReturnSelf(); + $request = Request::create('/'); + $request->headers->set('X-Socket-ID', '12345'); RequestContext::set($request); Broadcast::on('test-channel')->send(); diff --git a/tests/Integration/Cache/FailoverStoreTest.php b/tests/Integration/Cache/FailoverStoreTest.php index c9a894b695..d24e8e55b7 100644 --- a/tests/Integration/Cache/FailoverStoreTest.php +++ b/tests/Integration/Cache/FailoverStoreTest.php @@ -21,12 +21,16 @@ use Hypervel\Support\Facades\Event; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; #[WithConfig('cache.default', 'failover')] #[WithConfig('cache.stores.array.serialize', false)] class FailoverStoreTest extends TestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -64,36 +68,36 @@ public function testFailoverCacheDispatchesEventOnlyOnce(): void public function testSeparateFailoverStoresDoNotShareFailureEventsForTheSameFailingStore(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners') - ->twice() + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners') + ->times(2) ->with(CacheFailedOver::class) - ->andReturn(true); - $events->shouldReceive('dispatch') - ->twice() - ->with(m::on(fn (object $event) => $event instanceof CacheFailedOver && $event->storeName === 'failing')); - - $failingRepository = m::mock(CacheRepository::class, RawReadable::class); - $failingRepository->shouldReceive('getRaw') - ->twice() - ->with(m::type('string')) - ->andThrow(new Exception('The primary store failed.')); - - $fallbackRepository = m::mock(CacheRepository::class, RawReadable::class); - $fallbackRepository->shouldReceive('getRaw') - ->twice() - ->with(m::type('string')) - ->andReturn('fallback-a', 'fallback-b'); - - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store') + ->returns(true); + $events->expects('dispatch') + ->times(2) + ->with(Argument::satisfies(fn (object $event) => $event instanceof CacheFailedOver && $event->storeName === 'failing')); + + $failingRepository = Double::for(CacheRepository::class, RawReadable::class)->strict(); + $failingRepository->expects('getRaw') + ->times(2) + ->with(Argument::type('string')) + ->throws(new Exception('The primary store failed.')); + + $fallbackRepository = Double::for(CacheRepository::class, RawReadable::class)->strict(); + $fallbackRepository->expects('getRaw') + ->times(2) + ->with(Argument::type('string')) + ->returns('fallback-a', 'fallback-b'); + + $cacheManager = Double::for(CacheManager::class)->strict(); + $cacheManager->expects('store') ->with('failing') - ->twice() - ->andReturn($failingRepository); - $cacheManager->shouldReceive('store') + ->times(2) + ->returns($failingRepository); + $cacheManager->expects('store') ->with('fallback') - ->twice() - ->andReturn($fallbackRepository); + ->times(2) + ->returns($fallbackRepository); $storeA = new FailoverStore($cacheManager, $events, ['failing', 'fallback']); $storeB = new FailoverStore($cacheManager, $events, ['failing', 'fallback']); @@ -104,34 +108,29 @@ public function testSeparateFailoverStoresDoNotShareFailureEventsForTheSameFaili public function testFailoverCacheSkipsFailedOverEventWhenThereAreNoListeners(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners') - ->once() + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners') ->with(CacheFailedOver::class) - ->andReturn(false); - $events->shouldNotReceive('dispatch'); + ->returns(false); + $events->expects('dispatch')->never(); - $failingRepository = m::mock(CacheRepository::class, RawReadable::class); - $failingRepository->shouldReceive('getRaw') - ->once() + $failingRepository = Double::for(CacheRepository::class, RawReadable::class)->strict(); + $failingRepository->expects('getRaw') ->with('test') - ->andThrow(new Exception('The primary store failed.')); + ->throws(new Exception('The primary store failed.')); - $fallbackRepository = m::mock(CacheRepository::class, RawReadable::class); - $fallbackRepository->shouldReceive('getRaw') - ->once() + $fallbackRepository = Double::for(CacheRepository::class, RawReadable::class)->strict(); + $fallbackRepository->expects('getRaw') ->with('test') - ->andReturn('fallback'); + ->returns('fallback'); - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store') + $cacheManager = Double::for(CacheManager::class)->strict(); + $cacheManager->expects('store') ->with('failing') - ->once() - ->andReturn($failingRepository); - $cacheManager->shouldReceive('store') + ->returns($failingRepository); + $cacheManager->expects('store') ->with('fallback') - ->once() - ->andReturn($fallbackRepository); + ->returns($fallbackRepository); $store = new FailoverStore($cacheManager, $events, ['failing', 'fallback']); @@ -140,12 +139,12 @@ public function testFailoverCacheSkipsFailedOverEventWhenThereAreNoListeners(): public function testGetRawNormalizesIntegerBackedEnumKeys(): void { - $events = m::mock(Dispatcher::class); - $repository = m::mock(CacheRepository::class, RawReadable::class); - $repository->shouldReceive('getRaw')->once()->with('0')->andReturn('zero'); + $events = Double::for(Dispatcher::class)->strict(); + $repository = Double::for(CacheRepository::class, RawReadable::class)->strict(); + $repository->expects('getRaw')->with('0')->returns('zero'); - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store')->once()->with('primary')->andReturn($repository); + $cacheManager = Double::for(CacheManager::class)->strict(); + $cacheManager->expects('store')->with('primary')->returns($repository); $store = new FailoverStore($cacheManager, $events, ['primary']); @@ -154,16 +153,15 @@ public function testGetRawNormalizesIntegerBackedEnumKeys(): void public function testPutManyWithEmptyInputReturnsSelectedStoreResult(): void { - $events = m::mock(Dispatcher::class); + $events = Double::for(Dispatcher::class)->strict(); - $repository = m::mock(CacheRepository::class); - $repository->shouldReceive('putMany')->once()->with([], 60)->andReturn(false); + $repository = Double::for(CacheRepository::class)->strict(); + $repository->expects('putMany')->with([], 60)->returns(false); - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store') + $cacheManager = Double::for(CacheManager::class)->strict(); + $cacheManager->expects('store') ->with('primary') - ->once() - ->andReturn($repository); + ->returns($repository); $store = new FailoverStore($cacheManager, $events, ['primary']); @@ -252,10 +250,10 @@ public function testManyFiresCacheHitNotCacheMissedForSentinelThroughFailoverSta // Capture only the many() read-path events by attaching the dispatcher // after the write. $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function ($event) use (&$captured) { + $events = Double::for(Dispatcher::class)->strict(); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function ($event) use (&$captured) { $captured[] = $event; }); $outerRepo->setEventDispatcher($events); @@ -273,12 +271,12 @@ public function testManyFiresCacheHitNotCacheMissedForSentinelThroughFailoverSta public function testForgetAndFlushReachEveryStore(): void { - $primary = m::mock(CacheRepository::class); - $primary->shouldReceive('forget')->once()->with('key')->andReturn(false); - $primary->shouldReceive('flush')->once()->andReturn(true); - $fallback = m::mock(CacheRepository::class); - $fallback->shouldReceive('forget')->once()->with('key')->andReturn(true); - $fallback->shouldReceive('flush')->once()->andReturn(true); + $primary = Double::for(CacheRepository::class)->strict(); + $primary->expects('forget')->with('key')->returns(false); + $primary->expects('flush')->returns(true); + $fallback = Double::for(CacheRepository::class)->strict(); + $fallback->expects('forget')->with('key')->returns(true); + $fallback->expects('flush')->returns(true); $store = $this->failoverStore([ 'primary' => $primary, 'fallback' => $fallback, @@ -290,17 +288,15 @@ public function testForgetAndFlushReachEveryStore(): void public function testPartialInvalidationFailuresReturnFalseAfterTryingEveryStore(): void { - $primary = m::mock(CacheRepository::class); - $primary->shouldReceive('forget') - ->once() + $primary = Double::for(CacheRepository::class)->strict(); + $primary->expects('forget') ->with('key') - ->andThrow(new Exception('Primary forget failed.')); - $primary->shouldReceive('flush') - ->once() - ->andThrow(new Exception('Primary flush failed.')); - $fallback = m::mock(CacheRepository::class); - $fallback->shouldReceive('forget')->once()->with('key')->andReturn(false); - $fallback->shouldReceive('flush')->once()->andReturn(true); + ->throws(new Exception('Primary forget failed.')); + $primary->expects('flush') + ->throws(new Exception('Primary flush failed.')); + $fallback = Double::for(CacheRepository::class)->strict(); + $fallback->expects('forget')->with('key')->returns(false); + $fallback->expects('flush')->returns(true); $store = $this->failoverStore([ 'primary' => $primary, 'fallback' => $fallback, @@ -312,10 +308,10 @@ public function testPartialInvalidationFailuresReturnFalseAfterTryingEveryStore( public function testFlushReturnsFalseWhenAnyCompletedStoreReturnsFalse(): void { - $primary = m::mock(CacheRepository::class); - $primary->shouldReceive('flush')->once()->andReturn(false); - $fallback = m::mock(CacheRepository::class); - $fallback->shouldReceive('flush')->once()->andReturn(true); + $primary = Double::for(CacheRepository::class)->strict(); + $primary->expects('flush')->returns(false); + $fallback = Double::for(CacheRepository::class)->strict(); + $fallback->expects('flush')->returns(true); $store = $this->failoverStore([ 'primary' => $primary, 'fallback' => $fallback, @@ -326,16 +322,14 @@ public function testFlushReturnsFalseWhenAnyCompletedStoreReturnsFalse(): void public function testAllFailingInvalidationRethrowsTheLastExceptionAfterTryingEveryStore(): void { - $primary = m::mock(CacheRepository::class); - $primary->shouldReceive('forget') - ->once() + $primary = Double::for(CacheRepository::class)->strict(); + $primary->expects('forget') ->with('key') - ->andThrow(new Exception('Primary failed.')); - $fallback = m::mock(CacheRepository::class); - $fallback->shouldReceive('forget') - ->once() + ->throws(new Exception('Primary failed.')); + $fallback = Double::for(CacheRepository::class)->strict(); + $fallback->expects('forget') ->with('key') - ->andThrow(new Exception('Fallback failed.')); + ->throws(new Exception('Fallback failed.')); $store = $this->failoverStore([ 'primary' => $primary, 'fallback' => $fallback, @@ -349,16 +343,14 @@ public function testAllFailingInvalidationRethrowsTheLastExceptionAfterTryingEve public function testAllFailingFirstSuccessOperationStillRethrowsTheLastException(): void { - $primary = m::mock(CacheRepository::class, RawReadable::class); - $primary->shouldReceive('getRaw') - ->once() + $primary = Double::for(CacheRepository::class, RawReadable::class)->strict(); + $primary->expects('getRaw') ->with('key') - ->andThrow(new Exception('Primary failed.')); - $fallback = m::mock(CacheRepository::class, RawReadable::class); - $fallback->shouldReceive('getRaw') - ->once() + ->throws(new Exception('Primary failed.')); + $fallback = Double::for(CacheRepository::class, RawReadable::class)->strict(); + $fallback->expects('getRaw') ->with('key') - ->andThrow(new Exception('Fallback failed.')); + ->throws(new Exception('Fallback failed.')); $store = $this->failoverStore([ 'primary' => $primary, 'fallback' => $fallback, @@ -372,29 +364,25 @@ public function testAllFailingFirstSuccessOperationStillRethrowsTheLastException public function testFailedInvalidationUpdatesFailureContextForLaterFirstSuccessWrites(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners') - ->once() + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners') ->with(CacheFailedOver::class) - ->andReturn(true); - $events->shouldReceive('dispatch') - ->once() - ->with(m::on( + ->returns(true); + $events->expects('dispatch') + ->with(Argument::satisfies( fn (object $event): bool => $event instanceof CacheFailedOver && $event->storeName === 'primary' )); - $primary = m::mock(CacheRepository::class); - $primary->shouldReceive('forget') - ->once() + $primary = Double::for(CacheRepository::class)->strict(); + $primary->expects('forget') ->with('key') - ->andThrow(new Exception('Primary failed.')); - $primary->shouldReceive('put') - ->once() + ->throws(new Exception('Primary failed.')); + $primary->expects('put') ->with('key', 'value', 60) - ->andThrow(new Exception('Primary still failed.')); - $fallback = m::mock(CacheRepository::class); - $fallback->shouldReceive('forget')->once()->with('key')->andReturn(true); - $fallback->shouldReceive('put')->once()->with('key', 'value', 60)->andReturn(true); + ->throws(new Exception('Primary still failed.')); + $fallback = Double::for(CacheRepository::class)->strict(); + $fallback->expects('forget')->with('key')->returns(true); + $fallback->expects('put')->with('key', 'value', 60)->returns(true); $store = $this->failoverStore([ 'primary' => $primary, 'fallback' => $fallback, @@ -406,12 +394,12 @@ public function testFailedInvalidationUpdatesFailureContextForLaterFirstSuccessW public function testSuccessfulReadsAndWritesRemainFirstSuccessOperations(): void { - $primary = m::mock(CacheRepository::class, RawReadable::class); - $primary->shouldReceive('getRaw')->once()->with('key')->andReturn('value'); - $primary->shouldReceive('put')->once()->with('key', 'updated', 60)->andReturn(true); - $fallback = m::mock(CacheRepository::class, RawReadable::class); - $fallback->shouldNotReceive('getRaw'); - $fallback->shouldNotReceive('put'); + $primary = Double::for(CacheRepository::class, RawReadable::class)->strict(); + $primary->expects('getRaw')->with('key')->returns('value'); + $primary->expects('put')->with('key', 'updated', 60)->returns(true); + $fallback = Double::for(CacheRepository::class, RawReadable::class)->strict(); + $fallback->expects('getRaw')->never(); + $fallback->expects('put')->never(); $store = $this->failoverStore([ 'primary' => $primary, 'fallback' => $fallback, @@ -421,14 +409,17 @@ public function testSuccessfulReadsAndWritesRemainFirstSuccessOperations(): void $this->assertTrue($store->put('key', 'updated', 60)); } + /** + * Build a repository with primary and fallback cache stores. + */ private function buildFailoverRepository(Repository $primary, Repository $fallback): Repository { - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store')->with('primary')->andReturn($primary); - $cacheManager->shouldReceive('store')->with('fallback')->andReturn($fallback); + $cacheManager = Double::for(CacheManager::class)->strict(); + $cacheManager->allows('store')->with('primary')->returns($primary); + $cacheManager->allows('store')->with('fallback')->returns($fallback); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('dispatch')->withAnyArgs()->andReturnNull(); + $events = Double::for(Dispatcher::class)->strict(); + $events->allows('dispatch'); return new Repository(new FailoverStore($cacheManager, $events, ['primary', 'fallback'])); } @@ -442,15 +433,15 @@ private function failoverStore( array $repositories, ?Dispatcher $events = null, ): FailoverStore { - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store') - ->andReturnUsing( + $cacheManager = Double::for(CacheManager::class)->strict(); + $cacheManager->allows('store') + ->resolves( fn (string $store): CacheRepository => $repositories[$store], ); if ($events === null) { - $events = m::mock(Dispatcher::class); - $events->allows('hasListeners')->andReturn(false); + $events = Double::for(Dispatcher::class)->strict(); + $events->allows('hasListeners')->returns(false); } return new FailoverStore( diff --git a/tests/Integration/Cache/MemoizedTaggedCacheTest.php b/tests/Integration/Cache/MemoizedTaggedCacheTest.php index 2156915086..88767c7aae 100644 --- a/tests/Integration/Cache/MemoizedTaggedCacheTest.php +++ b/tests/Integration/Cache/MemoizedTaggedCacheTest.php @@ -384,7 +384,8 @@ public function testStoreFlushClearsExistingTaggedMemoizedCacheInstancesWithoutD Cache::memo()->flush(); $this->assertNull($cache->get('name')); - $this->assertSame([], $events); + $this->assertSame([CacheFlushing::class, CacheFlushed::class], array_map(get_class(...), $events)); + $this->assertSame([[], []], array_map(static fn (CacheFlushing|CacheFlushed $event): array => $event->tags, $events)); } public function testItDispatchesDecoratedDriverEventsOnly(): void diff --git a/tests/Integration/Cache/Redis/BenchmarkContextTest.php b/tests/Integration/Cache/Redis/BenchmarkContextTest.php index 30e0b83128..189042c2d1 100644 --- a/tests/Integration/Cache/Redis/BenchmarkContextTest.php +++ b/tests/Integration/Cache/Redis/BenchmarkContextTest.php @@ -9,10 +9,13 @@ use Hypervel\Cache\TagMode; use Hypervel\Console\Command; use Hypervel\Contracts\Cache\Factory as CacheContract; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class BenchmarkContextTest extends RedisCacheIntegrationTestCase { + use VerifiesDoubles; + public function testCleanupRemovesEveryBenchmarkKeyFamilyAndPreservesUnrelatedKeysInAnyMode(): void { $this->setTagMode(TagMode::Any); @@ -81,7 +84,7 @@ private function benchmarkContext(): BenchmarkContext items: 1, tagsPerItem: 1, heavyTags: 1, - command: m::mock(Command::class), + command: Double::for(Command::class)->strict(), cacheManager: $this->app->make(CacheContract::class), ); } diff --git a/tests/Integration/Cache/Redis/ConcurrencyIntegrationTest.php b/tests/Integration/Cache/Redis/ConcurrencyIntegrationTest.php index 03bb54cde7..b52c61cc44 100644 --- a/tests/Integration/Cache/Redis/ConcurrencyIntegrationTest.php +++ b/tests/Integration/Cache/Redis/ConcurrencyIntegrationTest.php @@ -14,7 +14,8 @@ use Hypervel\Coroutine\Parallel; use Hypervel\Support\Facades\Cache; use Hypervel\Support\LazyCollection; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Swoole\Coroutine\CanceledException; /** @@ -25,6 +26,8 @@ */ class ConcurrencyIntegrationTest extends RedisCacheIntegrationTestCase { + use VerifiesDoubles; + // ========================================================================= // CONCURRENT WRITES - BOTH MODES // ========================================================================= @@ -215,8 +218,8 @@ private function assertRaceBetweenPutAndFlush(): void $context = $this->store()->getContext(); if ($this->getTagMode()->isAnyMode()) { - $reader = m::mock(GetTaggedKeys::class); - $reader->expects('execute')->with('race-flush')->andReturnUsing(function () use ($cache): Generator { + $reader = Double::for(GetTaggedKeys::class)->strict(); + $reader->expects('execute')->with('race-flush')->resolves(function () use ($cache): Generator { yield 'early'; // Publish after the scan snapshot, before its deletion chunk. $cache->forever('late', 'late-value'); @@ -225,9 +228,9 @@ private function assertRaceBetweenPutAndFlush(): void $this->assertTrue($this->anyModeRegistryHasTag('race-flush')); } else { $members = array_keys($this->getAllModeTagEntries('race-flush')); - $reader = m::mock(GetEntries::class); + $reader = Double::for(GetEntries::class)->strict(); $reader->expects('execute')->with([$context->tagId('race-flush')]) - ->andReturn(new LazyCollection(function () use ($members, $cache): Generator { + ->returns(new LazyCollection(function () use ($members, $cache): Generator { yield from $members; $cache->forever('late', 'late-value'); })); @@ -252,8 +255,8 @@ public function testInterruptedAnyModeFlushKeepsRemainingMembersDiscoverableByPr } $exception = new CanceledException('Flush canceled between chunks'); - $reader = m::mock(GetTaggedKeys::class); - $reader->expects('execute')->with('interrupted')->andReturnUsing(function () use ($exception): Generator { + $reader = Double::for(GetTaggedKeys::class)->strict(); + $reader->expects('execute')->with('interrupted')->resolves(function () use ($exception): Generator { for ($index = 0; $index < 1000; ++$index) { yield 'key-' . $index; } @@ -289,9 +292,9 @@ public function testAnyModeFlushingTagsWhileASharedKeyIsRewrittenLeavesNoLiveVal $context = $this->store()->getContext(); $scanner = new GetTaggedKeys($context); - $reader = m::mock(GetTaggedKeys::class); - $reader->expects('execute')->with('people')->andReturnUsing(fn (): Generator => $scanner->execute('people')); - $reader->expects('execute')->with('artist')->andReturnUsing(function () use ($cache, $scanner): Generator { + $reader = Double::for(GetTaggedKeys::class)->strict(); + $reader->expects('execute')->with('people')->resolves(fn (): Generator => $scanner->execute('people')); + $reader->expects('execute')->with('artist')->resolves(function () use ($cache, $scanner): Generator { // Rewrite the shared key after the first tag's pass, before the second tag is scanned. $cache->forever('person', 'John'); diff --git a/tests/Integration/Concurrency/Console/InvokeSerializedClosureCommandTest.php b/tests/Integration/Concurrency/Console/InvokeSerializedClosureCommandTest.php index 5404af9979..b668017914 100644 --- a/tests/Integration/Concurrency/Console/InvokeSerializedClosureCommandTest.php +++ b/tests/Integration/Concurrency/Console/InvokeSerializedClosureCommandTest.php @@ -12,14 +12,17 @@ use Hypervel\Support\Facades\Artisan; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Concurrency\Fixtures\ConcurrentProcessExceptionFixtures; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Laravel\SerializableClosure\SerializableClosure; -use Mockery as m; use ReflectionMethod; use RuntimeException; use Symfony\Component\Console\Output\BufferedOutput; class InvokeSerializedClosureCommandTest extends TestCase { + use VerifiesDoubles; + private const string KEY = 'test-envelope-key'; public function testItCanInvokeSerializedClosureFromArgument(): void @@ -153,10 +156,9 @@ public function testItTransportsBinaryResultsLosslessly(): void public function testItContainsFailuresFromTheExceptionReporter(): void { - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report') - ->once() - ->andThrow(new RuntimeException('reporting failed')); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report') + ->throws(new RuntimeException('reporting failed')); $this->app->instance(ExceptionHandlerContract::class, $handler); $result = $this->invokeSerializedClosure( diff --git a/tests/Integration/Console/EnvironmentDecryptCommandTest.php b/tests/Integration/Console/EnvironmentDecryptCommandTest.php index 2d0a677b58..f79b4e69a3 100644 --- a/tests/Integration/Console/EnvironmentDecryptCommandTest.php +++ b/tests/Integration/Console/EnvironmentDecryptCommandTest.php @@ -10,12 +10,15 @@ use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Integration\Console\Fixtures\ArrayFilesystem; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Swoole\Coroutine\CanceledException; class EnvironmentDecryptCommandTest extends TestCase { + use VerifiesDoubles; + protected ArrayFilesystem $filesystem; /** @@ -55,16 +58,16 @@ public function testItFailsUsingCipherWithInvalidKey(): void public function testItPreservesCancellationWhileReadingTheEncryptedEnvironment(): void { $cancellation = new CanceledException('canceled'); - $filesystem = m::mock(Filesystem::class); + $filesystem = Double::for(Filesystem::class)->strict(); $filesystem->expects('exists') ->with(base_path('.env.encrypted')) - ->andReturn(true); + ->returns(true); $filesystem->expects('exists') ->with(base_path('.env')) - ->andReturn(false); + ->returns(false); $filesystem->expects('get') ->with(base_path('.env.encrypted')) - ->andThrow($cancellation); + ->throws($cancellation); File::swap($filesystem); try { @@ -428,10 +431,10 @@ public function testExistingEnvironmentFileSurvivesReplacementFailure(): void $files->put($outputFile, $previousContents); chmod($outputFile, 0640); - $filesystem = m::mock(Filesystem::class)->makePartial(); + $filesystem = Double::for(new Filesystem)->passthru(); $filesystem->expects('replace') ->with($outputFile, 'APP_NAME=Hypervel', 0640) - ->andThrow(new RuntimeException('publication failed')); + ->throws(new RuntimeException('publication failed')); File::swap($filesystem); try { diff --git a/tests/Integration/Console/EnvironmentEncryptCommandTest.php b/tests/Integration/Console/EnvironmentEncryptCommandTest.php index 43eee42c46..35509bc2e2 100644 --- a/tests/Integration/Console/EnvironmentEncryptCommandTest.php +++ b/tests/Integration/Console/EnvironmentEncryptCommandTest.php @@ -10,12 +10,16 @@ use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Integration\Console\Fixtures\ArrayFilesystem; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use Swoole\Coroutine\CanceledException; class EnvironmentEncryptCommandTest extends TestCase { + use VerifiesDoubles; + protected ArrayFilesystem $filesystem; /** @@ -53,17 +57,17 @@ public function testItFailsUsingCipherWithInvalidKey(): void public function testItPreservesCancellationWhileReadingTheEnvironment(): void { $cancellation = new CanceledException('canceled'); - $filesystem = m::mock(Filesystem::class); + $filesystem = Double::for(Filesystem::class)->strict(); $filesystem->expects('exists') ->with(base_path('.env')) - ->andReturn(true); + ->returns(true); $filesystem->expects('exists') ->with(base_path('.env.encrypted')) - ->andReturn(false); + ->returns(false); $filesystem->expects('get') ->with(base_path('.env')) - ->andThrow($cancellation); - $filesystem->shouldReceive('replace')->never(); + ->throws($cancellation); + $filesystem->expects('replace')->never(); File::swap($filesystem); try { @@ -382,12 +386,12 @@ public function testItFailsWhenPrunedEnvironmentFileRemains(): void { $environmentFile = base_path('.env'); $encryptedFile = base_path('.env.encrypted'); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('exists')->with($environmentFile)->twice()->andReturn(true, true); - $filesystem->expects('exists')->with($encryptedFile)->andReturnFalse(); - $filesystem->expects('get')->with($environmentFile)->andReturn('APP_NAME=Hypervel'); - $filesystem->expects('replace')->with($encryptedFile, m::type('string'), null); - $filesystem->expects('delete')->with($environmentFile)->andReturnFalse(); + $filesystem = Double::for(Filesystem::class)->strict(); + $filesystem->expects('exists')->with($environmentFile)->times(2)->returns(true, true); + $filesystem->expects('exists')->with($encryptedFile)->returns(false); + $filesystem->expects('get')->with($environmentFile)->returns('APP_NAME=Hypervel'); + $filesystem->expects('replace')->with($encryptedFile, Argument::type('string'), null); + $filesystem->expects('delete')->with($environmentFile)->returns(false); File::swap($filesystem); $this->artisan('env:encrypt', [ @@ -402,12 +406,12 @@ public function testItAcceptsConcurrentDisappearanceWhenPruning(): void { $environmentFile = base_path('.env'); $encryptedFile = base_path('.env.encrypted'); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('exists')->with($environmentFile)->twice()->andReturn(true, false); - $filesystem->expects('exists')->with($encryptedFile)->andReturnFalse(); - $filesystem->expects('get')->with($environmentFile)->andReturn('APP_NAME=Hypervel'); - $filesystem->expects('replace')->with($encryptedFile, m::type('string'), null); - $filesystem->expects('delete')->with($environmentFile)->andReturnFalse(); + $filesystem = Double::for(Filesystem::class)->strict(); + $filesystem->expects('exists')->with($environmentFile)->times(2)->returns(true, false); + $filesystem->expects('exists')->with($encryptedFile)->returns(false); + $filesystem->expects('get')->with($environmentFile)->returns('APP_NAME=Hypervel'); + $filesystem->expects('replace')->with($encryptedFile, Argument::type('string'), null); + $filesystem->expects('delete')->with($environmentFile)->returns(false); File::swap($filesystem); $this->artisan('env:encrypt', [ @@ -432,10 +436,10 @@ public function testExistingEncryptedFileSurvivesReplacementFailure(): void $files->put($encryptedFile, $previousContents); chmod($encryptedFile, 0640); - $filesystem = m::mock(Filesystem::class)->makePartial(); + $filesystem = Double::for(new Filesystem)->passthru(); $filesystem->expects('replace') - ->with($encryptedFile, m::type('string'), 0640) - ->andThrow(new RuntimeException('publication failed')); + ->with($encryptedFile, Argument::type('string'), 0640) + ->throws(new RuntimeException('publication failed')); File::swap($filesystem); try { diff --git a/tests/Integration/Console/JobSchedulingTest.php b/tests/Integration/Console/JobSchedulingTest.php index 901e0dc148..b046fc4c15 100644 --- a/tests/Integration/Console/JobSchedulingTest.php +++ b/tests/Integration/Console/JobSchedulingTest.php @@ -11,10 +11,13 @@ use Hypervel\Support\Facades\Queue; use Hypervel\Support\Testing\Fakes\QueueFake; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class JobSchedulingTest extends TestCase { + use VerifiesDoubles; + public function testJobQueuingRespectsJobQueue(): void { Queue::fake(); @@ -108,9 +111,9 @@ public function testJobQueuingNormalizesIntegerBackedEnumQueueAndConnection(): v public function testJobQueuingRespectsQueueRoutes(): void { // QueueFake ignores connection names, so verify selection separately from its push assertions. - $queue = m::mock(QueueFake::class, [$this->app])->makePartial(); - $queue->shouldReceive('connection')->twice()->with(null)->andReturnSelf(); - $queue->shouldReceive('connection')->once()->with('some-connection')->andReturnSelf(); + $queue = Double::for(new QueueFake($this->app))->passthru(); + $queue->expects('connection')->times(2)->with(null)->returns($queue); + $queue->expects('connection')->with('some-connection')->returns($queue); Queue::swap($queue); Queue::route(JobWithDefaultQueue::class, 'default-queue'); diff --git a/tests/Integration/Console/Scheduling/SchedulePauseCommandTest.php b/tests/Integration/Console/Scheduling/SchedulePauseCommandTest.php index 5d322768d6..d653aa12ff 100644 --- a/tests/Integration/Console/Scheduling/SchedulePauseCommandTest.php +++ b/tests/Integration/Console/Scheduling/SchedulePauseCommandTest.php @@ -10,17 +10,19 @@ use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Support\Facades\Event; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class SchedulePauseCommandTest extends TestCase { + use VerifiesDoubles; + public function testDispatchesEvent(): void { - $cache = m::mock(Cache::class); - $cache->shouldReceive('forever') - ->once() + $cache = Double::for(Cache::class)->strict(); + $cache->expects('forever') ->with('hypervel:schedule:paused', true) - ->andReturnTrue(); + ->returns(true); $this->app->instance(Cache::class, $cache); Event::fake(); @@ -33,8 +35,8 @@ public function testDispatchesEvent(): void public function testFailsWhenPausingIsDisabled(): void { - $cache = m::mock(Cache::class); - $cache->shouldNotReceive('forever'); + $cache = Double::for(Cache::class)->strict(); + $cache->expects('forever')->never(); $this->app->instance(Cache::class, $cache); Event::fake(); @@ -49,11 +51,10 @@ public function testFailsWhenPausingIsDisabled(): void public function testPassiveObserverDoesNotCausePauseSignalToDispatch(): void { - $cache = m::mock(Cache::class); - $cache->shouldReceive('forever') - ->once() + $cache = Double::for(Cache::class)->strict(); + $cache->expects('forever') ->with('hypervel:schedule:paused', true) - ->andReturnTrue(); + ->returns(true); $this->app->instance(Cache::class, $cache); $observedEvents = []; diff --git a/tests/Integration/Console/Scheduling/ScheduleResumeCommandTest.php b/tests/Integration/Console/Scheduling/ScheduleResumeCommandTest.php index e551006064..6eb93b0902 100644 --- a/tests/Integration/Console/Scheduling/ScheduleResumeCommandTest.php +++ b/tests/Integration/Console/Scheduling/ScheduleResumeCommandTest.php @@ -9,17 +9,19 @@ use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Support\Facades\Event; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class ScheduleResumeCommandTest extends TestCase { + use VerifiesDoubles; + public function testDispatchesEvent(): void { - $cache = m::mock(Cache::class); - $cache->shouldReceive('forget') - ->once() + $cache = Double::for(Cache::class)->strict(); + $cache->expects('forget') ->with('hypervel:schedule:paused') - ->andReturnTrue(); + ->returns(true); $this->app->instance(Cache::class, $cache); Event::fake(); @@ -32,11 +34,10 @@ public function testDispatchesEvent(): void public function testPassiveObserverDoesNotCauseResumeSignalToDispatch(): void { - $cache = m::mock(Cache::class); - $cache->shouldReceive('forget') - ->once() + $cache = Double::for(Cache::class)->strict(); + $cache->expects('forget') ->with('hypervel:schedule:paused') - ->andReturnTrue(); + ->returns(true); $this->app->instance(Cache::class, $cache); $observedEvents = []; @@ -54,11 +55,10 @@ static function (ScheduleResumed $event) use (&$observedEvents): void { public function testContinueAliasClearsPauseSignal(): void { - $cache = m::mock(Cache::class); - $cache->shouldReceive('forget') - ->once() + $cache = Double::for(Cache::class)->strict(); + $cache->expects('forget') ->with('hypervel:schedule:paused') - ->andReturnTrue(); + ->returns(true); $this->app->instance(Cache::class, $cache); Event::fake(); diff --git a/tests/Integration/Console/UniqueJobSchedulingTest.php b/tests/Integration/Console/UniqueJobSchedulingTest.php index 0e63954f5a..017ecdacb9 100644 --- a/tests/Integration/Console/UniqueJobSchedulingTest.php +++ b/tests/Integration/Console/UniqueJobSchedulingTest.php @@ -19,12 +19,15 @@ use Hypervel\Support\Facades\Bus; use Hypervel\Support\Facades\Queue; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use UnitEnum; class UniqueJobSchedulingTest extends TestCase { + use VerifiesDoubles; + public function testJobsPushedToQueue(): void { Queue::fake(); @@ -119,10 +122,10 @@ public function testUniqueLockIsReleasedWhenDispatchFailsBeforePayloadCreation() $exception = new RuntimeException('Dispatch failed before payload creation.'); $calls = 0; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch') - ->twice() - ->andReturnUsing(function (UniqueTestJob $job) use (&$calls, $exception): void { + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('dispatch') + ->times(2) + ->resolves(function (UniqueTestJob $job) use (&$calls, $exception): void { $metadata = DispatchLockContext::peekPayloadMetadata($job); $this->assertNotNull($metadata); $this->assertSame(UniqueLock::getKey($job), $metadata['laravel_unique_job_key']); diff --git a/tests/Integration/Database/EloquentModelLoadSumTest.php b/tests/Integration/Database/EloquentModelLoadSumTest.php index 17c4bf1e46..ce723cc64e 100644 --- a/tests/Integration/Database/EloquentModelLoadSumTest.php +++ b/tests/Integration/Database/EloquentModelLoadSumTest.php @@ -12,10 +12,13 @@ use Hypervel\Tests\Database\Fixtures\Models\LoadAggregate\Related1; use Hypervel\Tests\Database\Fixtures\Models\LoadAggregate\Related2; use Hypervel\Tests\Integration\Database\DatabaseTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class EloquentModelLoadSumTest extends DatabaseTestCase { + use VerifiesDoubles; + /** * Set up the database after refreshing it. */ @@ -59,8 +62,8 @@ public function testLoadSumSingleRelation(): void public function testLoadSumWithContractExpression(): void { $model = BaseModel::first(); - $expression = m::mock(Expression::class); - $expression->shouldReceive('getValue')->andReturn('number * 2'); + $expression = Double::for(Expression::class)->strict(); + $expression->allows('getValue')->returns('number * 2'); DB::enableQueryLog(); diff --git a/tests/Integration/Database/EloquentWhereHasMorphTest.php b/tests/Integration/Database/EloquentWhereHasMorphTest.php index 405c56fe4e..bc510b74ca 100644 --- a/tests/Integration/Database/EloquentWhereHasMorphTest.php +++ b/tests/Integration/Database/EloquentWhereHasMorphTest.php @@ -14,11 +14,14 @@ use Hypervel\Database\Schema\Blueprint; use Hypervel\Support\Facades\Schema; use Hypervel\Tests\Integration\Database\DatabaseTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class EloquentWhereHasMorphTest extends DatabaseTestCase { + use VerifiesDoubles; + protected function afterRefreshingDatabase(): void { Schema::create('posts', function (Blueprint $table) { @@ -113,9 +116,9 @@ public function testWhereHasMorphWithWildcardCountComparisons(string $operator, $this->assertSame($zeroIds, Comment::whereHasMorph('commentable', '*', null, $operator, new Expression('0')) ->orderBy('id')->pluck('id')->all()); - $count = m::mock(ExpressionContract::class); + $count = Double::for(ExpressionContract::class)->strict(); // Decimal subtraction avoids unsigned integer underflow on MySQL and MariaDB. - $count->shouldReceive('getValue')->andReturn('comments.id - 7.0'); + $count->allows('getValue')->returns('comments.id - 7.0'); $query = Comment::whereHasMorph('commentable', '*', null, $operator, $count)->orderBy('id'); diff --git a/tests/Integration/Database/PooledConnectionTest.php b/tests/Integration/Database/PooledConnectionTest.php index 642292b15c..8fee1a3a88 100644 --- a/tests/Integration/Database/PooledConnectionTest.php +++ b/tests/Integration/Database/PooledConnectionTest.php @@ -30,7 +30,8 @@ use Hypervel\Support\Facades\Event; use Hypervel\Testing\ParallelTesting; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; @@ -48,6 +49,8 @@ */ class PooledConnectionTest extends DatabaseTestCase { + use VerifiesDoubles; + protected function defineEnvironment(ApplicationContract $app): void { parent::defineEnvironment($app); @@ -1009,8 +1012,8 @@ public function testReleasePreservesCleanupFailurePrecedence(bool $releaseCancel $listenerFailure = new RuntimeException('Release listener failed.'); $loggingFailure = new RuntimeException('Release failure logging failed.'); $poolReleaseFailure = new RuntimeException('Pool release failed.', previous: $releaseCanceled ? new CanceledException : null); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('error')->once()->andThrow($loggingFailure); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('error')->throws($loggingFailure); $this->app->instance(StdoutLoggerInterface::class, $logger); $this->app->make(Dispatcher::class)->listen( ConnectionReleasing::class, @@ -1043,8 +1046,8 @@ public function testRawTransactionIsDiscardedDespiteCleanupFailure(bool $cancel) : new RuntimeException('Transaction logging failed.'); if (! $cancel) { - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('error')->once()->andThrow($failure); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('error')->throws($failure); $this->app->instance(StdoutLoggerInterface::class, $logger); } @@ -1428,7 +1431,7 @@ public function testPingCancellationStopsTheHeartbeatChildAndEscapesExactly(): v public function testPingCancellationDuringStartupReportingStopsThePublishedHeartbeatChild(): void { - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); $this->app->instance(ExceptionHandlerContract::class, $handler); $pool = new DatabasePool($this->app, 'pool_test'); $pooledConnection = $this->createPooledConnection($pool); @@ -1443,10 +1446,9 @@ public function testPingCancellationDuringStartupReportingStopsThePublishedHeart $parentCancellation = null; $childCoroutineId = null; - $handler->shouldReceive('report') - ->once() + $handler->expects('report') ->with($hookFailure) - ->andReturnUsing(static function () use ($reportStarted, $releaseReport, $cleanupStarted, $releaseCleanup, &$childCoroutineId): void { + ->resolves(static function () use ($reportStarted, $releaseReport, $cleanupStarted, $releaseCleanup, &$childCoroutineId): void { $childCoroutineId = EngineCoroutine::id(); $reportStarted->push(true); @@ -1512,8 +1514,8 @@ public function testPingTimeoutWaitsForHeartbeatCleanupBeforeReturningFalse(): v $releaseCleanup = new Channel(1); $childCoroutineId = null; $result = null; - $connection = m::mock(NeutralPoolConnection::class); - $connection->shouldReceive('ping')->once()->andReturnUsing(static function () use ($blocker, $cleanupStarted, $releaseCleanup, &$childCoroutineId): bool { + $connection = Double::for(NeutralPoolConnection::class)->strict(); + $connection->expects('ping')->resolves(static function () use ($blocker, $cleanupStarted, $releaseCleanup, &$childCoroutineId): bool { $childCoroutineId = EngineCoroutine::id(); try { diff --git a/tests/Integration/Database/Sqlite/DatabasePoolHeartbeatTest.php b/tests/Integration/Database/Sqlite/DatabasePoolHeartbeatTest.php index 0222f0ea48..f348b21212 100644 --- a/tests/Integration/Database/Sqlite/DatabasePoolHeartbeatTest.php +++ b/tests/Integration/Database/Sqlite/DatabasePoolHeartbeatTest.php @@ -21,7 +21,8 @@ use Hypervel\Support\ClassInvoker; use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Psr\Log\AbstractLogger; use ReflectionProperty; @@ -34,6 +35,8 @@ class DatabasePoolHeartbeatTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; protected string $databasePath; @@ -111,8 +114,8 @@ public function testHeartbeatStartupCanBeRetriedAfterTimerCreationFails(): void $property = new ReflectionProperty(DatabasePool::class, 'heartbeatTimer'); $timer = $property->getValue($pool); $failure = new RuntimeException('Timer creation failed.'); - $failingTimer = m::mock(Timer::class); - $failingTimer->shouldReceive('tick')->once()->andThrow($failure); + $failingTimer = Double::for(Timer::class)->strict(); + $failingTimer->expects('tick')->throws($failure); $property->setValue($pool, $failingTimer); $caught = null; @@ -492,12 +495,12 @@ public function testHeartbeatCancellationDisposesOnceAndLeavesLaterIdleConnectio $secondary = $path === 'evaluation with failed close' ? new RuntimeException('close failed') : new CanceledException('secondary close cancellation'); - $logger = m::mock(StdoutLoggerInterface::class); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); if ($path === 'evaluation with failed close') { - $logger->shouldReceive('error')->once()->with((string) $secondary); + $logger->expects('error')->with((string) $secondary); } else { - $logger->shouldNotReceive('error'); + $logger->expects('error')->never(); } $this->app->instance(StdoutLoggerInterface::class, $logger); diff --git a/tests/Integration/Database/Sqlite/InMemorySqliteSharedPdoTest.php b/tests/Integration/Database/Sqlite/InMemorySqliteSharedPdoTest.php index e3cf10046a..05fa7beeb0 100644 --- a/tests/Integration/Database/Sqlite/InMemorySqliteSharedPdoTest.php +++ b/tests/Integration/Database/Sqlite/InMemorySqliteSharedPdoTest.php @@ -14,7 +14,8 @@ use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; @@ -29,6 +30,8 @@ */ class InMemorySqliteSharedPdoTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; protected function setUp(): void @@ -365,12 +368,10 @@ public function testCloseClearsSharedPdo(): void public function testCanceledCloseClearsSharedPdo(): void { $cancellation = new CanceledException('connection close canceled'); - $connection = m::mock(PoolConnection::class); - $connection->shouldReceive('close')->once()->andThrow($cancellation); - $pool = m::mock(DatabasePool::class, [$this->app, 'memory_test']) - ->makePartial() - ->shouldAllowMockingProtectedMethods(); - $pool->shouldReceive('createConnection')->once()->andReturn($connection); + $connection = Double::for(PoolConnection::class)->strict(); + $connection->expects('close')->throws($cancellation); + $pool = Double::for(new DatabasePool($this->app, 'memory_test'))->passthru(); + $pool->expects('createConnection')->returns($connection); $pool->release($pool->borrow()); $caught = null; diff --git a/tests/Integration/Filesystem/ReceiveFileTest.php b/tests/Integration/Filesystem/ReceiveFileTest.php index 10f7a5065e..c21e1ee2e4 100644 --- a/tests/Integration/Filesystem/ReceiveFileTest.php +++ b/tests/Integration/Filesystem/ReceiveFileTest.php @@ -9,13 +9,16 @@ use Hypervel\Support\Facades\Storage; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\RequiresOperatingSystem; #[RequiresOperatingSystem('Linux|Darwin')] #[WithConfig('filesystems.disks.local.serve', true)] class ReceiveFileTest extends TestCase { + use VerifiesDoubles; + /** * Set up the test environment. */ @@ -97,8 +100,8 @@ public function testScopedDiskUploadsThroughItsServedParentRoute(): void public function testStorageFailureReturnsServerError(): void { $result = Storage::temporaryUploadUrl('receive-file-test.txt', now()->addMinute()); - $disk = m::mock(Filesystem::class); - $disk->shouldReceive('put')->once()->with('receive-file-test.txt', 'Hello World')->andReturnFalse(); + $disk = Double::for(Filesystem::class)->strict(); + $disk->expects('put')->with('receive-file-test.txt', 'Hello World')->returns(false); $manager = Storage::getFacadeRoot(); try { diff --git a/tests/Integration/Foundation/Console/ApiInstallCommandTest.php b/tests/Integration/Foundation/Console/ApiInstallCommandTest.php index a96af49695..40315568d6 100644 --- a/tests/Integration/Foundation/Console/ApiInstallCommandTest.php +++ b/tests/Integration/Foundation/Console/ApiInstallCommandTest.php @@ -12,7 +12,9 @@ use Hypervel\Support\Facades\Process; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Testing\Fixtures\CleanupActions; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use ReflectionClass; use RuntimeException; @@ -22,6 +24,8 @@ class ApiInstallCommandTest extends \Hypervel\Testbench\TestCase { + use VerifiesDoubles; + /** * Original bootstrap/app.php content to restore after each test. */ @@ -397,9 +401,9 @@ public function testApiRouteSourceReadFailurePreservesExistingRouteAndReportsNoS $this->createdFiles[] = $apiRoutesPath; file_put_contents($apiRoutesPath, 'existing route'); $source = dirname((new ReflectionClass(ApiInstallCommand::class))->getFileName()) . '/stubs/api-routes.stub'; - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $readException = new FileNotFoundException("File does not exist at path [{$source}]."); - $files->shouldReceive('get')->once()->with($source)->andThrow($readException); + $files->expects('get')->with($source)->throws($readException); $this->app->instance('files', $files); $tester = $this->commandTester(new TestableApiInstallCommand); @@ -423,12 +427,11 @@ public function testApiRouteReplacementFailurePreservesExistingRouteAndReportsNo $this->createdFiles[] = $apiRoutesPath; file_put_contents($apiRoutesPath, 'existing route'); chmod($apiRoutesPath, 0640); - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $publicationException = new RuntimeException('Unable to publish API route file.'); - $files->shouldReceive('replace') - ->once() - ->with($apiRoutesPath, m::type('string'), 0640) - ->andThrow($publicationException); + $files->expects('replace') + ->with($apiRoutesPath, Argument::type('string'), 0640) + ->throws($publicationException); $this->app->instance('files', $files); $tester = $this->commandTester(new TestableApiInstallCommand); @@ -452,9 +455,9 @@ public function testBootstrapReadFailureReportsNoRouteOrInstallationSuccess(): v $apiRoutesPath = $this->app->basePath('routes/api.php'); $bootstrapPath = $this->app->bootstrapPath('app.php'); $this->createdFiles[] = $apiRoutesPath; - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $readException = new FileNotFoundException("File does not exist at path [{$bootstrapPath}]."); - $files->shouldReceive('get')->with($bootstrapPath)->once()->andThrow($readException); + $files->allows('get')->with($bootstrapPath)->throws($readException); $this->app->instance('files', $files); $tester = $this->commandTester(new TestableApiInstallCommand); @@ -479,13 +482,11 @@ public function testBootstrapReplacementFailurePreservesTheExistingApplicationBo $bootstrapContent = file_get_contents($bootstrapPath); $bootstrapPermissions = fileperms($bootstrapPath) & 0777; $this->createdFiles[] = $apiRoutesPath; - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $publicationException = new RuntimeException('Unable to update the application bootstrap file.'); - $files->shouldReceive('replace')->byDefault()->passthru(); - $files->shouldReceive('replace') - ->once() - ->with($bootstrapPath, m::type('string'), $bootstrapPermissions) - ->andThrow($publicationException); + $files->allows('replace') + ->with($bootstrapPath, Argument::type('string'), $bootstrapPermissions) + ->throws($publicationException); $this->app->instance('files', $files); $tester = $this->commandTester(new TestableApiInstallCommand); diff --git a/tests/Integration/Foundation/Console/BroadcastingInstallCommandTest.php b/tests/Integration/Foundation/Console/BroadcastingInstallCommandTest.php index d63845f012..8aa739411f 100644 --- a/tests/Integration/Foundation/Console/BroadcastingInstallCommandTest.php +++ b/tests/Integration/Foundation/Console/BroadcastingInstallCommandTest.php @@ -14,8 +14,10 @@ use Hypervel\Support\Facades\ParallelTesting; use Hypervel\Support\Facades\Process; use Hypervel\Tests\Testing\Fixtures\CleanupActions; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use JsonException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use ReflectionClass; @@ -27,6 +29,8 @@ class BroadcastingInstallCommandTest extends \Hypervel\Testbench\TestCase { + use VerifiesDoubles; + /** * Original bootstrap/app.php content to restore after each test. */ @@ -527,9 +531,9 @@ public function testChannelsSourceReadFailurePreservesExistingRouteAndReportsNoS file_put_contents($channelsPath, 'existing route'); $source = dirname((new ReflectionClass(BroadcastingInstallCommand::class))->getFileName()) . '/stubs/broadcasting-routes.stub'; - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $readException = new FileNotFoundException("File does not exist at path [{$source}]."); - $files->shouldReceive('get')->once()->with($source)->andThrow($readException); + $files->expects('get')->with($source)->throws($readException); $this->app->instance('files', $files); $tester = $this->commandTester(new TestableBroadcastingInstallCommand); @@ -557,13 +561,11 @@ public function testChannelsReplacementFailurePreservesExistingRouteAndReportsNo $this->createdFiles[] = $channelsPath; file_put_contents($channelsPath, 'existing route'); chmod($channelsPath, 0640); - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $publicationException = new RuntimeException('Unable to publish broadcasting route file.'); - $files->shouldReceive('replace')->byDefault()->passthru(); - $files->shouldReceive('replace') - ->once() - ->with($channelsPath, m::type('string'), 0640) - ->andThrow($publicationException); + $files->allows('replace') + ->with($channelsPath, Argument::type('string'), 0640) + ->throws($publicationException); $this->app->instance('files', $files); $tester = $this->commandTester(new TestableBroadcastingInstallCommand); @@ -595,9 +597,9 @@ public function testBootstrapReadFailureStopsBeforeEnvironmentAndJavaScriptChang $originalAppJs = file_get_contents($appJsPath); $originalEnv = file_get_contents($envPath); $this->createdFiles[] = $channelsPath; - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $readException = new FileNotFoundException("File does not exist at path [{$bootstrapPath}]."); - $files->shouldReceive('get')->once()->with($bootstrapPath)->andThrow($readException); + $files->allows('get')->with($bootstrapPath)->throws($readException); $this->app->instance('files', $files); $tester = $this->commandTester(new TestableBroadcastingInstallCommand); @@ -626,13 +628,11 @@ public function testBootstrapReplacementFailurePreservesTheExistingApplicationBo $appJsContent = file_get_contents($appJsPath); $envContent = file_get_contents($envPath); $this->createdFiles[] = $channelsPath; - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $publicationException = new RuntimeException('Unable to update the application bootstrap file.'); - $files->shouldReceive('replace')->byDefault()->passthru(); - $files->shouldReceive('replace') - ->once() - ->with($bootstrapPath, m::type('string'), $bootstrapPermissions) - ->andThrow($publicationException); + $files->allows('replace') + ->with($bootstrapPath, Argument::type('string'), $bootstrapPermissions) + ->throws($publicationException); $this->app->instance('files', $files); $tester = $this->commandTester(new TestableBroadcastingInstallCommand); @@ -663,9 +663,9 @@ public function testEchoStubReadFailureDoesNotCreateEchoScript(): void . '/stubs/echo-js-reverb.stub'; $this->createdFiles[] = $channelsPath; $this->createdFiles[] = $echoPath; - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $readException = new FileNotFoundException("File does not exist at path [{$source}]."); - $files->shouldReceive('get')->once()->with($source)->andThrow($readException); + $files->allows('get')->with($source)->throws($readException); $this->app->instance('files', $files); $tester = $this->commandTester(new TestableBroadcastingInstallCommand); @@ -690,13 +690,11 @@ public function testAppScriptReplacementFailurePreservesExistingScript(): void $this->createdFiles[] = $echoPath; file_put_contents($appJsPath, '// existing app script' . PHP_EOL); chmod($appJsPath, 0640); - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $publicationException = new RuntimeException('Unable to update application script.'); - $files->shouldReceive('replace')->byDefault()->passthru(); - $files->shouldReceive('replace') - ->once() - ->with($appJsPath, m::type('string'), 0640) - ->andThrow($publicationException); + $files->allows('replace') + ->with($appJsPath, Argument::type('string'), 0640) + ->throws($publicationException); $this->app->instance('files', $files); $tester = $this->commandTester(new TestableBroadcastingInstallCommand); diff --git a/tests/Integration/Foundation/Console/ConfigClearCommandTest.php b/tests/Integration/Foundation/Console/ConfigClearCommandTest.php index f9ed37c9d8..3e01a4b7be 100644 --- a/tests/Integration/Foundation/Console/ConfigClearCommandTest.php +++ b/tests/Integration/Foundation/Console/ConfigClearCommandTest.php @@ -6,11 +6,14 @@ use Hypervel\Filesystem\Filesystem; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class ConfigClearCommandTest extends TestCase { + use VerifiesDoubles; + protected function tearDown(): void { @unlink($this->app->getCachedConfigPath()); @@ -34,9 +37,9 @@ public function testConfigClearCommandDeletesCacheFile(): void public function testConfigClearCommandFailsWhenCacheFileRemains(): void { $path = $this->app->getCachedConfigPath(); - $files = m::mock(Filesystem::class); - $files->shouldReceive('delete')->once()->with($path)->andReturnFalse(); - $files->shouldReceive('exists')->once()->with($path)->andReturnTrue(); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('delete')->with($path)->returns(false); + $files->expects('exists')->with($path)->returns(true); $this->app->instance(Filesystem::class, $files); $this->expectException(RuntimeException::class); @@ -48,9 +51,9 @@ public function testConfigClearCommandFailsWhenCacheFileRemains(): void public function testConfigClearCommandSucceedsWhenCacheDisappearsConcurrently(): void { $path = $this->app->getCachedConfigPath(); - $files = m::mock(Filesystem::class); - $files->shouldReceive('delete')->once()->with($path)->andReturnFalse(); - $files->shouldReceive('exists')->once()->with($path)->andReturnFalse(); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('delete')->with($path)->returns(false); + $files->expects('exists')->with($path)->returns(false); $this->app->instance(Filesystem::class, $files); $this->artisan('config:clear') diff --git a/tests/Integration/Foundation/Console/ConfigPublishCommandTest.php b/tests/Integration/Foundation/Console/ConfigPublishCommandTest.php index d47e3eb09b..61f5cca067 100644 --- a/tests/Integration/Foundation/Console/ConfigPublishCommandTest.php +++ b/tests/Integration/Foundation/Console/ConfigPublishCommandTest.php @@ -9,7 +9,9 @@ use Hypervel\Foundation\Bootstrap\LoadConfiguration; use Hypervel\Foundation\Console\ConfigPublishCommand; use Hypervel\Testbench\Concerns\InteractsWithPublishedFiles; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use Symfony\Component\Console\Application as ConsoleApplication; use Symfony\Component\Console\Tester\CommandTester; @@ -18,6 +20,7 @@ class ConfigPublishCommandTest extends \Hypervel\Testbench\TestCase { use InteractsWithPublishedFiles; + use VerifiesDoubles; protected array $files = []; @@ -177,9 +180,9 @@ public function testSourceReadFailurePreservesExistingDestinationAndReportsNoSuc $this->preserveConfigFile($name); file_put_contents($destination, 'existing destination'); - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $readException = new FileNotFoundException("File does not exist at path [{$source}]."); - $files->shouldReceive('get')->once()->with($source)->andThrow($readException); + $files->expects('get')->with($source)->throws($readException); $this->app->instance('files', $files); $tester = $this->commandTester(); @@ -203,12 +206,11 @@ public function testReplacementFailurePreservesExistingDestinationAndReportsNoSu file_put_contents($destination, 'existing destination'); chmod($destination, 0640); - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $publicationException = new RuntimeException('Unable to publish configuration file.'); - $files->shouldReceive('replace') - ->once() - ->with($destination, m::type('string'), 0640) - ->andThrow($publicationException); + $files->expects('replace') + ->with($destination, Argument::type('string'), 0640) + ->throws($publicationException); $this->app->instance('files', $files); $tester = $this->commandTester(); diff --git a/tests/Integration/Foundation/Console/EventClearCommandTest.php b/tests/Integration/Foundation/Console/EventClearCommandTest.php index d199e97703..e2d370eecf 100644 --- a/tests/Integration/Foundation/Console/EventClearCommandTest.php +++ b/tests/Integration/Foundation/Console/EventClearCommandTest.php @@ -6,11 +6,14 @@ use Hypervel\Filesystem\Filesystem; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class EventClearCommandTest extends TestCase { + use VerifiesDoubles; + protected function tearDown(): void { @unlink($this->app->getCachedEventsPath()); @@ -56,9 +59,9 @@ public function testEventsClearCommandSucceedsWhenNoCacheExists(): void public function testEventsClearCommandFailsWhenCacheFileRemains(): void { $path = $this->app->getCachedEventsPath(); - $files = m::mock(Filesystem::class); - $files->shouldReceive('delete')->once()->with($path)->andReturnFalse(); - $files->shouldReceive('exists')->once()->with($path)->andReturnTrue(); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('delete')->with($path)->returns(false); + $files->expects('exists')->with($path)->returns(true); $this->app->instance(Filesystem::class, $files); $this->expectException(RuntimeException::class); @@ -70,9 +73,9 @@ public function testEventsClearCommandFailsWhenCacheFileRemains(): void public function testEventsClearCommandSucceedsWhenCacheDisappearsConcurrently(): void { $path = $this->app->getCachedEventsPath(); - $files = m::mock(Filesystem::class); - $files->shouldReceive('delete')->once()->with($path)->andReturnFalse(); - $files->shouldReceive('exists')->once()->with($path)->andReturnFalse(); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('delete')->with($path)->returns(false); + $files->expects('exists')->with($path)->returns(false); $this->app->instance(Filesystem::class, $files); $this->artisan('event:clear') diff --git a/tests/Integration/Foundation/Console/LangPublishCommandTest.php b/tests/Integration/Foundation/Console/LangPublishCommandTest.php index 340af02220..cdd6cd726b 100644 --- a/tests/Integration/Foundation/Console/LangPublishCommandTest.php +++ b/tests/Integration/Foundation/Console/LangPublishCommandTest.php @@ -8,7 +8,9 @@ use Hypervel\Filesystem\Filesystem; use Hypervel\Foundation\Console\LangPublishCommand; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionClass; use RuntimeException; use Symfony\Component\Console\Application as ConsoleApplication; @@ -16,6 +18,8 @@ class LangPublishCommandTest extends TestCase { + use VerifiesDoubles; + protected Filesystem $filesystem; protected string $langPath; @@ -89,9 +93,9 @@ public function testSourceReadFailurePreservesExistingDestinationAndReportsNoSuc $source = dirname((new ReflectionClass(LangPublishCommand::class))->getFileName()) . '/../../../translation/lang/en/auth.php'; - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $readException = new FileNotFoundException("File does not exist at path [{$source}]."); - $files->shouldReceive('get')->once()->with($source)->andThrow($readException); + $files->expects('get')->with($source)->throws($readException); $this->app->instance('files', $files); $tester = $this->commandTester(); @@ -113,12 +117,11 @@ public function testReplacementFailurePreservesExistingDestinationAndReportsNoSu $this->filesystem->put($destination, 'existing contents'); chmod($destination, 0640); - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $publicationException = new RuntimeException('Unable to publish language file.'); - $files->shouldReceive('replace') - ->once() - ->with($destination, m::type('string'), 0640) - ->andThrow($publicationException); + $files->expects('replace') + ->with($destination, Argument::type('string'), 0640) + ->throws($publicationException); $this->app->instance('files', $files); $tester = $this->commandTester(); diff --git a/tests/Integration/Foundation/Console/RouteClearCommandTest.php b/tests/Integration/Foundation/Console/RouteClearCommandTest.php index 7327d24727..b6b4f0e6ba 100644 --- a/tests/Integration/Foundation/Console/RouteClearCommandTest.php +++ b/tests/Integration/Foundation/Console/RouteClearCommandTest.php @@ -6,11 +6,14 @@ use Hypervel\Filesystem\Filesystem; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class RouteClearCommandTest extends TestCase { + use VerifiesDoubles; + protected function tearDown(): void { @unlink($this->app->getCachedRoutesPath()); @@ -34,9 +37,9 @@ public function testRouteClearCommandDeletesCacheFile(): void public function testRouteClearCommandFailsWhenCacheFileRemains(): void { $path = $this->app->getCachedRoutesPath(); - $files = m::mock(Filesystem::class); - $files->shouldReceive('delete')->once()->with($path)->andReturnFalse(); - $files->shouldReceive('exists')->once()->with($path)->andReturnTrue(); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('delete')->with($path)->returns(false); + $files->expects('exists')->with($path)->returns(true); $this->app->instance(Filesystem::class, $files); $this->expectException(RuntimeException::class); @@ -48,9 +51,9 @@ public function testRouteClearCommandFailsWhenCacheFileRemains(): void public function testRouteClearCommandSucceedsWhenCacheDisappearsConcurrently(): void { $path = $this->app->getCachedRoutesPath(); - $files = m::mock(Filesystem::class); - $files->shouldReceive('delete')->once()->with($path)->andReturnFalse(); - $files->shouldReceive('exists')->once()->with($path)->andReturnFalse(); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('delete')->with($path)->returns(false); + $files->expects('exists')->with($path)->returns(false); $this->app->instance(Filesystem::class, $files); $this->artisan('route:clear') diff --git a/tests/Integration/Foundation/Console/StorageCommandTest.php b/tests/Integration/Foundation/Console/StorageCommandTest.php index 39e62f4b74..4948364a1e 100644 --- a/tests/Integration/Foundation/Console/StorageCommandTest.php +++ b/tests/Integration/Foundation/Console/StorageCommandTest.php @@ -6,11 +6,14 @@ use Hypervel\Filesystem\Filesystem; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class StorageCommandTest extends TestCase { + use VerifiesDoubles; + protected Filesystem $files; protected function setUp(): void @@ -111,8 +114,8 @@ public function testStorageLinkFailsWhenForcedLinkRemovalLeavesTheLink(): void symlink($target, $link); - $files = m::mock(Filesystem::class); - $files->shouldReceive('delete')->once()->with($link)->andReturnFalse(); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('delete')->with($link)->returns(false); $this->app->instance('files', $files); $this->expectException(RuntimeException::class); @@ -128,8 +131,8 @@ public function testStorageLinkAcceptsConcurrentDisappearanceDuringForcedRemoval symlink($target, $link); - $files = m::mock(Filesystem::class)->makePartial(); - $files->shouldReceive('delete')->once()->with($link)->andReturnUsing(function () use ($link): bool { + $files = Double::for(new Filesystem)->passthru(); + $files->expects('delete')->with($link)->resolves(function () use ($link): bool { unlink($link); return false; @@ -147,8 +150,8 @@ public function testStorageLinkFailsWhenNativeLinkCreationReturnsFalse(): void { $link = $this->app->publicPath('storage'); $target = $this->app->storagePath('app/public'); - $files = m::mock(Filesystem::class); - $files->shouldReceive('link')->once()->with($target, $link)->andReturnFalse(); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('link')->with($target, $link)->returns(false); $this->app->instance('files', $files); $this->expectException(RuntimeException::class); @@ -161,11 +164,10 @@ public function testStorageLinkAcceptsWindowsCompatibleNullAfterCreation(): void { $link = $this->app->publicPath('storage'); $target = $this->app->storagePath('app/public'); - $files = m::mock(Filesystem::class); - $files->shouldReceive('link') - ->once() + $files = Double::for(Filesystem::class)->strict(); + $files->expects('link') ->with($target, $link) - ->andReturnUsing(function () use ($target, $link): ?bool { + ->resolves(function () use ($target, $link): ?bool { symlink($target, $link); return null; @@ -183,8 +185,8 @@ public function testStorageLinkFailsWhenCreationDoesNotEstablishTheLink(): void { $link = $this->app->publicPath('storage'); $target = $this->app->storagePath('app/public'); - $files = m::mock(Filesystem::class); - $files->shouldReceive('link')->once()->with($target, $link)->andReturnTrue(); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('link')->with($target, $link)->returns(true); $this->app->instance('files', $files); $this->expectException(RuntimeException::class); @@ -224,8 +226,8 @@ public function testStorageUnlinkFailsWhenLinkRemains(): void symlink($this->app->storagePath('missing'), $link); - $files = m::mock(Filesystem::class); - $files->shouldReceive('delete')->once()->with($link)->andReturnFalse(); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('delete')->with($link)->returns(false); $this->app->instance('files', $files); $this->expectException(RuntimeException::class); @@ -240,8 +242,8 @@ public function testStorageUnlinkAcceptsConcurrentDisappearance(): void symlink($this->app->storagePath('missing'), $link); - $files = m::mock(Filesystem::class); - $files->shouldReceive('delete')->once()->with($link)->andReturnUsing(function () use ($link): bool { + $files = Double::for(Filesystem::class)->strict(); + $files->expects('delete')->with($link)->resolves(function () use ($link): bool { unlink($link); return false; diff --git a/tests/Integration/Foundation/Console/StubPublishCommandTest.php b/tests/Integration/Foundation/Console/StubPublishCommandTest.php index 508dcafa79..fea09a26d4 100644 --- a/tests/Integration/Foundation/Console/StubPublishCommandTest.php +++ b/tests/Integration/Foundation/Console/StubPublishCommandTest.php @@ -10,7 +10,9 @@ use Hypervel\Foundation\Console\StubPublishCommand; use Hypervel\Foundation\Events\PublishingStubs; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionClass; use RuntimeException; use Symfony\Component\Console\Application as ConsoleApplication; @@ -18,6 +20,8 @@ class StubPublishCommandTest extends TestCase { + use VerifiesDoubles; + protected Filesystem $filesystem; protected string $stubsPath; @@ -115,9 +119,9 @@ public function testSourceReadFailurePreservesExistingDestinationAndReportsNoSuc $destination = $this->stubsPath . '/class.stub'; $this->filesystem->put($destination, 'existing contents'); - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $readException = new FileNotFoundException("File does not exist at path [{$this->source}]."); - $files->shouldReceive('get')->once()->with($this->source)->andThrow($readException); + $files->expects('get')->with($this->source)->throws($readException); $this->app->instance('files', $files); $tester = $this->commandTester(); @@ -139,12 +143,11 @@ public function testReplacementFailurePreservesExistingDestinationAndReportsNoSu $this->filesystem->put($destination, 'existing contents'); chmod($destination, 0640); - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $publicationException = new RuntimeException('Unable to publish stub.'); - $files->shouldReceive('replace') - ->once() - ->with($destination, m::type('string'), 0640) - ->andThrow($publicationException); + $files->expects('replace') + ->with($destination, Argument::type('string'), 0640) + ->throws($publicationException); $this->app->instance('files', $files); $tester = $this->commandTester(); diff --git a/tests/Integration/Foundation/Console/ViewClearCommandTest.php b/tests/Integration/Foundation/Console/ViewClearCommandTest.php index bc9ad06829..a22fa09588 100644 --- a/tests/Integration/Foundation/Console/ViewClearCommandTest.php +++ b/tests/Integration/Foundation/Console/ViewClearCommandTest.php @@ -8,11 +8,14 @@ use Hypervel\Support\Facades\Blade; use Hypervel\Testbench\TestCase; use Hypervel\View\Component; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class ViewClearCommandTest extends TestCase { + use VerifiesDoubles; + protected string $compiledPath; protected function setUp(): void @@ -66,11 +69,10 @@ public function testViewClearCommandAllowsInlineViewsToBeRenderedAgainInTheSameP public function testViewClearCommandFailsWhenCompiledViewsCannotBeEnumerated(): void { - $files = m::mock(Filesystem::class); - $files->shouldReceive('glob') - ->once() + $files = Double::for(Filesystem::class)->strict(); + $files->expects('glob') ->with($this->compiledPath . '/*') - ->andReturnFalse(); + ->returns(false); $this->app->instance(Filesystem::class, $files); $this->expectException(RuntimeException::class); @@ -84,16 +86,15 @@ public function testViewClearCommandAttemptsEveryEntryAndPreservesTheEarliestFai $first = $this->compiledPath . '/first.php'; $second = $this->compiledPath . '/second.php'; $exception = new RuntimeException('first deletion failed'); - $files = m::mock(Filesystem::class); - $files->shouldReceive('glob') - ->once() + $files = Double::for(Filesystem::class)->strict(); + $files->expects('glob') ->with($this->compiledPath . '/*') - ->andReturn([$first, $second]); - $files->shouldReceive('isDirectory')->once()->with($first)->andReturnFalse(); - $files->shouldReceive('delete')->once()->with($first)->andThrow($exception); - $files->shouldReceive('isDirectory')->once()->with($second)->andReturnFalse(); - $files->shouldReceive('delete')->once()->with($second)->andReturnFalse(); - $files->shouldReceive('exists')->once()->with($second)->andReturnTrue(); + ->returns([$first, $second]); + $files->expects('isDirectory')->with($first)->returns(false); + $files->expects('delete')->with($first)->throws($exception); + $files->expects('isDirectory')->with($second)->returns(false); + $files->expects('delete')->with($second)->returns(false); + $files->expects('exists')->with($second)->returns(true); $this->app->instance(Filesystem::class, $files); $this->expectExceptionObject($exception); @@ -116,10 +117,10 @@ public function testViewClearCommandFlushesInProcessCachesBeforeRethrowingDeleti $view = $this->compiledPath . '/view.php'; $exception = new RuntimeException('deletion failed'); - $files = m::mock(Filesystem::class); - $files->shouldReceive('glob')->once()->with($this->compiledPath . '/*')->andReturn([$view]); - $files->shouldReceive('isDirectory')->once()->with($view)->andReturnFalse(); - $files->shouldReceive('delete')->once()->with($view)->andThrow($exception); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('glob')->with($this->compiledPath . '/*')->returns([$view]); + $files->expects('isDirectory')->with($view)->returns(false); + $files->expects('delete')->with($view)->throws($exception); $this->app->instance(Filesystem::class, $files); $caught = null; @@ -138,14 +139,13 @@ public function testViewClearCommandFlushesInProcessCachesBeforeRethrowingDeleti public function testViewClearCommandAcceptsConcurrentDisappearance(): void { $view = $this->compiledPath . '/view.php'; - $files = m::mock(Filesystem::class); - $files->shouldReceive('glob') - ->once() + $files = Double::for(Filesystem::class)->strict(); + $files->expects('glob') ->with($this->compiledPath . '/*') - ->andReturn([$view]); - $files->shouldReceive('isDirectory')->once()->with($view)->andReturnFalse(); - $files->shouldReceive('delete')->once()->with($view)->andReturnFalse(); - $files->shouldReceive('exists')->once()->with($view)->andReturnFalse(); + ->returns([$view]); + $files->expects('isDirectory')->with($view)->returns(false); + $files->expects('delete')->with($view)->returns(false); + $files->expects('exists')->with($view)->returns(false); $this->app->instance(Filesystem::class, $files); $this->artisan('view:clear') diff --git a/tests/Integration/Foundation/Exceptions/RenderBladeFilesTest.php b/tests/Integration/Foundation/Exceptions/RenderBladeFilesTest.php index c01472673b..0f5099674a 100644 --- a/tests/Integration/Foundation/Exceptions/RenderBladeFilesTest.php +++ b/tests/Integration/Foundation/Exceptions/RenderBladeFilesTest.php @@ -15,7 +15,8 @@ use Hypervel\View\Engines\CompilerEngine; use Hypervel\View\Engines\EngineResolver; use Hypervel\View\ViewException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use ReflectionMethod; use RuntimeException; @@ -29,6 +30,8 @@ #[WithConfig('app.debug', true)] class RenderBladeFilesTest extends TestCase { + use VerifiesDoubles; + /** * Define the test environment. */ @@ -202,8 +205,8 @@ public function testBladeMapperPreservesCancellationDuringSourceMapping(bool $th { $cancellation = new CanceledException('canceled'); $cancellation = $throwingCleanup ? new RuntimeException('cleanup failed', 0, $cancellation) : $cancellation; - $compiler = m::mock(BladeCompiler::class); - $compiler->shouldReceive('compileString')->once()->andThrow($cancellation); + $compiler = Double::for(BladeCompiler::class)->strict(); + $compiler->expects('compileString')->throws($cancellation); $method = new ReflectionMethod(BladeMapper::class, 'compileSourcemap'); try { diff --git a/tests/Integration/Foundation/Testing/Concerns/InteractsWithAuthenticationTest.php b/tests/Integration/Foundation/Testing/Concerns/InteractsWithAuthenticationTest.php index 79cb075513..f508511df0 100644 --- a/tests/Integration/Foundation/Testing/Concerns/InteractsWithAuthenticationTest.php +++ b/tests/Integration/Foundation/Testing/Concerns/InteractsWithAuthenticationTest.php @@ -18,12 +18,14 @@ use Hypervel\Support\Facades\Schema; use Hypervel\Testbench\Attributes\WithMigration; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; #[WithMigration] class InteractsWithAuthenticationTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; protected function defineEnvironment(ApplicationContract $app): void { @@ -57,10 +59,10 @@ protected function afterRefreshingDatabase(): void public function testAssertAsGuest(): void { - $guard = m::mock(Guard::class); - $guard->shouldReceive('check') - ->twice() - ->andReturn(false); + $guard = Double::for(Guard::class)->strict(); + $guard->expects('check') + ->times(2) + ->returns(false); $this->app->make('auth') ->extend('foo', fn () => $guard); @@ -78,20 +80,14 @@ public function testAssertAsGuest(): void public function testAssertActingAs(): void { - $user = m::mock(UserContract::class); - $guard = m::mock(Guard::class); - $guard->shouldReceive('check') - ->once() - ->andReturn(true); - $guard->shouldReceive('setUser') - ->once() - ->andReturnSelf(); - $guard->shouldReceive('user') - ->once() - ->andReturn($user); - $user->shouldReceive('getAuthIdentifier') - ->twice() - ->andReturn('id'); + $user = Double::for(UserContract::class)->strict(); + $guard = Double::for(Guard::class)->strict(); + $guard->expects('check')->returns(true); + $guard->expects('setUser')->returns($guard); + $guard->expects('user')->returns($user); + $user->expects('getAuthIdentifier') + ->times(2) + ->returns('id'); $this->app->make('auth') ->extend('foo', fn () => $guard); diff --git a/tests/Integration/Generators/ComponentMakeCommandTest.php b/tests/Integration/Generators/ComponentMakeCommandTest.php index 3484b30b3f..d70f2c9608 100644 --- a/tests/Integration/Generators/ComponentMakeCommandTest.php +++ b/tests/Integration/Generators/ComponentMakeCommandTest.php @@ -6,13 +6,16 @@ use Hypervel\Filesystem\Filesystem; use Hypervel\Foundation\Console\ComponentMakeCommand; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\Console\Application as ConsoleApplication; use Symfony\Component\Console\Tester\CommandTester; class ComponentMakeCommandTest extends TestCase { + use VerifiesDoubles; + protected $files = [ 'app/View/Components/Foo.php', 'resources/views/components/foo.blade.php', @@ -114,9 +117,9 @@ public function testItCanGenerateNestedComponentFileWithCustomPath(): void public function testViewPublicationFailureDoesNotReportSuccess(): void { - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $publicationException = new RuntimeException('Unable to publish component view.'); - $files->shouldReceive('replace')->once()->andThrow($publicationException); + $files->expects('replace')->throws($publicationException); $command = new ComponentMakeCommand($files); $command->setHypervel($this->app); diff --git a/tests/Integration/Generators/MailMakeCommandTest.php b/tests/Integration/Generators/MailMakeCommandTest.php index fde39041a8..d3e2a739c0 100644 --- a/tests/Integration/Generators/MailMakeCommandTest.php +++ b/tests/Integration/Generators/MailMakeCommandTest.php @@ -7,7 +7,9 @@ use Hypervel\Contracts\Filesystem\FileNotFoundException; use Hypervel\Filesystem\Filesystem; use Hypervel\Foundation\Console\MailMakeCommand; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Symfony\Component\Console\Application as ConsoleApplication; @@ -15,6 +17,8 @@ class MailMakeCommandTest extends TestCase { + use VerifiesDoubles; + protected array $files = [ 'app/Mail/*.php', 'resources/views/foo-mail.blade.php', @@ -192,13 +196,11 @@ public function testItCanGenerateMailWithMarkdownViewWithNoInitialInput(): void public function testViewPublicationFailureDoesNotReportViewSuccess(): void { $viewPath = resource_path('views/failed-mail.blade.php'); - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $publicationException = new RuntimeException('Unable to publish mail view.'); - $files->shouldReceive('replace')->byDefault()->passthru(); - $files->shouldReceive('replace') - ->once() - ->with($viewPath, m::type('string'), null) - ->andThrow($publicationException); + $files->allows('replace') + ->with($viewPath, Argument::type('string'), null) + ->throws($publicationException); $tester = $this->commandTester(new MailMakeCommand($files)); @@ -217,10 +219,9 @@ public function testMarkdownStubReadFailureDoesNotReportMarkdownSuccess(): void { $stubPath = dirname(__DIR__, 3) . '/src/foundation/src/Console/stubs/markdown.stub'; $viewPath = resource_path('views/failed-markdown.blade.php'); - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $readException = new FileNotFoundException("File does not exist at path [{$stubPath}]."); - $files->shouldReceive('get')->byDefault()->passthru(); - $files->shouldReceive('get')->once()->with($stubPath)->andThrow($readException); + $files->allows('get')->with($stubPath)->throws($readException); $tester = $this->commandTester(new MailMakeCommand($files)); diff --git a/tests/Integration/Generators/NotificationMakeCommandTest.php b/tests/Integration/Generators/NotificationMakeCommandTest.php index c6d284c05c..da08aa02b4 100644 --- a/tests/Integration/Generators/NotificationMakeCommandTest.php +++ b/tests/Integration/Generators/NotificationMakeCommandTest.php @@ -7,13 +7,17 @@ use Hypervel\Contracts\Filesystem\FileNotFoundException; use Hypervel\Filesystem\Filesystem; use Hypervel\Foundation\Console\NotificationMakeCommand; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use Symfony\Component\Console\Application as ConsoleApplication; use Symfony\Component\Console\Tester\CommandTester; class NotificationMakeCommandTest extends TestCase { + use VerifiesDoubles; + protected $files = [ 'app/Notifications/FooNotification.php', 'resources/views/foo-notification.blade.php', @@ -128,13 +132,11 @@ public function testItCanGenerateNotificationFileWithMarkdownTemplateWithNoIniti public function testMarkdownPublicationFailureDoesNotReportMarkdownSuccess(): void { $viewPath = resource_path('views/failed-notification.blade.php'); - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $publicationException = new RuntimeException('Unable to publish notification Markdown view.'); - $files->shouldReceive('replace')->byDefault()->passthru(); - $files->shouldReceive('replace') - ->once() - ->with($viewPath, m::type('string'), null) - ->andThrow($publicationException); + $files->allows('replace') + ->with($viewPath, Argument::type('string'), null) + ->throws($publicationException); $tester = $this->commandTester(new NotificationMakeCommand($files)); @@ -153,10 +155,9 @@ public function testMarkdownStubReadFailureDoesNotReportMarkdownSuccess(): void { $stubPath = dirname(__DIR__, 3) . '/src/foundation/src/Console/stubs/markdown.stub'; $viewPath = resource_path('views/unreadable-notification.blade.php'); - $files = m::mock(Filesystem::class)->makePartial(); + $files = Double::for(new Filesystem)->passthru(); $readException = new FileNotFoundException("File does not exist at path [{$stubPath}]."); - $files->shouldReceive('get')->byDefault()->passthru(); - $files->shouldReceive('get')->once()->with($stubPath)->andThrow($readException); + $files->allows('get')->with($stubPath)->throws($readException); $tester = $this->commandTester(new NotificationMakeCommand($files)); diff --git a/tests/Integration/Horizon/Controller/DashboardStatsControllerTest.php b/tests/Integration/Horizon/Controller/DashboardStatsControllerTest.php index 2200aa7bbd..eb40570fdb 100644 --- a/tests/Integration/Horizon/Controller/DashboardStatsControllerTest.php +++ b/tests/Integration/Horizon/Controller/DashboardStatsControllerTest.php @@ -12,15 +12,18 @@ use Hypervel\Horizon\WaitTimeCalculator; use Hypervel\Tests\Integration\Horizon\Controller\Fixtures\User; use Hypervel\Tests\Integration\Horizon\ControllerTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class DashboardStatsControllerTest extends ControllerTestCase { + use VerifiesDoubles; + public function testAllStatsAreCorrectlyReturned(): void { // Setup supervisor data... - $supervisors = m::mock(SupervisorRepository::class); - $supervisors->shouldReceive('all')->andReturn([ + $supervisors = Double::for(SupervisorRepository::class)->strict(); + $supervisors->allows('all')->returns([ (object) [ 'processes' => [ 'redis:first' => 10, @@ -36,20 +39,20 @@ public function testAllStatsAreCorrectlyReturned(): void $this->app->instance(SupervisorRepository::class, $supervisors); // Setup metrics data... - $metrics = m::mock(MetricsRepository::class); - $metrics->shouldReceive('jobsProcessedPerMinute')->andReturn(1); - $metrics->shouldReceive('queueWithMaximumRuntime')->andReturn('default'); - $metrics->shouldReceive('queueWithMaximumThroughput')->andReturn('default'); + $metrics = Double::for(MetricsRepository::class)->strict(); + $metrics->allows('jobsProcessedPerMinute')->returns(1); + $metrics->allows('queueWithMaximumRuntime')->returns('default'); + $metrics->allows('queueWithMaximumThroughput')->returns('default'); $this->app->instance(MetricsRepository::class, $metrics); - $jobs = m::mock(JobRepository::class); - $jobs->shouldReceive('countRecentlyFailed')->andReturn(1); - $jobs->shouldReceive('countRecent')->andReturn(1); + $jobs = Double::for(JobRepository::class)->strict(); + $jobs->allows('countRecentlyFailed')->returns(1); + $jobs->allows('countRecent')->returns(1); $this->app->instance(JobRepository::class, $jobs); // Setup wait time data... - $wait = m::mock(WaitTimeCalculator::class); - $wait->shouldReceive('calculate')->andReturn([ + $wait = Double::for(WaitTimeCalculator::class)->strict(); + $wait->allows('calculate')->returns([ 'first' => 20, 'second' => 10, ]); @@ -80,8 +83,8 @@ public function testAllStatsAreCorrectlyReturned(): void public function testPausedStatusIsReflectedIfAllMasterSupervisorsArePaused(): void { - $masters = m::mock(MasterSupervisorRepository::class); - $masters->shouldReceive('all')->andReturn([ + $masters = Double::for(MasterSupervisorRepository::class)->strict(); + $masters->allows('all')->returns([ (object) [ 'status' => 'paused', ], @@ -101,8 +104,8 @@ public function testPausedStatusIsReflectedIfAllMasterSupervisorsArePaused(): vo public function testPausedStatusIsntReflectedIfNotAllMasterSupervisorsArePaused(): void { - $masters = m::mock(MasterSupervisorRepository::class); - $masters->shouldReceive('all')->andReturn([ + $masters = Double::for(MasterSupervisorRepository::class)->strict(); + $masters->allows('all')->returns([ (object) [ 'status' => 'running', ], diff --git a/tests/Integration/Horizon/Controller/MonitoringControllerTest.php b/tests/Integration/Horizon/Controller/MonitoringControllerTest.php index 6312272aca..a4e5b58f0b 100644 --- a/tests/Integration/Horizon/Controller/MonitoringControllerTest.php +++ b/tests/Integration/Horizon/Controller/MonitoringControllerTest.php @@ -9,19 +9,22 @@ use Hypervel\Horizon\JobPayload; use Hypervel\Tests\Integration\Horizon\Controller\Fixtures\User; use Hypervel\Tests\Integration\Horizon\ControllerTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class MonitoringControllerTest extends ControllerTestCase { + use VerifiesDoubles; + public function testMonitoredTagsAndJobCountsAreReturned(): void { - $tags = m::mock(TagRepository::class); + $tags = Double::for(TagRepository::class)->strict(); - $tags->shouldReceive('monitoring')->andReturn(['first', 'second']); - $tags->shouldReceive('count')->with('first')->andReturn(1); - $tags->shouldReceive('count')->with('failed:first')->andReturn(1); - $tags->shouldReceive('count')->with('second')->andReturn(2); - $tags->shouldReceive('count')->with('failed:second')->andReturn(2); + $tags->allows('monitoring')->returns(['first', 'second']); + $tags->allows('count')->with('first')->returns(1); + $tags->allows('count')->with('failed:first')->returns(1); + $tags->allows('count')->with('second')->returns(2); + $tags->allows('count')->with('failed:second')->returns(2); $this->app->instance(TagRepository::class, $tags); diff --git a/tests/Integration/Horizon/Feature/AutoScalerTest.php b/tests/Integration/Horizon/Feature/AutoScalerTest.php index e8098941ef..ec3676a57e 100644 --- a/tests/Integration/Horizon/Feature/AutoScalerTest.php +++ b/tests/Integration/Horizon/Feature/AutoScalerTest.php @@ -13,11 +13,14 @@ use Hypervel\Horizon\SystemProcessCounter; use Hypervel\Tests\Integration\Horizon\Feature\Fixtures\FakePool; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class AutoScalerTest extends IntegrationTestCase { + use VerifiesDoubles; + public function testScalerAttemptsToGetCloserToProperBalanceOnEachIteration(): void { [$scaler, $supervisor] = $this->with_scaling_scenario(20, [ @@ -146,8 +149,8 @@ public function testScalerWillNotScalePastMaxProcessThresholdUnderHighLoad(): vo public function testScalerWillNotScaleBelowMinimumWorkerThreshold(): void { - $external = m::mock(SystemProcessCounter::class); - $external->shouldReceive('get')->with('name')->andReturn(5); + $external = Double::for(SystemProcessCounter::class)->strict(); + $external->allows('get')->with('name')->returns(5); $this->app->instance(SystemProcessCounter::class, $external); [$scaler, $supervisor] = $this->with_scaling_scenario(5, [ @@ -174,8 +177,8 @@ public function testScalerWillNotScaleBelowMinimumWorkerThreshold(): void protected function with_scaling_scenario(int $maxProcesses, array $pools, array $extraOptions = []): array { // Mock dependencies... - $queueFactory = m::mock(QueueFactory::class); - $metrics = m::mock(MetricsRepository::class); + $queueFactory = Double::for(QueueFactory::class)->strict(); + $metrics = Double::for(MetricsRepository::class)->strict(); // Create scaler... $scaler = new AutoScaler($queueFactory, $metrics); @@ -195,12 +198,12 @@ protected function with_scaling_scenario(int $maxProcesses, array $pools, array }); // Set stats per pool... - $queue = m::mock(RedisQueue::class); + $queue = Double::for(RedisQueue::class)->strict(); collect($pools)->each(function ($pool, $name) use ($queue, $metrics) { - $queue->shouldReceive('readyNow')->with($name)->andReturn($pool['size']); - $metrics->shouldReceive('runtimeForQueue')->with($name)->andReturn($pool['runtime']); + $queue->allows('readyNow')->with((string) $name)->returns($pool['size']); + $metrics->allows('runtimeForQueue')->with((string) $name)->returns($pool['runtime']); }); - $queueFactory->shouldReceive('connection')->with('redis')->andReturn($queue); + $queueFactory->allows('connection')->with('redis')->returns($queue); return [$scaler, $supervisor]; } @@ -244,8 +247,8 @@ public function testScalerConsidersMaxShiftAndAttemptsToGetCloserToProperBalance public function testScalerDoesNotPermitGoingToZeroProcessesDespiteExceedingMaxProcesses(): void { - $external = m::mock(SystemProcessCounter::class); - $external->shouldReceive('get')->with('name')->andReturn(5); + $external = Double::for(SystemProcessCounter::class)->strict(); + $external->allows('get')->with('name')->returns(5); $this->app->instance(SystemProcessCounter::class, $external); [$scaler, $supervisor] = $this->with_scaling_scenario(15, [ diff --git a/tests/Integration/Horizon/Feature/ClearCommandTest.php b/tests/Integration/Horizon/Feature/ClearCommandTest.php index 825b99d4bd..c63e29ae7a 100644 --- a/tests/Integration/Horizon/Feature/ClearCommandTest.php +++ b/tests/Integration/Horizon/Feature/ClearCommandTest.php @@ -16,13 +16,16 @@ use Hypervel\Support\Facades\Redis; use Hypervel\Tests\Integration\Horizon\Feature\Fixtures\Jobs\BasicJob; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; class ClearCommandTest extends IntegrationTestCase { + use VerifiesDoubles; + /** * Configure separate and shared queue storage connections. */ @@ -56,17 +59,17 @@ public function testCommandPreservesZeroAndDefaultsEmptyIdentifiers( ): void { config()->set('horizon.defaults', $defaults); - $jobRepository = m::mock(RedisJobRepository::class); - $jobRepository->shouldReceive('purge')->once()->with($expectedQueue, $expectedConnection); + $jobRepository = Double::for(RedisJobRepository::class)->strict(); + $jobRepository->expects('purge')->with($expectedQueue, $expectedConnection); $this->app->instance(JobRepository::class, $jobRepository); - $resolvedQueue = m::mock(RedisQueue::class); - $resolvedQueue->shouldReceive('getQueue')->once()->with($expectedQueue)->andReturn('queues:' . $expectedQueue); - $resolvedQueue->shouldReceive('getConnectionName')->once()->andReturn($expectedConnection); - $resolvedQueue->shouldReceive('clear')->once()->with($expectedQueue)->andReturn(1); + $resolvedQueue = Double::for(RedisQueue::class)->strict(); + $resolvedQueue->expects('getQueue')->with($expectedQueue)->returns('queues:' . $expectedQueue); + $resolvedQueue->expects('getConnectionName')->returns($expectedConnection); + $resolvedQueue->expects('clear')->with($expectedQueue)->returns(1); - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->once()->with($expectedConnection)->andReturn($resolvedQueue); + $manager = Double::for(QueueManager::class)->strict(); + $manager->expects('connection')->with($expectedConnection)->returns($resolvedQueue); $this->app->instance('queue', $manager); $command = new ClearCommand; @@ -142,15 +145,15 @@ public function testClearingSharedStoragePreservesOtherConnectionRecordsUntilThe public function testClearingANonHorizonConnectionDoesNotPurgeHorizonJobs(): void { - $jobRepository = m::mock(JobRepository::class); - $jobRepository->shouldNotReceive('purge'); + $jobRepository = Double::for(JobRepository::class)->strict(); + $jobRepository->expects('purge')->never(); $this->app->instance(JobRepository::class, $jobRepository); - $resolvedQueue = m::mock(QueueContract::class, ClearableQueue::class); - $resolvedQueue->shouldReceive('clear')->once()->with('default')->andReturn(1); + $resolvedQueue = Double::for(QueueContract::class, ClearableQueue::class)->strict(); + $resolvedQueue->expects('clear')->with('default')->returns(1); - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->once()->with('redis')->andReturn($resolvedQueue); + $manager = Double::for(QueueManager::class)->strict(); + $manager->expects('connection')->with('redis')->returns($resolvedQueue); $this->app->instance('queue', $manager); $this->artisan('horizon:clear', ['connection' => 'redis', '--force' => true]) @@ -159,8 +162,8 @@ public function testClearingANonHorizonConnectionDoesNotPurgeHorizonJobs(): void public function testUnsupportedConnectionsFailBeforePurgingHorizonJobs(): void { - $jobRepository = m::mock(JobRepository::class); - $jobRepository->shouldNotReceive('purge'); + $jobRepository = Double::for(JobRepository::class)->strict(); + $jobRepository->expects('purge')->never(); $this->app->instance(JobRepository::class, $jobRepository); $this->artisan('horizon:clear', ['connection' => 'sync', '--force' => true]) diff --git a/tests/Integration/Horizon/Feature/Listeners/MarkJobAsCompleteTest.php b/tests/Integration/Horizon/Feature/Listeners/MarkJobAsCompleteTest.php index 7a578196ca..ac6fe312df 100644 --- a/tests/Integration/Horizon/Feature/Listeners/MarkJobAsCompleteTest.php +++ b/tests/Integration/Horizon/Feature/Listeners/MarkJobAsCompleteTest.php @@ -11,28 +11,30 @@ use Hypervel\Horizon\Listeners\MarkJobAsComplete; use Hypervel\Queue\Jobs\RedisJob; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class MarkJobAsCompleteTest extends IntegrationTestCase { + use VerifiesDoubles; + public function testHandle(): void { - $payload = m::mock(JobPayload::class); - $payload->shouldReceive('tags')->once()->andReturn([]); - $payload->shouldReceive('isSilenced')->once()->andReturn(false); + $payload = Double::for(JobPayload::class)->strict(); + $payload->expects('tags')->returns([]); + $payload->expects('isSilenced')->returns(false); - $job = m::mock(RedisJob::class); - $job->shouldReceive('hasFailed')->twice()->andReturn(false); + $job = Double::for(RedisJob::class)->strict(); + $job->expects('hasFailed')->times(2)->returns(false); - $event = m::mock(JobDeleted::class); + $event = new JobDeleted($job, '{"id":"1"}'); $event->payload = $payload; - $event->job = $job; - $jobs = m::mock(JobRepository::class); - $jobs->shouldReceive('completed')->once()->with($payload, false, false); + $jobs = Double::for(JobRepository::class)->strict(); + $jobs->expects('completed')->with($payload, false, false); - $tags = m::mock(TagRepository::class); - $tags->shouldReceive('monitored')->once()->with([])->andReturn([]); + $tags = Double::for(TagRepository::class)->strict(); + $tags->expects('monitored')->with([])->returns([]); $listener = new MarkJobAsComplete($jobs, $tags); @@ -41,25 +43,24 @@ public function testHandle(): void public function testHandleWithTag(): void { - $payload = m::mock(JobPayload::class); - $payload->shouldReceive('tags')->once()->andReturn(['tag']); - $payload->shouldReceive('isSilenced')->once()->andReturn(false); + $payload = Double::for(JobPayload::class)->strict(); + $payload->expects('tags')->returns(['tag']); + $payload->expects('isSilenced')->returns(false); - $job = m::mock(RedisJob::class); - $job->shouldReceive('hasFailed')->twice()->andReturn(false); + $job = Double::for(RedisJob::class)->strict(); + $job->expects('hasFailed')->times(2)->returns(false); - $event = m::mock(JobDeleted::class); + $event = new JobDeleted($job, '{"id":"1"}'); $event->payload = $payload; - $event->job = $job; $event->connectionName = 'redis'; $event->queue = 'default'; - $jobs = m::mock(JobRepository::class); - $jobs->shouldReceive('completed')->once()->with($payload, false, false); - $jobs->shouldReceive('remember')->once()->with('redis', 'default', $payload); + $jobs = Double::for(JobRepository::class)->strict(); + $jobs->expects('completed')->with($payload, false, false); + $jobs->expects('remember')->with('redis', 'default', $payload); - $tags = m::mock(TagRepository::class); - $tags->shouldReceive('monitored')->once()->with(['tag'])->andReturn(['tag']); + $tags = Double::for(TagRepository::class)->strict(); + $tags->expects('monitored')->with(['tag'])->returns(['tag']); $listener = new MarkJobAsComplete($jobs, $tags); diff --git a/tests/Integration/Horizon/Feature/Listeners/StoreTagsForFailedTest.php b/tests/Integration/Horizon/Feature/Listeners/StoreTagsForFailedTest.php index 52629d9dca..553797d857 100644 --- a/tests/Integration/Horizon/Feature/Listeners/StoreTagsForFailedTest.php +++ b/tests/Integration/Horizon/Feature/Listeners/StoreTagsForFailedTest.php @@ -11,17 +11,20 @@ use Hypervel\Horizon\Repositories\RedisJobRepository; use Hypervel\Queue\Jobs\Job; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class StoreTagsForFailedTest extends IntegrationTestCase { + use VerifiesDoubles; + public function testTemporaryFailedJobShouldBeDeletedWhenTheMainJobIsDeleted(): void { config()->set('horizon.trim.failed', 120); - $tagRepository = m::mock(TagRepository::class); + $tagRepository = Double::for(TagRepository::class)->strict(); - $tagRepository->shouldReceive('addTemporary')->once()->with(120, '1', ['failed:foobar'])->andReturn([]); + $tagRepository->expects('addTemporary')->with(120, '1', ['failed:foobar']); $this->instance(TagRepository::class, $tagRepository); @@ -45,12 +48,12 @@ public function testFailedJobTrimUsesItsDefaultWhenTrimConfigurationIsReplaced() 'monitored' => 10080, ]); - $tagRepository = m::mock(TagRepository::class); - $tagRepository->shouldReceive('addTemporary')->once()->with( + $tagRepository = Double::for(TagRepository::class)->strict(); + $tagRepository->expects('addTemporary')->with( RedisJobRepository::DEFAULT_FAILED_JOB_RETENTION, '1', ['failed:foobar'], - )->andReturn([]); + ); $this->instance(TagRepository::class, $tagRepository); $event = new JobFailed( diff --git a/tests/Integration/Horizon/Feature/MasterSupervisorTest.php b/tests/Integration/Horizon/Feature/MasterSupervisorTest.php index 5e5e86f4e9..33366ae6f2 100644 --- a/tests/Integration/Horizon/Feature/MasterSupervisorTest.php +++ b/tests/Integration/Horizon/Feature/MasterSupervisorTest.php @@ -20,12 +20,15 @@ use Hypervel\Tests\Integration\Horizon\Feature\Fixtures\EternalSupervisor; use Hypervel\Tests\Integration\Horizon\Feature\Fixtures\SupervisorProcessWithFakeRestart; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\Process\Process; class MasterSupervisorTest extends IntegrationTestCase { + use VerifiesDoubles; + public function testNamesCanBeCustomized(): void { MasterSupervisor::determineNameUsing(function () { @@ -42,7 +45,9 @@ public function testNamesCanBeCustomized(): void #[DataProvider('terminalExitCodes')] public function testMasterProcessMarksTerminalExitsAsDeadAndRemovesThem(int $exitCode): void { - $process = m::mock(Process::class); + $process = Double::for(Process::class)->strict(); + // Symfony's destructor stops the process even when no real process was started. + $process->allows('stop')->with(0.0); $master = new MasterSupervisor; $master->working = true; $master->supervisors[] = $supervisorProcess = new SupervisorProcess( @@ -50,9 +55,9 @@ public function testMasterProcessMarksTerminalExitsAsDeadAndRemovesThem(int $exi $process ); - $process->shouldReceive('isStarted')->andReturn(true); - $process->shouldReceive('isRunning')->andReturn(false); - $process->shouldReceive('getExitCode')->andReturn($exitCode); + $process->allows('isStarted')->returns(true); + $process->allows('isRunning')->returns(false); + $process->allows('getExitCode')->returns($exitCode); $master->loop(); @@ -72,7 +77,8 @@ public static function terminalExitCodes(): array #[DataProvider('restartableExitCodes')] public function testMasterProcessRestartsUnexpectedExits(?int $exitCode): void { - $process = m::mock(Process::class); + $process = Double::for(Process::class)->strict(); + $process->allows('stop')->with(0.0); $master = new MasterSupervisor; $master->working = true; $master->supervisors[] = $supervisorProcess = new SupervisorProcessWithFakeRestart( @@ -80,9 +86,9 @@ public function testMasterProcessRestartsUnexpectedExits(?int $exitCode): void $process ); - $process->shouldReceive('isStarted')->andReturn(true); - $process->shouldReceive('isRunning')->andReturn(false); - $process->shouldReceive('getExitCode')->andReturn($exitCode); + $process->allows('isStarted')->returns(true); + $process->allows('isRunning')->returns(false); + $process->allows('getExitCode')->returns($exitCode); $master->loop(); @@ -111,7 +117,8 @@ public static function restartableExitCodes(): array public function testMasterProcessRestartsProcessesThatNeverStarted(): void { - $process = m::mock(Process::class); + $process = Double::for(Process::class)->strict(); + $process->allows('stop')->with(0.0); $master = new MasterSupervisor; $master->working = true; $master->supervisors[] = $supervisorProcess = new SupervisorProcessWithFakeRestart( @@ -119,7 +126,7 @@ public function testMasterProcessRestartsProcessesThatNeverStarted(): void $process ); - $process->shouldReceive('isStarted')->andReturn(false); + $process->allows('isStarted')->returns(false); $master->loop(); @@ -130,15 +137,16 @@ public function testMasterProcessRestartsProcessesThatNeverStarted(): void public function testMasterProcessStartsUnstartedProcessesWhenUnpaused(): void { - $process = m::mock(Process::class); + $process = Double::for(Process::class)->strict(); + $process->allows('stop')->with(0.0); $master = new MasterSupervisor; $master->supervisors[] = $supervisorProcess = new SupervisorProcessWithFakeRestart( $this->supervisorOptions(), $process ); - $process->shouldReceive('isStarted')->andReturn(false); - $process->shouldReceive('isRunning')->andReturn(false); + $process->allows('isStarted')->returns(false); + $process->allows('isRunning')->returns(false); $master->loop(); @@ -172,13 +180,14 @@ public function testMasterProcessLoopProcessesPendingCommands(): void public function testMasterProcessInformationIsPersisted(): void { - $process = m::mock(Process::class); + $process = Double::for(Process::class)->strict(); + $process->allows('stop')->with(0.0); $master = new MasterSupervisor; $master->working = true; $master->supervisors[] = new SupervisorProcess($this->supervisorOptions(), $process); - $process->shouldReceive('isStarted')->andReturn(true); - $process->shouldReceive('isRunning')->andReturn(true); - $process->shouldReceive('signal'); + $process->allows('isStarted')->returns(true); + $process->allows('isRunning')->returns(true); + $process->allows('signal'); $master->loop(); diff --git a/tests/Integration/Horizon/Feature/MetricsTest.php b/tests/Integration/Horizon/Feature/MetricsTest.php index a6cda8e449..2079d95206 100644 --- a/tests/Integration/Horizon/Feature/MetricsTest.php +++ b/tests/Integration/Horizon/Feature/MetricsTest.php @@ -13,10 +13,13 @@ use Hypervel\Tests\Integration\Horizon\Feature\Fixtures\Jobs\BasicJob; use Hypervel\Tests\Integration\Horizon\Feature\Fixtures\Jobs\ConditionallyFailingJob; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class MetricsTest extends IntegrationTestCase { + use VerifiesDoubles; + /** * Clear metrics before the test. */ @@ -75,10 +78,10 @@ public function testThroughputIsStoredPerQueue(): void public function testAverageRuntimeIsStoredPerJobClassInMilliseconds(): void { - $stopwatch = m::mock(Stopwatch::class); - $stopwatch->shouldReceive('start'); - $stopwatch->shouldReceive('forget'); - $stopwatch->shouldReceive('check')->andReturn(1, 2); + $stopwatch = Double::for(Stopwatch::class)->strict(); + $stopwatch->allows('start'); + $stopwatch->allows('forget'); + $stopwatch->allows('check')->returns(1, 2); $this->app->instance(Stopwatch::class, $stopwatch); Queue::push(new BasicJob); @@ -92,10 +95,10 @@ public function testAverageRuntimeIsStoredPerJobClassInMilliseconds(): void public function testAverageRuntimeIsStoredPerQueueInMilliseconds(): void { - $stopwatch = m::mock(Stopwatch::class); - $stopwatch->shouldReceive('start'); - $stopwatch->shouldReceive('forget'); - $stopwatch->shouldReceive('check')->andReturn(1, 2); + $stopwatch = Double::for(Stopwatch::class)->strict(); + $stopwatch->allows('start'); + $stopwatch->allows('forget'); + $stopwatch->allows('check')->returns(1, 2); $this->app->instance(Stopwatch::class, $stopwatch); Queue::push(new BasicJob); @@ -123,10 +126,10 @@ public function testListOfAllJobsWithMetricInformationIsMaintained(): void public function testSnapshotOfMetricsPerformanceCanBeStored(): void { - $stopwatch = m::mock(Stopwatch::class); - $stopwatch->shouldReceive('start'); - $stopwatch->shouldReceive('forget'); - $stopwatch->shouldReceive('check')->andReturn(1, 2, 3); + $stopwatch = Double::for(Stopwatch::class)->strict(); + $stopwatch->allows('start'); + $stopwatch->allows('forget'); + $stopwatch->allows('check')->returns(1, 2, 3); $this->app->instance(Stopwatch::class, $stopwatch); Queue::push(new BasicJob); @@ -225,14 +228,14 @@ public function testSnapshotOfMetricsPerformanceCanBeStored(): void public function testQueueSnapshotsRecordTheWaitOfThePoolsProcessingTheQueue(): void { - $stopwatch = m::mock(Stopwatch::class); - $stopwatch->shouldReceive('start'); - $stopwatch->shouldReceive('forget'); - $stopwatch->shouldReceive('check')->andReturn(1000); + $stopwatch = Double::for(Stopwatch::class)->strict(); + $stopwatch->allows('start'); + $stopwatch->allows('forget'); + $stopwatch->allows('check')->returns(1000); $this->app->instance(Stopwatch::class, $stopwatch); - $supervisors = m::mock(SupervisorRepository::class); - $supervisors->shouldReceive('all')->andReturn([ + $supervisors = Double::for(SupervisorRepository::class)->strict(); + $supervisors->allows('all')->returns([ (object) ['processes' => ['redis:high,default' => 1]], ]); $this->app->instance(SupervisorRepository::class, $supervisors); @@ -263,10 +266,10 @@ public function testQueueSnapshotsRecordTheWaitOfThePoolsProcessingTheQueue(): v public function testJobsProcessedPerMinuteSinceLastSnapshotIsCalculable(): void { - $stopwatch = m::mock(Stopwatch::class); - $stopwatch->shouldReceive('start'); - $stopwatch->shouldReceive('forget'); - $stopwatch->shouldReceive('check')->andReturn(1); + $stopwatch = Double::for(Stopwatch::class)->strict(); + $stopwatch->allows('start'); + $stopwatch->allows('forget'); + $stopwatch->allows('check')->returns(1); $this->app->instance(Stopwatch::class, $stopwatch); Queue::push(new BasicJob); @@ -331,10 +334,10 @@ public function testOmittedRetentionSettingsKeepTheDefaultNumberOfSnapshots(): v config()->set('horizon.metrics.trim_snapshots', []); $retention = 24; - $stopwatch = m::mock(Stopwatch::class); - $stopwatch->shouldReceive('start'); - $stopwatch->shouldReceive('forget'); - $stopwatch->shouldReceive('check')->andReturn(1); + $stopwatch = Double::for(Stopwatch::class)->strict(); + $stopwatch->allows('start'); + $stopwatch->allows('forget'); + $stopwatch->allows('check')->returns(1); $this->app->instance(Stopwatch::class, $stopwatch); CarbonImmutable::setTestNow(CarbonImmutable::now()); @@ -368,10 +371,10 @@ public function testOmittedRetentionSettingsKeepTheDefaultNumberOfSnapshots(): v public function testClearRemovesAllMetricsData(): void { - $stopwatch = m::mock(Stopwatch::class); - $stopwatch->shouldReceive('start'); - $stopwatch->shouldReceive('forget'); - $stopwatch->shouldReceive('check')->andReturn(1); + $stopwatch = Double::for(Stopwatch::class)->strict(); + $stopwatch->allows('start'); + $stopwatch->allows('forget'); + $stopwatch->allows('check')->returns(1); $this->app->instance(Stopwatch::class, $stopwatch); Queue::push(new BasicJob); diff --git a/tests/Integration/Horizon/Feature/MonitorMasterSupervisorMemoryTest.php b/tests/Integration/Horizon/Feature/MonitorMasterSupervisorMemoryTest.php index 2a8e16ac45..b3273ef876 100644 --- a/tests/Integration/Horizon/Feature/MonitorMasterSupervisorMemoryTest.php +++ b/tests/Integration/Horizon/Feature/MonitorMasterSupervisorMemoryTest.php @@ -11,10 +11,13 @@ use Hypervel\Horizon\MasterSupervisor; use Hypervel\Support\Facades\Event; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class MonitorMasterSupervisorMemoryTest extends IntegrationTestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -28,11 +31,11 @@ public function testSupervisorIsTerminatedWhenUsingTooMuchMemory(): void $monitor = new MonitorMasterSupervisorMemory; - $master = m::mock(MasterSupervisor::class); + $master = Double::for(MasterSupervisor::class)->strict(); - $master->shouldReceive('memoryUsage')->andReturn(192); - $master->shouldReceive('output')->once()->with('error', 'Memory limit exceeded: Using 192/64MB. Consider increasing horizon.memory_limit.'); - $master->shouldReceive('terminate')->once()->with(12); + $master->allows('memoryUsage')->returns(192); + $master->expects('output')->with('error', 'Memory limit exceeded: Using 192/64MB. Consider increasing horizon.memory_limit.'); + $master->expects('terminate')->with(12); $monitor->handle(new MasterSupervisorLooped($master)); @@ -51,10 +54,10 @@ static function (MasterSupervisorOutOfMemory $event) use (&$observedEvents): voi } ); - $master = m::mock(MasterSupervisor::class); - $master->shouldReceive('memoryUsage')->twice()->andReturn(192); - $master->shouldReceive('output')->once()->with('error', 'Memory limit exceeded: Using 192/64MB. Consider increasing horizon.memory_limit.'); - $master->shouldReceive('terminate')->once()->with(12); + $master = Double::for(MasterSupervisor::class)->strict(); + $master->expects('memoryUsage')->times(2)->returns(192); + $master->expects('output')->with('error', 'Memory limit exceeded: Using 192/64MB. Consider increasing horizon.memory_limit.'); + $master->expects('terminate')->with(12); (new MonitorMasterSupervisorMemory)->handle(new MasterSupervisorLooped($master)); @@ -65,10 +68,10 @@ public function testSupervisorIsNotTerminatedWhenUsingLowMemory(): void { $monitor = new MonitorMasterSupervisorMemory; - $master = m::mock(MasterSupervisor::class); + $master = Double::for(MasterSupervisor::class)->strict(); - $master->shouldReceive('memoryUsage')->andReturn(16); - $master->shouldReceive('terminate')->never(); + $master->allows('memoryUsage')->returns(16); + $master->expects('terminate')->never(); $monitor->handle(new MasterSupervisorLooped($master)); } diff --git a/tests/Integration/Horizon/Feature/MonitorSupervisorMemoryTest.php b/tests/Integration/Horizon/Feature/MonitorSupervisorMemoryTest.php index 86883cea8a..1010c5020a 100644 --- a/tests/Integration/Horizon/Feature/MonitorSupervisorMemoryTest.php +++ b/tests/Integration/Horizon/Feature/MonitorSupervisorMemoryTest.php @@ -12,10 +12,13 @@ use Hypervel\Horizon\SupervisorOptions; use Hypervel\Support\Facades\Event; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class MonitorSupervisorMemoryTest extends IntegrationTestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -29,11 +32,11 @@ public function testSupervisorIsTerminatedWhenUsingTooMuchMemory(): void $monitor = new MonitorSupervisorMemory; - $supervisor = m::mock(Supervisor::class); + $supervisor = Double::for(Supervisor::class)->strict(); $supervisor->options = new SupervisorOptions('redis', 'default'); - $supervisor->shouldReceive('memoryUsage')->andReturn(192); - $supervisor->shouldReceive('terminate')->once()->with(12); + $supervisor->allows('memoryUsage')->returns(192); + $supervisor->expects('terminate')->with(12); $monitor->handle(new SupervisorLooped($supervisor)); @@ -53,10 +56,10 @@ static function (SupervisorOutOfMemory $event) use (&$observedEvents): void { } ); - $supervisor = m::mock(Supervisor::class); + $supervisor = Double::for(Supervisor::class)->strict(); $supervisor->options = new SupervisorOptions('redis', 'default'); - $supervisor->shouldReceive('memoryUsage')->once()->andReturn(192); - $supervisor->shouldReceive('terminate')->once()->with(12); + $supervisor->expects('memoryUsage')->returns(192); + $supervisor->expects('terminate')->with(12); (new MonitorSupervisorMemory)->handle(new SupervisorLooped($supervisor)); @@ -67,11 +70,11 @@ public function testSupervisorIsNotTerminatedWhenUsingLowMemory(): void { $monitor = new MonitorSupervisorMemory; - $supervisor = m::mock(Supervisor::class); + $supervisor = Double::for(Supervisor::class)->strict(); $supervisor->options = new SupervisorOptions('redis', 'default'); - $supervisor->shouldReceive('memoryUsage')->andReturn(64); - $supervisor->shouldReceive('terminate')->never(); + $supervisor->allows('memoryUsage')->returns(64); + $supervisor->expects('terminate')->never(); $monitor->handle(new SupervisorLooped($supervisor)); } diff --git a/tests/Integration/Horizon/Feature/MonitorWaitTimesTest.php b/tests/Integration/Horizon/Feature/MonitorWaitTimesTest.php index 300055b8cc..0efb72930f 100644 --- a/tests/Integration/Horizon/Feature/MonitorWaitTimesTest.php +++ b/tests/Integration/Horizon/Feature/MonitorWaitTimesTest.php @@ -11,16 +11,19 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Facades\Event; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class MonitorWaitTimesTest extends IntegrationTestCase { + use VerifiesDoubles; + public function testQueuesWithLongWaitsAreFound(): void { Event::fake(); - $calc = m::mock(WaitTimeCalculator::class); - $calc->shouldReceive('calculate')->andReturn([ + $calc = Double::for(WaitTimeCalculator::class)->strict(); + $calc->allows('calculate')->returns([ 'redis:test-queue' => 10, 'redis:test-queue-2' => 80, ]); @@ -41,8 +44,8 @@ public function testQueueIgnoresLongWaits(): void Event::fake(); - $calc = m::mock(WaitTimeCalculator::class); - $calc->expects('calculate')->andReturn([ + $calc = Double::for(WaitTimeCalculator::class)->strict(); + $calc->expects('calculate')->returns([ 'redis:ignore-queue' => 10, ]); $this->app->instance(WaitTimeCalculator::class, $calc); @@ -58,12 +61,12 @@ public function testMonitorWaitTimesSkipsWhenLockIsNotAcquired(): void { Event::fake(); - $calc = m::mock(WaitTimeCalculator::class); + $calc = Double::for(WaitTimeCalculator::class)->strict(); $calc->expects('calculate')->never(); $this->app->instance(WaitTimeCalculator::class, $calc); - $metrics = m::mock(MetricsRepository::class); - $metrics->shouldReceive('acquireWaitTimeMonitorLock')->once()->andReturnFalse(); + $metrics = Double::for(MetricsRepository::class)->strict(); + $metrics->expects('acquireWaitTimeMonitorLock')->returns(false); $this->app->instance(MetricsRepository::class, $metrics); $listener = new MonitorWaitTimes($metrics); @@ -77,12 +80,12 @@ public function testMonitorWaitTimesSkipsWhenNotDueToMonitor(): void { Event::fake(); - $calc = m::mock(WaitTimeCalculator::class); + $calc = Double::for(WaitTimeCalculator::class)->strict(); $calc->expects('calculate')->never(); $this->app->instance(WaitTimeCalculator::class, $calc); - $metrics = m::mock(MetricsRepository::class); - $metrics->shouldReceive('acquireWaitTimeMonitorLock')->never(); + $metrics = Double::for(MetricsRepository::class)->strict(); + $metrics->expects('acquireWaitTimeMonitorLock')->never(); $this->app->instance(MetricsRepository::class, $metrics); $listener = new MonitorWaitTimes($metrics); @@ -99,14 +102,14 @@ public function testMonitorWaitTimesSkipsWhenNotDueToMonitorAndExecutesAfter2Min Event::fake(); - $calc = m::mock(WaitTimeCalculator::class); - $calc->expects('calculate')->once()->andReturn([ + $calc = Double::for(WaitTimeCalculator::class)->strict(); + $calc->expects('calculate')->returns([ 'redis:default' => 70, ]); $this->app->instance(WaitTimeCalculator::class, $calc); - $metrics = m::mock(MetricsRepository::class); - $metrics->shouldReceive('acquireWaitTimeMonitorLock')->once()->andReturnTrue(); + $metrics = Double::for(MetricsRepository::class)->strict(); + $metrics->expects('acquireWaitTimeMonitorLock')->returns(true); $this->app->instance(MetricsRepository::class, $metrics); $listener = new MonitorWaitTimes($metrics); @@ -129,14 +132,14 @@ public function testMonitorWaitTimesExecutesOnceWhenCalledTwice(): void Event::fake(); - $calc = m::mock(WaitTimeCalculator::class); - $calc->expects('calculate')->once()->andReturn([ + $calc = Double::for(WaitTimeCalculator::class)->strict(); + $calc->expects('calculate')->returns([ 'redis:default' => 70, ]); $this->app->instance(WaitTimeCalculator::class, $calc); - $metrics = m::mock(MetricsRepository::class); - $metrics->shouldReceive('acquireWaitTimeMonitorLock')->once()->andReturnTrue(); + $metrics = Double::for(MetricsRepository::class)->strict(); + $metrics->expects('acquireWaitTimeMonitorLock')->returns(true); $this->app->instance(MetricsRepository::class, $metrics); $listener = new MonitorWaitTimes($metrics); diff --git a/tests/Integration/Horizon/Feature/ProcessInspectorTest.php b/tests/Integration/Horizon/Feature/ProcessInspectorTest.php index c294c6076b..08037559ed 100644 --- a/tests/Integration/Horizon/Feature/ProcessInspectorTest.php +++ b/tests/Integration/Horizon/Feature/ProcessInspectorTest.php @@ -9,21 +9,24 @@ use Hypervel\Horizon\Exec; use Hypervel\Horizon\ProcessInspector; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class ProcessInspectorTest extends IntegrationTestCase { + use VerifiesDoubles; + public function testFindsOrphanedProcessIds(): void { - $exec = m::mock(Exec::class); - $exec->shouldReceive('run')->with('pgrep -f [h]orizon')->andReturn([1, 2, 3, 4, 5, 6]); - $exec->shouldReceive('run')->with('pgrep -f horizon:purge')->andReturn([]); - $exec->shouldReceive('run')->with('pgrep -P 2')->andReturn([4]); - $exec->shouldReceive('run')->with('pgrep -P 3')->andReturn([5]); + $exec = Double::for(Exec::class)->strict(); + $exec->allows('run')->with('pgrep -f [h]orizon')->returns([1, 2, 3, 4, 5, 6]); + $exec->allows('run')->with('pgrep -f horizon:purge')->returns([]); + $exec->allows('run')->with('pgrep -P 2')->returns([4]); + $exec->allows('run')->with('pgrep -P 3')->returns([5]); $this->app->instance(Exec::class, $exec); - $supervisors = m::mock(SupervisorRepository::class); - $supervisors->shouldReceive('all')->andReturn([ + $supervisors = Double::for(SupervisorRepository::class)->strict(); + $supervisors->allows('all')->returns([ [ 'pid' => 2, ], @@ -33,8 +36,8 @@ public function testFindsOrphanedProcessIds(): void ]); $this->app->instance(SupervisorRepository::class, $supervisors); - $masters = m::mock(MasterSupervisorRepository::class); - $masters->shouldReceive('all')->andReturn([ + $masters = Double::for(MasterSupervisorRepository::class)->strict(); + $masters->allows('all')->returns([ [ 'pid' => 6, ], diff --git a/tests/Integration/Horizon/Feature/RedisPayloadTest.php b/tests/Integration/Horizon/Feature/RedisPayloadTest.php index 06b4aa825b..cd7041fd7a 100644 --- a/tests/Integration/Horizon/Feature/RedisPayloadTest.php +++ b/tests/Integration/Horizon/Feature/RedisPayloadTest.php @@ -28,12 +28,15 @@ use Hypervel\Tests\Integration\Horizon\Feature\Fixtures\FakeSilencedJob; use Hypervel\Tests\Integration\Horizon\Feature\Fixtures\SilencedMailable; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use StdClass; class RedisPayloadTest extends IntegrationTestCase { + use VerifiesDoubles; + public function testTypeIsCorrectlyDetermined(): void { $JobPayload = new JobPayload(json_encode(['id' => '1'])); @@ -44,7 +47,7 @@ public function testTypeIsCorrectlyDetermined(): void $JobPayload->prepare(new CallQueuedListener('stdClass', 'method', [new StdClass])); $this->assertSame('event', $JobPayload->decoded['type']); - $JobPayload->prepare(new SendQueuedMailable(m::mock(Mailable::class))); + $JobPayload->prepare(new SendQueuedMailable(Double::for(Mailable::class)->strict())); $this->assertSame('mail', $JobPayload->decoded['type']); $JobPayload->prepare(new SendQueuedNotifications([], new StdClass, ['mail'])); @@ -281,7 +284,7 @@ public function testItDeterminesIfJobIsSilencedCorrectlyForMailable(): void { $JobPayload = new JobPayload(json_encode(['id' => '1'])); - $mailableMock = m::mock(SilencedMailable::class); + $mailableMock = Double::for(SilencedMailable::class)->strict(); config(['horizon.silenced' => [get_class($mailableMock)]]); $JobPayload->prepare(new SendQueuedMailable($mailableMock)); $this->assertTrue($JobPayload->isSilenced()); diff --git a/tests/Integration/Horizon/Feature/SupervisorTest.php b/tests/Integration/Horizon/Feature/SupervisorTest.php index f30be82d20..8c8cf4574a 100644 --- a/tests/Integration/Horizon/Feature/SupervisorTest.php +++ b/tests/Integration/Horizon/Feature/SupervisorTest.php @@ -28,12 +28,15 @@ use Hypervel\Tests\Integration\Horizon\Feature\Fixtures\Jobs\BasicJob; use Hypervel\Tests\Integration\Horizon\Feature\Fixtures\SupervisorThatThrowsException; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\RequiresPhpExtension; use Throwable; class SupervisorTest extends IntegrationTestCase { + use VerifiesDoubles; + public string $phpBinary; public ?Supervisor $supervisor = null; @@ -204,8 +207,8 @@ public function testSupervisorMonitorsWorkerProcesses(): void public function testExceptionsAreCaughtAndHandledDuringLoop(): void { - $exceptions = m::mock(ExceptionHandler::class); - $exceptions->shouldReceive('report')->once(); + $exceptions = Double::for(ExceptionHandler::class)->strict(); + $exceptions->expects('report'); $this->app->instance(ExceptionHandler::class, $exceptions); $this->supervisor = $supervisor = new SupervisorThatThrowsException($this->supervisorOptions()); @@ -482,8 +485,8 @@ public function testAutoScalerIsCalledOnLoopWhenAutoScaling(): void $this->supervisor = $supervisor = new Supervisor($options); // Mock the scaler... - $autoScaler = m::mock(AutoScaler::class); - $autoScaler->shouldReceive('scale')->once()->with($supervisor); + $autoScaler = Double::for(AutoScaler::class)->strict(); + $autoScaler->expects('scale')->with($supervisor); $this->app->singleton(AutoScaler::class, fn () => $autoScaler); // Start the supervisor... diff --git a/tests/Integration/Horizon/Feature/TrimFailedJobsTest.php b/tests/Integration/Horizon/Feature/TrimFailedJobsTest.php index e5cea291fd..85765f66b8 100644 --- a/tests/Integration/Horizon/Feature/TrimFailedJobsTest.php +++ b/tests/Integration/Horizon/Feature/TrimFailedJobsTest.php @@ -11,29 +11,32 @@ use Hypervel\Horizon\Repositories\RedisJobRepository; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class TrimFailedJobsTest extends IntegrationTestCase { + use VerifiesDoubles; + public function testOmittedRetentionUsesTheDefaultCooldown(): void { config()->set('horizon.trim', []); $trimmer = new TrimFailedJobs; - $repository = m::mock(JobRepository::class); - $repository->shouldReceive('trimFailedJobs')->twice(); + $repository = Double::for(JobRepository::class)->strict(); + $repository->expects('trimFailedJobs')->times(2); $this->app->instance(JobRepository::class, $repository); - $trimmer->handle(new MasterSupervisorLooped(m::mock(MasterSupervisor::class))); + $trimmer->handle(new MasterSupervisorLooped(Double::for(MasterSupervisor::class)->strict())); $this->assertSame(intdiv(RedisJobRepository::DEFAULT_FAILED_JOB_RETENTION, 12), $trimmer->frequency); CarbonImmutable::setTestNow(CarbonImmutable::now()->addMinutes(1600)); - $trimmer->handle(new MasterSupervisorLooped(m::mock(MasterSupervisor::class))); - $trimmer->handle(new MasterSupervisorLooped(m::mock(MasterSupervisor::class))); - $trimmer->handle(new MasterSupervisorLooped(m::mock(MasterSupervisor::class))); + $trimmer->handle(new MasterSupervisorLooped(Double::for(MasterSupervisor::class)->strict())); + $trimmer->handle(new MasterSupervisorLooped(Double::for(MasterSupervisor::class)->strict())); + $trimmer->handle(new MasterSupervisorLooped(Double::for(MasterSupervisor::class)->strict())); CarbonImmutable::setTestNow(); } diff --git a/tests/Integration/Horizon/Feature/TrimMonitoredJobsTest.php b/tests/Integration/Horizon/Feature/TrimMonitoredJobsTest.php index 3862b24fd8..602b42cf58 100644 --- a/tests/Integration/Horizon/Feature/TrimMonitoredJobsTest.php +++ b/tests/Integration/Horizon/Feature/TrimMonitoredJobsTest.php @@ -11,30 +11,33 @@ use Hypervel\Horizon\Repositories\RedisJobRepository; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class TrimMonitoredJobsTest extends IntegrationTestCase { + use VerifiesDoubles; + public function testTrimmerHasACooldownPeriod(): void { config()->set('horizon.trim', []); $trim = new TrimMonitoredJobs; - $repository = m::mock(JobRepository::class); - $repository->shouldReceive('trimMonitoredJobs')->twice(); + $repository = Double::for(JobRepository::class)->strict(); + $repository->expects('trimMonitoredJobs')->times(2); $this->app->instance(JobRepository::class, $repository); // Should not be called first time since date is initialized... - $trim->handle(new MasterSupervisorLooped(m::mock(MasterSupervisor::class))); + $trim->handle(new MasterSupervisorLooped(Double::for(MasterSupervisor::class)->strict())); $this->assertSame(intdiv(RedisJobRepository::DEFAULT_MONITORED_JOB_RETENTION, 12), $trim->frequency); CarbonImmutable::setTestNow(CarbonImmutable::now()->addMinutes(1600)); // Should only be called twice... - $trim->handle(new MasterSupervisorLooped(m::mock(MasterSupervisor::class))); - $trim->handle(new MasterSupervisorLooped(m::mock(MasterSupervisor::class))); - $trim->handle(new MasterSupervisorLooped(m::mock(MasterSupervisor::class))); + $trim->handle(new MasterSupervisorLooped(Double::for(MasterSupervisor::class)->strict())); + $trim->handle(new MasterSupervisorLooped(Double::for(MasterSupervisor::class)->strict())); + $trim->handle(new MasterSupervisorLooped(Double::for(MasterSupervisor::class)->strict())); CarbonImmutable::setTestNow(); } diff --git a/tests/Integration/Horizon/Feature/TrimRecentJobsTest.php b/tests/Integration/Horizon/Feature/TrimRecentJobsTest.php index 7242fee918..cccf589f02 100644 --- a/tests/Integration/Horizon/Feature/TrimRecentJobsTest.php +++ b/tests/Integration/Horizon/Feature/TrimRecentJobsTest.php @@ -10,27 +10,30 @@ use Hypervel\Horizon\MasterSupervisor; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class TrimRecentJobsTest extends IntegrationTestCase { + use VerifiesDoubles; + public function testTrimmerHasACooldownPeriod(): void { $trim = new TrimRecentJobs; - $repository = m::mock(JobRepository::class); - $repository->shouldReceive('trimRecentJobs')->twice(); + $repository = Double::for(JobRepository::class)->strict(); + $repository->expects('trimRecentJobs')->times(2); $this->app->instance(JobRepository::class, $repository); // Should not be called first time since date is initialized... - $trim->handle(new MasterSupervisorLooped(m::mock(MasterSupervisor::class))); + $trim->handle(new MasterSupervisorLooped(Double::for(MasterSupervisor::class)->strict())); CarbonImmutable::setTestNow(CarbonImmutable::now()->addMinutes(30)); // Should only be called twice... - $trim->handle(new MasterSupervisorLooped(m::mock(MasterSupervisor::class))); - $trim->handle(new MasterSupervisorLooped(m::mock(MasterSupervisor::class))); - $trim->handle(new MasterSupervisorLooped(m::mock(MasterSupervisor::class))); + $trim->handle(new MasterSupervisorLooped(Double::for(MasterSupervisor::class)->strict())); + $trim->handle(new MasterSupervisorLooped(Double::for(MasterSupervisor::class)->strict())); + $trim->handle(new MasterSupervisorLooped(Double::for(MasterSupervisor::class)->strict())); CarbonImmutable::setTestNow(); } diff --git a/tests/Integration/Horizon/Feature/WaitTimeCalculatorTest.php b/tests/Integration/Horizon/Feature/WaitTimeCalculatorTest.php index 4fef9b24bc..bebd679da3 100644 --- a/tests/Integration/Horizon/Feature/WaitTimeCalculatorTest.php +++ b/tests/Integration/Horizon/Feature/WaitTimeCalculatorTest.php @@ -5,15 +5,18 @@ namespace Hypervel\Tests\Integration\Horizon\Feature; use Hypervel\Contracts\Queue\Factory as QueueFactory; -use Hypervel\Contracts\Queue\Queue; use Hypervel\Horizon\Contracts\MetricsRepository; use Hypervel\Horizon\Contracts\SupervisorRepository; +use Hypervel\Horizon\RedisQueue; use Hypervel\Horizon\WaitTimeCalculator; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class WaitTimeCalculatorTest extends IntegrationTestCase { + use VerifiesDoubles; + public function testTimeToClearIsCalculatedPerQueue(): void { $calculator = $this->with_scenario([ @@ -207,19 +210,22 @@ public function testTotalProcessesCanBeZero(): void ); } - protected function with_scenario(array $supervisorSettings, array $queues) + /** + * Create a calculator for the given supervisors and queues. + */ + protected function with_scenario(array $supervisorSettings, array $queues): WaitTimeCalculator { - $queue = m::mock(Queue::class); - $queueFactory = m::mock(QueueFactory::class); - $supervisors = m::mock(SupervisorRepository::class); - $metrics = m::mock(MetricsRepository::class); + $queue = Double::for(RedisQueue::class)->strict(); + $queueFactory = Double::for(QueueFactory::class)->strict(); + $supervisors = Double::for(SupervisorRepository::class)->strict(); + $metrics = Double::for(MetricsRepository::class)->strict(); - $supervisors->shouldReceive('all')->andReturn($supervisorSettings); - $queueFactory->shouldReceive('connection')->andReturn($queue); + $supervisors->allows('all')->returns($supervisorSettings); + $queueFactory->allows('connection')->returns($queue); foreach ($queues as $name => $queueSettings) { - $queue->shouldReceive('readyNow')->with($name)->andReturn($queueSettings['size']); - $metrics->shouldReceive('runtimeForQueue')->with($name)->andReturn($queueSettings['runtime']); + $queue->allows('readyNow')->with($name)->returns($queueSettings['size']); + $metrics->allows('runtimeForQueue')->with($name)->returns($queueSettings['runtime']); } return new WaitTimeCalculator($queueFactory, $supervisors, $metrics); diff --git a/tests/Integration/Horizon/Feature/WorkerProcessTest.php b/tests/Integration/Horizon/Feature/WorkerProcessTest.php index 2d746c15c6..d4c0ef1bb0 100644 --- a/tests/Integration/Horizon/Feature/WorkerProcessTest.php +++ b/tests/Integration/Horizon/Feature/WorkerProcessTest.php @@ -16,7 +16,9 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Facades\Event; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionClass; use ReflectionMethod; use RuntimeException; @@ -24,29 +26,32 @@ class WorkerProcessTest extends IntegrationTestCase { + use VerifiesDoubles; + public function testWorkerProcessSkipsOptionalEventsWhenTheyHaveNoListeners(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(WorkerProcessRestarting::class)->andReturnFalse(); - $events->shouldReceive('hasListeners')->once()->with(UnableToLaunchProcess::class)->andReturnFalse(); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(WorkerProcessRestarting::class)->returns(false); + $events->expects('hasListeners')->with(UnableToLaunchProcess::class)->returns(false); + $events->expects('dispatch')->never(); $this->app->instance('events', $events); - $restartProcess = m::mock(Process::class); - $restartProcess->shouldReceive('isStarted')->once()->andReturnTrue(); - $restartProcess->shouldReceive('start')->once(); + $restartProcess = Double::for(Process::class)->strict(); + // Symfony's destructor calls stop() even for these unstarted process doubles. + $restartProcess->allows('stop')->with(0.0); + $restartProcess->expects('isStarted')->returns(true); + $restartProcess->expects('start'); $restartWorker = new WorkerProcess($restartProcess); $restartWorker->handleOutputUsing(static function (): void { }); (new ReflectionMethod(WorkerProcess::class, 'restart'))->invoke($restartWorker); - $failedProcess = m::mock(Process::class); - $failedProcess->shouldReceive('isRunning')->twice()->andReturnFalse(); + $failedProcess = Double::for(Process::class)->strict(); + $failedProcess->allows('stop')->with(0.0); + $failedProcess->expects('isRunning')->times(2)->returns(false); $failedWorker = new WorkerProcess($failedProcess); $failedWorker->restartAgainAt = CarbonImmutable::now()->subSecond(); (new ReflectionMethod(WorkerProcess::class, 'cooldown'))->invoke($failedWorker); - - $this->addToAssertionCount(1); } public function testControlSignalSentDuringBootstrapIsDeliveredAfterHandlerInstallation(): void @@ -87,8 +92,9 @@ public function testStartRestoresTheParentSignalMaskAfterSuccess(): void { $before = $this->signalMask(); $during = []; - $process = m::mock(Process::class); - $process->shouldReceive('start')->once()->with(m::type(Closure::class))->andReturnUsing( + $process = Double::for(Process::class)->strict(); + $process->allows('stop')->with(0.0); + $process->expects('start')->with(Argument::type(Closure::class))->resolves( static function () use (&$during): void { $during = self::signalMaskStatically(); }, @@ -111,8 +117,9 @@ public function testStartRestoresTheParentSignalMaskWhenStartThrows(): void { $before = $this->signalMask(); $failure = new RuntimeException('start failed'); - $process = m::mock(Process::class); - $process->shouldReceive('start')->once()->andThrow($failure); + $process = Double::for(Process::class)->strict(); + $process->allows('stop')->with(0.0); + $process->expects('start')->throws($failure); try { (new WorkerProcess($process))->start(static function (): void { @@ -143,13 +150,19 @@ public function testParentBlockSetsMatchTheChildHandlerSets(): void public function testKillStopsARunningProcessImmediately(): void { - $process = m::mock(Process::class); - $process->shouldReceive('isRunning')->once()->andReturnTrue(); - $process->shouldReceive('stop')->once()->with(0)->andReturn(0); + $timeouts = []; + $process = Double::for(Process::class)->strict(); + $process->expects('isRunning')->returns(true); + $process->allows('stop')->resolves(static function (float $timeout) use (&$timeouts): int { + $timeouts[] = $timeout; + + return 0; + }); (new WorkerProcess($process))->kill(); - $this->addToAssertionCount(1); + // Check kill() before Symfony's destructor makes its own stop() call. + $this->assertSame([0.0], $timeouts); } public function testWorkerProcessFiresEventIfStoppedProcessCantBeRestarted(): void diff --git a/tests/Integration/Mail/MailFailoverTransportTest.php b/tests/Integration/Mail/MailFailoverTransportTest.php index ff46853c09..dc001c3709 100644 --- a/tests/Integration/Mail/MailFailoverTransportTest.php +++ b/tests/Integration/Mail/MailFailoverTransportTest.php @@ -6,20 +6,23 @@ use Hypervel\Contracts\View\Factory as ViewFactory; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionProperty; use Symfony\Component\Mailer\Transport\FailoverTransport; use Symfony\Component\Mailer\Transport\RoundRobinTransport; class MailFailoverTransportTest extends TestCase { + use VerifiesDoubles; + /** * Set up the test environment. */ protected function setUp(): void { parent::setUp(); - $this->app->instance('view', m::mock(ViewFactory::class)); + $this->app->instance('view', Double::for(ViewFactory::class)->strict()); } public function testGetFailoverTransportWithConfiguredTransports(): void diff --git a/tests/Integration/Mail/MailLogTransportTest.php b/tests/Integration/Mail/MailLogTransportTest.php index 419242b398..a28bf3b2e4 100644 --- a/tests/Integration/Mail/MailLogTransportTest.php +++ b/tests/Integration/Mail/MailLogTransportTest.php @@ -9,7 +9,8 @@ use Hypervel\Mail\Message; use Hypervel\Mail\Transport\LogTransport; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Monolog\Handler\StreamHandler; use Monolog\Logger; use Psr\Log\LoggerInterface; @@ -19,13 +20,15 @@ class MailLogTransportTest extends TestCase { + use VerifiesDoubles; + /** * Set up the test environment. */ protected function setUp(): void { parent::setUp(); - $this->app->instance('view', m::mock(ViewFactory::class)); + $this->app->instance('view', Double::for(ViewFactory::class)->strict()); } public function testGetLogTransportWithConfiguredChannel(): void diff --git a/tests/Integration/Mail/MailManagerTest.php b/tests/Integration/Mail/MailManagerTest.php index 1b02907b2a..0dcc339373 100644 --- a/tests/Integration/Mail/MailManagerTest.php +++ b/tests/Integration/Mail/MailManagerTest.php @@ -24,7 +24,8 @@ use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use Psr\Log\LoggerInterface; @@ -39,13 +40,15 @@ class MailManagerTest extends TestCase { + use VerifiesDoubles; + /** * Set up the test environment. */ protected function setUp(): void { parent::setUp(); - $this->app->instance('view', m::mock(ViewFactory::class)); + $this->app->instance('view', Double::for(ViewFactory::class)->strict()); } public function testSetApplicationRefreshesConfigWithoutRebuildingResolvedMailers(): void @@ -344,9 +347,9 @@ public function testOnDemandTransportsDoNotInheritNamedMailerFallbacks(): void config(['mail.sendmail' => '/usr/sbin/sendmail -bs -i']); config(['mail.log_channel' => 'legacy-channel']); - $logger = m::mock(LoggerInterface::class); - $logManager = m::mock(LogManager::class); - $logManager->shouldReceive('channel')->once()->with(null)->andReturn($logger); + $logger = Double::for(LoggerInterface::class)->strict(); + $logManager = Double::for(LogManager::class)->strict(); + $logManager->expects('channel')->with(null)->returns($logger); $this->app->instance(LoggerInterface::class, $logManager); $manager = new MailManager($this->app); @@ -784,8 +787,8 @@ public function testSendingReleasesIdleSessionsAndPreservesTransactionsAndPins() { $observed = []; $pool = $this->app->make(PoolManager::class)->pool('mail'); - $transport = m::mock(TransportInterface::class); - $transport->shouldReceive('send')->times(3)->andReturnUsing(function () use ($pool, &$observed): null { + $transport = Double::for(TransportInterface::class)->strict(); + $transport->expects('send')->times(3)->resolves(function () use ($pool, &$observed): null { $observed[] = $pool->getBorrowedCount(); return null; diff --git a/tests/Integration/Mail/MailRoundRobinTransportTest.php b/tests/Integration/Mail/MailRoundRobinTransportTest.php index 8d9028e107..3a49780c88 100644 --- a/tests/Integration/Mail/MailRoundRobinTransportTest.php +++ b/tests/Integration/Mail/MailRoundRobinTransportTest.php @@ -6,18 +6,21 @@ use Hypervel\Contracts\View\Factory as ViewFactory; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Mailer\Transport\RoundRobinTransport; class MailRoundRobinTransportTest extends TestCase { + use VerifiesDoubles; + /** * Set up the test environment. */ protected function setUp(): void { parent::setUp(); - $this->app->instance('view', m::mock(ViewFactory::class)); + $this->app->instance('view', Double::for(ViewFactory::class)->strict()); } public function testGetRoundRobinTransportWithConfiguredTransports(): void diff --git a/tests/Integration/Mail/SendingQueuedMailTest.php b/tests/Integration/Mail/SendingQueuedMailTest.php index 986598d4fc..40b72fa5a4 100644 --- a/tests/Integration/Mail/SendingQueuedMailTest.php +++ b/tests/Integration/Mail/SendingQueuedMailTest.php @@ -12,10 +12,13 @@ use Hypervel\Support\Facades\Queue; use Hypervel\Support\Testing\Fakes\QueueFake; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class SendingQueuedMailTest extends TestCase { + use VerifiesDoubles; + protected function defineEnvironment(ApplicationContract $app): void { $app->make('config')->set('mail', [ @@ -42,8 +45,8 @@ public function testMailIsSentWithDefaultLocale(): void public function testMailIsSentWhenRoutingQueue(): void { // QueueFake ignores connection names, so verify selection separately from its push assertions. - $queue = m::mock(QueueFake::class, [$this->app])->makePartial(); - $queue->shouldReceive('connection')->once()->with('mail-connection')->andReturnSelf(); + $queue = Double::for(new QueueFake($this->app))->passthru(); + $queue->expects('connection')->with('mail-connection')->returns($queue); Queue::swap($queue); Queue::route(Mailable::class, 'mail-queue', 'mail-connection'); @@ -55,8 +58,8 @@ public function testMailIsSentWhenRoutingQueue(): void public function testMailIsSentWhenForwardingQueue(): void { - $queue = m::mock(QueueFake::class, [$this->app])->makePartial(); - $queue->shouldReceive('connection')->once()->with('mail-connection')->andReturnSelf(); + $queue = Double::for(new QueueFake($this->app))->passthru(); + $queue->expects('connection')->with('mail-connection')->returns($queue); Queue::swap($queue); Queue::forward('mail-queue', 'main', 'mail-connection'); diff --git a/tests/Integration/Passport/Database/Postgres/SigningKeyConcurrencyTest.php b/tests/Integration/Passport/Database/Postgres/SigningKeyConcurrencyTest.php index 4ff9c2a953..5febb1702d 100644 --- a/tests/Integration/Passport/Database/Postgres/SigningKeyConcurrencyTest.php +++ b/tests/Integration/Passport/Database/Postgres/SigningKeyConcurrencyTest.php @@ -18,7 +18,8 @@ use Hypervel\Testbench\Attributes\RequiresDatabase; use Hypervel\Testbench\Attributes\ResetRefreshDatabaseState; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use function Hypervel\Coroutine\parallel; @@ -27,6 +28,7 @@ class SigningKeyConcurrencyTest extends TestCase { use DatabaseTruncation; + use VerifiesDoubles; /** @var list */ protected static array $keys = []; @@ -77,8 +79,8 @@ public function testConcurrentProvisioningCommitsOneKeyBeforeReleasingTheLock(): { $ready = new Channel(2); $release = new Channel(2); - $generator = m::mock(KeyGenerator::class); - $generator->shouldReceive('generate')->with(2048)->twice()->andReturnUsing(function () use ($ready, $release): array { + $generator = Double::for(KeyGenerator::class)->strict(); + $generator->expects('generate')->with(2048)->times(2)->resolves(function () use ($ready, $release): array { $this->assertSame(0, DB::transactionLevel()); $ready->push(true); $this->assertTrue($release->pop(5)); @@ -116,8 +118,8 @@ public function testImportWaitsForRotationAndPublishesAfterItsWaitingKey(): void 'public_key' => self::$keys[0]['public'], 'private_key' => self::$keys[0]['private'], 'activates_at' => $now->subDay(), ]); - $generator = m::mock(KeyGenerator::class); - $generator->shouldReceive('generate')->with(2048)->once()->andReturn(self::$keys[1]); + $generator = Double::for(KeyGenerator::class)->strict(); + $generator->expects('generate')->with(2048)->returns(self::$keys[1]); $this->app->instance(KeyGenerator::class, $generator); $repository = $this->app->make(SigningKeyRepository::class); $ready = new Channel(1); @@ -155,8 +157,8 @@ public function testPruningCannotDeleteAKeyWhoseRetentionWasRaisedAfterItsRead() 'public_key' => self::$keys[0]['public'], 'private_key' => self::$keys[0]['private'], 'activates_at' => $now->subDay(), ]); - $generator = m::mock(KeyGenerator::class); - $generator->shouldReceive('generate')->with(2048)->once()->andReturn(self::$keys[1]); + $generator = Double::for(KeyGenerator::class)->strict(); + $generator->expects('generate')->with(2048)->returns(self::$keys[1]); $this->app->instance(KeyGenerator::class, $generator); $repository = $this->app->make(SigningKeyRepository::class); $servers = $this->app->make(ServerFactory::class); diff --git a/tests/Integration/Queue/Database/Sqlite/DatabaseQueueReservationTest.php b/tests/Integration/Queue/Database/Sqlite/DatabaseQueueReservationTest.php index a12fac4442..ca7901c04e 100644 --- a/tests/Integration/Queue/Database/Sqlite/DatabaseQueueReservationTest.php +++ b/tests/Integration/Queue/Database/Sqlite/DatabaseQueueReservationTest.php @@ -21,7 +21,8 @@ use Hypervel\Queue\QueueManager; use Hypervel\Queue\QueueRoutes; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PDOException; use PHPUnit\Framework\Attributes\TestWith; @@ -30,6 +31,8 @@ class DatabaseQueueReservationTest extends TestCase { + use VerifiesDoubles; + #[TestWith([null, 'reports'])] #[TestWith(['failover', 'processing'])] public function testFailoverForwardsOnceBeforeStoringOnTheFallbackConnection(?string $connection, string $delegatedQueue): void @@ -39,11 +42,11 @@ public function testFailoverForwardsOnceBeforeStoringOnTheFallbackConnection(?st $routes->forward(['reports' => 'processing', 'processing' => 'archive'], connection: $connection); $database->getContainer()->instance('queue.routes', $routes); $payload = json_encode(['job' => stdClass::class, 'data' => []]); - $primary = m::mock(QueueContract::class); - $primary->shouldReceive('pushRaw')->once()->with($payload, $delegatedQueue)->andThrow(new RuntimeException('Primary unavailable.')); - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->once()->with('primary')->andReturn($primary); - $manager->shouldReceive('connection')->once()->with('database')->andReturn($database); + $primary = Double::for(QueueContract::class)->strict(); + $primary->expects('pushRaw')->with($payload, $delegatedQueue)->throws(new RuntimeException('Primary unavailable.')); + $manager = Double::for(QueueManager::class)->strict(); + $manager->expects('connection')->with('primary')->returns($primary); + $manager->expects('connection')->with('database')->returns($database); $queue = new FailoverQueue($manager, $events, ['primary', 'database']); $queue->setContainer($database->getContainer()); $queue->setConnectionName('failover'); @@ -451,8 +454,8 @@ private function createQueue(?PDO $pdo = null): array $events = new Dispatcher($container); $container->instance(DispatcherContract::class, $events); $database->setEventDispatcher($events); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->with(null)->andReturn($database); + $resolver = Double::for(ConnectionResolverInterface::class)->strict(); + $resolver->allows('connection')->with(null)->returns($database); $queue = new DatabaseQueue($resolver, null, 'jobs'); $queue->setContainer($container); $queue->setConnectionName('database'); diff --git a/tests/Integration/Queue/Database/Sqlite/WorkerResourceLifetimeTest.php b/tests/Integration/Queue/Database/Sqlite/WorkerResourceLifetimeTest.php index 3994ea4bef..e29a26596a 100644 --- a/tests/Integration/Queue/Database/Sqlite/WorkerResourceLifetimeTest.php +++ b/tests/Integration/Queue/Database/Sqlite/WorkerResourceLifetimeTest.php @@ -40,13 +40,16 @@ use Hypervel\Support\Str; use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Swoole\Coroutine\CanceledException; use Throwable; class WorkerResourceLifetimeTest extends TestCase { + use VerifiesDoubles; + protected string $databaseDirectory; /** @@ -115,8 +118,8 @@ public function testOutboxPublicationReleasesOneSlotPoolsAcrossBlockingAndCancel $objectPools = new ObjectPoolManager; $started = new Channel(1); $finish = new Channel(1); - $transport = m::mock(SyncQueue::class . ', ' . PublishesOutboxMessages::class)->makePartial(); - $transport->expects('publishOutboxMessages')->andReturnUsing(function (array $messages) use ($started, $finish, $databasePool): OutboxBatchResult { + $transport = Double::for(WorkerPublishingQueue::class)->passthru(); + $transport->expects('publishOutboxMessages')->resolves(function (array $messages) use ($started, $finish, $databasePool): OutboxBatchResult { $this->assertSame(1, $databasePool->getIdleCount()); $started->push(true); $this->assertTrue($finish->pop(5)); @@ -128,8 +131,8 @@ public function testOutboxPublicationReleasesOneSlotPoolsAcrossBlockingAndCancel static fn (): SyncQueue => $transport, $objectPools, ); - $queues = m::mock(QueueManager::class); - $queues->expects('connection')->with('transport')->andReturn($proxy); + $queues = Double::for(QueueManager::class)->strict(); + $queues->expects('connection')->with('transport')->returns($proxy); $events = $this->app->make(EventDispatcher::class); $settled = false; $observed = false; @@ -144,7 +147,7 @@ public function testOutboxPublicationReleasesOneSlotPoolsAcrossBlockingAndCancel DB::selectOne('SELECT 1'); $observed = true; }); - $relay = new OutboxRelay($repository, $queues, $events, m::mock(ExceptionHandlerContract::class)); + $relay = new OutboxRelay($repository, $queues, $events, Double::for(ExceptionHandlerContract::class)->strict()); $messages = $relay->claim('worker_resource', 100); $failure = null; $result = null; @@ -228,11 +231,11 @@ public function testLifecycleCallbacksReleasePooledConnectionsBeforeTheDaemonAdv $observed[] = 'stopping'; }); - $connection = m::mock(Queue::class); - $connection->expects('getConnectionName')->twice()->andReturn('default'); - $connection->expects('pop')->once()->with('queue')->andReturnNull(); - $manager = m::mock(QueueManager::class); - $manager->expects('connection')->once()->with('default')->andReturn($connection); + $connection = Double::for(Queue::class)->strict(); + $connection->expects('getConnectionName')->times(2)->returns('default'); + $connection->expects('pop')->with('queue')->returns(null); + $manager = Double::for(QueueManager::class)->strict(); + $manager->expects('connection')->with('default')->returns($connection); $worker = new class($manager, $events, $this->app->make(ExceptionHandlerContract::class), static fn (): bool => false) extends Worker { protected function supportsAsyncSignals(): bool { @@ -261,23 +264,23 @@ public function testStoppingWaitsForAdmittedJobDeferredCleanup(): void $stopped = true; }); - $job = m::mock(JobContract::class); - $job->expects('payload')->twice()->andReturn([]); - $job->expects('maxTries')->once()->andReturnNull(); - $job->expects('retryUntil')->once()->andReturnNull(); - $job->expects('attempts')->once()->andReturn(1); - $job->expects('isDeleted')->once()->andReturnFalse(); - $job->expects('isReleased')->once()->andReturnFalse(); - $job->expects('timeout')->once()->andReturnNull(); - $job->expects('fire')->once()->andReturnUsing(static function (): void { + $job = Double::for(JobContract::class)->strict(); + $job->expects('payload')->times(2)->returns([]); + $job->expects('maxTries')->returns(null); + $job->expects('retryUntil')->returns(null); + $job->expects('attempts')->returns(1); + $job->expects('isDeleted')->returns(false); + $job->expects('isReleased')->returns(false); + $job->expects('timeout')->returns(null); + $job->expects('fire')->resolves(static function (): void { DB::selectOne('SELECT 1'); }); - $connection = m::mock(Queue::class); - $connection->expects('getConnectionName')->times(3)->andReturn('default'); - $connection->expects('pop')->once()->with('queue')->andReturn($job); - $manager = m::mock(QueueManager::class); - $manager->expects('connection')->once()->with('default')->andReturn($connection); + $connection = Double::for(Queue::class)->strict(); + $connection->expects('getConnectionName')->times(3)->returns('default'); + $connection->expects('pop')->with('queue')->returns($job); + $manager = Double::for(QueueManager::class)->strict(); + $manager->expects('connection')->with('default')->returns($connection); $worker = new class($manager, $events, $this->app->make(ExceptionHandlerContract::class), static fn (): bool => false) extends Worker { protected function supportsAsyncSignals(): bool { @@ -307,23 +310,23 @@ static function () use (&$modificationStates): void { $modificationStates[] = DB::connection()->hasModifiedRecords(); }, ] as $handler) { - $job = m::mock(JobContract::class); - $job->expects('payload')->twice()->andReturn([]); - $job->expects('maxTries')->once()->andReturnNull(); - $job->expects('retryUntil')->once()->andReturnNull(); - $job->expects('attempts')->once()->andReturn(1); - $job->expects('isDeleted')->once()->andReturnFalse(); - $job->expects('isReleased')->once()->andReturnFalse(); - $job->expects('timeout')->once()->andReturnNull(); - $job->expects('fire')->once()->andReturnUsing($handler); + $job = Double::for(JobContract::class)->strict(); + $job->expects('payload')->times(2)->returns([]); + $job->expects('maxTries')->returns(null); + $job->expects('retryUntil')->returns(null); + $job->expects('attempts')->returns(1); + $job->expects('isDeleted')->returns(false); + $job->expects('isReleased')->returns(false); + $job->expects('timeout')->returns(null); + $job->expects('fire')->resolves($handler); $jobs[] = $job; } - $connection = m::mock(Queue::class); - $connection->expects('getConnectionName')->times(6)->andReturn('default'); - $connection->expects('pop')->twice()->with('queue')->andReturn(...$jobs); - $manager = m::mock(QueueManager::class); - $manager->expects('connection')->twice()->with('default')->andReturn($connection); + $connection = Double::for(Queue::class)->strict(); + $connection->expects('getConnectionName')->times(6)->returns('default'); + $connection->expects('pop')->times(2)->with('queue')->returns(...$jobs); + $manager = Double::for(QueueManager::class)->strict(); + $manager->expects('connection')->times(2)->with('default')->returns($connection); $worker = new class($manager, $this->app->make(EventDispatcher::class), $this->app->make(ExceptionHandlerContract::class), static fn (): bool => false) extends Worker { protected function supportsAsyncSignals(): bool { @@ -347,7 +350,7 @@ public function testTimeoutAndSignalCallbacksReleasePooledConnectionsAfterEachBa $events->listen(WorkerPausing::class, static function (): void { DB::selectOne('SELECT 1'); }); - $worker = new class(m::mock(QueueManager::class), $events, $this->app->make(ExceptionHandlerContract::class), static fn (): bool => false, $timer) extends Worker { + $worker = new class(Double::for(QueueManager::class)->strict(), $events, $this->app->make(ExceptionHandlerContract::class), static fn (): bool => false, $timer) extends Worker { public Channel $completed; /** @@ -395,3 +398,7 @@ protected function terminateTimeoutJobs(WorkerOptions $options): void $this->assertSame(1, $pool->getIdleCount()); } } + +abstract class WorkerPublishingQueue extends SyncQueue implements PublishesOutboxMessages +{ +} diff --git a/tests/Integration/Queue/FailOnExceptionMiddlewareTest.php b/tests/Integration/Queue/FailOnExceptionMiddlewareTest.php index c58bf23a1f..7e60e6eae1 100644 --- a/tests/Integration/Queue/FailOnExceptionMiddlewareTest.php +++ b/tests/Integration/Queue/FailOnExceptionMiddlewareTest.php @@ -17,8 +17,9 @@ use Hypervel\Queue\Middleware\FailOnException; use Hypervel\Testbench\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use Swoole\Coroutine\CanceledException; @@ -26,6 +27,8 @@ class FailOnExceptionMiddlewareTest extends TestCase { + use VerifiesDoubles; + /** * Set up the test environment. */ @@ -124,8 +127,8 @@ static function () use (&$predicateCalled): bool { return true; }, ); - $job = m::mock(); - $job->shouldNotReceive('fail'); + $job = Double::for(FailOnExceptionMiddlewareTestJob::class)->strict(); + $job->expects('fail')->never(); $gate = $this->armCurrentCoroutineCancellation(); $cleanupException = new LogicException('Cleanup failed.'); diff --git a/tests/Integration/Queue/Fixtures/OutboxClaimTestCase.php b/tests/Integration/Queue/Fixtures/OutboxClaimTestCase.php index d0cc135230..8d12522c69 100644 --- a/tests/Integration/Queue/Fixtures/OutboxClaimTestCase.php +++ b/tests/Integration/Queue/Fixtures/OutboxClaimTestCase.php @@ -19,7 +19,8 @@ use Hypervel\Support\Str; use Hypervel\Testbench\Attributes\ResetRefreshDatabaseState; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -28,6 +29,7 @@ #[ResetRefreshDatabaseState] abstract class OutboxClaimTestCase extends TestCase { + use VerifiesDoubles; use DatabaseTruncation; /** @@ -96,7 +98,7 @@ public function testStagingUsesTheExactWriteRoleTransactionAndDrainsThroughItsBa $base = DB::connection(); $database = $base->getName(); $writer = DB::connection($database . '::write'); - $queue = new RedisQueue(m::mock(Factory::class), 'orders'); + $queue = new RedisQueue(Double::for(Factory::class)->strict(), 'orders'); $queue->setContainer($this->app)->setConnectionName('redis'); $base->beginTransaction(); $writer->beginTransaction(); diff --git a/tests/Integration/Queue/Redis/RateLimitedRedisStoreTest.php b/tests/Integration/Queue/Redis/RateLimitedRedisStoreTest.php index 4e706c0c00..c42cbdc7dc 100644 --- a/tests/Integration/Queue/Redis/RateLimitedRedisStoreTest.php +++ b/tests/Integration/Queue/Redis/RateLimitedRedisStoreTest.php @@ -17,13 +17,15 @@ use Hypervel\RateLimiter\Unlimited; use Hypervel\Support\Str; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\RequiresPhpExtension; #[RequiresPhpExtension('redis')] // REMOVED: RateLimitedWithRedis is replaced by RateLimited::store('redis'). class RateLimitedRedisStoreTest extends TestCase { + use VerifiesDoubles; use InteractsWithRedis; public function testUnlimitedJobsAreExecuted(): void @@ -232,12 +234,12 @@ protected function assertJobWasReleasedAfter(RedisRateLimitedTestJob $testJob, i $testJob::$handled = false; $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app); - $job = m::mock(Job::class); + $job = Double::for(Job::class)->strict(); - $job->expects('hasFailed')->andReturn(false); + $job->expects('hasFailed')->returns(false); $job->expects('release')->with($delay); - $job->expects('isReleased')->times(2)->andReturn(true); - $job->expects('isDeletedOrReleased')->andReturn(true); + $job->expects('isReleased')->times(2)->returns(true); + $job->expects('isDeletedOrReleased')->returns(true); $instance->call($job, [ 'command' => serialize($testJob), diff --git a/tests/Integration/Queue/ThrottlesExceptionsTest.php b/tests/Integration/Queue/ThrottlesExceptionsTest.php index 9ec1e948c6..850ef7f5f7 100644 --- a/tests/Integration/Queue/ThrottlesExceptionsTest.php +++ b/tests/Integration/Queue/ThrottlesExceptionsTest.php @@ -22,6 +22,9 @@ use Hypervel\RateLimiter\RateLimiter; use Hypervel\Support\CarbonImmutable; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -30,6 +33,8 @@ class ThrottlesExceptionsTest extends TestCase { + use VerifiesDoubles; + public function testCircuitIsOpenedForJobErrors(): void { $this->assertJobWasReleasedImmediately(CircuitBreakerTestJob::class); @@ -413,15 +418,16 @@ public function release(int $delay): static #[TestWith([true])] public function testCancellationBypassesFailurePolicyAndRateLimitAccounting(bool $cleanupThrows): void { - $limiter = m::mock(Limiter::class); + $limiter = Double::for(Limiter::class)->strict(); $limiter->expects('inspect') - ->with(m::type(Limit::class)) - ->andReturn(new LimitResult(true, 10, 10, 0, 0)); - $limiter->shouldNotReceive('clear', 'consume'); + ->with(Argument::type(Limit::class)) + ->returns(new LimitResult(true, 10, 10, 0, 0)); + $limiter->expects('clear')->never(); + $limiter->expects('consume')->never(); - $rateLimiter = m::mock(RateLimiter::class); - $rateLimiter->expects('store')->with(null)->andReturn($limiter); - $this->app->instance(RateLimiter::class, $rateLimiter); + $rateLimiter = Double::for(RateLimiter::class, override: true)->strict(); + $rateLimiter->expects('store')->with(null)->returns($limiter); + $this->app->instance(RateLimiter::class, $rateLimiter->instance()); $callbacksCalled = false; $middleware = (new ThrottlesExceptions) @@ -446,8 +452,10 @@ public function testCancellationBypassesFailurePolicyAndRateLimitAccounting(bool return false; }); - $job = m::mock(); - $job->shouldNotReceive('release', 'delete', 'fail'); + $job = Double::for(CircuitBreakerTestJob::class)->strict(); + $job->expects('release')->never(); + $job->expects('delete')->never(); + $job->expects('fail')->never(); $gate = $this->armCurrentCoroutineCancellation(); $cleanupException = new RuntimeException('Cleanup failed.'); @@ -480,13 +488,13 @@ public function testIndependentChildCancellationIsCountedAndReleased(): void { $job = (new CircuitBreakerTestJob)->withFakeQueueInteractions(); $failure = new ChildCancellationException(previous: new CanceledException); - $limiter = m::mock(Limiter::class); - $limiter->expects('inspect')->with(m::type(Limit::class))->andReturn(new LimitResult(true, 10, 10, 0, 0)); - $limiter->expects('consume')->with(m::type(Limit::class))->andReturn(new LimitResult(true, 10, 9, 0, 0)); - $limiter->shouldNotReceive('clear'); - $rateLimiter = m::mock(RateLimiter::class); - $rateLimiter->expects('store')->with(null)->andReturn($limiter); - $this->app->instance(RateLimiter::class, $rateLimiter); + $limiter = Double::for(Limiter::class)->strict(); + $limiter->expects('inspect')->with(Argument::type(Limit::class))->returns(new LimitResult(true, 10, 10, 0, 0)); + $limiter->expects('consume')->with(Argument::type(Limit::class))->returns(new LimitResult(true, 10, 9, 0, 0)); + $limiter->expects('clear')->never(); + $rateLimiter = Double::for(RateLimiter::class, override: true)->strict(); + $rateLimiter->expects('store')->with(null)->returns($limiter); + $this->app->instance(RateLimiter::class, $rateLimiter->instance()); $this->spy(ExceptionHandler::class)->expects('report')->with($failure, []); (new ThrottlesExceptions)->backoff(1)->report()->handle($job, static fn () => throw $failure); diff --git a/tests/Integration/Queue/UniqueJobTest.php b/tests/Integration/Queue/UniqueJobTest.php index 94b3022f65..a60490279a 100644 --- a/tests/Integration/Queue/UniqueJobTest.php +++ b/tests/Integration/Queue/UniqueJobTest.php @@ -35,7 +35,8 @@ use Hypervel\Testbench\Attributes\WithMigration; use Hypervel\Testbench\Factories\UserFactory; use Hypervel\Tests\Integration\Queue\QueueTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -46,6 +47,8 @@ #[WithMigration('queue')] class UniqueJobTest extends QueueTestCase { + use VerifiesDoubles; + /** * Define the test environment. */ @@ -407,7 +410,7 @@ public function testScopedQueueFakeReleasesItsLocksAfterSwappingTheFacade(string UniqueTestJob::dispatch(); Queue::assertPushed(UniqueTestJob::class); - Queue::swap(m::mock(QueueManager::class)); + Queue::swap(Double::for(QueueManager::class)->strict()); }); $this->assertSame($manager, Queue::getFacadeRoot()); diff --git a/tests/Integration/Queue/WithoutOverlappingJobsTest.php b/tests/Integration/Queue/WithoutOverlappingJobsTest.php index 43663a2dfb..810cf376a3 100644 --- a/tests/Integration/Queue/WithoutOverlappingJobsTest.php +++ b/tests/Integration/Queue/WithoutOverlappingJobsTest.php @@ -16,10 +16,13 @@ use Hypervel\Queue\Middleware\WithoutOverlapping; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Tests\Integration\Queue\QueueTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class WithoutOverlappingJobsTest extends QueueTestCase { + use VerifiesDoubles; + public function testNonOverlappingJobsAreExecuted(): void { OverlappingTestJob::$handled = false; @@ -127,11 +130,11 @@ public function testLockIsTakenOnTheNamedStore(): void $this->app->get(Cache::class)->lock($lockKey, 10)->acquire(); StoreOverlappingTestJob::$handled = false; - $job = m::mock(Job::class); + $job = Double::for(Job::class)->strict(); - $job->expects('hasFailed')->andReturn(false); - $job->expects('isReleased')->times(2)->andReturn(false); - $job->expects('isDeletedOrReleased')->andReturn(false); + $job->expects('hasFailed')->returns(false); + $job->expects('isReleased')->times(2)->returns(false); + $job->expects('isDeletedOrReleased')->returns(false); $job->expects('delete'); $instance->call($job, [ @@ -144,12 +147,12 @@ public function testLockIsTakenOnTheNamedStore(): void $this->app->get(CacheFactory::class)->store('overlaps')->lock($lockKey, 10)->acquire(); StoreOverlappingTestJob::$handled = false; - $job = m::mock(Job::class); + $job = Double::for(Job::class)->strict(); $job->expects('release'); - $job->expects('hasFailed')->andReturn(false); - $job->expects('isReleased')->times(2)->andReturn(true); - $job->expects('isDeletedOrReleased')->andReturn(true); + $job->expects('hasFailed')->returns(false); + $job->expects('isReleased')->times(2)->returns(true); + $job->expects('isDeletedOrReleased')->returns(true); $instance->call($job, [ 'command' => serialize($command), diff --git a/tests/Integration/Routing/RouteCachingTest.php b/tests/Integration/Routing/RouteCachingTest.php index a7f46b0a46..a9c2b090b1 100644 --- a/tests/Integration/Routing/RouteCachingTest.php +++ b/tests/Integration/Routing/RouteCachingTest.php @@ -9,12 +9,15 @@ use Hypervel\Routing\Contracts\CallableDispatcher as CallableDispatcherContract; use Hypervel\Routing\Contracts\ControllerDispatcher as ControllerDispatcherContract; use Hypervel\Routing\Route; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Laravel\SerializableClosure\SerializableClosure; -use Mockery as m; use ReflectionProperty; class RouteCachingTest extends RoutingTestCase { + use VerifiesDoubles; + public function testWildcardCatchAllRoutes(): void { $this->defineCacheRoutes(file_get_contents(dirname(__DIR__, 2) . '/Routing/Fixtures/wildcard_catch_all_routes.php')); @@ -46,7 +49,7 @@ public function testQueryRoutes(): void public function testSetContainerInvalidatesControllerDispatcherCache(): void { $container1 = new Container; - $dispatcher1 = m::mock(ControllerDispatcherContract::class); + $dispatcher1 = Double::for(ControllerDispatcherContract::class)->strict(); $container1->singleton(ControllerDispatcherContract::class, fn () => $dispatcher1); $route = new Route('GET', '/test', ['uses' => 'FooController@bar']); @@ -57,7 +60,7 @@ public function testSetContainerInvalidatesControllerDispatcherCache(): void // Swap to a new container with a different dispatcher. $container2 = new Container; - $dispatcher2 = m::mock(ControllerDispatcherContract::class); + $dispatcher2 = Double::for(ControllerDispatcherContract::class)->strict(); $container2->singleton(ControllerDispatcherContract::class, fn () => $dispatcher2); $route->setContainer($container2); @@ -69,8 +72,8 @@ public function testSetContainerInvalidatesControllerDispatcherCache(): void public function testSetContainerInvalidatesCallableDispatcherCache(): void { - $dispatcher1 = m::mock(CallableDispatcherContract::class); - $dispatcher1->shouldReceive('dispatch')->once()->andReturn('result1'); + $dispatcher1 = Double::for(CallableDispatcherContract::class)->strict(); + $dispatcher1->expects('dispatch')->returns('result1'); $container1 = new Container; $container1->singleton(CallableDispatcherContract::class, fn () => $dispatcher1); @@ -84,8 +87,8 @@ public function testSetContainerInvalidatesCallableDispatcherCache(): void $this->assertSame($dispatcher1, $cached1); // Swap container — cache should be invalidated. - $dispatcher2 = m::mock(CallableDispatcherContract::class); - $dispatcher2->shouldReceive('dispatch')->once()->andReturn('result2'); + $dispatcher2 = Double::for(CallableDispatcherContract::class)->strict(); + $dispatcher2->expects('dispatch')->returns('result2'); $container2 = new Container; $container2->singleton(CallableDispatcherContract::class, fn () => $dispatcher2); @@ -104,8 +107,8 @@ public function testSerializedCallableIsCachedAcrossCalls(): void $closure = fn () => 'result'; $serialized = serialize(SerializableClosure::unsigned($closure)); - $dispatcher = m::mock(CallableDispatcherContract::class); - $dispatcher->shouldReceive('dispatch')->twice()->andReturn('result'); + $dispatcher = Double::for(CallableDispatcherContract::class)->strict(); + $dispatcher->expects('dispatch')->times(2)->returns('result'); $container = new Container; $container->singleton(CallableDispatcherContract::class, fn () => $dispatcher); @@ -130,8 +133,8 @@ public function testSerializedCallableIsCachedAcrossCalls(): void public function testSetActionInvalidatesCallableCache(): void { - $dispatcher = m::mock(CallableDispatcherContract::class); - $dispatcher->shouldReceive('dispatch')->once()->andReturn('result'); + $dispatcher = Double::for(CallableDispatcherContract::class)->strict(); + $dispatcher->expects('dispatch')->returns('result'); $container = new Container; $container->singleton(CallableDispatcherContract::class, fn () => $dispatcher); @@ -202,10 +205,10 @@ public function testSetActionInvalidatesMissingCache(): void public function testPrepareForSerializationClearsAllCaches(): void { - $dispatcher = m::mock(CallableDispatcherContract::class); - $dispatcher->shouldReceive('dispatch')->once()->andReturn('result'); + $dispatcher = Double::for(CallableDispatcherContract::class)->strict(); + $dispatcher->expects('dispatch')->returns('result'); - $controllerDispatcher = m::mock(ControllerDispatcherContract::class); + $controllerDispatcher = Double::for(ControllerDispatcherContract::class)->strict(); $container = new Container; $container->singleton(CallableDispatcherContract::class, fn () => $dispatcher); diff --git a/tests/Integration/Scout/Database/Postgres/DatabaseVectorImportTest.php b/tests/Integration/Scout/Database/Postgres/DatabaseVectorImportTest.php index 4207def3a1..cd68d9d279 100644 --- a/tests/Integration/Scout/Database/Postgres/DatabaseVectorImportTest.php +++ b/tests/Integration/Scout/Database/Postgres/DatabaseVectorImportTest.php @@ -19,12 +19,15 @@ use Hypervel\Support\Facades\Schema; use Hypervel\Testbench\Attributes\RequiresDatabase; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; #[RequiresDatabase('pgsql')] class DatabaseVectorImportTest extends TestCase { + use VerifiesDoubles; + /** * Register the database search engine. */ @@ -66,8 +69,8 @@ public function testImportUsesTheQueryConnectionCapacity(int $capacity, bool $wr try { if ($wrapResolver) { - $decorator = m::mock(ConnectionResolverInterface::class); - $decorator->shouldReceive('connection')->andReturnUsing($resolver->connection(...)); + $decorator = Double::for(ConnectionResolverInterface::class)->strict(); + $decorator->allows('connection')->resolves($resolver->connection(...)); Model::setConnectionResolver($decorator); } diff --git a/tests/Integration/Session/Database/DatabaseSessionHandlerTestCase.php b/tests/Integration/Session/Database/DatabaseSessionHandlerTestCase.php index 9c28af0113..309c079173 100644 --- a/tests/Integration/Session/Database/DatabaseSessionHandlerTestCase.php +++ b/tests/Integration/Session/Database/DatabaseSessionHandlerTestCase.php @@ -23,11 +23,14 @@ use Hypervel\Support\Facades\Schema; use Hypervel\Tests\Integration\Database\DatabaseTestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; abstract class DatabaseSessionHandlerTestCase extends DatabaseTestCase { + use VerifiesDoubles; + protected const string CURRENT_SESSION_ID = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; protected const string OTHER_SESSION_ID = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'; @@ -295,8 +298,8 @@ public function testUnresolvedExpiredWriteClearsItsOldOwnerAtTheExactBoundary(): public function testUnownedWriteClearsItsOwnerWithoutResolvingTheGuard(): void { - $guard = m::mock(Guard::class); - $guard->shouldReceive('id')->never(); + $guard = Double::for(Guard::class)->strict(); + $guard->expects('id')->never(); $this->useGuard($guard); $this->insertSession( @@ -372,8 +375,8 @@ public function testStoreInvalidationCannotPersistAnOwnedReplacement(): void public function testFailedReplacementWriteRetryRemainsUnowned(): void { - $guard = m::mock(Guard::class); - $guard->shouldReceive('id')->never(); + $guard = Double::for(Guard::class)->strict(); + $guard->expects('id')->never(); $this->useGuard($guard); $this->insertSession( @@ -772,8 +775,8 @@ protected function insertSession( protected function useGuardIdentity(int|string|null $userId, ?string $authProvider = 'users'): void { - $guard = m::mock(Guard::class); - $guard->shouldReceive('id')->andReturn($userId); + $guard = Double::for(Guard::class)->strict(); + $guard->allows('id')->returns($userId); $this->useGuard($guard, $authProvider); } diff --git a/tests/Integration/Session/Redis/RedisSessionHandlerTest.php b/tests/Integration/Session/Redis/RedisSessionHandlerTest.php index aedf72ad64..4ac20c6659 100644 --- a/tests/Integration/Session/Redis/RedisSessionHandlerTest.php +++ b/tests/Integration/Session/Redis/RedisSessionHandlerTest.php @@ -24,7 +24,8 @@ use Hypervel\Session\UserSessionIdentity; use Hypervel\Support\CarbonImmutable; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Redis as PhpRedis; @@ -32,6 +33,7 @@ class RedisSessionHandlerTest extends TestCase { use InteractsWithRedis; use RequiresHashFieldExpiration; + use VerifiesDoubles; private const string SESSION_ID = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; @@ -214,10 +216,10 @@ public function testProviderlessAuthenticatedWriteClearsManagedOwnership(): void public function testTrackedWritesUseOnlyTheCurrentlySelectedGuard(): void { $this->skipIfHashFieldExpirationUnsupported(); - $primaryGuard = m::mock(Guard::class); - $primaryGuard->shouldReceive('id')->once()->andReturn('primary-user'); - $secondaryGuard = m::mock(Guard::class); - $secondaryGuard->shouldReceive('id')->once()->andReturn('secondary-user'); + $primaryGuard = Double::for(Guard::class)->strict(); + $primaryGuard->expects('id')->returns('primary-user'); + $secondaryGuard = Double::for(Guard::class)->strict(); + $secondaryGuard->expects('id')->returns('secondary-user'); $config = $this->app->make('config'); $config->set([ 'auth.defaults.guard' => 'primary', @@ -765,8 +767,8 @@ private function sessionManager( private function configureSelectedUser(string $userId): void { - $guard = m::mock(Guard::class); - $guard->shouldReceive('id')->andReturn($userId); + $guard = Double::for(Guard::class)->strict(); + $guard->allows('id')->returns($userId); $this->app->make('config')->set([ 'auth.defaults.guard' => 'web', 'auth.guards.web' => ['driver' => 'session-test', 'provider' => 'users'], @@ -799,8 +801,8 @@ private function identityContainer( ?string $authProvider = 'users', ): Container { $guardCalls ??= $writes; - $guard = m::mock(Guard::class); - $guard->shouldReceive('id')->times($guardCalls)->andReturn($userId); + $guard = Double::for(Guard::class)->strict(); + $guard->expects('id')->times($guardCalls)->returns($userId); $guardConfig = ['driver' => 'session-test']; diff --git a/tests/Integration/Support/MultipleInstanceManagerTest.php b/tests/Integration/Support/MultipleInstanceManagerTest.php index 5a50f232a0..cf69619d1d 100644 --- a/tests/Integration/Support/MultipleInstanceManagerTest.php +++ b/tests/Integration/Support/MultipleInstanceManagerTest.php @@ -8,11 +8,14 @@ use Hypervel\Contracts\Foundation\Application; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Integration\Support\Fixtures\MultipleInstanceManager; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class MultipleInstanceManagerTest extends TestCase { + use VerifiesDoubles; + public function testConfigurableInstancesCanBeResolved(): void { $manager = new MultipleInstanceManager($this->app); @@ -46,10 +49,10 @@ public function testSetApplicationRefreshesConfigWithoutRebuildingResolvedInstan ], ], ]); - $application = m::mock(Application::class); - $application->shouldReceive('make')->once()->with('config')->andReturn($config); + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('make')->with('config')->returns($config); - $this->assertSame($manager, $manager->setApplication($application)); + $this->assertSame($manager, $manager->setApplication($application->instance())); $this->assertSame($resolved, $manager->instance('foo')); $this->assertSame('replacement', $manager->instance('configured')->config['source']); } diff --git a/tests/Integration/View/BladeTest.php b/tests/Integration/View/BladeTest.php index c8af3bc9ed..83c64fe795 100644 --- a/tests/Integration/View/BladeTest.php +++ b/tests/Integration/View/BladeTest.php @@ -12,7 +12,8 @@ use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; use Hypervel\View\Component; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Override; use PHPUnit\Framework\Attributes\RequiresOperatingSystem; use PHPUnit\Framework\Attributes\RunInSeparateProcess; @@ -23,6 +24,8 @@ class BladeTest extends TestCase { + use VerifiesDoubles; + /** * Clear compiled views after the test. */ @@ -297,11 +300,13 @@ public function testViewCacheCommandDeduplicatesPathsBeforeCompiling(): void View::addNamespace('templates', join_paths(__DIR__, 'Fixtures', 'templates')); View::addNamespace('components', join_paths(__DIR__, 'Fixtures', 'templates', 'components')); - // Unmatched compile() calls need the configured compiler; a class-based partial mock skips its constructor. - Blade::swap(m::mock(Blade::getFacadeRoot())->makePartial()); - Blade::expects('compile')->with(realpath(__DIR__ . '/Fixtures/templates/components/panel.blade.php')); + $path = realpath(__DIR__ . '/Fixtures/templates/components/panel.blade.php'); + $compiler = Double::for(Blade::getFacadeRoot())->passthru(); + Blade::swap($compiler); $this->artisan('view:cache'); + + $compiler->received('compile')->with($path)->times(1); } #[RequiresOperatingSystem('Linux|Darwin')] diff --git a/tests/Jwt/BlacklistTest.php b/tests/Jwt/BlacklistTest.php index eb6ed477a9..4b06cdfa7e 100644 --- a/tests/Jwt/BlacklistTest.php +++ b/tests/Jwt/BlacklistTest.php @@ -11,16 +11,17 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Facades\Date; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; class BlacklistTest extends TestCase { - /** - * @var MockInterface|StorageContract - */ - private StorageContract $storage; + use VerifiesDoubles; + + private StorageContract&DoubleInterface $storage; private Blacklist $blacklist; @@ -33,7 +34,7 @@ protected function setUp(): void CarbonImmutable::setTestNow('2000-01-01T00:00:00.000000Z'); $this->testNowTimestamp = Date::now()->timestamp; - $this->storage = m::mock(StorageContract::class); + $this->storage = Double::for(StorageContract::class)->strict(); $this->blacklist = new Blacklist($this->storage, refreshTTL: 20160); } @@ -50,15 +51,13 @@ public function testAddAValidTokenToTheBlacklist(): void $refreshTTL = 20161; - $this->storage->shouldReceive('get') + $this->storage->expects('get') ->with('foo') - ->once() - ->andReturn([]); + ->returns([]); - $this->storage->shouldReceive('add') + $this->storage->expects('add') ->with('foo', ['valid_until' => $this->testNowTimestamp], $refreshTTL + 1) - ->once() - ->andReturnTrue(); + ->returns(true); $this->assertTrue($this->blacklist->setRefreshTTL($refreshTTL)->add($payload)); } @@ -73,11 +72,10 @@ public function testAddATokenWithNoExpToTheBlacklistForever(): void 'jti' => 'foo', ]; - $this->storage->shouldReceive('get')->with('foo')->once()->andReturnNull(); - $this->storage->shouldReceive('forever') + $this->storage->expects('get')->with('foo')->returns(null); + $this->storage->expects('forever') ->with('foo', ['valid_until' => $this->testNowTimestamp]) - ->once() - ->andReturnTrue(); + ->returns(true); $this->assertTrue($this->blacklist->add($payload)); } @@ -90,11 +88,10 @@ public function testAddATokenWithNullExpirationToTheBlacklistForever(): void 'jti' => 'foo', ]; - $this->storage->shouldReceive('get')->with('foo')->once()->andReturnNull(); - $this->storage->shouldReceive('forever') + $this->storage->expects('get')->with('foo')->returns(null); + $this->storage->expects('forever') ->with('foo', ['valid_until' => $this->testNowTimestamp]) - ->once() - ->andReturnTrue(); + ->returns(true); $this->assertTrue($this->blacklist->add($payload)); } @@ -107,11 +104,10 @@ public function testAddARefreshableTokenForeverWhenTheRefreshWindowIsDisabled(): 'jti' => 'foo', ]; - $this->storage->shouldReceive('get')->with('foo')->once()->andReturnNull(); - $this->storage->shouldReceive('forever') + $this->storage->expects('get')->with('foo')->returns(null); + $this->storage->expects('forever') ->with('foo', ['valid_until' => $this->testNowTimestamp]) - ->once() - ->andReturnTrue(); + ->returns(true); $this->assertTrue($this->blacklist->setRefreshTTL(null)->add($payload)); } @@ -126,8 +122,8 @@ public function testPermanentBlacklistEntryHonorsGraceWhenRefreshWindowIsDisable $entry = ['valid_until' => $this->testNowTimestamp + 300]; $blacklist = new Blacklist($this->storage, gracePeriod: 300, refreshTTL: null); - $this->storage->shouldReceive('get')->with('foo')->times(3)->andReturn(null, $entry, $entry); - $this->storage->shouldReceive('forever')->with('foo', $entry)->once()->andReturnTrue(); + $this->storage->expects('get')->with('foo')->times(3)->returns(null, $entry, $entry); + $this->storage->expects('forever')->with('foo', $entry)->returns(true); $this->assertTrue($blacklist->add($payload)); $this->assertFalse($blacklist->has($payload)); @@ -147,8 +143,8 @@ public function testPermanentBlacklistEntryDoesNotSlideGraceOnRepeatedAdd(): voi $entry = ['valid_until' => $this->testNowTimestamp + 300]; $blacklist = new Blacklist($this->storage, gracePeriod: 300, refreshTTL: null); - $this->storage->shouldReceive('get')->with('foo')->once()->andReturn($entry); - $this->storage->shouldReceive('forever')->never(); + $this->storage->expects('get')->with('foo')->returns($entry); + $this->storage->expects('forever')->never(); $this->assertTrue($blacklist->add($payload)); } @@ -157,7 +153,7 @@ public function testAddTokenToBlacklistForeverReturnsTheStorageResult(): void { $payload = ['jti' => 'foo']; - $this->storage->shouldReceive('forever')->with('foo', 'forever')->once()->andReturnFalse(); + $this->storage->expects('forever')->with('foo', 'forever')->returns(false); $this->assertFalse($this->blacklist->addForever($payload)); } @@ -172,12 +168,11 @@ public function testMissingIssuedAtUsesTheFiniteExpirationBoundary(array $issued ]; $blacklist = new Blacklist($this->storage, refreshTTL: null, leeway: 60); - $this->storage->shouldReceive('get')->with('foo')->once()->andReturnNull(); - $this->storage->shouldReceive('forever')->never(); - $this->storage->shouldReceive('add') + $this->storage->expects('get')->with('foo')->returns(null); + $this->storage->expects('forever')->never(); + $this->storage->expects('add') ->with('foo', ['valid_until' => $this->testNowTimestamp], 12) - ->once() - ->andReturnTrue(); + ->returns(true); $this->assertTrue($blacklist->add($payload)); } @@ -203,15 +198,13 @@ public function testReturnTrueWhenAddingAnExpiredTokenToTheBlacklist(): void $refreshTTL = 20161; - $this->storage->shouldReceive('get') + $this->storage->expects('get') ->with('foo') - ->once() - ->andReturn([]); + ->returns([]); - $this->storage->shouldReceive('add') + $this->storage->expects('add') ->with('foo', ['valid_until' => $this->testNowTimestamp], $refreshTTL + 1) - ->once() - ->andReturnTrue(); + ->returns(true); $this->assertTrue($this->blacklist->setRefreshTTL($refreshTTL)->add($payload)); } @@ -229,12 +222,11 @@ public function testReturnTrueEarlyWhenAddingAnItemAndItAlreadyExists(): void $refreshTTL = 20161; - $this->storage->shouldReceive('get') + $this->storage->expects('get') ->with('foo') - ->once() - ->andReturn(['valid_until' => $this->testNowTimestamp]); + ->returns(['valid_until' => $this->testNowTimestamp]); - $this->storage->shouldReceive('add') + $this->storage->expects('add') ->with('foo', ['valid_until' => $this->testNowTimestamp], $refreshTTL + 1) ->never(); @@ -255,15 +247,13 @@ public function testBlacklistTtlRoundsFractionalMinutesUp(): void 'jti' => 'foo', ]; - $this->storage->shouldReceive('get') + $this->storage->expects('get') ->with('foo') - ->once() - ->andReturn([]); + ->returns([]); - $this->storage->shouldReceive('add') + $this->storage->expects('add') ->with('foo', ['valid_until' => $nowTimestamp], 2) - ->once() - ->andReturnTrue(); + ->returns(true); $this->assertTrue($this->blacklist->setRefreshTTL(0)->add($payload)); } @@ -282,18 +272,16 @@ public function testFiniteLifetimeStaysPositiveWhenTheClockAdvancesDuringTheStor $blacklist = new Blacklist($this->storage, refreshTTL: 0); // Model the clock advancing while the storage lookup is in flight. - $this->storage->shouldReceive('get') + $this->storage->expects('get') ->with('foo') - ->once() - ->andReturnUsing(function () use ($base) { + ->resolves(function () use ($base) { CarbonImmutable::setTestNow($base->addSeconds(2)); return null; }); - $this->storage->shouldReceive('add') - ->with('foo', m::type('array'), m::on(fn (int $minutes): bool => $minutes >= 1)) - ->once() - ->andReturnTrue(); + $this->storage->expects('add') + ->with('foo', Argument::type('array'), Argument::satisfies(fn (int $minutes): bool => $minutes >= 1)) + ->returns(true); $this->assertTrue($blacklist->add($payload)); } @@ -307,11 +295,10 @@ public function testExpirationLeewayCanDefineTheBlacklistLifetime(): void ]; $blacklist = new Blacklist($this->storage, refreshTTL: 5, leeway: 120); - $this->storage->shouldReceive('get')->with('foo')->once()->andReturnNull(); - $this->storage->shouldReceive('add') + $this->storage->expects('get')->with('foo')->returns(null); + $this->storage->expects('add') ->with('foo', ['valid_until' => $this->testNowTimestamp], 13) - ->once() - ->andReturnTrue(); + ->returns(true); $this->assertTrue($blacklist->add($payload)); } @@ -326,11 +313,10 @@ public function testRefreshWindowCanDefineTheBlacklistLifetime(int $leeway, int ]; $blacklist = new Blacklist($this->storage, refreshTTL: 20, leeway: $leeway); - $this->storage->shouldReceive('get')->with('foo')->once()->andReturnNull(); - $this->storage->shouldReceive('add') + $this->storage->expects('get')->with('foo')->returns(null); + $this->storage->expects('add') ->with('foo', ['valid_until' => $this->testNowTimestamp], $minutes) - ->once() - ->andReturnTrue(); + ->returns(true); $this->assertTrue($blacklist->add($payload)); } @@ -357,7 +343,9 @@ public function testTerminalTokensSkipBlacklistStorage(int $expirationOffset): v ]; $blacklist = new Blacklist($this->storage, refreshTTL: null, leeway: 60); - $this->storage->shouldReceive('get', 'add', 'forever')->never(); + $this->storage->expects('get')->never(); + $this->storage->expects('add')->never(); + $this->storage->expects('forever')->never(); $this->assertTrue($blacklist->add($payload)); } @@ -382,14 +370,13 @@ public function testBlacklistEntryIsRetainedWhileExpirationLeewayStillAcceptsThe // so the entry must be written. (new ExpiredClaim(['leeway' => 60]))->validate($payload); - $this->storage->shouldReceive('get') + $this->storage->expects('get') ->with('foo') - ->twice() - ->andReturn(null, ['valid_until' => $this->testNowTimestamp]); - $this->storage->shouldReceive('add') + ->times(2) + ->returns(null, ['valid_until' => $this->testNowTimestamp]); + $this->storage->expects('add') ->with('foo', ['valid_until' => $this->testNowTimestamp], 2) - ->once() - ->andReturnTrue(); + ->returns(true); $this->assertTrue($blacklist->add($payload)); $this->assertTrue($blacklist->has($payload)); @@ -403,8 +390,8 @@ public function testFiniteStorageFailureIsReturned(): void 'jti' => 'foo', ]; - $this->storage->shouldReceive('get')->with('foo')->once()->andReturnNull(); - $this->storage->shouldReceive('add')->with('foo', m::type('array'), 2)->once()->andReturnFalse(); + $this->storage->expects('get')->with('foo')->returns(null); + $this->storage->expects('add')->with('foo', Argument::type('array'), 2)->returns(false); $this->assertFalse($this->blacklist->setRefreshTTL(0)->add($payload)); } @@ -413,11 +400,10 @@ public function testPermanentStorageFailureIsReturned(): void { $payload = ['iat' => $this->testNowTimestamp, 'jti' => 'foo']; - $this->storage->shouldReceive('get')->with('foo')->once()->andReturnNull(); - $this->storage->shouldReceive('forever') + $this->storage->expects('get')->with('foo')->returns(null); + $this->storage->expects('forever') ->with('foo', ['valid_until' => $this->testNowTimestamp]) - ->once() - ->andReturnFalse(); + ->returns(false); $this->assertFalse($this->blacklist->add($payload)); } @@ -433,7 +419,7 @@ public function testCheckWhetherATokenHasBeenBlacklisted(): void 'jti' => 'foobar', ]; - $this->storage->shouldReceive('get')->with('foobar')->once()->andReturn(['valid_until' => $this->testNowTimestamp]); + $this->storage->expects('get')->with('foobar')->returns(['valid_until' => $this->testNowTimestamp]); $this->assertTrue($this->blacklist->has($payload)); } @@ -450,7 +436,7 @@ public function testCheckWhetherATokenHasNotBeenBlacklisted(mixed $result): void 'jti' => 'foobar', ]; - $this->storage->shouldReceive('get')->with('foobar')->once()->andReturn($result); + $this->storage->expects('get')->with('foobar')->returns($result); $this->assertFalse($this->blacklist->has($payload)); } @@ -477,7 +463,7 @@ public function testCheckWhetherATokenHasBeenBlacklistedForever(): void 'jti' => 'foobar', ]; - $this->storage->shouldReceive('get')->with('foobar')->once()->andReturn('forever'); + $this->storage->expects('get')->with('foobar')->returns('forever'); $this->assertTrue($this->blacklist->has($payload)); } @@ -493,7 +479,7 @@ public function testCheckWhetherATokenHasBeenBlacklistedWhenTheTokenIsNotBlackli 'jti' => 'foobar', ]; - $this->storage->shouldReceive('get')->with('foobar')->once()->andReturn(null); + $this->storage->expects('get')->with('foobar')->returns(null); $this->assertFalse($this->blacklist->has($payload)); } @@ -509,7 +495,7 @@ public function testRemoveATokenFromTheBlacklist(): void 'jti' => 'foobar', ]; - $this->storage->shouldReceive('destroy')->with('foobar')->andReturn(true); + $this->storage->allows('destroy')->with('foobar')->returns(true); $this->assertTrue($this->blacklist->remove($payload)); } @@ -525,7 +511,7 @@ public function testSetACustomUniqueKeyForTheBlacklist(): void 'jti' => 'foobar', ]; - $this->storage->shouldReceive('get')->with('1')->once()->andReturn(['valid_until' => $this->testNowTimestamp]); + $this->storage->expects('get')->with('1')->returns(['valid_until' => $this->testNowTimestamp]); $this->assertTrue($this->blacklist->setKey('sub')->has($payload)); $this->assertSame('1', $this->blacklist->getKey($payload)); @@ -533,7 +519,7 @@ public function testSetACustomUniqueKeyForTheBlacklist(): void public function testEmptyTheBlacklistReturnsTheStorageResult(): void { - $this->storage->shouldReceive('flush')->once()->andReturnFalse(); + $this->storage->expects('flush')->returns(false); $this->assertFalse($this->blacklist->clear()); } diff --git a/tests/Jwt/Http/ParserTest.php b/tests/Jwt/Http/ParserTest.php index 75f29001be..0ce6d394c9 100644 --- a/tests/Jwt/Http/ParserTest.php +++ b/tests/Jwt/Http/ParserTest.php @@ -11,11 +11,14 @@ use Hypervel\Jwt\Http\Parser\InputSource; use Hypervel\Jwt\Http\Parser\Parser; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class ParserTest extends TestCase { + use VerifiesDoubles; + public function testParsesBearerHeader(): void { $parser = new Parser([new AuthHeaders]); @@ -214,17 +217,17 @@ public function testUsesTheFirstExtractorInTheChainThatFindsAToken(): void { $request = Request::create('/'); - $missing = m::mock(TokenExtractor::class); - $missing->shouldReceive('parseToken')->with($request)->once()->andReturnNull(); + $missing = Double::for(TokenExtractor::class)->strict(); + $missing->expects('parseToken')->with($request)->returns(null); - $empty = m::mock(TokenExtractor::class); - $empty->shouldReceive('parseToken')->with($request)->once()->andReturn(''); + $empty = Double::for(TokenExtractor::class)->strict(); + $empty->expects('parseToken')->with($request)->returns(''); - $found = m::mock(TokenExtractor::class); - $found->shouldReceive('parseToken')->with($request)->once()->andReturn('custom-token'); + $found = Double::for(TokenExtractor::class)->strict(); + $found->expects('parseToken')->with($request)->returns('custom-token'); - $unused = m::mock(TokenExtractor::class); - $unused->shouldNotReceive('parseToken'); + $unused = Double::for(TokenExtractor::class)->strict(); + $unused->expects('parseToken')->never(); $parser = new Parser([$missing, $empty, $found, $unused]); diff --git a/tests/Jwt/JwtGuardContextTest.php b/tests/Jwt/JwtGuardContextTest.php index acf71d492a..d4ded26c2e 100644 --- a/tests/Jwt/JwtGuardContextTest.php +++ b/tests/Jwt/JwtGuardContextTest.php @@ -17,10 +17,13 @@ use Hypervel\Jwt\JwtServiceProvider; use Hypervel\Support\Facades\Route; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class JwtGuardContextTest extends TestCase { + use VerifiesDoubles; + protected ManagerContract $jwtManager; protected UserProvider $provider; @@ -29,8 +32,8 @@ protected function setUp(): void { parent::setUp(); - $this->jwtManager = m::mock(ManagerContract::class); - $this->provider = m::mock(UserProvider::class); + $this->jwtManager = Double::for(ManagerContract::class)->strict(); + $this->provider = Double::for(UserProvider::class)->strict(); $this->app->instance('jwt', $this->jwtManager); $this->app->make(AuthManager::class)->provider( @@ -96,8 +99,8 @@ protected function defineEnvironment(ApplicationContract $app): void public function testBearerResolutionRunsAgainForEachRequest(): void { $user = $this->user(1); - $this->jwtManager->shouldReceive('decode')->with('request-token')->twice()->andReturn(['sub' => 1]); - $this->provider->shouldReceive('retrieveById')->with(1)->twice()->andReturn($user); + $this->jwtManager->expects('decode')->with('request-token')->times(2)->returns(['sub' => 1]); + $this->provider->expects('retrieveById')->with(1)->times(2)->returns($user); $this->withHeader('Authorization', 'Bearer request-token') ->getJson('/jwt-context/user') @@ -111,8 +114,8 @@ public function testBearerResolutionRunsAgainForEachRequest(): void public function testAuthMiddlewareAcceptsAValidToken(): void { - $this->jwtManager->shouldReceive('decode')->with('valid-token')->once()->andReturn(['sub' => 1]); - $this->provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($this->user(1)); + $this->jwtManager->expects('decode')->with('valid-token')->returns(['sub' => 1]); + $this->provider->expects('retrieveById')->with(1)->returns($this->user(1)); $this->withHeader('Authorization', 'Bearer valid-token') ->getJson('/jwt-context/protected') @@ -122,19 +125,19 @@ public function testAuthMiddlewareAcceptsAValidToken(): void public function testRequestWithoutATokenIsRejectedByAuthMiddlewareAndAGuestElsewhere(): void { - $this->jwtManager->shouldNotReceive('decode'); - $this->provider->shouldNotReceive('retrieveById'); + $this->jwtManager->expects('decode')->never(); + $this->provider->expects('retrieveById')->never(); $this->assertRejectedByAuthMiddlewareAndAGuestElsewhere(); } public function testInvalidTokenIsRejectedByAuthMiddlewareAndAGuestElsewhere(): void { - $this->jwtManager->shouldReceive('decode') + $this->jwtManager->expects('decode') ->with('invalid-token') - ->twice() - ->andThrow(new TokenInvalidException('Token Signature could not be verified.')); - $this->provider->shouldNotReceive('retrieveById'); + ->times(2) + ->throws(new TokenInvalidException('Token Signature could not be verified.')); + $this->provider->expects('retrieveById')->never(); $this->withHeader('Authorization', 'Bearer invalid-token'); @@ -143,8 +146,8 @@ public function testInvalidTokenIsRejectedByAuthMiddlewareAndAGuestElsewhere(): public function testTokenForAMissingUserIsRejectedByAuthMiddlewareAndAGuestElsewhere(): void { - $this->jwtManager->shouldReceive('decode')->with('orphan-token')->twice()->andReturn(['sub' => 404]); - $this->provider->shouldReceive('retrieveById')->with(404)->twice()->andReturnNull(); + $this->jwtManager->expects('decode')->with('orphan-token')->times(2)->returns(['sub' => 404]); + $this->provider->expects('retrieveById')->with(404)->times(2)->returns(null); $this->withHeader('Authorization', 'Bearer orphan-token'); @@ -153,8 +156,8 @@ public function testTokenForAMissingUserIsRejectedByAuthMiddlewareAndAGuestElsew public function testCookieTokenIsReadAfterEncryptCookiesDecryptsIt(): void { - $this->jwtManager->shouldReceive('decode')->with('cookie-token')->once()->andReturn(['sub' => 1]); - $this->provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($this->user(1)); + $this->jwtManager->expects('decode')->with('cookie-token')->returns(['sub' => 1]); + $this->provider->expects('retrieveById')->with(1)->returns($this->user(1)); $this->withCredentials() ->withCookie('token', 'cookie-token') @@ -165,7 +168,7 @@ public function testCookieTokenIsReadAfterEncryptCookiesDecryptsIt(): void public function testCookieThatCannotBeDecryptedLeavesTheRequestAGuest(): void { - $this->jwtManager->shouldNotReceive('decode'); + $this->jwtManager->expects('decode')->never(); $this->withCredentials() ->withUnencryptedCookie('token', 'not-encrypted') @@ -176,8 +179,8 @@ public function testCookieThatCannotBeDecryptedLeavesTheRequestAGuest(): void public function testExplicitUserSurvivesAcrossRequestsWithoutResolvingBearerTokens(): void { - $this->jwtManager->shouldNotReceive('decode'); - $this->provider->shouldNotReceive('retrieveById'); + $this->jwtManager->expects('decode')->never(); + $this->provider->expects('retrieveById')->never(); $this->app->make('auth')->guard('jwt')->setUser($this->user(10)); @@ -194,7 +197,8 @@ public function testExplicitUserSurvivesAcrossRequestsWithoutResolvingBearerToke public function testRequestDrivenLogoutClearsParentExplicitUser(): void { - $this->jwtManager->shouldNotReceive('hasBlacklistEnabled', 'invalidate'); + $this->jwtManager->expects('hasBlacklistEnabled')->never(); + $this->jwtManager->expects('invalidate')->never(); $this->app->make('auth')->guard('jwt')->setUser($this->user(10)); $this->postJson('/jwt-context/logout')->assertNoContent(); @@ -204,7 +208,7 @@ public function testRequestDrivenLogoutClearsParentExplicitUser(): void public function testRequestDrivenLoginDoesNotAuthenticateParentWithoutBearerToken(): void { - $this->jwtManager->shouldReceive('encode')->once()->andReturn('new-token'); + $this->jwtManager->expects('encode')->returns('new-token'); $this->postJson('/jwt-context/login') ->assertOk() diff --git a/tests/Jwt/JwtGuardEventTest.php b/tests/Jwt/JwtGuardEventTest.php index 710ebe3667..d1612dd92f 100644 --- a/tests/Jwt/JwtGuardEventTest.php +++ b/tests/Jwt/JwtGuardEventTest.php @@ -25,21 +25,25 @@ use Hypervel\Jwt\Http\Parser\Parser; use Hypervel\Jwt\JwtGuard; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; class JwtGuardEventTest extends TestCase { + use VerifiesDoubles; + public function testDoesNotDispatchEventsWhenNoListenersExist(): void { $user = $this->user(1); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturn('token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->returns('token'); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnFalse(); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class)->strict(); + $events->allows('hasListeners')->returns(false); + $events->expects('dispatch')->never(); $guard = $this->createGuard(jwtManager: $jwtManager); $guard->setDispatcher($events); @@ -48,8 +52,8 @@ public function testDoesNotDispatchEventsWhenNoListenersExist(): void public function testAttemptingEventIsDispatchedWhenListening(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->once()->andReturn(null); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveByCredentials')->returns(null); $events = $this->dispatcherListeningFor(Attempting::class, function (Attempting $event): bool { return $event->guard === 'jwt' @@ -67,12 +71,12 @@ public function testValidatedEventIsDispatchedWhenListening(): void { $user = $this->user(1); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->once()->andReturn($user); - $provider->shouldReceive('validateCredentials')->once()->andReturnTrue(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveByCredentials')->returns($user); + $provider->expects('validateCredentials')->returns(true); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturn('token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->returns('token'); $events = $this->dispatcherListeningFor(Validated::class, function (Validated $event) use ($user): bool { return $event->guard === 'jwt' && $event->user === $user; @@ -86,8 +90,8 @@ public function testValidatedEventIsDispatchedWhenListening(): void public function testFailedEventIsDispatchedWhenListening(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->once()->andReturn(null); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveByCredentials')->returns(null); $events = $this->dispatcherListeningFor(Failed::class, function (Failed $event): bool { return $event->guard === 'jwt' @@ -106,14 +110,14 @@ public function testCredentialChecksWithoutLoginDoNotDispatchTheLoginEvent(strin { $user = $this->user(1); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->once()->andReturn($user); - $provider->shouldReceive('validateCredentials')->once()->andReturnTrue(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveByCredentials')->returns($user); + $provider->expects('validateCredentials')->returns(true); $dispatched = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->andReturnTrue(); - $events->shouldReceive('dispatch')->andReturnUsing(function (object $event) use (&$dispatched): void { + $events = Double::for(Dispatcher::class)->strict(); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch')->resolves(function (object $event) use (&$dispatched): void { $dispatched[] = $event::class; }); @@ -142,13 +146,13 @@ public function testLoginAndAuthenticatedEventsAreDispatchedWhenListening(): voi $user = $this->user(1); $dispatched = []; - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturn('token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->returns('token'); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->with(Login::class)->once()->andReturnTrue(); - $events->shouldReceive('hasListeners')->with(Authenticated::class)->once()->andReturnTrue(); - $events->shouldReceive('dispatch')->twice()->andReturnUsing( + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(Login::class)->returns(true); + $events->expects('hasListeners')->with(Authenticated::class)->returns(true); + $events->expects('dispatch')->times(2)->resolves( function (object $event) use (&$dispatched): void { $dispatched[] = $event; }, @@ -172,11 +176,11 @@ public function testAuthenticatedEventIsDispatchedOnceWhenTheTokenUserResolves() { $user = $this->user(1); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($user); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('token')->once()->andReturn(['sub' => 1]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('token')->returns(['sub' => 1]); $events = $this->dispatcherListeningFor(Authenticated::class, function (Authenticated $event) use ($user): bool { return $event->guard === 'jwt' && $event->user === $user; @@ -195,14 +199,15 @@ public function testAuthenticatedEventIsDispatchedOnceWhenTheTokenUserResolves() public function testNoEventIsDispatchedWhenTheTokenUserIsMissing(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturnNull(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns(null); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('token')->once()->andReturn(['sub' => 1]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('token')->returns(['sub' => 1]); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners', 'dispatch')->never(); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->never(); + $events->expects('dispatch')->never(); $guard = $this->createGuard( provider: $provider, @@ -218,8 +223,8 @@ public function testOnceUsingIdDispatchesTheAuthenticatedEvent(): void { $user = $this->user(1); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($user); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns($user); $events = $this->dispatcherListeningFor(Authenticated::class, function (Authenticated $event) use ($user): bool { return $event->guard === 'jwt' && $event->user === $user; @@ -235,14 +240,15 @@ public function testIssuingTokensWithoutLoginDispatchesNoEvents(): void { $user = $this->user(1); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($user); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->twice()->andReturn('token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->times(2)->returns('token'); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners', 'dispatch')->never(); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->never(); + $events->expects('dispatch')->never(); $guard = $this->createGuard(provider: $provider, jwtManager: $jwtManager); $guard->setDispatcher($events); @@ -255,13 +261,13 @@ public function testLogoutEventIncludesTheTokenUserWhenListening(): void { $user = $this->user(1); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($user); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('token')->once()->andReturn(['sub' => 1]); - $jwtManager->shouldReceive('hasBlacklistEnabled')->once()->andReturnTrue(); - $jwtManager->shouldReceive('invalidate')->with('token', false)->once()->andReturnTrue(); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('token')->returns(['sub' => 1]); + $jwtManager->expects('hasBlacklistEnabled')->returns(true); + $jwtManager->expects('invalidate')->with('token', false)->returns(true); $events = $this->dispatcherListeningFor(Logout::class, function (Logout $event) use ($user): bool { return $event->guard === 'jwt' && $event->user === $user; @@ -278,16 +284,15 @@ public function testLogoutEventIncludesTheTokenUserWhenListening(): void public function testLogoutWithAnExpiredTokenInvalidatesItAndDispatchesLogoutWithoutAUser(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldNotReceive('retrieveById'); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->never(); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode') + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode') ->with('token') - ->once() - ->andThrow(new TokenExpiredException('Token has expired')); - $jwtManager->shouldReceive('hasBlacklistEnabled')->once()->andReturnTrue(); - $jwtManager->shouldReceive('invalidate')->with('token', false)->once()->andReturnTrue(); + ->throws(new TokenExpiredException('Token has expired')); + $jwtManager->expects('hasBlacklistEnabled')->returns(true); + $jwtManager->expects('invalidate')->with('token', false)->returns(true); $events = $this->dispatcherListeningFor(Logout::class, function (Logout $event): bool { return $event->guard === 'jwt' && $event->user === null; @@ -309,15 +314,15 @@ public function testLogoutEventIsNotDispatchedWhenInvalidationFails(): void { $user = $this->user(1); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('hasBlacklistEnabled')->once()->andReturnTrue(); - $jwtManager->shouldReceive('invalidate') + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('hasBlacklistEnabled')->returns(true); + $jwtManager->expects('invalidate') ->with('token', false) - ->once() - ->andThrow(new JwtException('blacklist write failed')); + ->throws(new JwtException('blacklist write failed')); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners', 'dispatch')->never(); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->never(); + $events->expects('dispatch')->never(); $guard = $this->createGuard(jwtManager: $jwtManager, request: $this->requestWithToken('token')); $guard->setUser($user); @@ -336,8 +341,8 @@ public function testAttemptingRegistersListener(): void { $listener = static fn (): null => null; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('listen')->once()->with(Attempting::class, $listener); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('listen')->with(Attempting::class, $listener); $guard = $this->createGuard(); $guard->setDispatcher($events); @@ -349,11 +354,11 @@ public function testAttemptingRegistersListener(): void */ private function dispatcherListeningFor(string $eventClass, callable $assertion): Dispatcher { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnUsing( + $events = Double::for(Dispatcher::class)->strict(); + $events->allows('hasListeners')->resolves( fn (string $class): bool => $class === $eventClass ); - $events->shouldReceive('dispatch')->once()->with(m::on( + $events->expects('dispatch')->with(Argument::satisfies( fn (object $event): bool => $event instanceof $eventClass && $assertion($event) )); @@ -374,8 +379,8 @@ private function createGuard( return new JwtGuard( name: 'jwt', - provider: $provider ?? m::mock(UserProvider::class), - jwtManager: $jwtManager ?? m::mock(ManagerContract::class), + provider: $provider ?? Double::for(UserProvider::class)->strict(), + jwtManager: $jwtManager ?? Double::for(ManagerContract::class)->strict(), claimFactory: new ClaimFactory(new Repository([ 'jwt' => [ 'issuer' => null, @@ -394,8 +399,8 @@ private function createGuard( */ private function user(int|string $id): Authenticatable { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn($id); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns($id); return $user; } diff --git a/tests/Jwt/JwtGuardSubjectLockTest.php b/tests/Jwt/JwtGuardSubjectLockTest.php index 50e0558cc4..93f70e88be 100644 --- a/tests/Jwt/JwtGuardSubjectLockTest.php +++ b/tests/Jwt/JwtGuardSubjectLockTest.php @@ -16,18 +16,21 @@ use Hypervel\Jwt\Http\Parser\Parser; use Hypervel\Jwt\JwtGuard; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use SensitiveParameter; class JwtGuardSubjectLockTest extends TestCase { + use VerifiesDoubles; + public function testMatchingProviderSubjectResolvesUser(): void { $user = new JwtGuardSubjectUser(42); $provider = new JwtGuardSubjectModelProvider(JwtGuardSubjectUser::class, $user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->once()->andReturn([ + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->returns([ 'sub' => 42, 'prv' => hash('xxh128', JwtGuardSubjectUser::class), ]); @@ -42,8 +45,8 @@ public function testMismatchedProviderSubjectDoesNotResolveUser(): void { $provider = new JwtGuardSubjectModelProvider(JwtGuardSubjectUser::class, new JwtGuardSubjectUser(42)); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->once()->andReturn([ + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->returns([ 'sub' => 42, 'prv' => hash('xxh128', JwtGuardOtherSubjectUser::class), ]); @@ -58,8 +61,8 @@ public function testMissingProviderSubjectDoesNotResolveUser(): void { $provider = new JwtGuardSubjectModelProvider(JwtGuardSubjectUser::class, new JwtGuardSubjectUser(42)); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->once()->andReturn(['sub' => 42]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->returns(['sub' => 42]); $guard = $this->createGuard($provider, $jwtManager); @@ -71,8 +74,8 @@ public function testGetUserIdRejectsMismatchedProviderSubject(): void { $provider = new JwtGuardSubjectModelProvider(JwtGuardSubjectUser::class, new JwtGuardSubjectUser(42)); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->once()->andReturn([ + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->returns([ 'sub' => 42, 'prv' => hash('xxh128', JwtGuardOtherSubjectUser::class), ]); @@ -88,8 +91,8 @@ public function testProviderWithoutModelSkipsSubjectLocking(): void $user = new JwtGuardSubjectUser(42); $provider = new JwtGuardSubjectProvider($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->once()->andReturn(['sub' => 42]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->returns(['sub' => 42]); $guard = $this->createGuard($provider, $jwtManager); diff --git a/tests/Jwt/JwtGuardTest.php b/tests/Jwt/JwtGuardTest.php index 38886edf8a..c1b9d640fb 100644 --- a/tests/Jwt/JwtGuardTest.php +++ b/tests/Jwt/JwtGuardTest.php @@ -28,8 +28,9 @@ use Hypervel\Jwt\JwtServiceProvider; use Hypervel\Support\Sleep; use Hypervel\Testbench\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; @@ -37,6 +38,8 @@ class JwtGuardTest extends TestCase { + use VerifiesDoubles; + public function testParseTokenFromBearerHeader(): void { $guard = $this->createGuard( @@ -65,14 +68,14 @@ public function testParseTokenReturnsNullWhenNoRequestContext(): void public function testUserReturnsUserFromJwtPayload(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(42); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(42); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(42)->once()->andReturn($user); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(42)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->once()->andReturn(['sub' => 42]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('valid-token')->returns(['sub' => 42]); $guard = $this->createGuard( provider: $provider, @@ -96,12 +99,12 @@ public function testUserReturnsNullWhenNoToken(): void public function testUserCachesResultInContext(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(42)->once()->andReturn($user); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(42)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->once()->andReturn(['sub' => 42]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('valid-token')->returns(['sub' => 42]); $guard = $this->createGuard( provider: $provider, @@ -115,23 +118,23 @@ public function testUserCachesResultInContext(): void public function testNewGuardWithTheSameNameStartsWithoutThePreviousGuardsState(): void { - $previousUser = m::mock(Authenticatable::class); - $previousProvider = m::mock(UserProvider::class); - $previousProvider->expects('retrieveById')->with(42)->andReturn($previousUser); - $previousManager = m::mock(ManagerContract::class); - $previousManager->expects('decode')->with('request-token')->andReturn(['sub' => 42]); + $previousUser = Double::for(Authenticatable::class)->strict(); + $previousProvider = Double::for(UserProvider::class)->strict(); + $previousProvider->expects('retrieveById')->with(42)->returns($previousUser); + $previousManager = Double::for(ManagerContract::class)->strict(); + $previousManager->expects('decode')->with('request-token')->returns(['sub' => 42]); $previousGuard = $this->createGuard( provider: $previousProvider, jwtManager: $previousManager, request: $this->createRequestWithBearer('request-token'), ); $this->assertSame($previousUser, $previousGuard->user()); - $previousGuard->setUser(m::mock(Authenticatable::class)); + $previousGuard->setUser(Double::for(Authenticatable::class)->strict()); $previousGuard->setToken('previous-token'); - $provider = m::mock(UserProvider::class); - $provider->expects('retrieveById')->with(7)->andReturnNull(); - $manager = m::mock(ManagerContract::class); - $manager->expects('decode')->with('request-token')->andReturn(['sub' => 7]); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(7)->returns(null); + $manager = Double::for(ManagerContract::class)->strict(); + $manager->expects('decode')->with('request-token')->returns(['sub' => 7]); $guard = $this->createGuard(provider: $provider, jwtManager: $manager); @@ -142,10 +145,10 @@ public function testNewGuardWithTheSameNameStartsWithoutThePreviousGuardsState() public function testCopiedRequestRechecksBlacklistAfterWarmingUserAndPayload(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->expects('retrieveById')->with(42)->andReturn($user); - $manager = m::mock(ManagerContract::class); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(42)->returns($user); + $manager = Double::for(ManagerContract::class)->strict(); $this->stubDecodeThenBlacklisted($manager, 'token', ['sub' => 42]); $request = $this->createRequestWithBearer('token'); $guard = $this->createGuard(provider: $provider, jwtManager: $manager, request: $request); @@ -164,11 +167,11 @@ public function testCopiedRequestRechecksBlacklistAfterWarmingUserAndPayload(): public function testMissingTokenUserIsCachedAsUnauthenticated(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(42)->once()->andReturn(null); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(42)->returns(null); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->once()->andReturn(['sub' => 42]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('valid-token')->returns(['sub' => 42]); $guard = $this->createGuard( provider: $provider, @@ -186,11 +189,11 @@ public function testMissingTokenUserIsCachedAsUnauthenticated(): void #[DataProvider('unusableTokenExceptionProvider')] public function testUnusableTokenIsCachedAsUnauthenticated(JwtException $exception): void { - $provider = m::mock(UserProvider::class); - $provider->shouldNotReceive('retrieveById'); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->never(); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('unusable-token')->once()->andThrow($exception); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('unusable-token')->throws($exception); $guard = $this->createGuard( provider: $provider, @@ -223,18 +226,18 @@ public static function unusableTokenExceptionProvider(): array public function testAttemptReturnsTokenOnValidCredentials(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(1); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(1); $credentials = ['email' => 'foo@bar.com', 'password' => 'secret']; - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->with($credentials)->andReturn($user); - $provider->shouldReceive('validateCredentials')->with($user, $credentials)->andReturnTrue(); - $provider->shouldReceive('rehashPasswordIfRequired')->with($user, $credentials)->once(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->allows('retrieveByCredentials')->with($credentials)->returns($user); + $provider->allows('validateCredentials')->with($user, $credentials)->returns(true); + $provider->expects('rehashPasswordIfRequired')->with($user, $credentials); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturn('new-token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->returns('new-token'); $guard = $this->createGuard( provider: $provider, @@ -248,8 +251,8 @@ public function testAttemptReturnsTokenOnValidCredentials(): void public function testAttemptReturnsFalseOnInvalidCredentials(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->andReturn(null); + $provider = Double::for(UserProvider::class)->strict(); + $provider->allows('retrieveByCredentials')->returns(null); $guard = $this->createGuard( provider: $provider, @@ -261,14 +264,14 @@ public function testAttemptReturnsFalseOnInvalidCredentials(): void public function testValidateDoesNotLoginUser(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->andReturn($user); - $provider->shouldReceive('validateCredentials')->andReturnTrue(); - $provider->shouldNotReceive('rehashPasswordIfRequired'); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->allows('retrieveByCredentials')->returns($user); + $provider->allows('validateCredentials')->returns(true); + $provider->expects('rehashPasswordIfRequired')->never(); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldNotReceive('encode'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->never(); $guard = $this->createGuard( provider: $provider, @@ -281,14 +284,14 @@ public function testValidateDoesNotLoginUser(): void public function testAttemptWithoutLoginReturnsTrueAndDoesNotMintToken(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->once()->andReturn($user); - $provider->shouldReceive('validateCredentials')->once()->andReturnTrue(); - $provider->shouldNotReceive('rehashPasswordIfRequired'); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveByCredentials')->returns($user); + $provider->expects('validateCredentials')->returns(true); + $provider->expects('rehashPasswordIfRequired')->never(); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldNotReceive('encode'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->never(); $guard = $this->createGuard( provider: $provider, @@ -304,11 +307,11 @@ public function testAttemptWithoutLoginReturnsTrueAndDoesNotMintToken(): void public function testLoginReturnsToken(bool $withRequest): void { RequestContext::forget(); - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(1); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(1); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturn('jwt-token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->returns('jwt-token'); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -324,12 +327,12 @@ public function testLoginReturnsToken(bool $withRequest): void public function testLoginOverridesExistingRequestToken(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(1); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(1); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturn('new-token'); - $jwtManager->shouldNotReceive('decode'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->returns('new-token'); + $jwtManager->expects('decode')->never(); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -343,12 +346,12 @@ public function testLoginOverridesExistingRequestToken(): void public function testLoginReplacesAnExplicitUserWithTheLoggedInUser(): void { - $explicitUser = m::mock(Authenticatable::class); - $loginUser = m::mock(Authenticatable::class); - $loginUser->shouldReceive('getAuthIdentifier')->andReturn(1); + $explicitUser = Double::for(Authenticatable::class)->strict(); + $loginUser = Double::for(Authenticatable::class)->strict(); + $loginUser->allows('getAuthIdentifier')->returns(1); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturn('new-token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->returns('new-token'); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -363,12 +366,12 @@ public function testLoginReplacesAnExplicitUserWithTheLoggedInUser(): void public function testLoginPayloadContainsSubIatExp(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(42); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(42); $capturedPayload = null; - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturnUsing(function ($payload) use (&$capturedPayload) { + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->resolves(function ($payload) use (&$capturedPayload) { $capturedPayload = $payload; return 'token'; @@ -390,12 +393,12 @@ public function testLoginPayloadContainsSubIatExp(): void public function testLoginOmitsExpirationWhenTtlIsNull(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(42); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(42); $capturedPayload = null; - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturnUsing(function ($payload) use (&$capturedPayload) { + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->resolves(function ($payload) use (&$capturedPayload) { $capturedPayload = $payload; return 'token'; @@ -417,12 +420,12 @@ public function testLoginOmitsExpirationWhenTtlIsNull(): void public function testClaimsMergeIntoNextToken(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(1); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(1); $capturedPayload = null; - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturnUsing(function ($payload) use (&$capturedPayload) { + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->resolves(function ($payload) use (&$capturedPayload) { $capturedPayload = $payload; return 'token'; @@ -442,12 +445,12 @@ public function testClaimsMergeIntoNextToken(): void public function testClaimsAreClearedAfterNextToken(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(1); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(1); $capturedPayloads = []; - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->twice()->andReturnUsing(function ($payload) use (&$capturedPayloads) { + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->times(2)->resolves(function ($payload) use (&$capturedPayloads) { $capturedPayloads[] = $payload; return 'token-' . count($capturedPayloads); @@ -467,12 +470,12 @@ public function testClaimsAreClearedAfterNextToken(): void public function testSetTtlAppliesOnlyToNextToken(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(1); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(1); $capturedPayloads = []; - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->twice()->andReturnUsing(function ($payload) use (&$capturedPayloads) { + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->times(2)->resolves(function ($payload) use (&$capturedPayloads) { $capturedPayloads[] = $payload; return 'token-' . count($capturedPayloads); @@ -492,12 +495,12 @@ public function testSetTtlAppliesOnlyToNextToken(): void public function testSetTtlNullAppliesOnlyToNextToken(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(1); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(1); $capturedPayloads = []; - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->twice()->andReturnUsing(function ($payload) use (&$capturedPayloads) { + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->times(2)->resolves(function ($payload) use (&$capturedPayloads) { $capturedPayloads[] = $payload; return 'token-' . count($capturedPayloads); @@ -517,8 +520,8 @@ public function testSetTtlNullAppliesOnlyToNextToken(): void public function testGetPayloadReturnsDecodedToken(): void { - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->once()->andReturn(['sub' => 1, 'iat' => 1000]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('valid-token')->returns(['sub' => 1, 'iat' => 1000]); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -532,8 +535,8 @@ public function testGetPayloadReturnsDecodedToken(): void public function testPayloadAliasesGetPayload(): void { - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->once()->andReturn(['sub' => 1, 'iat' => 1000]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('valid-token')->returns(['sub' => 1, 'iat' => 1000]); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -547,8 +550,8 @@ public function testGetPayloadThrowsWhenPresentTokenIsInvalid(): void { $this->expectException(TokenInvalidException::class); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('invalid-token')->once()->andThrow(new TokenInvalidException); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('invalid-token')->throws(new TokenInvalidException); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -568,8 +571,8 @@ public function testGetPayloadReturnsEmptyArrayWhenNoToken(): void public function testRefreshDelegatesAndClearsContext(): void { - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('refresh')->with('old-token', false, false, [], 120)->once()->andReturn('new-token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('refresh')->with('old-token', false, false, [], 120)->returns('new-token'); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -581,9 +584,9 @@ public function testRefreshDelegatesAndClearsContext(): void public function testRefreshUsesPerCallTtlOverrideAndClearsIt(): void { - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('refresh')->with('old-token', false, false, [], 5)->once()->andReturn('new-token'); - $jwtManager->shouldReceive('refresh')->with('new-token', false, false, [], 120)->once()->andReturn('newer-token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('refresh')->with('old-token', false, false, [], 5)->returns('new-token'); + $jwtManager->expects('refresh')->with('new-token', false, false, [], 120)->returns('newer-token'); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -596,8 +599,8 @@ public function testRefreshUsesPerCallTtlOverrideAndClearsIt(): void public function testRefreshUsesNullTtlOverride(): void { - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('refresh')->with('old-token', false, false, [], null)->once()->andReturn('new-token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('refresh')->with('old-token', false, false, [], null)->returns('new-token'); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -609,8 +612,8 @@ public function testRefreshUsesNullTtlOverride(): void public function testRefreshUsesPerGuardTtl(): void { - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('refresh')->with('old-token', false, false, [], 15)->once()->andReturn('new-token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('refresh')->with('old-token', false, false, [], 15)->returns('new-token'); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -623,13 +626,13 @@ public function testRefreshUsesPerGuardTtl(): void public function testRefreshKeepsCachedUserUnderNewToken(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($user); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('old-token')->once()->andReturn(['sub' => 1]); - $jwtManager->shouldReceive('refresh')->with('old-token', false, false, [], 120)->once()->andReturn('new-token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('old-token')->returns(['sub' => 1]); + $jwtManager->expects('refresh')->with('old-token', false, false, [], 120)->returns('new-token'); $guard = $this->createGuard( provider: $provider, @@ -644,10 +647,10 @@ public function testRefreshKeepsCachedUserUnderNewToken(): void public function testRefreshPreservesExplicitUserAfterSuccess(): void { - $explicitUser = m::mock(Authenticatable::class); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('refresh')->with('old-token', false, false, [], 120)->once()->andReturn('new-token'); - $jwtManager->shouldNotReceive('decode'); + $explicitUser = Double::for(Authenticatable::class)->strict(); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('refresh')->with('old-token', false, false, [], 120)->returns('new-token'); + $jwtManager->expects('decode')->never(); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -661,13 +664,12 @@ public function testRefreshPreservesExplicitUserAfterSuccess(): void public function testRefreshPreservesExplicitUserAfterFailure(): void { - $explicitUser = m::mock(Authenticatable::class); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('refresh') + $explicitUser = Double::for(Authenticatable::class)->strict(); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('refresh') ->with('old-token', false, false, [], 120) - ->once() - ->andThrow(new JwtException('refresh failed')); - $jwtManager->shouldNotReceive('decode'); + ->throws(new JwtException('refresh failed')); + $jwtManager->expects('decode')->never(); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -696,15 +698,15 @@ public function testRefreshReturnsNullWhenNoToken(): void public function testLogoutInvalidatesTheRequestTokenAndStopsUsingIt(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->twice()->andReturn($user); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->times(2)->returns($user); // The grace period keeps the revoked token decodable during this request. - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->twice()->andReturn(['sub' => 1]); - $jwtManager->shouldReceive('hasBlacklistEnabled')->once()->andReturnTrue(); - $jwtManager->shouldReceive('invalidate')->with('valid-token', false)->once()->andReturnTrue(); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('valid-token')->times(2)->returns(['sub' => 1]); + $jwtManager->expects('hasBlacklistEnabled')->returns(true); + $jwtManager->expects('invalidate')->with('valid-token', false)->returns(true); $guard = $this->createGuard( provider: $provider, @@ -727,18 +729,18 @@ public function testLogoutInvalidatesTheRequestTokenAndStopsUsingIt(): void public function testLogoutWithBlacklistDisabledStopsUsingTheRequestTokenWithoutInvalidating(): void { - $user = m::mock(Authenticatable::class); - $nextUser = m::mock(Authenticatable::class); - $nextUser->shouldReceive('getAuthIdentifier')->andReturn(2); + $user = Double::for(Authenticatable::class)->strict(); + $nextUser = Double::for(Authenticatable::class)->strict(); + $nextUser->allows('getAuthIdentifier')->returns(2); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($user); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->once()->andReturn(['sub' => 1]); - $jwtManager->shouldReceive('hasBlacklistEnabled')->once()->andReturnFalse(); - $jwtManager->shouldNotReceive('invalidate'); - $jwtManager->shouldReceive('encode')->once()->andReturn('next-token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('valid-token')->returns(['sub' => 1]); + $jwtManager->expects('hasBlacklistEnabled')->returns(false); + $jwtManager->expects('invalidate')->never(); + $jwtManager->expects('encode')->returns('next-token'); $guard = $this->createGuard( provider: $provider, @@ -763,14 +765,14 @@ public function testLogoutWithBlacklistDisabledStopsUsingTheRequestTokenWithoutI public function testLogoutClearsDecodedPayloadCache(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($user); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns($user); - $jwtManager = m::mock(ManagerContract::class); + $jwtManager = Double::for(ManagerContract::class)->strict(); $this->stubDecodeThenBlacklisted($jwtManager, 'valid-token', ['sub' => 1]); - $jwtManager->shouldReceive('hasBlacklistEnabled')->once()->andReturnTrue(); - $jwtManager->shouldReceive('invalidate')->with('valid-token', false)->once()->andReturnTrue(); + $jwtManager->expects('hasBlacklistEnabled')->returns(true); + $jwtManager->expects('invalidate')->with('valid-token', false)->returns(true); $guard = $this->createGuard( provider: $provider, @@ -791,14 +793,13 @@ public function testLogoutClearsDecodedPayloadCache(): void public function testLogoutFailureRetainsTheTokenAndUser(): void { - $user = m::mock(Authenticatable::class); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->once()->andReturn(['sub' => 1]); - $jwtManager->shouldReceive('hasBlacklistEnabled')->once()->andReturnTrue(); - $jwtManager->shouldReceive('invalidate') + $user = Double::for(Authenticatable::class)->strict(); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('valid-token')->returns(['sub' => 1]); + $jwtManager->expects('hasBlacklistEnabled')->returns(true); + $jwtManager->expects('invalidate') ->with('valid-token', false) - ->once() - ->andThrow(new JwtException('blacklist write failed')); + ->throws(new JwtException('blacklist write failed')); $guard = $this->createGuard(jwtManager: $jwtManager, request: null) ->setToken('valid-token') @@ -821,14 +822,14 @@ public function testLogoutFailureRetainsTheTokenAndUser(): void public function testLogoutPassesForceForeverFlag(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($user); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->once()->andReturn(['sub' => 1]); - $jwtManager->shouldReceive('hasBlacklistEnabled')->once()->andReturnTrue(); - $jwtManager->shouldReceive('invalidate')->with('valid-token', true)->once()->andReturnTrue(); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('valid-token')->returns(['sub' => 1]); + $jwtManager->expects('hasBlacklistEnabled')->returns(true); + $jwtManager->expects('invalidate')->with('valid-token', true)->returns(true); $guard = $this->createGuard( provider: $provider, @@ -841,9 +842,9 @@ public function testLogoutPassesForceForeverFlag(): void public function testLogoutWithoutTokenClearsLocalUserState(): void { - $user = m::mock(Authenticatable::class); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldNotReceive('invalidate'); + $user = Double::for(Authenticatable::class)->strict(); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('invalidate')->never(); $guard = $this->createGuard(jwtManager: $jwtManager, request: null); RequestContext::forget(); @@ -857,12 +858,12 @@ public function testLogoutWithoutTokenClearsLocalUserState(): void public function testGetUserReturnsTheResolvedUser(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->andReturn($user); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->allows('retrieveById')->with(1)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->andReturn(['sub' => 1]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->allows('decode')->with('valid-token')->returns(['sub' => 1]); $guard = $this->createGuard( provider: $provider, @@ -878,8 +879,8 @@ public function testGetUserReturnsTheResolvedUser(): void public function testGetUserDoesNotResolveTheTokenUser(): void { - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldNotReceive('decode'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->never(); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -892,11 +893,11 @@ public function testGetUserDoesNotResolveTheTokenUser(): void public function testGetUserIdUsesCachedUserWithoutDecodingToken(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->once()->andReturn(42); + $user = Double::for(Authenticatable::class)->strict(); + $user->expects('getAuthIdentifier')->returns(42); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldNotReceive('decode'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->never(); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -909,11 +910,11 @@ public function testGetUserIdUsesCachedUserWithoutDecodingToken(): void public function testGetUserIdReadsTheTokenSubjectWithoutLoadingTheUser(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldNotReceive('retrieveById'); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->never(); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->once()->andReturn(['sub' => 42]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('valid-token')->returns(['sub' => 42]); $guard = $this->createGuard( provider: $provider, @@ -935,15 +936,15 @@ public function testGetUserIdReturnsNullWithoutToken(): void public function testExplicitUserOverridesAnUnrelatedTokenUntilForgotten(): void { - $explicitUser = m::mock(Authenticatable::class); - $explicitUser->shouldReceive('getAuthIdentifier')->once()->andReturn(10); - $tokenUser = m::mock(Authenticatable::class); + $explicitUser = Double::for(Authenticatable::class)->strict(); + $explicitUser->expects('getAuthIdentifier')->returns(10); + $tokenUser = Double::for(Authenticatable::class)->strict(); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(20)->once()->andReturn($tokenUser); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(20)->returns($tokenUser); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('bearer-token')->once()->andReturn(['sub' => 20]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('bearer-token')->returns(['sub' => 20]); $guard = $this->createGuard( provider: $provider, @@ -963,13 +964,13 @@ public function testExplicitUserOverridesAnUnrelatedTokenUntilForgotten(): void public function testSetUserOverridesCachedUser(): void { - $user1 = m::mock(Authenticatable::class); - $user2 = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->andReturn($user1); + $user1 = Double::for(Authenticatable::class)->strict(); + $user2 = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->allows('retrieveById')->with(1)->returns($user1); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->andReturn(['sub' => 1]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->allows('decode')->with('valid-token')->returns(['sub' => 1]); $guard = $this->createGuard( provider: $provider, @@ -985,12 +986,12 @@ public function testSetUserOverridesCachedUser(): void public function testForgetUserClearsCache(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->andReturn($user); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->allows('retrieveById')->with(1)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->andReturn(['sub' => 1]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->allows('decode')->with('valid-token')->returns(['sub' => 1]); $guard = $this->createGuard( provider: $provider, @@ -1017,11 +1018,11 @@ public function testAuthContextKeysIncludeOnlyDurableExplicitState(): void public function testLogoutClearsDefaultUserCacheWhenTokenOverrideIsActive(): void { - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class)->strict(); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('hasBlacklistEnabled')->once()->andReturnTrue(); - $jwtManager->shouldReceive('invalidate')->with('active-token', false)->once()->andReturnTrue(); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('hasBlacklistEnabled')->returns(true); + $jwtManager->expects('invalidate')->with('active-token', false)->returns(true); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -1041,16 +1042,16 @@ public function testLogoutClearsDefaultUserCacheWhenTokenOverrideIsActive(): voi public function testSwitchingTokensResolvesDifferentUsersInSameCoroutine(): void { - $firstUser = m::mock(Authenticatable::class); - $secondUser = m::mock(Authenticatable::class); + $firstUser = Double::for(Authenticatable::class)->strict(); + $secondUser = Double::for(Authenticatable::class)->strict(); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($firstUser); - $provider->shouldReceive('retrieveById')->with(2)->once()->andReturn($secondUser); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns($firstUser); + $provider->expects('retrieveById')->with(2)->returns($secondUser); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('first-token')->once()->andReturn(['sub' => 1]); - $jwtManager->shouldReceive('decode')->with('second-token')->once()->andReturn(['sub' => 2]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('first-token')->returns(['sub' => 1]); + $jwtManager->expects('decode')->with('second-token')->returns(['sub' => 2]); $guard = $this->createGuard( provider: $provider, @@ -1065,12 +1066,12 @@ public function testSwitchingTokensResolvesDifferentUsersInSameCoroutine(): void public function testOnceUsingIdAndByIdReturnUserWhenUserExists(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->twice()->andReturn($user); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->times(2)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldNotReceive('encode'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->never(); $guard = $this->createGuard( provider: $provider, @@ -1085,16 +1086,16 @@ public function testOnceUsingIdAndByIdReturnUserWhenUserExists(): void public function testOnceDoesNotMintTokenAndSetsUser(): void { - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class)->strict(); $credentials = ['email' => 'foo@bar.com', 'password' => 'secret']; - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->once()->andReturn($user); - $provider->shouldReceive('validateCredentials')->once()->andReturnTrue(); - $provider->shouldReceive('rehashPasswordIfRequired')->with($user, $credentials)->once(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveByCredentials')->returns($user); + $provider->expects('validateCredentials')->returns(true); + $provider->expects('rehashPasswordIfRequired')->with($user, $credentials); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldNotReceive('encode'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->never(); $guard = $this->createGuard( provider: $provider, @@ -1108,12 +1109,12 @@ public function testOnceDoesNotMintTokenAndSetsUser(): void public function testOnceReturnsFalseForInvalidCredentials(): void { - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class)->strict(); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->once()->andReturn($user); - $provider->shouldReceive('validateCredentials')->once()->andReturnFalse(); - $provider->shouldNotReceive('rehashPasswordIfRequired'); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveByCredentials')->returns($user); + $provider->expects('validateCredentials')->returns(false); + $provider->expects('rehashPasswordIfRequired')->never(); $guard = $this->createGuard(provider: $provider, request: $this->createRequestWithBearer(null)); @@ -1123,16 +1124,16 @@ public function testOnceReturnsFalseForInvalidCredentials(): void public function testDisabledRehashOnLoginNeverRehashesPasswords(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(1); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(1); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->twice()->andReturn($user); - $provider->shouldReceive('validateCredentials')->twice()->andReturnTrue(); - $provider->shouldNotReceive('rehashPasswordIfRequired'); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveByCredentials')->times(2)->returns($user); + $provider->expects('validateCredentials')->times(2)->returns(true); + $provider->expects('rehashPasswordIfRequired')->never(); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturn('new-token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->returns('new-token'); $guard = $this->createGuard( provider: $provider, @@ -1149,8 +1150,8 @@ public function testFailedAttemptWaitsForTheTimebox(): void { Sleep::fake(); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->once()->andReturnNull(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveByCredentials')->returns(null); $guard = $this->createGuard( provider: $provider, @@ -1170,16 +1171,16 @@ public function testSuccessfulAttemptReturnsWithoutWaitingForTheTimebox(): void { Sleep::fake(); - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(1); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(1); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->once()->andReturn($user); - $provider->shouldReceive('validateCredentials')->once()->andReturnTrue(); - $provider->shouldReceive('rehashPasswordIfRequired')->once(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveByCredentials')->returns($user); + $provider->expects('validateCredentials')->returns(true); + $provider->expects('rehashPasswordIfRequired'); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturn('new-token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->returns('new-token'); $guard = $this->createGuard( provider: $provider, @@ -1195,8 +1196,8 @@ public function testSuccessfulAttemptReturnsWithoutWaitingForTheTimebox(): void public function testOnceUsingIdAndByIdReturnFalseWhenUserNotFound(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(999)->twice()->andReturn(null); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(999)->times(2)->returns(null); $guard = $this->createGuard( provider: $provider, @@ -1209,14 +1210,14 @@ public function testOnceUsingIdAndByIdReturnFalseWhenUserNotFound(): void public function testTokenByIdReturnsTokenWithoutSettingCurrentUserOrToken(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(1); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(1); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($user); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturn('token-by-id'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->returns('token-by-id'); $guard = $this->createGuard( provider: $provider, @@ -1232,11 +1233,11 @@ public function testTokenByIdReturnsTokenWithoutSettingCurrentUserOrToken(): voi public function testTokenByIdReturnsNullWhenUserIsNotFound(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturnNull(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns(null); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldNotReceive('encode'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->never(); $guard = $this->createGuard(provider: $provider, jwtManager: $jwtManager, request: null); @@ -1245,12 +1246,12 @@ public function testTokenByIdReturnsNullWhenUserIsNotFound(): void public function testFromUserReturnsTokenWithoutSettingCurrentUserOrToken(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(1); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(1); $capturedPayload = null; - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturnUsing(function (array $payload) use (&$capturedPayload): string { + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->resolves(function (array $payload) use (&$capturedPayload): string { $capturedPayload = $payload; return 'token-for-user'; @@ -1268,8 +1269,8 @@ public function testFromUserReturnsTokenWithoutSettingCurrentUserOrToken(): void public function testInvalidateReturnsGuardInstance(): void { - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('invalidate')->with('valid-token', true)->once()->andReturnTrue(); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('invalidate')->with('valid-token', true)->returns(true); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -1281,13 +1282,13 @@ public function testInvalidateReturnsGuardInstance(): void public function testInvalidateClearsTheExactTokenUserAndRetainsTokenIdentity(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($user); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns($user); - $jwtManager = m::mock(ManagerContract::class); + $jwtManager = Double::for(ManagerContract::class)->strict(); $this->stubDecodeThenBlacklisted($jwtManager, 'valid-token', ['sub' => 1]); - $jwtManager->shouldReceive('invalidate')->with('valid-token', false)->once()->andReturnTrue(); + $jwtManager->expects('invalidate')->with('valid-token', false)->returns(true); $guard = $this->createGuard(provider: $provider, jwtManager: $jwtManager, request: null) ->setToken('valid-token'); @@ -1300,9 +1301,9 @@ public function testInvalidateClearsTheExactTokenUserAndRetainsTokenIdentity(): public function testInvalidateClearsTheExactTokenPayload(): void { - $jwtManager = m::mock(ManagerContract::class); + $jwtManager = Double::for(ManagerContract::class)->strict(); $this->stubDecodeThenBlacklisted($jwtManager, 'valid-token', ['sub' => 1]); - $jwtManager->shouldReceive('invalidate')->with('valid-token', false)->once()->andReturnTrue(); + $jwtManager->expects('invalidate')->with('valid-token', false)->returns(true); $guard = $this->createGuard(jwtManager: $jwtManager, request: null) ->setToken('valid-token'); @@ -1318,16 +1319,16 @@ public function testInvalidateClearsTheExactTokenPayload(): void public function testInvalidateLeavesSiblingTokenStateUntouched(): void { - $firstUser = m::mock(Authenticatable::class); - $secondUser = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($firstUser); - $provider->shouldReceive('retrieveById')->with(2)->once()->andReturn($secondUser); + $firstUser = Double::for(Authenticatable::class)->strict(); + $secondUser = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns($firstUser); + $provider->expects('retrieveById')->with(2)->returns($secondUser); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('first-token')->once()->andReturn(['sub' => 1]); - $jwtManager->shouldReceive('decode')->with('second-token')->once()->andReturn(['sub' => 2]); - $jwtManager->shouldReceive('invalidate')->with('first-token', false)->once()->andReturnTrue(); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('first-token')->returns(['sub' => 1]); + $jwtManager->expects('decode')->with('second-token')->returns(['sub' => 2]); + $jwtManager->expects('invalidate')->with('first-token', false)->returns(true); $guard = $this->createGuard(provider: $provider, jwtManager: $jwtManager, request: null); @@ -1342,16 +1343,15 @@ public function testInvalidateLeavesSiblingTokenStateUntouched(): void public function testInvalidateFailureLeavesExactTokenStateUntouched(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->once()->andReturn($user); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->once()->andReturn(['sub' => 1]); - $jwtManager->shouldReceive('invalidate') + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('valid-token')->returns(['sub' => 1]); + $jwtManager->expects('invalidate') ->with('valid-token', false) - ->once() - ->andThrow(new JwtException('blacklist write failed')); + ->throws(new JwtException('blacklist write failed')); $guard = $this->createGuard(provider: $provider, jwtManager: $jwtManager, request: null) ->setToken('valid-token'); @@ -1372,13 +1372,13 @@ public function testInvalidateFailureLeavesExactTokenStateUntouched(): void public function testInvalidateReevaluatesTokenWhenManagerGracePeriodAllowsIt(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->twice()->andReturn($user); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->times(2)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->twice()->andReturn(['sub' => 1]); - $jwtManager->shouldReceive('invalidate')->with('valid-token', false)->once()->andReturnTrue(); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('valid-token')->times(2)->returns(['sub' => 1]); + $jwtManager->expects('invalidate')->with('valid-token', false)->returns(true); $guard = $this->createGuard(provider: $provider, jwtManager: $jwtManager, request: null) ->setToken('valid-token'); @@ -1411,12 +1411,12 @@ public function testUserOrFailThrowsWhenUserIsNotDefined(): void public function testUserOrFailReturnsResolvedUser(): void { - $user = m::mock(Authenticatable::class); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->andReturn($user); + $user = Double::for(Authenticatable::class)->strict(); + $provider = Double::for(UserProvider::class)->strict(); + $provider->allows('retrieveById')->with(1)->returns($user); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->andReturn(['sub' => 1]); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->allows('decode')->with('valid-token')->returns(['sub' => 1]); $guard = $this->createGuard( provider: $provider, @@ -1431,8 +1431,8 @@ public function testUserPropagatesSecretMisconfiguration(): void { $this->expectException(SecretMissingException::class); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('decode')->with('valid-token')->once()->andThrow(new SecretMissingException); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('decode')->with('valid-token')->throws(new SecretMissingException); $guard = $this->createGuard( jwtManager: $jwtManager, @@ -1447,14 +1447,14 @@ public function testUserPropagatesSecretMisconfiguration(): void public function testDecodedPayloadIsCachedBetweenUserAndGetPayload(bool $withRequest): void { RequestContext::forget(); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveById')->with(1)->andReturn( - m::mock(Authenticatable::class) + $provider = Double::for(UserProvider::class)->strict(); + $provider->allows('retrieveById')->with(1)->returns( + Double::for(Authenticatable::class)->strict() ); - $jwtManager = m::mock(ManagerContract::class); + $jwtManager = Double::for(ManagerContract::class)->strict(); // decode() should be called exactly once — the second call uses the cache - $jwtManager->shouldReceive('decode')->with('valid-token')->once()->andReturn([ + $jwtManager->expects('decode')->with('valid-token')->returns([ 'sub' => 1, 'iat' => 1000, 'exp' => 9999999999, @@ -1488,12 +1488,12 @@ public function testGuardIsMacroable(): void public function testServiceProviderRegistersJwtGuardWhenAuthManagerResolvesAfterBoot(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class)->strict(); $container = $this->createAuthTestContainer(); $jwtServiceProvider = new JwtServiceProvider($container); $jwtServiceProvider->register(); - $container->instance('jwt', m::mock(ManagerContract::class)); + $container->instance('jwt', Double::for(ManagerContract::class)->strict()); $jwtServiceProvider->boot(); /** @var AuthManager $authManager */ @@ -1505,12 +1505,12 @@ public function testServiceProviderRegistersJwtGuardWhenAuthManagerResolvesAfter public function testServiceProviderRegistersJwtGuardWhenAuthManagerIsAlreadyResolved(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class)->strict(); $container = $this->createAuthTestContainer(); $jwtServiceProvider = new JwtServiceProvider($container); $jwtServiceProvider->register(); - $container->instance('jwt', m::mock(ManagerContract::class)); + $container->instance('jwt', Double::for(ManagerContract::class)->strict()); /** @var AuthManager $authManager */ $authManager = $container->make(AuthManager::class); @@ -1525,17 +1525,17 @@ public function testRegisteredGuardUsesTheTimeboxAndRehashSettings(): void { Sleep::fake(); - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn(1); + $user = Double::for(Authenticatable::class)->strict(); + $user->allows('getAuthIdentifier')->returns(1); - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->with(['email' => 'missing@bar.com'])->once()->andReturnNull(); - $provider->shouldReceive('retrieveByCredentials')->with(['email' => 'foo@bar.com'])->once()->andReturn($user); - $provider->shouldReceive('validateCredentials')->once()->andReturnTrue(); - $provider->shouldNotReceive('rehashPasswordIfRequired'); + $provider = Double::for(UserProvider::class)->strict(); + $provider->expects('retrieveByCredentials')->with(['email' => 'missing@bar.com'])->returns(null); + $provider->expects('retrieveByCredentials')->with(['email' => 'foo@bar.com'])->returns($user); + $provider->expects('validateCredentials')->returns(true); + $provider->expects('rehashPasswordIfRequired')->never(); - $jwtManager = m::mock(ManagerContract::class); - $jwtManager->shouldReceive('encode')->once()->andReturn('new-token'); + $jwtManager = Double::for(ManagerContract::class)->strict(); + $jwtManager->expects('encode')->returns('new-token'); $container = $this->createAuthTestContainer(rehashOnLogin: false, timeboxDuration: 300000); $jwtServiceProvider = new JwtServiceProvider($container); @@ -1567,16 +1567,16 @@ public function testRegisteredGuardUsesTheTimeboxAndRehashSettings(): void * @param array $payload */ protected function stubDecodeThenBlacklisted( - ManagerContract&MockInterface $jwtManager, + ManagerContract&DoubleInterface $jwtManager, string $token, array $payload, ): void { $decodeCalls = 0; - $jwtManager->shouldReceive('decode') + $jwtManager->expects('decode') ->with($token) - ->twice() - ->andReturnUsing(function () use (&$decodeCalls, $payload): array { + ->times(2) + ->resolves(function () use (&$decodeCalls, $payload): array { if (++$decodeCalls === 1) { return $payload; } @@ -1602,8 +1602,8 @@ protected function createGuard( return new JwtGuard( name: 'jwt', - provider: $provider ?? m::mock(UserProvider::class), - jwtManager: $jwtManager ?? m::mock(ManagerContract::class), + provider: $provider ?? Double::for(UserProvider::class)->strict(), + jwtManager: $jwtManager ?? Double::for(ManagerContract::class)->strict(), claimFactory: new ClaimFactory(new Repository([ 'jwt' => [ 'issuer' => null, diff --git a/tests/Jwt/JwtManagerTest.php b/tests/Jwt/JwtManagerTest.php index 79426f2aad..dde1d41826 100644 --- a/tests/Jwt/JwtManagerTest.php +++ b/tests/Jwt/JwtManagerTest.php @@ -27,38 +27,28 @@ use Hypervel\Support\Str; use Hypervel\Tests\Jwt\Fixtures\ValidationStub; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; +use JMac\Testing\OverriddenDouble; use PHPUnit\Framework\Attributes\DataProvider; use SensitiveParameterValue; use Symfony\Component\Uid\Uuid; class JwtManagerTest extends TestCase { - /** - * @var Container|MockInterface - */ - private Container $container; + use VerifiesDoubles; - /** - * @var MockInterface|Repository - */ - private Repository $config; + private OverriddenDouble $container; - /** - * @var Lcobucci|MockInterface - */ - private Lcobucci $provider; + private Repository&DoubleInterface $config; - /** - * @var BlacklistContract|MockInterface - */ - private BlacklistContract $blacklist; + private Lcobucci&DoubleInterface $provider; - /** - * @var ClaimFactory|MockInterface - */ - private ClaimFactory $claimFactory; + private BlacklistContract&DoubleInterface $blacklist; + + private ClaimFactory&DoubleInterface $claimFactory; private int $testNowTimestamp; @@ -89,8 +79,8 @@ public function testEncodeAPayload(): void $this->mockUuid($jti); - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->provider->shouldReceive('encode')->with($payload)->andReturn($token); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->provider->allows('encode')->with($payload)->returns($token); $this->assertEquals($token, $this->createManager()->encode($payload)); } @@ -103,8 +93,8 @@ public function testEncodeAddsJtiWhenBlacklistIsEnabledAndMissing(): void $this->mockUuid($jti); - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->provider->shouldReceive('encode')->once()->with($payload + ['jti' => $jti])->andReturn($token); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->provider->expects('encode')->with($payload + ['jti' => $jti])->returns($token); $this->assertSame($token, $this->createManager()->encode($payload)); } @@ -114,8 +104,8 @@ public function testEncodeDoesNotAddJtiWhenBlacklistIsDisabled(): void $token = 'foo.bar.baz'; $payload = ['sub' => 1, 'iat' => $this->testNowTimestamp]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); - $this->provider->shouldReceive('encode')->once()->with($payload)->andReturn($token); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); + $this->provider->expects('encode')->with($payload)->returns($token); $this->assertSame($token, $this->createManager()->encode($payload)); } @@ -137,7 +127,7 @@ public function testNullSecretSupportsAsymmetricSigning(): void ], ])); - $manager = new JwtManager($application, m::mock(ClaimFactory::class)); + $manager = new JwtManager($application, Double::for(ClaimFactory::class)->strict()); $token = $manager->encode([ 'sub' => 1, 'iat' => $this->testNowTimestamp, @@ -152,10 +142,10 @@ public function testNullSecretSupportsAsymmetricSigning(): void public function testCustomDriverCanReplaceTheLcobucciDriver(): void { - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); - $this->config->shouldReceive('string')->with('jwt.driver')->andReturn('lcobucci'); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); + $this->config->allows('string')->with('jwt.driver')->returns('lcobucci'); - $manager = new JwtManager($this->container, $this->claimFactory); + $manager = new JwtManager($this->container->instance(), $this->claimFactory); $provider = $this->provider; $manager->extend('lcobucci', static fn (): Lcobucci => $provider); @@ -171,18 +161,18 @@ public function testDisabledBlacklistIsNeverResolved(): void $this->mockContainer(); $this->mockConfig(); - $this->container->shouldReceive('make')->with(BlacklistContract::class)->never(); - - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([ValidationStub::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn([]); - $this->config->shouldReceive('get')->with('jwt.refresh_ttl')->andReturn(20160); - $this->config->shouldReceive('get')->with('jwt.ttl')->andReturn(120); - $this->config->shouldReceive('boolean')->with('jwt.refresh_iat')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.persistent_claims')->andReturn([]); - $this->claimFactory->shouldReceive('refresh')->once()->andReturn($payload); - $this->provider->shouldReceive('decode')->twice()->with($token)->andReturn($payload); - $this->provider->shouldReceive('encode')->once()->with($payload)->andReturn($refreshedToken); + $this->container->expects('make')->with(BlacklistContract::class)->never(); + + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); + $this->config->allows('array')->with('jwt.validations')->returns([ValidationStub::class]); + $this->config->allows('array')->with('jwt')->returns([]); + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(20160); + $this->config->allows('get')->with('jwt.ttl')->returns(120); + $this->config->allows('boolean')->with('jwt.refresh_iat')->returns(false); + $this->config->allows('array')->with('jwt.persistent_claims')->returns([]); + $this->claimFactory->expects('refresh')->returns($payload); + $this->provider->expects('decode')->times(2)->with($token)->returns($payload); + $this->provider->expects('encode')->with($payload)->returns($refreshedToken); $manager = $this->createManager(); @@ -203,11 +193,11 @@ public function testDecodeAToken(): void 'jti' => 'foo', ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([ValidationStub::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn([]); - $this->provider->shouldReceive('decode')->with($token)->andReturn($payload); - $this->blacklist->shouldReceive('has')->with($payload)->andReturn(false); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->config->allows('array')->with('jwt.validations')->returns([ValidationStub::class]); + $this->config->allows('array')->with('jwt')->returns([]); + $this->provider->allows('decode')->with($token)->returns($payload); + $this->blacklist->allows('has')->with($payload)->returns(false); $this->assertSame($payload, $this->createManager()->decode($token)); } @@ -227,11 +217,11 @@ public function testThrowExceptionWhenTokenIsBlacklisted(): void 'jti' => 'foo', ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([ValidationStub::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn([]); - $this->provider->shouldReceive('decode')->once()->with($token)->andReturn($payload); - $this->blacklist->shouldReceive('has')->with($payload)->andReturn(true); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->config->allows('array')->with('jwt.validations')->returns([ValidationStub::class]); + $this->config->allows('array')->with('jwt')->returns([]); + $this->provider->expects('decode')->with($token)->returns($payload); + $this->blacklist->allows('has')->with($payload)->returns(true); $this->createManager()->decode($token); } @@ -259,25 +249,25 @@ public function testRefreshAToken(): void $this->mockUuid($refreshJti); - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([ValidationStub::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn([]); - $this->config->shouldReceive('get')->with('jwt.refresh_ttl')->andReturn(20160); - $this->config->shouldReceive('array')->with('jwt.persistent_claims')->andReturn(['iss']); - $this->config->shouldReceive('get')->with('jwt.ttl')->andReturn(120); - $this->config->shouldReceive('boolean')->with('jwt.refresh_iat')->andReturnFalse(); - $this->claimFactory->shouldReceive('refresh')->once()->with( + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->config->allows('array')->with('jwt.validations')->returns([ValidationStub::class]); + $this->config->allows('array')->with('jwt')->returns([]); + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(20160); + $this->config->allows('array')->with('jwt.persistent_claims')->returns(['iss']); + $this->config->allows('get')->with('jwt.ttl')->returns(120); + $this->config->allows('boolean')->with('jwt.refresh_iat')->returns(false); + $this->claimFactory->expects('refresh')->with( $payload, 120, false, false, ['iss'], [], - )->andReturn($refreshPayload); - $this->provider->shouldReceive('decode')->twice()->with('foo.bar.baz')->andReturn($payload); - $this->provider->shouldReceive('encode')->with($refreshPayload)->andReturn($refreshedToken); - $this->blacklist->shouldReceive('has')->with($payload)->andReturn(false); - $this->blacklist->shouldReceive('add')->once()->with($payload)->andReturnTrue(); + )->returns($refreshPayload); + $this->provider->expects('decode')->times(2)->with('foo.bar.baz')->returns($payload); + $this->provider->allows('encode')->with($refreshPayload)->returns($refreshedToken); + $this->blacklist->allows('has')->with($payload)->returns(false); + $this->blacklist->expects('add')->with($payload)->returns(true); $this->assertSame($refreshedToken, $this->createManager()->refresh($token)); } @@ -297,18 +287,18 @@ public function testRefreshDoesNotInvalidateOldTokenWhenEncodingReplacementFails 'iat' => $this->testNowTimestamp, ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([RequiredClaims::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn(['required_claims' => ['iat', 'sub']]); - $this->config->shouldReceive('get')->with('jwt.refresh_ttl')->andReturn(20160); - $this->config->shouldReceive('array')->with('jwt.persistent_claims')->andReturn([]); - $this->config->shouldReceive('get')->with('jwt.ttl')->andReturn(120); - $this->config->shouldReceive('boolean')->with('jwt.refresh_iat')->andReturnFalse(); - $this->claimFactory->shouldReceive('refresh')->once()->andReturn($refreshPayload); - $this->provider->shouldReceive('decode')->once()->with($token)->andReturn($payload); - $this->provider->shouldReceive('encode')->once()->with($refreshPayload + ['jti' => '11111111-1111-4111-8111-111111111111'])->andThrow(new JwtException('signing failed')); - $this->blacklist->shouldReceive('has')->once()->with($payload)->andReturnFalse(); - $this->blacklist->shouldReceive('add')->never(); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->config->allows('array')->with('jwt.validations')->returns([RequiredClaims::class]); + $this->config->allows('array')->with('jwt')->returns(['required_claims' => ['iat', 'sub']]); + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(20160); + $this->config->allows('array')->with('jwt.persistent_claims')->returns([]); + $this->config->allows('get')->with('jwt.ttl')->returns(120); + $this->config->allows('boolean')->with('jwt.refresh_iat')->returns(false); + $this->claimFactory->expects('refresh')->returns($refreshPayload); + $this->provider->expects('decode')->with($token)->returns($payload); + $this->provider->expects('encode')->with($refreshPayload + ['jti' => '11111111-1111-4111-8111-111111111111'])->throws(new JwtException('signing failed')); + $this->blacklist->expects('has')->with($payload)->returns(false); + $this->blacklist->expects('add')->never(); $this->mockUuid('11111111-1111-4111-8111-111111111111'); @@ -333,23 +323,23 @@ public function testRefreshOmitsExpirationWhenTtlIsNull(): void 'iat' => $this->testNowTimestamp, ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([ValidationStub::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn([]); - $this->config->shouldReceive('get')->with('jwt.refresh_ttl')->andReturn(20160); - $this->config->shouldReceive('array')->with('jwt.persistent_claims')->andReturn(['iss']); - $this->config->shouldReceive('get')->with('jwt.ttl')->andReturn(null); - $this->config->shouldReceive('boolean')->with('jwt.refresh_iat')->andReturnFalse(); - $this->claimFactory->shouldReceive('refresh')->once()->with( + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); + $this->config->allows('array')->with('jwt.validations')->returns([ValidationStub::class]); + $this->config->allows('array')->with('jwt')->returns([]); + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(20160); + $this->config->allows('array')->with('jwt.persistent_claims')->returns(['iss']); + $this->config->allows('get')->with('jwt.ttl')->returns(null); + $this->config->allows('boolean')->with('jwt.refresh_iat')->returns(false); + $this->claimFactory->expects('refresh')->with( $payload, null, false, false, ['iss'], [], - )->andReturn($refreshPayload); - $this->provider->shouldReceive('decode')->once()->with('foo.bar.baz')->andReturn($payload); - $this->provider->shouldReceive('encode')->with($refreshPayload)->andReturn($refreshedToken); + )->returns($refreshPayload); + $this->provider->expects('decode')->with('foo.bar.baz')->returns($payload); + $this->provider->allows('encode')->with($refreshPayload)->returns($refreshedToken); $this->assertSame($refreshedToken, $this->createManager()->refresh($token)); } @@ -365,10 +355,10 @@ public function testDecodeStillRejectsExpiredTokensWhenExpiredClaimValidationIsE 'iat' => $this->testNowTimestamp, ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([RequiredClaims::class, ExpiredClaim::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn(['required_claims' => ['iat', 'sub']]); - $this->provider->shouldReceive('decode')->once()->with('foo.bar.baz')->andReturn($payload); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); + $this->config->allows('array')->with('jwt.validations')->returns([RequiredClaims::class, ExpiredClaim::class]); + $this->config->allows('array')->with('jwt')->returns(['required_claims' => ['iat', 'sub']]); + $this->provider->expects('decode')->with('foo.bar.baz')->returns($payload); $this->createManager()->decode('foo.bar.baz'); } @@ -394,7 +384,7 @@ public function testCustomValidationsAreResolvedFromTheContainerOnceAndReused(): }); $provider = $this->provider; - $provider->shouldReceive('decode')->times(3)->with($token)->andReturn($payload); + $provider->expects('decode')->times(3)->with($token)->returns($payload); $manager = new JwtManager($application, $this->claimFactory); $manager->extend('dummy', static fn (): Lcobucci => $provider); @@ -429,33 +419,33 @@ public function testRefreshSkipsTemporalValidationsInsideRefreshWindow(): void 'exp' => $this->testNowTimestamp + 7200, ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([ + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); + $this->config->allows('array')->with('jwt.validations')->returns([ RequiredClaims::class, ExpiredClaim::class, IssuerClaim::class, IssuedAtClaim::class, NotBeforeClaim::class, ]); - $this->config->shouldReceive('array')->with('jwt')->andReturn([ + $this->config->allows('array')->with('jwt')->returns([ 'required_claims' => ['iat', 'sub'], 'issuer' => 'http://example.com', 'leeway' => 0, ]); - $this->config->shouldReceive('get')->with('jwt.refresh_ttl')->andReturn(20160); - $this->config->shouldReceive('get')->with('jwt.ttl')->andReturn(120); - $this->config->shouldReceive('boolean')->with('jwt.refresh_iat')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.persistent_claims')->andReturn([]); - $this->claimFactory->shouldReceive('refresh')->once()->with( + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(20160); + $this->config->allows('get')->with('jwt.ttl')->returns(120); + $this->config->allows('boolean')->with('jwt.refresh_iat')->returns(false); + $this->config->allows('array')->with('jwt.persistent_claims')->returns([]); + $this->claimFactory->expects('refresh')->with( $payload, 120, false, false, [], [], - )->andReturn($refreshPayload); - $this->provider->shouldReceive('decode')->once()->with($token)->andReturn($payload); - $this->provider->shouldReceive('encode')->once()->with($refreshPayload)->andReturn($refreshedToken); + )->returns($refreshPayload); + $this->provider->expects('decode')->with($token)->returns($payload); + $this->provider->expects('encode')->with($refreshPayload)->returns($refreshedToken); $this->assertSame($refreshedToken, $this->createManager()->refresh($token)); } @@ -473,12 +463,12 @@ public function testRefreshRejectsFutureTimestampClaimsBeyondTheLeeway(string $v $claim => $this->testNowTimestamp + 61, ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([RequiredClaims::class, $validation]); - $this->config->shouldReceive('array')->with('jwt')->andReturn(['required_claims' => ['iat', 'sub'], 'leeway' => 60]); - $this->provider->shouldReceive('decode')->once()->with($token)->andReturn($payload); - $this->provider->shouldReceive('encode')->never(); - $this->blacklist->shouldReceive('add')->never(); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->config->allows('array')->with('jwt.validations')->returns([RequiredClaims::class, $validation]); + $this->config->allows('array')->with('jwt')->returns(['required_claims' => ['iat', 'sub'], 'leeway' => 60]); + $this->provider->expects('decode')->with($token)->returns($payload); + $this->provider->expects('encode')->never(); + $this->blacklist->expects('add')->never(); $this->createManager()->refresh($token); } @@ -498,17 +488,17 @@ public function testRefreshAcceptsFutureTimestampClaimsWithinTheLeeway(string $v 'iat' => $this->testNowTimestamp, ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([RequiredClaims::class, $validation]); - $this->config->shouldReceive('array')->with('jwt')->andReturn(['required_claims' => ['iat', 'sub'], 'leeway' => 60]); - $this->config->shouldReceive('get')->with('jwt.refresh_ttl')->andReturn(20160); - $this->config->shouldReceive('integer')->with('jwt.leeway')->andReturn(60); - $this->config->shouldReceive('get')->with('jwt.ttl')->andReturn(120); - $this->config->shouldReceive('boolean')->with('jwt.refresh_iat')->andReturnTrue(); - $this->config->shouldReceive('array')->with('jwt.persistent_claims')->andReturn([]); - $this->claimFactory->shouldReceive('refresh')->once()->with($payload, 120, true, false, [], [])->andReturn($refreshPayload); - $this->provider->shouldReceive('decode')->once()->with($token)->andReturn($payload); - $this->provider->shouldReceive('encode')->once()->with($refreshPayload)->andReturn($refreshedToken); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); + $this->config->allows('array')->with('jwt.validations')->returns([RequiredClaims::class, $validation]); + $this->config->allows('array')->with('jwt')->returns(['required_claims' => ['iat', 'sub'], 'leeway' => 60]); + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(20160); + $this->config->allows('integer')->with('jwt.leeway')->returns(60); + $this->config->allows('get')->with('jwt.ttl')->returns(120); + $this->config->allows('boolean')->with('jwt.refresh_iat')->returns(true); + $this->config->allows('array')->with('jwt.persistent_claims')->returns([]); + $this->claimFactory->expects('refresh')->with($payload, 120, true, false, [], [])->returns($refreshPayload); + $this->provider->expects('decode')->with($token)->returns($payload); + $this->provider->expects('encode')->with($refreshPayload)->returns($refreshedToken); $this->assertSame($refreshedToken, $this->createManager()->refresh($token)); } @@ -541,23 +531,23 @@ public function testRefreshAllowsPastNotBeforeClaim(): void 'nbf' => $this->testNowTimestamp, ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([RequiredClaims::class, NotBeforeClaim::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn(['required_claims' => ['iat', 'sub'], 'leeway' => 0]); - $this->config->shouldReceive('get')->with('jwt.refresh_ttl')->andReturn(20160); - $this->config->shouldReceive('get')->with('jwt.ttl')->andReturn(120); - $this->config->shouldReceive('boolean')->with('jwt.refresh_iat')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.persistent_claims')->andReturn([]); - $this->claimFactory->shouldReceive('refresh')->once()->with( + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); + $this->config->allows('array')->with('jwt.validations')->returns([RequiredClaims::class, NotBeforeClaim::class]); + $this->config->allows('array')->with('jwt')->returns(['required_claims' => ['iat', 'sub'], 'leeway' => 0]); + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(20160); + $this->config->allows('get')->with('jwt.ttl')->returns(120); + $this->config->allows('boolean')->with('jwt.refresh_iat')->returns(false); + $this->config->allows('array')->with('jwt.persistent_claims')->returns([]); + $this->claimFactory->expects('refresh')->with( $payload, 120, false, false, [], [], - )->andReturn($refreshPayload); - $this->provider->shouldReceive('decode')->once()->with($token)->andReturn($payload); - $this->provider->shouldReceive('encode')->once()->with($refreshPayload)->andReturn($refreshedToken); + )->returns($refreshPayload); + $this->provider->expects('decode')->with($token)->returns($payload); + $this->provider->expects('encode')->with($refreshPayload)->returns($refreshedToken); $this->assertSame($refreshedToken, $this->createManager()->refresh($token)); } @@ -575,22 +565,22 @@ public function testRefreshPassesResetClaimsCustomClaimsAndExplicitTtlToClaimFac 'tenant' => 'acme', ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([RequiredClaims::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn(['required_claims' => ['iat', 'sub']]); - $this->config->shouldReceive('get')->with('jwt.refresh_ttl')->andReturn(20160); - $this->config->shouldReceive('boolean')->with('jwt.refresh_iat')->andReturnTrue(); - $this->config->shouldReceive('array')->with('jwt.persistent_claims')->andReturn(['tenant']); - $this->claimFactory->shouldReceive('refresh')->once()->with( + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); + $this->config->allows('array')->with('jwt.validations')->returns([RequiredClaims::class]); + $this->config->allows('array')->with('jwt')->returns(['required_claims' => ['iat', 'sub']]); + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(20160); + $this->config->allows('boolean')->with('jwt.refresh_iat')->returns(true); + $this->config->allows('array')->with('jwt.persistent_claims')->returns(['tenant']); + $this->claimFactory->expects('refresh')->with( $payload, null, true, true, ['tenant'], ['tenant' => 'acme'], - )->andReturn($refreshPayload); - $this->provider->shouldReceive('decode')->once()->with($token)->andReturn($payload); - $this->provider->shouldReceive('encode')->once()->with($refreshPayload)->andReturn($refreshedToken); + )->returns($refreshPayload); + $this->provider->expects('decode')->with($token)->returns($payload); + $this->provider->expects('encode')->with($refreshPayload)->returns($refreshedToken); $this->assertSame($refreshedToken, $this->createManager()->refresh( token: $token, @@ -616,15 +606,15 @@ public function testRefreshThrowsWhenRefreshWindowHasExpired(int $leeway): void 'jti' => 'foo', ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([ValidationStub::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn([]); - $this->config->shouldReceive('get')->with('jwt.refresh_ttl')->andReturn(10); - $this->config->shouldReceive('integer')->with('jwt.leeway')->andReturn($leeway); - $this->provider->shouldReceive('decode')->once()->with('foo.bar.baz')->andReturn($payload); - $this->provider->shouldReceive('encode')->never(); - $this->blacklist->shouldReceive('has')->with($payload)->andReturn(false); - $this->blacklist->shouldReceive('add')->never(); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->config->allows('array')->with('jwt.validations')->returns([ValidationStub::class]); + $this->config->allows('array')->with('jwt')->returns([]); + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(10); + $this->config->allows('integer')->with('jwt.leeway')->returns($leeway); + $this->provider->expects('decode')->with('foo.bar.baz')->returns($payload); + $this->provider->expects('encode')->never(); + $this->blacklist->allows('has')->with($payload)->returns(false); + $this->blacklist->expects('add')->never(); $this->createManager()->refresh($token); } @@ -657,17 +647,17 @@ public function testRefreshWindowIncludesTheLeeway(): void 'exp' => $this->testNowTimestamp + 7200, ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([ValidationStub::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn([]); - $this->config->shouldReceive('get')->with('jwt.refresh_ttl')->andReturn(10); - $this->config->shouldReceive('integer')->with('jwt.leeway')->andReturn(60); - $this->config->shouldReceive('get')->with('jwt.ttl')->andReturn(120); - $this->config->shouldReceive('boolean')->with('jwt.refresh_iat')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.persistent_claims')->andReturn([]); - $this->claimFactory->shouldReceive('refresh')->once()->with($payload, 120, false, false, [], [])->andReturn($refreshPayload); - $this->provider->shouldReceive('decode')->once()->with($token)->andReturn($payload); - $this->provider->shouldReceive('encode')->once()->with($refreshPayload)->andReturn($refreshedToken); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); + $this->config->allows('array')->with('jwt.validations')->returns([ValidationStub::class]); + $this->config->allows('array')->with('jwt')->returns([]); + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(10); + $this->config->allows('integer')->with('jwt.leeway')->returns(60); + $this->config->allows('get')->with('jwt.ttl')->returns(120); + $this->config->allows('boolean')->with('jwt.refresh_iat')->returns(false); + $this->config->allows('array')->with('jwt.persistent_claims')->returns([]); + $this->claimFactory->expects('refresh')->with($payload, 120, false, false, [], [])->returns($refreshPayload); + $this->provider->expects('decode')->with($token)->returns($payload); + $this->provider->expects('encode')->with($refreshPayload)->returns($refreshedToken); $this->assertSame($refreshedToken, $this->createManager()->refresh($token)); } @@ -691,23 +681,23 @@ public function testRefreshWindowCanBeDisabled(): void 'exp' => $this->testNowTimestamp + 7200, ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([ValidationStub::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn([]); - $this->config->shouldReceive('get')->with('jwt.refresh_ttl')->andReturn(null); - $this->config->shouldReceive('array')->with('jwt.persistent_claims')->andReturn(['iss']); - $this->config->shouldReceive('get')->with('jwt.ttl')->andReturn(120); - $this->config->shouldReceive('boolean')->with('jwt.refresh_iat')->andReturnFalse(); - $this->claimFactory->shouldReceive('refresh')->once()->with( + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); + $this->config->allows('array')->with('jwt.validations')->returns([ValidationStub::class]); + $this->config->allows('array')->with('jwt')->returns([]); + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(null); + $this->config->allows('array')->with('jwt.persistent_claims')->returns(['iss']); + $this->config->allows('get')->with('jwt.ttl')->returns(120); + $this->config->allows('boolean')->with('jwt.refresh_iat')->returns(false); + $this->claimFactory->expects('refresh')->with( $payload, 120, false, false, ['iss'], [], - )->andReturn($refreshPayload); - $this->provider->shouldReceive('decode')->once()->with('foo.bar.baz')->andReturn($payload); - $this->provider->shouldReceive('encode')->with($refreshPayload)->andReturn($refreshedToken); + )->returns($refreshPayload); + $this->provider->expects('decode')->with('foo.bar.baz')->returns($payload); + $this->provider->allows('encode')->with($refreshPayload)->returns($refreshedToken); $this->assertSame($refreshedToken, $this->createManager()->refresh($token)); } @@ -724,16 +714,16 @@ public function testRefreshRejectsMissingIssuedAtBeforeAnInfiniteRefreshWindow(a ...$issuedAt, ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([RequiredClaims::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn(['required_claims' => ['sub']]); - $this->config->shouldReceive('get')->with('jwt.refresh_ttl')->andReturnNull(); - $this->config->shouldReceive('get')->with('jwt.ttl')->andReturn(120); - $this->config->shouldReceive('boolean')->with('jwt.refresh_iat')->andReturnTrue(); - $this->config->shouldReceive('array')->with('jwt.persistent_claims')->andReturn([]); - $this->claimFactory->shouldReceive('refresh')->never(); - $this->provider->shouldReceive('decode')->once()->with('foo.bar.baz')->andReturn($payload); - $this->provider->shouldReceive('encode')->never(); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); + $this->config->allows('array')->with('jwt.validations')->returns([RequiredClaims::class]); + $this->config->allows('array')->with('jwt')->returns(['required_claims' => ['sub']]); + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(null); + $this->config->allows('get')->with('jwt.ttl')->returns(120); + $this->config->allows('boolean')->with('jwt.refresh_iat')->returns(true); + $this->config->allows('array')->with('jwt.persistent_claims')->returns([]); + $this->claimFactory->expects('refresh')->never(); + $this->provider->expects('decode')->with('foo.bar.baz')->returns($payload); + $this->provider->expects('encode')->never(); $this->createManager()->refresh('foo.bar.baz'); } @@ -762,18 +752,18 @@ public function testRefreshFailsWhenTheOldTokenCannotBeInvalidated(): void 'jti' => 'bar', ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->config->shouldReceive('array')->with('jwt.validations')->andReturn([ValidationStub::class]); - $this->config->shouldReceive('array')->with('jwt')->andReturn([]); - $this->config->shouldReceive('get')->with('jwt.refresh_ttl')->andReturn(20160); - $this->config->shouldReceive('get')->with('jwt.ttl')->andReturn(120); - $this->config->shouldReceive('boolean')->with('jwt.refresh_iat')->andReturnFalse(); - $this->config->shouldReceive('array')->with('jwt.persistent_claims')->andReturn([]); - $this->claimFactory->shouldReceive('refresh')->once()->andReturn($refreshPayload); - $this->provider->shouldReceive('decode')->twice()->with('foo.bar.baz')->andReturn($payload); - $this->provider->shouldReceive('encode')->once()->with($refreshPayload)->andReturn('baz.bar.foo'); - $this->blacklist->shouldReceive('has')->once()->with($payload)->andReturnFalse(); - $this->blacklist->shouldReceive('add')->once()->with($payload)->andReturnFalse(); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->config->allows('array')->with('jwt.validations')->returns([ValidationStub::class]); + $this->config->allows('array')->with('jwt')->returns([]); + $this->config->allows('get')->with('jwt.refresh_ttl')->returns(20160); + $this->config->allows('get')->with('jwt.ttl')->returns(120); + $this->config->allows('boolean')->with('jwt.refresh_iat')->returns(false); + $this->config->allows('array')->with('jwt.persistent_claims')->returns([]); + $this->claimFactory->expects('refresh')->returns($refreshPayload); + $this->provider->expects('decode')->times(2)->with('foo.bar.baz')->returns($payload); + $this->provider->expects('encode')->with($refreshPayload)->returns('baz.bar.foo'); + $this->blacklist->expects('has')->with($payload)->returns(false); + $this->blacklist->expects('add')->with($payload)->returns(false); $this->createManager()->refresh('foo.bar.baz'); } @@ -790,10 +780,10 @@ public function testInvalidateAnExpiredButStructurallyValidToken(): void 'jti' => 'foo', ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->config->shouldReceive('array')->with('jwt.validations')->never(); - $this->provider->shouldReceive('decode')->once()->with('foo.bar.baz')->andReturn($payload); - $this->blacklist->shouldReceive('add')->once()->with($payload)->andReturnTrue(); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->config->expects('array')->with('jwt.validations')->never(); + $this->provider->expects('decode')->with('foo.bar.baz')->returns($payload); + $this->blacklist->expects('add')->with($payload)->returns(true); $this->assertTrue($this->createManager()->invalidate($token)); } @@ -810,9 +800,9 @@ public function testForceInvalidateATokenForever(): void 'jti' => 'foo', ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->provider->shouldReceive('decode')->once()->with('foo.bar.baz')->andReturn($payload); - $this->blacklist->shouldReceive('addForever')->once()->with($payload)->andReturnTrue(); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->provider->expects('decode')->with('foo.bar.baz')->returns($payload); + $this->blacklist->expects('addForever')->with($payload)->returns(true); $this->assertTrue($this->createManager()->invalidate($token, true)); } @@ -829,9 +819,9 @@ public function testInvalidateThrowsWhenBlacklistPersistenceFails(bool $forceFor 'jti' => 'foo', ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->provider->shouldReceive('decode')->once()->with('foo.bar.baz')->andReturn($payload); - $this->blacklist->shouldReceive($method)->once()->with($payload)->andReturnFalse(); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->provider->expects('decode')->with('foo.bar.baz')->returns($payload); + $this->blacklist->expects($method)->with($payload)->returns(false); $this->createManager()->invalidate('foo.bar.baz', $forceForever); } @@ -850,9 +840,9 @@ public function testFailedInvalidationKeepsTheTokenOutOfTheExceptionTrace(): voi $payload = ['sub' => 1, 'iat' => $this->testNowTimestamp, 'jti' => 'foo']; $exception = null; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->provider->shouldReceive('decode')->once()->with($token)->andReturn($payload); - $this->blacklist->shouldReceive('add')->once()->with($payload)->andReturnFalse(); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->provider->expects('decode')->with($token)->returns($payload); + $this->blacklist->expects('add')->with($payload)->returns(false); $manager = $this->createManager(); $ignoreArguments = ini_set('zend.exception_ignore_args', '0'); @@ -888,10 +878,10 @@ public function testInvalidateDoesNotReadTheBlacklistBeforeWriting(): void 'jti' => 'foo', ]; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnTrue(); - $this->provider->shouldReceive('decode')->once()->with('foo.bar.baz')->andReturn($payload); - $this->blacklist->shouldNotReceive('has'); - $this->blacklist->shouldReceive('add')->once()->with($payload)->andReturn(true); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(true); + $this->provider->expects('decode')->with('foo.bar.baz')->returns($payload); + $this->blacklist->expects('has')->never(); + $this->blacklist->expects('add')->with($payload)->returns(true); $this->assertTrue($this->createManager()->invalidate($token)); } @@ -903,7 +893,7 @@ public function testThrowAnExceptionWhenEnableBlacklistIsSetToFalse(): void $token = 'foo.bar.baz'; - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); $this->createManager()->invalidate($token); } @@ -912,9 +902,9 @@ public function testGetTheBlacklist(): void { $this->mockContainer(); $this->mockConfig(); - $this->container->shouldReceive('make')->once()->with(BlacklistContract::class)->andReturn($this->blacklist); + $this->container->expects('make')->with(BlacklistContract::class)->returns($this->blacklist); - $this->config->shouldReceive('boolean')->with('jwt.blacklist_enabled')->andReturnFalse(); + $this->config->allows('boolean')->with('jwt.blacklist_enabled')->returns(false); $manager = $this->createManager(); @@ -931,43 +921,43 @@ private function setTestNow(): void private function mockContainer(): void { - $this->container = m::mock(Container::class); + $this->container = Double::for(Container::class, override: true)->strict(); - $this->container->shouldReceive('make') - ->with(m::type('string'), m::hasKey('config')) - ->andReturnUsing(static fn (string $class, array $parameters): object => new $class($parameters['config'])); + $this->container->allows('make') + ->with(Argument::type('string'), Argument::satisfies(static fn (array $parameters): bool => array_key_exists('config', $parameters))) + ->resolves(static fn (string $class, array $parameters): object => new $class($parameters['config'])); } private function mockConfig(): void { - $this->config = m::mock(Repository::class); + $this->config = Double::for(Repository::class)->strict(); + $this->config->allows('integer')->with('jwt.leeway')->returns(0); - $this->container->shouldReceive('make')->with('config')->andReturn($this->config); + $this->container->allows('make')->with('config')->returns($this->config); } private function mockProvider(): void { - $this->provider = m::mock(Lcobucci::class); + $this->provider = Double::for(Lcobucci::class)->strict(); } private function mockBlacklist(): void { - $this->blacklist = m::mock(BlacklistContract::class); + $this->blacklist = Double::for(BlacklistContract::class)->strict(); - $this->container->shouldReceive('make')->with(BlacklistContract::class)->andReturn($this->blacklist); + $this->container->allows('make')->with(BlacklistContract::class)->returns($this->blacklist); } private function mockClaimFactory(): void { - $this->claimFactory = m::mock(ClaimFactory::class); + $this->claimFactory = Double::for(ClaimFactory::class)->strict(); } private function createManager(): JwtManager { - $this->config->shouldReceive('string')->with('jwt.driver')->andReturn('dummy'); - $this->config->shouldReceive('integer')->with('jwt.leeway')->andReturn(0)->byDefault(); + $this->config->allows('string')->with('jwt.driver')->returns('dummy'); - $manager = new JwtManager($this->container, $this->claimFactory); + $manager = new JwtManager($this->container->instance(), $this->claimFactory); $provider = $this->provider; $manager->extend('dummy', static fn () => $provider); diff --git a/tests/Jwt/JwtServiceProviderTest.php b/tests/Jwt/JwtServiceProviderTest.php index 72a1d364b5..7e9449bdd5 100644 --- a/tests/Jwt/JwtServiceProviderTest.php +++ b/tests/Jwt/JwtServiceProviderTest.php @@ -7,6 +7,7 @@ use Hypervel\Auth\AuthManager; use Hypervel\Cache\Repository as CacheRepository; use Hypervel\Contracts\Auth\UserProvider; +use Hypervel\Contracts\Cache\Factory as CacheFactory; use Hypervel\Contracts\Cache\Store; use Hypervel\Contracts\Foundation\Application as ApplicationContract; use Hypervel\Http\Request; @@ -27,12 +28,15 @@ use Hypervel\Support\Facades\Date; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionProperty; class JwtServiceProviderTest extends TestCase { + use VerifiesDoubles; + protected function getPackageProviders(ApplicationContract $app): array { return [ @@ -108,11 +112,11 @@ public function testGuardReceivesExplicitNullTtlAndDispatcher(): void 'driver' => 'jwt-test-provider', ]); - $this->app->instance('jwt', m::mock(ManagerContract::class)); + $this->app->instance('jwt', Double::for(ManagerContract::class)->strict()); /** @var AuthManager $authManager */ $authManager = $this->app->make(AuthManager::class); - $authManager->provider('jwt-test-provider', fn () => m::mock(UserProvider::class)); + $authManager->provider('jwt-test-provider', fn () => Double::for(UserProvider::class)->strict()); /** @var JwtGuard $guard */ $guard = $authManager->guard('jwt'); @@ -134,11 +138,11 @@ public function testGuardReceivesNumericPerGuardTtl(): void 'driver' => 'jwt-test-provider', ]); - $this->app->instance('jwt', m::mock(ManagerContract::class)); + $this->app->instance('jwt', Double::for(ManagerContract::class)->strict()); /** @var AuthManager $authManager */ $authManager = $this->app->make(AuthManager::class); - $authManager->provider('jwt-test-provider', fn () => m::mock(UserProvider::class)); + $authManager->provider('jwt-test-provider', fn () => Double::for(UserProvider::class)->strict()); /** @var JwtGuard $guard */ $guard = $authManager->guard('jwt'); @@ -170,10 +174,10 @@ public function testCacheStorageUsesTheConfiguredBlacklistStore(?string $store): $config->set('jwt.blacklist_enabled', true); $config->set('jwt.blacklist_store', $store); - $repository = m::mock(CacheRepository::class); - $repository->shouldReceive('getStore')->once()->andReturn(m::mock(Store::class)); - $cache = m::mock(); - $cache->shouldReceive('store')->once()->with($store)->andReturn($repository); + $repository = Double::for(CacheRepository::class)->strict(); + $repository->expects('getStore')->returns(Double::for(Store::class)->strict()); + $cache = Double::for(CacheFactory::class)->strict(); + $cache->expects('store')->with($store)->returns($repository); $this->app->instance('cache', $cache); $this->app->forgetInstance(BlacklistContract::class); @@ -207,8 +211,8 @@ public function testCustomBlacklistStorageSkipsCacheStoreResolution(): void $config->set('jwt.blacklist_grace_period', 0); $config->set('jwt.refresh_ttl', 20160); - $cache = m::mock(); - $cache->shouldReceive('store')->never(); + $cache = Double::for(CacheFactory::class)->strict(); + $cache->expects('store')->never(); $this->app->instance('cache', $cache); $this->app->forgetInstance(BlacklistContract::class); diff --git a/tests/Jwt/Storage/CacheStorageTest.php b/tests/Jwt/Storage/CacheStorageTest.php index c5d9c3a17e..c7c1a482a5 100644 --- a/tests/Jwt/Storage/CacheStorageTest.php +++ b/tests/Jwt/Storage/CacheStorageTest.php @@ -8,28 +8,29 @@ use Hypervel\Cache\ArrayStore; use Hypervel\Cache\Repository; use Hypervel\Cache\TaggableStore; +use Hypervel\Cache\TaggedCache; use Hypervel\Cache\TagMode; -use Hypervel\Contracts\Cache\Repository as CacheRepository; use Hypervel\Contracts\Cache\Store; use Hypervel\Jwt\Storage\CacheStorage; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class CacheStorageTest extends TestCase { - /** - * @var CacheRepository|MockInterface - */ - protected CacheRepository $cache; + use VerifiesDoubles; + + protected Repository&DoubleInterface $cache; protected CacheStorage $storage; public function testAddTheItemToAllModeTaggedStorage(): void { $this->useStoreMode(TagMode::All); - $this->cache->shouldReceive('tags')->with(['jwt_blacklist'])->once()->andReturnSelf(); - $this->cache->shouldReceive('put')->with($this->storageKey('foo'), 'bar', 10 * 60)->once()->andReturnFalse(); + $this->cache->expects('tags')->with(['jwt_blacklist'])->returns($this->cache); + $this->cache->expects('put')->with($this->storageKey('foo'), 'bar', 10 * 60)->returns(false); $this->assertFalse($this->storage->add('foo', 'bar', 10)); } @@ -37,8 +38,8 @@ public function testAddTheItemToAllModeTaggedStorage(): void public function testAddTheItemToAnyModeTaggedStorage(): void { $this->useStoreMode(TagMode::Any); - $this->cache->shouldReceive('tags')->with(['jwt_blacklist'])->once()->andReturnSelf(); - $this->cache->shouldReceive('put')->with($this->storageKey('foo'), 'bar', 10 * 60)->once()->andReturnTrue(); + $this->cache->expects('tags')->with(['jwt_blacklist'])->returns($this->cache); + $this->cache->expects('put')->with($this->storageKey('foo'), 'bar', 10 * 60)->returns(true); $this->assertTrue($this->storage->add('foo', 'bar', 10)); } @@ -46,8 +47,8 @@ public function testAddTheItemToAnyModeTaggedStorage(): void public function testAddTheItemToUntaggedStorage(): void { $this->useUntaggedStore(); - $this->cache->shouldReceive('tags')->never(); - $this->cache->shouldReceive('put')->with($this->storageKey('foo'), 'bar', 10 * 60)->once()->andReturnTrue(); + $this->cache->expects('tags')->never(); + $this->cache->expects('put')->with($this->storageKey('foo'), 'bar', 10 * 60)->returns(true); $this->assertTrue($this->storage->add('foo', 'bar', 10)); } @@ -55,8 +56,8 @@ public function testAddTheItemToUntaggedStorage(): void public function testAddTheItemToAllModeTaggedStorageForever(): void { $this->useStoreMode(TagMode::All); - $this->cache->shouldReceive('tags')->with(['jwt_blacklist'])->once()->andReturnSelf(); - $this->cache->shouldReceive('forever')->with($this->storageKey('foo'), 'bar')->once()->andReturnFalse(); + $this->cache->expects('tags')->with(['jwt_blacklist'])->returns($this->cache); + $this->cache->expects('forever')->with($this->storageKey('foo'), 'bar')->returns(false); $this->assertFalse($this->storage->forever('foo', 'bar')); } @@ -64,8 +65,8 @@ public function testAddTheItemToAllModeTaggedStorageForever(): void public function testAddTheItemToAnyModeTaggedStorageForever(): void { $this->useStoreMode(TagMode::Any); - $this->cache->shouldReceive('tags')->with(['jwt_blacklist'])->once()->andReturnSelf(); - $this->cache->shouldReceive('forever')->with($this->storageKey('foo'), 'bar')->once()->andReturnTrue(); + $this->cache->expects('tags')->with(['jwt_blacklist'])->returns($this->cache); + $this->cache->expects('forever')->with($this->storageKey('foo'), 'bar')->returns(true); $this->assertTrue($this->storage->forever('foo', 'bar')); } @@ -73,8 +74,8 @@ public function testAddTheItemToAnyModeTaggedStorageForever(): void public function testAddTheItemToUntaggedStorageForever(): void { $this->useUntaggedStore(); - $this->cache->shouldReceive('tags')->never(); - $this->cache->shouldReceive('forever')->with($this->storageKey('foo'), 'bar')->once()->andReturnTrue(); + $this->cache->expects('tags')->never(); + $this->cache->expects('forever')->with($this->storageKey('foo'), 'bar')->returns(true); $this->assertTrue($this->storage->forever('foo', 'bar')); } @@ -82,8 +83,8 @@ public function testAddTheItemToUntaggedStorageForever(): void public function testGetAnItemFromAllModeTaggedStorage(): void { $this->useStoreMode(TagMode::All); - $this->cache->shouldReceive('tags')->with(['jwt_blacklist'])->once()->andReturnSelf(); - $this->cache->shouldReceive('get')->with($this->storageKey('foo'))->once()->andReturn(['foo' => 'bar']); + $this->cache->expects('tags')->with(['jwt_blacklist'])->returns($this->cache); + $this->cache->expects('get')->with($this->storageKey('foo'))->returns(['foo' => 'bar']); $this->assertSame(['foo' => 'bar'], $this->storage->get('foo')); } @@ -91,8 +92,8 @@ public function testGetAnItemFromAllModeTaggedStorage(): void public function testGetAnItemFromAnyModeStorageUsesPlainKey(): void { $this->useStoreMode(TagMode::Any); - $this->cache->shouldReceive('tags')->never(); - $this->cache->shouldReceive('get')->with($this->storageKey('foo'))->once()->andReturn(['foo' => 'bar']); + $this->cache->expects('tags')->never(); + $this->cache->expects('get')->with($this->storageKey('foo'))->returns(['foo' => 'bar']); $this->assertSame(['foo' => 'bar'], $this->storage->get('foo')); } @@ -100,8 +101,8 @@ public function testGetAnItemFromAnyModeStorageUsesPlainKey(): void public function testGetAnItemFromUntaggedStorage(): void { $this->useUntaggedStore(); - $this->cache->shouldReceive('tags')->never(); - $this->cache->shouldReceive('get')->with($this->storageKey('foo'))->once()->andReturn(['foo' => 'bar']); + $this->cache->expects('tags')->never(); + $this->cache->expects('get')->with($this->storageKey('foo'))->returns(['foo' => 'bar']); $this->assertSame(['foo' => 'bar'], $this->storage->get('foo')); } @@ -109,8 +110,8 @@ public function testGetAnItemFromUntaggedStorage(): void public function testRemoveTheItemFromAllModeTaggedStorage(): void { $this->useStoreMode(TagMode::All); - $this->cache->shouldReceive('tags')->with(['jwt_blacklist'])->once()->andReturnSelf(); - $this->cache->shouldReceive('forget')->with($this->storageKey('foo'))->once()->andReturn(true); + $this->cache->expects('tags')->with(['jwt_blacklist'])->returns($this->cache); + $this->cache->expects('forget')->with($this->storageKey('foo'))->returns(true); $this->assertTrue($this->storage->destroy('foo')); } @@ -118,8 +119,8 @@ public function testRemoveTheItemFromAllModeTaggedStorage(): void public function testRemoveTheItemFromAnyModeStorageUsesPlainKey(): void { $this->useStoreMode(TagMode::Any); - $this->cache->shouldReceive('tags')->never(); - $this->cache->shouldReceive('forget')->with($this->storageKey('foo'))->once()->andReturn(true); + $this->cache->expects('tags')->never(); + $this->cache->expects('forget')->with($this->storageKey('foo'))->returns(true); $this->assertTrue($this->storage->destroy('foo')); } @@ -127,8 +128,8 @@ public function testRemoveTheItemFromAnyModeStorageUsesPlainKey(): void public function testRemoveTheItemFromUntaggedStorage(): void { $this->useUntaggedStore(); - $this->cache->shouldReceive('tags')->never(); - $this->cache->shouldReceive('forget')->with($this->storageKey('foo'))->once()->andReturnFalse(); + $this->cache->expects('tags')->never(); + $this->cache->expects('forget')->with($this->storageKey('foo'))->returns(false); $this->assertFalse($this->storage->destroy('foo')); } @@ -136,8 +137,8 @@ public function testRemoveTheItemFromUntaggedStorage(): void public function testRemoveAllAllModeTaggedItemsFromStorage(): void { $this->useStoreMode(TagMode::All); - $this->cache->shouldReceive('tags')->with(['jwt_blacklist'])->once()->andReturnSelf(); - $this->cache->shouldReceive('flush')->withNoArgs()->once()->andReturnFalse(); + $this->cache->expects('tags')->with(['jwt_blacklist'])->returns($this->cache); + $this->cache->expects('flush')->with()->returns(false); $this->assertFalse($this->storage->flush()); } @@ -145,8 +146,8 @@ public function testRemoveAllAllModeTaggedItemsFromStorage(): void public function testRemoveAllAnyModeTaggedItemsFromStorage(): void { $this->useStoreMode(TagMode::Any); - $this->cache->shouldReceive('tags')->with(['jwt_blacklist'])->once()->andReturnSelf(); - $this->cache->shouldReceive('flush')->withNoArgs()->once()->andReturnTrue(); + $this->cache->expects('tags')->with(['jwt_blacklist'])->returns($this->cache); + $this->cache->expects('flush')->with()->returns(true); $this->assertTrue($this->storage->flush()); } @@ -166,9 +167,8 @@ public function testRemoveAllItemsKeepsUnrelatedCacheEntries(): void public function testRemoveAllItemsFromUntaggedStorageThrowsWithoutFlushingTheStore(): void { - /** @var MockInterface|Store */ - $store = m::mock(Store::class); - $store->shouldReceive('flush')->never(); + $store = Double::for(Store::class)->strict(); + $store->expects('flush')->never(); $storage = new CacheStorage(new Repository($store)); $this->expectException(BadMethodCallException::class); @@ -179,17 +179,15 @@ public function testRemoveAllItemsFromUntaggedStorageThrowsWithoutFlushingTheSto public function testStoreWithTagsDisabledUsesPlainKeysWithoutReadingTagMode(): void { - /** @var CacheRepository|MockInterface */ - $cache = m::mock(CacheRepository::class); - /** @var MockInterface|TaggableStore */ - $store = m::mock(TaggableStore::class); - - $store->shouldReceive('supportsTags')->once()->andReturnFalse(); - $store->shouldReceive('getTagMode')->never(); - $cache->shouldReceive('getStore')->once()->andReturn($store); - $cache->shouldReceive('tags')->never(); - $cache->shouldReceive('put')->with($this->storageKey('foo'), 'bar', 10 * 60)->once()->andReturnTrue(); - $cache->shouldReceive('get')->with($this->storageKey('foo'))->once()->andReturn('bar'); + $cache = Double::for(Repository::class)->strict(); + $store = Double::for(TaggableStore::class)->strict(); + + $store->expects('supportsTags')->returns(false); + $store->expects('getTagMode')->never(); + $cache->expects('getStore')->returns($store); + $cache->expects('tags')->never(); + $cache->expects('put')->with($this->storageKey('foo'), 'bar', 10 * 60)->returns(true); + $cache->expects('get')->with($this->storageKey('foo'))->returns('bar'); $storage = new CacheStorage($cache); @@ -200,7 +198,7 @@ public function testStoreWithTagsDisabledUsesPlainKeysWithoutReadingTagMode(): v public function testLongIdentifiersFitLimitedKeyColumns(): void { $this->useUntaggedStore(); - $this->cache->shouldReceive('forever')->with(m::capture($key), 'forever')->once()->andReturnTrue(); + $this->cache->expects('forever')->with(Argument::capture($key), 'forever')->returns(true); $this->assertTrue($this->storage->forever(str_repeat('a', 1000), 'forever')); $this->assertLessThanOrEqual(255, strlen($key)); @@ -222,14 +220,12 @@ public function testIdentifiersSharingALongPrefixStayDistinct(): void */ protected function useStoreMode(TagMode $mode): void { - /** @var CacheRepository|MockInterface */ - $cache = m::mock(CacheRepository::class); - /** @var MockInterface|TaggableStore */ - $store = m::mock(TaggableStore::class); + $cache = Double::for(TaggedCache::class)->strict(); + $store = Double::for(TaggableStore::class)->strict(); - $store->shouldReceive('supportsTags')->once()->andReturnTrue(); - $store->shouldReceive('getTagMode')->once()->andReturn($mode); - $cache->shouldReceive('getStore')->once()->andReturn($store); + $store->expects('supportsTags')->returns(true); + $store->expects('getTagMode')->returns($mode); + $cache->expects('getStore')->returns($store); $this->cache = $cache; $this->storage = new CacheStorage($this->cache); @@ -240,9 +236,8 @@ protected function useStoreMode(TagMode $mode): void */ protected function useUntaggedStore(): void { - /** @var CacheRepository|MockInterface */ - $cache = m::mock(CacheRepository::class); - $cache->shouldReceive('getStore')->once()->andReturn(m::mock(Store::class)); + $cache = Double::for(Repository::class)->strict(); + $cache->expects('getStore')->returns(Double::for(Store::class)->strict()); $this->cache = $cache; $this->storage = new CacheStorage($this->cache); diff --git a/tests/Log/ContextQueueTest.php b/tests/Log/ContextQueueTest.php index 09cf3f942a..e0f7535c8d 100644 --- a/tests/Log/ContextQueueTest.php +++ b/tests/Log/ContextQueueTest.php @@ -25,13 +25,16 @@ use Hypervel\Queue\Queue; use Hypervel\Queue\SyncQueue; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Throwable; class ContextQueueTest extends TestCase { + use VerifiesDoubles; + public function testContextIsIncludedInJobPayload(): void { Repository::getInstance()->add('trace_id', 'abc-123'); @@ -203,8 +206,8 @@ public function testContextIsHydratedWhenJobProcesses(): void $this->assertFalse(Repository::hasInstance()); // Simulate JobProcessing event with the payload - $job = m::mock(\Hypervel\Contracts\Queue\Job::class); - $job->shouldReceive('payload')->andReturn($payload); + $job = Double::for(JobContract::class)->strict(); + $job->allows('payload')->returns($payload); $event = new JobProcessing('sync', $job); $this->app->make('events')->dispatch($event); @@ -216,8 +219,8 @@ public function testContextIsHydratedWhenJobProcesses(): void public function testHydrateSkipsWhenPayloadHasNoContext(): void { - $job = m::mock(\Hypervel\Contracts\Queue\Job::class); - $job->shouldReceive('payload')->andReturn(['job' => 'SomeJob']); + $job = Double::for(JobContract::class)->strict(); + $job->allows('payload')->returns(['job' => 'SomeJob']); $event = new JobProcessing('sync', $job); $this->app->make('events')->dispatch($event); @@ -232,8 +235,8 @@ public function testPayloadWithoutContextFlushesAnExistingRepository(): void $repository->add('stale', 'value'); $repository->addHidden('secret', 'value'); - $job = m::mock(\Hypervel\Contracts\Queue\Job::class); - $job->shouldReceive('payload')->andReturn(['job' => 'SomeJob']); + $job = Double::for(JobContract::class)->strict(); + $job->allows('payload')->returns(['job' => 'SomeJob']); $this->app->make('events')->dispatch(new JobProcessing('sync', $job)); @@ -295,8 +298,8 @@ public function testHydratedHookFiresWhenJobProcesses(): void }); // Simulate JobProcessing - $job = m::mock(\Hypervel\Contracts\Queue\Job::class); - $job->shouldReceive('payload')->andReturn($payload); + $job = Double::for(JobContract::class)->strict(); + $job->allows('payload')->returns($payload); $this->app->make('events')->dispatch(new JobProcessing('sync', $job)); @@ -310,8 +313,8 @@ public function testHydratedHookRunsWithoutPayloadContextInAFreshCoroutine(): vo }); $events = $this->app->make('events'); - $job = m::mock(JobContract::class); - $job->shouldReceive('payload')->once()->andReturn(['job' => 'SomeJob']); + $job = Double::for(JobContract::class)->strict(); + $job->expects('payload')->returns(['job' => 'SomeJob']); $channel = new Channel(1); Coroutine::create(static function () use ($events, $job, $channel): void { @@ -360,8 +363,8 @@ public function testRoundTripPreservesVariousDataTypes(): void CoroutineContext::flush(); // Hydrate from the payload - $job = m::mock(\Hypervel\Contracts\Queue\Job::class); - $job->shouldReceive('payload')->andReturn($payload); + $job = Double::for(JobContract::class)->strict(); + $job->allows('payload')->returns($payload); $this->app->make('events')->dispatch(new JobProcessing('sync', $job)); // Verify all types survived the round trip diff --git a/tests/Log/ContextTest.php b/tests/Log/ContextTest.php index b556cb8642..c90b12c580 100644 --- a/tests/Log/ContextTest.php +++ b/tests/Log/ContextTest.php @@ -9,12 +9,16 @@ use Hypervel\Log\Context\Events\ContextHydrated; use Hypervel\Log\Context\Repository; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use stdClass; class ContextTest extends TestCase { + use VerifiesDoubles; + protected Repository $context; protected Dispatcher $events; @@ -23,10 +27,8 @@ protected function setUp(): void { parent::setUp(); - $this->events = m::mock(Dispatcher::class); - $this->events->shouldReceive('hasListeners')->byDefault()->andReturn(true); - $this->events->shouldReceive('listen')->byDefault(); - $this->events->shouldReceive('dispatch')->byDefault(); + $this->events = Double::for(Dispatcher::class)->strict(); + $this->events->allows('hasListeners')->returns(true); $this->context = new Repository($this->events); } @@ -530,9 +532,8 @@ public function testItCanSerializeAndDeserializeValues(): void 'backed_enum' => StringBackedSuit::Clubs, ]); - $this->events->shouldReceive('dispatch') - ->once() - ->with(m::type(ContextDehydrating::class)); + $this->events->expects('dispatch') + ->with(Argument::type(ContextDehydrating::class)); $payload = $this->context->dehydrate(); $this->assertNotNull($payload); @@ -541,9 +542,8 @@ public function testItCanSerializeAndDeserializeValues(): void // Hydrate into a fresh context $fresh = new Repository($this->events); - $this->events->shouldReceive('dispatch') - ->once() - ->with(m::type(ContextHydrated::class)); + $this->events->expects('dispatch') + ->with(Argument::type(ContextHydrated::class)); $fresh->hydrate($payload); @@ -559,15 +559,16 @@ public function testItCanSerializeAndDeserializeValues(): void public function testDehydrateReturnsNullWhenEmpty(): void { + $this->events->allows('dispatch')->with(Argument::type(ContextDehydrating::class)); + $this->assertNull($this->context->dehydrate()); } public function testDehydrateIncludesHiddenData(): void { $this->context->addHidden('secret', 'token'); - $this->events->shouldReceive('dispatch') - ->once() - ->with(m::type(ContextDehydrating::class)); + $this->events->expects('dispatch') + ->with(Argument::type(ContextDehydrating::class)); $payload = $this->context->dehydrate(); @@ -578,9 +579,8 @@ public function testDehydrateIncludesHiddenData(): void public function testHydratingNullTriggersHydratedEvent(): void { - $this->events->shouldReceive('dispatch') - ->once() - ->with(m::type(ContextHydrated::class)); + $this->events->expects('dispatch') + ->with(Argument::type(ContextHydrated::class)); $this->context->hydrate(null); } @@ -589,12 +589,10 @@ public function testHydrateFlushesExistingDataBeforeRestoring(): void { $this->context->add('old', 'data'); - $this->events->shouldReceive('dispatch') - ->once() - ->with(m::type(ContextDehydrating::class)); - $this->events->shouldReceive('dispatch') - ->once() - ->with(m::type(ContextHydrated::class)); + $this->events->expects('dispatch') + ->with(Argument::type(ContextDehydrating::class)); + $this->events->expects('dispatch') + ->with(Argument::type(ContextHydrated::class)); $other = new Repository($this->events); $other->add('new', 'data'); @@ -610,13 +608,12 @@ public function testDehydratingCallbackCanModifyWithoutAffectingOriginal(): void { $this->context->add('key', 'original'); - $this->events->shouldReceive('dispatch') - ->once() - ->with(m::on(function (ContextDehydrating $event) { + $this->events->expects('dispatch') + ->with(Argument::type(ContextDehydrating::class)) + ->resolves(function (ContextDehydrating $event): void { $event->context->add('key', 'modified'); $event->context->add('extra', 'added'); - return true; - })); + }); $payload = $this->context->dehydrate(); @@ -633,15 +630,13 @@ public function testHydratedCallbackFiresAfterHydration(): void { $callbackContext = null; - $this->events->shouldReceive('dispatch') - ->once() - ->with(m::type(ContextDehydrating::class)); - $this->events->shouldReceive('dispatch') - ->once() - ->with(m::on(function (ContextHydrated $event) use (&$callbackContext) { + $this->events->expects('dispatch') + ->with(Argument::type(ContextDehydrating::class)); + $this->events->expects('dispatch') + ->with(Argument::type(ContextHydrated::class)) + ->resolves(function (ContextHydrated $event) use (&$callbackContext): void { $callbackContext = $event->context; - return true; - })); + }); $other = new Repository($this->events); $other->add('key', 'value'); @@ -661,27 +656,25 @@ public function testContextDehydratingEventIsDispatched(): void { $this->context->add('key', 'value'); - $this->events->shouldReceive('dispatch') - ->once() - ->with(m::type(ContextDehydrating::class)); + $this->events->expects('dispatch') + ->with(Argument::type(ContextDehydrating::class)); $this->context->dehydrate(); } public function testContextHydratedEventIsDispatched(): void { - $this->events->shouldReceive('dispatch') - ->once() - ->with(m::type(ContextHydrated::class)); + $this->events->expects('dispatch') + ->with(Argument::type(ContextHydrated::class)); $this->context->hydrate(null); } public function testContextDehydratingEventIsSkippedWhenNoListenersAreRegistered(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(ContextDehydrating::class)->andReturn(false); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(ContextDehydrating::class)->returns(false); + $events->expects('dispatch')->never(); $context = new Repository($events); $context->add('key', 'value'); @@ -694,9 +687,9 @@ public function testContextDehydratingEventIsSkippedWhenNoListenersAreRegistered public function testContextHydratedEventIsSkippedWhenNoListenersAreRegistered(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(ContextHydrated::class)->andReturn(false); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(ContextHydrated::class)->returns(false); + $events->expects('dispatch')->never(); $context = new Repository($events); $context->hydrate([ @@ -711,12 +704,11 @@ public function testDehydratingEventReceivesCloneNotOriginal(): void $this->context->add('key', 'value'); $eventContext = null; - $this->events->shouldReceive('dispatch') - ->once() - ->with(m::on(function (ContextDehydrating $event) use (&$eventContext) { + $this->events->expects('dispatch') + ->with(Argument::type(ContextDehydrating::class)) + ->resolves(function (ContextDehydrating $event) use (&$eventContext): void { $eventContext = $event->context; - return true; - })); + }); $this->context->dehydrate(); diff --git a/tests/Log/LogLoggerTest.php b/tests/Log/LogLoggerTest.php index 4e2b3cf651..fd87e69891 100644 --- a/tests/Log/LogLoggerTest.php +++ b/tests/Log/LogLoggerTest.php @@ -14,7 +14,8 @@ use Hypervel\Log\Events\MessageLogged; use Hypervel\Log\Logger; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Monolog\Handler\AbstractHandler; use Monolog\Handler\TestHandler; use Monolog\Level; @@ -28,6 +29,8 @@ class LogLoggerTest extends TestCase { + use VerifiesDoubles; + public function testMethodsPassErrorAdditionsToMonolog(): void { $monolog = new Monolog('test'); @@ -326,7 +329,7 @@ public function testNamedLoggerRejectsNonMonologDrivers(): void { $this->expectExceptionObject(new RuntimeException('Named loggers are only supported by Monolog drivers.')); - (new Logger(m::mock(LoggerInterface::class)))->withName('tenant'); + (new Logger(Double::for(LoggerInterface::class)->strict()))->withName('tenant'); } // -- Hypervel-specific tests -- @@ -338,7 +341,7 @@ public function testWithContext(): void $writer->withContext(['foo' => 'bar']); $writer->withContext(['baz' => 'qux']); - $monolog->shouldReceive('isHandling')->with('error')->andReturn(true); + $monolog->allows('isHandling')->with('error')->returns(true); $monolog->expects('error')->with('test message', ['foo' => 'bar', 'baz' => 'qux']); $writer->error('test message'); @@ -346,11 +349,11 @@ public function testWithContext(): void public function testLoggerSkipsEventDispatchWhenNoListenersAreRegistered(): void { - $writer = new Logger($monolog = $this->mockMonolog(), $events = m::mock(DispatcherContract::class)); - $monolog->shouldReceive('isHandling')->with('error')->andReturn(true); + $writer = new Logger($monolog = $this->mockMonolog(), $events = Double::for(DispatcherContract::class)->strict()); + $monolog->allows('isHandling')->with('error')->returns(true); $monolog->expects('error')->with('foo', []); - $events->expects('hasListeners')->with(MessageLogged::class)->andReturn(false); - $events->shouldNotReceive('dispatch'); + $events->expects('hasListeners')->with(MessageLogged::class)->returns(false); + $events->expects('dispatch')->never(); $writer->error('foo'); } @@ -364,7 +367,7 @@ public function testMessageLoggedExtraContainsVisibleContextAndExcludesHidden(): CoroutineContext::set(ContextRepository::CONTEXT_KEY, $repository); $writer = new Logger($monolog = $this->mockMonolog(), $events); - $monolog->shouldReceive('isHandling')->with('info')->andReturn(true); + $monolog->allows('isHandling')->with('info')->returns(true); $monolog->expects('info')->with('test', []); $captured = null; @@ -386,7 +389,7 @@ public function testMessageLoggedExtraIsEmptyWhenNoContextUsed(): void $events = new Dispatcher; $writer = new Logger($monolog = $this->mockMonolog(), $events); - $monolog->shouldReceive('isHandling')->with('info')->andReturn(true); + $monolog->allows('isHandling')->with('info')->returns(true); $monolog->expects('info')->with('test', []); $captured = null; @@ -404,7 +407,7 @@ public function testMessageLoggedExtraIsEmptyWhenNoContextUsed(): void */ private function mockMonolog(): Monolog { - $monolog = m::mock(Monolog::class); + $monolog = Double::for(Monolog::class)->strict(); $monolog->expects('useLoggingLoopDetection')->with(false); return $monolog; diff --git a/tests/Log/LogServiceProviderTest.php b/tests/Log/LogServiceProviderTest.php index 2803c87eb8..21fd966e64 100644 --- a/tests/Log/LogServiceProviderTest.php +++ b/tests/Log/LogServiceProviderTest.php @@ -8,7 +8,8 @@ use Hypervel\Core\Events\BeforeServerFork; use Hypervel\Log\LogManager; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Monolog\Handler\BufferHandler; use Monolog\Handler\TestHandler; use Psr\Log\AbstractLogger; @@ -17,6 +18,8 @@ class LogServiceProviderTest extends TestCase { + use VerifiesDoubles; + private TestHandler $handler; /** @@ -85,6 +88,6 @@ public function testBeforeServerForkForgetsLoggersWithoutMonologLifecycle(): voi */ private function dispatchBeforeServerFork(): void { - $this->app->make('events')->dispatch(new BeforeServerFork(m::mock(Server::class))); + $this->app->make('events')->dispatch(new BeforeServerFork(Double::for(Server::class)->strict())); } } diff --git a/tests/Mail/AttachmentTest.php b/tests/Mail/AttachmentTest.php index 28ebfdcdb6..73d677a770 100644 --- a/tests/Mail/AttachmentTest.php +++ b/tests/Mail/AttachmentTest.php @@ -11,10 +11,13 @@ use Hypervel\Mail\Attachment; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class AttachmentTest extends TestCase { + use VerifiesDoubles; + public function testFromUrlWithHttpScheme(): void { $attachment = Attachment::fromUrl('http://example.com/file.pdf'); @@ -128,12 +131,12 @@ public function testIsEquivalentHonorsComparisonOptions(): void public function testIsEquivalentWithStorageAttachments(): void { - $storage = m::mock(FilesystemAdapter::class); - $storage->shouldReceive('mimeType')->twice()->with('report.txt')->andReturn('text/plain'); - $storage->shouldReceive('get')->twice()->with('report.txt')->andReturn('file content'); + $storage = Double::for(FilesystemAdapter::class)->strict(); + $storage->expects('mimeType')->times(2)->with('report.txt')->returns('text/plain'); + $storage->expects('get')->times(2)->with('report.txt')->returns('file content'); - $factory = m::mock(FilesystemFactory::class); - $factory->shouldReceive('disk')->twice()->with('documents')->andReturn($storage); + $factory = Double::for(FilesystemFactory::class)->strict(); + $factory->expects('disk')->times(2)->with('documents')->returns($storage); $container = new Container; $container->instance(FilesystemFactory::class, $factory); @@ -165,12 +168,12 @@ public function testFromDataCreatesAttachment(): void public function testStorageAttachmentResolvesDiskOnceAndOmitsFailedMimeDetection(): void { - $storage = m::mock(FilesystemAdapter::class); - $storage->shouldReceive('mimeType')->once()->with('report.txt')->andReturnFalse(); - $storage->shouldReceive('get')->once()->with('report.txt')->andReturn('file content'); + $storage = Double::for(FilesystemAdapter::class)->strict(); + $storage->expects('mimeType')->with('report.txt')->returns(false); + $storage->expects('get')->with('report.txt')->returns('file content'); - $factory = m::mock(FilesystemFactory::class); - $factory->shouldReceive('disk')->once()->with('documents')->andReturn($storage); + $factory = Double::for(FilesystemFactory::class)->strict(); + $factory->expects('disk')->with('documents')->returns($storage); $container = new Container; $container->instance(FilesystemFactory::class, $factory); @@ -188,12 +191,12 @@ public function testStorageAttachmentResolvesDiskOnceAndOmitsFailedMimeDetection public function testExplicitStorageAttachmentMimeSkipsDetection(): void { - $storage = m::mock(FilesystemAdapter::class); - $storage->shouldNotReceive('mimeType'); - $storage->shouldReceive('get')->once()->with('report.txt')->andReturn('file content'); + $storage = Double::for(FilesystemAdapter::class)->strict(); + $storage->expects('mimeType')->never(); + $storage->expects('get')->with('report.txt')->returns('file content'); - $factory = m::mock(FilesystemFactory::class); - $factory->shouldReceive('disk')->once()->with('documents')->andReturn($storage); + $factory = Double::for(FilesystemFactory::class)->strict(); + $factory->expects('disk')->with('documents')->returns($storage); $container = new Container; $container->instance(FilesystemFactory::class, $factory); diff --git a/tests/Mail/MailCloudflareTransportTest.php b/tests/Mail/MailCloudflareTransportTest.php index efad516d85..876cee4e01 100644 --- a/tests/Mail/MailCloudflareTransportTest.php +++ b/tests/Mail/MailCloudflareTransportTest.php @@ -9,7 +9,8 @@ use Hypervel\Mail\Transport\CloudflareTransport; use Hypervel\Support\ClassInvoker; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\HttpClient\Response\MockResponse; use Symfony\Component\Mailer\Exception\TransportException; @@ -18,10 +19,12 @@ class MailCloudflareTransportTest extends TestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); - $this->app->instance('view', m::mock(ViewFactory::class)); + $this->app->instance('view', Double::for(ViewFactory::class)->strict()); } public function testGetTransport(): void diff --git a/tests/Mail/MailMarkdownTest.php b/tests/Mail/MailMarkdownTest.php index 0acc8761e2..c55a8cb6d2 100644 --- a/tests/Mail/MailMarkdownTest.php +++ b/tests/Mail/MailMarkdownTest.php @@ -5,35 +5,43 @@ namespace Hypervel\Tests\Mail; use Closure; -use Hypervel\Contracts\View\Factory as ViewFactory; +use Hypervel\Container\Container; +use Hypervel\Contracts\View\Factory as ViewFactoryContract; use Hypervel\Contracts\View\View as ViewContract; +use Hypervel\Events\Dispatcher; +use Hypervel\Filesystem\Filesystem; use Hypervel\Mail\Markdown; use Hypervel\Tests\TestCase; use Hypervel\View\Compilers\BladeCompiler; +use Hypervel\View\Engines\CompilerEngine; use Hypervel\View\Engines\EngineResolver; -use Mockery as m; +use Hypervel\View\Factory as ViewFactory; +use Hypervel\View\FileViewFinder; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class MailMarkdownTest extends TestCase { + use VerifiesDoubles; + public function testRenderFunctionReturnsHtml(): void { - $viewInterface = m::mock(ViewContract::class); - $viewInterface->shouldReceive('render')->twice()->andReturn('', 'body {}'); - - $viewFactory = m::mock(ViewFactory::class); - $engineResolver = m::mock(EngineResolver::class); - $bladeCompiler = m::mock(BladeCompiler::class); - $viewFactory->shouldReceive('getEngineResolver')->andReturn($engineResolver); - $engineResolver->shouldReceive('resolve->getCompiler')->andReturn($bladeCompiler); - $bladeCompiler->shouldReceive('usingEchoFormat') - ->with('new \Hypervel\Support\EncodedHtmlString(%s)', m::type('Closure')) - ->andReturnUsing(fn (string $echoFormat, Closure $callback): mixed => $callback()); + $viewInterface = Double::for(ViewContract::class)->strict(); + $viewInterface->expects('render')->times(2)->returns('', 'body {}'); + + $bladeCompiler = Double::for(BladeCompiler::class)->strict(); + $viewFactory = $this->viewFactory($bladeCompiler); + $bladeCompiler->allows('usingEchoFormat') + ->with('new \Hypervel\Support\EncodedHtmlString(%s)', Argument::type('Closure')) + ->resolves(fn (string $echoFormat, Closure $callback): mixed => $callback()); $markdown = new Markdown($viewFactory); - $viewFactory->shouldReceive('replaceNamespace')->once()->with('mail', $markdown->htmlComponentPaths())->andReturnSelf(); - $viewFactory->shouldReceive('exists')->with('mail.default')->andReturn(false); - $viewFactory->shouldReceive('make')->with('view', [])->andReturn($viewInterface); - $viewFactory->shouldReceive('make')->with('mail::themes.default', [])->andReturn($viewInterface); + $viewFactory->expects('replaceNamespace')->with('mail', $markdown->htmlComponentPaths()); + $viewFactory->allows('exists')->with('mail.default')->returns(false); + $viewFactory->allows('make')->with('view', [])->returns($viewInterface); + $viewFactory->allows('make')->with('mail::themes.default', [])->returns($viewInterface); $result = $markdown->render('view', [])->toHtml(); @@ -42,24 +50,21 @@ public function testRenderFunctionReturnsHtml(): void public function testRenderFunctionReturnsHtmlWithCustomTheme(): void { - $viewInterface = m::mock(ViewContract::class); - $viewInterface->shouldReceive('render')->twice()->andReturn('', 'body {}'); - - $viewFactory = m::mock(ViewFactory::class); - $engineResolver = m::mock(EngineResolver::class); - $bladeCompiler = m::mock(BladeCompiler::class); - $viewFactory->shouldReceive('getEngineResolver')->andReturn($engineResolver); - $engineResolver->shouldReceive('resolve->getCompiler')->andReturn($bladeCompiler); - $bladeCompiler->shouldReceive('usingEchoFormat') - ->with('new \Hypervel\Support\EncodedHtmlString(%s)', m::type('Closure')) - ->andReturnUsing(fn (string $echoFormat, Closure $callback): mixed => $callback()); + $viewInterface = Double::for(ViewContract::class)->strict(); + $viewInterface->expects('render')->times(2)->returns('', 'body {}'); + + $bladeCompiler = Double::for(BladeCompiler::class)->strict(); + $viewFactory = $this->viewFactory($bladeCompiler); + $bladeCompiler->allows('usingEchoFormat') + ->with('new \Hypervel\Support\EncodedHtmlString(%s)', Argument::type('Closure')) + ->resolves(fn (string $echoFormat, Closure $callback): mixed => $callback()); $markdown = new Markdown($viewFactory); $markdown->theme('yaz'); - $viewFactory->shouldReceive('replaceNamespace')->once()->with('mail', $markdown->htmlComponentPaths())->andReturnSelf(); - $viewFactory->shouldReceive('exists')->with('mail.yaz')->andReturn(true); - $viewFactory->shouldReceive('make')->with('view', [])->andReturn($viewInterface); - $viewFactory->shouldReceive('make')->with('mail.yaz', [])->andReturn($viewInterface); + $viewFactory->expects('replaceNamespace')->with('mail', $markdown->htmlComponentPaths()); + $viewFactory->allows('exists')->with('mail.yaz')->returns(true); + $viewFactory->allows('make')->with('view', [])->returns($viewInterface); + $viewFactory->allows('make')->with('mail.yaz', [])->returns($viewInterface); $result = $markdown->render('view', [])->toHtml(); @@ -68,24 +73,21 @@ public function testRenderFunctionReturnsHtmlWithCustomTheme(): void public function testRenderFunctionReturnsHtmlWithCustomThemeWithMailPrefix(): void { - $viewInterface = m::mock(ViewContract::class); - $viewInterface->shouldReceive('render')->twice()->andReturn('', 'body {}'); - - $viewFactory = m::mock(ViewFactory::class); - $engineResolver = m::mock(EngineResolver::class); - $bladeCompiler = m::mock(BladeCompiler::class); - $viewFactory->shouldReceive('getEngineResolver')->andReturn($engineResolver); - $engineResolver->shouldReceive('resolve->getCompiler')->andReturn($bladeCompiler); - $bladeCompiler->shouldReceive('usingEchoFormat') - ->with('new \Hypervel\Support\EncodedHtmlString(%s)', m::type('Closure')) - ->andReturnUsing(fn (string $echoFormat, Closure $callback): mixed => $callback()); + $viewInterface = Double::for(ViewContract::class)->strict(); + $viewInterface->expects('render')->times(2)->returns('', 'body {}'); + + $bladeCompiler = Double::for(BladeCompiler::class)->strict(); + $viewFactory = $this->viewFactory($bladeCompiler); + $bladeCompiler->allows('usingEchoFormat') + ->with('new \Hypervel\Support\EncodedHtmlString(%s)', Argument::type('Closure')) + ->resolves(fn (string $echoFormat, Closure $callback): mixed => $callback()); $markdown = new Markdown($viewFactory); $markdown->theme('mail.yaz'); - $viewFactory->shouldReceive('replaceNamespace')->once()->with('mail', $markdown->htmlComponentPaths())->andReturnSelf(); - $viewFactory->shouldReceive('exists')->with('mail.yaz')->andReturn(true); - $viewFactory->shouldReceive('make')->with('view', [])->andReturn($viewInterface); - $viewFactory->shouldReceive('make')->with('mail.yaz', [])->andReturn($viewInterface); + $viewFactory->expects('replaceNamespace')->with('mail', $markdown->htmlComponentPaths()); + $viewFactory->allows('exists')->with('mail.yaz')->returns(true); + $viewFactory->allows('make')->with('view', [])->returns($viewInterface); + $viewFactory->allows('make')->with('mail.yaz', [])->returns($viewInterface); $result = $markdown->render('view', [])->toHtml(); @@ -94,13 +96,13 @@ public function testRenderFunctionReturnsHtmlWithCustomThemeWithMailPrefix(): vo public function testRenderTextReturnsText(): void { - $viewInterface = m::mock(ViewContract::class); - $viewInterface->shouldReceive('render')->andReturn('text'); + $viewInterface = Double::for(ViewContract::class)->strict(); + $viewInterface->allows('render')->returns('text'); - $viewFactory = m::mock(ViewFactory::class); + $viewFactory = Double::for(ViewFactoryContract::class)->strict(); $markdown = new Markdown($viewFactory); - $viewFactory->shouldReceive('replaceNamespace')->once()->with('mail', $markdown->textComponentPaths())->andReturnSelf(); - $viewFactory->shouldReceive('make')->with('view', [])->andReturn($viewInterface); + $viewFactory->expects('replaceNamespace')->with('mail', $markdown->textComponentPaths()); + $viewFactory->allows('make')->with('view', [])->returns($viewInterface); $result = $markdown->renderText('view', [])->toHtml(); @@ -113,4 +115,19 @@ public function testParseReturnsParsedMarkdown(): void $this->assertSame("

Something

\n", $result); } + + /** + * Create a view factory whose render-local clones retain real finder and engine state. + */ + private function viewFactory(BladeCompiler $bladeCompiler): ViewFactory&DoubleInterface + { + $engines = new EngineResolver; + $engines->register('blade', fn (): CompilerEngine => new CompilerEngine($bladeCompiler)); + + return Double::for(new ViewFactory( + $engines, + new FileViewFinder(new Filesystem, []), + new Dispatcher(new Container), + ))->passthru(); + } } diff --git a/tests/Mail/MarkdownCoroutineSafetyTest.php b/tests/Mail/MarkdownCoroutineSafetyTest.php index 25acbd360a..cfedde91d7 100644 --- a/tests/Mail/MarkdownCoroutineSafetyTest.php +++ b/tests/Mail/MarkdownCoroutineSafetyTest.php @@ -29,12 +29,15 @@ use Hypervel\View\Engines\PhpEngine; use Hypervel\View\Factory as ViewFactory; use Hypervel\View\FileViewFinder; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use function Hypervel\Coroutine\parallel; class MarkdownCoroutineSafetyTest extends TestCase { + use VerifiesDoubles; + protected Filesystem $filesystem; protected string $tempDir; @@ -205,7 +208,7 @@ public function testMailMessageRenderUsesThemeWithoutMutatingMarkdownSingleton() public function testMailChannelUsesNotificationThemeWithoutMutatingMarkdownSingleton(): void { $markdown = $this->swapThemeProbeMarkdownIntoContainer(); - $channel = new ThemeProbeMailChannel(m::mock(MailFactory::class), $markdown); + $channel = new ThemeProbeMailChannel(Double::for(MailFactory::class)->strict(), $markdown); $message = (new NotificationMailMessage)->theme('theme-a'); $this->assertSame('theme-a:theme-a', $channel->renderHtml($message)); @@ -255,11 +258,11 @@ protected function makeRealViewFactory(): ViewFactory $container = new Container; $filesystem = $this->filesystem; $resolver = new EngineResolver; - $application = m::mock(ApplicationContract::class); + $application = Double::for(ApplicationContract::class, override: true)->strict(); $compiledPath = $this->tempDir . '/views'; $bladeCompiler = new BladeCompiler($filesystem, $compiledPath, shouldCache: false); - $application->shouldReceive('getNamespace')->andReturn('App\\'); + $application->allows('getNamespace')->returns('App\\'); $filesystem->ensureDirectoryExists($compiledPath); $resolver->register('blade', fn () => new CompilerEngine($bladeCompiler, $filesystem)); @@ -273,7 +276,7 @@ protected function makeRealViewFactory(): ViewFactory ); $factory->setContainer($container); - $container->instance(ApplicationContract::class, $application); + $container->instance(ApplicationContract::class, $application->instance()); $container->instance(ViewFactory::class, $factory); $container->instance(ViewFactoryContract::class, $factory); Container::setInstance($container); diff --git a/tests/Mcp/Unit/Client/Transport/StdioTransportTest.php b/tests/Mcp/Unit/Client/Transport/StdioTransportTest.php index ea0e6f5568..ecb746b0f9 100644 --- a/tests/Mcp/Unit/Client/Transport/StdioTransportTest.php +++ b/tests/Mcp/Unit/Client/Transport/StdioTransportTest.php @@ -15,7 +15,8 @@ use Hypervel\Mcp\Schema\Implementation; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -26,6 +27,8 @@ class StdioTransportTest extends TestCase { + use VerifiesDoubles; + protected string $directory; /** @@ -232,19 +235,21 @@ public function testDisconnectDetachesOwnedStateBeforePropagatingCancellation(bo $cancellation = $wrapped ? new RuntimeException('Stop cleanup failed.', previous: new CanceledException) : new CanceledException('Stop canceled.'); - $process = m::mock(Process::class); + $process = Double::for(Process::class)->strict(); + // Symfony's destructor calls stop(0) when the double is released. + $process->allows('stop')->with(0.0)->returns(0); if ($receive) { - $process->shouldReceive('getLastOutputTime')->once()->andReturn(microtime(true)); - $process->shouldReceive('setIdleTimeout')->once()->andReturnSelf(); - $process->shouldReceive('getIterator')->once()->andReturnUsing(static function (): Generator { + $process->expects('getLastOutputTime')->returns(microtime(true)); + $process->expects('setIdleTimeout'); + $process->expects('getIterator')->resolves(static function (): Generator { yield from []; }); } - $process->shouldReceive('isRunning')->once()->andReturnTrue(); - $process->shouldReceive('stop')->once()->with(0.1, null)->ordered()->andThrow($cancellation); - $process->shouldReceive('stop')->once()->with(0, null)->ordered()->andReturn(0); + $process->expects('isRunning')->returns(true); + $process->expects('stop')->with(0.1, null)->ordered()->throws($cancellation); + $process->expects('stop')->with(0.0, null)->ordered()->returns(0); $input = new StdioInput; $transport = new InspectableStdioTransport('silent'); $transport->installProcess($process, $input); diff --git a/tests/Mcp/Unit/Console/Commands/McpInspectorCommandTest.php b/tests/Mcp/Unit/Console/Commands/McpInspectorCommandTest.php index b19e95098b..f663d36c93 100644 --- a/tests/Mcp/Unit/Console/Commands/McpInspectorCommandTest.php +++ b/tests/Mcp/Unit/Console/Commands/McpInspectorCommandTest.php @@ -15,8 +15,10 @@ use Hypervel\Support\Facades\URL; use Hypervel\Tests\Mcp\Fixtures\ExampleServer; use Hypervel\Tests\Mcp\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionClass; use ReflectionMethod; use ReflectionProperty; @@ -29,7 +31,9 @@ class McpInspectorCommandTest extends TestCase { - private Registrar&MockInterface $registrar; + use VerifiesDoubles; + + private Registrar&DoubleInterface $registrar; /** * Start with an empty MCP registry. @@ -39,7 +43,7 @@ protected function setUp(): void parent::setUp(); Mcp::swap(new Registrar); - $this->registrar = m::mock(Registrar::class); + $this->registrar = Double::for(Registrar::class)->strict(); } public function testNormalizesMixedPathsCorrectly(): void @@ -96,11 +100,11 @@ public function testHandlesSingleServerWithUnknownType(): void $this->app->instance(Registrar::class, $this->registrar); - $this->registrar->shouldReceive('getLocalServer')->once()->with('demo')->andReturn(null); + $this->registrar->expects('getLocalServer')->with('demo')->returns(null); - $this->registrar->shouldReceive('getWebServer')->once()->with('demo')->andReturn(null); + $this->registrar->expects('getWebServer')->with('demo')->returns(null); - $this->registrar->shouldReceive('servers')->once()->andReturn(['single' => $unknownServer]); + $this->registrar->expects('servers')->returns(['single' => $unknownServer]); $this->artisan('mcp:inspector', ['handle' => 'demo']) ->expectsOutputToContain('MCP Server with name [demo] not found') @@ -124,10 +128,10 @@ public function testAsksForRouteParameterValuesWhenBuildingTheServerUrl(): void { $route = (new Registrar)->web('mcp/{organisation:uuid}', ExampleServer::class); - $output = m::mock(OutputStyle::class, [new ArrayInput([]), new BufferedOutput])->makePartial(); - $output->shouldReceive('askQuestion')->once() - ->with(m::on(fn (Question $question): bool => $question->getQuestion() === 'What is the value for the [organisation] route parameter?')) - ->andReturn('4f8a1c2e'); + $output = Double::for(new OutputStyle(new ArrayInput([]), new BufferedOutput))->passthru(); + $output->expects('askQuestion') + ->with(Argument::satisfies(fn (Question $question): bool => $question->getQuestion() === 'What is the value for the [organisation] route parameter?')) + ->returns('4f8a1c2e'); $components = new Factory($output); diff --git a/tests/Mcp/Unit/Console/Commands/StartCommandTest.php b/tests/Mcp/Unit/Console/Commands/StartCommandTest.php index aba5795b69..fc94b17402 100644 --- a/tests/Mcp/Unit/Console/Commands/StartCommandTest.php +++ b/tests/Mcp/Unit/Console/Commands/StartCommandTest.php @@ -6,13 +6,16 @@ use Hypervel\Mcp\Server\Registrar; use Hypervel\Tests\Mcp\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class StartCommandTest extends TestCase { - private Registrar&MockInterface $registrar; + use VerifiesDoubles; + + private Registrar&DoubleInterface $registrar; /** * Bind the local server registry double. @@ -20,7 +23,7 @@ class StartCommandTest extends TestCase protected function setUp(): void { parent::setUp(); - $this->registrar = m::mock(Registrar::class); + $this->registrar = Double::for(Registrar::class)->strict(); $this->app->instance(Registrar::class, $this->registrar); } @@ -31,7 +34,7 @@ public function testStartsARegisteredLocalServerSuccessfully(): void $serverCalled = true; }; - $this->registrar->shouldReceive('getLocalServer')->once()->with('demo')->andReturn($server); + $this->registrar->expects('getLocalServer')->with('demo')->returns($server); $this->artisan('mcp:start', ['handle' => 'demo']) ->assertExitCode(0); @@ -41,7 +44,7 @@ public function testStartsARegisteredLocalServerSuccessfully(): void public function testFailsWhenServerHandleIsNotFound(): void { - $this->registrar->shouldReceive('getLocalServer')->once()->with('invalid')->andReturn(null); + $this->registrar->expects('getLocalServer')->with('invalid')->returns(null); $this->artisan('mcp:start', ['handle' => 'invalid']) ->expectsOutputToContain('MCP Server with name [invalid] not found. Did you register it using [Mcp::local()]?') @@ -59,7 +62,7 @@ public function testAcceptsAStringHandle(): void { $server = function (): void {}; - $this->registrar->shouldReceive('getLocalServer')->once()->with('test-handle')->andReturn($server); + $this->registrar->expects('getLocalServer')->with('test-handle')->returns($server); $this->artisan('mcp:start', ['handle' => 'test-handle']) ->assertExitCode(0); diff --git a/tests/Mcp/Unit/Server/RegistrarTest.php b/tests/Mcp/Unit/Server/RegistrarTest.php index 649b4397d0..ed718d652c 100644 --- a/tests/Mcp/Unit/Server/RegistrarTest.php +++ b/tests/Mcp/Unit/Server/RegistrarTest.php @@ -31,7 +31,8 @@ use Hypervel\Tests\Mcp\Fixtures\PassportClient; use Hypervel\Tests\Mcp\Fixtures\PassportClientRepository; use Hypervel\Tests\Mcp\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use Swoole\Coroutine\CanceledException; @@ -39,6 +40,8 @@ class RegistrarTest extends TestCase { + use VerifiesDoubles; + /** * Load Passport's registration limiter and client services. */ @@ -314,8 +317,8 @@ public function testAuthorizationMetadataIsUnavailableWithoutPassportRoutes(): v { Route::setRoutes(new RouteCollection); config(['mcp.authorization_server' => 'https://auth.example.com']); - $servers = m::mock(ServerFactory::class); - $servers->shouldNotReceive('settings'); + $servers = Double::for(ServerFactory::class)->strict(); + $servers->expects('settings')->never(); $this->app->instance(ServerFactory::class, $servers); (new Registrar)->oauthRoutes(registration: false); @@ -423,8 +426,8 @@ public function testRegistrationHonorsTheApplicationPassportRateLimit(): void public function testRegistrationCancellationIsNotConvertedToAServerError(): void { $exception = new CanceledException('Registration canceled.'); - $repository = m::mock(ClientRepository::class); - $repository->shouldReceive('createAuthorizationCodeGrantClient')->once()->andThrow($exception); + $repository = Double::for(ClientRepository::class)->strict(); + $repository->expects('createAuthorizationCodeGrantClient')->throws($exception); $this->app->instance(ClientRepository::class, $repository); try { diff --git a/tests/NestedSet/NestedSetTest.php b/tests/NestedSet/NestedSetTest.php index f5f7af23e0..3559e61fa5 100644 --- a/tests/NestedSet/NestedSetTest.php +++ b/tests/NestedSet/NestedSetTest.php @@ -17,19 +17,22 @@ use Hypervel\NestedSet\NestedSet; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use stdClass; use Stringable; class NestedSetTest extends TestCase { + use VerifiesDoubles; + public function testStructuralIdentityUsesTheNormalizedConnectionNameAndTableWithoutResolving(): void { - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('getDefaultConnection')->andReturn('primary::write'); - $resolver->shouldNotReceive('connection'); + $resolver = Double::for(ConnectionResolverInterface::class)->strict(); + $resolver->allows('getDefaultConnection')->returns('primary::write'); + $resolver->expects('connection')->never(); Model::setConnectionResolver($resolver); @@ -67,8 +70,8 @@ public function testStructuralIdentityUsesTheNormalizedConnectionNameAndTableWit public function testStructuralIdentityFallsBackToTheResolversDefaultConnection(): void { - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('getDefaultConnection')->andReturn('primary'); + $resolver = Double::for(ConnectionResolverInterface::class)->strict(); + $resolver->allows('getDefaultConnection')->returns('primary'); Model::setConnectionResolver($resolver); @@ -82,8 +85,8 @@ public function testStructuralIdentityFallsBackToTheResolversDefaultConnection() public function testStructuralIdentityUsesAStableMarkerWithoutAnyConnectionName(): void { - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('getDefaultConnection')->andReturn(null); + $resolver = Double::for(ConnectionResolverInterface::class)->strict(); + $resolver->allows('getDefaultConnection')->returns(null); Model::setConnectionResolver($resolver); @@ -106,7 +109,7 @@ public function testIsNodeReturnsTrueForModelUsingHasNodeThroughAnotherTrait(): public function testNodeUsesNestedSetBuilderByDefault(): void { $builder = (new NestedSetTestNodeModel) - ->newEloquentBuilder(m::mock(BaseQueryBuilder::class)); + ->newEloquentBuilder(Double::for(BaseQueryBuilder::class)->strict()); $this->assertInstanceOf(QueryBuilder::class, $builder); } @@ -118,7 +121,7 @@ public function testNodeUsesNestedSetBuilderByDefault(): void #[DataProvider('compatibleBuilderModels')] public function testNodeUsesCompatibleCustomBuilder(string $model, string $builder): void { - $instance = (new $model)->newEloquentBuilder(m::mock(BaseQueryBuilder::class)); + $instance = (new $model)->newEloquentBuilder(Double::for(BaseQueryBuilder::class)->strict()); $this->assertSame($builder, $instance::class); } @@ -150,7 +153,7 @@ public function testNodeRejectsIncompatibleCustomBuilder(string $model): void QueryBuilder::class, )); - (new $model)->newEloquentBuilder(m::mock(BaseQueryBuilder::class)); + (new $model)->newEloquentBuilder(Double::for(BaseQueryBuilder::class)->strict()); } /** @@ -187,12 +190,12 @@ public function testIsNodeReturnsFalseForArbitraryObject(): void public function testScopeValuesAreNormalizedForSqlAndBucketIdentity(): void { // Dates use the connection grammar's own format, which a custom grammar may change. - $grammar = m::mock(QueryGrammar::class); - $grammar->shouldReceive('getDateFormat')->andReturn('d/m/Y H:i:s'); - $connection = m::mock(Connection::class); - $connection->shouldReceive('getQueryGrammar')->andReturn($grammar); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->andReturn($connection); + $grammar = Double::for(QueryGrammar::class)->strict(); + $grammar->allows('getDateFormat')->returns('d/m/Y H:i:s'); + $connection = Double::for(Connection::class)->strict(); + $connection->allows('getQueryGrammar')->returns($grammar); + $resolver = Double::for(ConnectionResolverInterface::class)->strict(); + $resolver->allows('connection')->returns($connection); Model::setConnectionResolver($resolver); $model = new NestedSetTestScopeNodeModel; diff --git a/tests/Notifications/CoroutineIsolationTest.php b/tests/Notifications/CoroutineIsolationTest.php index 5d5b8d0ba6..c8105849c3 100644 --- a/tests/Notifications/CoroutineIsolationTest.php +++ b/tests/Notifications/CoroutineIsolationTest.php @@ -14,12 +14,15 @@ use Hypervel\Tests\TestCase; use Hypervel\Translation\ArrayLoader; use Hypervel\Translation\Translator; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use function Hypervel\Coroutine\parallel; class CoroutineIsolationTest extends TestCase { + use VerifiesDoubles; + public function testManagerOverridesAreIsolatedBetweenCoroutines(): void { $application = new Application; @@ -60,7 +63,7 @@ public function testConcurrentSendsConsumeOnlyTheirOwnLocaleOverride(): void { $application = new Application; $application->instance('config', new ConfigRepository([])); - $application->instance(BusDispatcher::class, m::mock(BusDispatcher::class)); + $application->instance(BusDispatcher::class, Double::for(BusDispatcher::class)->strict()); $translator = new Translator(new ArrayLoader, 'en'); $application->instance('translator', $translator); $manager = new ChannelManager($application); diff --git a/tests/Notifications/NotificationMailChannelTest.php b/tests/Notifications/NotificationMailChannelTest.php index 108e55f1fc..8145e3447f 100644 --- a/tests/Notifications/NotificationMailChannelTest.php +++ b/tests/Notifications/NotificationMailChannelTest.php @@ -12,18 +12,21 @@ use Hypervel\Notifications\Notification; use Hypervel\Support\ClassInvoker; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Mailer\Header\MetadataHeader; use Symfony\Component\Mailer\Header\TagHeader; use Symfony\Component\Mime\Email; class NotificationMailChannelTest extends TestCase { + use VerifiesDoubles; + public function testBuildMessageAddsTagsAndStringifiesMetadata(): void { $channel = new MailChannel( - m::mock(MailFactory::class), - m::mock(Markdown::class), + Double::for(MailFactory::class)->strict(), + Double::for(Markdown::class)->strict(), ); $message = new Email; $notifiable = new class { diff --git a/tests/ObjectPool/LeaseTest.php b/tests/ObjectPool/LeaseTest.php index d313560cd5..072d587772 100644 --- a/tests/ObjectPool/LeaseTest.php +++ b/tests/ObjectPool/LeaseTest.php @@ -12,7 +12,8 @@ use Hypervel\ObjectPool\Lease; use Hypervel\ObjectPool\PoolOptions; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use stdClass; @@ -21,6 +22,8 @@ class LeaseTest extends TestCase { + use VerifiesDoubles; + /** @var list */ private array $pools = []; @@ -109,8 +112,8 @@ public function testDiscardFailureDoesNotMaskAReleaseCallbackFailure(): void $container = $this->container(); $callbackFailure = new RuntimeException('reset failed'); $discardFailure = new RuntimeException('discard failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($discardFailure); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($discardFailure); $container->instance(ExceptionHandler::class, $handler); $pool = new ContractOnlyObjectPool; @@ -152,9 +155,9 @@ public function testReleaseCallbackPreservesCancellationPrecedence( if ($discardCleanupThrows) { $discardCancellation = new RuntimeException('discard cleanup failed', previous: $discardCancellation); } - $handler = m::mock(ExceptionHandler::class); - $expectation = $handler->shouldReceive('report')->with($discardCancellation); - $expectCallbackFailure && $discardCleanupThrows ? $expectation->once() : $expectation->never(); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($discardCancellation) + ->times($expectCallbackFailure && $discardCleanupThrows ? 1 : 0); $this->container()->instance(ExceptionHandler::class, $handler); $pool = new ContractOnlyObjectPool; @@ -222,8 +225,8 @@ public function testDestructorReportsAndSwallowsFinalizationFailures(): void { $container = $this->container(); $expected = new RuntimeException('reset failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($expected); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($expected); $container->instance(ExceptionHandler::class, $handler); $pool = $this->pool(); @@ -272,9 +275,9 @@ public function testFailureFinalizersPreserveCancellationPrecedence( if ($cleanupThrowsAgain) { $cleanup = new RuntimeException('finalizer cleanup failed', previous: $cleanup); } - $handler = m::mock(ExceptionHandler::class); - $expectation = $handler->shouldReceive('report')->with($cleanup); - $expectPrimary && ! $cleanup instanceof CanceledException ? $expectation->once() : $expectation->never(); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($cleanup) + ->times($expectPrimary && ! $cleanup instanceof CanceledException ? 1 : 0); $container->instance(ExceptionHandler::class, $handler); $pool = new ContractOnlyObjectPool; diff --git a/tests/ObjectPool/ObjectPoolServiceProviderTest.php b/tests/ObjectPool/ObjectPoolServiceProviderTest.php index cb18a554d8..e51081f651 100644 --- a/tests/ObjectPool/ObjectPoolServiceProviderTest.php +++ b/tests/ObjectPool/ObjectPoolServiceProviderTest.php @@ -16,12 +16,15 @@ use Hypervel\ObjectPool\PoolOptions; use Hypervel\ObjectPool\PoolRecycler; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use stdClass; use Swoole\Server; class ObjectPoolServiceProviderTest extends TestCase { + use VerifiesDoubles; + protected function getPackageProviders($app): array { return [ObjectPoolServiceProvider::class]; @@ -75,25 +78,25 @@ public function testShippedPoolConfigurationMatchesNormalizedDefaults(): void public function testLifecyclePurgesResolvedMasterPoolsBeforeForkAndStartsTheWorkerRecycler(): void { $listeners = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('listen') - ->twice() - ->andReturnUsing(function (string $event, callable $listener) use (&$listeners): void { + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('listen') + ->times(2) + ->resolves(function (string $event, callable $listener) use (&$listeners): void { $listeners[$event] = $listener; }); - $manager = m::mock(PoolManager::class); - $manager->shouldReceive('purgeAll')->once(); - $recycler = m::mock(StartRecycler::class); - $server = m::mock(Server::class); + $manager = Double::for(PoolManager::class)->strict(); + $manager->expects('purgeAll'); + $recycler = Double::for(StartRecycler::class)->strict(); + $server = Double::for(Server::class)->strict(); $afterWorkerStart = new AfterWorkerStart($server, 0); - $recycler->shouldReceive('handle')->once()->with($afterWorkerStart); - $application = m::mock(Application::class); - $application->shouldReceive('make')->once()->with('events')->andReturn($events); - $application->shouldReceive('resolved')->once()->with(PoolManager::class)->andReturnTrue(); - $application->shouldReceive('make')->once()->with(PoolManager::class)->andReturn($manager); - $application->shouldReceive('make')->once()->with(StartRecycler::class)->andReturn($recycler); + $recycler->expects('handle')->with($afterWorkerStart); + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('make')->with('events')->returns($events); + $application->expects('resolved')->with(PoolManager::class)->returns(true); + $application->expects('make')->with(PoolManager::class)->returns($manager); + $application->expects('make')->with(StartRecycler::class)->returns($recycler); - (new ObjectPoolServiceProvider($application))->boot(); + (new ObjectPoolServiceProvider($application->instance()))->boot(); $listeners[BeforeServerFork::class](new BeforeServerFork($server)); $listeners[AfterWorkerStart::class]($afterWorkerStart); @@ -102,18 +105,18 @@ public function testLifecyclePurgesResolvedMasterPoolsBeforeForkAndStartsTheWork public function testBeforeForkDoesNotResolveAnUnusedPoolManager(): void { $listeners = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('listen') - ->twice() - ->andReturnUsing(function (string $event, callable $listener) use (&$listeners): void { + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('listen') + ->times(2) + ->resolves(function (string $event, callable $listener) use (&$listeners): void { $listeners[$event] = $listener; }); - $application = m::mock(Application::class); - $application->shouldReceive('make')->once()->with('events')->andReturn($events); - $application->shouldReceive('resolved')->once()->with(PoolManager::class)->andReturnFalse(); + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('make')->with('events')->returns($events); + $application->expects('resolved')->with(PoolManager::class)->returns(false); - (new ObjectPoolServiceProvider($application))->boot(); + (new ObjectPoolServiceProvider($application->instance()))->boot(); - $listeners[BeforeServerFork::class](new BeforeServerFork(m::mock(Server::class))); + $listeners[BeforeServerFork::class](new BeforeServerFork(Double::for(Server::class)->strict())); } } diff --git a/tests/ObjectPool/ObjectPoolTest.php b/tests/ObjectPool/ObjectPoolTest.php index bb2b6e910f..d1b0af6683 100644 --- a/tests/ObjectPool/ObjectPoolTest.php +++ b/tests/ObjectPool/ObjectPoolTest.php @@ -16,7 +16,8 @@ use Hypervel\ObjectPool\ObjectPool; use Hypervel\ObjectPool\PoolOptions; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -28,6 +29,8 @@ class ObjectPoolTest extends TestCase { + use VerifiesDoubles; + public function testCloseDrainsIdleObjectsAndIsIdempotent(): void { $destroyed = []; @@ -66,8 +69,8 @@ public function testCloseDrainsEveryIdleObjectBeforeRethrowingTheFirstCancellati if ($secondCleanupThrows) { $secondCancellation = new RuntimeException('Second cleanup failed.', previous: $secondCancellation); } - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->with($secondCancellation)->times($secondCleanupThrows ? 1 : 0); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($secondCancellation)->times($secondCleanupThrows ? 1 : 0); $this->container()->instance(ExceptionHandler::class, $handler); $destroyed = []; $pool = $this->pool( @@ -745,8 +748,8 @@ public function testDestroyCallbackFailuresAreReportedWithoutLeavingManagedGhost { $container = $this->container(); $failure = new RuntimeException('destroy failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->twice()->with($failure); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->times(2)->with($failure); $container->instance(ExceptionHandler::class, $handler); $pool = new InspectableObjectPool( PoolOptions::fromArray(['max_objects' => 2]), @@ -777,8 +780,8 @@ public function testDestroyCancellationEscapesAfterReleasingPoolCapacity(bool $c if ($cleanupThrows) { $cancellation = new RuntimeException('Destroy cleanup failed.', previous: $cancellation); } - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); $this->container()->instance(ExceptionHandler::class, $handler); $pool = $this->pool( destroyCallback: static function () use ($cancellation): never { diff --git a/tests/ObjectPool/PoolErrorReporterTest.php b/tests/ObjectPool/PoolErrorReporterTest.php index fe34c3fdf1..c9b5b376cf 100644 --- a/tests/ObjectPool/PoolErrorReporterTest.php +++ b/tests/ObjectPool/PoolErrorReporterTest.php @@ -8,11 +8,14 @@ use Hypervel\Contracts\Debug\ExceptionHandler; use Hypervel\ObjectPool\PoolErrorReporter; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class PoolErrorReporterTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; public function testReportsThroughTheSupportFailureReporter(): void @@ -20,8 +23,8 @@ public function testReportsThroughTheSupportFailureReporter(): void $container = new Container; Container::setInstance($container); $exception = new RuntimeException('reported through handler'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($exception); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($exception); $container->instance(ExceptionHandler::class, $handler); PoolErrorReporter::report($exception); diff --git a/tests/ObjectPool/PoolManagerTest.php b/tests/ObjectPool/PoolManagerTest.php index 2da995fd86..b87c2bb470 100644 --- a/tests/ObjectPool/PoolManagerTest.php +++ b/tests/ObjectPool/PoolManagerTest.php @@ -11,7 +11,8 @@ use Hypervel\ObjectPool\PoolOptions; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionProperty; use RuntimeException; @@ -23,6 +24,8 @@ class PoolManagerTest extends TestCase { + use VerifiesDoubles; + protected PoolManager $manager; protected function setUp(): void @@ -309,8 +312,8 @@ public function testPurgeAllAttemptsEveryDetachedPoolAndPreservesFailurePriority foreach ([$firstFailure, $secondFailure, null] as $index => $failure) { $identity = 'pool:' . $index; - $pool = m::mock(ObjectPool::class); - $pool->shouldReceive('close')->once()->andReturnUsing(function () use ( + $pool = Double::for(ObjectPool::class)->strict(); + $pool->expects('close')->resolves(function () use ( $identity, $failure, &$observedRegistries, @@ -357,8 +360,8 @@ public static function closeFailures(): array public function testPurgeAllPreservesPoolsRegisteredDuringDetachedCleanup(): void { $replacement = null; - $pool = m::mock(ObjectPool::class); - $pool->shouldReceive('close')->once()->andReturnUsing(function () use (&$replacement): void { + $pool = Double::for(ObjectPool::class)->strict(); + $pool->expects('close')->resolves(function () use (&$replacement): void { $replacement = $this->manager->pool('reports', static fn () => new stdClass); }); (new ReflectionProperty(PoolManager::class, 'pools'))->setValue($this->manager, ['reports' => $pool]); diff --git a/tests/ObjectPool/PoolProxyTest.php b/tests/ObjectPool/PoolProxyTest.php index 03bd595115..e29887c4e6 100644 --- a/tests/ObjectPool/PoolProxyTest.php +++ b/tests/ObjectPool/PoolProxyTest.php @@ -16,11 +16,14 @@ use Hypervel\ObjectPool\PoolOptions; use Hypervel\ObjectPool\PoolProxy; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class PoolProxyTest extends TestCase { + use VerifiesDoubles; + protected Container $container; protected PoolManager $manager; @@ -122,15 +125,15 @@ public function testDiscardFailureDoesNotMaskAConfigureFailure(): void $object = new PoolProxyObject; $configureFailure = new RuntimeException('configuration failed'); $discardFailure = new RuntimeException('discard failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($discardFailure); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($discardFailure); $this->container->instance(ExceptionHandler::class, $handler); - $pool = m::mock(ObjectPoolContract::class); - $pool->shouldReceive('borrow')->once()->andReturn($object); - $pool->shouldReceive('discard')->once()->with($object)->andThrow($discardFailure); - $factory = m::mock(Factory::class); - $factory->shouldReceive('getOrCreate')->once()->andReturn($pool); + $pool = Double::for(ObjectPoolContract::class)->strict(); + $pool->expects('borrow')->returns($object); + $pool->expects('discard')->with($object)->throws($discardFailure); + $factory = Double::for(Factory::class)->strict(); + $factory->expects('getOrCreate')->returns($pool); $proxy = new InspectablePoolProxy( $this->definition, static fn (): object => $object, @@ -152,8 +155,8 @@ public function testOperationFailureRemainsPrimaryWhenFinalizationAlsoFails(): v { $operationFailure = new RuntimeException('operation failed'); $finalizationFailure = new RuntimeException('release failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($finalizationFailure); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($finalizationFailure); $this->container->instance(ExceptionHandler::class, $handler); $proxy = $this->proxy( static fn (): object => new PoolProxyObject($operationFailure), diff --git a/tests/ObjectPool/PoolRecyclerTest.php b/tests/ObjectPool/PoolRecyclerTest.php index 448d678508..6f0215b564 100644 --- a/tests/ObjectPool/PoolRecyclerTest.php +++ b/tests/ObjectPool/PoolRecyclerTest.php @@ -16,7 +16,9 @@ use Hypervel\ObjectPool\PoolRecycler; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use stdClass; @@ -24,6 +26,8 @@ class PoolRecyclerTest extends TestCase { + use VerifiesDoubles; + /** @var list */ private array $poolManagers = []; @@ -36,11 +40,11 @@ protected function tearDownInCoroutine(): void public function testIdlePoolIsEvictedByIdentityAndExactInstance(): void { - $pool = m::mock(ObjectPool::class); - $pool->shouldReceive('isIdleExpired')->once()->andReturnTrue(); - $manager = m::mock(Factory::class); - $manager->shouldReceive('getPools')->once()->andReturn(['idle' => $pool]); - $manager->shouldReceive('purge')->once()->with('idle', $pool)->andReturnTrue(); + $pool = Double::for(ObjectPool::class)->strict(); + $pool->expects('isIdleExpired')->returns(true); + $manager = Double::for(Factory::class)->strict(); + $manager->expects('getPools')->returns(['idle' => $pool]); + $manager->expects('purge')->with('idle', $pool)->returns(true); (new InspectablePoolRecycler($manager))->maintain(); } @@ -50,14 +54,13 @@ public function testReplacementPoolSurvivesAStaleEvictionSnapshot(): void $manager = $this->poolManager(); $definition = $this->definition('shared'); $replacement = $manager->getOrCreate($definition, static fn (): object => new stdClass); - $stale = m::mock(ObjectPool::class); - $stale->shouldReceive('isIdleExpired')->once()->andReturnTrue(); - $snapshotManager = m::mock(Factory::class); - $snapshotManager->shouldReceive('getPools')->once()->andReturn(['shared' => $stale]); - $snapshotManager->shouldReceive('purge') - ->once() + $stale = Double::for(ObjectPool::class)->strict(); + $stale->expects('isIdleExpired')->returns(true); + $snapshotManager = Double::for(Factory::class)->strict(); + $snapshotManager->expects('getPools')->returns(['shared' => $stale]); + $snapshotManager->expects('purge') ->with('shared', $stale) - ->andReturnUsing(fn (): bool => $manager->purge('shared', $stale)); + ->resolves(fn (): bool => $manager->purge('shared', $stale)); (new InspectablePoolRecycler($snapshotManager))->maintain(); @@ -129,12 +132,12 @@ public function testParkedWaiterAndBorrowedObjectPreventIdleEviction(): void public function testNonIdlePoolsAreSweptAndTrimmed(): void { - $pool = m::mock(ObjectPool::class); - $pool->shouldReceive('isIdleExpired')->once()->andReturnFalse(); - $pool->shouldReceive('sweepExpired')->once()->ordered(); - $pool->shouldReceive('trimIdle')->once()->ordered(); - $manager = m::mock(Factory::class); - $manager->shouldReceive('getPools')->once()->andReturn(['active' => $pool]); + $pool = Double::for(ObjectPool::class)->strict(); + $pool->expects('isIdleExpired')->returns(false); + $pool->expects('sweepExpired')->ordered(); + $pool->expects('trimIdle')->ordered(); + $manager = Double::for(Factory::class)->strict(); + $manager->expects('getPools')->returns(['active' => $pool]); (new InspectablePoolRecycler($manager))->maintain(); } @@ -143,26 +146,25 @@ public function testPoolFailureIsReportedWithoutSkippingLaterPools(): void { $failure = new RuntimeException('sweep failed'); $reported = null; - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report') - ->once() - ->andReturnUsing(function (RuntimeException $exception) use (&$reported): void { + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report') + ->resolves(function (RuntimeException $exception) use (&$reported): void { $reported = $exception; }); $container = new Container; $container->instance(ExceptionHandler::class, $handler); Container::setInstance($container); - $failingPool = m::mock(ObjectPool::class); - $failingPool->shouldReceive('isIdleExpired')->once()->andReturnFalse(); - $failingPool->shouldReceive('sweepExpired')->once()->andThrow($failure); - $failingPool->shouldNotReceive('trimIdle'); - $healthyPool = m::mock(ObjectPool::class); - $healthyPool->shouldReceive('isIdleExpired')->once()->ordered()->andReturnFalse(); - $healthyPool->shouldReceive('sweepExpired')->once()->ordered(); - $healthyPool->shouldReceive('trimIdle')->once()->ordered(); - $manager = m::mock(Factory::class); - $manager->shouldReceive('getPools')->once()->andReturn([ + $failingPool = Double::for(ObjectPool::class)->strict(); + $failingPool->expects('isIdleExpired')->returns(false); + $failingPool->expects('sweepExpired')->throws($failure); + $failingPool->expects('trimIdle')->never(); + $healthyPool = Double::for(ObjectPool::class)->strict(); + $healthyPool->expects('isIdleExpired')->ordered()->returns(false); + $healthyPool->expects('sweepExpired')->ordered(); + $healthyPool->expects('trimIdle')->ordered(); + $manager = Double::for(Factory::class)->strict(); + $manager->expects('getPools')->returns([ 'failing' => $failingPool, 'healthy' => $healthyPool, ]); @@ -176,14 +178,14 @@ public function testPoolFailureIsReportedWithoutSkippingLaterPools(): void public function testStartIsIdempotentAndStopClearsTheTimer(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('tick') - ->twice() - ->with(1.0, m::type('Closure')) - ->andReturn(99, 100); - $timer->shouldReceive('clear')->once()->with(99); - $timer->shouldReceive('clear')->once()->with(100); - $recycler = new PoolRecycler(m::mock(Factory::class), 1.0, $timer); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('tick') + ->times(2) + ->with(1.0, Argument::type('Closure')) + ->returns(99, 100); + $timer->expects('clear')->with(99); + $timer->expects('clear')->with(100); + $recycler = new PoolRecycler(Double::for(Factory::class)->strict(), 1.0, $timer); $recycler->start(); $recycler->start(); @@ -197,40 +199,40 @@ public function testStartIsIdempotentAndStopClearsTheTimer(): void public function testCancellationStopsMaintenanceWithoutReporting(bool $scheduled, string $operation): void { $cancellation = new CanceledException('maintenance canceled'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); $container = new Container; $container->instance(ExceptionHandler::class, $handler); Container::setInstance($container); - $pool = m::mock(ObjectPool::class); - $pool->shouldReceive('isIdleExpired')->once()->andReturn($operation === 'purge'); - $manager = m::mock(Factory::class); - $manager->shouldReceive('getPools')->once()->andReturn([ + $pool = Double::for(ObjectPool::class)->strict(); + $pool->expects('isIdleExpired')->returns($operation === 'purge'); + $manager = Double::for(Factory::class)->strict(); + $manager->expects('getPools')->returns([ 'canceled' => $pool, - 'later' => m::mock(ObjectPool::class), + 'later' => Double::for(ObjectPool::class)->strict(), ]); if ($operation === 'purge') { - $manager->shouldReceive('purge')->once()->with('canceled', $pool)->andThrow($cancellation); + $manager->expects('purge')->with('canceled', $pool)->throws($cancellation); } else { - $pool->shouldReceive('sweepExpired')->once()->andThrow($cancellation); - $pool->shouldNotReceive('trimIdle'); + $pool->expects('sweepExpired')->throws($cancellation); + $pool->expects('trimIdle')->never(); } $callback = null; - $timer = m::mock(Timer::class); + $timer = Double::for(Timer::class)->strict(); $recycler = new InspectablePoolRecycler($manager, timer: $timer); if ($scheduled) { - $timer->shouldReceive('tick')->once()->andReturnUsing( + $timer->expects('tick')->resolves( function (float $interval, callable $scheduled) use (&$callback): int { $callback = $scheduled; return 99; }, ); - $timer->shouldReceive('clear')->once()->with(99); + $timer->expects('clear')->with(99); $recycler->start(); $this->assertIsCallable($callback); } @@ -261,24 +263,23 @@ public static function maintenanceCancellationPaths(): array public function testTimerReportsMaintenanceFailures(): void { $failure = new RuntimeException('maintenance failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($failure); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($failure); $container = new Container; $container->instance(ExceptionHandler::class, $handler); Container::setInstance($container); - $manager = m::mock(Factory::class); - $manager->shouldReceive('getPools')->once()->andThrow($failure); + $manager = Double::for(Factory::class)->strict(); + $manager->expects('getPools')->throws($failure); $callback = null; - $timer = m::mock(Timer::class); - $timer->shouldReceive('tick') - ->once() - ->andReturnUsing(function (float $interval, callable $scheduled) use (&$callback): int { + $timer = Double::for(Timer::class)->strict(); + $timer->expects('tick') + ->resolves(function (float $interval, callable $scheduled) use (&$callback): int { $callback = $scheduled; return 99; }); - $timer->shouldReceive('clear')->once()->with(99); + $timer->expects('clear')->with(99); $recycler = new PoolRecycler($manager, 1.0, $timer); $recycler->start(); @@ -296,7 +297,7 @@ public function testConstructorRejectsInvalidIntervals(float $interval): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The recycler interval must be a finite number greater than 0.'); - new PoolRecycler(m::mock(Factory::class), $interval); + new PoolRecycler(Double::for(Factory::class)->strict(), $interval); } public static function invalidIntervals(): array @@ -306,7 +307,7 @@ public static function invalidIntervals(): array public function testFinitePositiveIntervalCanBeConfiguredAtConstruction(): void { - $recycler = new PoolRecycler(m::mock(Factory::class), 2.5); + $recycler = new PoolRecycler(Double::for(Factory::class)->strict(), 2.5); $this->assertSame(2.5, $recycler->getInterval()); } diff --git a/tests/OpenTelemetry/Deferred/DeferredLogsTest.php b/tests/OpenTelemetry/Deferred/DeferredLogsTest.php index 7fe6e1729a..29488583fd 100644 --- a/tests/OpenTelemetry/Deferred/DeferredLogsTest.php +++ b/tests/OpenTelemetry/Deferred/DeferredLogsTest.php @@ -7,7 +7,8 @@ use Generator; use Hypervel\OpenTelemetry\Deferred\Logs\DeferredLoggerProvider; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Logs\LoggerInterface; use OpenTelemetry\API\Logs\LoggerProviderInterface; use OpenTelemetry\API\Logs\LogRecord; @@ -17,6 +18,8 @@ class DeferredLogsTest extends TestCase { + use VerifiesDoubles; + public function testPreBindLoggerDropsRecordsAndReplaysItsScopeAcrossBindings(): void { $provider = new DeferredLoggerProvider; @@ -31,19 +34,17 @@ public function testPreBindLoggerDropsRecordsAndReplaysItsScopeAcrossBindings(): $this->assertInstanceOf(NoopLogRecordBuilder::class, $preBindBuilder); $this->assertFalse($attributes->valid()); - $workerBuilder = m::mock(LogRecordBuilderInterface::class); - $workerLogger = m::mock(LoggerInterface::class); - $workerLogger->shouldReceive('isEnabled') - ->once() + $workerBuilder = Double::for(LogRecordBuilderInterface::class)->strict(); + $workerLogger = Double::for(LoggerInterface::class)->strict(); + $workerLogger->expects('isEnabled') ->with(Context::getRoot(), 17, 'exception') - ->andReturnTrue(); - $workerLogger->shouldReceive('logRecordBuilder')->once()->andReturn($workerBuilder); - $workerLogger->shouldReceive('emit')->once()->with($record); - $workerProvider = m::mock(LoggerProviderInterface::class); - $workerProvider->shouldReceive('getLogger') - ->once() + ->returns(true); + $workerLogger->expects('logRecordBuilder')->returns($workerBuilder); + $workerLogger->expects('emit')->with($record); + $workerProvider = Double::for(LoggerProviderInterface::class)->strict(); + $workerProvider->expects('getLogger') ->with('billing', '1.0', 'https://schema.test', ['scope.kind' => 'test']) - ->andReturn($workerLogger); + ->returns($workerLogger); $provider->bind($workerProvider); @@ -60,12 +61,11 @@ public function testPreBindLoggerDropsRecordsAndReplaysItsScopeAcrossBindings(): public function testLoggerRequestedAfterBindComesDirectlyFromTheWorkerProvider(): void { $provider = new DeferredLoggerProvider; - $workerLogger = m::mock(LoggerInterface::class); - $workerProvider = m::mock(LoggerProviderInterface::class); - $workerProvider->shouldReceive('getLogger') - ->once() + $workerLogger = Double::for(LoggerInterface::class)->strict(); + $workerProvider = Double::for(LoggerProviderInterface::class)->strict(); + $workerProvider->expects('getLogger') ->with('worker', null, null, []) - ->andReturn($workerLogger); + ->returns($workerLogger); $provider->bind($workerProvider); diff --git a/tests/OpenTelemetry/Deferred/DeferredMetricsTest.php b/tests/OpenTelemetry/Deferred/DeferredMetricsTest.php index 4f1922afa6..e5ef213ea9 100644 --- a/tests/OpenTelemetry/Deferred/DeferredMetricsTest.php +++ b/tests/OpenTelemetry/Deferred/DeferredMetricsTest.php @@ -8,7 +8,10 @@ use Generator; use Hypervel\OpenTelemetry\Deferred\Metrics\DeferredMeterProvider; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use OpenTelemetry\API\Metrics\CounterInterface; use OpenTelemetry\API\Metrics\GaugeInterface; use OpenTelemetry\API\Metrics\HistogramInterface; @@ -24,6 +27,8 @@ class DeferredMetricsTest extends TestCase { + use VerifiesDoubles; + public function testPreBindSynchronousInstrumentsDropMeasurementsAndBindWithTheirDescriptors(): void { $provider = new DeferredMeterProvider; @@ -45,40 +50,35 @@ public function testPreBindSynchronousInstrumentsDropMeasurementsAndBindWithThei $this->assertFalse($gauge->isEnabled()); $this->assertFalse($attributes->valid()); - $workerCounter = m::mock(CounterInterface::class); - $workerCounter->shouldReceive('isEnabled')->once()->andReturnTrue(); - $workerCounter->shouldReceive('add')->once()->with(2, ['result' => 'ok'], null); - $workerUpDownCounter = m::mock(UpDownCounterInterface::class); - $workerUpDownCounter->shouldReceive('isEnabled')->once()->andReturnTrue(); - $workerUpDownCounter->shouldReceive('add')->once()->with(-2, [], null); - $workerHistogram = m::mock(HistogramInterface::class); - $workerHistogram->shouldReceive('isEnabled')->once()->andReturnTrue(); - $workerHistogram->shouldReceive('record')->once()->with(1.5, [], null); - $workerGauge = m::mock(GaugeInterface::class); - $workerGauge->shouldReceive('isEnabled')->once()->andReturnTrue(); - $workerGauge->shouldReceive('record')->once()->with(20, [], null); - $workerMeter = m::mock(MeterInterface::class); - $workerMeter->shouldReceive('createCounter') - ->once() + $workerCounter = Double::for(CounterInterface::class)->strict(); + $workerCounter->expects('isEnabled')->returns(true); + $workerCounter->expects('add')->with(2, ['result' => 'ok'], null); + $workerUpDownCounter = Double::for(UpDownCounterInterface::class)->strict(); + $workerUpDownCounter->expects('isEnabled')->returns(true); + $workerUpDownCounter->expects('add')->with(-2, [], null); + $workerHistogram = Double::for(HistogramInterface::class)->strict(); + $workerHistogram->expects('isEnabled')->returns(true); + $workerHistogram->expects('record')->with(1.5, [], null); + $workerGauge = Double::for(GaugeInterface::class)->strict(); + $workerGauge->expects('isEnabled')->returns(true); + $workerGauge->expects('record')->with(20, [], null); + $workerMeter = Double::for(MeterInterface::class)->strict(); + $workerMeter->expects('createCounter') ->with('billing.count', '{item}', 'Count items', ['key' => 'value']) - ->andReturn($workerCounter); - $workerMeter->shouldReceive('createUpDownCounter') - ->once() + ->returns($workerCounter); + $workerMeter->expects('createUpDownCounter') ->with('billing.active', null, null, []) - ->andReturn($workerUpDownCounter); - $workerMeter->shouldReceive('createHistogram') - ->once() + ->returns($workerUpDownCounter); + $workerMeter->expects('createHistogram') ->with('billing.duration', 's', null, []) - ->andReturn($workerHistogram); - $workerMeter->shouldReceive('createGauge') - ->once() + ->returns($workerHistogram); + $workerMeter->expects('createGauge') ->with('billing.size', 'By', null, []) - ->andReturn($workerGauge); - $workerProvider = m::mock(MeterProviderInterface::class); - $workerProvider->shouldReceive('getMeter') - ->once() + ->returns($workerGauge); + $workerProvider = Double::for(MeterProviderInterface::class)->strict(); + $workerProvider->expects('getMeter') ->with('billing', '1.0', 'https://schema.test', ['scope.kind' => 'test']) - ->andReturn($workerMeter); + ->returns($workerMeter); $provider->bind($workerProvider); @@ -145,13 +145,13 @@ public function testObservableCreationAndRegistrationsReplayWithoutResurrectingD $counterCallback, $batchCallback, ); - $firstCounterToken->shouldReceive('detach')->once(); - $firstBatchToken->shouldReceive('detach')->once(); + $firstCounterToken->expects('detach'); + $firstBatchToken->expects('detach'); $provider->bind($secondProvider); - $secondCounterToken->shouldReceive('detach')->once(); - $secondBatchToken->shouldReceive('detach')->once(); + $secondCounterToken->expects('detach'); + $secondBatchToken->expects('detach'); $counterToken->detach(); $batchToken->detach(); @@ -166,18 +166,16 @@ public function testBoundObjectCallbackIsDetachedWhenItsTargetIsCollected(): voi $target = new DeferredMetricsCallbackTarget; $targetReference = WeakReference::create($target); $counter->observe($target->callback()); - $workerCounter = m::mock(ObservableCounterInterface::class); - $workerCounter->shouldReceive('isEnabled')->andReturnTrue(); - $workerMeter = m::mock(MeterInterface::class); - $workerMeter->shouldReceive('createObservableCounter') - ->once() + $workerCounter = Double::for(ObservableCounterInterface::class)->strict(); + $workerCounter->allows('isEnabled')->returns(true); + $workerMeter = Double::for(MeterInterface::class)->strict(); + $workerMeter->expects('createObservableCounter') ->with('runtime.count', null, null, []) - ->andReturn($workerCounter); - $workerProvider = m::mock(MeterProviderInterface::class); - $workerProvider->shouldReceive('getMeter') - ->once() + ->returns($workerCounter); + $workerProvider = Double::for(MeterProviderInterface::class)->strict(); + $workerProvider->expects('getMeter') ->with('runtime', null, null, []) - ->andReturn($workerMeter); + ->returns($workerMeter); unset($target); gc_collect_cycles(); @@ -195,29 +193,26 @@ public function testCollectingBoundObjectDetachesItsCurrentDelegateToken(): void $target = new DeferredMetricsCallbackTarget; $targetReference = WeakReference::create($target); $counter->observe([$target, 'observe']); - $delegateToken = m::mock(ObservableCallbackInterface::class); - $delegateToken->shouldReceive('detach')->once(); - $workerCounter = m::mock(ObservableCounterInterface::class); - $workerCounter->shouldReceive('observe') - ->once() - ->with(m::type(Closure::class)) - ->andReturnUsing(function (Closure $callback) use ($delegateToken): ObservableCallbackInterface { - $observer = m::mock(ObserverInterface::class); - $observer->shouldReceive('observe')->once()->with(1); + $delegateToken = Double::for(ObservableCallbackInterface::class)->strict(); + $delegateToken->expects('detach'); + $workerCounter = Double::for(ObservableCounterInterface::class)->strict(); + $workerCounter->expects('observe') + ->with(Argument::type(Closure::class)) + ->resolves(function (Closure $callback) use ($delegateToken): ObservableCallbackInterface { + $observer = Double::for(ObserverInterface::class)->strict(); + $observer->expects('observe')->with(1); $callback($observer); return $delegateToken; }); - $workerMeter = m::mock(MeterInterface::class); - $workerMeter->shouldReceive('createObservableCounter') - ->once() + $workerMeter = Double::for(MeterInterface::class)->strict(); + $workerMeter->expects('createObservableCounter') ->with('runtime.count', null, null, []) - ->andReturn($workerCounter); - $workerProvider = m::mock(MeterProviderInterface::class); - $workerProvider->shouldReceive('getMeter') - ->once() + ->returns($workerCounter); + $workerProvider = Double::for(MeterProviderInterface::class)->strict(); + $workerProvider->expects('getMeter') ->with('runtime', null, null, []) - ->andReturn($workerMeter); + ->returns($workerMeter); $provider->bind($workerProvider); $this->assertSame(1, $target->observations); @@ -232,49 +227,44 @@ public function testBatchObservationMapsOwnedInstrumentsAndLeavesForeignInstrume $provider = new DeferredMeterProvider; $meter = $provider->getMeter('runtime'); $counter = $meter->createObservableCounter('runtime.count'); - $foreignGauge = m::mock(ObservableGaugeInterface::class); + $foreignGauge = Double::for(ObservableGaugeInterface::class)->strict(); $callback = static function (ObserverInterface $counter, ObserverInterface $gauge): void { $counter->observe(1); $gauge->observe(2); }; - $counterDelegate = m::mock(ObservableCounterInterface::class); - $delegateToken = m::mock(ObservableCallbackInterface::class); - $workerMeter = m::mock(MeterInterface::class); - $workerMeter->shouldReceive('createObservableCounter') - ->once() + $counterDelegate = Double::for(ObservableCounterInterface::class)->strict(); + $delegateToken = Double::for(ObservableCallbackInterface::class)->strict(); + $workerMeter = Double::for(MeterInterface::class)->strict(); + $workerMeter->expects('createObservableCounter') ->with('runtime.count', null, null, []) - ->andReturn($counterDelegate); - $workerMeter->shouldReceive('batchObserve') - ->once() + ->returns($counterDelegate); + $workerMeter->expects('batchObserve') ->with($callback, $counterDelegate, $foreignGauge) - ->andReturn($delegateToken); - $workerProvider = m::mock(MeterProviderInterface::class); - $workerProvider->shouldReceive('getMeter') - ->once() + ->returns($delegateToken); + $workerProvider = Double::for(MeterProviderInterface::class)->strict(); + $workerProvider->expects('getMeter') ->with('runtime', null, null, []) - ->andReturn($workerMeter); + ->returns($workerMeter); $token = $meter->batchObserve($callback, $counter, $foreignGauge); $provider->bind($workerProvider); - $delegateToken->shouldReceive('detach')->once(); + $delegateToken->expects('detach'); $token->detach(); } public function testMeterAndInstrumentsRequestedAfterBindComeDirectlyFromTheWorkerProvider(): void { $provider = new DeferredMeterProvider; - $workerCounter = m::mock(CounterInterface::class); - $workerMeter = m::mock(MeterInterface::class); - $workerMeter->shouldReceive('createCounter') - ->once() + $workerCounter = Double::for(CounterInterface::class)->strict(); + $workerMeter = Double::for(MeterInterface::class)->strict(); + $workerMeter->expects('createCounter') ->with('worker.count') - ->andReturn($workerCounter); - $workerProvider = m::mock(MeterProviderInterface::class); - $workerProvider->shouldReceive('getMeter') - ->once() + ->returns($workerCounter); + $workerProvider = Double::for(MeterProviderInterface::class)->strict(); + $workerProvider->expects('getMeter') ->with('worker', null, null, []) - ->andReturn($workerMeter); + ->returns($workerMeter); $provider->bind($workerProvider); $meter = $provider->getMeter('worker'); @@ -286,7 +276,7 @@ public function testMeterAndInstrumentsRequestedAfterBindComeDirectlyFromTheWork /** * Create a worker provider configured for observable replay. * - * @return array{MeterProviderInterface, ObservableCallbackInterface, ObservableCallbackInterface} + * @return array{DoubleInterface&MeterProviderInterface, DoubleInterface&ObservableCallbackInterface, DoubleInterface&ObservableCallbackInterface} */ private function observableProvider( callable $counterCreation, @@ -294,37 +284,32 @@ private function observableProvider( callable $counterCallback, callable $batchCallback, ): array { - $counterToken = m::mock(ObservableCallbackInterface::class); - $batchToken = m::mock(ObservableCallbackInterface::class); - $counter = m::mock(ObservableCounterInterface::class); - $counter->shouldReceive('isEnabled')->andReturnTrue(); - $counter->shouldReceive('observe')->once()->with($counterCallback)->andReturn($counterToken); - $gauge = m::mock(ObservableGaugeInterface::class); - $gauge->shouldReceive('isEnabled')->andReturnTrue(); - $upDownCounter = m::mock(ObservableUpDownCounterInterface::class); - $upDownCounter->shouldReceive('isEnabled')->andReturnTrue(); - $meter = m::mock(MeterInterface::class); - $meter->shouldReceive('createObservableCounter') - ->once() + $counterToken = Double::for(ObservableCallbackInterface::class)->strict(); + $batchToken = Double::for(ObservableCallbackInterface::class)->strict(); + $counter = Double::for(ObservableCounterInterface::class)->strict(); + $counter->allows('isEnabled')->returns(true); + $counter->expects('observe')->with($counterCallback)->returns($counterToken); + $gauge = Double::for(ObservableGaugeInterface::class)->strict(); + $gauge->allows('isEnabled')->returns(true); + $upDownCounter = Double::for(ObservableUpDownCounterInterface::class)->strict(); + $upDownCounter->allows('isEnabled')->returns(true); + $meter = Double::for(MeterInterface::class)->strict(); + $meter->expects('createObservableCounter') ->with('runtime.count', null, null, [], $counterCreation) - ->andReturn($counter); - $meter->shouldReceive('createObservableGauge') - ->once() + ->returns($counter); + $meter->expects('createObservableGauge') ->with('runtime.gauge', null, null, [], $gaugeCreation) - ->andReturn($gauge); - $meter->shouldReceive('createObservableUpDownCounter') - ->once() + ->returns($gauge); + $meter->expects('createObservableUpDownCounter') ->with('runtime.active', null, null, []) - ->andReturn($upDownCounter); - $meter->shouldReceive('batchObserve') - ->once() + ->returns($upDownCounter); + $meter->expects('batchObserve') ->with($batchCallback, $counter, $gauge) - ->andReturn($batchToken); - $provider = m::mock(MeterProviderInterface::class); - $provider->shouldReceive('getMeter') - ->once() + ->returns($batchToken); + $provider = Double::for(MeterProviderInterface::class)->strict(); + $provider->expects('getMeter') ->with('runtime', null, null, []) - ->andReturn($meter); + ->returns($meter); return [$provider, $counterToken, $batchToken]; } diff --git a/tests/OpenTelemetry/Deferred/DeferredTraceTest.php b/tests/OpenTelemetry/Deferred/DeferredTraceTest.php index 9538dd51fd..1f346e42bd 100644 --- a/tests/OpenTelemetry/Deferred/DeferredTraceTest.php +++ b/tests/OpenTelemetry/Deferred/DeferredTraceTest.php @@ -7,13 +7,16 @@ use Generator; use Hypervel\OpenTelemetry\Deferred\Trace\DeferredTracerProvider; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Trace\SpanBuilderInterface; use OpenTelemetry\API\Trace\TracerInterface; use OpenTelemetry\API\Trace\TracerProviderInterface; class DeferredTraceTest extends TestCase { + use VerifiesDoubles; + public function testPreBindTracerReplaysItsScopeAcrossBindUnbindAndRebind(): void { $provider = new DeferredTracerProvider; @@ -24,15 +27,14 @@ public function testPreBindTracerReplaysItsScopeAcrossBindUnbindAndRebind(): voi $this->assertInstanceOf(SpanBuilderInterface::class, $tracer->spanBuilder('before-bind')); $this->assertFalse($attributes->valid()); - $firstBuilder = m::mock(SpanBuilderInterface::class); - $firstTracer = m::mock(TracerInterface::class); - $firstTracer->shouldReceive('isEnabled')->once()->andReturnTrue(); - $firstTracer->shouldReceive('spanBuilder')->once()->with('first')->andReturn($firstBuilder); - $firstProvider = m::mock(TracerProviderInterface::class); - $firstProvider->shouldReceive('getTracer') - ->once() + $firstBuilder = Double::for(SpanBuilderInterface::class)->strict(); + $firstTracer = Double::for(TracerInterface::class)->strict(); + $firstTracer->expects('isEnabled')->returns(true); + $firstTracer->expects('spanBuilder')->with('first')->returns($firstBuilder); + $firstProvider = Double::for(TracerProviderInterface::class)->strict(); + $firstProvider->expects('getTracer') ->with('billing', '1.0', 'https://schema.test', ['scope.kind' => 'test']) - ->andReturn($firstTracer); + ->returns($firstTracer); $provider->bind($firstProvider); @@ -43,13 +45,12 @@ public function testPreBindTracerReplaysItsScopeAcrossBindUnbindAndRebind(): voi $this->assertFalse($tracer->isEnabled()); - $secondTracer = m::mock(TracerInterface::class); - $secondTracer->shouldReceive('isEnabled')->once()->andReturnTrue(); - $secondProvider = m::mock(TracerProviderInterface::class); - $secondProvider->shouldReceive('getTracer') - ->once() + $secondTracer = Double::for(TracerInterface::class)->strict(); + $secondTracer->expects('isEnabled')->returns(true); + $secondProvider = Double::for(TracerProviderInterface::class)->strict(); + $secondProvider->expects('getTracer') ->with('billing', '1.0', 'https://schema.test', ['scope.kind' => 'test']) - ->andReturn($secondTracer); + ->returns($secondTracer); $provider->bind($secondProvider); @@ -59,12 +60,11 @@ public function testPreBindTracerReplaysItsScopeAcrossBindUnbindAndRebind(): voi public function testTracerRequestedAfterBindComesDirectlyFromTheWorkerProvider(): void { $provider = new DeferredTracerProvider; - $workerTracer = m::mock(TracerInterface::class); - $workerProvider = m::mock(TracerProviderInterface::class); - $workerProvider->shouldReceive('getTracer') - ->once() + $workerTracer = Double::for(TracerInterface::class)->strict(); + $workerProvider = Double::for(TracerProviderInterface::class)->strict(); + $workerProvider->expects('getTracer') ->with('worker', null, null, []) - ->andReturn($workerTracer); + ->returns($workerTracer); $provider->bind($workerProvider); diff --git a/tests/OpenTelemetry/Exporters/OtlpExporterFactoryTest.php b/tests/OpenTelemetry/Exporters/OtlpExporterFactoryTest.php index cd2e62f321..23ecb4dab2 100644 --- a/tests/OpenTelemetry/Exporters/OtlpExporterFactoryTest.php +++ b/tests/OpenTelemetry/Exporters/OtlpExporterFactoryTest.php @@ -7,7 +7,8 @@ use Hypervel\OpenTelemetry\Exporters\OtlpExporterFactory; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Signals; use OpenTelemetry\Contrib\Otlp\ContentTypes; use OpenTelemetry\Contrib\Otlp\LogsExporter; @@ -21,6 +22,8 @@ class OtlpExporterFactoryTest extends TestCase { + use VerifiesDoubles; + public function testSignalOverridesTakePrecedenceAndSharedEndpointsReceiveTheStandardPath(): void { $factory = new TestOtlpExporterFactory; @@ -458,6 +461,6 @@ protected function createClient(array $options): ClientInterface { $this->createdOptions[] = $options; - return m::mock(ClientInterface::class); + return Double::for(ClientInterface::class)->strict(); } } diff --git a/tests/OpenTelemetry/Instrumentation/CacheInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/CacheInstrumentationTest.php index 5f9be3288d..1d6a939372 100644 --- a/tests/OpenTelemetry/Instrumentation/CacheInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/CacheInstrumentationTest.php @@ -24,8 +24,8 @@ use Hypervel\OpenTelemetry\Instrumentation\CacheInstrumentation; use Hypervel\OpenTelemetry\OpenTelemetryManager; use Hypervel\Tests\TestCase; -use Mockery as m; -use OpenTelemetry\API\Trace\TracerProviderInterface; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\Context\Context; use OpenTelemetry\Context\ContextStorageInterface; use OpenTelemetry\Context\ExecutionContextAwareInterface; @@ -48,6 +48,8 @@ class CacheInstrumentationTest extends TestCase { + use VerifiesDoubles; + private ContextStorageInterface&ExecutionContextAwareInterface $previousStorage; private Dispatcher $events; @@ -272,7 +274,7 @@ public function testNonRecordingSpanSkipsEveryKeyDependencyWhileMetricsRemainAct ->build(); try { - $this->instrumentation(tracerProvider: $tracerProvider, resolverCalls: 0) + $this->instrumentation(resolverCalls: 0) ->register($this->options(['key' => true])); $span = $tracerProvider->getTracer('test')->spanBuilder('request')->startSpan(); $scope = $span->activate(); @@ -324,17 +326,10 @@ public function testAllOutputsOffRegistersNoCacheListeners(): void */ private function instrumentation( ?Closure $resolver = null, - ?TracerProviderInterface $tracerProvider = null, int $resolverCalls = 1, ): CacheInstrumentation { - $openTelemetryManager = m::mock(OpenTelemetryManager::class); - $expectation = $openTelemetryManager->shouldReceive('cacheKeyResolver'); - - if ($resolverCalls === 0) { - $expectation->never(); - } else { - $expectation->times($resolverCalls)->andReturn($resolver); - } + $openTelemetryManager = Double::for(OpenTelemetryManager::class)->strict(); + $openTelemetryManager->expects('cacheKeyResolver')->times($resolverCalls)->returns($resolver); return new CacheInstrumentation( $this->events, diff --git a/tests/OpenTelemetry/Instrumentation/ConsoleInstrumentationNonCoroutineTest.php b/tests/OpenTelemetry/Instrumentation/ConsoleInstrumentationNonCoroutineTest.php index ceddf25910..79048fade1 100644 --- a/tests/OpenTelemetry/Instrumentation/ConsoleInstrumentationNonCoroutineTest.php +++ b/tests/OpenTelemetry/Instrumentation/ConsoleInstrumentationNonCoroutineTest.php @@ -16,7 +16,8 @@ use Hypervel\OpenTelemetry\Support\OperationOrigin; use Hypervel\OpenTelemetry\Support\ProcessIdentity; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Common\Time\ClockInterface; use OpenTelemetry\API\Metrics\Noop\NoopMeterProvider; use OpenTelemetry\API\Trace\Span; @@ -30,6 +31,8 @@ class ConsoleInstrumentationNonCoroutineTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; private ContextStorageInterface&ExecutionContextAwareInterface $previousStorage; @@ -63,8 +66,8 @@ protected function tearDown(): void public function testCommandSpanUsesAndClearsTheNonCoroutineContextStack(): void { - $logContextScopes = m::mock(LogContextScopeFactory::class); - $logContextScopes->shouldReceive('activate')->once()->andReturnNull(); + $logContextScopes = Double::for(LogContextScopeFactory::class)->strict(); + $logContextScopes->expects('activate')->returns(null); $instrumentation = new ConsoleInstrumentation( $this->events, $this->tracerProvider, diff --git a/tests/OpenTelemetry/Instrumentation/ConsoleInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/ConsoleInstrumentationTest.php index fc167b1f7c..ceebd4366e 100644 --- a/tests/OpenTelemetry/Instrumentation/ConsoleInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/ConsoleInstrumentationTest.php @@ -17,7 +17,8 @@ use Hypervel\OpenTelemetry\Support\ProcessIdentity; use Hypervel\Tests\OpenTelemetry\Fixtures\CapturingAlwaysOffSampler; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Common\Time\ClockInterface; use OpenTelemetry\API\Trace\Span; use OpenTelemetry\API\Trace\SpanKind; @@ -47,6 +48,8 @@ class ConsoleInstrumentationTest extends TestCase { + use VerifiesDoubles; + private const string DURATION_METRIC = 'hypervel.console.command.duration'; private ContextStorageInterface&ExecutionContextAwareInterface $previousStorage; @@ -387,8 +390,8 @@ private function finishCommand( */ private function instrumentation(): ConsoleInstrumentation { - $logContextScopes = m::mock(LogContextScopeFactory::class); - $logContextScopes->shouldReceive('activate')->zeroOrMoreTimes()->andReturnNull(); + $logContextScopes = Double::for(LogContextScopeFactory::class)->strict(); + $logContextScopes->allows('activate')->returns(null); return new ConsoleInstrumentation( $this->events, diff --git a/tests/OpenTelemetry/Instrumentation/DatabaseInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/DatabaseInstrumentationTest.php index 8d402ddf44..a416b02785 100644 --- a/tests/OpenTelemetry/Instrumentation/DatabaseInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/DatabaseInstrumentationTest.php @@ -16,7 +16,8 @@ use Hypervel\OpenTelemetry\Support\OperationOrigin; use Hypervel\OpenTelemetry\Support\ProcessIdentity; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Common\Time\ClockInterface; use OpenTelemetry\API\Trace\Span; use OpenTelemetry\API\Trace\SpanKind; @@ -45,6 +46,8 @@ class DatabaseInstrumentationTest extends TestCase { + use VerifiesDoubles; + private ContextStorageInterface&ExecutionContextAwareInterface $previousStorage; private Dispatcher $events; @@ -410,13 +413,12 @@ private function connection( array $config = [], string $name = 'primary', ): Connection { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getName')->zeroOrMoreTimes()->andReturn($name); - $connection->shouldReceive('getDriverName')->zeroOrMoreTimes()->andReturn($driver); - $connection->shouldReceive('getDatabaseName')->zeroOrMoreTimes()->andReturn($database); - $connection->shouldReceive('getConfig') - ->zeroOrMoreTimes() - ->andReturnUsing(static fn (?string $key = null): mixed => $key === null + $connection = Double::for(Connection::class)->strict(); + $connection->allows('getName')->returns($name); + $connection->allows('getDriverName')->returns($driver); + $connection->allows('getDatabaseName')->returns($database); + $connection->allows('getConfig') + ->resolves(static fn (?string $key = null): mixed => $key === null ? $config : ($config[$key] ?? null)); diff --git a/tests/OpenTelemetry/Instrumentation/ExceptionInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/ExceptionInstrumentationTest.php index 9f39b3d6d0..bfdac82518 100644 --- a/tests/OpenTelemetry/Instrumentation/ExceptionInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/ExceptionInstrumentationTest.php @@ -21,7 +21,9 @@ use Hypervel\OpenTelemetry\Support\UserContextResolver; use Hypervel\Support\Lottery; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Common\Time\ClockInterface; use OpenTelemetry\API\Logs\LogRecordBuilderInterface; use OpenTelemetry\API\Logs\Severity; @@ -53,6 +55,8 @@ class ExceptionInstrumentationTest extends TestCase { + use VerifiesDoubles; + private ContextStorageInterface&ExecutionContextAwareInterface $previousStorage; private Container $container; @@ -73,7 +77,7 @@ class ExceptionInstrumentationTest extends TestCase private OperationOrigin $origins; - private UserContextResolver $userContexts; + private UserContextResolver&DoubleInterface $userContexts; protected function setUp(): void { @@ -100,7 +104,7 @@ protected function setUpInCoroutine(): void ->build(); $this->exceptionContexts = new ExceptionContextRegistry; $this->origins = new OperationOrigin; - $this->userContexts = m::mock(UserContextResolver::class); + $this->userContexts = Double::for(UserContextResolver::class)->strict(); } protected function tearDownInCoroutine(): void @@ -198,10 +202,9 @@ public function testRequestOnlyStateSuppliesLazyUserContextToExceptionLogs(): vo false, ); RequestTelemetryState::set($state); - $this->userContexts->shouldReceive('resolve') - ->once() + $this->userContexts->expects('resolve') ->with($state) - ->andReturn(['user.id' => '42']); + ->returns(['user.id' => '42']); $this->handler->report(new RuntimeException('Request failed.')); @@ -342,7 +345,7 @@ public function testMetricsOnlyModeDoesNotEnableDirectLogDeduplication(): void public function testCustomHandlerWithoutReportableSupportIsLeftUntouched(): void { $container = new Container; - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); $container->instance(ExceptionHandlerContract::class, $handler); $instrumentation = $this->instrumentation(container: $container); @@ -362,15 +365,15 @@ private function instrumentation( array $enrichers = [], ?Container $container = null, ): ExceptionInstrumentation { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('configuration')->zeroOrMoreTimes()->andReturn([ + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->allows('configuration')->returns([ 'instrumentation' => [ HttpServerInstrumentation::class => $userContext ? ['user_context' => true] : false, ], ]); - $manager->shouldReceive('exceptionEnrichers')->zeroOrMoreTimes()->andReturn($enrichers); + $manager->allows('exceptionEnrichers')->returns($enrichers); return new ExceptionInstrumentation( $container ?? $this->container, diff --git a/tests/OpenTelemetry/Instrumentation/GrpcInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/GrpcInstrumentationTest.php index 8a03990a42..dda7b1ff01 100644 --- a/tests/OpenTelemetry/Instrumentation/GrpcInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/GrpcInstrumentationTest.php @@ -22,8 +22,9 @@ use Hypervel\OpenTelemetry\Support\OperationOrigin; use Hypervel\OpenTelemetry\Support\ProcessIdentity; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use OpenTelemetry\API\Common\Time\ClockInterface; use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator; use OpenTelemetry\API\Trace\Span; @@ -58,6 +59,8 @@ class GrpcInstrumentationTest extends TestCase { + use VerifiesDoubles; + private const string CLIENT_DURATION_METRIC = 'rpc.client.call.duration'; private const string SERVER_DURATION_METRIC = 'rpc.server.call.duration'; @@ -477,8 +480,8 @@ private function registerInstrumentation( */ private function instrumentation(?TextMapPropagatorInterface $propagator = null): GrpcInstrumentation { - $logContextScopes = m::mock(LogContextScopeFactory::class); - $logContextScopes->shouldReceive('activate')->zeroOrMoreTimes()->andReturnNull(); + $logContextScopes = Double::for(LogContextScopeFactory::class)->strict(); + $logContextScopes->allows('activate')->returns(null); return new GrpcInstrumentation( $this->operations, diff --git a/tests/OpenTelemetry/Instrumentation/HttpClientInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/HttpClientInstrumentationTest.php index 848039abf9..2c8326bcd4 100644 --- a/tests/OpenTelemetry/Instrumentation/HttpClientInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/HttpClientInstrumentationTest.php @@ -20,7 +20,9 @@ use Hypervel\OpenTelemetry\Support\OperationOrigin; use Hypervel\OpenTelemetry\Support\ProcessIdentity; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Nyholm\Psr7\Request as NyholmRequest; use OpenTelemetry\API\Common\Time\ClockInterface; use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator; @@ -53,6 +55,8 @@ class HttpClientInstrumentationTest extends TestCase { + use VerifiesDoubles; + private ContextStorageInterface&ExecutionContextAwareInterface $previousStorage; private Factory $factory; @@ -69,7 +73,7 @@ class HttpClientInstrumentationTest extends TestCase private MeterProvider $meterProvider; - private OpenTelemetryManager $manager; + private OpenTelemetryManager&DoubleInterface $manager; private ExceptionContextRegistry $exceptionContexts; @@ -98,10 +102,9 @@ protected function setUpInCoroutine(): void $this->meterProvider = (new MeterProviderBuilder) ->addReader($this->metricReader) ->build(); - $this->manager = m::mock(OpenTelemetryManager::class); - $this->manager->shouldReceive('urlTemplateResolver') - ->zeroOrMoreTimes() - ->andReturnUsing(function (): ?Closure { + $this->manager = Double::for(OpenTelemetryManager::class)->strict(); + $this->manager->allows('urlTemplateResolver') + ->resolves(function (): ?Closure { ++$this->urlTemplateResolverCalls; return $this->urlTemplateResolver; diff --git a/tests/OpenTelemetry/Instrumentation/HttpServerInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/HttpServerInstrumentationTest.php index 2e75046944..4b18758c6c 100644 --- a/tests/OpenTelemetry/Instrumentation/HttpServerInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/HttpServerInstrumentationTest.php @@ -22,7 +22,8 @@ use Hypervel\OpenTelemetry\Support\UserContextResolver; use Hypervel\Routing\Route; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Common\Time\ClockInterface; use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator; use OpenTelemetry\API\Trace\Span; @@ -58,6 +59,8 @@ class HttpServerInstrumentationTest extends TestCase { + use VerifiesDoubles; + private ContextStorageInterface&ExecutionContextAwareInterface $previousStorage; private Dispatcher $events; @@ -97,7 +100,7 @@ protected function setUpInCoroutine(): void $this->meterProvider = (new MeterProviderBuilder) ->addReader($this->metricReader) ->build(); - $this->userContexts = m::mock(UserContextResolver::class); + $this->userContexts = Double::for(UserContextResolver::class)->strict(); } protected function tearDownInCoroutine(): void @@ -429,8 +432,8 @@ public function testDoesNotReadTheClientControlledServerAuthority(): void private function instrumentation( ?ResponsePropagatorInterface $responsePropagator = null, ): HttpServerInstrumentation { - $logContextScopes = m::mock(LogContextScopeFactory::class); - $logContextScopes->shouldReceive('activate')->zeroOrMoreTimes()->andReturnNull(); + $logContextScopes = Double::for(LogContextScopeFactory::class)->strict(); + $logContextScopes->allows('activate')->returns(null); return new HttpServerInstrumentation( $this->events, diff --git a/tests/OpenTelemetry/Instrumentation/PoolInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/PoolInstrumentationTest.php index b449ab66a0..71cc5b3ebf 100644 --- a/tests/OpenTelemetry/Instrumentation/PoolInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/PoolInstrumentationTest.php @@ -19,7 +19,8 @@ use Hypervel\OpenTelemetry\Instrumentation\PoolInstrumentation; use Hypervel\Redis\Pool\PoolManager as RedisPoolManager; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Metrics\MeterProviderInterface; use OpenTelemetry\SDK\Metrics\Data\Metric; use OpenTelemetry\SDK\Metrics\Data\NumberDataPoint; @@ -33,6 +34,8 @@ class PoolInstrumentationTest extends TestCase { + use VerifiesDoubles; + private InMemoryExporter $exporter; private ExportingReader $reader; @@ -57,10 +60,10 @@ public function testRecordsExistingConnectionAndObjectPoolsWithExactWireIdentiti { $databasePool = $this->connectionPool(current: 4, idle: 2, max: 10, waiters: 1); $redisPool = $this->connectionPool(current: 3, idle: 1, max: 8, waiters: 2); - $databasePools = m::mock(DatabasePoolManager::class); - $databasePools->shouldReceive('getPools')->once()->andReturn(['default' => $databasePool]); - $redisPools = m::mock(RedisPoolManager::class); - $redisPools->shouldReceive('getPools')->once()->andReturn(['default' => $redisPool]); + $databasePools = Double::for(DatabasePoolManager::class)->strict(); + $databasePools->expects('getPools')->returns(['default' => $databasePool]); + $redisPools = Double::for(RedisPoolManager::class)->strict(); + $redisPools->expects('getPools')->returns(['default' => $redisPool]); $objectPools = new ObjectPoolManager; $definitions = new PoolDefinitionManagerStub($objectPools); $autoDefinition = $definitions->definition( @@ -183,12 +186,12 @@ static function () use ($destroyStarted, $finishDestroy): void { $finishDestroy->pop(1.0); }, ); - $objectPools = m::mock(ObjectPoolManager::class); - $objectPools->shouldReceive('getPools')->twice()->andReturn(['app:reports' => $pool]); - $databasePools = m::mock(DatabasePoolManager::class); - $databasePools->shouldNotReceive('getPools'); - $redisPools = m::mock(RedisPoolManager::class); - $redisPools->shouldNotReceive('getPools'); + $objectPools = Double::for(ObjectPoolManager::class)->strict(); + $objectPools->expects('getPools')->times(2)->returns(['app:reports' => $pool]); + $databasePools = Double::for(DatabasePoolManager::class)->strict(); + $databasePools->expects('getPools')->never(); + $redisPools = Double::for(RedisPoolManager::class)->strict(); + $redisPools->expects('getPools')->never(); $instrumentation = $this->instrumentation($databasePools, $redisPools, $objectPools); $instrumentation->register($this->options(enabled: ['hypervel.object_pool.objects'])); $borrowed = $pool->borrow(); @@ -223,14 +226,14 @@ static function () use ($destroyStarted, $finishDestroy): void { public function testDisabledMetricsDoNotResolveTheMeterOrInspectPoolRegistries(): void { - $databasePools = m::mock(DatabasePoolManager::class); - $databasePools->shouldNotReceive('getPools'); - $redisPools = m::mock(RedisPoolManager::class); - $redisPools->shouldNotReceive('getPools'); - $objectPools = m::mock(ObjectPoolManager::class); - $objectPools->shouldNotReceive('getPools'); - $meterProvider = m::mock(MeterProviderInterface::class); - $meterProvider->shouldNotReceive('getMeter'); + $databasePools = Double::for(DatabasePoolManager::class)->strict(); + $databasePools->expects('getPools')->never(); + $redisPools = Double::for(RedisPoolManager::class)->strict(); + $redisPools->expects('getPools')->never(); + $objectPools = Double::for(ObjectPoolManager::class)->strict(); + $objectPools->expects('getPools')->never(); + $meterProvider = Double::for(MeterProviderInterface::class)->strict(); + $meterProvider->expects('getMeter')->never(); $instrumentation = new PoolInstrumentation( $databasePools, @@ -239,24 +242,22 @@ public function testDisabledMetricsDoNotResolveTheMeterOrInspectPoolRegistries() $meterProvider, ); $instrumentation->register($this->options(enabled: [])); - - $this->addToAssertionCount(1); } public function testIndividualConnectionMetricsReadOnlyTheirRequiredSourceValues(): void { - $pool = m::mock(ConnectionPool::class); - $pool->shouldReceive('getOptions')->once()->andReturn(ConnectionPoolOptions::fromArray(['max_connections' => 12])); - $pool->shouldNotReceive('getManagedCount'); - $pool->shouldNotReceive('getIdleCount'); - $pool->shouldNotReceive('getWaitingCount'); - $pool->shouldNotReceive('getStats'); - $databasePools = m::mock(DatabasePoolManager::class); - $databasePools->shouldReceive('getPools')->once()->andReturn(['primary' => $pool]); - $redisPools = m::mock(RedisPoolManager::class); - $redisPools->shouldReceive('getPools')->once()->andReturn([]); - $objectPools = m::mock(ObjectPoolManager::class); - $objectPools->shouldNotReceive('getPools'); + $pool = Double::for(ConnectionPool::class)->strict(); + $pool->expects('getOptions')->returns(ConnectionPoolOptions::fromArray(['max_connections' => 12])); + $pool->expects('getManagedCount')->never(); + $pool->expects('getIdleCount')->never(); + $pool->expects('getWaitingCount')->never(); + $pool->expects('getStats')->never(); + $databasePools = Double::for(DatabasePoolManager::class)->strict(); + $databasePools->expects('getPools')->returns(['primary' => $pool]); + $redisPools = Double::for(RedisPoolManager::class)->strict(); + $redisPools->expects('getPools')->returns([]); + $objectPools = Double::for(ObjectPoolManager::class)->strict(); + $objectPools->expects('getPools')->never(); $instrumentation = $this->instrumentation($databasePools, $redisPools, $objectPools); $instrumentation->register($this->options( @@ -272,15 +273,15 @@ public function testIndividualConnectionMetricsReadOnlyTheirRequiredSourceValues public function testIndividualObjectMetricsReadOnlyTheirRequiredSourceValues(): void { - $objectPool = m::mock(ObjectPool::class); - $objectPool->shouldReceive('getOptions')->once()->andReturn(PoolOptions::fromArray(['max_objects' => 7])); - $objectPool->shouldNotReceive('getStats'); - $objectPools = m::mock(ObjectPoolManager::class); - $objectPools->shouldReceive('getPools')->once()->andReturn(['app:bounded' => $objectPool]); - $databasePools = m::mock(DatabasePoolManager::class); - $databasePools->shouldNotReceive('getPools'); - $redisPools = m::mock(RedisPoolManager::class); - $redisPools->shouldNotReceive('getPools'); + $objectPool = Double::for(ObjectPool::class)->strict(); + $objectPool->expects('getOptions')->returns(PoolOptions::fromArray(['max_objects' => 7])); + $objectPool->expects('getStats')->never(); + $objectPools = Double::for(ObjectPoolManager::class)->strict(); + $objectPools->expects('getPools')->returns(['app:bounded' => $objectPool]); + $databasePools = Double::for(DatabasePoolManager::class)->strict(); + $databasePools->expects('getPools')->never(); + $redisPools = Double::for(RedisPoolManager::class)->strict(); + $redisPools->expects('getPools')->never(); $instrumentation = $this->instrumentation($databasePools, $redisPools, $objectPools); $instrumentation->register($this->options(enabled: ['hypervel.object_pool.limit'])); @@ -294,12 +295,12 @@ public function testIndividualObjectMetricsReadOnlyTheirRequiredSourceValues(): public function testBoundCallbacksStopCollectingAfterTheInstrumentationIsDestroyed(): void { - $databasePools = m::mock(DatabasePoolManager::class); - $databasePools->shouldReceive('getPools')->once()->andReturn([]); - $redisPools = m::mock(RedisPoolManager::class); - $redisPools->shouldReceive('getPools')->once()->andReturn([]); - $objectPools = m::mock(ObjectPoolManager::class); - $objectPools->shouldNotReceive('getPools'); + $databasePools = Double::for(DatabasePoolManager::class)->strict(); + $databasePools->expects('getPools')->returns([]); + $redisPools = Double::for(RedisPoolManager::class)->strict(); + $redisPools->expects('getPools')->returns([]); + $objectPools = Double::for(ObjectPoolManager::class)->strict(); + $objectPools->expects('getPools')->never(); $instrumentation = $this->instrumentation($databasePools, $redisPools, $objectPools); $reference = WeakReference::create($instrumentation); $instrumentation->register($this->options(enabled: [ @@ -316,10 +317,10 @@ public function testBoundCallbacksStopCollectingAfterTheInstrumentationIsDestroy public function testRemovedObjectPoolDisappearsFromTheNextCollection(): void { - $databasePools = m::mock(DatabasePoolManager::class); - $databasePools->shouldNotReceive('getPools'); - $redisPools = m::mock(RedisPoolManager::class); - $redisPools->shouldNotReceive('getPools'); + $databasePools = Double::for(DatabasePoolManager::class)->strict(); + $databasePools->expects('getPools')->never(); + $redisPools = Double::for(RedisPoolManager::class)->strict(); + $redisPools->expects('getPools')->never(); $objectPools = new ObjectPoolManager; $objectPools->pool('app:ephemeral', static fn (): object => new PoolMetricObject); $instrumentation = $this->instrumentation($databasePools, $redisPools, $objectPools); @@ -358,11 +359,11 @@ private function instrumentation( */ private function connectionPool(int $current, int $idle, int $max, int $waiters): ConnectionPool { - $pool = m::mock(ConnectionPool::class); - $pool->shouldReceive('getManagedCount')->once()->andReturn($current); - $pool->shouldReceive('getIdleCount')->once()->andReturn($idle); - $pool->shouldReceive('getOptions')->once()->andReturn(ConnectionPoolOptions::fromArray(['max_connections' => $max])); - $pool->shouldReceive('getWaitingCount')->once()->andReturn($waiters); + $pool = Double::for(ConnectionPool::class)->strict(); + $pool->expects('getManagedCount')->returns($current); + $pool->expects('getIdleCount')->returns($idle); + $pool->expects('getOptions')->returns(ConnectionPoolOptions::fromArray(['max_connections' => $max])); + $pool->expects('getWaitingCount')->returns($waiters); return $pool; } diff --git a/tests/OpenTelemetry/Instrumentation/QueueInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/QueueInstrumentationTest.php index 91bca5a446..04d3eb61ec 100644 --- a/tests/OpenTelemetry/Instrumentation/QueueInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/QueueInstrumentationTest.php @@ -35,8 +35,9 @@ use Hypervel\Queue\TimeoutExceededException; use Hypervel\Tests\OpenTelemetry\Fixtures\CapturingAlwaysOffSampler; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use OpenTelemetry\API\Common\Time\ClockInterface; use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator; use OpenTelemetry\API\Trace\Span; @@ -77,6 +78,8 @@ class QueueInstrumentationTest extends TestCase { + use VerifiesDoubles; + private const string SENT_MESSAGES_METRIC = 'messaging.client.sent.messages'; private const string SEND_DURATION_METRIC = 'messaging.client.operation.duration'; @@ -874,8 +877,8 @@ public function testPropagationOnlySyncConsumerUsesAmbientContextWithoutExtracti 'propagation' => true, 'metrics' => false, ])); - $job = m::mock(Job::class); - $job->shouldNotReceive('payload'); + $job = Double::for(Job::class)->strict(); + $job->expects('payload')->never(); $ambient = Context::getCurrent(); $this->events->dispatch(new JobProcessing('sync', $job)); @@ -1131,13 +1134,13 @@ public function testOutboxMetricsCountAcceptanceAndSettlementFailuresWithoutASec public function testDepthCollectionRunsOnlyInEventWorkerZeroAndIsolatesBackendFailures(): void { - $queues = m::mock(QueueManager::class); - $failedQueue = m::mock(QueueContract::class); - $healthyQueue = m::mock(QueueContract::class); - $queues->shouldReceive('connection')->twice()->with('failed')->andReturn($failedQueue); - $queues->shouldReceive('connection')->twice()->with('redis')->andReturn($healthyQueue); - $failedQueue->shouldReceive('size')->twice()->with('bad')->andThrow(new RuntimeException('Unavailable.')); - $healthyQueue->shouldReceive('size')->twice()->with('emails')->andReturn(7); + $queues = Double::for(QueueManager::class)->strict(); + $failedQueue = Double::for(QueueContract::class)->strict(); + $healthyQueue = Double::for(QueueContract::class)->strict(); + $queues->expects('connection')->times(2)->with('failed')->returns($failedQueue); + $queues->expects('connection')->times(2)->with('redis')->returns($healthyQueue); + $failedQueue->expects('size')->times(2)->with('bad')->throws(new RuntimeException('Unavailable.')); + $healthyQueue->expects('size')->times(2)->with('emails')->returns(7); $this->instrumentation(queues: $queues)->register($this->options([ 'traces' => false, 'propagation' => false, @@ -1166,8 +1169,8 @@ public function testDepthCollectionRunsOnlyInEventWorkerZeroAndIsolatesBackendFa public function testDepthCollectionRegistersNothingOutsideEventWorkerZero(): void { - $queues = m::mock(QueueManager::class); - $queues->shouldNotReceive('connection'); + $queues = Double::for(QueueManager::class)->strict(); + $queues->expects('connection')->never(); $this->instrumentation( queues: $queues, identity: ProcessIdentity::eventWorker(1), @@ -1192,13 +1195,13 @@ private function instrumentation( ?QueueManager $queues = null, ?ProcessIdentity $identity = null, ): QueueInstrumentationTestInstrumentation { - $logContextScopes = m::mock(LogContextScopeFactory::class); - $logContextScopes->shouldReceive('activate')->zeroOrMoreTimes()->andReturnNull(); + $logContextScopes = Double::for(LogContextScopeFactory::class)->strict(); + $logContextScopes->allows('activate')->returns(null); return new QueueInstrumentationTestInstrumentation( $this->events, $configuration ?? $this->configuration(), - $queues ?? m::mock(QueueManager::class), + $queues ?? Double::for(QueueManager::class)->strict(), $this->tracerProvider, $this->meterProvider, $this->clock, @@ -1254,11 +1257,11 @@ private function payload(string $uuid = 'job-uuid'): string private function job(string $payload, string $queue = 'emails'): Job { $decoded = json_decode($payload, true, flags: JSON_THROW_ON_ERROR); - $job = m::mock(Job::class); - $job->shouldReceive('payload')->zeroOrMoreTimes()->andReturn($decoded); - $job->shouldReceive('getQueue')->zeroOrMoreTimes()->andReturn($queue); - $job->shouldReceive('uuid')->zeroOrMoreTimes()->andReturn($decoded['uuid'] ?? null); - $job->shouldReceive('getRawBody')->zeroOrMoreTimes()->andReturn($payload); + $job = Double::for(Job::class)->strict(); + $job->allows('payload')->returns($decoded); + $job->allows('getQueue')->returns($queue); + $job->allows('uuid')->returns($decoded['uuid'] ?? null); + $job->allows('getRawBody')->returns($payload); return $job; } diff --git a/tests/OpenTelemetry/Instrumentation/RedisInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/RedisInstrumentationTest.php index ef285d9ae1..daf0c2547f 100644 --- a/tests/OpenTelemetry/Instrumentation/RedisInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/RedisInstrumentationTest.php @@ -19,7 +19,8 @@ use Hypervel\Redis\RedisConnection; use Hypervel\Redis\RedisManager; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Common\Time\ClockInterface; use OpenTelemetry\API\Trace\Span; use OpenTelemetry\API\Trace\SpanKind; @@ -49,6 +50,8 @@ class RedisInstrumentationTest extends TestCase { + use VerifiesDoubles; + private ContextStorageInterface&ExecutionContextAwareInterface $previousStorage; private Dispatcher $events; @@ -372,17 +375,11 @@ private function instrumentation( int $resolverCalls = 1, int $enableEventCalls = 1, ): RedisInstrumentation { - $openTelemetryManager = m::mock(OpenTelemetryManager::class); - $expectation = $openTelemetryManager->shouldReceive('redisQueryTextResolver'); - - if ($resolverCalls === 0) { - $expectation->never(); - } else { - $expectation->times($resolverCalls)->andReturn($resolver); - } + $openTelemetryManager = Double::for(OpenTelemetryManager::class)->strict(); + $openTelemetryManager->expects('redisQueryTextResolver')->times($resolverCalls)->returns($resolver); - $redisManager = m::mock(RedisManager::class); - $redisManager->shouldReceive('enableEvents')->times($enableEventCalls); + $redisManager = Double::for(RedisManager::class)->strict(); + $redisManager->expects('enableEvents')->times($enableEventCalls); return new RedisInstrumentation( $this->events, @@ -403,8 +400,8 @@ private function instrumentation( */ private function connection(string $name = 'primary'): RedisConnection { - $connection = m::mock(RedisConnection::class); - $connection->shouldReceive('getName')->once()->andReturn($name); + $connection = Double::for(RedisConnection::class)->strict(); + $connection->expects('getName')->returns($name); return $connection; } diff --git a/tests/OpenTelemetry/Instrumentation/RuntimeInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/RuntimeInstrumentationTest.php index f68fa1e0a4..99f4339771 100644 --- a/tests/OpenTelemetry/Instrumentation/RuntimeInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/RuntimeInstrumentationTest.php @@ -8,7 +8,8 @@ use Hypervel\OpenTelemetry\Instrumentation\RuntimeInstrumentation; use Hypervel\OpenTelemetry\Support\ProcessIdentity; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Metrics\MeterProviderInterface; use OpenTelemetry\SDK\Metrics\Data\Gauge; use OpenTelemetry\SDK\Metrics\Data\Metric; @@ -23,6 +24,8 @@ class RuntimeInstrumentationTest extends TestCase { + use VerifiesDoubles; + private const array METRICS = [ 'php.memory.usage', 'php.memory.peak_usage', @@ -91,9 +94,9 @@ public function testRecordsAvailablePhpRuntimeMetricsFromCollectionTimeSnapshots 'process.context_switches', 'hypervel.worker.coroutines', ]; - $container = m::mock(Container::class); - $container->shouldNotReceive('make'); - $this->instrumentation($container, ProcessIdentity::cli())->register($this->options($enabled)); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->never(); + $this->instrumentation($container->instance(), ProcessIdentity::cli())->register($this->options($enabled)); $metrics = $this->collect(); @@ -128,8 +131,8 @@ public function testRecordsAvailablePhpRuntimeMetricsFromCollectionTimeSnapshots public function testEventWorkerZeroResolvesServerOnceAndRecordsOneSnapshotPerCollection(): void { $snapshotCount = 0; - $server = m::mock(Server::class); - $server->shouldReceive('stats')->andReturnUsing( + $server = Double::for(Server::class)->strict(); + $server->allows('stats')->resolves( static function () use (&$snapshotCount): array { ++$snapshotCount; @@ -142,8 +145,8 @@ static function () use (&$snapshotCount): array { ]; }, ); - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with(Server::class)->andReturn($server); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(Server::class)->returns($server); $enabled = [ 'hypervel.server.connections', 'hypervel.server.requests', @@ -151,7 +154,7 @@ static function () use (&$snapshotCount): array { 'hypervel.server.task_queue.size', 'hypervel.worker.requests', ]; - $this->instrumentation($container, ProcessIdentity::eventWorker(0)) + $this->instrumentation($container->instance(), ProcessIdentity::eventWorker(0)) ->register($this->options($enabled)); $metrics = $this->collect(); @@ -168,14 +171,14 @@ static function () use (&$snapshotCount): array { public function testOtherServerWorkersRecordOnlyTheirWorkerLocalRequestCount(): void { - $server = m::mock(Server::class); - $server->shouldReceive('stats')->andReturn([ + $server = Double::for(Server::class)->strict(); + $server->allows('stats')->returns([ 'connection_num' => 11, 'request_count' => 120, 'worker_request_count' => 7, ]); - $container = m::mock(Container::class); - $container->shouldReceive('make')->with(Server::class)->andReturn($server); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('make')->with(Server::class)->returns($server); $enabled = [ 'hypervel.server.connections', 'hypervel.server.requests', @@ -183,7 +186,7 @@ public function testOtherServerWorkersRecordOnlyTheirWorkerLocalRequestCount(): 'hypervel.server.task_queue.size', 'hypervel.worker.requests', ]; - $this->instrumentation($container, ProcessIdentity::taskWorker(1)) + $this->instrumentation($container->instance(), ProcessIdentity::taskWorker(1)) ->register($this->options($enabled)); $metrics = $this->collect(); @@ -194,8 +197,8 @@ public function testOtherServerWorkersRecordOnlyTheirWorkerLocalRequestCount(): public function testOpcacheMetricsExistOnlyWhenOpcacheIsActiveInEventWorkerZero(): void { - $container = m::mock(Container::class); - $container->shouldNotReceive('make'); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->never(); $enabled = [ 'php.opcache.memory_used', 'php.opcache.memory_free', @@ -208,7 +211,7 @@ public function testOpcacheMetricsExistOnlyWhenOpcacheIsActiveInEventWorkerZero( 'php.opcache.interned_strings.memory_free', 'php.opcache.interned_strings.count', ]; - $this->instrumentation($container, ProcessIdentity::eventWorker(0)) + $this->instrumentation($container->instance(), ProcessIdentity::eventWorker(0)) ->register($this->options($enabled)); $metrics = $this->collect(); @@ -219,18 +222,16 @@ public function testOpcacheMetricsExistOnlyWhenOpcacheIsActiveInEventWorkerZero( public function testDisabledMetricsDoNotResolveTheMeterOrServer(): void { - $container = m::mock(Container::class); - $container->shouldNotReceive('make'); - $meterProvider = m::mock(MeterProviderInterface::class); - $meterProvider->shouldNotReceive('getMeter'); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->never(); + $meterProvider = Double::for(MeterProviderInterface::class)->strict(); + $meterProvider->expects('getMeter')->never(); (new RuntimeInstrumentation( - $container, + $container->instance(), $meterProvider, ProcessIdentity::eventWorker(0), ))->register($this->options([])); - - $this->addToAssertionCount(1); } #[DataProvider('metricProvider')] @@ -241,23 +242,23 @@ public function testEachMetricSwitchCreatesOnlyItsOwnInstrument(string $name): v $processIdentity = $usesServer || str_starts_with($name, 'php.opcache.') ? ProcessIdentity::eventWorker(0) : ProcessIdentity::cli(); - $container = m::mock(Container::class); + $container = Double::for(Container::class, override: true)->strict(); if ($usesServer) { - $server = m::mock(Server::class); - $server->shouldReceive('stats')->andReturn([ + $server = Double::for(Server::class)->strict(); + $server->allows('stats')->returns([ 'connection_num' => 1, 'request_count' => 1, 'tasking_num' => 1, 'task_queue_num' => 1, 'worker_request_count' => 1, ]); - $container->shouldReceive('make')->with(Server::class)->andReturn($server); + $container->allows('make')->with(Server::class)->returns($server); } else { - $container->shouldNotReceive('make'); + $container->expects('make')->never(); } - $this->instrumentation($container, $processIdentity) + $this->instrumentation($container->instance(), $processIdentity) ->register($this->options([$name])); $metrics = $this->collect(); diff --git a/tests/OpenTelemetry/Instrumentation/SchedulerInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/SchedulerInstrumentationTest.php index e7951beaac..642df7ccdd 100644 --- a/tests/OpenTelemetry/Instrumentation/SchedulerInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/SchedulerInstrumentationTest.php @@ -21,7 +21,8 @@ use Hypervel\OpenTelemetry\Support\ProcessIdentity; use Hypervel\Tests\OpenTelemetry\Fixtures\CapturingAlwaysOffSampler; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Common\Time\ClockInterface; use OpenTelemetry\API\Trace\Span; use OpenTelemetry\API\Trace\SpanContext; @@ -53,6 +54,8 @@ class SchedulerInstrumentationTest extends TestCase { + use VerifiesDoubles; + private const string DURATION_METRIC = 'hypervel.scheduler.task.duration'; private const string EXECUTIONS_METRIC = 'hypervel.scheduler.task.executions'; @@ -360,8 +363,8 @@ function () use ($task): string { */ private function instrumentation(): SchedulerInstrumentation { - $logContextScopes = m::mock(LogContextScopeFactory::class); - $logContextScopes->shouldReceive('activate')->zeroOrMoreTimes()->andReturnNull(); + $logContextScopes = Double::for(LogContextScopeFactory::class)->strict(); + $logContextScopes->allows('activate')->returns(null); return new SchedulerInstrumentation( $this->events, diff --git a/tests/OpenTelemetry/Instrumentation/ScoutInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/ScoutInstrumentationTest.php index c9911ef2b5..737958db5a 100644 --- a/tests/OpenTelemetry/Instrumentation/ScoutInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/ScoutInstrumentationTest.php @@ -13,7 +13,8 @@ use Hypervel\Scout\EngineOperationRunner; use Hypervel\Tests\OpenTelemetry\Fixtures\CapturingAlwaysOffSampler; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Common\Time\ClockInterface; use OpenTelemetry\API\Trace\Span; use OpenTelemetry\API\Trace\SpanKind; @@ -45,6 +46,8 @@ class ScoutInstrumentationTest extends TestCase { + use VerifiesDoubles; + private ContextStorageInterface&ExecutionContextAwareInterface $previousStorage; private EngineOperationRunner $operations; @@ -348,8 +351,8 @@ private function registerInstrumentation(bool $traces = true, bool $duration = t */ private function instrumentation(): ScoutInstrumentation { - $logContextScopes = m::mock(LogContextScopeFactory::class); - $logContextScopes->shouldReceive('activate')->zeroOrMoreTimes()->andReturnNull(); + $logContextScopes = Double::for(LogContextScopeFactory::class)->strict(); + $logContextScopes->allows('activate')->returns(null); return new ScoutInstrumentation( $this->operations, diff --git a/tests/OpenTelemetry/Instrumentation/ViewInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/ViewInstrumentationTest.php index 8f1d1f9bb0..5fbf5e03ec 100644 --- a/tests/OpenTelemetry/Instrumentation/ViewInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/ViewInstrumentationTest.php @@ -13,7 +13,10 @@ use Hypervel\Tests\OpenTelemetry\Fixtures\CapturingAlwaysOffSampler; use Hypervel\Tests\TestCase; use Hypervel\View\Factory; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use OpenTelemetry\API\Common\Time\ClockInterface; use OpenTelemetry\API\Trace\Span; use OpenTelemetry\API\Trace\SpanKind; @@ -41,11 +44,13 @@ class ViewInstrumentationTest extends TestCase { + use VerifiesDoubles; + private const string DURATION_METRIC = 'hypervel.view.render.duration'; private ContextStorageInterface&ExecutionContextAwareInterface $previousStorage; - private Factory $views; + private Factory&DoubleInterface $views; private Closure $renderingObserver; @@ -73,7 +78,7 @@ protected function setUp(): void protected function setUpInCoroutine(): void { Context::setStorage(new CoroutineContextStorage(Context::getRoot())); - $this->views = m::mock(Factory::class); + $this->views = Double::for(Factory::class)->strict(); $this->clock = new ViewInstrumentationTestClock; $this->spanExporter = new InMemorySpanExporter(new ArrayObject); $this->tracerProvider = TracerProvider::builder() @@ -101,8 +106,8 @@ protected function tearDown(): void public function testRegistersNoObserversWhenEveryOutputIsDisabled(): void { - $this->views->shouldNotReceive('observeRendering'); - $this->views->shouldNotReceive('observeRendered'); + $this->views->expects('observeRendering')->never(); + $this->views->expects('observeRendered')->never(); $this->instrumentation()->register($this->options(traces: false, duration: false)); @@ -291,19 +296,15 @@ public function testViewIdentityIsAvailableToTheSampler(): void */ private function registerInstrumentation(bool $traces = true, bool $duration = true): void { - $this->views->shouldReceive('observeRendering') - ->once() - ->withArgs(function (Closure $observer): bool { + $this->views->expects('observeRendering') + ->with(Argument::type(Closure::class)) + ->resolves(function (Closure $observer): void { $this->renderingObserver = $observer; - - return true; }); - $this->views->shouldReceive('observeRendered') - ->once() - ->withArgs(function (Closure $observer): bool { + $this->views->expects('observeRendered') + ->with(Argument::type(Closure::class)) + ->resolves(function (Closure $observer): void { $this->renderedObserver = $observer; - - return true; }); $this->instrumentation()->register($this->options($traces, $duration)); @@ -314,8 +315,8 @@ private function registerInstrumentation(bool $traces = true, bool $duration = t */ private function instrumentation(): ViewInstrumentation { - $logContextScopes = m::mock(LogContextScopeFactory::class); - $logContextScopes->shouldReceive('activate')->zeroOrMoreTimes()->andReturnNull(); + $logContextScopes = Double::for(LogContextScopeFactory::class)->strict(); + $logContextScopes->allows('activate')->returns(null); return new ViewInstrumentation( $this->views, @@ -344,8 +345,8 @@ private function options(bool $traces = true, bool $duration = true): array */ private function view(string $name, int $calls = 1): ViewContract { - $view = m::mock(ViewContract::class); - $view->shouldReceive('name')->times($calls)->andReturn($name); + $view = Double::for(ViewContract::class)->strict(); + $view->expects('name')->times($calls)->returns($name); return $view; } diff --git a/tests/OpenTelemetry/Instrumentation/WebSocketInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/WebSocketInstrumentationTest.php index 8788cc4597..fc17d02ffe 100644 --- a/tests/OpenTelemetry/Instrumentation/WebSocketInstrumentationTest.php +++ b/tests/OpenTelemetry/Instrumentation/WebSocketInstrumentationTest.php @@ -16,7 +16,8 @@ use Hypervel\WebSocketServer\Events\ConnectionOpened; use Hypervel\WebSocketServer\Events\MessageHandled; use Hypervel\WebSocketServer\Events\MessageReceived; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\API\Common\Time\ClockInterface; use OpenTelemetry\API\Trace\Span; use OpenTelemetry\API\Trace\SpanKind; @@ -48,6 +49,8 @@ class WebSocketInstrumentationTest extends TestCase { + use VerifiesDoubles; + private const string DURATION_METRIC = 'hypervel.websocket.message.duration'; private const string MESSAGES_METRIC = 'hypervel.websocket.messages'; @@ -373,8 +376,8 @@ public function testActiveConnectionsAloneUsesOnlyConnectionEvents(): void */ private function instrumentation(): WebSocketInstrumentation { - $logContextScopes = m::mock(LogContextScopeFactory::class); - $logContextScopes->shouldReceive('activate')->zeroOrMoreTimes()->andReturnNull(); + $logContextScopes = Double::for(LogContextScopeFactory::class)->strict(); + $logContextScopes->allows('activate')->returns(null); return new WebSocketInstrumentation( $this->events, diff --git a/tests/OpenTelemetry/Logging/OpenTelemetryHandlerTest.php b/tests/OpenTelemetry/Logging/OpenTelemetryHandlerTest.php index dbddd8f78c..ccafa6b533 100644 --- a/tests/OpenTelemetry/Logging/OpenTelemetryHandlerTest.php +++ b/tests/OpenTelemetry/Logging/OpenTelemetryHandlerTest.php @@ -14,7 +14,10 @@ use Hypervel\OpenTelemetry\OpenTelemetryManager; use Hypervel\OpenTelemetry\Support\ExceptionContextRegistry; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\OverriddenDouble; use Monolog\Level; use Monolog\LogRecord; use OpenTelemetry\API\Logs\Severity; @@ -35,17 +38,19 @@ class OpenTelemetryHandlerTest extends TestCase { + use VerifiesDoubles; + private ContextStorageInterface&ExecutionContextAwareInterface $previousStorage; private ArrayObject $records; private LoggerProvider $loggerProvider; - private OpenTelemetryManager $manager; + private OpenTelemetryManager&DoubleInterface $manager; private ExceptionContextRegistry $exceptionContexts; - private Container $container; + private OverriddenDouble $container; protected function setUp(): void { @@ -61,9 +66,9 @@ protected function setUpInCoroutine(): void $this->loggerProvider = (new LoggerProviderBuilder) ->addLogRecordProcessor(new SimpleLogRecordProcessor(new InMemoryExporter($this->records))) ->build(); - $this->manager = m::mock(OpenTelemetryManager::class); + $this->manager = Double::for(OpenTelemetryManager::class)->strict(); $this->exceptionContexts = new ExceptionContextRegistry; - $this->container = m::mock(Container::class); + $this->container = Double::for(Container::class, override: true)->strict(); } protected function tearDownInCoroutine(): void @@ -80,7 +85,7 @@ protected function tearDown(): void public function testDisabledSignalReturnsImmediatelyAndContinuesBubbling(): void { - $this->manager->shouldReceive('logsEnabled')->twice()->andReturnFalse(); + $this->manager->expects('logsEnabled')->times(2)->returns(false); $handler = $this->handler(); $record = $this->record(); @@ -92,8 +97,8 @@ public function testDisabledSignalReturnsImmediatelyAndContinuesBubbling(): void public function testItPreservesStructuredRecordFieldsAndCurrentTraceContext(): void { - $this->manager->shouldReceive('logsEnabled')->once()->andReturnTrue(); - $this->container->shouldNotReceive('make'); + $this->manager->expects('logsEnabled')->returns(true); + $this->container->expects('make')->never(); $handler = $this->handler(); $spanContext = SpanContext::create( '1234567890abcdef1234567890abcdef', @@ -140,8 +145,8 @@ public function testItPreservesStructuredRecordFieldsAndCurrentTraceContext(): v public function testOrdinaryExceptionContextBecomesStandardExceptionAttributes(): void { - $this->manager->shouldReceive('logsEnabled')->once()->andReturnTrue(); - $this->container->shouldNotReceive('make'); + $this->manager->expects('logsEnabled')->returns(true); + $this->container->expects('make')->never(); $exception = new RuntimeException('Application failed.'); $this->handler()->handle($this->record(context: [ @@ -159,17 +164,16 @@ public function testOrdinaryExceptionContextBecomesStandardExceptionAttributes() public function testItSuppressesOnlyTheExactExceptionBeingDirectlyReported(): void { - $this->manager->shouldReceive('logsEnabled')->twice()->andReturnTrue(); + $this->manager->expects('logsEnabled')->times(2)->returns(true); $this->exceptionContexts->markRecorderRegistered(); $reported = new RuntimeException('Reported.'); $other = new RuntimeException('Other.'); - $exceptionHandler = m::mock(ExceptionHandler::class); - $exceptionHandler->shouldReceive('isReporting')->once()->with($reported)->andReturnTrue(); - $exceptionHandler->shouldReceive('isReporting')->once()->with($other)->andReturnFalse(); - $this->container->shouldReceive('make') - ->once() + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); + $exceptionHandler->expects('isReporting')->with($reported)->returns(true); + $exceptionHandler->expects('isReporting')->with($other)->returns(false); + $this->container->expects('make') ->with(ExceptionHandlerContract::class) - ->andReturn($exceptionHandler); + ->returns($exceptionHandler); $handler = $this->handler(); $this->assertFalse($handler->handle($this->record(context: ['exception' => $reported]))); @@ -182,7 +186,7 @@ public function testItSuppressesOnlyTheExactExceptionBeingDirectlyReported(): vo public function testConfiguredLevelStillFiltersRecords(): void { - $this->manager->shouldReceive('logsEnabled')->twice()->andReturnTrue(); + $this->manager->expects('logsEnabled')->times(2)->returns(true); $handler = $this->handler(Level::Error); $this->assertFalse($handler->isHandling($this->record(level: Level::Info))); @@ -198,7 +202,7 @@ private function handler(int|string|Level $level = Level::Debug): OpenTelemetryH $this->loggerProvider->getLogger('application'), $this->manager, $this->exceptionContexts, - $this->container, + $this->container->instance(), new AttributeValidator, $level, ); diff --git a/tests/OpenTelemetry/OpenTelemetryLifecycleNonCoroutineTest.php b/tests/OpenTelemetry/OpenTelemetryLifecycleNonCoroutineTest.php index d0d9161434..18fcdec0aa 100644 --- a/tests/OpenTelemetry/OpenTelemetryLifecycleNonCoroutineTest.php +++ b/tests/OpenTelemetry/OpenTelemetryLifecycleNonCoroutineTest.php @@ -12,27 +12,31 @@ use Hypervel\OpenTelemetry\Support\ExportScheduler; use Hypervel\OpenTelemetry\Support\ProcessIdentity; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use function Hypervel\Coroutine\run; class OpenTelemetryLifecycleNonCoroutineTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; public function testNonCoroutineCommandDoesNotPreventNestedCoroutineScheduling(): void { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->twice()->andReturn(false, true); - $manager->shouldReceive('bind')->once()->withArgs( + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->times(2)->returns(false, true); + $manager->expects('bind')->with(Argument::satisfies( static fn (ProcessIdentity $identity): bool => $identity->type === ProcessIdentity::CLI, - ); - $scheduler = m::mock(ExportScheduler::class); - $scheduler->shouldReceive('start')->once(); - $scheduler->shouldReceive('stop')->once(); - $scheduler->shouldReceive('shutdown')->once()->andReturnTrue(); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('listen')->once()->with(Terminating::class, m::type('callable')); + )); + $scheduler = Double::for(ExportScheduler::class)->strict(); + $scheduler->expects('start'); + $scheduler->expects('stop'); + $scheduler->expects('shutdown')->returns(true); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('listen')->with(Terminating::class, Argument::type('callable')); $lifecycle = new OpenTelemetryLifecycle( $manager, $scheduler, diff --git a/tests/OpenTelemetry/OpenTelemetryLifecycleTest.php b/tests/OpenTelemetry/OpenTelemetryLifecycleTest.php index d01bc2f217..323bb273fa 100644 --- a/tests/OpenTelemetry/OpenTelemetryLifecycleTest.php +++ b/tests/OpenTelemetry/OpenTelemetryLifecycleTest.php @@ -17,23 +17,27 @@ use Hypervel\ServerProcess\Events\AfterProcessHandle; use Hypervel\ServerProcess\Events\BeforeProcessHandle; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use Swoole\Server; class OpenTelemetryLifecycleTest extends TestCase { + use VerifiesDoubles; + public function testBindsTheCorrectWorkerIdentityAndStartsOneScheduler(): void { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('bind')->once()->withArgs( + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('bind')->with(Argument::satisfies( static fn (ProcessIdentity $identity): bool => $identity->type === ProcessIdentity::TASK && $identity->workerId === 7, - ); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $scheduler = m::mock(ExportScheduler::class); - $scheduler->shouldReceive('start')->once(); - $server = m::mock(Server::class); + )); + $manager->expects('isBound')->returns(true); + $scheduler = Double::for(ExportScheduler::class)->strict(); + $scheduler->expects('start'); + $server = Double::for(Server::class)->strict(); $server->taskworker = true; $this->lifecycle($manager, $scheduler)->startWorker(new AfterWorkerStart($server, 7)); @@ -41,15 +45,15 @@ public function testBindsTheCorrectWorkerIdentityAndStartsOneScheduler(): void public function testBindsAnEventWorkerIdentity(): void { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('bind')->once()->withArgs( + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('bind')->with(Argument::satisfies( static fn (ProcessIdentity $identity): bool => $identity->type === ProcessIdentity::EVENT && $identity->workerId === 3, - ); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $scheduler = m::mock(ExportScheduler::class); - $scheduler->shouldReceive('start')->once(); - $server = m::mock(Server::class); + )); + $manager->expects('isBound')->returns(true); + $scheduler = Double::for(ExportScheduler::class)->strict(); + $scheduler->expects('start'); + $server = Double::for(Server::class)->strict(); $server->taskworker = false; $this->lifecycle($manager, $scheduler)->startWorker(new AfterWorkerStart($server, 3)); @@ -58,12 +62,12 @@ public function testBindsAnEventWorkerIdentity(): void public function testWorkerRetainsShutdownOwnershipAfterRegistrationFailure(): void { $expected = new RuntimeException('Unable to register instrumentation.'); - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('bind')->once()->andThrow($expected); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $scheduler = m::mock(ExportScheduler::class); - $scheduler->shouldReceive('start')->once(); - $server = m::mock(Server::class); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('bind')->throws($expected); + $manager->expects('isBound')->returns(true); + $scheduler = Double::for(ExportScheduler::class)->strict(); + $scheduler->expects('start'); + $server = Double::for(Server::class)->strict(); $server->taskworker = false; try { @@ -76,24 +80,19 @@ public function testWorkerRetainsShutdownOwnershipAfterRegistrationFailure(): vo public function testStandaloneCliBindsOnceAndSharesOneTimerAcrossNestedCommands(): void { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->times(3)->andReturn(false, true, true); - $manager->shouldReceive('bind')->once()->withArgs( + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->times(3)->returns(false, true, true); + $manager->expects('bind')->with(Argument::satisfies( static fn (ProcessIdentity $identity): bool => $identity->type === ProcessIdentity::CLI, - ); - $scheduler = m::mock(ExportScheduler::class); - $scheduler->shouldReceive('start')->once(); - $scheduler->shouldReceive('stop')->once(); - $scheduler->shouldReceive('shutdown')->once()->andReturnTrue(); + )); + $scheduler = Double::for(ExportScheduler::class)->strict(); + $scheduler->expects('start'); + $scheduler->expects('stop'); + $scheduler->expects('shutdown')->returns(true); $terminatingListener = null; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('listen') - ->once() - ->with(Terminating::class, m::on(function (callable $listener) use (&$terminatingListener): bool { - $terminatingListener = $listener; - - return true; - })); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('listen') + ->with(Terminating::class, Argument::capture($terminatingListener)); $lifecycle = $this->lifecycle($manager, $scheduler, events: $events); $lifecycle->startCli(); @@ -110,20 +109,15 @@ public function testStandaloneCliBindsOnceAndSharesOneTimerAcrossNestedCommands( public function testStandaloneCliRetainsShutdownOwnershipAfterRegistrationFailure(): void { $expected = new RuntimeException('Unable to register instrumentation.'); - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->twice()->andReturn(false, true); - $manager->shouldReceive('bind')->once()->andThrow($expected); - $scheduler = m::mock(ExportScheduler::class); - $scheduler->shouldReceive('shutdown')->once()->andReturnTrue(); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->times(2)->returns(false, true); + $manager->expects('bind')->throws($expected); + $scheduler = Double::for(ExportScheduler::class)->strict(); + $scheduler->expects('shutdown')->returns(true); $terminatingListener = null; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('listen') - ->once() - ->with(Terminating::class, m::on(function (callable $listener) use (&$terminatingListener): bool { - $terminatingListener = $listener; - - return true; - })); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('listen') + ->with(Terminating::class, Argument::capture($terminatingListener)); $lifecycle = $this->lifecycle($manager, $scheduler, events: $events); try { @@ -139,20 +133,20 @@ public function testStandaloneCliRetainsShutdownOwnershipAfterRegistrationFailur public function testCoroutineServerProcessBindsItsIdentityAndClosesAtItsOwnBoundary(): void { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('bind')->once()->withArgs( + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('bind')->with(Argument::satisfies( static fn (ProcessIdentity $identity): bool => $identity->type === ProcessIdentity::PROCESS && $identity->processClass === LifecycleProcess::class && $identity->processName === 'telemetry-test' && $identity->processIndex === 2, - ); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $scheduler = m::mock(ExportScheduler::class); - $scheduler->shouldReceive('start')->once(); - $scheduler->shouldReceive('shutdown')->once()->andReturnTrue(); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->once()->with('events')->andReturnFalse(); - $process = new LifecycleProcess($container); + )); + $manager->expects('isBound')->returns(true); + $scheduler = Double::for(ExportScheduler::class)->strict(); + $scheduler->expects('start'); + $scheduler->expects('shutdown')->returns(true); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('bound')->with('events')->returns(false); + $process = new LifecycleProcess($container->instance()); $process->name = 'telemetry-test'; $lifecycle = $this->lifecycle($manager, $scheduler); @@ -162,14 +156,14 @@ public function testCoroutineServerProcessBindsItsIdentityAndClosesAtItsOwnBound public function testNonCoroutineServerProcessDrainsWithoutStartingATimer(): void { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('bind')->once(); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $scheduler = m::mock(ExportScheduler::class); - $scheduler->shouldReceive('shutdown')->once()->andReturnTrue(); - $container = m::mock(Container::class); - $container->shouldReceive('bound')->once()->with('events')->andReturnFalse(); - $process = new LifecycleProcess($container); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('bind'); + $manager->expects('isBound')->returns(true); + $scheduler = Double::for(ExportScheduler::class)->strict(); + $scheduler->expects('shutdown')->returns(true); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('bound')->with('events')->returns(false); + $process = new LifecycleProcess($container->instance()); $process->enableCoroutine = false; $lifecycle = $this->lifecycle($manager, $scheduler); @@ -179,12 +173,12 @@ public function testNonCoroutineServerProcessDrainsWithoutStartingATimer(): void public function testExcludedAndFailedProcessesHaveNoCleanupLifecycle(): void { - $container = m::mock(Container::class); - $container->shouldReceive('bound')->once()->with('events')->andReturnFalse(); - $process = new LifecycleProcess($container); - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->once()->andReturnFalse(); - $scheduler = m::mock(ExportScheduler::class); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('bound')->with('events')->returns(false); + $process = new LifecycleProcess($container->instance()); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->returns(false); + $scheduler = Double::for(ExportScheduler::class)->strict(); $configuration = ['opentelemetry' => ['server_processes' => ['except' => [LifecycleProcess::class]]]]; $lifecycle = $this->lifecycle($manager, $scheduler, $configuration); @@ -192,9 +186,9 @@ public function testExcludedAndFailedProcessesHaveNoCleanupLifecycle(): void $lifecycle->finishProcess(new AfterProcessHandle($process, 0)); $expected = new RuntimeException('Unable to bind process telemetry.'); - $failingManager = m::mock(OpenTelemetryManager::class); - $failingManager->shouldReceive('bind')->once()->andThrow($expected); - $failingManager->shouldReceive('isBound')->once()->andReturnFalse(); + $failingManager = Double::for(OpenTelemetryManager::class)->strict(); + $failingManager->expects('bind')->throws($expected); + $failingManager->expects('isBound')->returns(false); $failingLifecycle = $this->lifecycle($failingManager, $scheduler); try { @@ -209,15 +203,15 @@ public function testExcludedAndFailedProcessesHaveNoCleanupLifecycle(): void public function testProcessRegistrationFailureClosesTheBoundGraph(): void { - $container = m::mock(Container::class); - $container->shouldReceive('bound')->once()->with('events')->andReturnFalse(); - $process = new LifecycleProcess($container); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('bound')->with('events')->returns(false); + $process = new LifecycleProcess($container->instance()); $expected = new RuntimeException('Unable to register instrumentation.'); - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('bind')->once()->andThrow($expected); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $scheduler = m::mock(ExportScheduler::class); - $scheduler->shouldReceive('shutdown')->once()->andReturnTrue(); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('bind')->throws($expected); + $manager->expects('isBound')->returns(true); + $scheduler = Double::for(ExportScheduler::class)->strict(); + $scheduler->expects('shutdown')->returns(true); $lifecycle = $this->lifecycle($manager, $scheduler); try { @@ -243,7 +237,7 @@ private function lifecycle( $manager, $scheduler, new Repository($configuration), - $events ?? m::mock(Dispatcher::class), + $events ?? Double::for(Dispatcher::class)->strict(), ); } } diff --git a/tests/OpenTelemetry/OpenTelemetryManagerTest.php b/tests/OpenTelemetry/OpenTelemetryManagerTest.php index 46eea3b6d2..270a38f869 100644 --- a/tests/OpenTelemetry/OpenTelemetryManagerTest.php +++ b/tests/OpenTelemetry/OpenTelemetryManagerTest.php @@ -23,8 +23,10 @@ use Hypervel\OpenTelemetry\Support\ProcessIdentity; use Hypervel\OpenTelemetry\Support\ProviderSet; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\OverriddenDouble; use LogicException; -use Mockery as m; use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator; use OpenTelemetry\API\Trace\Span; use OpenTelemetry\API\Trace\StatusCode; @@ -45,6 +47,8 @@ class OpenTelemetryManagerTest extends TestCase { + use VerifiesDoubles; + public function testLogsSignalAvailabilityTracksTheBoundProviderLifecycle(): void { [$manager] = $this->manager(); @@ -102,7 +106,7 @@ public function testCustomExporterCreatorIsResolvedOnceAcrossSignals(): void $creatorCalls = 0; [$manager, $exporters, $container] = $this->manager(function (Container $resolvedContainer) use (&$creatorCalls, &$container, &$exporters): ExporterFactory { ++$creatorCalls; - $this->assertSame($container, $resolvedContainer); + $this->assertSame($container->instance(), $resolvedContainer); return $exporters; }); @@ -126,17 +130,13 @@ public function testBindResolvesAndRegistersConfiguredInstrumentationAfterProvid $identity = ProcessIdentity::eventWorker(2); [$manager, , $container] = $this->manager(configuration: $configuration); $instrumentation = new ManagerTestInstrumentation; - $container->shouldReceive('instance') - ->once() - ->with(ProcessIdentity::class, $identity) - ->andReturn($identity); - $container->shouldReceive('make') - ->once() + $container->expects('make') ->with(ManagerTestInstrumentation::class) - ->andReturn($instrumentation); + ->returns($instrumentation); $manager->bind($identity); + $container->received('instance')->with(ProcessIdentity::class, $identity)->times(1); $this->assertSame(['metrics' => true, 'custom' => 'value'], $instrumentation->options); $manager->shutdown(); } @@ -159,13 +159,10 @@ public function testBindRegistersIdentityWithoutInstrumentationsAndRetainsItAfte $configuration['instrumentation'] = []; $identity = ProcessIdentity::cli(); [$manager, , $container, $exceptionContexts] = $this->manager(configuration: $configuration); - $container->shouldReceive('instance') - ->once() - ->with(ProcessIdentity::class, $identity) - ->andReturn($identity); $exceptionContexts->enable(); $manager->bind($identity); + $container->received('instance')->with(ProcessIdentity::class, $identity)->times(1); $manager->shutdown(); $expected = new RuntimeException('failure'); @@ -328,18 +325,12 @@ public function testInstrumentationRegistrationFailureKeepsTheGraphBoundAndOneSh $failingInstrumentation = new FailingManagerTestInstrumentation; $expected = new RuntimeException('Unable to register instrumentation.'); $failingInstrumentation->exception = $expected; - $container->shouldReceive('instance') - ->once() - ->with(ProcessIdentity::class, $identity) - ->andReturn($identity); - $container->shouldReceive('make') - ->once() + $container->expects('make') ->with(ManagerTestInstrumentation::class) - ->andReturn($instrumentation); - $container->shouldReceive('make') - ->once() + ->returns($instrumentation); + $container->expects('make') ->with(FailingManagerTestInstrumentation::class) - ->andReturn($failingInstrumentation); + ->returns($failingInstrumentation); try { $manager->bind($identity); @@ -350,6 +341,7 @@ public function testInstrumentationRegistrationFailureKeepsTheGraphBoundAndOneSh $this->assertTrue($manager->isBound()); $manager->bind($identity); + $container->received('instance')->with(ProcessIdentity::class, $identity)->times(1); $this->assertSame(1, $instrumentation->registrations); $this->assertSame(1, $failingInstrumentation->registrations); $this->assertTrue($manager->shutdown()); @@ -362,12 +354,12 @@ public function testManagerCannotBindASecondLifecycleAfterShutdown(): void $configuration['traces']['processors'] = ['custom.span.processor']; $configuration['logs']['processors'] = ['custom.log.processor']; [$manager, , $container] = $this->manager(configuration: $configuration); - $spanProcessor = m::mock(SpanProcessorInterface::class); - $spanProcessor->shouldReceive('shutdown')->once()->andReturnTrue(); - $logProcessor = m::mock(LogRecordProcessorInterface::class); - $logProcessor->shouldReceive('shutdown')->once()->andReturnTrue(); - $container->shouldReceive('make')->once()->with('custom.span.processor')->andReturn($spanProcessor); - $container->shouldReceive('make')->once()->with('custom.log.processor')->andReturn($logProcessor); + $spanProcessor = Double::for(SpanProcessorInterface::class)->strict(); + $spanProcessor->expects('shutdown')->returns(true); + $logProcessor = Double::for(LogRecordProcessorInterface::class)->strict(); + $logProcessor->expects('shutdown')->returns(true); + $container->expects('make')->with('custom.span.processor')->returns($spanProcessor); + $container->expects('make')->with('custom.log.processor')->returns($logProcessor); $manager->bind(ProcessIdentity::cli()); $manager->shutdown(); @@ -382,17 +374,17 @@ public function testConcurrentManualFlushReturnsFalseWithoutOverlappingTheProvid $flushStarted = new Channel(1); $releaseFlush = new Channel(1); $flushFinished = new Channel(1); - $traces = m::mock(TracerProviderInterface::class); - $traces->shouldReceive('forceFlush')->once()->andReturnUsing( + $traces = Double::for(TracerProviderInterface::class)->strict(); + $traces->expects('forceFlush')->resolves( static function () use ($flushStarted, $releaseFlush): bool { $flushStarted->push(true); return $releaseFlush->pop(1.0) === true; }, ); - $traces->shouldReceive('shutdown')->once()->andReturnTrue(); - $providerFactory = m::mock(ProviderFactory::class); - $providerFactory->shouldReceive('create')->once()->andReturn(new ProviderSet(null, $traces, null)); + $traces->expects('shutdown')->returns(true); + $providerFactory = Double::for(ProviderFactory::class)->strict(); + $providerFactory->expects('create')->returns(new ProviderSet(null, $traces, null)); [$manager] = $this->manager(providerFactory: $providerFactory); $manager->bind(ProcessIdentity::cli()); @@ -412,17 +404,17 @@ public function testShutdownWaitsForAnInflightFlushBeforeClosingProviders(): voi $releaseFlush = new Channel(1); $flushFinished = new Channel(1); $shutdownFinished = new Channel(1); - $traces = m::mock(TracerProviderInterface::class); - $traces->shouldReceive('forceFlush')->once()->andReturnUsing( + $traces = Double::for(TracerProviderInterface::class)->strict(); + $traces->expects('forceFlush')->resolves( static function () use ($flushStarted, $releaseFlush): bool { $flushStarted->push(true); return $releaseFlush->pop(1.0) === true; }, ); - $traces->shouldReceive('shutdown')->once()->andReturnTrue(); - $providerFactory = m::mock(ProviderFactory::class); - $providerFactory->shouldReceive('create')->once()->andReturn(new ProviderSet(null, $traces, null)); + $traces->expects('shutdown')->returns(true); + $providerFactory = Double::for(ProviderFactory::class)->strict(); + $providerFactory->expects('create')->returns(new ProviderSet(null, $traces, null)); [$manager] = $this->manager(providerFactory: $providerFactory); $manager->bind(ProcessIdentity::cli()); @@ -440,27 +432,26 @@ static function () use ($flushStarted, $releaseFlush): bool { /** * Create a manager with recording exporters. * - * @return array{OpenTelemetryManager, ManagerExporterFactory, Container, ExceptionContextRegistry} + * @return array{OpenTelemetryManager, ManagerExporterFactory, OverriddenDouble, ExceptionContextRegistry} */ private function manager( ?callable $creator = null, ?array $configuration = null, ?ProviderFactory $providerFactory = null, ): array { - $container = m::mock(Container::class); - $container->shouldReceive('instance') - ->byDefault() - ->andReturnUsing(static fn (string $abstract, mixed $instance): mixed => $instance); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('instance') + ->resolves(static fn (string $abstract, mixed $instance): mixed => $instance); $exporters = new ManagerExporterFactory; $deferredMetrics = new DeferredMeterProvider; $deferredTraces = new DeferredTracerProvider; $deferredLogs = new DeferredLoggerProvider; $exceptionContexts = new ExceptionContextRegistry; $manager = new OpenTelemetryManager( - $container, + $container->instance(), new Repository(['opentelemetry' => $configuration ?? $this->configuration()]), new ConfigurationNormalizer, - $providerFactory ?? new ProviderFactory($container), + $providerFactory ?? new ProviderFactory($container->instance()), $exceptionContexts, new OperationOrigin, $deferredMetrics, diff --git a/tests/OpenTelemetry/OpenTelemetryServiceProviderTest.php b/tests/OpenTelemetry/OpenTelemetryServiceProviderTest.php index a6a87516cb..ffce906618 100644 --- a/tests/OpenTelemetry/OpenTelemetryServiceProviderTest.php +++ b/tests/OpenTelemetry/OpenTelemetryServiceProviderTest.php @@ -24,7 +24,8 @@ use Hypervel\Support\ServiceProvider; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Monolog\Level; use Monolog\Logger as Monolog; use Monolog\LogRecord; @@ -38,6 +39,8 @@ class OpenTelemetryServiceProviderTest extends TestCase { + use VerifiesDoubles; + protected function getPackageProviders(ApplicationContract $app): array { return [OpenTelemetryServiceProvider::class]; @@ -79,8 +82,8 @@ public function testProviderRegistersProducingProcessLifecycleListeners(): void public function testProviderBindsCliWhenArtisanStartsAfterApplicationBoot(): void { - $lifecycle = m::mock(OpenTelemetryLifecycle::class); - $lifecycle->shouldReceive('startCli')->once(); + $lifecycle = Double::for(OpenTelemetryLifecycle::class)->strict(); + $lifecycle->expects('startCli'); $this->app->instance(OpenTelemetryLifecycle::class, $lifecycle); $this->app->make(ConsoleApplicationContract::class); diff --git a/tests/OpenTelemetry/ProviderFactoryTest.php b/tests/OpenTelemetry/ProviderFactoryTest.php index 128105aee2..7a4c2997e4 100644 --- a/tests/OpenTelemetry/ProviderFactoryTest.php +++ b/tests/OpenTelemetry/ProviderFactoryTest.php @@ -13,7 +13,8 @@ use Hypervel\OpenTelemetry\Support\ProcessIdentity; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OpenTelemetry\SDK\Logs\Exporter\InMemoryExporter as InMemoryLogExporter; use OpenTelemetry\SDK\Logs\LogRecordExporterInterface; use OpenTelemetry\SDK\Metrics\MeterProviderInterface; @@ -33,6 +34,8 @@ class ProviderFactoryTest extends TestCase { + use VerifiesDoubles; + public function testNoneSignalsBuildNoProviderOrExporterGraph(): void { $configuration = $this->configuration(); @@ -41,7 +44,7 @@ public function testNoneSignalsBuildNoProviderOrExporterGraph(): void $configuration['logs']['exporter'] = 'none'; $resolved = false; - $providers = (new ProviderFactory(m::mock(Container::class)))->create( + $providers = (new ProviderFactory(Double::for(Container::class, override: true)->strict()->instance()))->create( (new ConfigurationNormalizer)->normalize($configuration), ProcessIdentity::eventWorker(0), function () use (&$resolved): ExporterFactory { @@ -60,7 +63,7 @@ function () use (&$resolved): ExporterFactory { public function testBuildsProvidersThatExportAllThreeSignals(): void { $exporters = new RecordingExporterFactory; - $providers = (new ProviderFactory(m::mock(Container::class)))->create( + $providers = (new ProviderFactory(Double::for(Container::class, override: true)->strict()->instance()))->create( (new ConfigurationNormalizer)->normalize($this->configuration()), ProcessIdentity::eventWorker(2), static fn (): ExporterFactory => $exporters, @@ -103,7 +106,7 @@ public function testResourceAttributesApplyExplicitPrecedenceAndUniqueProcessIde $configuration['metrics']['exporter'] = 'none'; $configuration['logs']['exporter'] = 'none'; $exporters = new RecordingExporterFactory; - $providers = (new ProviderFactory(m::mock(Container::class)))->create( + $providers = (new ProviderFactory(Double::for(Container::class, override: true)->strict()->instance()))->create( (new ConfigurationNormalizer)->normalize($configuration), ProcessIdentity::taskWorker(5), static fn (): ExporterFactory => $exporters, @@ -137,12 +140,12 @@ public function testCompleteProviderOverrideSkipsThePackageExporterGraph(): void $configuration['metrics']['provider'] = 'custom.metrics'; $configuration['traces']['exporter'] = 'none'; $configuration['logs']['exporter'] = 'none'; - $provider = m::mock(MeterProviderInterface::class); - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with('custom.metrics')->andReturn($provider); + $provider = Double::for(MeterProviderInterface::class)->strict(); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with('custom.metrics')->returns($provider); $resolved = false; - $providers = (new ProviderFactory($container))->create( + $providers = (new ProviderFactory($container->instance()))->create( (new ConfigurationNormalizer)->normalize($configuration), ProcessIdentity::cli(), function () use (&$resolved): ExporterFactory { @@ -162,13 +165,13 @@ public function testProviderOverridesMustImplementTheSdkLifecycleContract(): voi $configuration['metrics']['provider'] = 'invalid.metrics'; $configuration['traces']['exporter'] = 'none'; $configuration['logs']['exporter'] = 'none'; - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with('invalid.metrics')->andReturn(new stdClass); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with('invalid.metrics')->returns(new stdClass); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIsOrContains('must implement [OpenTelemetry\SDK\Metrics\MeterProviderInterface]'); - (new ProviderFactory($container))->create( + (new ProviderFactory($container->instance()))->create( (new ConfigurationNormalizer)->normalize($configuration), ProcessIdentity::cli(), static fn (): ExporterFactory => new RecordingExporterFactory, @@ -180,16 +183,16 @@ public function testResolvesCustomSamplerAndTypedMetricViewsThroughTheContainer( $configuration = $this->configuration(); $configuration['traces']['sampler'] = 'custom.sampler'; $configuration['metrics']['views'] = ['custom.view']; - $sampler = m::mock(SamplerInterface::class); - $view = m::mock(MetricView::class); - $view->shouldReceive('criteria')->once()->andReturn(new InstrumentNameCriteria('original.metric')); - $view->shouldReceive('template')->once()->andReturn(ViewTemplate::create()->withName('renamed.metric')); - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with('custom.view')->andReturn($view); - $container->shouldReceive('make')->once()->with('custom.sampler')->andReturn($sampler); + $sampler = Double::for(SamplerInterface::class)->strict(); + $view = Double::for(MetricView::class)->strict(); + $view->expects('criteria')->returns(new InstrumentNameCriteria('original.metric')); + $view->expects('template')->returns(ViewTemplate::create()->withName('renamed.metric')); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with('custom.view')->returns($view); + $container->expects('make')->with('custom.sampler')->returns($sampler); $exporters = new RecordingExporterFactory; - $providers = (new ProviderFactory($container))->create( + $providers = (new ProviderFactory($container->instance()))->create( (new ConfigurationNormalizer)->normalize($configuration), ProcessIdentity::cli(), static fn (): ExporterFactory => $exporters, @@ -212,7 +215,7 @@ public function testInternalMetricsUseTheActiveMetricsProvider(): void $configuration = $this->configuration(); $configuration['internal_metrics'] = true; $exporters = new RecordingExporterFactory; - $providers = (new ProviderFactory(m::mock(Container::class)))->create( + $providers = (new ProviderFactory(Double::for(Container::class, override: true)->strict()->instance()))->create( (new ConfigurationNormalizer)->normalize($configuration), ProcessIdentity::cli(), static fn (): ExporterFactory => $exporters, @@ -239,14 +242,14 @@ public function testResolvesMetricViewsBeforeCreatingTheExporter(): void $configuration = $this->configuration(); $configuration['metrics']['views'] = ['failing.view']; $expected = new RuntimeException('Unable to build metric view.'); - $view = m::mock(MetricView::class); - $view->shouldReceive('criteria')->once()->andThrow($expected); - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with('failing.view')->andReturn($view); + $view = Double::for(MetricView::class)->strict(); + $view->expects('criteria')->throws($expected); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with('failing.view')->returns($view); $exporterCreated = false; try { - (new ProviderFactory($container))->create( + (new ProviderFactory($container->instance()))->create( (new ConfigurationNormalizer)->normalize($configuration), ProcessIdentity::cli(), function () use (&$exporterCreated): ExporterFactory { diff --git a/tests/OpenTelemetry/Support/ExportSchedulerTest.php b/tests/OpenTelemetry/Support/ExportSchedulerTest.php index 4701a1aea4..74c00e9889 100644 --- a/tests/OpenTelemetry/Support/ExportSchedulerTest.php +++ b/tests/OpenTelemetry/Support/ExportSchedulerTest.php @@ -10,18 +10,21 @@ use Hypervel\OpenTelemetry\OpenTelemetryManager; use Hypervel\OpenTelemetry\Support\ExportScheduler; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Swoole\Coroutine\CanceledException; class ExportSchedulerTest extends TestCase { + use VerifiesDoubles; + public function testUsesOneTimerAtTheSmallestCadenceAndFlushesOnlyDueSignals(): void { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $manager->shouldReceive('configuration')->once()->andReturn($this->configuration()); - $manager->shouldReceive('flushSignals')->once()->with(['logs'])->andReturnTrue(); - $manager->shouldReceive('flushSignals')->once()->with(['traces', 'logs'])->andReturnTrue(); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->returns(true); + $manager->expects('configuration')->returns($this->configuration()); + $manager->expects('flushSignals')->with(['logs'])->returns(true); + $manager->expects('flushSignals')->with(['traces', 'logs'])->returns(true); $timer = new ExportSchedulerTimer; $scheduler = new TestExportScheduler($manager, $timer); @@ -44,20 +47,19 @@ public function testUsesOneTimerAtTheSmallestCadenceAndFlushesOnlyDueSignals(): public function testAdvancesDueTimesPastASlowExportWithoutCatchUpBursts(): void { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $manager->shouldReceive('configuration')->once()->andReturn($this->configuration()); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->returns(true); + $manager->expects('configuration')->returns($this->configuration()); $timer = new ExportSchedulerTimer; $scheduler = new TestExportScheduler($manager, $timer); - $manager->shouldReceive('flushSignals') - ->once() + $manager->expects('flushSignals') ->with(['traces', 'logs']) - ->andReturnUsing(function () use ($scheduler): bool { + ->resolves(function () use ($scheduler): bool { $scheduler->time = 12500; return true; }); - $manager->shouldReceive('flushSignals')->once()->with(['logs'])->andReturnTrue(); + $manager->expects('flushSignals')->with(['logs'])->returns(true); $scheduler->start(); $scheduler->time = 5000; @@ -70,15 +72,14 @@ public function testAdvancesDueTimesPastASlowExportWithoutCatchUpBursts(): void public function testStopDuringAnInFlightExportDoesNotRescheduleClearedCadence(): void { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $manager->shouldReceive('configuration')->once()->andReturn($this->configuration()); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->returns(true); + $manager->expects('configuration')->returns($this->configuration()); $timer = new ExportSchedulerTimer; $scheduler = new TestExportScheduler($manager, $timer); - $manager->shouldReceive('flushSignals') - ->once() + $manager->expects('flushSignals') ->with(['logs']) - ->andReturnUsing(function () use ($scheduler): bool { + ->resolves(function () use ($scheduler): bool { $scheduler->stop(); return true; @@ -93,21 +94,23 @@ public function testStopDuringAnInFlightExportDoesNotRescheduleClearedCadence(): public function testStaleExportDoesNotAdvanceRestartedCadence(): void { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->twice()->andReturnTrue(); - $manager->shouldReceive('configuration')->twice()->andReturn($this->configuration()); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->times(2)->returns(true); + $manager->expects('configuration')->times(2)->returns($this->configuration()); $timer = new ExportSchedulerTimer; $scheduler = new TestExportScheduler($manager, $timer); - $manager->shouldReceive('flushSignals') - ->once() + $flushCalls = 0; + $manager->expects('flushSignals') + ->times(2) ->with(['logs']) - ->andReturnUsing(function () use ($scheduler): bool { - $scheduler->stop(); - $scheduler->start(); + ->resolves(function () use ($scheduler, &$flushCalls): bool { + if (++$flushCalls === 1) { + $scheduler->stop(); + $scheduler->start(); + } return true; }); - $manager->shouldReceive('flushSignals')->once()->with(['logs'])->andReturnTrue(); $scheduler->start(); $scheduler->time = 1000; @@ -126,10 +129,10 @@ public function testStaleExportDoesNotAdvanceRestartedCadence(): void public function testPeriodicContentionSkipsWithoutReportingProviderFailure(): void { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $manager->shouldReceive('configuration')->once()->andReturn($this->configuration()); - $manager->shouldReceive('flushSignals')->once()->with(['logs'])->andReturnNull(); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->returns(true); + $manager->expects('configuration')->returns($this->configuration()); + $manager->expects('flushSignals')->with(['logs'])->returns(null); $timer = new ExportSchedulerTimer; $scheduler = new TestExportScheduler($manager, $timer); $scheduler->start(); @@ -144,10 +147,10 @@ public function testPeriodicContentionSkipsWithoutReportingProviderFailure(): vo public function testPeriodicCancellationEscapesToTheTimerOwner(): void { $cancellation = new CanceledException; - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $manager->shouldReceive('configuration')->once()->andReturn($this->configuration()); - $manager->shouldReceive('flushSignals')->once()->with(['logs'])->andThrow($cancellation); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->returns(true); + $manager->expects('configuration')->returns($this->configuration()); + $manager->expects('flushSignals')->with(['logs'])->throws($cancellation); $timer = new ExportSchedulerTimer; $scheduler = new TestExportScheduler($manager, $timer); $scheduler->start(); @@ -169,9 +172,9 @@ public function testDoesNotStartATimerWithoutAnActiveSignal(): void $configuration['metrics']['exporter'] = 'none'; $configuration['traces']['exporter'] = 'none'; $configuration['logs']['exporter'] = 'none'; - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $manager->shouldReceive('configuration')->once()->andReturn($configuration); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->returns(true); + $manager->expects('configuration')->returns($configuration); $timer = new ExportSchedulerTimer; $scheduler = new TestExportScheduler($manager, $timer); @@ -183,10 +186,10 @@ public function testDoesNotStartATimerWithoutAnActiveSignal(): void public function testClosingTickShutsDownProvidersAndStopsTheTimer(): void { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $manager->shouldReceive('configuration')->once()->andReturn($this->configuration()); - $manager->shouldReceive('shutdown')->once()->andReturnTrue(); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->returns(true); + $manager->expects('configuration')->returns($this->configuration()); + $manager->expects('shutdown')->returns(true); $timer = new ExportSchedulerTimer; $scheduler = new TestExportScheduler($manager, $timer); $scheduler->start(); @@ -199,10 +202,10 @@ public function testClosingTickShutsDownProvidersAndStopsTheTimer(): void public function testClosingCancellationEscapesToTheTimerOwner(): void { $cancellation = new CanceledException; - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $manager->shouldReceive('configuration')->once()->andReturn($this->configuration()); - $manager->shouldReceive('shutdown')->once()->andThrow($cancellation); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->returns(true); + $manager->expects('configuration')->returns($this->configuration()); + $manager->expects('shutdown')->throws($cancellation); $timer = new ExportSchedulerTimer; $scheduler = new TestExportScheduler($manager, $timer); $scheduler->start(); @@ -219,10 +222,10 @@ public function testClosingCancellationEscapesToTheTimerOwner(): void public function testExplicitShutdownClearsTheTimerBeforeClosingProviders(): void { - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('isBound')->once()->andReturnTrue(); - $manager->shouldReceive('configuration')->once()->andReturn($this->configuration()); - $manager->shouldReceive('shutdown')->once()->andReturnTrue(); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('isBound')->returns(true); + $manager->expects('configuration')->returns($this->configuration()); + $manager->expects('shutdown')->returns(true); $timer = new ExportSchedulerTimer; $scheduler = new TestExportScheduler($manager, $timer); $scheduler->start(); diff --git a/tests/OpenTelemetry/Support/UserContextResolverTest.php b/tests/OpenTelemetry/Support/UserContextResolverTest.php index 231e2ca0d5..b5d47a5666 100644 --- a/tests/OpenTelemetry/Support/UserContextResolverTest.php +++ b/tests/OpenTelemetry/Support/UserContextResolverTest.php @@ -12,7 +12,8 @@ use Hypervel\OpenTelemetry\Support\RequestTelemetryState; use Hypervel\OpenTelemetry\Support\UserContextResolver; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -20,19 +21,21 @@ class UserContextResolverTest extends TestCase { + use VerifiesDoubles; + #[TestWith([false], 'direct cancellation')] #[TestWith([true], 'wrapped cancellation')] public function testCustomResolverRethrowsCoroutineCancellation(bool $wrapped): void { $cancellation = $wrapped ? new RuntimeException('Resolver cleanup failed.', previous: new CanceledException) : new CanceledException; - $user = m::mock(Authenticatable::class); - $guard = m::mock(Guard::class); - $guard->shouldReceive('hasUser')->once()->andReturnTrue(); - $guard->shouldReceive('user')->once()->andReturn($user); - $auth = m::mock(Factory::class); - $auth->shouldReceive('guard')->once()->andReturn($guard); - $manager = m::mock(OpenTelemetryManager::class); - $manager->shouldReceive('userResolver')->once()->andReturn( + $user = Double::for(Authenticatable::class)->strict(); + $guard = Double::for(Guard::class)->strict(); + $guard->expects('hasUser')->returns(true); + $guard->expects('user')->returns($user); + $auth = Double::for(Factory::class)->strict(); + $auth->expects('guard')->returns($guard); + $manager = Double::for(OpenTelemetryManager::class)->strict(); + $manager->expects('userResolver')->returns( static fn (): never => throw $cancellation, ); $resolver = new UserContextResolver($auth, $manager); diff --git a/tests/PHPStan/Unit/Internal/ConsoleApplicationResolverTest.php b/tests/PHPStan/Unit/Internal/ConsoleApplicationResolverTest.php index 964e9c7467..ec3d274eb7 100644 --- a/tests/PHPStan/Unit/Internal/ConsoleApplicationResolverTest.php +++ b/tests/PHPStan/Unit/Internal/ConsoleApplicationResolverTest.php @@ -12,28 +12,33 @@ use Hypervel\Tests\PHPStan\Fixtures\Console\WithArgumentCommand; use Hypervel\Tests\PHPStan\Fixtures\Console\WithoutArgumentCommand; use Hypervel\Tests\PHPStan\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPStan\Testing\PHPStanTestCase; use function array_values; class ConsoleApplicationResolverTest extends TestCase { + use VerifiesDoubles; + public function testFindCommandsListsEachRegisteredCommandOnce(): void { $with = new WithArgumentCommand; $without = new WithoutArgumentCommand; - $container = new Container; - $container->instance(Kernel::class, m::mock(Kernel::class, ['all' => [ + $kernel = Double::for(Kernel::class)->strict(); + $kernel->allows('all')->returns([ 'lookup:with' => $with, 'lookup:with-alias' => $with, // A command loader may list a command only under a key other than its own name. 'lookup:without-alias' => $without, - ]])); + ]); + $container = new Container; + $container->instance(Kernel::class, $kernel); $reflectionProvider = PHPStanTestCase::createReflectionProvider(); - $resolver = new ConsoleApplicationResolver($reflectionProvider, m::mock(RuntimeInputs::class)); + $resolver = new ConsoleApplicationResolver($reflectionProvider, Double::for(RuntimeInputs::class)->strict()); $resolver->setContainer($container); $commands = $resolver->findCommands($reflectionProvider->getClass(LookupCommand::class)); diff --git a/tests/PHPStan/Unit/Support/ConfigSourceResolverTest.php b/tests/PHPStan/Unit/Support/ConfigSourceResolverTest.php index f6d16158a1..f5e16db197 100644 --- a/tests/PHPStan/Unit/Support/ConfigSourceResolverTest.php +++ b/tests/PHPStan/Unit/Support/ConfigSourceResolverTest.php @@ -22,7 +22,8 @@ use Hypervel\Tests\PHPStan\Fixtures\Config\Writes\UnpackedCallbackWriteProvider; use Hypervel\Tests\PHPStan\Fixtures\Config\Writes\UnrecognizedFlowProvider; use Hypervel\Tests\PHPStan\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPStan\File\FileHelper; use PHPStan\Testing\PHPStanTestCase; use PHPUnit\Framework\Attributes\DataProvider; @@ -32,6 +33,8 @@ class ConfigSourceResolverTest extends TestCase { + use VerifiesDoubles; + /** * Writes that would leave a key unbounded make every lookup unknown; flows the * static pass leaves to the tracker do not. @@ -66,7 +69,7 @@ public static function providerWrites(): array */ public function testAnonymousProviderWritesAreUnknown(): void { - $provider = new class(m::mock(Application::class)) extends ServiceProvider {}; + $provider = new class(Double::for(Application::class, override: true)->strict()->instance()) extends ServiceProvider {}; $this->assertTrue($this->createResolver($provider::class)->hasUnknownWrites()); } @@ -150,16 +153,16 @@ public function testKeySources(): void */ private function createResolver(string $providerClass): ConfigSourceResolver { - $app = m::mock(Application::class); - $provider = new $providerClass($app); + $app = Double::for(Application::class, override: true)->strict(); + $provider = new $providerClass($app->instance()); - $app->shouldReceive('getProviders')->with(ServiceProvider::class)->andReturn([$providerClass => $provider]); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->andReturn(new ConfigMutationTracker); - $app->shouldReceive('configPath')->andReturn(__DIR__ . '/missing-config'); - $app->shouldReceive('shouldMergeFrameworkConfiguration')->andReturn(true); + $app->allows('getProviders')->with(ServiceProvider::class)->returns([$providerClass => $provider]); + $app->allows('make')->with(ConfigMutationTracker::class)->returns(new ConfigMutationTracker); + $app->allows('configPath')->returns(__DIR__ . '/missing-config'); + $app->allows('shouldMergeFrameworkConfiguration')->returns(true); $container = new Container; - $container->instance(Application::class, $app); + $container->instance(Application::class, $app->instance()); $phpstan = PHPStanTestCase::getContainer(); $resolver = new ConfigSourceResolver( diff --git a/tests/Pagination/PaginationResolverTest.php b/tests/Pagination/PaginationResolverTest.php index 89d83bbc86..332d879459 100644 --- a/tests/Pagination/PaginationResolverTest.php +++ b/tests/Pagination/PaginationResolverTest.php @@ -15,7 +15,8 @@ use Hypervel\Pagination\Paginator; use Hypervel\Support\Stringable; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionProperty; use function Hypervel\Coroutine\parallel; @@ -28,6 +29,8 @@ */ class PaginationResolverTest extends TestCase { + use VerifiesDoubles; + public function testCurrentPageResolverReadsFromRequest(): void { $this->setUpMockRequest(['page' => '3']); @@ -177,7 +180,7 @@ public function testViewFactoryResolverHonorsLazyContainerRebinding(): void { PaginationState::resolveUsing($this->app); - $factory = m::mock(Factory::class); + $factory = Double::for(Factory::class)->strict(); $this->app->instance('view', $factory); $this->assertSame($factory, Paginator::viewFactory()); @@ -244,7 +247,7 @@ function () use ($cursor2): array { public function testFlushStateRestoresEveryStaticPaginationSetting(): void { - $factory = m::mock(Factory::class); + $factory = Double::for(Factory::class)->strict(); $cursor = new Cursor(['id' => 10]); Paginator::currentPathResolver(fn () => '/custom'); diff --git a/tests/Passkeys/Feature/Actions/DeletePasskeyTest.php b/tests/Passkeys/Feature/Actions/DeletePasskeyTest.php index ece261908d..f9eb9e1b53 100644 --- a/tests/Passkeys/Feature/Actions/DeletePasskeyTest.php +++ b/tests/Passkeys/Feature/Actions/DeletePasskeyTest.php @@ -12,10 +12,14 @@ use Hypervel\Support\Facades\Event; use Hypervel\Tests\Passkeys\Fixtures\User; use Hypervel\Tests\Passkeys\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class DeletePasskeyTest extends TestCase { + use VerifiesDoubles; + public function testItDeletesThePasskey(): void { $user = User::create([ @@ -89,12 +93,8 @@ public function testItDoesNotDispatchPasskeyDeletedEventWithoutListeners(): void ]); $passkey = $this->createPasskeyForUser($user, 'credential-quiet-delete'); - $events = m::mock(Dispatcher::class)->shouldIgnoreMissing(); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnFalse()->byDefault(); - $events->shouldReceive('hasListeners')->once()->with(PasskeyDeleted::class)->andReturnFalse(); - $events->shouldReceive('dispatch') - ->withArgs(static fn (mixed $event): bool => $event instanceof PasskeyDeleted) - ->never(); + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(false); $this->instance('events', $events); @@ -103,6 +103,8 @@ public function testItDoesNotDispatchPasskeyDeletedEventWithoutListeners(): void $this->assertDatabaseMissing('passkeys', [ 'id' => $passkey->getKey(), ]); + $events->received('hasListeners')->with(PasskeyDeleted::class)->times(1); + $events->received('dispatch')->with(Argument::type(PasskeyDeleted::class))->never(); } /** diff --git a/tests/Passkeys/Feature/Actions/StorePasskeyTest.php b/tests/Passkeys/Feature/Actions/StorePasskeyTest.php index d7b5e2dea6..a424d0cd81 100644 --- a/tests/Passkeys/Feature/Actions/StorePasskeyTest.php +++ b/tests/Passkeys/Feature/Actions/StorePasskeyTest.php @@ -13,7 +13,8 @@ use Hypervel\Tests\Passkeys\Fixtures\User; use Hypervel\Tests\Passkeys\Fixtures\WebAuthnFixtures; use Hypervel\Tests\Passkeys\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ParagonIE\ConstantTime\Base64UrlSafe; use RuntimeException; use Webauthn\AttestationStatement\AttestationObject; @@ -31,6 +32,7 @@ class StorePasskeyTest extends TestCase { + use VerifiesDoubles; use WebAuthnFixtures; public function testItStoresAPasskeyForTheUser(): void @@ -42,7 +44,7 @@ public function testItStoresAPasskeyForTheUser(): void 'email' => 'john@example.com', ]); - $attestationResponse = m::mock(AuthenticatorAttestationResponse::class); + $attestationResponse = Double::for(AuthenticatorAttestationResponse::class)->strict(); $credential = PublicKeyCredential::create( type: 'public-key', @@ -53,13 +55,8 @@ public function testItStoresAPasskeyForTheUser(): void $options = $this->createRegistrationOptions($user); $source = $this->createCredentialSource($user->getPasskeyUserHandle()); - $action = m::mock(StorePasskey::class) - ->makePartial() - ->shouldAllowMockingProtectedMethods() - ->shouldReceive('validate') - ->once() - ->andReturn($source) - ->getMock(); + $action = Double::for(new StorePasskey)->passthru(); + $action->expects('validate')->returns($source); $passkey = $action($user, 'My MacBook', $credential, $options); @@ -92,7 +89,7 @@ public function testItThrowsExceptionWhenCredentialIsAlreadyRegistered(): void 'credential' => ['test' => 'data'], ]); - $attestationResponse = m::mock(AuthenticatorAttestationResponse::class); + $attestationResponse = Double::for(AuthenticatorAttestationResponse::class)->strict(); $credential = PublicKeyCredential::create( type: 'public-key', @@ -103,13 +100,8 @@ public function testItThrowsExceptionWhenCredentialIsAlreadyRegistered(): void $options = $this->createRegistrationOptions($user); $source = $this->createCredentialSource($user->getPasskeyUserHandle(), $credentialId); - $action = m::mock(StorePasskey::class) - ->makePartial() - ->shouldAllowMockingProtectedMethods() - ->shouldReceive('validate') - ->once() - ->andReturn($source) - ->getMock(); + $action = Double::for(new StorePasskey)->passthru(); + $action->expects('validate')->returns($source); $this->expectException(InvalidPasskeyException::class); $this->expectExceptionMessageIs('Unable to register this passkey.'); @@ -211,7 +203,7 @@ public function testItThrowsExceptionWhenResponseIsNotAnAttestationResponse(): v 'email' => 'john@example.com', ]); - $assertionResponse = m::mock(AuthenticatorAssertionResponse::class); + $assertionResponse = Double::for(AuthenticatorAssertionResponse::class)->strict(); $credential = PublicKeyCredential::create( type: 'public-key', diff --git a/tests/Passkeys/Feature/Actions/VerifyPasskeyTest.php b/tests/Passkeys/Feature/Actions/VerifyPasskeyTest.php index cd4eee4f75..f3eb6f60da 100644 --- a/tests/Passkeys/Feature/Actions/VerifyPasskeyTest.php +++ b/tests/Passkeys/Feature/Actions/VerifyPasskeyTest.php @@ -17,7 +17,9 @@ use Hypervel\Tests\Passkeys\Fixtures\User; use Hypervel\Tests\Passkeys\Fixtures\WebAuthnFixtures; use Hypervel\Tests\Passkeys\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ParagonIE\ConstantTime\Base64UrlSafe; use RuntimeException; use Symfony\Component\Uid\Uuid; @@ -35,6 +37,7 @@ class VerifyPasskeyTest extends TestCase { + use VerifiesDoubles; use WebAuthnFixtures; public function testItVerifiesAPasskeyAndReturnsIt(): void @@ -60,20 +63,15 @@ public function testItVerifiesAPasskeyAndReturnsIt(): void $assertion = PublicKeyCredential::create( type: 'public-key', rawId: $credentialId, - response: m::mock(AuthenticatorAssertionResponse::class), + response: Double::for(AuthenticatorAssertionResponse::class)->strict(), ); $options = $this->createRequestOptions(); $updatedSource = $this->createCredentialSource($userHandle, $credentialId, counter: 6); - $action = m::mock(VerifyPasskey::class) - ->makePartial() - ->shouldAllowMockingProtectedMethods() - ->shouldReceive('validate') - ->once() - ->andReturn($updatedSource) - ->getMock(); + $action = Double::for(new VerifyPasskey)->passthru(); + $action->expects('validate')->returns($updatedSource); $result = $action($assertion, $options); @@ -96,7 +94,7 @@ public function testItThrowsExceptionWhenResponseIsNotAnAssertionResponse(): voi $assertion = PublicKeyCredential::create( type: 'public-key', rawId: 'test-raw-id', - response: m::mock(AuthenticatorAttestationResponse::class), + response: Double::for(AuthenticatorAttestationResponse::class)->strict(), ); $this->expectException(InvalidPasskeyException::class); @@ -110,7 +108,7 @@ public function testItThrowsExceptionWhenPasskeyIsNotFound(): void $assertion = PublicKeyCredential::create( type: 'public-key', rawId: random_bytes(16), - response: m::mock(AuthenticatorAssertionResponse::class), + response: Double::for(AuthenticatorAssertionResponse::class)->strict(), ); $this->expectException(InvalidPasskeyException::class); @@ -121,7 +119,7 @@ public function testItThrowsExceptionWhenPasskeyIsNotFound(): void public function testItRejectsOversizedCredentialIdsBeforeQuerying(): void { - $response = m::mock(AuthenticatorAssertionResponse::class); + $response = Double::for(AuthenticatorAssertionResponse::class)->strict(); $action = app(VerifyPasskey::class); DB::flushQueryLog(); @@ -169,15 +167,11 @@ public function testItThrowsExceptionWhenPasskeyDoesNotBelongToExpectedUser(): v $assertion = PublicKeyCredential::create( type: 'public-key', rawId: $credentialId, - response: m::mock(AuthenticatorAssertionResponse::class), + response: Double::for(AuthenticatorAssertionResponse::class)->strict(), ); - $action = m::mock(VerifyPasskey::class) - ->makePartial() - ->shouldAllowMockingProtectedMethods() - ->shouldReceive('validate') - ->never() - ->getMock(); + $action = Double::for(new VerifyPasskey)->passthru(); + $action->expects('validate')->never(); $this->expectException(InvalidPasskeyException::class); $this->expectExceptionMessageIsOrContains('Passkey not recognized'); @@ -351,12 +345,8 @@ public function testItUsesTheConfiguredPasskeyModelConnectionForVerificationTran 'credential' => ['id' => 'credential-connection'], ]); - $events = m::mock(Dispatcher::class)->shouldIgnoreMissing(); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnFalse()->byDefault(); - $events->shouldReceive('hasListeners')->once()->with(PasskeyVerified::class)->andReturnFalse(); - $events->shouldReceive('dispatch') - ->withArgs(static fn (mixed $event): bool => $event instanceof PasskeyVerified) - ->never(); + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(false); $this->instance('events', $events); $credential = PublicKeyCredential::create( @@ -378,6 +368,8 @@ public function testItUsesTheConfiguredPasskeyModelConnectionForVerificationTran $this->assertSame($passkey, $verifier($credential, $options, $user)); $this->assertTrue($verifier->receivedLockedLookup); $this->assertSame(1, $verifier->lookupTransactionLevel); + $events->received('hasListeners')->with(PasskeyVerified::class)->times(1); + $events->received('dispatch')->with(Argument::type(PasskeyVerified::class))->never(); } /** diff --git a/tests/Passkeys/Feature/Controllers/PasskeyConfirmationTest.php b/tests/Passkeys/Feature/Controllers/PasskeyConfirmationTest.php index ebf10f2bcc..fce3dc8030 100644 --- a/tests/Passkeys/Feature/Controllers/PasskeyConfirmationTest.php +++ b/tests/Passkeys/Feature/Controllers/PasskeyConfirmationTest.php @@ -10,10 +10,13 @@ use Hypervel\Tests\Passkeys\Fixtures\User; use Hypervel\Tests\Passkeys\Fixtures\WebAuthnFixtures; use Hypervel\Tests\Passkeys\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class PasskeyConfirmationTest extends TestCase { + use VerifiesDoubles; use WebAuthnFixtures; public function testItReturnsConfirmationOptionsForAuthenticatedUser(): void @@ -77,11 +80,11 @@ public function testItReturnsValidationErrorWhenPasskeyConfirmationIsInvalid(): 'email' => 'test@example.com', ]); - $this->instance(VerifyPasskey::class, m::mock(VerifyPasskey::class) - ->shouldReceive('__invoke') - ->once() - ->andThrow(InvalidPasskeyException::make('Unable to verify passkey. Please try again.')) - ->getMock()); + $action = Double::for(VerifyPasskey::class)->strict(); + $action + ->expects('__invoke') + ->throws(InvalidPasskeyException::make('Unable to verify passkey. Please try again.')); + $this->instance(VerifyPasskey::class, $action); $this->actingAs($user) ->withSession(['passkey.verification_options_web' => WebAuthn::toJson($this->createRequestOptions())]) @@ -107,13 +110,14 @@ public function testItMarksThePasswordAsConfirmedWhenPasskeyConfirmationSucceeds 'credential' => [], ]); - $this->instance(VerifyPasskey::class, m::mock(VerifyPasskey::class) - ->shouldReceive('__invoke') - ->once() - ->withArgs(static fn ($credential, $options, $expectedUser): bool => $expectedUser instanceof User - && $expectedUser->is($user)) - ->andReturn($passkey) - ->getMock()); + $action = Double::for(VerifyPasskey::class)->strict(); + $action + ->expects('__invoke') + ->with(Argument::any(), Argument::any(), Argument::satisfies( + static fn ($expectedUser): bool => $expectedUser instanceof User && $expectedUser->is($user), + )) + ->returns($passkey); + $this->instance(VerifyPasskey::class, $action); $this->actingAs($user) ->withSession(['passkey.verification_options_web' => WebAuthn::toJson($this->createRequestOptions())]) diff --git a/tests/Passkeys/Feature/Controllers/PasskeyLoginControllerTest.php b/tests/Passkeys/Feature/Controllers/PasskeyLoginControllerTest.php index 4082c8ea86..2f80a16d6c 100644 --- a/tests/Passkeys/Feature/Controllers/PasskeyLoginControllerTest.php +++ b/tests/Passkeys/Feature/Controllers/PasskeyLoginControllerTest.php @@ -11,10 +11,12 @@ use Hypervel\Tests\Passkeys\Fixtures\WebAuthnFixtures; use Hypervel\Tests\Passkeys\TestCase; use Hypervel\Validation\ValidationException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class PasskeyLoginControllerTest extends TestCase { + use VerifiesDoubles; use WebAuthnFixtures; public function testItDoesNotLogInWhenCustomSignInAuthorizationCallbackReturnsFalse(): void @@ -30,11 +32,11 @@ public function testItDoesNotLogInWhenCustomSignInAuthorizationCallbackReturnsFa 'credential' => [], ]); - $this->instance(VerifyPasskey::class, m::mock(VerifyPasskey::class) - ->shouldReceive('__invoke') - ->once() - ->andReturn($passkey) - ->getMock()); + $action = Double::for(VerifyPasskey::class)->strict(); + $action + ->expects('__invoke') + ->returns($passkey); + $this->instance(VerifyPasskey::class, $action); Passkeys::authorizeLoginUsing(static fn (): bool => false); @@ -58,11 +60,11 @@ public function testItReturnsTheCustomSignInAuthorizationValidationMessage(): vo 'credential' => [], ]); - $this->instance(VerifyPasskey::class, m::mock(VerifyPasskey::class) - ->shouldReceive('__invoke') - ->once() - ->andReturn($passkey) - ->getMock()); + $action = Double::for(VerifyPasskey::class)->strict(); + $action + ->expects('__invoke') + ->returns($passkey); + $this->instance(VerifyPasskey::class, $action); Passkeys::authorizeLoginUsing(static function (): never { throw ValidationException::withMessages([ @@ -91,11 +93,11 @@ public function testItLogsInWhenCustomSignInAuthorizationCallbackReturnsTrue(): 'credential' => [], ]); - $this->instance(VerifyPasskey::class, m::mock(VerifyPasskey::class) - ->shouldReceive('__invoke') - ->once() - ->andReturn($passkey) - ->getMock()); + $action = Double::for(VerifyPasskey::class)->strict(); + $action + ->expects('__invoke') + ->returns($passkey); + $this->instance(VerifyPasskey::class, $action); Passkeys::authorizeLoginUsing(static fn (): bool => true); diff --git a/tests/Passkeys/Feature/Controllers/PasskeyLoginTest.php b/tests/Passkeys/Feature/Controllers/PasskeyLoginTest.php index 0b9fbcfd4b..350ceb00aa 100644 --- a/tests/Passkeys/Feature/Controllers/PasskeyLoginTest.php +++ b/tests/Passkeys/Feature/Controllers/PasskeyLoginTest.php @@ -9,10 +9,12 @@ use Hypervel\Passkeys\Support\WebAuthn; use Hypervel\Tests\Passkeys\Fixtures\WebAuthnFixtures; use Hypervel\Tests\Passkeys\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class PasskeyLoginTest extends TestCase { + use VerifiesDoubles; use WebAuthnFixtures; public function testItReturnsLoginOptions(): void @@ -39,11 +41,11 @@ public function testItStoresLoginOptionsInSession(): void public function testItReturnsValidationErrorWhenPasskeyIsInvalid(): void { - $this->instance(VerifyPasskey::class, m::mock(VerifyPasskey::class) - ->shouldReceive('__invoke') - ->once() - ->andThrow(InvalidPasskeyException::make('Unable to verify passkey. Please try again.')) - ->getMock()); + $action = Double::for(VerifyPasskey::class)->strict(); + $action + ->expects('__invoke') + ->throws(InvalidPasskeyException::make('Unable to verify passkey. Please try again.')); + $this->instance(VerifyPasskey::class, $action); $this->withSession(['passkey.verification_options_web' => WebAuthn::toJson($this->createRequestOptions())]) ->postJson('/passkeys/login', [ diff --git a/tests/Passkeys/Feature/Controllers/PasskeyRegistrationTest.php b/tests/Passkeys/Feature/Controllers/PasskeyRegistrationTest.php index d59dfd4ae7..d231818795 100644 --- a/tests/Passkeys/Feature/Controllers/PasskeyRegistrationTest.php +++ b/tests/Passkeys/Feature/Controllers/PasskeyRegistrationTest.php @@ -22,11 +22,13 @@ use Hypervel\Tests\Passkeys\Fixtures\WebAuthnFixtures; use Hypervel\Tests\Passkeys\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use UnitEnum; class PasskeyRegistrationTest extends TestCase { + use VerifiesDoubles; use WebAuthnFixtures; public function testItReturnsRegistrationOptionsForAuthenticatedUser(): void @@ -154,11 +156,11 @@ public function testItReturnsValidationErrorWhenPasskeyIsInvalid(): void 'email' => 'test@example.com', ]); - $this->instance(StorePasskey::class, m::mock(StorePasskey::class) - ->shouldReceive('__invoke') - ->once() - ->andThrow(InvalidPasskeyException::make('Unable to register passkey. Please try again.')) - ->getMock()); + $action = Double::for(StorePasskey::class)->strict(); + $action + ->expects('__invoke') + ->throws(InvalidPasskeyException::make('Unable to register passkey. Please try again.')); + $this->instance(StorePasskey::class, $action); $this->actingAs($user) ->withSession(['auth.password_confirmed_at_web' => time()]) @@ -419,8 +421,8 @@ public function testPasskeyBindingReturnsNotFoundWithoutAnAuthenticatedUser(): v public function testPasskeyBindingReturnsNotFoundForANonStatefulGuard(): void { $passkey = $this->createPasskeyForBinding('stateless@example.com'); - $auth = m::mock(AuthFactory::class); - $auth->shouldReceive('guard')->once()->andReturn(m::mock(Guard::class)); + $auth = Double::for(AuthFactory::class)->strict(); + $auth->expects('guard')->returns(Double::for(Guard::class)->strict()); $this->app->instance(AuthFactory::class, $auth); $binding = Route::getBindingCallback('passkey'); @@ -432,8 +434,8 @@ public function testPasskeyBindingReturnsNotFoundForANonStatefulGuard(): void public function testPasskeyBindingDoesNotHideGuardConfigurationFailures(): void { - $auth = m::mock(AuthFactory::class); - $auth->shouldReceive('guard')->once()->andThrow(new InvalidArgumentException('Invalid guard configuration.')); + $auth = Double::for(AuthFactory::class)->strict(); + $auth->expects('guard')->throws(new InvalidArgumentException('Invalid guard configuration.')); $this->app->instance(AuthFactory::class, $auth); $binding = Route::getBindingCallback('passkey'); diff --git a/tests/Passport/ClientAuthenticatorTest.php b/tests/Passport/ClientAuthenticatorTest.php index bf3894e44f..1c5cd8f28c 100644 --- a/tests/Passport/ClientAuthenticatorTest.php +++ b/tests/Passport/ClientAuthenticatorTest.php @@ -23,12 +23,16 @@ use Hypervel\Passport\ServerSettings; use Hypervel\Support\Facades\Http; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use League\OAuth2\Server\Exception\OAuthServerException; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; class ClientAuthenticatorTest extends TestCase { + use VerifiesDoubles; + #[TestWith([null, 'client_secret_basic'])] #[TestWith([null, 'client_secret_post'])] #[TestWith(['client_secret_basic', 'client_secret_basic'])] @@ -75,13 +79,13 @@ public function testMultipleAuthenticationMethodsAreRejectedBeforeClientLookup() $request = (new ServerRequest('POST', '/token')) ->withHeader('Authorization', 'Basic ' . base64_encode('client:secret')) ->withParsedBody(['client_id' => 'client', 'client_secret' => 'secret']); - $clients = m::mock(ClientRepository::class); - $clients->shouldNotReceive('findActive'); + $clients = Double::for(ClientRepository::class)->strict(); + $clients->expects('findActive')->never(); $authenticator = new ClientAuthenticator( $clients, - m::mock(ClientKeyRepository::class), - m::mock(ReplayCache::class), - m::mock(ServerFactory::class), + Double::for(ClientKeyRepository::class)->strict(), + Double::for(ReplayCache::class)->strict(), + Double::for(ServerFactory::class)->strict(), ); $this->expectException(OAuthServerException::class); @@ -127,10 +131,10 @@ public function testPublicClientsWithoutARegisteredMethodIgnoreSuppliedSecrets(b public function testSignedAssertionsUseTheIssuerAndCannotBeReplayed(string|array $audience): void { [$client, $privateKey] = $this->assertionClient(); - $replays = m::mock(ReplayCache::class); - $replays->shouldReceive('consume')->twice()->with(m::on(static fn (string $identifier): bool => json_decode($identifier, true) === [ + $replays = Double::for(ReplayCache::class)->strict(); + $replays->expects('consume')->times(2)->with(Argument::satisfies(static fn (string $identifier): bool => json_decode($identifier, true) === [ 'client', 'https://auth.example', 'client', 'assertion', - ]), m::type('int'))->andReturn(true, false); + ]), Argument::type('int'))->returns(true, false); $authenticator = $this->authenticator($client, $replays); $request = $this->assertionRequest($privateKey, ['aud' => $audience]); @@ -154,8 +158,8 @@ public function testSignedAssertionsUseTheIssuerAndCannotBeReplayed(string|array public function testInvalidAssertionsDoNotConsumeReplayEntries(string $claim, mixed $value): void { [$client, $privateKey] = $this->assertionClient(); - $replays = m::mock(ReplayCache::class); - $replays->shouldNotReceive('consume'); + $replays = Double::for(ReplayCache::class)->strict(); + $replays->expects('consume')->never(); $this->expectException(OAuthServerException::class); $this->authenticator($client, $replays)->authenticate($this->assertionRequest($privateKey, [$claim => $value])); @@ -175,7 +179,7 @@ public function testAssertionsWithoutIssuedAtHaveABoundedRemainingLifetime(int $ { $now = $this->freezeSecond()->getTimestamp(); [$client, $privateKey] = $this->assertionClient(); - $replays = m::mock(ReplayCache::class); + $replays = Double::for(ReplayCache::class)->strict(); $expiresAt = $now + $remaining + ClientJwt::$leeway; $assertion = JWT::encode([ 'iss' => 'client', 'sub' => 'client', 'aud' => 'https://auth.example', @@ -187,9 +191,9 @@ public function testAssertionsWithoutIssuedAtHaveABoundedRemainingLifetime(int $ ]); if ($accepted) { - $replays->shouldReceive('consume')->once()->with(m::type('string'), $expiresAt + ClientJwt::$leeway)->andReturnTrue(); + $replays->expects('consume')->with(Argument::type('string'), $expiresAt + ClientJwt::$leeway)->returns(true); } else { - $replays->shouldNotReceive('consume'); + $replays->expects('consume')->never(); $this->expectException(OAuthServerException::class); } @@ -204,14 +208,14 @@ public function testClientClockAllowanceDoesNotChangeOtherJwtConsumers(string $c { $now = $this->freezeSecond()->getTimestamp(); [$client, $privateKey] = $this->assertionClient(); - $replays = m::mock(ReplayCache::class); + $replays = Double::for(ReplayCache::class)->strict(); $request = $this->assertionRequest($privateKey, ['iat' => $now, 'exp' => $now + 120, $claim => $now + $offset]); $previousLeeway = JWT::$leeway; if ($accepted) { - $replays->shouldReceive('consume')->once()->with(m::type('string'), $now + 180)->andReturnTrue(); + $replays->expects('consume')->with(Argument::type('string'), $now + 180)->returns(true); } else { - $replays->shouldNotReceive('consume'); + $replays->expects('consume')->never(); $this->expectException(OAuthServerException::class); } @@ -242,8 +246,8 @@ public function testUnsupportedClientKeysExplainTheRequirementWithoutConsumingRe 'kty' => 'RSA', 'e' => 'AQAB', 'n' => JWT::urlsafeB64Encode("\x80" . random_bytes(511) . "\x01"), ]]]; - $replays = m::mock(ReplayCache::class); - $replays->shouldNotReceive('consume'); + $replays = Double::for(ReplayCache::class)->strict(); + $replays->expects('consume')->never(); try { $this->authenticator($client, $replays)->authenticate($this->assertionRequest($privateKey)); @@ -269,8 +273,8 @@ public function testRemoteKeyFailuresRejectAuthenticationWithoutConsumingReplayS $client->jwks = null; $client->jwks_uri = 'https://keys.example/jwks'; Http::fake(['https://keys.example/jwks' => Http::response($body, $status)]); - $replays = m::mock(ReplayCache::class); - $replays->shouldNotReceive('consume'); + $replays = Double::for(ReplayCache::class)->strict(); + $replays->expects('consume')->never(); $authenticator = $this->authenticator($client, $replays, keys: $this->app->make(ClientKeyRepository::class)); try { @@ -287,8 +291,8 @@ public function testServerDestinationPolicyErrorsAreNotHiddenAsInvalidCredential { [$client, $privateKey] = $this->assertionClient(); $failure = new DestinationPolicyException('The HTTP transport cannot enforce the destination policy.'); - $keys = m::mock(ClientKeyRepository::class); - $keys->shouldReceive('find')->once()->andThrow($failure); + $keys = Double::for(ClientKeyRepository::class)->strict(); + $keys->expects('find')->throws($failure); $this->expectExceptionObject($failure); $this->authenticator($client, keys: $keys)->authenticate($this->assertionRequest($privateKey)); @@ -303,13 +307,13 @@ protected function authenticator( ?string $issuer = 'https://auth.example', ?ClientKeyRepository $keys = null, ): ClientAuthenticator { - $clients = m::mock(ClientRepository::class); - $clients->shouldReceive('findActive')->with($client->getKey())->andReturn($client); - $servers = m::mock(ServerFactory::class); - $servers->shouldReceive('settings')->andReturn(new ServerSettings([], issuer: $issuer)); - $keys ??= new ClientKeyRepository(m::mock(Factory::class), new Repository, m::mock(RemoteDocumentFetcher::class), new JwkValidator); + $clients = Double::for(ClientRepository::class)->strict(); + $clients->allows('findActive')->with($client->getKey())->returns($client); + $servers = Double::for(ServerFactory::class)->strict(); + $servers->allows('settings')->returns(new ServerSettings([], issuer: $issuer)); + $keys ??= new ClientKeyRepository(Double::for(Factory::class)->strict(), new Repository, Double::for(RemoteDocumentFetcher::class)->strict(), new JwkValidator); - return new ClientAuthenticator($clients, $keys, $replays ?? m::mock(ReplayCache::class), $servers); + return new ClientAuthenticator($clients, $keys, $replays ?? Double::for(ReplayCache::class)->strict(), $servers); } /** diff --git a/tests/Passport/ClientMetadataValidatorTest.php b/tests/Passport/ClientMetadataValidatorTest.php index 6ee535ba79..215126e66a 100644 --- a/tests/Passport/ClientMetadataValidatorTest.php +++ b/tests/Passport/ClientMetadataValidatorTest.php @@ -17,12 +17,15 @@ use Hypervel\Passport\ServerSettings; use Hypervel\Support\Facades\Event; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; class ClientMetadataValidatorTest extends TestCase { + use VerifiesDoubles; + /** * Load registration settings without requiring signing-key files. */ @@ -185,8 +188,8 @@ public function testExtensionsCannotOverrideCoreMetadataOrOwnership(string $name public function testPrivateKeyAuthenticationRequiresAnIssuerAndPublicKeys(): void { - $servers = m::mock(ServerFactory::class); - $servers->shouldReceive('settings')->andReturn(new ServerSettings([], issuer: 'https://issuer.example'), new ServerSettings([])); + $servers = Double::for(ServerFactory::class)->strict(); + $servers->allows('settings')->returns(new ServerSettings([], issuer: 'https://issuer.example'), new ServerSettings([])); $this->app->instance(ServerFactory::class, $servers); $validator = $this->app->make(ClientMetadataValidator::class); $key = ParsedKey::fromPublicKey((new SigningKeyFactory)->definition()['public_key'])->getJwk(); @@ -238,8 +241,8 @@ public function testInlineAndRemoteKeysCannotBeRegisteredTogether(): void public function testInlineKeySetsUseTheRemoteDocumentSizeLimit(): void { - $servers = m::mock(ServerFactory::class); - $servers->shouldReceive('settings')->andReturn(new ServerSettings([], issuer: 'https://issuer.example')); + $servers = Double::for(ServerFactory::class)->strict(); + $servers->allows('settings')->returns(new ServerSettings([], issuer: 'https://issuer.example')); $this->app->instance(ServerFactory::class, $servers); $key = ParsedKey::fromPublicKey((new SigningKeyFactory)->definition()['public_key'])->getJwk(); diff --git a/tests/Passport/DpopProofValidatorTest.php b/tests/Passport/DpopProofValidatorTest.php index af875b4575..1f66a57906 100644 --- a/tests/Passport/DpopProofValidatorTest.php +++ b/tests/Passport/DpopProofValidatorTest.php @@ -19,8 +19,10 @@ use Hypervel\Support\Facades\DB; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Passport\Fixtures\JsonWebKeyPair; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use League\OAuth2\Server\Exception\OAuthServerException; -use Mockery as m; use Nyholm\Psr7\ServerRequest; use PHPUnit\Framework\Attributes\TestWith; @@ -28,6 +30,8 @@ class DpopProofValidatorTest extends TestCase { + use VerifiesDoubles; + /** * Enable proofs with a dedicated database replay store. */ @@ -50,10 +54,10 @@ public function testVerifiesTheEmbeddedPublicKeyAndNormalizesTheHttpTarget(strin { $this->freezeSecond(); [$request, $thumbprint] = $this->proof(['htu' => 'HTTPS://AUTH.EXAMPLE:443/a/../oauth/%74oken?ignored=1#ignored'], algorithm: $algorithm); - $replays = m::mock(ReplayCache::class); - $replays->shouldReceive('consume')->once()->with(m::on(static fn (string $identifier): bool => json_decode($identifier, true) === [ + $replays = Double::for(ReplayCache::class)->strict(); + $replays->expects('consume')->with(Argument::satisfies(static fn (string $identifier): bool => json_decode($identifier, true) === [ 'dpop', $thumbprint, 'https://auth.example/oauth/token', hash('sha256', 'proof'), - ]), Date::now()->getTimestamp() + 120)->andReturnTrue(); + ]), Date::now()->getTimestamp() + 120)->returns(true); $this->assertSame($thumbprint, $this->validator($replays)->validate($request)); } @@ -66,12 +70,12 @@ public function testIssuedAtBoundariesRetainReplayEvidenceUntilTheFullDeadline(i { $now = $this->freezeSecond()->getTimestamp(); [$request, $thumbprint] = $this->proof(['iat' => $now + $offset]); - $replays = m::mock(ReplayCache::class); + $replays = Double::for(ReplayCache::class)->strict(); if ($accepted) { - $replays->shouldReceive('consume')->once()->with(m::type('string'), (int) ceil($now + $offset + 120))->andReturnTrue(); + $replays->expects('consume')->with(Argument::type('string'), (int) ceil($now + $offset + 120))->returns(true); } else { - $replays->shouldNotReceive('consume'); + $replays->expects('consume')->never(); $this->expectException(OAuthServerException::class); } @@ -90,8 +94,8 @@ public function testIssuedAtBoundariesRetainReplayEvidenceUntilTheFullDeadline(i public function testInvalidClaimsDoNotConsumeReplayState(string $claim, mixed $value): void { [$request] = $this->proof([$claim => $value]); - $replays = m::mock(ReplayCache::class); - $replays->shouldNotReceive('consume'); + $replays = Double::for(ReplayCache::class)->strict(); + $replays->expects('consume')->never(); $this->expectException(OAuthServerException::class); $this->validator($replays)->validate($request); @@ -143,8 +147,8 @@ public function testMalformedProofsAreRejected(string $case): void default => $invalidSignature === null ? $request : $request->withHeader('DPoP', $parts[0] . '.' . $parts[1] . '.' . JWT::urlsafeB64Encode($invalidSignature)), }; - $replays = m::mock(ReplayCache::class); - $replays->shouldNotReceive('consume'); + $replays = Double::for(ReplayCache::class)->strict(); + $replays->expects('consume')->never(); $this->expectException(OAuthServerException::class); $this->validator($replays)->validate($request); @@ -159,8 +163,8 @@ public function testUnsupportedKeysHavePublicErrorDescriptions(int $modulusBytes 'n' => JWT::urlsafeB64Encode("\x80" . random_bytes($modulusBytes - 2) . "\x01"), 'e' => JWT::urlsafeB64Encode("\x01" . str_repeat("\0", $exponentBytes - 2) . "\x01"), ]], algorithm: 'RS256'); - $replays = m::mock(ReplayCache::class); - $replays->shouldNotReceive('consume'); + $replays = Double::for(ReplayCache::class)->strict(); + $replays->expects('consume')->never(); try { $this->validator($replays)->validate($request); @@ -177,12 +181,12 @@ public function testUnsupportedKeysHavePublicErrorDescriptions(int $modulusBytes public function testResourceProofsMustBindBothTheAccessTokenAndItsPublicKey(bool $matchingToken, bool $matchingKey): void { [$request, $thumbprint] = $this->proof(['ath' => JWT::urlsafeB64Encode(hash('sha256', 'access-token', true))]); - $replays = m::mock(ReplayCache::class); + $replays = Double::for(ReplayCache::class)->strict(); if ($matchingToken && $matchingKey) { - $replays->shouldReceive('consume')->once()->andReturnTrue(); + $replays->expects('consume')->returns(true); } else { - $replays->shouldNotReceive('consume'); + $replays->expects('consume')->never(); $this->expectException(OAuthServerException::class); } @@ -241,8 +245,8 @@ public function testSuccessfulProofReuseIsLimitedToTheSameRequestAndInputs(): vo { [$request, $thumbprint] = $this->proof(); RequestContext::set(Request::create('https://auth.example/oauth/token', 'POST')); - $replays = m::mock(ReplayCache::class); - $replays->shouldReceive('consume')->twice()->andReturn(true, false); + $replays = Double::for(ReplayCache::class)->strict(); + $replays->expects('consume')->times(2)->returns(true, false); $validator = $this->validator($replays); $this->assertSame($thumbprint, $validator->validate($request)); $this->assertSame($thumbprint, $validator->validate($request)); @@ -263,13 +267,13 @@ public function testWeakerValidationCannotSatisfyAServerRequiringReplayProtectio { [$request, $thumbprint] = $this->proof(); RequestContext::set(Request::create('https://auth.example/oauth/token', 'POST')); - $servers = m::mock(ServerFactory::class); - $servers->shouldReceive('settings')->andReturn( + $servers = Double::for(ServerFactory::class)->strict(); + $servers->allows('settings')->returns( new ServerSettings([], dpopReplayProtection: false), new ServerSettings([], dpopReplayProtection: true), ); - $replays = m::mock(ReplayCache::class); - $replays->shouldReceive('consume')->once()->andReturnFalse(); + $replays = Double::for(ReplayCache::class)->strict(); + $replays->expects('consume')->returns(false); $validator = new DpopProofValidator($this->app->make(Repository::class), new JwkValidator, $replays, $servers); $this->assertSame($thumbprint, $validator->validate($request)); @@ -281,8 +285,8 @@ public function testProofMemosRemainIndependentAcrossConcurrentRequests(): void { [$first, $firstThumbprint] = $this->proof(); [$second, $secondThumbprint] = $this->proof(); - $replays = m::mock(ReplayCache::class); - $replays->shouldReceive('consume')->twice()->andReturnTrue(); + $replays = Double::for(ReplayCache::class)->strict(); + $replays->expects('consume')->times(2)->returns(true); $validator = $this->validator($replays); $validate = static function (ServerRequest $request) use ($validator): string { RequestContext::set(Request::create('https://auth.example/oauth/token', 'POST')); @@ -302,8 +306,8 @@ public function testDisabledSupportRejectsProofsWithoutAccessingReplayStorage(): { config(['passport.dpop.enabled' => false]); [$request] = $this->proof(); - $replays = m::mock(ReplayCache::class); - $replays->shouldNotReceive('consume'); + $replays = Double::for(ReplayCache::class)->strict(); + $replays->expects('consume')->never(); $this->expectException(OAuthServerException::class); $this->expectExceptionMessage('DPoP proof is invalid'); @@ -315,8 +319,8 @@ public function testDisabledSupportRejectsProofsWithoutAccessingReplayStorage(): */ protected function validator(ReplayCache $replays, ?ServerSettings $settings = null): DpopProofValidator { - $servers = m::mock(ServerFactory::class); - $servers->shouldReceive('settings')->andReturn($settings ?? new ServerSettings([])); + $servers = Double::for(ServerFactory::class)->strict(); + $servers->allows('settings')->returns($settings ?? new ServerSettings([])); return new DpopProofValidator($this->app->make(Repository::class), new JwkValidator, $replays, $servers); } diff --git a/tests/Passport/Feature/AuthorizationInteractionTest.php b/tests/Passport/Feature/AuthorizationInteractionTest.php index 65ae228f89..70b7745881 100644 --- a/tests/Passport/Feature/AuthorizationInteractionTest.php +++ b/tests/Passport/Feature/AuthorizationInteractionTest.php @@ -23,12 +23,15 @@ use Hypervel\Support\Facades\Route; use Hypervel\Testbench\Concerns\WithHypervelMigrations; use Hypervel\Tests\Passport\Fixtures\UserFactory; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use League\OAuth2\Server\Exception\OAuthServerException; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; class AuthorizationInteractionTest extends PassportTestCase { + use VerifiesDoubles; use WithHypervelMigrations; /** @@ -113,11 +116,11 @@ public function testCustomConfirmationResponseReceivesTheClient(): void { $client = ClientFactory::new()->create(); $this->actingAs(UserFactory::new()->create(), 'web'); - $response = m::mock(ReauthenticationResponse::class); - $response->shouldReceive('withParameters')->once()->with(m::on( + $response = Double::for(ReauthenticationResponse::class)->strict(); + $response->expects('withParameters')->with(Argument::satisfies( static fn (array $parameters): bool => $parameters['client']->is($client), - ))->andReturnSelf(); - $response->shouldReceive('toResponse')->once()->andReturn(response('Confirm identity')); + )); + $response->expects('toResponse')->returns(response('Confirm identity')); $this->app->instance(ReauthenticationResponse::class, $response); $this->get('/oauth/authorize?' . http_build_query([ diff --git a/tests/Passport/Feature/ClientRegistrationTest.php b/tests/Passport/Feature/ClientRegistrationTest.php index 0c25626d32..06eaadf7c6 100644 --- a/tests/Passport/Feature/ClientRegistrationTest.php +++ b/tests/Passport/Feature/ClientRegistrationTest.php @@ -27,11 +27,13 @@ use Hypervel\Testbench\Attributes\DefineEnvironment; use Hypervel\Testbench\Concerns\WithHypervelMigrations; use Hypervel\Tests\Passport\Fixtures\UserFactory; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; class ClientRegistrationTest extends PassportTestCase { + use VerifiesDoubles; use WithHypervelMigrations; protected bool $registrationEnabled = true; @@ -139,8 +141,8 @@ public function testCompleteMetadataUpdatesReplaceTheAuthenticationKeySource(): config(['passport.issuer' => 'https://issuer.example', 'passport.replay.store' => 'database']); $material = (new SigningKeyFactory)->definition(); $key = ParsedKey::fromPublicKey($material['public_key'])->getJwk(); - $documents = m::mock(RemoteDocumentFetcher::class); - $documents->shouldReceive('fetch')->with('https://keys.example/jwks')->andReturn(['keys' => [[...$key, 'kid' => 'remote']]]); + $documents = Double::for(RemoteDocumentFetcher::class)->strict(); + $documents->allows('fetch')->with('https://keys.example/jwks')->returns(['keys' => [[...$key, 'kid' => 'remote']]]); $this->app->instance(RemoteDocumentFetcher::class, $documents); $validator = $this->app->make(ClientMetadataValidator::class); $client = ClientFactory::new()->asClientCredentials()->create(['secret' => null]); diff --git a/tests/Passport/Feature/DpopIssuanceTest.php b/tests/Passport/Feature/DpopIssuanceTest.php index cfa22e0e96..c7c23ff746 100644 --- a/tests/Passport/Feature/DpopIssuanceTest.php +++ b/tests/Passport/Feature/DpopIssuanceTest.php @@ -35,11 +35,13 @@ use Hypervel\Testing\TestResponse; use Hypervel\Tests\Passport\Fixtures\JsonWebKeyPair; use Hypervel\Tests\Passport\Fixtures\UserFactory; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; class DpopIssuanceTest extends PassportTestCase { + use VerifiesDoubles; use WithHypervelMigrations; protected const string ORIGIN = 'https://auth.example'; @@ -270,9 +272,9 @@ public function testResourceMiddlewareRequiresProofBindingAndIgnoresProofHeaders public function testSelectedServerCapsOnlyProofBoundTokens(): void { $settings = new ServerSettings($this->app->make(ServerFactory::class)->fileKeys(), dpopTokensExpireIn: new DateInterval('PT30S')); - $resolver = m::mock(ServerSettingsResolver::class); - $resolver->shouldReceive('current')->andReturn('short-lived'); - $resolver->shouldReceive('resolve')->with('short-lived')->andReturn($settings); + $resolver = Double::for(ServerSettingsResolver::class)->strict(); + $resolver->allows('current')->returns('short-lived'); + $resolver->allows('resolve')->with('short-lived')->returns($settings); $this->app->instance(ServerSettingsResolver::class, $resolver); Passport::tokensExpireIn(new DateInterval('PT600S')); $client = ClientFactory::new()->asClientCredentials()->create(); @@ -439,11 +441,11 @@ public function testWarmCredentialValidationAddsNoDatabaseQueriesAndConsumesEach ], $key)->assertOk()->json('access_token'); $headers = ['Authorization' => ($proofBound ? 'DPoP ' : 'Bearer ') . $token]; $this->getJson(self::ORIGIN . '/cached-proof', $headers + ($key === null ? [] : ['DPoP' => $this->proof($key, '/cached-proof', 'GET', $token)]))->assertOk(); - $replays = m::mock(ReplayCache::class); + $replays = Double::for(ReplayCache::class)->strict(); if ($proofBound && $replayProtection) { - $replays->shouldReceive('consume')->once()->andReturnTrue(); + $replays->expects('consume')->returns(true); } else { - $replays->shouldNotReceive('consume'); + $replays->expects('consume')->never(); } // DpopProofValidator already holds the resolved service; replace it to use the counted store. $this->app->forgetInstance(DpopProofValidator::class); diff --git a/tests/Passport/Feature/RefreshTokenGrantTest.php b/tests/Passport/Feature/RefreshTokenGrantTest.php index bf5c8e0740..3d7de2243c 100644 --- a/tests/Passport/Feature/RefreshTokenGrantTest.php +++ b/tests/Passport/Feature/RefreshTokenGrantTest.php @@ -18,12 +18,15 @@ use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\Concerns\WithHypervelMigrations; use Hypervel\Tests\Passport\Fixtures\UserFactory; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use function Hypervel\Testbench\artisan; class RefreshTokenGrantTest extends PassportTestCase { + use VerifiesDoubles; use WithHypervelMigrations; /** @@ -169,16 +172,20 @@ public function testReplacementRefreshTokenRetainsItsOriginalScopes(): void #[WithConfig('passport.cache', ['enabled' => true, 'store' => 'file', 'ttl' => 300, 'prefix' => 'passport'])] public function testRefreshReturnsUsableTokensWhenInvalidationFailsAfterCommit(): void { - $coordinator = m::mock(ModelCacheCoordinator::class, [$this->app])->makePartial(); + $realCoordinator = new ModelCacheCoordinator($this->app); + $coordinator = Double::for($realCoordinator)->passthru(); $this->app->instance(ModelCacheCoordinator::class, $coordinator); $client = ClientFactory::new()->create(); $oldToken = $this->getNewAccessToken($client); $oldRefresh = Passport::refreshToken()->newQuery()->sole(); $failure = new LockTimeoutException; - $coordinator->shouldReceive('invalidate')->once() - ->with($this->app->make('cache')->store('file'), 'passport:tokens:' . $oldRefresh->access_token_id) - ->andThrow($failure); - $coordinator->shouldReceive('invalidate')->withAnyArgs()->passthru()->byDefault(); + $tokenCacheKey = 'passport:tokens:' . $oldRefresh->access_token_id; + $coordinator->expects('invalidate') + ->with($this->app->make('cache')->store('file'), $tokenCacheKey) + ->throws($failure); + $coordinator->allows('invalidate') + ->with(Argument::any(), Argument::not($tokenCacheKey)) + ->resolves($realCoordinator->invalidate(...)); Exceptions::fake(); $newToken = $this->post('/oauth/token', [ diff --git a/tests/Passport/Feature/ServerMetadataTest.php b/tests/Passport/Feature/ServerMetadataTest.php index d4a2b3d11b..c060b0d065 100644 --- a/tests/Passport/Feature/ServerMetadataTest.php +++ b/tests/Passport/Feature/ServerMetadataTest.php @@ -20,13 +20,15 @@ use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\Concerns\WithHypervelMigrations; use Hypervel\Tests\Passport\Fixtures\UserFactory; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use Symfony\Component\HttpFoundation\Response; #[WithConfig('passport.issuer', 'https://auth.example')] class ServerMetadataTest extends PassportTestCase { + use VerifiesDoubles; use WithHypervelMigrations; public function testDiscoveryPublishesOnlySupportedCapabilitiesAndConditionalResponses(): void @@ -141,12 +143,12 @@ public function testChangedSettingsPublishNewKeysWithANewEtagAndTheirOwnCacheLif 'second' => new ServerSettings([...$keys, new ServerKey($material['public'])], issuer: 'https://auth.example'), ]; $revision = 'first'; - $resolver = m::mock(ServerSettingsResolver::class); - $resolver->shouldReceive('current')->andReturnUsing(static function () use (&$revision): string { + $resolver = Double::for(ServerSettingsResolver::class)->strict(); + $resolver->allows('current')->resolves(static function () use (&$revision): string { return $revision; }); - $resolver->shouldReceive('resolve')->with('first')->once()->andReturn($settings['first']); - $resolver->shouldReceive('resolve')->with('second')->once()->andReturn($settings['second']); + $resolver->expects('resolve')->with('first')->returns($settings['first']); + $resolver->expects('resolve')->with('second')->returns($settings['second']); $this->app->instance(ServerSettingsResolver::class, $resolver); $first = $this->get('https://auth.example/oauth/jwks')->assertOk()->assertExactJson($servers->jwks()) diff --git a/tests/Passport/Feature/TokenGuardTest.php b/tests/Passport/Feature/TokenGuardTest.php index 117446e53c..5a0a19c413 100644 --- a/tests/Passport/Feature/TokenGuardTest.php +++ b/tests/Passport/Feature/TokenGuardTest.php @@ -30,13 +30,15 @@ use Hypervel\Tests\Passport\Fixtures\JsonWebKeyPair; use Hypervel\Tests\Passport\Fixtures\User; use Hypervel\Tests\Passport\Fixtures\UserFactory; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use League\OAuth2\Server\Exception\OAuthServerException; use League\OAuth2\Server\ResourceServer; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; class TokenGuardTest extends PassportTestCase { + use VerifiesDoubles; use WithHypervelMigrations; /** @@ -133,12 +135,12 @@ public function testGuardMemosFollowServerChangesOnTheSameRequest(): void $otherKey = JsonWebKeyPair::generate('RS256'); $otherPublicKey = openssl_pkey_get_details(openssl_pkey_get_private($otherKey->privateKey))['key']; $identifier = 'first'; - $resolver = m::mock(ServerSettingsResolver::class); - $resolver->shouldReceive('current')->andReturnUsing(static function () use (&$identifier): string { + $resolver = Double::for(ServerSettingsResolver::class)->strict(); + $resolver->allows('current')->resolves(static function () use (&$identifier): string { return $identifier; }); - $resolver->shouldReceive('resolve')->with('first')->once()->andReturn(new ServerSettings($servers->fileKeys())); - $resolver->shouldReceive('resolve')->with('second')->once()->andReturn(new ServerSettings(['other' => new ServerKey($otherPublicKey)])); + $resolver->expects('resolve')->with('first')->returns(new ServerSettings($servers->fileKeys())); + $resolver->expects('resolve')->with('second')->returns(new ServerSettings(['other' => new ServerKey($otherPublicKey)])); $this->app->instance(ServerSettingsResolver::class, $resolver); $request = Request::create('/guard'); $request->headers->set('Authorization', 'Bearer ' . $result->accessToken); @@ -158,8 +160,8 @@ public function testGuardMemosFollowServerChangesOnTheSameRequest(): void $this->assertSame($user->id, $guard->user()->getKey()); $this->assertSame($client->id, $guard->client()->getKey()); - $override = m::mock(ResourceServer::class); - $override->shouldReceive('validateAuthenticatedRequest')->once()->andThrow(OAuthServerException::accessDenied()); + $override = Double::for(ResourceServer::class)->strict(); + $override->expects('validateAuthenticatedRequest')->throws(OAuthServerException::accessDenied()); CoroutineContext::set(ServerFactory::RESOURCE_SERVER_CONTEXT_KEY, $override); $this->assertFalse($guard->hasUser()); $this->assertNull($guard->user()); diff --git a/tests/Passport/PassportCacheTest.php b/tests/Passport/PassportCacheTest.php index c34a98fcb0..d89e69ebaa 100644 --- a/tests/Passport/PassportCacheTest.php +++ b/tests/Passport/PassportCacheTest.php @@ -26,7 +26,8 @@ use Hypervel\Support\Facades\Event; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Passport\Fixtures\User; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; @@ -38,6 +39,8 @@ class PassportCacheTest extends TestCase { + use VerifiesDoubles; + /** * Configure the cache independently of the OAuth server. */ @@ -391,11 +394,12 @@ public function testBatchInvalidationContinuesAfterAFailureFollowingCommit(): vo { $failure = new LockTimeoutException; $cache = $this->app->make('cache')->store('passport-file'); - $coordinator = m::mock(ModelCacheCoordinator::class, [$this->app])->makePartial(); - $coordinator->shouldReceive('invalidate')->once() - ->with($cache, 'passport:tokens:token')->andThrow($failure); - $coordinator->shouldReceive('invalidate')->once() - ->with($cache, 'passport:tokens:token-second')->passthru(); + $realCoordinator = new ModelCacheCoordinator($this->app); + $coordinator = Double::for($realCoordinator)->passthru(); + $coordinator->expects('invalidate') + ->with($cache, 'passport:tokens:token')->throws($failure); + $coordinator->expects('invalidate') + ->with($cache, 'passport:tokens:token-second')->resolves($realCoordinator->invalidate(...)); $this->app->instance(ModelCacheCoordinator::class, $coordinator); $first = $this->createToken(); @@ -432,12 +436,12 @@ public function testBatchInvalidationStopsOnCancellationAfterAnOrdinaryFailure(b } $cache = $this->app->make('cache')->store('passport-file'); - $coordinator = m::mock(ModelCacheCoordinator::class, [$this->app])->makePartial(); - $coordinator->shouldReceive('invalidate')->once() - ->with($cache, 'passport:tokens:token')->andThrow(new LockTimeoutException); - $coordinator->shouldReceive('invalidate')->once() - ->with($cache, 'passport:tokens:token-second')->andThrow($failure); - $coordinator->shouldReceive('invalidate')->never() + $coordinator = Double::for(new ModelCacheCoordinator($this->app))->passthru(); + $coordinator->expects('invalidate') + ->with($cache, 'passport:tokens:token')->throws(new LockTimeoutException); + $coordinator->expects('invalidate') + ->with($cache, 'passport:tokens:token-second')->throws($failure); + $coordinator->expects('invalidate')->never() ->with($cache, 'passport:tokens:token-third'); $this->app->instance(ModelCacheCoordinator::class, $coordinator); diff --git a/tests/Passport/ReplayCacheTest.php b/tests/Passport/ReplayCacheTest.php index 6e377fba12..0211e0c21e 100644 --- a/tests/Passport/ReplayCacheTest.php +++ b/tests/Passport/ReplayCacheTest.php @@ -21,14 +21,17 @@ use Hypervel\Passport\ReplayCache; use Hypervel\Support\Facades\DB; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; class ReplayCacheTest extends TestCase { + use VerifiesDoubles; + /** * Configure separate application and replay databases. */ @@ -140,8 +143,8 @@ public function testTestWrappersPermitClaimsButNestedApplicationTransactionsDoNo #[DataProvider('unsupportedStores')] public function testLocalAndSwitchingStoresCannotBeUsedForReplayProtection(string $store): void { - $factory = m::mock(Factory::class); - $factory->shouldReceive('store')->with(null)->andReturn(new Repository(m::mock($store))); + $factory = Double::for(Factory::class)->strict(); + $factory->allows('store')->with(null)->returns(new Repository(Double::for($store)->strict())); $replays = new ReplayCache($factory, $this->app->make(ConfigRepository::class)); $this->expectException(LogicException::class); @@ -168,10 +171,10 @@ public static function unsupportedStores(): array public function testBackendFailureDoesNotAcceptTheProof(): void { $failure = new RuntimeException('Replay store unavailable'); - $store = m::mock(RedisStore::class); - $store->shouldReceive('add')->once()->andThrow($failure); - $factory = m::mock(Factory::class); - $factory->shouldReceive('store')->with(null)->andReturn(new Repository($store)); + $store = Double::for(RedisStore::class)->strict(); + $store->expects('add')->throws($failure); + $factory = Double::for(Factory::class)->strict(); + $factory->allows('store')->with(null)->returns(new Repository($store)); $this->expectExceptionObject($failure); (new ReplayCache($factory, $this->app->make(ConfigRepository::class)))->consume('assertion', time() + 300); diff --git a/tests/Passport/ServerFactoryTest.php b/tests/Passport/ServerFactoryTest.php index 5d181c875f..57b0ed2511 100644 --- a/tests/Passport/ServerFactoryTest.php +++ b/tests/Passport/ServerFactoryTest.php @@ -23,6 +23,8 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Facades\DB; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Lcobucci\JWT\Encoding\ChainedFormatter; use Lcobucci\JWT\Encoding\JoseEncoder; use Lcobucci\JWT\Signer\Key\InMemory; @@ -30,7 +32,6 @@ use Lcobucci\JWT\Token\Builder; use Lcobucci\JWT\Token\Parser; use LogicException; -use Mockery as m; use Nyholm\Psr7\Response; use Nyholm\Psr7\ServerRequest; use PHPUnit\Framework\Attributes\TestWith; @@ -41,6 +42,8 @@ class ServerFactoryTest extends TestCase { + use VerifiesDoubles; + /** * Configure the files store with reusable PEM material. */ @@ -162,14 +165,14 @@ public function testUnsetIssuersAreOmittedFromDefaultSettings(string $store, ?st public function testSettingsCacheEvictsTheLeastRecentlyUsedEntryAndKeepsScopesSeparate(): void { $identifier = 'first'; - $resolver = m::mock(ServerSettingsResolver::class); - $resolver->shouldReceive('current')->andReturnUsing(static function () use (&$identifier): string { + $resolver = Double::for(ServerSettingsResolver::class)->strict(); + $resolver->allows('current')->resolves(static function () use (&$identifier): string { return $identifier; }); $key = new ServerKey(config('passport.public_key'), config('passport.private_key')); - $resolver->shouldReceive('resolve')->with('first')->once()->andReturn(new ServerSettings([$key], scopes: ['first' => 'First'])); - $resolver->shouldReceive('resolve')->with('second')->twice()->andReturn(new ServerSettings([$key], scopes: ['second' => 'Second'])); - $resolver->shouldReceive('resolve')->with('third')->once()->andReturn(new ServerSettings([$key], scopes: ['third' => 'Third'])); + $resolver->expects('resolve')->with('first')->returns(new ServerSettings([$key], scopes: ['first' => 'First'])); + $resolver->expects('resolve')->with('second')->times(2)->returns(new ServerSettings([$key], scopes: ['second' => 'Second'])); + $resolver->expects('resolve')->with('third')->returns(new ServerSettings([$key], scopes: ['third' => 'Third'])); $this->app->instance(ServerSettingsResolver::class, $resolver); $servers = $this->app->make(ServerFactory::class); Passport::tokensCan(['global' => 'Global']); @@ -191,9 +194,9 @@ public function testSettingsCacheEvictsTheLeastRecentlyUsedEntryAndKeepsScopesSe public function testPublicOnlySettingsExposeVerificationWithoutARequiredPrivateKey(): void { - $resolver = m::mock(ServerSettingsResolver::class); - $resolver->shouldReceive('current')->andReturn('verification'); - $resolver->shouldReceive('resolve')->once()->with('verification')->andReturn(new ServerSettings([ + $resolver = Double::for(ServerSettingsResolver::class)->strict(); + $resolver->allows('current')->returns('verification'); + $resolver->expects('resolve')->with('verification')->returns(new ServerSettings([ new ServerKey(config('passport.public_key')), ])); $this->app->instance(ServerSettingsResolver::class, $resolver); @@ -211,9 +214,9 @@ public function testPublicOnlySettingsExposeVerificationWithoutARequiredPrivateK public function testSettingsWithoutKeysCannotVerifyTokens(): void { - $resolver = m::mock(ServerSettingsResolver::class); - $resolver->shouldReceive('current')->andReturn('empty'); - $resolver->shouldReceive('resolve')->once()->with('empty')->andReturn(new ServerSettings([])); + $resolver = Double::for(ServerSettingsResolver::class)->strict(); + $resolver->allows('current')->returns('empty'); + $resolver->expects('resolve')->with('empty')->returns(new ServerSettings([])); $this->app->instance(ServerSettingsResolver::class, $resolver); $this->expectException(LogicException::class); @@ -275,8 +278,8 @@ public function testConcurrentKeyLoadsDoNotOverwriteNewerEntriesAndFailuresCanRe $ready = new Channel(1); $release = new Channel(1); $failure = new RuntimeException('Key storage unavailable.'); - $repository = m::mock(SigningKeyRepository::class); - $repository->shouldReceive('serverKeys')->andReturnUsing(function () use (&$keys, &$pause, &$calls, $ready, $release, $scenario, $failure): array { + $repository = Double::for(SigningKeyRepository::class)->strict(); + $repository->allows('serverKeys')->resolves(function () use (&$keys, &$pause, &$calls, $ready, $release, $scenario, $failure): array { ++$calls; $snapshot = $keys; @@ -356,9 +359,9 @@ public function testCustomSettingsPreserveStoredKeyRetentionAndDoNotPublishRolle CarbonImmutable::setTestNow($now); $key = SigningKey::factory()->create(); $repository = $this->app->make(SigningKeyRepository::class); - $resolver = m::mock(ServerSettingsResolver::class); - $resolver->shouldReceive('current')->andReturn('custom'); - $resolver->shouldReceive('resolve')->with('custom')->once()->andReturnUsing( + $resolver = Double::for(ServerSettingsResolver::class)->strict(); + $resolver->allows('current')->returns('custom'); + $resolver->expects('resolve')->with('custom')->resolves( static fn (): ServerSettings => new ServerSettings($repository->serverKeys()), ); $this->app->instance(ServerSettingsResolver::class, $resolver); diff --git a/tests/Passport/SigningKeyCommandsTest.php b/tests/Passport/SigningKeyCommandsTest.php index 7513b706c6..c81831cad6 100644 --- a/tests/Passport/SigningKeyCommandsTest.php +++ b/tests/Passport/SigningKeyCommandsTest.php @@ -17,11 +17,14 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; class SigningKeyCommandsTest extends TestCase { + use VerifiesDoubles; + /** * Boot the real Passport provider to exercise command and schedule registration. */ @@ -75,8 +78,8 @@ public function testDatabaseKeyCommandsProvisionListRotateAndRevoke(): void $now = CarbonImmutable::now()->startOfSecond(); CarbonImmutable::setTestNow($now); $material = (new SigningKeyFactory)->definition(); - $generator = m::mock(KeyGenerator::class); - $generator->shouldReceive('generate')->with(2048)->times(3)->andReturn( + $generator = Double::for(KeyGenerator::class)->strict(); + $generator->expects('generate')->with(2048)->times(3)->returns( ['public' => $material['public_key'], 'private' => $material['private_key']], (new KeyGenerator)->generate(2048), (new KeyGenerator)->generate(2048), @@ -116,8 +119,8 @@ public function testDatabaseKeyCommandsProvisionListRotateAndRevoke(): void public function testImportCommandCarriesTheExplicitRetentionFloor(): void { $material = (new SigningKeyFactory)->definition(); - $factory = m::mock(ServerFactory::class); - $factory->shouldReceive('fileKeys')->once()->andReturn([new ServerKey($material['public_key'], $material['private_key'])]); + $factory = Double::for(ServerFactory::class)->strict(); + $factory->expects('fileKeys')->returns([new ServerKey($material['public_key'], $material['private_key'])]); $this->app->instance(ServerFactory::class, $factory); $this->artisan('passport:keys:import', ['--retain-until' => '2030-01-01T00:00:00Z']) ->expectsOutputToContain('Signing keys imported.')->assertSuccessful(); @@ -136,9 +139,9 @@ public function testRevokingAnUnknownKeyFails(): void public function testDatabaseManagementCommandsRejectTheFilesStore(string $command, array $parameters): void { config(['passport.key_store' => 'files']); - $repository = m::mock(SigningKeyRepository::class); - $repository->shouldNotReceive('rotate'); - $repository->shouldNotReceive('revoke'); + $repository = Double::for(SigningKeyRepository::class)->strict(); + $repository->expects('rotate')->never(); + $repository->expects('revoke')->never(); $this->app->instance(SigningKeyRepository::class, $repository); $this->artisan($command, $parameters)->expectsOutputToContain('Rotate file keys manually using passport.verification_keys.')->assertFailed(); diff --git a/tests/Passport/SigningKeyRepositoryTest.php b/tests/Passport/SigningKeyRepositoryTest.php index 44024953e3..5309c0f915 100644 --- a/tests/Passport/SigningKeyRepositoryTest.php +++ b/tests/Passport/SigningKeyRepositoryTest.php @@ -20,13 +20,16 @@ use Hypervel\Support\Facades\DB; use Hypervel\Testbench\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; class SigningKeyRepositoryTest extends TestCase { + use VerifiesDoubles; + /** @var list */ protected static array $keys = []; @@ -81,8 +84,8 @@ protected function tearDown(): void public function testCreateIsIdempotentAndGeneratesBeforeTakingTheLockOrTransaction(): void { - $generator = m::mock(KeyGenerator::class); - $generator->shouldReceive('generate')->with(2048)->once()->andReturnUsing(function (): array { + $generator = Double::for(KeyGenerator::class)->strict(); + $generator->expects('generate')->with(2048)->resolves(function (): array { $this->assertSame(0, DB::transactionLevel()); $this->assertFalse($this->app->make('cache')->store()->getStore()->lock('passport:signing-keys:default')->isLocked()); @@ -247,8 +250,8 @@ public function testFileImportDeduplicatesKeysAndRetainsAlreadyIssuedTokens(int { Passport::tokensExpireIn(new DateInterval('PT15M')); Passport::personalAccessTokensExpireIn(new DateInterval('PT15M')); - $factory = m::mock(ServerFactory::class); - $factory->shouldReceive('fileKeys')->once()->andReturn([ + $factory = Double::for(ServerFactory::class)->strict(); + $factory->expects('fileKeys')->returns([ new ServerKey(self::$keys[0]['public'], self::$keys[0]['private']), new ServerKey(self::$keys[0]['public']), new ServerKey(self::$keys[1]['public']), @@ -281,8 +284,8 @@ public function testFileImportRetainsTokensIssuedBeforeFileWorkersRestart(): voi { Passport::tokensExpireIn(new DateInterval('PT15M')); Passport::personalAccessTokensExpireIn(new DateInterval('P1Y')); - $factory = m::mock(ServerFactory::class); - $factory->shouldReceive('fileKeys')->once()->andReturn([ + $factory = Double::for(ServerFactory::class)->strict(); + $factory->expects('fileKeys')->returns([ new ServerKey(self::$keys[0]['public'], self::$keys[0]['private']), ]); $this->app->instance(ServerFactory::class, $factory); @@ -327,8 +330,8 @@ public function testManagementRequiresASharedLockStore(string $driver): void public function testManagementRejectsAnAmbientTransactionBeforeGeneratingOrChangingKeys(): void { - $generator = m::mock(KeyGenerator::class); - $generator->shouldNotReceive('generate'); + $generator = Double::for(KeyGenerator::class)->strict(); + $generator->expects('generate')->never(); $this->app->instance(KeyGenerator::class, $generator); $repository = $this->app->make(SigningKeyRepository::class); DB::beginTransaction(); @@ -361,10 +364,11 @@ public function testManagementRejectsAnAmbientTransactionBeforeGeneratingOrChang */ protected function generator(array $indices): void { - $generator = m::mock(KeyGenerator::class); + $generator = Double::for(KeyGenerator::class)->strict(); - foreach ($indices as $index) { - $generator->shouldReceive('generate')->with(2048)->once()->ordered()->andReturn(self::$keys[$index]); + if ($indices !== []) { + $generator->expects('generate')->with(2048)->times(count($indices)) + ->returns(...array_map(static fn (int $index): array => self::$keys[$index], $indices)); } $this->app->instance(KeyGenerator::class, $generator); diff --git a/tests/Passport/TokenIssuanceTest.php b/tests/Passport/TokenIssuanceTest.php index d2658d3aa3..dc6dc1ca05 100644 --- a/tests/Passport/TokenIssuanceTest.php +++ b/tests/Passport/TokenIssuanceTest.php @@ -33,9 +33,11 @@ use Hypervel\Support\Facades\Event; use Hypervel\Support\Facades\Exceptions; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use League\OAuth2\Server\Exception\OAuthServerException; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -46,7 +48,9 @@ class TokenIssuanceTest extends TestCase { - protected ServerFactory $servers; + use VerifiesDoubles; + + protected ServerFactory&DoubleInterface $servers; protected ServerEntry $entry; @@ -85,8 +89,8 @@ protected function setUpInCoroutine(): void [$private->getKeyId() => $public], [$private->getKeyId() => new SigningCryptKey($private)], ); - $this->servers = m::mock(ServerFactory::class); - $this->servers->shouldReceive('entry')->andReturn($this->entry); + $this->servers = Double::for(ServerFactory::class)->strict(); + $this->servers->allows('entry')->returns($this->entry); } #[DataProvider('outcomes')] diff --git a/tests/Passport/Unit/AuthorizationResponseTest.php b/tests/Passport/Unit/AuthorizationResponseTest.php index 2cc219bb47..56f466e7d4 100644 --- a/tests/Passport/Unit/AuthorizationResponseTest.php +++ b/tests/Passport/Unit/AuthorizationResponseTest.php @@ -9,13 +9,16 @@ use Hypervel\Passport\ServerFactory; use Hypervel\Passport\ServerSettings; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use League\OAuth2\Server\Exception\OAuthServerException; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; use Symfony\Component\HttpFoundation\Response; class AuthorizationResponseTest extends TestCase { + use VerifiesDoubles; + #[TestWith([null, false])] #[TestWith(['HTTPS://Auth.Example:443/issuer/', false])] #[TestWith(['https://auth.example', true])] @@ -79,8 +82,8 @@ public function testFormPostEscapesProtocolFieldsWithoutRestrictingTheClientsSub public function testLocalErrorsDoNotResolveOrExposeAnIssuer(): void { - $servers = m::mock(ServerFactory::class); - $servers->shouldNotReceive('settings'); + $servers = Double::for(ServerFactory::class)->strict(); + $servers->expects('settings')->never(); $response = (new AuthorizationResponse($servers))->error(OAuthServerException::invalidRequest('client_id'), null, null, 'query'); $this->assertSame(400, $response->getStatusCode()); @@ -92,8 +95,8 @@ public function testLocalErrorsDoNotResolveOrExposeAnIssuer(): void */ protected function renderer(?string $issuer): AuthorizationResponse { - $servers = m::mock(ServerFactory::class); - $servers->shouldReceive('settings')->andReturn(new ServerSettings([], issuer: $issuer)); + $servers = Double::for(ServerFactory::class)->strict(); + $servers->allows('settings')->returns(new ServerSettings([], issuer: $issuer)); return new AuthorizationResponse($servers); } diff --git a/tests/Passport/Unit/BearerTokenValidatorTest.php b/tests/Passport/Unit/BearerTokenValidatorTest.php index c3c4dbe70b..2edd6084b3 100644 --- a/tests/Passport/Unit/BearerTokenValidatorTest.php +++ b/tests/Passport/Unit/BearerTokenValidatorTest.php @@ -10,6 +10,8 @@ use Hypervel\Passport\Bridge\ParsedKey; use Hypervel\Passport\Bridge\SigningCryptKey; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Lcobucci\JWT\Configuration; use Lcobucci\JWT\Signer\Hmac\Sha256 as HmacSha256; use Lcobucci\JWT\Signer\Key\InMemory; @@ -19,12 +21,13 @@ use League\OAuth2\Server\Exception\OAuthServerException; use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface; use League\OAuth2\Server\ResourceServer; -use Mockery as m; use Nyholm\Psr7\ServerRequest; use PHPUnit\Framework\Attributes\DataProvider; class BearerTokenValidatorTest extends TestCase { + use VerifiesDoubles; + /** * @var array */ @@ -46,12 +49,12 @@ protected function setUp(): void #[DataProvider('validationCases')] public function testValidationMatchesLeague(string $scenario, bool $valid): void { - $repository = m::mock(AccessTokenRepositoryInterface::class); + $repository = Double::for(AccessTokenRepositoryInterface::class)->strict(); if ($scenario === 'valid' || $scenario === 'revoked') { - $repository->shouldReceive('isAccessTokenRevoked')->with('token-id')->twice()->andReturn($scenario === 'revoked'); + $repository->expects('isAccessTokenRevoked')->with('token-id')->times(2)->returns($scenario === 'revoked'); } else { - $repository->shouldNotReceive('isAccessTokenRevoked'); + $repository->expects('isAccessTokenRevoked')->never(); } $public = ParsedKey::fromPublicKey(self::$keys[0]['public']); @@ -105,8 +108,8 @@ public static function validationCases(): array public function testRetainedKeysVerifyNamedAndLegacyTokensThroughTheResourceServer(): void { - $repository = m::mock(AccessTokenRepositoryInterface::class); - $repository->shouldReceive('isAccessTokenRevoked')->with('token-id')->times(3)->andReturnFalse(); + $repository = Double::for(AccessTokenRepositoryInterface::class)->strict(); + $repository->expects('isAccessTokenRevoked')->with('token-id')->times(3)->returns(false); $current = ParsedKey::fromPublicKey(self::$keys[1]['public']); $retained = ParsedKey::fromPublicKey(self::$keys[0]['public']); $validator = new BearerTokenValidator($repository, [ @@ -128,8 +131,8 @@ public function testRetainedKeysVerifyNamedAndLegacyTokensThroughTheResourceServ #[DataProvider('invalidKeyIds')] public function testInvalidKeyIdsCannotFallBackToAnotherKey(mixed $identifier): void { - $repository = m::mock(AccessTokenRepositoryInterface::class); - $repository->shouldNotReceive('isAccessTokenRevoked'); + $repository = Double::for(AccessTokenRepositoryInterface::class)->strict(); + $repository->expects('isAccessTokenRevoked')->never(); $public = ParsedKey::fromPublicKey(self::$keys[0]['public']); $validator = new BearerTokenValidator($repository, [$public->getKeyId() => $public]); $request = new ServerRequest('GET', 'https://example.test', [ @@ -151,8 +154,8 @@ public static function invalidKeyIds(): array public function testConfiguredLeewayAppliesToTokenTimes(): void { - $repository = m::mock(AccessTokenRepositoryInterface::class); - $repository->shouldReceive('isAccessTokenRevoked')->with('token-id')->once()->andReturnFalse(); + $repository = Double::for(AccessTokenRepositoryInterface::class)->strict(); + $repository->expects('isAccessTokenRevoked')->with('token-id')->returns(false); $public = ParsedKey::fromPublicKey(self::$keys[0]['public']); $validator = new BearerTokenValidator($repository, [$public->getKeyId() => $public], new DateInterval('PT120S')); @@ -166,8 +169,8 @@ public function testConfiguredLeewayAppliesToTokenTimes(): void #[DataProvider('invalidIdentifiers')] public function testSignedArtifactsWithoutTokenIdentifiersAreRejectedBeforeLookup(string $scenario): void { - $repository = m::mock(AccessTokenRepositoryInterface::class); - $repository->shouldNotReceive('isAccessTokenRevoked'); + $repository = Double::for(AccessTokenRepositoryInterface::class)->strict(); + $repository->expects('isAccessTokenRevoked')->never(); $public = ParsedKey::fromPublicKey(self::$keys[0]['public']); $validator = new BearerTokenValidator($repository, [$public->getKeyId() => $public]); diff --git a/tests/Passport/Unit/BridgeScopeRepositoryTest.php b/tests/Passport/Unit/BridgeScopeRepositoryTest.php index b91b48d804..b7c555a36d 100644 --- a/tests/Passport/Unit/BridgeScopeRepositoryTest.php +++ b/tests/Passport/Unit/BridgeScopeRepositoryTest.php @@ -11,10 +11,13 @@ use Hypervel\Passport\ClientRepository; use Hypervel\Passport\Passport; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class BridgeScopeRepositoryTest extends TestCase { + use VerifiesDoubles; + public function testInvalidScopesAreRemoved(): void { Passport::tokensCan([ @@ -23,8 +26,8 @@ public function testInvalidScopesAreRemoved(): void $client = new ClientModel; - $clients = m::mock(ClientRepository::class); - $clients->expects('findActive')->with('id')->andReturn($client); + $clients = Double::for(ClientRepository::class)->strict(); + $clients->expects('findActive')->with('id')->returns($client); $repository = new ScopeRepository($clients); @@ -44,8 +47,8 @@ public function testInvalidScopesAreRemovedWithoutAClientRepository(): void 'scope-1' => 'description', ]); - $clients = m::mock(ClientRepository::class); - $clients->expects('findActive')->with('id')->andReturn(new ClientModel); + $clients = Double::for(ClientRepository::class)->strict(); + $clients->expects('findActive')->with('id')->returns(new ClientModel); $repository = new ScopeRepository($clients); @@ -69,8 +72,8 @@ public function testClientsDoNotRestrictScopesByDefault(): void $client = new ClientModel; $client->scopes = null; - $clients = m::mock(ClientRepository::class); - $clients->expects('findActive')->with('id')->andReturn($client); + $clients = Double::for(ClientRepository::class)->strict(); + $clients->expects('findActive')->with('id')->returns($client); $repository = new ScopeRepository($clients); @@ -94,8 +97,8 @@ public function testScopesDisallowedForClientAreRemoved(): void $client = new ClientModel; $client->scopes = ['scope-1']; - $clients = m::mock(ClientRepository::class); - $clients->expects('findActive')->with('id')->andReturn($client); + $clients = Double::for(ClientRepository::class)->strict(); + $clients->expects('findActive')->with('id')->returns($client); $repository = new ScopeRepository($clients); @@ -122,8 +125,8 @@ public function testScopesDisallowedForClientAreRemovedButInheritedScopesAreNot( $client = new ClientModel; $client->scopes = ['scope-1']; - $clients = m::mock(ClientRepository::class); - $clients->expects('findActive')->with('id')->andReturn($client); + $clients = Double::for(ClientRepository::class)->strict(); + $clients->expects('findActive')->with('id')->returns($client); $repository = new ScopeRepository($clients); @@ -145,8 +148,8 @@ public function testSuperuserScopeCantBeAppliedIfWrongGrant(): void $client = new ClientModel; - $clients = m::mock(ClientRepository::class); - $clients->expects('findActive')->with('id')->andReturn($client); + $clients = Double::for(ClientRepository::class)->strict(); + $clients->expects('findActive')->with('id')->returns($client); $repository = new ScopeRepository($clients); @@ -166,8 +169,8 @@ public function testSuperuserScopeCantBeAppliedIfWrongGrantWithoutAClientReposit 'scope-1' => 'description', ]); - $clients = m::mock(ClientRepository::class); - $clients->expects('findActive')->with('id')->andReturn(new ClientModel); + $clients = Double::for(ClientRepository::class)->strict(); + $clients->expects('findActive')->with('id')->returns(new ClientModel); $repository = new ScopeRepository($clients); diff --git a/tests/Passport/Unit/ClientRepositoryTest.php b/tests/Passport/Unit/ClientRepositoryTest.php index 68341da859..666488eb95 100644 --- a/tests/Passport/Unit/ClientRepositoryTest.php +++ b/tests/Passport/Unit/ClientRepositoryTest.php @@ -8,18 +8,22 @@ use Hypervel\Contracts\Foundation\Application; use Hypervel\Database\Eloquent\Builder; use Hypervel\Database\Eloquent\Concerns\HasUlids; +use Hypervel\Database\Query\Builder as QueryBuilder; use Hypervel\Database\QueryException; use Hypervel\Passport\Client; use Hypervel\Passport\ClientRepository; use Hypervel\Passport\Passport; use Hypervel\Passport\PassportServiceProvider; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDOException; use RuntimeException; class ClientRepositoryTest extends TestCase { + use VerifiesDoubles; + /** * Register the configured cache and model services. */ @@ -63,9 +67,10 @@ public function testValidUuidClientIdsAreLookedUp(): void { $id = '550e8400-e29b-41d4-a716-446655440000'; $client = new Client; - $query = m::mock(Builder::class); - $query->expects('useWritePdo')->andReturnSelf(); - $query->expects('find')->with($id)->andReturn($client); + $baseQuery = Double::for(QueryBuilder::class)->strict(); + $baseQuery->expects('useWritePdo'); + $query = Double::for(new Builder($baseQuery))->passthru(); + $query->expects('find')->with($id)->returns($client); ClientRepositoryTestClient::$query = fn () => $query; $this->assertSame($client, (new ClientRepository)->find($id)); @@ -79,9 +84,10 @@ public function testCustomUniqueIdClientIdsAreValidatedByTheModel(): void $id = '01ARZ3NDEKTSV4RRFFQ69G5FAV'; $client = new Client; - $query = m::mock(Builder::class); - $query->expects('useWritePdo')->andReturnSelf(); - $query->expects('find')->with($id)->andReturn($client); + $baseQuery = Double::for(QueryBuilder::class)->strict(); + $baseQuery->expects('useWritePdo'); + $query = Double::for(new Builder($baseQuery))->passthru(); + $query->expects('find')->with($id)->returns($client); ClientRepositoryTestClient::$query = fn () => $query; $repository = new ClientRepository; diff --git a/tests/Passport/Unit/HasApiTokensTest.php b/tests/Passport/Unit/HasApiTokensTest.php index 70b7d2ff39..bc5bc07a2e 100644 --- a/tests/Passport/Unit/HasApiTokensTest.php +++ b/tests/Passport/Unit/HasApiTokensTest.php @@ -9,16 +9,19 @@ use Hypervel\Passport\Contracts\OAuthenticatable; use Hypervel\Passport\HasApiTokens; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class HasApiTokensTest extends TestCase { + use VerifiesDoubles; + public function testTokenCanIndicatesIfTokenHasGivenScope(): void { $user = new HasApiTokensTestStub; - $token = m::mock(AccessToken::class); - $token->expects('can')->with('scope')->andReturn(true); - $token->expects('can')->with('another-scope')->andReturn(false); + $token = Double::for(AccessToken::class)->strict(); + $token->expects('can')->with('scope')->returns(true); + $token->expects('can')->with('another-scope')->returns(false); $this->assertTrue($user->withAccessToken($token)->tokenCan('scope')); $this->assertFalse($user->withAccessToken($token)->tokenCan('another-scope')); diff --git a/tests/Passport/Unit/ServerFactoryValidationTest.php b/tests/Passport/Unit/ServerFactoryValidationTest.php index 8adc674257..fecec3cb52 100644 --- a/tests/Passport/Unit/ServerFactoryValidationTest.php +++ b/tests/Passport/Unit/ServerFactoryValidationTest.php @@ -12,20 +12,23 @@ use Hypervel\Passport\Bridge\BearerRequestFactory; use Hypervel\Passport\ServerFactory; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use League\OAuth2\Server\Exception\OAuthServerException; use League\OAuth2\Server\ResourceServer; -use Mockery as m; use Nyholm\Psr7\Factory\Psr17Factory; use Nyholm\Psr7\ServerRequest; use Psr\Http\Message\ServerRequestInterface; class ServerFactoryValidationTest extends TestCase { + use VerifiesDoubles; + public function testRepeatedValidationUsesOneResult(): void { $result = (new ServerRequest('GET', '/'))->withAttribute('oauth_access_token_id', 'token'); - $server = m::mock(ResourceServer::class); - $server->shouldReceive('validateAuthenticatedRequest')->once()->andReturn($result); + $server = Double::for(ResourceServer::class)->strict(); + $server->expects('validateAuthenticatedRequest')->returns($result); CoroutineContext::set(ServerFactory::RESOURCE_SERVER_CONTEXT_KEY, $server); $factory = $this->factory(); $request = Request::create('/'); @@ -38,8 +41,8 @@ public function testRepeatedValidationUsesOneResult(): void public function testFailedValidationIsAlsoReused(): void { $failure = OAuthServerException::accessDenied('Invalid signature'); - $server = m::mock(ResourceServer::class); - $server->shouldReceive('validateAuthenticatedRequest')->once()->andThrow($failure); + $server = Double::for(ResourceServer::class)->strict(); + $server->expects('validateAuthenticatedRequest')->throws($failure); CoroutineContext::set(ServerFactory::RESOURCE_SERVER_CONTEXT_KEY, $server); $factory = $this->factory(); $request = Request::create('/'); @@ -56,9 +59,9 @@ public function testFailedValidationIsAlsoReused(): void public function testNewRequestsAndChangedCredentialsAreValidated(): void { - $server = m::mock(ResourceServer::class); - $server->shouldReceive('validateAuthenticatedRequest')->times(3) - ->andReturnUsing(static fn (ServerRequestInterface $request): ServerRequestInterface => $request); + $server = Double::for(ResourceServer::class)->strict(); + $server->expects('validateAuthenticatedRequest')->times(3) + ->resolves(static fn (ServerRequestInterface $request): ServerRequestInterface => $request); CoroutineContext::set(ServerFactory::RESOURCE_SERVER_CONTEXT_KEY, $server); $factory = $this->factory(); $first = Request::create('/'); @@ -76,10 +79,10 @@ public function testChangingTheResourceServerCannotReuseItsPredecessorsResult(): { $firstResult = (new ServerRequest('GET', '/'))->withAttribute('oauth_client_id', 'first'); $secondResult = (new ServerRequest('GET', '/'))->withAttribute('oauth_client_id', 'second'); - $first = m::mock(ResourceServer::class); - $first->shouldReceive('validateAuthenticatedRequest')->once()->andReturn($firstResult); - $second = m::mock(ResourceServer::class); - $second->shouldReceive('validateAuthenticatedRequest')->once()->andReturn($secondResult); + $first = Double::for(ResourceServer::class)->strict(); + $first->expects('validateAuthenticatedRequest')->returns($firstResult); + $second = Double::for(ResourceServer::class)->strict(); + $second->expects('validateAuthenticatedRequest')->returns($secondResult); $factory = $this->factory(); $request = Request::create('/'); @@ -93,9 +96,12 @@ public function testExplicitValidationBypassesASuccessfulCachedResult(): void { $result = new ServerRequest('GET', '/'); $failure = OAuthServerException::accessDenied('Revoked'); - $server = m::mock(ResourceServer::class); - $server->shouldReceive('validateAuthenticatedRequest')->once()->ordered()->andReturn($result); - $server->shouldReceive('validateAuthenticatedRequest')->once()->ordered()->andThrow($failure); + $server = Double::for(ResourceServer::class)->strict(); + $calls = 0; + $server->expects('validateAuthenticatedRequest')->times(2) + ->resolves(static function () use (&$calls, $result, $failure): ServerRequestInterface { + return ++$calls === 1 ? $result : throw $failure; + }); CoroutineContext::set(ServerFactory::RESOURCE_SERVER_CONTEXT_KEY, $server); $factory = $this->factory(); $request = Request::create('/'); @@ -108,8 +114,8 @@ public function testExplicitValidationBypassesASuccessfulCachedResult(): void public function testExplicitValidationDoesNotPopulateTheCache(): void { - $server = m::mock(ResourceServer::class); - $server->shouldReceive('validateAuthenticatedRequest')->twice()->andReturn(new ServerRequest('GET', '/')); + $server = Double::for(ResourceServer::class)->strict(); + $server->expects('validateAuthenticatedRequest')->times(2)->returns(new ServerRequest('GET', '/')); CoroutineContext::set(ServerFactory::RESOURCE_SERVER_CONTEXT_KEY, $server); $factory = $this->factory(); $request = Request::create('/'); @@ -120,9 +126,9 @@ public function testExplicitValidationDoesNotPopulateTheCache(): void public function testBearerConversionDoesNotCopyTheRequestBody(): void { - $server = m::mock(ResourceServer::class); - $server->shouldReceive('validateAuthenticatedRequest')->once() - ->andReturnUsing(function (ServerRequestInterface $request): ServerRequestInterface { + $server = Double::for(ResourceServer::class)->strict(); + $server->expects('validateAuthenticatedRequest') + ->resolves(function (ServerRequestInterface $request): ServerRequestInterface { $this->assertSame('', (string) $request->getBody()); $this->assertNull($request->getParsedBody()); $this->assertSame([], $request->getUploadedFiles()); @@ -148,7 +154,7 @@ protected function factory(): ServerFactory return new ServerFactory( new Container, new Repository, - m::mock(Encrypter::class), + Double::for(Encrypter::class)->strict(), new BearerRequestFactory(new Psr17Factory), ); } diff --git a/tests/Passport/Unit/SimpleViewResponseTest.php b/tests/Passport/Unit/SimpleViewResponseTest.php index 48a3118232..e1ef131e92 100644 --- a/tests/Passport/Unit/SimpleViewResponseTest.php +++ b/tests/Passport/Unit/SimpleViewResponseTest.php @@ -14,18 +14,21 @@ use Hypervel\Passport\Http\Responses\SimpleViewResponse; use Hypervel\Passport\Passport; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; class SimpleViewResponseTest extends TestCase { + use VerifiesDoubles; + #[TestWith(['viewNamespace', 'passport', 'passport::'])] #[TestWith(['viewPrefix', 'auth', 'auth.'])] #[TestWith(['viewPrefix', 'auth.', 'auth.'])] public function testConventionalViewsPreserveNamespacesAndDirectoryPrefixes(string $method, string $prefix, string $expectedPrefix): void { Passport::{$method}($prefix); - $factory = m::mock(ResponseFactory::class); + $factory = Double::for(ResponseFactory::class)->strict(); $this->app->instance(ResponseFactory::class, $factory); foreach ([ @@ -34,7 +37,7 @@ public function testConventionalViewsPreserveNamespacesAndDirectoryPrefixes(stri DeviceUserCodeViewResponse::class => 'device.user-code', ] as $contract => $name) { $expected = new Response('Consent'); - $factory->shouldReceive('view')->once()->with($expectedPrefix . $name, [])->andReturn($expected); + $factory->expects('view')->with($expectedPrefix . $name, [])->returns($expected); $this->assertSame($expected, $this->app->make($contract)->toResponse(Request::create('/'))); } @@ -43,8 +46,8 @@ public function testConventionalViewsPreserveNamespacesAndDirectoryPrefixes(stri public function testNamedViewsReceiveTheirParameters(): void { $expected = new Response('Consent'); - $factory = m::mock(ResponseFactory::class); - $factory->shouldReceive('view')->once()->with('oauth.authorize', ['client' => 'example'])->andReturn($expected); + $factory = Double::for(ResponseFactory::class)->strict(); + $factory->expects('view')->with('oauth.authorize', ['client' => 'example'])->returns($expected); $this->app->instance(ResponseFactory::class, $factory); $response = (new SimpleViewResponse('oauth.authorize'))->withParameters(['client' => 'example']); @@ -56,8 +59,8 @@ public function testCallbacksCanReturnResponsableObjects(): void { $request = Request::create('/oauth/authorize'); $expected = new Response('Consent', 202, ['X-Consent' => 'pending']); - $responsable = m::mock(Responsable::class); - $responsable->shouldReceive('toResponse')->once()->with($request)->andReturn($expected); + $responsable = Double::for(Responsable::class)->strict(); + $responsable->expects('toResponse')->with($request)->returns($expected); $response = new SimpleViewResponse(function (array $parameters) use ($responsable): Responsable { $this->assertSame(['client' => 'example'], $parameters); diff --git a/tests/Passport/Unit/TokenGuardTest.php b/tests/Passport/Unit/TokenGuardTest.php index 68db5556da..8a7103f960 100644 --- a/tests/Passport/Unit/TokenGuardTest.php +++ b/tests/Passport/Unit/TokenGuardTest.php @@ -23,13 +23,17 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Passport\Fixtures\User as TokenGuardTestUser; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; class TokenGuardTest extends TestCase { + use VerifiesDoubles; + // REMOVED: User/client integer-ID collisions require the pre-13 client schema. /** @@ -44,8 +48,8 @@ protected function defineEnvironment(Application $app): void #[TestWith(['Basic dXNlcjpwYXNzd29yZA=='])] public function testUsersMayBeRetrievedFromCookiesWithCsrfTokenHeader(?string $authorization): void { - $userProvider = m::mock(PassportUserProvider::class); - $clients = m::mock(ClientRepository::class); + $userProvider = Double::for(PassportUserProvider::class)->strict(); + $clients = Double::for(ClientRepository::class)->strict(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $key = hash_hkdf('sha256', $encrypter->getKey(), 32, 'hypervel-passport-cookie'); @@ -64,7 +68,7 @@ public function testUsersMayBeRetrievedFromCookiesWithCsrfTokenHeader(?string $a $guard = $this->makeGuard($userProvider, $clients, $encrypter, $request); - $userProvider->expects('retrieveById')->twice()->with(1)->andReturn($expectedUser = new TokenGuardTestUser); + $userProvider->expects('retrieveById')->times(2)->with(1)->returns($expectedUser = new TokenGuardTestUser); $user = $guard->user(); @@ -78,8 +82,8 @@ public function testUsersMayBeRetrievedFromCookiesWithCsrfTokenHeader(?string $a public function testUsersMayBeRetrievedFromCookiesWithXsrfTokenHeader(): void { - $userProvider = m::mock(PassportUserProvider::class); - $clients = m::mock(ClientRepository::class); + $userProvider = Double::for(PassportUserProvider::class)->strict(); + $clients = Double::for(ClientRepository::class)->strict(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $key = hash_hkdf('sha256', $encrypter->getKey(), 32, 'hypervel-passport-cookie'); @@ -97,7 +101,7 @@ public function testUsersMayBeRetrievedFromCookiesWithXsrfTokenHeader(): void $guard = $this->makeGuard($userProvider, $clients, $encrypter, $request); - $userProvider->expects('retrieveById')->with(1)->andReturn($expectedUser = new TokenGuardTestUser); + $userProvider->expects('retrieveById')->with(1)->returns($expectedUser = new TokenGuardTestUser); $user = $guard->user(); @@ -106,8 +110,8 @@ public function testUsersMayBeRetrievedFromCookiesWithXsrfTokenHeader(): void public function testCookieXsrfIsVerifiedAgainstCsrfTokenHeader(): void { - $userProvider = m::mock(PassportUserProvider::class); - $clients = m::mock(ClientRepository::class); + $userProvider = Double::for(PassportUserProvider::class)->strict(); + $clients = Double::for(ClientRepository::class)->strict(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $key = hash_hkdf('sha256', $encrypter->getKey(), 32, 'hypervel-passport-cookie'); @@ -132,8 +136,8 @@ public function testCookieXsrfIsVerifiedAgainstCsrfTokenHeader(): void public function testCookieXsrfIsVerifiedAgainstXsrfTokenHeader(): void { - $userProvider = m::mock(PassportUserProvider::class); - $clients = m::mock(ClientRepository::class); + $userProvider = Double::for(PassportUserProvider::class)->strict(); + $clients = Double::for(ClientRepository::class)->strict(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $key = hash_hkdf('sha256', $encrypter->getKey(), 32, 'hypervel-passport-cookie'); @@ -162,8 +166,8 @@ public function testUsersMayBeRetrievedFromCookiesWithXsrfTokenHeaderWhenUsingAC return $encrypter->getKey() . '.mykey'; }); - $userProvider = m::mock(PassportUserProvider::class); - $clients = m::mock(ClientRepository::class); + $userProvider = Double::for(PassportUserProvider::class)->strict(); + $clients = Double::for(ClientRepository::class)->strict(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $request = Request::create('/'); @@ -180,7 +184,7 @@ public function testUsersMayBeRetrievedFromCookiesWithXsrfTokenHeaderWhenUsingAC $guard = $this->makeGuard($userProvider, $clients, $encrypter, $request); - $userProvider->expects('retrieveById')->with(1)->andReturn($expectedUser = new TokenGuardTestUser); + $userProvider->expects('retrieveById')->with(1)->returns($expectedUser = new TokenGuardTestUser); $user = $guard->user(); @@ -194,8 +198,8 @@ public function testUsersMayBeRetrievedFromCookiesWithoutEncryption(): void return $encrypter->getKey() . '.mykey'; }); - $userProvider = m::mock(PassportUserProvider::class); - $clients = m::mock(ClientRepository::class); + $userProvider = Double::for(PassportUserProvider::class)->strict(); + $clients = Double::for(ClientRepository::class)->strict(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $request = Request::create('/'); @@ -212,7 +216,7 @@ public function testUsersMayBeRetrievedFromCookiesWithoutEncryption(): void $guard = $this->makeGuard($userProvider, $clients, $encrypter, $request); - $userProvider->expects('retrieveById')->with(1)->andReturn($expectedUser = new TokenGuardTestUser); + $userProvider->expects('retrieveById')->with(1)->returns($expectedUser = new TokenGuardTestUser); $user = $guard->user(); @@ -227,11 +231,11 @@ public function testArrayCookiesAreRejected(bool $encrypted): void Passport::withoutCookieEncryption(); } - $userProvider = m::mock(PassportUserProvider::class); - $userProvider->shouldNotReceive('retrieveById'); + $userProvider = Double::for(PassportUserProvider::class)->strict(); + $userProvider->expects('retrieveById')->never(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $request = Request::create('/', cookies: [Passport::cookie() => ['x' => '1']]); - $guard = $this->makeGuard($userProvider, m::mock(ClientRepository::class), $encrypter, $request); + $guard = $this->makeGuard($userProvider, Double::for(ClientRepository::class)->strict(), $encrypter, $request); $this->assertNull($guard->user()); $this->assertFalse($guard->validate(['request' => $request])); @@ -239,8 +243,8 @@ public function testArrayCookiesAreRejected(bool $encrypted): void public function testXsrfTokenCookieWithoutATokenHeaderIsNotAccepted(): void { - $userProvider = m::mock(PassportUserProvider::class); - $clients = m::mock(ClientRepository::class); + $userProvider = Double::for(PassportUserProvider::class)->strict(); + $clients = Double::for(ClientRepository::class)->strict(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $key = hash_hkdf('sha256', $encrypter->getKey(), 32, 'hypervel-passport-cookie'); @@ -265,8 +269,8 @@ public function testXsrfTokenCookieWithoutATokenHeaderIsNotAccepted(): void public function testExpiredCookiesMayNotBeUsed(): void { - $userProvider = m::mock(PassportUserProvider::class); - $clients = m::mock(ClientRepository::class); + $userProvider = Double::for(PassportUserProvider::class)->strict(); + $clients = Double::for(ClientRepository::class)->strict(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $key = hash_hkdf('sha256', $encrypter->getKey(), 32, 'hypervel-passport-cookie'); @@ -291,8 +295,8 @@ public function testExpiredCookiesMayNotBeUsed(): void public function testCsrfCheckCanBeDisabled(): void { - $userProvider = m::mock(PassportUserProvider::class); - $clients = m::mock(ClientRepository::class); + $userProvider = Double::for(PassportUserProvider::class)->strict(); + $clients = Double::for(ClientRepository::class)->strict(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $key = hash_hkdf('sha256', $encrypter->getKey(), 32, 'hypervel-passport-cookie'); @@ -310,7 +314,7 @@ public function testCsrfCheckCanBeDisabled(): void $guard = $this->makeGuard($userProvider, $clients, $encrypter, $request); - $userProvider->expects('retrieveById')->with(1)->andReturn($expectedUser = new TokenGuardTestUser); + $userProvider->expects('retrieveById')->with(1)->returns($expectedUser = new TokenGuardTestUser); $user = $guard->user(); @@ -320,8 +324,8 @@ public function testCsrfCheckCanBeDisabled(): void // REMOVED: Cookie client lookup; factory cookies carry no aud claim and have no OAuth client. public function testCookiesHaveNoOauthClient(): void { - $userProvider = m::mock(PassportUserProvider::class); - $clients = m::mock(ClientRepository::class); + $userProvider = Double::for(PassportUserProvider::class)->strict(); + $clients = Double::for(ClientRepository::class)->strict(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $request = Request::create('/'); @@ -334,8 +338,8 @@ public function testCookiesHaveNoOauthClient(): void CookieValuePrefix::create($cookie->getName(), $encrypter->getKey()) . $cookie->getValue(), false )); - $userProvider->expects('retrieveById')->with(1)->andReturn(new TokenGuardTestUser); - $clients->shouldNotReceive('findActive'); + $userProvider->expects('retrieveById')->with(1)->returns(new TokenGuardTestUser); + $clients->expects('findActive')->never(); $this->assertInstanceOf(TokenGuardTestUser::class, $guard->user()); $this->assertNull($guard->client()); @@ -347,8 +351,8 @@ public function testCookiesHaveNoOauthClient(): void #[TestWith([['provider' => 'admins']])] public function testCookiesRequireTheGuardsProvider(array $providerClaim): void { - $userProvider = m::mock(PassportUserProvider::class); - $userProvider->shouldNotReceive('retrieveById'); + $userProvider = Double::for(PassportUserProvider::class)->strict(); + $userProvider->expects('retrieveById')->never(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $request = Request::create('/'); $request->headers->set('X-CSRF-TOKEN', 'token'); @@ -362,7 +366,7 @@ public function testCookiesRequireTheGuardsProvider(array $providerClaim): void false )); - $guard = $this->makeGuard($userProvider, m::mock(ClientRepository::class), $encrypter, $request); + $guard = $this->makeGuard($userProvider, Double::for(ClientRepository::class)->strict(), $encrypter, $request); $this->assertNull($guard->user()); } @@ -371,7 +375,7 @@ public function testCookiesRequireTheGuardsProvider(array $providerClaim): void public function testCookieBindingIsCheckedBeforeLoadingTheUser(array $bindingClaim, ?string $binding, bool $accepted): void { Passport::bindCookiesUsing(static fn (Request $request): ?string => $request->headers->get('X-Organization')); - $userProvider = m::mock(PassportUserProvider::class); + $userProvider = Double::for(PassportUserProvider::class)->strict(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $request = Request::create('/'); $request->headers->set('X-Organization', $binding); @@ -389,12 +393,12 @@ public function testCookieBindingIsCheckedBeforeLoadingTheUser(array $bindingCla $expected = $accepted ? new TokenGuardTestUser : null; if ($accepted) { - $userProvider->expects('retrieveById')->with(1)->andReturn($expected); + $userProvider->expects('retrieveById')->with(1)->returns($expected); } else { - $userProvider->shouldNotReceive('retrieveById'); + $userProvider->expects('retrieveById')->never(); } - $guard = $this->makeGuard($userProvider, m::mock(ClientRepository::class), $encrypter, $request); + $guard = $this->makeGuard($userProvider, Double::for(ClientRepository::class)->strict(), $encrypter, $request); $this->assertSame($expected, $guard->user()); @@ -423,7 +427,7 @@ public static function cookieBindings(): array public function testUserProviderFailuresAreNotTreatedAsInvalidCookies(): void { - $userProvider = m::mock(PassportUserProvider::class); + $userProvider = Double::for(PassportUserProvider::class)->strict(); $encrypter = new Encrypter(str_repeat('a', 32), 'aes-256-cbc'); $request = Request::create('/'); $request->headers->set('X-CSRF-TOKEN', 'token'); @@ -437,8 +441,8 @@ public function testUserProviderFailuresAreNotTreatedAsInvalidCookies(): void false )); $failure = new RuntimeException('User provider unavailable.'); - $userProvider->expects('retrieveById')->with(1)->andThrow($failure); - $guard = $this->makeGuard($userProvider, m::mock(ClientRepository::class), $encrypter, $request); + $userProvider->expects('retrieveById')->with(1)->throws($failure); + $guard = $this->makeGuard($userProvider, Double::for(ClientRepository::class)->strict(), $encrypter, $request); $this->expectExceptionObject($failure); @@ -459,16 +463,16 @@ public function testNewGuardWithTheSameNameStartsWithoutThePreviousGuardsUsersAn ], hash_hkdf('sha256', $encrypter->getKey(), 32, 'hypervel-passport-cookie'), 'HS256'), false )); - $previousProvider = m::mock(PassportUserProvider::class); - $previousProvider->expects('retrieveById')->with(1)->andReturn(new TokenGuardTestUser); - $previousGuard = $this->makeGuard($previousProvider, m::mock(ClientRepository::class), $encrypter, $request); + $previousProvider = Double::for(PassportUserProvider::class)->strict(); + $previousProvider->expects('retrieveById')->with(1)->returns(new TokenGuardTestUser); + $previousGuard = $this->makeGuard($previousProvider, Double::for(ClientRepository::class)->strict(), $encrypter, $request); $this->assertNotNull($previousGuard->user()); $previousGuard->setUser(new TokenGuardTestUser); $previousGuard->setClient(new Client); - $provider = m::mock(PassportUserProvider::class); - $provider->expects('retrieveById')->with(1)->andReturnNull(); + $provider = Double::for(PassportUserProvider::class)->strict(); + $provider->expects('retrieveById')->with(1)->returns(null); - $guard = $this->makeGuard($provider, m::mock(ClientRepository::class), $encrypter, $request); + $guard = $this->makeGuard($provider, Double::for(ClientRepository::class)->strict(), $encrypter, $request); $this->assertFalse($guard->hasUser()); $this->assertNull($guard->user()); @@ -478,10 +482,10 @@ public function testNewGuardWithTheSameNameStartsWithoutThePreviousGuardsUsersAn /** * Create the guard with real key derivation and the coroutine's request. */ - protected function makeGuard(PassportUserProvider $provider, ClientRepository $clients, EncrypterContract $encrypter, Request $request): TokenGuard + protected function makeGuard(PassportUserProvider&DoubleInterface $provider, ClientRepository $clients, EncrypterContract $encrypter, Request $request): TokenGuard { RequestContext::set($request); - $provider->allows('getProviderName')->andReturn('users'); + $provider->allows('getProviderName')->returns('users'); return new TokenGuard( 'passport', diff --git a/tests/Pennant/StoredValueCacheTest.php b/tests/Pennant/StoredValueCacheTest.php index 05ce17a350..9b48793dde 100644 --- a/tests/Pennant/StoredValueCacheTest.php +++ b/tests/Pennant/StoredValueCacheTest.php @@ -16,8 +16,9 @@ use Hypervel\Support\Facades\Event; use Hypervel\Testbench\Attributes\DefineEnvironment; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonSerializable; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -29,6 +30,7 @@ class StoredValueCacheTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; protected function defineEnvironment(Application $app): void { @@ -236,9 +238,9 @@ public static function emptyWrites(): array public function testValuesAreNotCachedWhenNewTokensCantBeStored(): void { - $cache = m::mock(Repository::class); - $cache->shouldReceive('get')->once()->andReturnUsing(fn (array $keys) => array_fill_keys($keys, null)); - $cache->shouldReceive('put')->once()->andReturnFalse(); + $cache = Double::for(Repository::class)->strict(); + $cache->expects('get')->resolves(fn (array $keys) => array_fill_keys($keys, null)); + $cache->expects('put')->returns(false); $this->app->make('cache')->extend('mocked', fn () => $cache); config([ 'cache.stores.mocked' => ['driver' => 'mocked'], @@ -278,10 +280,10 @@ protected function withFailingInvalidationTarget(Application $app): void public function testATargetThatCantStoreTokensDoesntStopTheOthers(): void { - $failing = m::mock(Repository::class); - $failing->shouldReceive('put')->once()->andReturnFalse(); - $working = m::mock(Repository::class); - $working->shouldReceive('put')->once()->andReturnTrue(); + $failing = Double::for(Repository::class)->strict(); + $failing->expects('put')->returns(false); + $working = Double::for(Repository::class)->strict(); + $working->expects('put')->returns(true); $this->expectExceptionObject(new RuntimeException('Unable to invalidate cached feature values. They may be stale until they expire.')); @@ -291,10 +293,10 @@ public function testATargetThatCantStoreTokensDoesntStopTheOthers(): void public function testATargetThatThrowsDoesntStopTheOthers(): void { $exception = new RuntimeException('The cache is unavailable.'); - $failing = m::mock(Repository::class); - $failing->shouldReceive('put')->once()->andThrow($exception); - $working = m::mock(Repository::class); - $working->shouldReceive('put')->once()->andReturnTrue(); + $failing = Double::for(Repository::class)->strict(); + $failing->expects('put')->throws($exception); + $working = Double::for(Repository::class)->strict(); + $working->expects('put')->returns(true); try { (new StoredValueCache('features', [[$failing, 60], [$working, 60]]))->rotatePartition('testing', null); @@ -314,12 +316,12 @@ public function testCancellationStopsInvalidationAfterAnOrdinaryFailure(bool $wr $failure = new RuntimeException('Invalidation cleanup failed.', previous: $failure); } - $failed = m::mock(Repository::class); - $failed->shouldReceive('put')->once()->andReturnFalse(); - $canceled = m::mock(Repository::class); - $canceled->shouldReceive('put')->once()->andThrow($failure); - $unvisited = m::mock(Repository::class); - $unvisited->shouldNotReceive('put'); + $failed = Double::for(Repository::class)->strict(); + $failed->expects('put')->returns(false); + $canceled = Double::for(Repository::class)->strict(); + $canceled->expects('put')->throws($failure); + $unvisited = Double::for(Repository::class)->strict(); + $unvisited->expects('put')->never(); $caught = null; try { diff --git a/tests/Permission/Events/EventTest.php b/tests/Permission/Events/EventTest.php index 2cfde64c48..b56cfe0a75 100644 --- a/tests/Permission/Events/EventTest.php +++ b/tests/Permission/Events/EventTest.php @@ -14,10 +14,14 @@ use Hypervel\Support\Facades\Event; use Hypervel\Tests\Permission\Fixtures\Models\User; use Hypervel\Tests\Permission\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class EventTest extends TestCase { + use VerifiesDoubles; + public function testRoleAttachedEventIsNotDispatchedWhenEventsAreDisabled(): void { Event::fake([RoleAttachedEvent::class]); @@ -31,10 +35,10 @@ public function testRoleAttachedEventChecksListenersBeforeDispatching(): void { $this->app->make('config')->set('permission.events_enabled', true); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->byDefault()->andReturnFalse(); - $events->shouldReceive('hasListeners')->once()->with(RoleAttachedEvent::class)->andReturnFalse(); - $events->shouldReceive('dispatch')->with(m::type(RoleAttachedEvent::class), m::any(), m::any())->never(); + $events = Double::for(Dispatcher::class)->strict(); + $events->allows('hasListeners')->with(Argument::not(RoleAttachedEvent::class))->returns(false); + $events->expects('hasListeners')->with(RoleAttachedEvent::class)->returns(false); + $events->expects('dispatch')->with(Argument::type(RoleAttachedEvent::class), Argument::any(), Argument::any())->never(); $this->app->instance('events', $events); $this->app->instance(Dispatcher::class, $events); diff --git a/tests/Permission/GuardTest.php b/tests/Permission/GuardTest.php index 2bdf60c7a8..153a43d52b 100644 --- a/tests/Permission/GuardTest.php +++ b/tests/Permission/GuardTest.php @@ -14,11 +14,14 @@ use Hypervel\Support\Facades\Auth; use Hypervel\Tests\Permission\Fixtures\Models\Admin; use Hypervel\Tests\Permission\Fixtures\Models\User; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class GuardTest extends TestCase { + use VerifiesDoubles; + public function testItReturnsNullForTheModelOfAGuardThatHasNoProviderConfigured(): void { config()->set('auth.guards.no-provider-guard', []); @@ -51,7 +54,7 @@ public function testItReturnsNullFromGetPassportClientWhenTheResolvedGuardDoesNo ]); // The auth manager's guard() return type rejects upstream's stdClass, so use a guard without client(). - Auth::shouldReceive('guard')->once()->with('fake-passport')->andReturn(m::mock(GuardContract::class)); + Auth::shouldReceive('guard')->once()->with('fake-passport')->andReturn(Double::for(GuardContract::class)->strict()); $this->assertNull(Guard::getPassportClient('web')); } diff --git a/tests/Permission/Integration/CacheTest.php b/tests/Permission/Integration/CacheTest.php index 74882b790b..7e1f055b27 100644 --- a/tests/Permission/Integration/CacheTest.php +++ b/tests/Permission/Integration/CacheTest.php @@ -14,10 +14,13 @@ use Hypervel\Support\Facades\DB; use Hypervel\Tests\Permission\Fixtures\Models\User; use Hypervel\Tests\Permission\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class CacheTest extends TestCase { + use VerifiesDoubles; + protected PermissionRegistrar $registrar; protected int $cacheInitCount = 0; @@ -340,13 +343,12 @@ public function testItCanResetTheCacheWithArtisanCommand(): void public function testItShowsAnErrorWhenTheCacheExistsButCannotBeFlushed(): void { - $registrar = m::mock(PermissionRegistrar::class)->makePartial(); - $registrar->cacheKey = $this->registrar->cacheKey; - $registrar->shouldReceive('forgetCachedPermissions')->once()->andReturn(false); + $registrar = Double::for($this->registrar)->passthru(); + $registrar->expects('forgetCachedPermissions')->returns(false); - $cacheRepository = m::mock(Repository::class); - $cacheRepository->shouldReceive('has')->with($registrar->cacheKey)->andReturn(true); - $registrar->shouldReceive('getCacheRepository')->once()->andReturn($cacheRepository); + $cacheRepository = Double::for(Repository::class)->strict(); + $cacheRepository->allows('has')->with($registrar->cacheKey)->returns(true); + $registrar->expects('getCacheRepository')->returns($cacheRepository); $this->app->instance(PermissionRegistrar::class, $registrar); diff --git a/tests/Permission/PartitionQueueContextTest.php b/tests/Permission/PartitionQueueContextTest.php index 9509aa9143..c93df72a0d 100644 --- a/tests/Permission/PartitionQueueContextTest.php +++ b/tests/Permission/PartitionQueueContextTest.php @@ -16,10 +16,13 @@ use Hypervel\Tests\Permission\Fixtures\Models\PartitionedPermission; use Hypervel\Tests\Permission\Fixtures\Models\PartitionedRole; use Hypervel\Tests\Permission\Fixtures\PartitionContext; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class PartitionQueueContextTest extends PartitionTestCase { + use VerifiesDoubles; + public function testQueuePayloadHydratesPartitionBeforeRestoringModelsAndCheckingPermission(): void { $user = GlobalPartitionUser::create(['email' => 'global@example.com']); @@ -38,8 +41,8 @@ public function testQueuePayloadHydratesPartitionBeforeRestoringModelsAndCheckin CoroutineContext::flush(); - $job = m::mock(JobContract::class); - $job->shouldReceive('payload')->andReturn($payload); + $job = Double::for(JobContract::class)->strict(); + $job->allows('payload')->returns($payload); $this->app->make('events')->dispatch(new JobProcessing('sync', $job)); $this->assertSame(self::PARTITION_A, PartitionContext::get()); diff --git a/tests/Pipeline/PipelineTest.php b/tests/Pipeline/PipelineTest.php index b9157cc3e0..8a7aee67c5 100644 --- a/tests/Pipeline/PipelineTest.php +++ b/tests/Pipeline/PipelineTest.php @@ -13,12 +13,15 @@ use Hypervel\Pipeline\Pipeline; use Hypervel\Tests\Pipeline\Fixtures\FooPipeline; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use stdClass; class PipelineTest extends TestCase { + use VerifiesDoubles; + public function testPipelineBasicUsage(): void { $pipeTwo = function ($piped, $next) { @@ -354,10 +357,10 @@ public function testCompiledClosureAppliesFinallyWhenAnInvocationThrows(): void public function testCompiledClosureAppliesTransactionToEveryInvocation(): void { $container = new Container; - $connection = m::mock(Connection::class); - $connection->shouldReceive('transaction')->twice()->andReturnUsing(fn (callable $callback) => $callback()); - $manager = m::mock(DatabaseManager::class); - $manager->shouldReceive('connection')->twice()->with(null)->andReturn($connection); + $connection = Double::for(Connection::class)->strict(); + $connection->expects('transaction')->times(2)->resolves(fn (callable $callback) => $callback()); + $manager = Double::for(DatabaseManager::class)->strict(); + $manager->expects('connection')->times(2)->with(null)->returns($connection); $container->instance('db', $manager); $pipeline = (new Pipeline($container)) @@ -436,10 +439,10 @@ public function testPipelineThrowsExceptionWhenUsingTransactionsWithoutContainer public function testPipelineDelegatesIntegerBackedEnumTransactionConnection(): void { $container = new Container; - $connection = m::mock(Connection::class); - $connection->shouldReceive('transaction')->once()->andReturnUsing(fn (callable $callback) => $callback()); - $manager = m::mock(DatabaseManager::class); - $manager->shouldReceive('connection')->once()->with(PipelineConnectionName::Zero)->andReturn($connection); + $connection = Double::for(Connection::class)->strict(); + $connection->expects('transaction')->resolves(fn (callable $callback) => $callback()); + $manager = Double::for(DatabaseManager::class)->strict(); + $manager->expects('connection')->with(PipelineConnectionName::Zero)->returns($connection); $container->instance('db', $manager); $result = (new Pipeline($container)) diff --git a/tests/Process/ProcessTest.php b/tests/Process/ProcessTest.php index ebb251214e..080ce12cb2 100644 --- a/tests/Process/ProcessTest.php +++ b/tests/Process/ProcessTest.php @@ -25,7 +25,9 @@ use Hypervel\Support\Traits\GuardsProcessOutput; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use OutOfBoundsException; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\Attributes\RequiresOperatingSystem; @@ -42,6 +44,8 @@ class ProcessTest extends TestCase { + use VerifiesDoubles; + public function testSuccessfulProcess(): void { $factory = new Factory; @@ -665,12 +669,12 @@ public function testStopStillTerminatesTheProcessWhenDatabaseReleaseFails(bool $ $cleanupFailure = new RuntimeException('Stop cleanup failed.', previous: $cleanupFailure); } } - $lease = m::mock(ConnectionLease::class); - $lease->shouldReceive('releaseIfIdle')->once()->andThrow($failure); + $lease = Double::for(ConnectionLease::class)->strict(); + $lease->expects('releaseIfIdle')->throws($failure); CoroutineContext::set('__process.test.lease', $lease); - $process = m::mock(SymfonyProcess::class); - $process->shouldReceive('isRunning')->once()->andReturnTrue(); - $process->shouldReceive('stop')->once()->with(0, 15)->andThrow($cleanupFailure); + $process = Double::for(ProcessWithoutDestructor::class)->strict(); + $process->expects('isRunning')->returns(true); + $process->expects('stop')->with(0.0, 15)->throws($cleanupFailure); $caught = null; try { @@ -689,12 +693,17 @@ public function testStopStillTerminatesTheProcessWhenDatabaseReleaseFails(bool $ public function testInterruptedStopFinishesEmergencyCleanup(float $timeout): void { $cancellation = new CanceledException('Stop canceled.'); - $process = m::mock(SymfonyProcess::class); + $process = Double::for(ProcessWithoutDestructor::class)->strict(); if ($timeout > 0) { - $process->shouldReceive('isRunning')->once()->andReturnTrue(); + $process->expects('isRunning')->returns(true); } - $process->shouldReceive('stop')->once()->with($timeout, 15)->ordered()->andThrow($cancellation); - $process->shouldReceive('stop')->once()->with(0, 15)->ordered()->andReturn(0); + $timeouts = []; + $process->expects('stop')->with(Argument::type('float'), 15)->times(2) + ->resolves(static function (float $stopTimeout) use (&$timeouts, $cancellation): int { + $timeouts[] = $stopTimeout; + + return count($timeouts) === 1 ? throw $cancellation : 0; + }); $caught = null; try { @@ -704,6 +713,7 @@ public function testInterruptedStopFinishesEmergencyCleanup(float $timeout): voi } $this->assertSame($cancellation, $caught); + $this->assertSame([$timeout, 0.0], $timeouts); } #[TestWith(['run'])] @@ -714,16 +724,16 @@ public function testPendingProcessStopsTheChildWhenExecutionFailsBeforeHandoff(s $failure = $method === 'run' ? new CanceledException('Run canceled.') : new RuntimeException('Input iterator failed.'); - $process = m::mock(SymfonyProcess::class); - $process->shouldReceive('getCommandline')->once()->andReturn('test-command'); - $process->shouldReceive($method)->once()->with(null)->andThrow($failure); + $process = Double::for(ProcessWithoutDestructor::class)->strict(); + $process->expects('getCommandline')->returns('test-command'); + $process->expects($method)->with(null)->throws($failure); $cleanupFailure = $cleanupIsCanceled ? new RuntimeException('Stop cleanup failed.', previous: new CanceledException) : null; if ($cleanupFailure !== null) { - $process->shouldReceive('stop')->twice()->with(0, null)->andThrow($cleanupFailure); + $process->expects('stop')->times(2)->with(0.0, null)->throws($cleanupFailure); } else { - $process->shouldReceive('stop')->once()->with(0, null)->andReturn(0); + $process->expects('stop')->with(0.0, null)->returns(0); } $pending = new class(new Factory, $process) extends PendingProcess { /** @@ -765,9 +775,12 @@ public function testOutputGuardPreservesCancellationDuringEmergencyStop(bool $wr $cancellation = $stopWrapped ? new RuntimeException('Emergency stop failed.', previous: new CanceledException('Emergency stop canceled.')) : new CanceledException('Emergency stop canceled.'); - $process = m::mock(SymfonyProcess::class); - $process->shouldReceive('stop')->once()->with(0)->ordered()->andThrow($cancellation); - $process->shouldReceive('stop')->once()->with(0)->ordered()->andReturn(0); + $process = Double::for(ProcessWithoutDestructor::class)->strict(); + $stops = 0; + $process->expects('stop')->with(0.0)->times(2) + ->resolves(static function () use (&$stops, $cancellation): int { + return ++$stops === 1 ? throw $cancellation : 0; + }); $guard = new class { use GuardsProcessOutput { guardProcessOutput as public; @@ -2373,3 +2386,13 @@ protected function ls(): string return windows_os() ? 'dir' : 'ls'; } } + +class ProcessWithoutDestructor extends SymfonyProcess +{ + /** + * Leave cleanup to explicit stop calls; this fixture never starts a child. + */ + public function __destruct() + { + } +} diff --git a/tests/Prompts/PromptAnimationTest.php b/tests/Prompts/PromptAnimationTest.php index 72a4e86b41..23a7306e99 100644 --- a/tests/Prompts/PromptAnimationTest.php +++ b/tests/Prompts/PromptAnimationTest.php @@ -11,7 +11,8 @@ use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Prompts\Support\PromptAnimation; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use RuntimeException; use Swoole\Coroutine as SwooleCoroutine; @@ -19,6 +20,8 @@ class PromptAnimationTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; #[RunInSeparateProcess] @@ -30,11 +33,10 @@ public function testOwnerCancellationDuringCreationLeavesAnimationStoppable(): v $releaseReport = new Channel(1); $parentCoroutineId = EngineCoroutine::id(); $childCoroutineId = null; - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $exceptionHandler->shouldReceive('report') - ->once() + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $exceptionHandler->expects('report') ->with($hookFailure) - ->andReturnUsing(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { + ->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { $childCoroutineId = EngineCoroutine::id(); $reportStarted->push(true); $releaseReport->pop(); diff --git a/tests/Queue/CallQueuedHandlerTest.php b/tests/Queue/CallQueuedHandlerTest.php index 7620916c9d..352dd8aa7d 100644 --- a/tests/Queue/CallQueuedHandlerTest.php +++ b/tests/Queue/CallQueuedHandlerTest.php @@ -15,6 +15,7 @@ use Hypervel\Container\Container; use Hypervel\Contracts\Bus\Dispatcher as BusDispatcher; use Hypervel\Contracts\Cache\Lock; +use Hypervel\Contracts\Cache\LockProvider; use Hypervel\Contracts\Cache\Repository as Cache; use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\Contracts\Queue\Job; @@ -26,7 +27,8 @@ use Hypervel\Queue\InteractsWithQueue; use Hypervel\Queue\Jobs\FakeJob; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionMethod; use RuntimeException; @@ -36,6 +38,8 @@ class CallQueuedHandlerTest extends TestCase { + use VerifiesDoubles; + protected Container $container; protected Repository $cache; @@ -206,53 +210,53 @@ public function testCommandShouldBeUniqueUntilProcessingReturnsFalseForCallQueue public function testUniqueJobLockIsReleasedAfterProcessing(): void { - $lock = m::mock(Lock::class); - $lock->shouldReceive('forceRelease')->once(); + $lock = Double::for(Lock::class)->strict(); + $lock->expects('forceRelease'); - $cache = m::mock(Cache::class); - $cache->shouldReceive('lock')->andReturn($lock); + $cache = Double::for(Cache::class, LockProvider::class)->strict(); + $cache->allows('lock')->returns($lock); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make')->with(Cache::class)->andReturn($cache); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->allows('make')->with(Cache::class)->returns($cache); - $dispatcher = m::mock(BusDispatcher::class); - $dispatcher->shouldReceive('dispatchNow'); - $dispatcher->shouldReceive('getCommandHandler')->andReturn(null); + $dispatcher = Double::for(BusDispatcher::class)->strict(); + $dispatcher->allows('dispatchNow'); + $dispatcher->allows('getCommandHandler')->returns(null); - $job = m::mock(Job::class); - $job->shouldReceive('isReleased')->andReturn(false); - $job->shouldReceive('hasFailed')->andReturn(false); - $job->shouldReceive('isDeletedOrReleased')->andReturn(false); - $job->shouldReceive('delete')->once(); + $job = Double::for(Job::class)->strict(); + $job->allows('isReleased')->returns(false); + $job->allows('hasFailed')->returns(false); + $job->allows('isDeletedOrReleased')->returns(false); + $job->expects('delete'); // Serialize before setting the mock job (mocks aren't serializable) $command = new CallQueuedHandlerTestUniqueJob; $serialized = serialize($command); - $handler = new CallQueuedHandler($dispatcher, $container); + $handler = new CallQueuedHandler($dispatcher, $container->instance()); $handler->call($job, ['command' => $serialized]); } public function testUniqueUntilProcessingRetryDoesNotReleaseLockAgain(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make')->with(Cache::class)->never(); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->expects('make')->with(Cache::class)->never(); - $dispatcher = m::mock(BusDispatcher::class); - $dispatcher->shouldReceive('dispatchNow')->once(); - $dispatcher->shouldReceive('getCommandHandler')->andReturn(null); + $dispatcher = Double::for(BusDispatcher::class)->strict(); + $dispatcher->expects('dispatchNow'); + $dispatcher->allows('getCommandHandler')->returns(null); - $job = m::mock(Job::class); - $job->shouldReceive('isReleased')->andReturn(false); - $job->shouldReceive('attempts')->andReturn(2); - $job->shouldReceive('hasFailed')->andReturn(false); - $job->shouldReceive('isDeletedOrReleased')->andReturn(false); - $job->shouldReceive('delete')->once(); + $job = Double::for(Job::class)->strict(); + $job->allows('isReleased')->returns(false); + $job->allows('attempts')->returns(2); + $job->allows('hasFailed')->returns(false); + $job->allows('isDeletedOrReleased')->returns(false); + $job->expects('delete'); $command = new CallQueuedHandlerTestUniqueUntilProcessingJob; $serialized = serialize($command); - $handler = new CallQueuedHandler($dispatcher, $container); + $handler = new CallQueuedHandler($dispatcher, $container->instance()); $handler->call($job, ['command' => $serialized]); } @@ -265,24 +269,24 @@ public function testMiddlewareFailureOnRetryReleasesOnlyItsOwnLockWithoutJobTrai $this->assertTrue($lock->get()); $failure = new RuntimeException('Middleware failed.'); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make')->with(Cache::class)->andReturn($cache); - $container->shouldReceive('make')->with('failing.middleware')->once() - ->andReturn(static fn (): never => throw $failure); - - $dispatcher = m::mock(BusDispatcher::class); - $dispatcher->shouldReceive('dispatchNow')->never(); - - $job = m::mock(Job::class); - $job->shouldReceive('isReleased')->andReturn(false); - $job->shouldReceive('attempts')->andReturn(2); - $job->shouldReceive('payload')->andReturn([ + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->allows('make')->with(Cache::class)->returns($cache); + $container->expects('make')->with('failing.middleware') + ->returns(static fn (): never => throw $failure); + + $dispatcher = Double::for(BusDispatcher::class)->strict(); + $dispatcher->expects('dispatchNow')->never(); + + $job = Double::for(Job::class)->strict(); + $job->allows('isReleased')->returns(false); + $job->allows('attempts')->returns(2); + $job->allows('payload')->returns([ 'illuminate:log:context' => [ 'hidden' => ['laravel_unique_job_lock_owner' => serialize('original-owner')], ], ]); - $handler = new CallQueuedHandler($dispatcher, $container); + $handler = new CallQueuedHandler($dispatcher, $container->instance()); try { $handler->call($job, ['command' => serialize($command)]); @@ -307,78 +311,77 @@ public static function middlewareRetryLockOwners(): array public function testHandleModelNotFoundFailsJobWhenDeleteWhenMissingModelsIsFalse(): void { - $container = m::mock(ContainerContract::class); + $container = Double::for(ContainerContract::class, override: true)->strict(); - $job = m::mock(Job::class); - $job->shouldReceive('payload')->andReturn(['deleteWhenMissingModels' => false]); - $job->shouldReceive('fail')->once(); + $job = Double::for(Job::class)->strict(); + $job->allows('payload')->returns(['deleteWhenMissingModels' => false]); + $job->expects('fail'); - $handler = new CallQueuedHandler(m::mock(BusDispatcher::class), $container); + $handler = new CallQueuedHandler(Double::for(BusDispatcher::class)->strict(), $container->instance()); $this->invokeMethod($handler, 'handleModelNotFound', [$job, new \Hypervel\Database\Eloquent\ModelNotFoundException]); } public function testHandleModelNotFoundDeletesJobWhenDeleteWhenMissingModelsIsTrue(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with(BatchRepository::class)->andReturn(false); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->allows('bound')->with(BatchRepository::class)->returns(false); - $job = m::mock(Job::class); - $job->shouldReceive('payload')->andReturn(['deleteWhenMissingModels' => true]); - $job->shouldReceive('resolveQueuedJobClass')->andReturn(CallQueuedHandlerTestRegularJob::class); - $job->shouldReceive('delete')->once(); - $job->shouldReceive('fail')->never(); + $job = Double::for(Job::class)->strict(); + $job->allows('payload')->returns(['deleteWhenMissingModels' => true]); + $job->allows('resolveQueuedJobClass')->returns(CallQueuedHandlerTestRegularJob::class); + $job->expects('delete'); + $job->expects('fail')->never(); - $handler = new CallQueuedHandler(m::mock(BusDispatcher::class), $container); + $handler = new CallQueuedHandler(Double::for(BusDispatcher::class)->strict(), $container->instance()); $this->invokeMethod($handler, 'handleModelNotFound', [$job, new \Hypervel\Database\Eloquent\ModelNotFoundException]); } public function testEnsureUniqueJobLockIsReleasedViaContextDoesNothingWithoutContext(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->never(); - $container->shouldReceive('make')->never(); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->expects('bound')->never(); + $container->expects('make')->never(); // No propagated context set — hasPropagated() returns false - $handler = new CallQueuedHandler(m::mock(BusDispatcher::class), $container); + $handler = new CallQueuedHandler(Double::for(BusDispatcher::class)->strict(), $container->instance()); $this->invokeMethod($handler, 'ensureUniqueJobLockIsReleasedViaContext', []); } public function testFailedMethodSetsJobInstanceWhenProvided(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make')->with(Cache::class)->andReturn(m::mock(Cache::class)); - - $dispatcher = m::mock(BusDispatcher::class); - - $command = new CallQueuedHandlerTestRegularJob; - $serialized = serialize($command); - - $job = m::mock(Job::class); + $job = new FakeJob; - $handler = new CallQueuedHandler($dispatcher, $container); - $handler->failed(['command' => $serialized], new Exception('test'), 'test-uuid', $job); + try { + $this->handler->failed( + ['command' => serialize(new CallQueuedHandlerTestFailedJob)], + new Exception('test'), + 'test-uuid', + $job, + ); - // If we get here without error, the job was set successfully - $this->assertTrue(true); + $this->assertSame($job, CallQueuedHandlerTestFailedJob::$failedJob); + } finally { + CallQueuedHandlerTestFailedJob::$failedJob = null; + } } public function testRunningCommandIsAvailableWhileCommandIsProcessing(): void { - $container = m::mock(ContainerContract::class); + $container = Double::for(ContainerContract::class, override: true)->strict(); - $dispatcher = m::mock(BusDispatcher::class); - $dispatcher->shouldReceive('getCommandHandler')->andReturn(null); - $dispatcher->shouldReceive('dispatchNow')->once()->andReturnUsing(function ($command) { + $dispatcher = Double::for(BusDispatcher::class)->strict(); + $dispatcher->allows('getCommandHandler')->returns(null); + $dispatcher->expects('dispatchNow')->resolves(function ($command) { $command->handle(); }); - $job = m::mock(Job::class); - $job->shouldReceive('isReleased')->andReturn(false); - $job->shouldReceive('hasFailed')->andReturn(false); - $job->shouldReceive('isDeletedOrReleased')->andReturn(false); - $job->shouldReceive('delete')->once(); + $job = Double::for(Job::class)->strict(); + $job->allows('isReleased')->returns(false); + $job->allows('hasFailed')->returns(false); + $job->allows('isDeletedOrReleased')->returns(false); + $job->expects('delete'); - $handler = new CallQueuedHandler($dispatcher, $container); + $handler = new CallQueuedHandler($dispatcher, $container->instance()); CallQueuedHandlerTestRunningCommandJob::$handler = $handler; CallQueuedHandlerTestRunningCommandJob::$runningCommandDuringMiddleware = null; @@ -398,15 +401,15 @@ public function testRunningCommandIsAvailableWhileCommandIsProcessing(): void public function testRunningCommandIsResetWhenCommandThrows(): void { - $container = m::mock(ContainerContract::class); + $container = Double::for(ContainerContract::class, override: true)->strict(); - $dispatcher = m::mock(BusDispatcher::class); - $dispatcher->shouldReceive('getCommandHandler')->andReturn(null); - $dispatcher->shouldReceive('dispatchNow')->once()->andThrow($exception = new RuntimeException('Command failed.')); + $dispatcher = Double::for(BusDispatcher::class)->strict(); + $dispatcher->allows('getCommandHandler')->returns(null); + $dispatcher->expects('dispatchNow')->throws($exception = new RuntimeException('Command failed.')); - $job = m::mock(Job::class); + $job = Double::for(Job::class)->strict(); - $handler = new CallQueuedHandler($dispatcher, $container); + $handler = new CallQueuedHandler($dispatcher, $container->instance()); try { $handler->call($job, ['command' => serialize(new CallQueuedHandlerTestRegularJob)]); @@ -421,17 +424,17 @@ public function testRunningCommandIsResetWhenCommandThrows(): void public function testRunningCommandStaysNullForDebouncedJobs(): void { - $cache = m::mock(Cache::class); - $cache->shouldReceive('get')->once()->andReturn('new-owner'); + $cache = Double::for(Cache::class)->strict(); + $cache->expects('get')->returns('new-owner'); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make')->with(Cache::class)->andReturn($cache); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->allows('make')->with(Cache::class)->returns($cache); + $container->allows('bound')->with('events')->returns(false); - $job = m::mock(Job::class); - $job->shouldReceive('delete')->once(); + $job = Double::for(Job::class)->strict(); + $job->expects('delete'); - $handler = new CallQueuedHandler(m::mock(BusDispatcher::class), $container); + $handler = new CallQueuedHandler(Double::for(BusDispatcher::class)->strict(), $container->instance()); $handler->call($job, ['command' => serialize(new CallQueuedHandlerTestDebouncedJob)]); @@ -443,23 +446,23 @@ public function testNextChainJobIsDispatchedBeforeCurrentJobIsDeleted(): void CallQueuedHandlerTestChainJob::$order = []; try { - $dispatcher = m::mock(BusDispatcher::class); - $dispatcher->shouldReceive('getCommandHandler')->andReturn(null); - $dispatcher->shouldReceive('dispatchNow')->once()->andReturnUsing(function (): void { + $dispatcher = Double::for(BusDispatcher::class)->strict(); + $dispatcher->allows('getCommandHandler')->returns(null); + $dispatcher->expects('dispatchNow')->resolves(function (): void { CallQueuedHandlerTestChainJob::$order[] = 'handle'; }); - $job = m::mock(Job::class); - $job->shouldReceive('isReleased')->andReturn(false); - $job->shouldReceive('hasFailed')->andReturn(false); - $job->shouldReceive('isDeletedOrReleased')->andReturn(false); - $job->shouldReceive('delete')->once()->andReturnUsing(function (): void { + $job = Double::for(Job::class)->strict(); + $job->allows('isReleased')->returns(false); + $job->allows('hasFailed')->returns(false); + $job->allows('isDeletedOrReleased')->returns(false); + $job->expects('delete')->resolves(function (): void { CallQueuedHandlerTestChainJob::$order[] = 'delete'; }); (new CallQueuedHandler( $dispatcher, - m::mock(ContainerContract::class), + Double::for(ContainerContract::class, override: true)->strict()->instance(), ))->call($job, ['command' => serialize(new CallQueuedHandlerTestChainJob)]); $this->assertSame(['handle', 'chain', 'delete'], CallQueuedHandlerTestChainJob::$order); @@ -522,8 +525,8 @@ function () use ($handler, $secondJob, $firstReady, $secondReady) { private function createHandler(): CallQueuedHandler { return new CallQueuedHandler( - m::mock(BusDispatcher::class), - m::mock(ContainerContract::class) + Double::for(BusDispatcher::class)->strict(), + Double::for(ContainerContract::class, override: true)->strict()->instance() ); } @@ -616,6 +619,19 @@ public function handle(): void } } +class CallQueuedHandlerTestFailedJob extends CallQueuedHandlerTestRegularJob +{ + public static ?Job $failedJob = null; + + /** + * Record the injected job when failure handling runs. + */ + public function failed(): void + { + self::$failedJob = $this->job; + } +} + class CallQueuedHandlerTestMappedCommand { } diff --git a/tests/Queue/DatabaseFailedJobProviderTest.php b/tests/Queue/DatabaseFailedJobProviderTest.php index ca82aed243..4ff6013361 100644 --- a/tests/Queue/DatabaseFailedJobProviderTest.php +++ b/tests/Queue/DatabaseFailedJobProviderTest.php @@ -14,12 +14,14 @@ use Hypervel\Support\Str; use Hypervel\Support\Stringable; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class DatabaseFailedJobProviderTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; protected ?DatabaseFailedJobProvider $provider = null; @@ -66,14 +68,13 @@ public function testCanGetAllFailedJobIds(): void public function testNonIntegerFailedJobIdsAreCastToStrings(): void { - $builder = m::mock(Builder::class); - $builder->shouldReceive('when')->andReturnSelf(); - $builder->shouldReceive('orderBy')->andReturnSelf(); - $builder->shouldReceive('pluck')->with('id')->andReturn(new Collection([new Stringable('4'), 3])); - - $provider = m::mock(DatabaseFailedJobProvider::class, [$this->resolver, null, 'failed_jobs']) - ->makePartial(); - $provider->shouldReceive('getTable')->andReturn($builder); + $builder = Double::for(Builder::class)->strict(); + $builder->allows('when')->returns($builder); + $builder->allows('orderBy'); + $builder->allows('pluck')->with('id')->returns(new Collection([new Stringable('4'), 3])); + + $provider = Double::for($this->provider)->passthru(); + $provider->allows('getTable')->returns($builder); $this->assertSame(['4', 3], $provider->ids()); } diff --git a/tests/Queue/DatabaseQueueRollbackTest.php b/tests/Queue/DatabaseQueueRollbackTest.php index 89659a82fb..8e4c95ded8 100644 --- a/tests/Queue/DatabaseQueueRollbackTest.php +++ b/tests/Queue/DatabaseQueueRollbackTest.php @@ -18,7 +18,8 @@ use Hypervel\Events\Dispatcher; use Hypervel\Queue\DatabaseQueue; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PDOException; use PHPUnit\Framework\Attributes\DataProvider; @@ -26,6 +27,8 @@ class DatabaseQueueRollbackTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('dispatchMethods')] public function testRollbackReleasesAcceptedLocksOnTheStorageOwner(string $method, string $kind): void { @@ -154,8 +157,8 @@ protected function queue(): DatabaseQueue $table->unsignedBigInteger('available_at'); $table->unsignedBigInteger('created_at'); }); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->with('testing::write')->andReturn($database); + $resolver = Double::for(ConnectionResolverInterface::class)->strict(); + $resolver->allows('connection')->with('testing::write')->returns($database); $queue = new DatabaseQueue($resolver, 'testing::write', 'jobs'); $queue->setContainer($container); $queue->setConnectionName('database'); diff --git a/tests/Queue/Fixtures/timeout-worker.php b/tests/Queue/Fixtures/timeout-worker.php index f0019b8206..a985ce7250 100644 --- a/tests/Queue/Fixtures/timeout-worker.php +++ b/tests/Queue/Fixtures/timeout-worker.php @@ -21,7 +21,7 @@ use Hypervel\Queue\InteractsWithQueue; use Hypervel\Queue\Worker; use Hypervel\Queue\WorkerOptions; -use Mockery as m; +use JMac\Testing\Double; use Swoole\Coroutine; use Swoole\Coroutine\Channel; use Swoole\Runtime; @@ -184,10 +184,10 @@ public function interrupted(int $signal): void ], JSON_THROW_ON_ERROR)); } - $manager = m::mock(Factory::class); - $manager->shouldReceive('connection')->andReturn($queue); - $exceptions = m::mock(ExceptionHandler::class); - $exceptions->shouldReceive('report')->andReturnUsing(static function (Throwable $exception): void { + $manager = Double::for(Factory::class)->strict(); + $manager->allows('connection')->returns($queue); + $exceptions = Double::for(ExceptionHandler::class)->strict(); + $exceptions->allows('report')->resolves(static function (Throwable $exception): void { fwrite(STDERR, (string) $exception); }); $worker = new Worker($manager, $events, $exceptions, static fn (): bool => false); diff --git a/tests/Queue/ListenCommandTest.php b/tests/Queue/ListenCommandTest.php index c231272745..ae06ba77fa 100644 --- a/tests/Queue/ListenCommandTest.php +++ b/tests/Queue/ListenCommandTest.php @@ -7,18 +7,22 @@ use Hypervel\Queue\Listener; use Hypervel\Queue\ListenerOptions; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; class ListenCommandTest extends TestCase { + use VerifiesDoubles; + #[TestWith(['60%'])] #[TestWith(['128.5'])] public function testMemoryLimitIsPassedToTheListenerUnchanged(string $memory): void { - $listener = m::mock(Listener::class); + $listener = Double::for(Listener::class)->strict(); $listener->allows('setOutputHandler'); - $listener->expects('listen')->withArgs(static fn (?string $connection, string $queue, ListenerOptions $options): bool => $options->memory === $memory); + $listener->expects('listen')->with(Argument::any(), Argument::any(), Argument::satisfies(static fn (ListenerOptions $options): bool => $options->memory === $memory)); $this->app->instance(Listener::class, $listener); $this->artisan('queue:listen', ['--memory' => $memory])->assertSuccessful(); @@ -26,9 +30,9 @@ public function testMemoryLimitIsPassedToTheListenerUnchanged(string $memory): v public function testFractionalSleepAndRestSecondsAreKept(): void { - $listener = m::mock(Listener::class); + $listener = Double::for(Listener::class)->strict(); $listener->allows('setOutputHandler'); - $listener->expects('listen')->withArgs(static fn (?string $connection, string $queue, ListenerOptions $options): bool => $options->sleep === 0.5 && $options->rest === 0.25); + $listener->expects('listen')->with(Argument::any(), Argument::any(), Argument::satisfies(static fn (ListenerOptions $options): bool => $options->sleep === 0.5 && $options->rest === 0.25)); $this->app->instance(Listener::class, $listener); $this->artisan('queue:listen', ['--sleep' => '0.5', '--rest' => '0.25'])->assertSuccessful(); diff --git a/tests/Queue/MonitorCommandTest.php b/tests/Queue/MonitorCommandTest.php index 0b62992fc1..8946e53cac 100644 --- a/tests/Queue/MonitorCommandTest.php +++ b/tests/Queue/MonitorCommandTest.php @@ -12,7 +12,9 @@ use Hypervel\Queue\Console\MonitorCommand; use Hypervel\Queue\Events\QueueBusy; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; @@ -20,25 +22,26 @@ class MonitorCommandTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('outputDecoration')] public function testItDisplaysQueueMetricsAsJsonAndDispatchesBusyEvent(bool $decorated): void { $name = 'Queue\name \literal'; - $queue = m::mock(Queue::class); - $queue->shouldReceive('size')->with($name)->andReturn(1001); - $queue->shouldReceive('pendingSize')->with($name)->andReturn(0); - $queue->shouldReceive('delayedSize')->with($name)->andReturn(2); - $queue->shouldReceive('reservedSize')->with($name)->andReturn(3); - $queue->shouldReceive('creationTimeOfOldestPendingJob')->with($name)->andReturn(null); - - $manager = m::mock(Factory::class); - $manager->shouldReceive('connection')->with('redis')->andReturn($queue); - - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(QueueBusy::class)->andReturnTrue(); - $events->shouldReceive('dispatch') - ->once() - ->with(m::on(fn (mixed $event): bool => $event instanceof QueueBusy + $queue = Double::for(Queue::class)->strict(); + $queue->allows('size')->with($name)->returns(1001); + $queue->allows('pendingSize')->with($name)->returns(0); + $queue->allows('delayedSize')->with($name)->returns(2); + $queue->allows('reservedSize')->with($name)->returns(3); + $queue->allows('creationTimeOfOldestPendingJob')->with($name)->returns(null); + + $manager = Double::for(Factory::class)->strict(); + $manager->allows('connection')->with('redis')->returns($queue); + + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(QueueBusy::class)->returns(true); + $events->expects('dispatch') + ->with(Argument::satisfies(fn (mixed $event): bool => $event instanceof QueueBusy && $event->connectionName === 'redis' && $event->queue === $name && $event->size === 1001)); @@ -71,19 +74,19 @@ public static function outputDecoration(): array public function testItDisplaysDetailedQueueMetricsForTheDefaultConnection(): void { - $queue = m::mock(Queue::class); - $queue->shouldReceive('size')->with('default')->andReturn(1); - $queue->shouldReceive('pendingSize')->with('default')->andReturn(1); - $queue->shouldReceive('delayedSize')->with('default')->andReturn(0); - $queue->shouldReceive('reservedSize')->with('default')->andReturn(0); - $queue->shouldReceive('creationTimeOfOldestPendingJob')->with('default')->andReturn(null); - - $manager = m::mock(Factory::class); - $manager->shouldReceive('connection')->with('redis')->andReturn($queue); - - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(QueueBusy::class)->andReturnFalse(); - $events->shouldNotReceive('dispatch'); + $queue = Double::for(Queue::class)->strict(); + $queue->allows('size')->with('default')->returns(1); + $queue->allows('pendingSize')->with('default')->returns(1); + $queue->allows('delayedSize')->with('default')->returns(0); + $queue->allows('reservedSize')->with('default')->returns(0); + $queue->allows('creationTimeOfOldestPendingJob')->with('default')->returns(null); + + $manager = Double::for(Factory::class)->strict(); + $manager->allows('connection')->with('redis')->returns($queue); + + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(QueueBusy::class)->returns(false); + $events->expects('dispatch')->never(); $output = $this->runCommand( new MonitorCommand($manager, $events, new Repository(['queue' => ['default' => 'redis']])), diff --git a/tests/Queue/Outbox/DatabaseOutboxPublicationTest.php b/tests/Queue/Outbox/DatabaseOutboxPublicationTest.php index 25d4e89b63..6a9c9873fd 100644 --- a/tests/Queue/Outbox/DatabaseOutboxPublicationTest.php +++ b/tests/Queue/Outbox/DatabaseOutboxPublicationTest.php @@ -15,7 +15,8 @@ use Hypervel\Support\Facades\Facade; use Hypervel\Support\Str; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -24,6 +25,8 @@ class DatabaseOutboxPublicationTest extends TestCase { + use VerifiesDoubles; + public function testRawPublicationUsesOneInsertAcrossQueuesWithAbsoluteAvailability(): void { CarbonImmutable::setTestNow('2030-01-01 12:00:00'); @@ -98,8 +101,8 @@ protected function queue(): array $container->instance('queue.routes', $routes = new QueueRoutes); Facade::setFacadeApplication($container); (require dirname(__DIR__, 3) . '/src/testbench/hypervel/migrations/0001_01_01_000006_testbench_create_jobs_table.php')->up(); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->with('target')->andReturn($database); + $resolver = Double::for(ConnectionResolverInterface::class)->strict(); + $resolver->allows('connection')->with('target')->returns($database); $queue = new DatabaseQueue($resolver, 'target', 'jobs'); $queue->setContainer($container)->setConnectionName('database'); diff --git a/tests/Queue/Outbox/DatabaseOutboxRepositoryTest.php b/tests/Queue/Outbox/DatabaseOutboxRepositoryTest.php index 2faa1a564d..78aa6de03c 100644 --- a/tests/Queue/Outbox/DatabaseOutboxRepositoryTest.php +++ b/tests/Queue/Outbox/DatabaseOutboxRepositoryTest.php @@ -18,12 +18,14 @@ use Hypervel\Support\Str; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class DatabaseOutboxRepositoryTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; protected bool $migrateRefresh = true; @@ -94,12 +96,12 @@ public function testExpiredClaimCanBeRecoveredWithoutChangingDeliveryOrPayload() public function testCustomNonPdoConnectionsUseTheConditionalClaimAndBindingFallback(): void { $database = DB::connection(); - $connection = m::mock(Connection::class); - $connection->shouldReceive('supportsSkipLocked')->andReturnFalse(); - $connection->shouldReceive('table')->with('job_outbox')->andReturnUsing(fn (): Builder => $database->table('job_outbox')); - $connection->shouldReceive('transaction')->andReturnUsing(fn (Closure $callback): mixed => $database->transaction($callback)); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->with('custom')->andReturn($connection); + $connection = Double::for(Connection::class)->strict(); + $connection->allows('supportsSkipLocked')->returns(false); + $connection->allows('table')->with('job_outbox')->resolves(fn (): Builder => $database->table('job_outbox')); + $connection->allows('transaction')->resolves(fn (Closure $callback): mixed => $database->transaction($callback)); + $resolver = Double::for(ConnectionResolverInterface::class)->strict(); + $resolver->allows('connection')->with('custom')->returns($connection); $repository = new DatabaseOutboxRepository($resolver, ['custom'], 'job_outbox', 300); $row = $this->row(Date::now()->getTimestamp()); $repository->insert($connection, [$row]); diff --git a/tests/Queue/Outbox/OutboxBatchTest.php b/tests/Queue/Outbox/OutboxBatchTest.php index 5ff8bcecdd..8f3fb87cf0 100644 --- a/tests/Queue/Outbox/OutboxBatchTest.php +++ b/tests/Queue/Outbox/OutboxBatchTest.php @@ -12,12 +12,15 @@ use Hypervel\Support\Facades\DB; use Hypervel\Support\Facades\Schema; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; class OutboxBatchTest extends TestCase { + use VerifiesDoubles; + /** * Keep batch counters and a conflicting business transaction on separate sessions. */ @@ -47,7 +50,7 @@ protected function setUpInCoroutine(): void Schema::swap(DB::connection('business')->getSchemaBuilder()); (require $migrations . '0001_01_01_000006_testbench_create_jobs_table.php')->up(); (require $migrations . '0001_01_01_000009_testbench_create_job_outbox_table.php')->up(); - $this->app->instance('redis', m::mock(Factory::class)); + $this->app->instance('redis', Double::for(Factory::class)->strict()); } #[DataProvider('queueConnections')] diff --git a/tests/Queue/Outbox/OutboxCommandsTest.php b/tests/Queue/Outbox/OutboxCommandsTest.php index a29876877f..0d62e0e21a 100644 --- a/tests/Queue/Outbox/OutboxCommandsTest.php +++ b/tests/Queue/Outbox/OutboxCommandsTest.php @@ -16,14 +16,17 @@ use Hypervel\Support\Str; use Hypervel\Testbench\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; class OutboxCommandsTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; protected bool $migrateRefresh = true; @@ -137,10 +140,10 @@ public function testRetryAllPreservesAttemptHistoryAndExcludesLiveAndNeverAttemp public function testRetryRefusesCrossSourceUuidAmbiguityBeforeMutation(): void { - $repository = m::mock(DatabaseOutboxRepository::class); - $repository->expects('getDatabases')->andReturn(['first', 'second']); - $repository->expects('find')->with('first', 'same')->andReturn((object) ['id' => 1]); - $repository->expects('find')->with('second', 'same')->andReturn((object) ['id' => 2]); + $repository = Double::for(DatabaseOutboxRepository::class)->strict(); + $repository->expects('getDatabases')->returns(['first', 'second']); + $repository->expects('find')->with('first', 'same')->returns((object) ['id' => 1]); + $repository->expects('find')->with('second', 'same')->returns((object) ['id' => 2]); $this->app->instance(DatabaseOutboxRepository::class, $repository); $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Select one using --database'); @@ -216,8 +219,8 @@ public function testForgetReportsUnresolvableOwnershipAfterDeletingWithoutGuessi 'laravel_unique_job_lock_owner' => serialize($lock->owner()), ]], ], JSON_THROW_ON_ERROR)]); - $exceptions = m::mock(ExceptionHandler::class); - $exceptions->expects('report')->with(m::type(LogicException::class), m::on(fn (array $context): bool => $context['job_uuid'] === $uuid)); + $exceptions = Double::for(ExceptionHandler::class)->strict(); + $exceptions->expects('report')->with(Argument::type(LogicException::class), Argument::satisfies(fn (array $context): bool => $context['job_uuid'] === $uuid)); $this->app->instance(ExceptionHandler::class, $exceptions); $this->artisan('queue:outbox-forget', ['uuid' => $uuid]) diff --git a/tests/Queue/Outbox/OutboxDispatchTest.php b/tests/Queue/Outbox/OutboxDispatchTest.php index 823e3a100d..5b1040d68a 100644 --- a/tests/Queue/Outbox/OutboxDispatchTest.php +++ b/tests/Queue/Outbox/OutboxDispatchTest.php @@ -30,7 +30,8 @@ use Hypervel\Support\Facades\DB; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Pheanstalk\Contract\PheanstalkManagerInterface; use Pheanstalk\Contract\PheanstalkPublisherInterface; use Pheanstalk\Contract\PheanstalkSubscriberInterface; @@ -44,6 +45,7 @@ class OutboxDispatchTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; protected bool $migrateRefresh = true; @@ -152,11 +154,15 @@ public function testBulkStagingUsesOneInsertAndFinalizesEachPayloadOnce(): void public function testBaseBulkStagesOneInsertAndKeepsTheDirectPartition(bool $beanstalk): void { $queue = $beanstalk - ? m::mock(BeanstalkdQueue::class, [m::mock(PheanstalkManagerInterface::class . ', ' . PheanstalkPublisherInterface::class . ', ' . PheanstalkSubscriberInterface::class), 'orders', 60])->makePartial() - : m::mock(Queue::class . ', ' . QueueContract::class)->makePartial(); + ? Double::for(new BeanstalkdQueue( + Double::for(PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class)->strict(), + 'orders', + 60, + ))->passthru() + : Double::for(OutboxDispatchBaseQueue::class)->passthru(); $queue->setContainer($this->app)->setConnectionName($beanstalk ? 'beanstalkd' : 'custom'); $direct = (new OutboxDispatchJob)->withoutOutbox(); - $queue->expects('push')->with($direct, '', 'orders')->andReturn('direct'); + $queue->expects('push')->with($direct, '', 'orders')->returns('direct'); $jobs = array_map(static fn (): OutboxDispatchJob => (new OutboxDispatchJob)->viaOutbox(), range(1, 100)); $connection = DB::connection(); $connection->enableQueryLog(); @@ -216,12 +222,12 @@ public function testStorageFailureTerminatesEveryMemberAsAttempted(bool $bulk): { $queue = $this->queue(); $failure = new RuntimeException('Storage failed'); - $dispatcher = m::mock(OutboxDispatcher::class, [ + $dispatcher = Double::for(new OutboxDispatcher( $this->app->make(DatabaseOutboxRepository::class), $this->app->make(ConnectionResolverInterface::class), $this->app->make('db.transactions'), - ])->makePartial(); - $dispatcher->expects('store')->andThrow($failure); + ))->passthru(); + $dispatcher->expects('store')->throws($failure); $this->app->instance(OutboxDispatcher::class, $dispatcher); $failed = []; $this->app->make('events')->listen(JobQueueingFailed::class, function (JobQueueingFailed $event) use (&$failed): void { @@ -255,7 +261,7 @@ public function testBulkFailureIsNotReplacedByAFailingFailureListener(): void $failed[] = $event->job; }); $this->app->make('events')->listen(JobQueueingFailed::class, static fn () => throw $listener); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $handler->expects('report')->with($listener); $this->app->instance(ExceptionHandler::class, $handler); $jobs = [(new OutboxDispatchJob)->viaOutbox(), (new OutboxDispatchJob)->viaOutbox()]; @@ -365,7 +371,7 @@ public static function deliveryTimes(): array public function testSqsStagingCapturesOptionsOnceAndWaitsForItsTransportWindow(string $method, bool $fifo, int $eligibleDelay): void { Date::setTestNow('2040-01-01 12:00:00'); - $queue = new SqsQueue(m::mock(SqsClient::class), $fifo ? 'orders.fifo' : 'orders'); + $queue = new SqsQueue(Double::for(SqsClient::class)->strict(), $fifo ? 'orders.fifo' : 'orders'); $queue->setContainer($this->app)->setConnectionName('sqs'); $job = (new OutboxFifoDispatchJob)->viaOutbox()->onGroup('tenant:17')->delay(1200); @@ -441,13 +447,17 @@ public function testDatabaseFastPathResolutionFailureEmitsTheFailedLifecycle(): */ protected function queue(): RecordingOutboxRedisQueue { - $queue = new RecordingOutboxRedisQueue(m::mock(Factory::class), 'orders'); + $queue = new RecordingOutboxRedisQueue(Double::for(Factory::class)->strict(), 'orders'); $queue->setContainer($this->app)->setConnectionName('redis'); return $queue; } } +abstract class OutboxDispatchBaseQueue extends Queue implements QueueContract +{ +} + class OutboxDispatchJob { use Queueable; diff --git a/tests/Queue/Outbox/OutboxDispatcherTest.php b/tests/Queue/Outbox/OutboxDispatcherTest.php index 4ca4112bd7..b3b92cec2d 100644 --- a/tests/Queue/Outbox/OutboxDispatcherTest.php +++ b/tests/Queue/Outbox/OutboxDispatcherTest.php @@ -11,13 +11,16 @@ use Hypervel\Queue\Outbox\DatabaseOutboxRepository; use Hypervel\Queue\Outbox\OutboxDispatcher; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PDO; use PHPUnit\Framework\Attributes\DataProvider; class OutboxDispatcherTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('ownershipCases')] public function testStorageResolvesTheExactTransactionOwner(array $active, ?string $explicit, array $configured, ?string $expected, ?string $error): void { @@ -36,8 +39,8 @@ public function testStorageResolvesTheExactTransactionOwner(array $active, ?stri $connections[$name] = $connection; } - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->andReturnUsing(fn (string $name): SQLiteConnection => $connections[$name]); + $resolver = Double::for(ConnectionResolverInterface::class)->strict(); + $resolver->allows('connection')->resolves(fn (string $name): SQLiteConnection => $connections[$name]); $repository = new DatabaseOutboxRepository($resolver, $configured, 'job_outbox', 300); $dispatcher = new OutboxDispatcher($repository, $resolver, $transactions); $job = new OutboxOwnershipJob; diff --git a/tests/Queue/Outbox/OutboxFastPathTest.php b/tests/Queue/Outbox/OutboxFastPathTest.php index 4b43964c97..9e7af9b5a0 100644 --- a/tests/Queue/Outbox/OutboxFastPathTest.php +++ b/tests/Queue/Outbox/OutboxFastPathTest.php @@ -25,14 +25,18 @@ use Hypervel\Support\Facades\DB; use Hypervel\Support\Testing\Fakes\QueueFake; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use UnitEnum; class OutboxFastPathTest extends TestCase { + use VerifiesDoubles; + /** * Configure isolated databases without installing any outbox tables. */ @@ -63,8 +67,8 @@ public function testLocalSelectionWithoutATransactionPreservesImmediateResults() public function testLocalSelectionWithoutATransactionPreservesTimerIds(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->with(60.0, m::type('callable'))->twice()->andReturn(41, 42); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(60.0, Argument::type('callable'))->times(2)->returns(41, 42); $queue = new BackgroundQueue(timer: $timer); $queue->setContainer($this->app)->setConnectionName('local'); @@ -159,15 +163,15 @@ public function testDatabaseQueueOnAnotherOwnerStagesInsideTheBusinessTransactio public function testFailoverSuppressesChildDefaultsAndRestoresThemAfterNestedFailure(): void { - $primary = new FailingOutboxRedisQueue(m::mock(Factory::class), 'orders'); + $primary = new FailingOutboxRedisQueue(Double::for(Factory::class)->strict(), 'orders'); $primary->setContainer($this->app)->setConnectionName('primary')->setConfig(['outbox' => true]); $sync = $this->app->make('queue')->connection('sync'); - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->with('primary')->andReturn($primary); - $manager->shouldReceive('connection')->with('sync')->andReturn($sync); + $manager = Double::for(QueueManager::class)->strict(); + $manager->allows('connection')->with('primary')->returns($primary); + $manager->allows('connection')->with('sync')->returns($sync); $inner = new FailoverQueue($manager, $this->app->make('events'), ['primary']); $inner->setContainer($this->app)->setConnectionName('inner'); - $manager->shouldReceive('connection')->with('inner')->andReturn($inner); + $manager->allows('connection')->with('inner')->returns($inner); $outer = new FailoverQueue($manager, $this->app->make('events'), ['inner', 'sync']); $outer->setContainer($this->app)->setConnectionName('outer'); @@ -186,8 +190,8 @@ public function testFailoverSuppressesChildDefaultsAndRestoresThemAfterNestedFai #[DataProvider('transactionOutcomes')] public function testSelectedFailoverDefersTheWholeAttemptWithoutSchema(bool $commit): void { - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->with('sync')->andReturn($this->app->make('queue')->connection('sync')); + $manager = Double::for(QueueManager::class)->strict(); + $manager->allows('connection')->with('sync')->returns($this->app->make('queue')->connection('sync')); $queue = new FailoverQueue($manager, $this->app->make('events'), ['sync']); $queue->setContainer($this->app)->setConnectionName('failover')->setConfig(['outbox' => true]); $log = $this->app->make(OutboxExecutionLog::class); @@ -228,14 +232,14 @@ protected function executePayload(string $payload, ?string $queue = null): int } }; $first->setContainer($this->app)->setConnectionName('first'); - $target = new FastPathRecordingRedisQueue(m::mock(Factory::class), dispatchAfterCommit: true); + $target = new FastPathRecordingRedisQueue(Double::for(Factory::class)->strict(), dispatchAfterCommit: true); $target->setContainer($this->app)->setConnectionName('target')->setConfig(['outbox' => true]); - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->with('first')->andReturn($first); - $manager->shouldReceive('connection')->with('target')->andReturn($target); + $manager = Double::for(QueueManager::class)->strict(); + $manager->allows('connection')->with('first')->returns($first); + $manager->allows('connection')->with('target')->returns($target); $inner = new FailoverQueue($manager, $this->app->make('events'), ['first', 'target'], true); $inner->setContainer($this->app)->setConnectionName('inner'); - $manager->shouldReceive('connection')->with('inner')->andReturn($inner); + $manager->allows('connection')->with('inner')->returns($inner); $outer = new FailoverQueue($manager, $this->app->make('events'), ['inner']); $outer->setContainer($this->app)->setConnectionName('outer'); $job = (new UniqueOutboxLocalJob)->onOutboxDatabase('secondary')->afterCommit(); @@ -264,11 +268,11 @@ protected function executePayload(string $payload, ?string $queue = null): int public function testSyncFallbackDoesNotSuppressIndependentContinuation(string $kind): void { (require dirname(__DIR__, 3) . '/src/testbench/hypervel/migrations/0001_01_01_000009_testbench_create_job_outbox_table.php')->up(); - $target = new FastPathRecordingRedisQueue(m::mock(Factory::class)); + $target = new FastPathRecordingRedisQueue(Double::for(Factory::class)->strict()); $target->setContainer($this->app)->setConnectionName('target')->setConfig(['outbox' => true]); $this->app->instance(RedisQueue::class, $target); - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->with('sync')->andReturn($this->app->make('queue')->connection('sync')); + $manager = Double::for(QueueManager::class)->strict(); + $manager->allows('connection')->with('sync')->returns($this->app->make('queue')->connection('sync')); $failover = new FailoverQueue($manager, $this->app->make('events'), ['sync']); $failover->setContainer($this->app)->setConnectionName('failover'); diff --git a/tests/Queue/Outbox/OutboxProducerTest.php b/tests/Queue/Outbox/OutboxProducerTest.php index edd73f124c..7ffdac449c 100644 --- a/tests/Queue/Outbox/OutboxProducerTest.php +++ b/tests/Queue/Outbox/OutboxProducerTest.php @@ -23,11 +23,13 @@ use Hypervel\Support\Facades\Mail; use Hypervel\Support\Facades\Notification as NotificationFacade; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class OutboxProducerTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; protected bool $migrateRefresh = true; @@ -54,7 +56,7 @@ protected function migrateFreshUsing(): array public function testPublicProducerApisStageTheirExistingWrapperJobs(): void { - $this->app->instance('redis', m::mock(Factory::class)); + $this->app->instance('redis', Double::for(Factory::class)->strict()); Event::listen('outbox.created', OutboxProducerListener::class); DB::transaction(static function (): void { diff --git a/tests/Queue/Outbox/OutboxRelayTest.php b/tests/Queue/Outbox/OutboxRelayTest.php index 9cdeef26bb..c462d37d7b 100644 --- a/tests/Queue/Outbox/OutboxRelayTest.php +++ b/tests/Queue/Outbox/OutboxRelayTest.php @@ -20,8 +20,10 @@ use Hypervel\Queue\Outbox\OutboxRelay; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -29,26 +31,28 @@ class OutboxRelayTest extends TestCase { + use VerifiesDoubles; + public function testClaimPublishSettleAndObserversReleaseTheirResourcesInOrder(): void { CarbonImmutable::setTestNow('2040-01-01 12:00:00'); CoroutineContext::set('request-only', true); - $repository = m::mock(DatabaseOutboxRepository::class); - $queues = m::mock(Factory::class); - $queue = m::mock(Queue::class . ', ' . PublishesOutboxMessages::class); + $repository = Double::for(DatabaseOutboxRepository::class)->strict(); + $queues = Double::for(Factory::class)->strict(); + $queue = Double::for(Queue::class, PublishesOutboxMessages::class)->strict(); $events = new Dispatcher; - $exceptions = m::mock(ExceptionHandler::class); + $exceptions = Double::for(ExceptionHandler::class)->strict(); $messages = [$this->message(1)]; $phases = []; - $repository->expects('claim')->with('primary', 100)->andReturnUsing(function () use (&$phases, $messages): array { + $repository->expects('claim')->with('primary', 100)->resolves(function () use (&$phases, $messages): array { $this->assertFalse(CoroutineContext::has('request-only')); $phases[] = 'claim'; Coroutine::defer(static function () use (&$phases): void { $phases[] = 'claim released'; }); return $messages; }); - $queues->expects('connection')->with('redis')->andReturn($queue); - $queue->expects('publishOutboxMessages')->with($messages)->andReturnUsing(function () use (&$phases): OutboxBatchResult { + $queues->expects('connection')->with('redis')->returns($queue); + $queue->expects('publishOutboxMessages')->with($messages)->resolves(function () use (&$phases): OutboxBatchResult { $this->assertSame(['claim', 'claim released'], $phases); $this->assertFalse(CoroutineContext::has('request-only')); $phases[] = 'publish'; @@ -57,7 +61,7 @@ public function testClaimPublishSettleAndObserversReleaseTheirResourcesInOrder() // Drivers may preserve keys when filtering a batch's row IDs. return new OutboxBatchResult([7 => 1]); }); - $repository->expects('settle')->andReturnUsing(function () use (&$phases): int { + $repository->expects('settle')->resolves(function () use (&$phases): int { $this->assertSame('publish released', end($phases)); $phases[] = 'settle'; Coroutine::defer(static function () use (&$phases): void { $phases[] = 'settle released'; }); @@ -80,24 +84,24 @@ public function testClaimPublishSettleAndObserversReleaseTheirResourcesInOrder() public function testPartialResultsSettleBeforeAnotherConnectionAndReportingCannotBlockItsPublication(): void { - $repository = m::mock(DatabaseOutboxRepository::class); - $queues = m::mock(Factory::class); - $first = m::mock(Queue::class . ', ' . PublishesOutboxMessages::class); - $second = m::mock(Queue::class . ', ' . PublishesOutboxMessages::class); + $repository = Double::for(DatabaseOutboxRepository::class)->strict(); + $queues = Double::for(Factory::class)->strict(); + $first = Double::for(Queue::class, PublishesOutboxMessages::class)->strict(); + $second = Double::for(Queue::class, PublishesOutboxMessages::class)->strict(); $events = new Dispatcher; - $exceptions = m::mock(ExceptionHandler::class); + $exceptions = Double::for(ExceptionHandler::class)->strict(); $messages = [$this->message(1), $this->message(2), $this->message(3, 'other')]; $failure = new RuntimeException('Second publication rejected.'); $settled = []; - $queues->expects('connection')->with('redis')->andReturn($first); - $queues->expects('connection')->with('other')->andReturn($second); - $first->expects('publishOutboxMessages')->andReturn(new OutboxBatchResult([1], failure: $failure)); - $second->expects('publishOutboxMessages')->andReturnUsing(function () use (&$settled): OutboxBatchResult { + $queues->expects('connection')->with('redis')->returns($first); + $queues->expects('connection')->with('other')->returns($second); + $first->expects('publishOutboxMessages')->returns(new OutboxBatchResult([1], failure: $failure)); + $second->expects('publishOutboxMessages')->resolves(function () use (&$settled): OutboxBatchResult { $this->assertSame([[1]], $settled); return new OutboxBatchResult([3]); }); - $repository->shouldReceive('settle')->twice()->andReturnUsing(function (string $database, array $group, OutboxBatchResult $result) use (&$settled): int { + $repository->expects('settle')->times(2)->resolves(function (string $database, array $group, OutboxBatchResult $result) use (&$settled): int { $settled[] = $result->accepted; return count($group); @@ -107,7 +111,7 @@ public function testPartialResultsSettleBeforeAnotherConnectionAndReportingCanno $this->assertSame(1, $event->failed); $this->assertSame($failure, $event->exception); }); - $exceptions->expects('report')->with($failure, m::on(function (array $context) use (&$settled): bool { + $exceptions->expects('report')->with($failure, Argument::satisfies(function (array $context) use (&$settled): bool { $this->assertSame([[1], [3]], $settled); $this->assertSame([1, 2], $context['outbox_ids']); $this->assertSame(['SendInvoice', 'SendInvoice'], $context['jobs']); @@ -121,20 +125,20 @@ public function testPartialResultsSettleBeforeAnotherConnectionAndReportingCanno #[DataProvider('invalidResults')] public function testInvalidResultsReleaseEveryInputAsFailure(OutboxBatchResult $invalid): void { - $repository = m::mock(DatabaseOutboxRepository::class); - $queues = m::mock(Factory::class); - $queue = m::mock(Queue::class . ', ' . PublishesOutboxMessages::class); - $exceptions = m::mock(ExceptionHandler::class); - $queues->expects('connection')->andReturn($queue); - $queue->expects('publishOutboxMessages')->andReturn($invalid); - $repository->expects('settle')->with('primary', m::type('array'), m::on(function (OutboxBatchResult $result): bool { + $repository = Double::for(DatabaseOutboxRepository::class)->strict(); + $queues = Double::for(Factory::class)->strict(); + $queue = Double::for(Queue::class, PublishesOutboxMessages::class)->strict(); + $exceptions = Double::for(ExceptionHandler::class)->strict(); + $queues->expects('connection')->returns($queue); + $queue->expects('publishOutboxMessages')->returns($invalid); + $repository->expects('settle')->with('primary', Argument::type('array'), Argument::satisfies(function (OutboxBatchResult $result): bool { $this->assertSame([], $result->accepted); $this->assertSame([], $result->deferred); $this->assertInstanceOf(LogicException::class, $result->failure); return true; - }))->andReturn(2); - $exceptions->expects('report')->with(m::type(LogicException::class), m::type('array')); + }))->returns(2); + $exceptions->expects('report')->with(Argument::type(LogicException::class), Argument::type('array')); $this->assertFalse((new OutboxRelay($repository, $queues, new Dispatcher, $exceptions))->deliver('primary', [$this->message(1), $this->message(2)])); } @@ -156,33 +160,33 @@ public static function invalidResults(): array public function testGenericFallbackDefersFutureRowsWithoutEventsAndSettlesThemNormally(): void { - $repository = m::mock(DatabaseOutboxRepository::class); - $queues = m::mock(Factory::class); - $queue = m::mock(Queue::class); - $exceptions = m::mock(ExceptionHandler::class); + $repository = Double::for(DatabaseOutboxRepository::class)->strict(); + $queues = Double::for(Factory::class)->strict(); + $queue = Double::for(Queue::class)->strict(); + $exceptions = Double::for(ExceptionHandler::class)->strict(); $events = new Dispatcher; $events->listen(OutboxBatchDelivered::class, fn () => $this->fail('Deferred rows were not delivered.')); $events->listen(OutboxBatchDeliveryFailed::class, fn () => $this->fail('Deferral is not failure.')); - $queues->expects('connection')->andReturn($queue); - $repository->expects('settle')->with('primary', m::type('array'), m::on(fn (OutboxBatchResult $result): bool => $result->accepted === [] && $result->deferred === [1] && $result->failure === null))->andReturn(1); + $queues->expects('connection')->returns($queue); + $repository->expects('settle')->with('primary', Argument::type('array'), Argument::satisfies(fn (OutboxBatchResult $result): bool => $result->accepted === [] && $result->deferred === [1] && $result->failure === null))->returns(1); $this->assertTrue((new OutboxRelay($repository, $queues, $events, $exceptions))->deliver('primary', [$this->message(1, deliverAt: CarbonImmutable::now()->getTimestamp() + 60)])); } public function testPublicationAndSettlementErrorsAreBothReportedWithPublicationOnTheEvent(): void { - $repository = m::mock(DatabaseOutboxRepository::class); - $queues = m::mock(Factory::class); - $queue = m::mock(Queue::class); - $exceptions = m::mock(ExceptionHandler::class); + $repository = Double::for(DatabaseOutboxRepository::class)->strict(); + $queues = Double::for(Factory::class)->strict(); + $queue = Double::for(Queue::class)->strict(); + $exceptions = Double::for(ExceptionHandler::class)->strict(); $events = new Dispatcher; $publication = new RuntimeException('Broker unavailable.'); $settlement = new RuntimeException('Database unavailable.'); - $queues->expects('connection')->andReturn($queue); - $queue->expects('pushRaw')->andThrow($publication); - $repository->expects('settle')->andThrow($settlement); - $exceptions->expects('report')->with($publication, m::type('array')); - $exceptions->expects('report')->with($settlement, m::type('array')); + $queues->expects('connection')->returns($queue); + $queue->expects('pushRaw')->throws($publication); + $repository->expects('settle')->throws($settlement); + $exceptions->expects('report')->with($publication, Argument::type('array')); + $exceptions->expects('report')->with($settlement, Argument::type('array')); $events->listen(OutboxBatchDeliveryFailed::class, function (OutboxBatchDeliveryFailed $event) use ($publication): void { $this->assertSame($publication, $event->exception); }); @@ -192,21 +196,21 @@ public function testPublicationAndSettlementErrorsAreBothReportedWithPublication public function testLostSettlementOwnershipReportsConfirmedDeliveryWithoutRepublishing(): void { - $repository = m::mock(DatabaseOutboxRepository::class); - $queues = m::mock(Factory::class); - $queue = m::mock(Queue::class); - $exceptions = m::mock(ExceptionHandler::class); + $repository = Double::for(DatabaseOutboxRepository::class)->strict(); + $queues = Double::for(Factory::class)->strict(); + $queue = Double::for(Queue::class)->strict(); + $exceptions = Double::for(ExceptionHandler::class)->strict(); $events = new Dispatcher; - $queues->expects('connection')->andReturn($queue); - $queue->expects('pushRaw')->andReturn('accepted'); - $repository->expects('settle')->andReturn(0); + $queues->expects('connection')->returns($queue); + $queue->expects('pushRaw')->returns('accepted'); + $repository->expects('settle')->returns(0); $events->listen(OutboxBatchDelivered::class, fn () => $this->fail('Lost ownership is a settlement failure.')); $events->listen(OutboxBatchDeliveryFailed::class, function (OutboxBatchDeliveryFailed $event): void { $this->assertSame(1, $event->accepted); $this->assertSame(0, $event->failed); $this->assertStringContainsString('lease ownership changed', $event->exception->getMessage()); }); - $exceptions->expects('report')->with(m::type(RuntimeException::class), m::type('array')); + $exceptions->expects('report')->with(Argument::type(RuntimeException::class), Argument::type('array')); $this->assertFalse((new OutboxRelay($repository, $queues, $events, $exceptions))->deliver('primary', [$this->message(1)])); } @@ -214,26 +218,26 @@ public function testLostSettlementOwnershipReportsConfirmedDeliveryWithoutRepubl #[DataProvider('reportingOutcomes')] public function testListenerFailureDoesNotThrottleDeliveryAndReporterFailureEscapes(bool $reporterFails): void { - $repository = m::mock(DatabaseOutboxRepository::class); - $queues = m::mock(Factory::class); - $queue = m::mock(Queue::class); - $exceptions = m::mock(ExceptionHandler::class); + $repository = Double::for(DatabaseOutboxRepository::class)->strict(); + $queues = Double::for(Factory::class)->strict(); + $queue = Double::for(Queue::class)->strict(); + $exceptions = Double::for(ExceptionHandler::class)->strict(); $events = new Dispatcher; $listenerFailure = new RuntimeException('Listener failed.'); $reporterFailure = new RuntimeException('Reporter failed.'); $released = false; - $queues->expects('connection')->andReturn($queue); - $queue->expects('pushRaw')->andReturn('accepted'); - $repository->expects('settle')->andReturn(1); + $queues->expects('connection')->returns($queue); + $queue->expects('pushRaw')->returns('accepted'); + $repository->expects('settle')->returns(1); $events->listen(OutboxBatchDelivered::class, static function () use ($listenerFailure, &$released): void { Coroutine::defer(static function () use (&$released): void { $released = true; }); throw $listenerFailure; }); $events->listen(OutboxBatchDeliveryFailed::class, fn () => $this->fail('Listener failure must not change the delivery event.')); - $report = $exceptions->expects('report')->with($listenerFailure, m::type('array')); + $report = $exceptions->expects('report')->with($listenerFailure, Argument::type('array')); if ($reporterFails) { - $report->andThrow($reporterFailure); + $report->throws($reporterFailure); } try { @@ -262,16 +266,18 @@ public static function reportingOutcomes(): array #[TestWith(['notification', true])] public function testIndependentPhaseCancellationReleasesResourcesAndStopsDelivery(string $phase, bool $cleanupThrows): void { - $repository = m::mock(DatabaseOutboxRepository::class); - $queues = m::mock(Factory::class); - $queue = m::mock($phase === 'sequential' ? Queue::class : Queue::class . ', ' . PublishesOutboxMessages::class); - $exceptions = m::mock(ExceptionHandler::class); + $repository = Double::for(DatabaseOutboxRepository::class)->strict(); + $queues = Double::for(Factory::class)->strict(); + $queue = ($phase === 'sequential' + ? Double::for(Queue::class) + : Double::for(Queue::class, PublishesOutboxMessages::class))->strict(); + $exceptions = Double::for(ExceptionHandler::class)->strict(); $cancellation = new CanceledException; if ($cleanupThrows) { $cancellation = new RuntimeException('Phase cleanup failed.', previous: $cancellation); } $released = false; - $queues->expects('connection')->andReturn($queue); + $queues->expects('connection')->returns($queue); $cancel = static function () use ($cancellation, &$released): never { Coroutine::defer(static function () use (&$released): void { $released = true; }); throw $cancellation; @@ -279,15 +285,15 @@ public function testIndependentPhaseCancellationReleasesResourcesAndStopsDeliver $events = new Dispatcher; if ($phase === 'sequential') { - $queue->expects('pushRaw')->andReturnUsing($cancel); + $queue->expects('pushRaw')->resolves($cancel); } elseif ($phase === 'publication') { - $queue->expects('publishOutboxMessages')->andReturnUsing($cancel); + $queue->expects('publishOutboxMessages')->resolves($cancel); } else { - $queue->expects('publishOutboxMessages')->andReturn(new OutboxBatchResult([1])); + $queue->expects('publishOutboxMessages')->returns(new OutboxBatchResult([1])); if ($phase === 'settlement') { - $repository->expects('settle')->andReturnUsing($cancel); + $repository->expects('settle')->resolves($cancel); } else { - $repository->expects('settle')->andReturn(1); + $repository->expects('settle')->returns(1); $events->listen(OutboxBatchDelivered::class, $cancel); } } @@ -309,21 +315,23 @@ public function testIndependentPhaseCancellationReleasesResourcesAndStopsDeliver #[DataProvider('driverCancellationOutcomes')] public function testDriverCancellationStopsDeliveryWithoutSettlement(string $outcome, bool $child): void { - $repository = m::mock(DatabaseOutboxRepository::class); - $repository->shouldNotReceive('settle'); - $queues = m::mock(Factory::class); - $queue = m::mock($outcome === 'sequential' ? Queue::class : Queue::class . ', ' . PublishesOutboxMessages::class); - $exceptions = m::mock(ExceptionHandler::class); - $exceptions->shouldNotReceive('report'); + $repository = Double::for(DatabaseOutboxRepository::class)->strict(); + $repository->expects('settle')->never(); + $queues = Double::for(Factory::class)->strict(); + $queue = ($outcome === 'sequential' + ? Double::for(Queue::class) + : Double::for(Queue::class, PublishesOutboxMessages::class))->strict(); + $exceptions = Double::for(ExceptionHandler::class)->strict(); + $exceptions->expects('report')->never(); $cancellation = new RuntimeException('Observer cleanup failed.', previous: new CanceledException); if ($child) { $cancellation = new ChildCancellationException('Publication child canceled.', previous: $cancellation); } - $queues->expects('connection')->with('redis')->andReturn($queue); + $queues->expects('connection')->with('redis')->returns($queue); $publication = $queue->expects($outcome === 'sequential' ? 'pushRaw' : 'publishOutboxMessages'); $outcome === 'returned' - ? $publication->andReturn(new OutboxBatchResult([1], failure: $cancellation)) - : $publication->andThrow($cancellation); + ? $publication->returns(new OutboxBatchResult([1], failure: $cancellation)) + : $publication->throws($cancellation); try { (new OutboxRelay($repository, $queues, new Dispatcher, $exceptions))->deliver('primary', [$this->message(1), $this->message(2, 'other')]); diff --git a/tests/Queue/Outbox/OutboxTransactionTest.php b/tests/Queue/Outbox/OutboxTransactionTest.php index 9007304eee..6584f90ee0 100644 --- a/tests/Queue/Outbox/OutboxTransactionTest.php +++ b/tests/Queue/Outbox/OutboxTransactionTest.php @@ -23,12 +23,15 @@ use Hypervel\Queue\RedisQueue; use Hypervel\Support\Facades\Facade; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\DataProvider; class OutboxTransactionTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('transactionDepths')] public function testFailedLaterInsertChunkLeavesNoPartialGroup(int $depth): void { @@ -145,11 +148,11 @@ protected function queue(): array Facade::setFacadeApplication($container); (require dirname(__DIR__, 3) . '/src/testbench/hypervel/migrations/0001_01_01_000009_testbench_create_job_outbox_table.php')->up(); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->with('business')->andReturn($database); + $resolver = Double::for(ConnectionResolverInterface::class)->strict(); + $resolver->allows('connection')->with('business')->returns($database); $repository = new DatabaseOutboxRepository($resolver, ['business'], 'job_outbox', 300); $container->instance(OutboxDispatcher::class, new OutboxDispatcher($repository, $resolver, $transactions)); - $queue = new RedisQueue(m::mock(Factory::class), 'orders'); + $queue = new RedisQueue(Double::for(Factory::class)->strict(), 'orders'); $queue->setContainer($container)->setConnectionName('redis'); return [$queue, $database, $events]; diff --git a/tests/Queue/Outbox/OutboxWorkerTest.php b/tests/Queue/Outbox/OutboxWorkerTest.php index 1f968f790b..720c7c94e1 100644 --- a/tests/Queue/Outbox/OutboxWorkerTest.php +++ b/tests/Queue/Outbox/OutboxWorkerTest.php @@ -21,17 +21,22 @@ use Hypervel\Queue\Worker; use Hypervel\Support\Sleep; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use Swoole\Coroutine\CanceledException; class OutboxWorkerTest extends TestCase { - protected OutboxRelay $relay; + use VerifiesDoubles; - protected Cache $cache; + protected OutboxRelay&DoubleInterface $relay; - protected ExceptionHandler $exceptions; + protected Cache&DoubleInterface $cache; + + protected ExceptionHandler&DoubleInterface $exceptions; protected Closure $signalHandler; @@ -42,9 +47,9 @@ public function testRoundRobinClaimsHaveAnExactJobLimitAndConcurrentPublication( $running = 0; $peak = 0; $finished = 0; - $this->relay->expects('claim')->with('primary', 2)->andReturn([$this->message(1), $this->message(2)]); - $this->relay->expects('claim')->with('secondary', 1)->andReturn([$this->message(3)]); - $this->relay->shouldReceive('deliver')->twice()->andReturnUsing(function (string $database) use ($releaseFirst, &$running, &$peak, &$finished): bool { + $this->relay->expects('claim')->with('primary', 2)->returns([$this->message(1), $this->message(2)]); + $this->relay->expects('claim')->with('secondary', 1)->returns([$this->message(3)]); + $this->relay->expects('deliver')->times(2)->resolves(function (string $database) use ($releaseFirst, &$running, &$peak, &$finished): bool { $peak = max($peak, ++$running); try { @@ -73,9 +78,9 @@ public function testFailedSourceCoolsDownWithoutDelayingHealthySources(): void Sleep::fake(); $worker = $this->worker(['broken', 'healthy']); $failure = new RuntimeException('Connection refused.'); - $this->relay->expects('claim')->with('broken', 1)->andThrow($failure); - $this->relay->shouldReceive('claim')->with('healthy', 1)->times(3)->andReturn([$this->message(1)]); - $this->relay->shouldReceive('deliver')->with('healthy', m::type('array'))->times(3)->andReturn(true); + $this->relay->expects('claim')->with('broken', 1)->throws($failure); + $this->relay->expects('claim')->with('healthy', 1)->times(3)->returns([$this->message(1)]); + $this->relay->expects('deliver')->with('healthy', Argument::type('array'))->times(3)->returns(true); $this->exceptions->expects('report')->with($failure, ['outbox_database' => 'broken']); $this->assertSame(0, $worker->run(null, new OutboxWorkerOptions(batch: 1, sleep: 60, maxJobs: 3, memory: 1024))); @@ -87,8 +92,8 @@ public function testStopWhenEmptyTreatsFailedSourcesAsEmptyAndDoesNotRecheckAfte Sleep::fake(); $worker = $this->worker(['broken', 'empty']); $failure = new RuntimeException('Missing table.'); - $this->relay->expects('claim')->with('broken', 100)->andThrow($failure); - $this->relay->expects('claim')->with('empty', 100)->andReturn([]); + $this->relay->expects('claim')->with('broken', 100)->throws($failure); + $this->relay->expects('claim')->with('empty', 100)->returns([]); $this->exceptions->expects('report')->with($failure, ['outbox_database' => 'broken']); $this->assertSame(0, $worker->run(null, new OutboxWorkerOptions(memory: 1024, stopWhenEmpty: true))); @@ -99,9 +104,9 @@ public function testOnceVisitsEverySourceWithoutSleepingEvenWhenDeliveryFails(): { Sleep::fake(); $worker = $this->worker(['first', 'second']); - $this->relay->expects('claim')->with('first', 100)->andReturn([$this->message(1)]); - $this->relay->expects('claim')->with('second', 100)->andReturn([]); - $this->relay->expects('deliver')->with('first', m::type('array'))->andReturn(false); + $this->relay->expects('claim')->with('first', 100)->returns([$this->message(1)]); + $this->relay->expects('claim')->with('second', 100)->returns([]); + $this->relay->expects('deliver')->with('first', Argument::type('array'))->returns(false); $this->assertSame(0, $worker->run(null, new OutboxWorkerOptions(memory: 1024, once: true))); Sleep::assertNeverSlept(); @@ -110,7 +115,7 @@ public function testOnceVisitsEverySourceWithoutSleepingEvenWhenDeliveryFails(): public function testPinnedSourceDoesNotClaimFromOtherConfiguredDatabases(): void { $worker = $this->worker(['first', 'second']); - $this->relay->expects('claim')->with('second', 100)->andReturn([]); + $this->relay->expects('claim')->with('second', 100)->returns([]); $this->assertSame(0, $worker->run('second', new OutboxWorkerOptions(memory: 1024, once: true))); } @@ -120,11 +125,10 @@ public function testFailureSleepKeepsThePublicationSlotOccupied(): void Sleep::fake(); $worker = $this->worker(); $claims = 0; - $this->relay->shouldReceive('claim')->twice()->andReturnUsing(function () use (&$claims): array { + $this->relay->expects('claim')->times(2)->resolves(function () use (&$claims): array { return [$this->message(++$claims)]; }); - $this->relay->expects('deliver')->andReturn(false); - $this->relay->expects('deliver')->andReturn(true); + $this->relay->expects('deliver')->times(2)->returns(false, true); Sleep::whenFakingSleep(function () use (&$claims): void { $this->assertSame(1, $claims); }); @@ -137,8 +141,8 @@ public function testEmptyPassSleepsOnceAndSignalStopsFurtherAdmission(): void { Sleep::fake(); $worker = $this->worker(['first', 'second']); - $this->relay->expects('claim')->with('first', 100)->andReturn([]); - $this->relay->expects('claim')->with('second', 100)->andReturn([]); + $this->relay->expects('claim')->with('first', 100)->returns([]); + $this->relay->expects('claim')->with('second', 100)->returns([]); Sleep::whenFakingSleep(function (): void { ($this->signalHandler)(SIGTERM); }); $this->assertSame(0, $worker->run(null, new OutboxWorkerOptions(sleep: 0.25, memory: 1024))); @@ -151,10 +155,10 @@ public function testPauseStopsAdmissionUntilTheResumeSignal(): void $worker = $this->worker(); $claims = 0; $sleeps = 0; - $this->relay->shouldReceive('claim')->twice()->andReturnUsing(function () use (&$claims): array { + $this->relay->expects('claim')->times(2)->resolves(function () use (&$claims): array { return ++$claims === 1 ? [] : [$this->message(1)]; }); - $this->relay->expects('deliver')->andReturn(true); + $this->relay->expects('deliver')->returns(true); Sleep::whenFakingSleep(function () use (&$claims, &$sleeps): void { $this->assertSame(1, $claims); ($this->signalHandler)(++$sleeps === 1 ? SIGUSR2 : SIGCONT); @@ -170,41 +174,42 @@ public function testRestartReadsEndTheirCoroutineBeforeClaimingAndRestartStopsAd CoroutineContext::set('request-only', true); $borrowed = false; $reads = 0; - $this->cache->shouldReceive('get')->with(Worker::RESTART_SIGNAL_CACHE_KEY)->times(3)->andReturnUsing(function () use (&$borrowed, &$reads): int { + $this->cache->allows('get')->with(Worker::RESTART_SIGNAL_CACHE_KEY)->resolves(function () use (&$borrowed, &$reads): int { $this->assertFalse(CoroutineContext::has('request-only')); $borrowed = true; Coroutine::defer(static function () use (&$borrowed): void { $borrowed = false; }); return ++$reads === 3 ? 2 : 1; }); - $this->relay->expects('claim')->andReturnUsing(function () use (&$borrowed): array { + $this->relay->expects('claim')->resolves(function () use (&$borrowed): array { $this->assertFalse($borrowed); return [$this->message(1)]; }); - $this->relay->expects('deliver')->andReturn(true); + $this->relay->expects('deliver')->returns(true); $this->assertSame(0, $worker->run(null, new OutboxWorkerOptions(memory: 1024))); $this->assertFalse($borrowed); + $this->cache->received('get')->with(Worker::RESTART_SIGNAL_CACHE_KEY)->times(3); } public function testRestartSignalIsNotReadWithoutInterruptionPolling(): void { Worker::$restartable = false; $worker = $this->worker(); - $this->cache->shouldNotReceive('get'); - $this->relay->expects('claim')->andReturn([$this->message(1)]); - $this->relay->expects('deliver')->andReturn(true); + $this->relay->expects('claim')->returns([$this->message(1)]); + $this->relay->expects('deliver')->returns(true); $this->assertSame(0, $worker->run(null, new OutboxWorkerOptions(maxJobs: 1, memory: 1024))); + $this->cache->received('get')->never(); } public function testEscapingTaskFailureStopsAdmissionAndPropagates(): void { $worker = $this->worker(); $failure = new RuntimeException('Reporter unavailable.'); - $this->relay->expects('claim')->andReturn([$this->message(1)]); - $this->relay->expects('deliver')->andThrow($failure); + $this->relay->expects('claim')->returns([$this->message(1)]); + $this->relay->expects('deliver')->throws($failure); try { $worker->run(null, new OutboxWorkerOptions(memory: 1024)); @@ -221,8 +226,8 @@ public function testCancellationJoinsTaskCleanupBeforeReturningToTheCaller(): vo $blocker = new Channel(1); $released = false; $caught = null; - $this->relay->expects('claim')->andReturn([$this->message(1)]); - $this->relay->expects('deliver')->andReturnUsing(static function () use ($started, $blocker, &$released): bool { + $this->relay->expects('claim')->returns([$this->message(1)]); + $this->relay->expects('deliver')->resolves(static function () use ($started, $blocker, &$released): bool { Coroutine::defer(static function () use (&$released): void { $released = true; }); $started->push(true); $blocker->pop(5); @@ -262,7 +267,7 @@ public function testPercentageMemoryLimitControlsAdmission(): void try { $worker = $this->worker(); - $this->relay->expects('claim')->with('primary', 100)->andReturn([]); + $this->relay->expects('claim')->with('primary', 100)->returns([]); $this->assertSame(Worker::EXIT_SUCCESS, $worker->run(null, new OutboxWorkerOptions(memory: '50%', once: true))); $this->assertSame(Worker::EXIT_MEMORY_LIMIT, $this->worker()->run(null, new OutboxWorkerOptions(memory: '1%'))); @@ -276,20 +281,20 @@ public function testPercentageMemoryLimitControlsAdmission(): void */ protected function worker(array $databases = ['primary']): OutboxWorker { - $repository = m::mock(DatabaseOutboxRepository::class); - $repository->shouldReceive('getDatabases')->andReturn($databases); - $this->relay = m::mock(OutboxRelay::class); - $this->exceptions = m::mock(ExceptionHandler::class); - $this->cache = m::mock(Cache::class); - $this->cache->shouldReceive('get')->with(Worker::RESTART_SIGNAL_CACHE_KEY)->andReturn(null)->byDefault(); - $cacheFactory = m::mock(CacheFactory::class); - $cacheFactory->shouldReceive('store')->andReturn($this->cache); - $signals = m::mock(SignalRegistry::class); - $signals->expects('register')->andReturnUsing(function (object $owner, array $signals, Closure $callback): void { + $repository = Double::for(DatabaseOutboxRepository::class)->strict(); + $repository->allows('getDatabases')->returns($databases); + $this->relay = Double::for(OutboxRelay::class)->strict(); + $this->exceptions = Double::for(ExceptionHandler::class)->strict(); + $this->cache = Double::for(Cache::class)->strict(); + $this->cache->allows('get')->with(Worker::RESTART_SIGNAL_CACHE_KEY)->returns(null); + $cacheFactory = Double::for(CacheFactory::class)->strict(); + $cacheFactory->allows('store')->returns($this->cache); + $signals = Double::for(SignalRegistry::class)->strict(); + $signals->expects('register')->resolves(function (object $owner, array $signals, Closure $callback): void { $this->assertSame($owner, $callback); $this->signalHandler = $callback; }); - $signals->expects('unregister')->with(m::on(fn (object $owner): bool => $owner === $this->signalHandler)); + $signals->expects('unregister')->with(Argument::satisfies(fn (object $owner): bool => $owner === $this->signalHandler)); return new OutboxWorker($repository, $this->relay, $cacheFactory, $this->exceptions, $signals); } diff --git a/tests/Queue/Outbox/PooledOutboxPublicationTest.php b/tests/Queue/Outbox/PooledOutboxPublicationTest.php index f2a200430b..be879a697b 100644 --- a/tests/Queue/Outbox/PooledOutboxPublicationTest.php +++ b/tests/Queue/Outbox/PooledOutboxPublicationTest.php @@ -15,7 +15,8 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Str; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -23,12 +24,14 @@ class PooledOutboxPublicationTest extends TestCase { + use VerifiesDoubles; + public function testNativeBatchCapabilityUsesOneLeaseAndRetainsItsResult(): void { - $queue = m::mock(SyncQueue::class . ', ' . PublishesOutboxMessages::class)->makePartial(); + $queue = Double::for(PooledOutboxPublishingQueue::class)->passthru(); $messages = [$this->message(1), $this->message(2)]; $expected = new OutboxBatchResult([1], failure: new RuntimeException('Partial rejection.')); - $queue->expects('publishOutboxMessages')->with($messages)->andReturn($expected); + $queue->expects('publishOutboxMessages')->with($messages)->returns($expected); $released = 0; $pools = new PoolManager; $proxy = $this->proxy($queue, $pools, $released); @@ -45,11 +48,11 @@ public function testNativeBatchCapabilityUsesOneLeaseAndRetainsItsResult(): void public function testSequentialFallbackRetainsConfirmedPrefixAndDefersFutureRows(): void { CarbonImmutable::setTestNow('2040-01-01 12:00:00'); - $queue = m::mock(SyncQueue::class)->makePartial(); + $queue = Double::for(new SyncQueue)->passthru(); $messages = [$this->message(1), $this->message(2, 60), $this->message(3), $this->message(4), $this->message(5, 120)]; $failure = new RuntimeException('Publication outcome unknown.'); - $queue->expects('pushRaw')->with($messages[0]->payload, 'orders', $messages[0]->options)->andReturn('accepted'); - $queue->expects('pushRaw')->with($messages[2]->payload, 'orders', $messages[2]->options)->andThrow($failure); + $queue->expects('pushRaw')->with($messages[0]->payload, 'orders', $messages[0]->options)->returns('accepted'); + $queue->expects('pushRaw')->with($messages[2]->payload, 'orders', $messages[2]->options)->throws($failure); $released = 0; $pools = new PoolManager; $proxy = $this->proxy($queue, $pools, $released); @@ -71,12 +74,12 @@ public function testSequentialFallbackRetainsConfirmedPrefixAndDefersFutureRows( #[TestWith([true])] public function testCancellationReleasesTheBorrowedTransportAndRemainsCancellation(bool $cleanupThrows): void { - $queue = m::mock(SyncQueue::class)->makePartial(); + $queue = Double::for(new SyncQueue)->passthru(); $cancellation = new CanceledException; if ($cleanupThrows) { $cancellation = new RuntimeException('Transport cleanup failed.', previous: $cancellation); } - $queue->expects('pushRaw')->andThrow($cancellation); + $queue->expects('pushRaw')->throws($cancellation); $released = 0; $pools = new PoolManager; $proxy = $this->proxy($queue, $pools, $released); @@ -133,3 +136,7 @@ protected function message(int $id, ?int $delay = null): OutboxMessage ); } } + +abstract class PooledOutboxPublishingQueue extends SyncQueue implements PublishesOutboxMessages +{ +} diff --git a/tests/Queue/Outbox/RedisOutboxPublicationTest.php b/tests/Queue/Outbox/RedisOutboxPublicationTest.php index 7fd1dbec0d..ea1194b4e8 100644 --- a/tests/Queue/Outbox/RedisOutboxPublicationTest.php +++ b/tests/Queue/Outbox/RedisOutboxPublicationTest.php @@ -17,11 +17,17 @@ use Hypervel\Queue\Outbox\OutboxMessage; use Hypervel\Queue\QueueRoutes; use Hypervel\Queue\RedisQueue; +use Hypervel\Redis\Pool\PoolManager; +use Hypervel\Redis\Pool\RedisPool; +use Hypervel\Redis\RedisConnection; use Hypervel\Redis\RedisProxy; +use Hypervel\Redis\RedisSentinelFactory; use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Str; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -30,6 +36,8 @@ class RedisOutboxPublicationTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('clusterModes')] public function testPublicationBatchesResolvedDestinationsWithoutReencodingPayloads(bool $cluster): void { @@ -43,7 +51,7 @@ public function testPublicationBatchesResolvedDestinationsWithoutReencodingPaylo LuaScripts::bulk(), [$key, $key . ':notify', $key . ':delayed'], ['i', $messages[0]->payload, $messages[1]->deliverAt, $messages[1]->payload], - )->andReturn(2); + )->returns(2); $result = $queue->publishOutboxMessages($messages); @@ -71,8 +79,8 @@ public function testLaterDestinationFailurePreservesEarlierConfirmation(string $ 'cleanup' => new RuntimeException('Redis cleanup failed.', previous: new CanceledException), default => new RuntimeException('Redis connection lost.'), }; - $connection->expects('evalWithShaCache')->withArgs(fn (string $script, array $keys): bool => $keys[0] === 'queues:first')->andReturn(1); - $connection->expects('evalWithShaCache')->withArgs(fn (string $script, array $keys): bool => $keys[0] === 'queues:second')->andThrow($failure); + $connection->expects('evalWithShaCache')->with(Argument::any(), Argument::satisfies(fn (array $keys): bool => $keys[0] === 'queues:first'), Argument::any())->returns(1); + $connection->expects('evalWithShaCache')->with(Argument::any(), Argument::satisfies(fn (array $keys): bool => $keys[0] === 'queues:second'), Argument::any())->throws($failure); try { $result = $queue->publishOutboxMessages([$this->message(1, 'first'), $this->message(2, 'second'), $this->message(3, 'third')]); @@ -91,7 +99,7 @@ public function testLaterDestinationFailurePreservesEarlierConfirmation(string $ public function testIncompleteConfirmationRetainsTheEntireDestination(): void { [$queue, $connection] = $this->queue(); - $connection->expects('evalWithShaCache')->andReturn(1); + $connection->expects('evalWithShaCache')->returns(1); $result = $queue->publishOutboxMessages([$this->message(1), $this->message(2)]); @@ -116,7 +124,7 @@ public function testHorizonStampsPublicationAndKeepsPublishingAfterObserverFailu }); $events->listen(JobQueued::class, fn () => $this->fail('Horizon relay must not emit JobQueued.')); $stored = []; - $connection->expects('evalWithShaCache')->twice()->andReturnUsing(function (string $script, array $keys, array $arguments) use (&$stored): int { + $connection->expects('evalWithShaCache')->times(2)->resolves(function (string $script, array $keys, array $arguments) use (&$stored): int { for ($index = 1; $index < count($arguments); $index += 2) { $stored[] = $arguments[$index]; } @@ -146,7 +154,7 @@ public function testObserverCancellationStopsPublishingLaterDestinations(): void [$queue, $connection, $events] = $this->queue(horizon: true); $cancellation = new RuntimeException('Observer cleanup failed.', previous: new CanceledException); $events->listen(JobPushed::class, static fn () => throw $cancellation); - $connection->expects('evalWithShaCache')->once()->andReturn(1); + $connection->expects('evalWithShaCache')->returns(1); try { $queue->publishOutboxMessages([$this->message(1), $this->message(2, 'other')]); @@ -161,11 +169,11 @@ public function testCancellationDuringObserverFailureReportingPropagates(): void [$queue, $connection, $events] = $this->queue(horizon: true); $observerFailure = new RuntimeException('Observer failed.'); $events->listen(JobPushed::class, static fn () => throw $observerFailure); - $connection->expects('evalWithShaCache')->withArgs(fn (string $script, array $keys): bool => $keys[0] === 'queues:first')->andReturn(1); - $connection->expects('evalWithShaCache')->withArgs(fn (string $script, array $keys): bool => $keys[0] === 'queues:second')->andThrow(new RuntimeException('Redis unavailable.')); + $connection->expects('evalWithShaCache')->with(Argument::any(), Argument::satisfies(fn (array $keys): bool => $keys[0] === 'queues:first'), Argument::any())->returns(1); + $connection->expects('evalWithShaCache')->with(Argument::any(), Argument::satisfies(fn (array $keys): bool => $keys[0] === 'queues:second'), Argument::any())->throws(new RuntimeException('Redis unavailable.')); $cancellation = new RuntimeException('Reporting cleanup failed.', previous: new CanceledException); - $handler = m::mock(ExceptionHandler::class); - $handler->expects('report')->with($observerFailure)->andThrow($cancellation); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($observerFailure)->throws($cancellation); Container::getInstance()->instance(ExceptionHandler::class, $handler); try { @@ -187,11 +195,19 @@ protected function queue(bool $cluster = false, bool $horizon = false): array $container->instance('events', $events); $container->instance(EventDispatcher::class, $events); $container->instance('queue.routes', $routes = new QueueRoutes); - $connection = m::mock(RedisProxy::class); - $connection->shouldAllowMockingMethod('evalWithShaCache'); - $connection->expects('isCluster')->andReturn($cluster); - $factory = m::mock(Factory::class); - $factory->shouldReceive('connection')->andReturn($connection); + $connection = Double::for(RedisConnection::class)->strict(); + $connection->allows('getConnection')->returns($connection); + $connection->allows('shouldTransform'); + $connection->allows('getEventDispatcher')->returns(null); + $connection->allows('release'); + $pool = Double::for(RedisPool::class)->strict(); + $pool->allows('borrow')->returns($connection); + $manager = Double::for(new PoolManager($container))->passthru(); + $manager->allows('pool')->with('outbox')->returns($pool); + $proxy = Double::for(new RedisProxy($manager, 'outbox', new RedisSentinelFactory))->passthru(); + $proxy->expects('isCluster')->returns($cluster); + $factory = Double::for(Factory::class)->strict(); + $factory->allows('connection')->returns($proxy); $queue = $horizon ? new HorizonRedisQueue($factory, 'orders') : new RedisQueue($factory, 'orders'); $queue->setContainer($container)->setConnectionName('redis'); diff --git a/tests/Queue/Outbox/SqsOutboxPublicationTest.php b/tests/Queue/Outbox/SqsOutboxPublicationTest.php index f0c78bb646..f6a5923e83 100644 --- a/tests/Queue/Outbox/SqsOutboxPublicationTest.php +++ b/tests/Queue/Outbox/SqsOutboxPublicationTest.php @@ -9,6 +9,7 @@ use Aws\Result; use Aws\Sqs\Exception\SqsException; use Aws\Sqs\SqsClient; +use Closure; use Hypervel\Cache\Repository; use Hypervel\Cache\WorkerArrayStore; use Hypervel\Container\Container; @@ -18,7 +19,8 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Str; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -27,14 +29,48 @@ class SqsOutboxPublicationTest extends TestCase { + use VerifiesDoubles; + + protected MockHandler $handler; + + protected SqsClient $client; + + /** + * Create a real SDK client whose requests stay inside the test. + */ + protected function setUp(): void + { + parent::setUp(); + + $this->handler = new MockHandler; + $this->client = new SqsClient([ + 'region' => 'us-east-1', + 'version' => 'latest', + 'credentials' => false, + 'handler' => $this->handler, + ]); + } + + /** + * Verify that every expected SDK request was made. + */ + protected function tearDown(): void + { + try { + $this->assertCount(0, $this->handler); + } finally { + parent::tearDown(); + } + } + #[DataProvider('deliveryTimes')] public function testPublicationPreservesQueueDefaultsAndAbsoluteTimers(?int $offset, bool $fifo, ?int $expected): void { CarbonImmutable::setTestNow('2040-01-01 12:00:00'); - $client = m::mock(SqsClient::class); + $client = $this->client; $queue = new SqsQueue($client, 'orders', 'https://sqs.test/account'); $message = $this->message(1, $fifo ? 'orders.fifo' : 'orders', $offset); - $client->expects('sendMessageBatch')->andReturnUsing(function (array $arguments) use ($fifo, $expected): Result { + $this->expectBatch(function (array $arguments) use ($fifo, $expected): Result { $entry = $arguments['Entries'][0]; $this->assertSame('https://sqs.test/account/orders' . ($fifo ? '.fifo' : ''), $arguments['QueueUrl']); @@ -71,7 +107,7 @@ public static function deliveryTimes(): array #[TestWith(['cleanup'])] public function testBatchSizeLimitsAndLaterSdkFailureRetainEarlierConfirmation(string $failureType): void { - $client = m::mock(SqsClient::class); + $client = $this->client; $queue = new SqsQueue($client, 'orders'); $failure = match ($failureType) { 'cancellation' => new CanceledException, @@ -79,7 +115,7 @@ public function testBatchSizeLimitsAndLaterSdkFailureRetainEarlierConfirmation(s default => new RuntimeException('SDK retries exhausted.'), }; $calls = 0; - $client->expects('sendMessageBatch')->twice()->andReturnUsing(function (array $arguments) use (&$calls, $failure): Result { + $this->expectBatch(function (array $arguments) use (&$calls, $failure): Result { if (++$calls === 2) { $this->assertCount(1, $arguments['Entries']); throw $failure; @@ -88,7 +124,7 @@ public function testBatchSizeLimitsAndLaterSdkFailureRetainEarlierConfirmation(s $this->assertCount(10, $arguments['Entries']); return new Result(['Successful' => array_map(static fn (array $entry): array => ['Id' => $entry['Id'], 'MessageId' => 'sqs-' . $entry['Id']], $arguments['Entries'])]); - }); + }, times: 2); try { $result = $queue->publishOutboxMessages(array_map(fn (int $id): OutboxMessage => $this->message($id), range(1, 11))); @@ -106,13 +142,13 @@ public function testBatchSizeLimitsAndLaterSdkFailureRetainEarlierConfirmation(s public function testByteLimitSplitsLargeMessagesBeforeTheCountLimit(): void { - $client = m::mock(SqsClient::class); + $client = $this->client; $queue = new SqsQueue($client, 'orders'); - $client->expects('sendMessageBatch')->twice()->andReturnUsing(function (array $arguments): Result { + $this->expectBatch(function (array $arguments): Result { $this->assertCount(1, $arguments['Entries']); return new Result(['Successful' => [['Id' => $arguments['Entries'][0]['Id'], 'MessageId' => 'accepted']]]); - }); + }, times: 2); $result = $queue->publishOutboxMessages([ $this->message(1, payload: json_encode(['data' => str_repeat('a', 600000)])), @@ -128,10 +164,10 @@ public function testExplicitRejectionCleansOnlyThatAttemptAndRetainsConfirmedEnt $container = new Container; Container::setInstance($container); $store = new Repository(new WorkerArrayStore); - $cache = m::mock(CacheFactory::class); - $cache->shouldReceive('store')->with(null)->andReturn($store); + $cache = Double::for(CacheFactory::class)->strict(); + $cache->allows('store')->with(null)->returns($store); $container->instance('cache', $cache); - $client = m::mock(SqsClient::class); + $client = $this->client; $queue = new SqsQueue($client, 'orders', overflowStorage: ['enabled' => true, 'always' => true]); $queue->setContainer($container); $first = $this->message(1); @@ -151,7 +187,7 @@ public function testExplicitRejectionCleansOnlyThatAttemptAndRetainsConfirmedEnt $accepted = $this->message(2); $paths = []; $calls = 0; - $client->expects('sendMessageBatch')->twice()->andReturnUsing(function (array $arguments) use (&$calls, &$paths, $store): Result { + $this->expectBatch(function (array $arguments) use (&$calls, &$paths, $store): Result { foreach ($arguments['Entries'] as $entry) { $path = json_decode($entry['MessageBody'], true)['@pointer']; $paths[] = $path; @@ -166,7 +202,7 @@ public function testExplicitRejectionCleansOnlyThatAttemptAndRetainsConfirmedEnt 'Successful' => [['Id' => '2', 'MessageId' => 'confirmed']], 'Failed' => [['Id' => '1', 'Code' => 'Rejected', 'Message' => 'Rejected entry', 'SenderFault' => true]], ]); - }); + }, times: 2); $this->assertSame([], $queue->publishOutboxMessages([$first])->accepted); $result = $queue->publishOutboxMessages([$secondAttempt, $accepted]); @@ -185,11 +221,11 @@ public function testServerFaultAfterAnSdkRetryRetainsThePayloadAnEarlierAttemptM $container = new Container; Container::setInstance($container); $store = new Repository(new WorkerArrayStore); - $cache = m::mock(CacheFactory::class); - $cache->shouldReceive('store')->with(null)->andReturn($store); + $cache = Double::for(CacheFactory::class)->strict(); + $cache->allows('store')->with(null)->returns($store); $container->instance('cache', $cache); $paths = []; - $handler = new MockHandler; + $handler = $this->handler; $handler->append( function (CommandInterface $command) use (&$paths): SqsException { $paths[] = json_decode($command['Entries'][0]['MessageBody'], true)['@pointer']; @@ -205,7 +241,7 @@ function (CommandInterface $command) use (&$paths): Result { ]); }, ); - $client = new SqsClient(['region' => 'us-east-1', 'version' => 'latest', 'credentials' => false, 'handler' => $handler]); + $client = $this->client; $queue = new SqsQueue($client, 'orders.fifo', overflowStorage: ['enabled' => true, 'always' => true]); $queue->setContainer($container); $message = $this->message(1, 'orders.fifo'); @@ -219,6 +255,22 @@ function (CommandInterface $command) use (&$paths): Result { $this->assertSame($message->payload, $store->get($paths[0])); } + /** + * Queue the expected batch requests and their responses. + * + * @param Closure(array): Result $response + */ + protected function expectBatch(Closure $response, int $times = 1): void + { + for ($index = 0; $index < $times; ++$index) { + $this->handler->append(function (CommandInterface $command) use ($response): Result { + $this->assertSame('SendMessageBatch', $command->getName()); + + return $response($command->toArray()); + }); + } + } + /** * Build a claimed envelope with previously captured FIFO options. */ diff --git a/tests/Queue/PooledJobWorkerTest.php b/tests/Queue/PooledJobWorkerTest.php index 8404f7f733..bb7f8ae13d 100644 --- a/tests/Queue/PooledJobWorkerTest.php +++ b/tests/Queue/PooledJobWorkerTest.php @@ -21,17 +21,21 @@ use Hypervel\Queue\Worker; use Hypervel\Queue\WorkerOptions; use Hypervel\Tests\TestCase; -use Mockery as m; -use Pheanstalk\Contract\JobIdInterface; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Pheanstalk\Contract\PheanstalkManagerInterface; use Pheanstalk\Contract\PheanstalkPublisherInterface; use Pheanstalk\Contract\PheanstalkSubscriberInterface; +use Pheanstalk\Values\Job as PheanstalkJob; +use Pheanstalk\Values\JobId; use Pheanstalk\Values\JobStats; use RuntimeException; use stdClass; class PooledJobWorkerTest extends TestCase { + use VerifiesDoubles; + /** @var list */ private array $pools = []; @@ -48,16 +52,15 @@ public function testProcessedListenerCanReadPrimedAttemptsAfterTerminalDelete(): Container::setInstance($container); $container->instance('handler', new PooledJobWorkerHandler); - $pheanstalk = m::mock(implode(',', [ + $pheanstalk = Double::for( PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class, - ])); - $pheanstalk->shouldReceive('statsJob')->once()->andReturn($this->stats(3)); - $pheanstalk->shouldReceive('delete')->once(); + )->strict(); + $pheanstalk->expects('statsJob')->returns($this->stats(3)); + $pheanstalk->expects('delete'); - $rawJob = m::mock(JobIdInterface::class); - $rawJob->shouldReceive('getData')->andReturn(json_encode([ + $rawJob = new PheanstalkJob(new JobId(1), json_encode([ 'job' => 'handler', 'data' => [], ], JSON_THROW_ON_ERROR)); @@ -73,12 +76,12 @@ public function testProcessedListenerCanReadPrimedAttemptsAfterTerminalDelete(): $job->withPoolLease(new Lease($pool, $pool->borrow())); $attemptsObservedByListener = null; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobProcessing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobProcessed::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobAttempted::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->times(3) - ->andReturnUsing(function (object $event) use (&$attemptsObservedByListener): array { + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobProcessing::class)->returns(true); + $events->expects('hasListeners')->with(JobProcessed::class)->returns(true); + $events->expects('hasListeners')->with(JobAttempted::class)->returns(true); + $events->expects('dispatch')->times(3) + ->resolves(function (object $event) use (&$attemptsObservedByListener): array { if ($event instanceof JobProcessed) { $attemptsObservedByListener = $event->job->attempts(); } @@ -87,9 +90,9 @@ public function testProcessedListenerCanReadPrimedAttemptsAfterTerminalDelete(): }); $worker = new Worker( - m::mock(Factory::class), + Double::for(Factory::class)->strict(), $events, - m::mock(ExceptionHandler::class), + Double::for(ExceptionHandler::class)->strict(), fn () => false, ); @@ -108,28 +111,27 @@ public function testWorkerExceptionReleasesTheBackendBeforeReturningTheLease(): $container = new Container; Container::setInstance($container); $container->instance('handler', new FailingPooledJobWorkerHandler); - $pheanstalk = m::mock(implode(',', [ + $pheanstalk = Double::for( PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class, - ])); - $pheanstalk->shouldReceive('statsJob')->atLeast()->once()->andReturn($this->stats(1)); - $pheanstalk->shouldReceive('release')->once(); - $rawJob = m::mock(JobIdInterface::class); - $rawJob->shouldReceive('getData')->andReturn(json_encode([ + )->strict(); + $pheanstalk->expects('statsJob')->times(minimum: 1)->returns($this->stats(1)); + $pheanstalk->expects('release'); + $rawJob = new PheanstalkJob(new JobId(1), json_encode([ 'job' => 'handler', 'data' => [], ], JSON_THROW_ON_ERROR)); $job = new BeanstalkdJob($container, $pheanstalk, $rawJob, 'connection', 'queue'); $pool = $this->pool(); $job->withPoolLease(new Lease($pool, $pool->borrow())); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobProcessing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobExceptionOccurred::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobReleasedAfterException::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobAttempted::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->times(4)->andReturn([]); - $worker = new Worker(m::mock(Factory::class), $events, m::mock(ExceptionHandler::class), fn () => false); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobProcessing::class)->returns(true); + $events->expects('hasListeners')->with(JobExceptionOccurred::class)->returns(true); + $events->expects('hasListeners')->with(JobReleasedAfterException::class)->returns(true); + $events->expects('hasListeners')->with(JobAttempted::class)->returns(true); + $events->expects('dispatch')->times(4)->returns([]); + $worker = new Worker(Double::for(Factory::class)->strict(), $events, Double::for(ExceptionHandler::class)->strict(), fn () => false); try { $worker->process('connection', $job, new WorkerOptions(maxTries: 0, backoff: 3)); @@ -148,29 +150,28 @@ public function testWorkerTerminalFailureDeletesBeforeReturningTheLease(): void $container = new Container; Container::setInstance($container); $container->instance('handler', new FailingPooledJobWorkerHandler); - $pheanstalk = m::mock(implode(',', [ + $pheanstalk = Double::for( PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class, - ])); - $pheanstalk->shouldReceive('statsJob')->atLeast()->once()->andReturn($this->stats(1)); - $pheanstalk->shouldReceive('delete')->once(); - $rawJob = m::mock(JobIdInterface::class); - $rawJob->shouldReceive('getData')->andReturn(json_encode([ + )->strict(); + $pheanstalk->expects('statsJob')->times(minimum: 1)->returns($this->stats(1)); + $pheanstalk->expects('delete'); + $rawJob = new PheanstalkJob(new JobId(1), json_encode([ 'job' => 'handler', 'data' => [], ], JSON_THROW_ON_ERROR)); $job = new BeanstalkdJob($container, $pheanstalk, $rawJob, 'connection', 'queue'); $pool = $this->pool(); $job->withPoolLease(new Lease($pool, $pool->borrow())); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobProcessing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobFailed::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobExceptionOccurred::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobAttempted::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->times(4)->andReturn([]); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobProcessing::class)->returns(true); + $events->expects('hasListeners')->with(JobFailed::class)->returns(true); + $events->expects('hasListeners')->with(JobExceptionOccurred::class)->returns(true); + $events->expects('hasListeners')->with(JobAttempted::class)->returns(true); + $events->expects('dispatch')->times(4)->returns([]); $container->instance(Dispatcher::class, $events); - $worker = new Worker(m::mock(Factory::class), $events, m::mock(ExceptionHandler::class), fn () => false); + $worker = new Worker(Double::for(Factory::class)->strict(), $events, Double::for(ExceptionHandler::class)->strict(), fn () => false); try { $worker->process('connection', $job, new WorkerOptions(maxTries: 1)); diff --git a/tests/Queue/QueueBackgroundQueueTest.php b/tests/Queue/QueueBackgroundQueueTest.php index c7c009881d..0d784a9934 100644 --- a/tests/Queue/QueueBackgroundQueueTest.php +++ b/tests/Queue/QueueBackgroundQueueTest.php @@ -31,7 +31,9 @@ use Hypervel\Queue\Jobs\SyncJob; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -41,6 +43,8 @@ class QueueBackgroundQueueTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; public function testPushShouldRunInBackground(): void @@ -154,12 +158,12 @@ public function testFailedJobGetsHandledWhenAnExceptionIsThrown(): void }); $background->setConnectionName('background'); $container = $this->getContainer(); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobProcessing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobExceptionOccurred::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobFailed::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobAttempted::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->times(4); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobProcessing::class)->returns(true); + $events->expects('hasListeners')->with(JobExceptionOccurred::class)->returns(true); + $events->expects('hasListeners')->with(JobFailed::class)->returns(true); + $events->expects('hasListeners')->with(JobAttempted::class)->returns(true); + $events->expects('dispatch')->times(4); $container->instance('events', $events); $container->instance(Dispatcher::class, $events); $background->setContainer($container); @@ -187,11 +191,11 @@ public function testCancellationReportsOnlyCleanupErrorsThroughTheExceptionCallb $handler = new CancelingBackgroundQueueTestHandler; $handler->cleanupException = $cleanupThrows ? new RuntimeException('Job cleanup failed.') : null; $container->instance(CancelingBackgroundQueueTestHandler::class, $handler); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobProcessing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobAttempted::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->once()->with(m::type(JobProcessing::class)); - $events->shouldReceive('dispatch')->once()->with(m::on( + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobProcessing::class)->returns(true); + $events->expects('hasListeners')->with(JobAttempted::class)->returns(true); + $events->expects('dispatch')->with(Argument::type(JobProcessing::class)); + $events->expects('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof JobAttempted && $event->canceled, )); $container->instance('events', $events); @@ -216,9 +220,9 @@ public function testItAddsATransactionCallbackForAfterCommitJobs(): void $background = new BackgroundQueue; $background->setConnectionName('background'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback')->once()->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); $container->instance('db.transactions', $transactionManager); $background->setContainer($container); @@ -230,9 +234,9 @@ public function testItAddsATransactionCallbackForInterfaceBasedAfterCommitJobs() $background = new BackgroundQueue; $background->setConnectionName('background'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback')->once()->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); $container->instance('db.transactions', $transactionManager); $background->setContainer($container); @@ -244,10 +248,10 @@ public function testItAddsATransactionCallbackForAfterCommitUniqueJobs(): void $background = new BackgroundQueue; $background->setConnectionName('background'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback')->once()->andReturn(null); - $transactionManager->shouldReceive('addCallbackForRollback')->once()->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new BackgroundQueueAfterCommitUniqueJob; @@ -262,10 +266,10 @@ public function testItAddsATransactionRollbackCallbackForAfterCommitDebouncedJob $background = new BackgroundQueue; $background->setConnectionName('background'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback')->once()->andReturn(null); - $transactionManager->shouldReceive('addCallbackForRollback')->once()->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new BackgroundQueueAfterCommitDebouncedJob; @@ -280,10 +284,10 @@ public function testItAddsATransactionCallbackForInterfaceBasedAfterCommitUnique $background = new BackgroundQueue; $background->setConnectionName('background'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback')->once()->andReturn(null); - $transactionManager->shouldReceive('addCallbackForRollback')->once()->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new BackgroundQueueAfterCommitInterfaceUniqueJob; @@ -295,11 +299,10 @@ public function testItAddsATransactionCallbackForInterfaceBasedAfterCommitUnique public function testLaterSchedulesJobWithDelay(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after') - ->once() - ->with(5.0, m::type('Closure')) - ->andReturnUsing(function ($delay, $callback) { + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after') + ->with(5.0, Argument::type('Closure')) + ->resolves(function ($delay, $callback) { $callback(); return 1; }); @@ -318,11 +321,10 @@ public function testLaterSchedulesJobWithDelay(): void public function testBulkRespectsDelayAttribute(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after') - ->once() - ->with(5.0, m::type('Closure')) - ->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after') + ->with(5.0, Argument::type('Closure')) + ->returns(1); $background = new BackgroundQueue(timer: $timer); $background->setConnectionName('background'); @@ -336,11 +338,10 @@ public function testBulkRespectsDelayAttribute(): void public function testLaterSnapshotsMutableJobBeforeTheTimerRuns(bool $afterCommit): void { $scheduled = null; - $timer = m::mock(Timer::class); - $timer->shouldReceive('after') - ->once() - ->with(5.0, m::type('Closure')) - ->andReturnUsing(function ($delay, $callback) use (&$scheduled) { + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after') + ->with(5.0, Argument::type('Closure')) + ->resolves(function ($delay, $callback) use (&$scheduled) { $scheduled = $callback; return 1; @@ -378,11 +379,10 @@ public function testPushSnapshotsAfterCommitJobAtDispatch(): void { $afterCommit = null; $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback') - ->once() - ->andReturnUsing(function ($callback) use (&$afterCommit) { + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback') + ->resolves(function ($callback) use (&$afterCommit) { $afterCommit = $callback; return null; @@ -409,11 +409,10 @@ public function testLaterWithDateInterval(): void { CarbonImmutable::setTestNow('2024-01-01 12:00:00'); - $timer = m::mock(Timer::class); - $timer->shouldReceive('after') - ->once() - ->with(10.0, m::type('Closure')) - ->andReturnUsing(function ($delay, $callback) { + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after') + ->with(10.0, Argument::type('Closure')) + ->resolves(function ($delay, $callback) { $callback(); return 1; }); @@ -436,11 +435,10 @@ public function testLaterWithDateTime(): void { CarbonImmutable::setTestNow('2024-01-01 12:00:00'); - $timer = m::mock(Timer::class); - $timer->shouldReceive('after') - ->once() - ->with(15.0, m::type('Closure')) - ->andReturnUsing(function ($delay, $callback) { + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after') + ->with(15.0, Argument::type('Closure')) + ->resolves(function ($delay, $callback) { $callback(); return 1; }); @@ -461,18 +459,17 @@ public function testLaterWithDateTime(): void public function testLaterAddsTransactionCallbackForAfterCommitJobs(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(5.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(5.0, Argument::type('Closure'))->returns(1); $background = new BackgroundQueue(timer: $timer); $background->setConnectionName('background'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback') - ->once() - ->andReturnUsing(function ($callback) { + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback') + ->resolves(function ($callback) { $callback(); return null; }); @@ -484,18 +481,17 @@ public function testLaterAddsTransactionCallbackForAfterCommitJobs(): void public function testLaterAddsTransactionCallbackForInterfaceBasedAfterCommitJobs(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(5.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(5.0, Argument::type('Closure'))->returns(1); $background = new BackgroundQueue(timer: $timer); $background->setConnectionName('background'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback') - ->once() - ->andReturnUsing(function ($callback) { + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback') + ->resolves(function ($callback) { $callback(); return null; }); @@ -507,22 +503,21 @@ public function testLaterAddsTransactionCallbackForInterfaceBasedAfterCommitJobs public function testLaterAddsTransactionCallbackForAfterCommitUniqueJobs(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(5.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(5.0, Argument::type('Closure'))->returns(1); $background = new BackgroundQueue(timer: $timer); $background->setConnectionName('background'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback') - ->once() - ->andReturnUsing(function ($callback) { + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback') + ->resolves(function ($callback) { $callback(); return null; }); - $transactionManager->shouldReceive('addCallbackForRollback')->once()->andReturn(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new BackgroundQueueAfterCommitUniqueJob; DispatchLockContext::registerUnique($job, $container->make(Cache::class), null, 'unique-key', 'owner'); @@ -533,22 +528,21 @@ public function testLaterAddsTransactionCallbackForAfterCommitUniqueJobs(): void public function testLaterAddsTransactionRollbackCallbackForAfterCommitDebouncedJobs(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(5.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(5.0, Argument::type('Closure'))->returns(1); $background = new BackgroundQueue(timer: $timer); $background->setConnectionName('background'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback') - ->once() - ->andReturnUsing(function ($callback) { + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback') + ->resolves(function ($callback) { $callback(); return null; }); - $transactionManager->shouldReceive('addCallbackForRollback')->once()->andReturn(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new BackgroundQueueAfterCommitDebouncedJob; DispatchLockContext::registerDebounce($job, $container->make(Cache::class), 'debounce-key', 'owner'); @@ -559,22 +553,21 @@ public function testLaterAddsTransactionRollbackCallbackForAfterCommitDebouncedJ public function testLaterAddsTransactionCallbackForInterfaceBasedAfterCommitUniqueJobs(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(5.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(5.0, Argument::type('Closure'))->returns(1); $background = new BackgroundQueue(timer: $timer); $background->setConnectionName('background'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback') - ->once() - ->andReturnUsing(function ($callback) { + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback') + ->resolves(function ($callback) { $callback(); return null; }); - $transactionManager->shouldReceive('addCallbackForRollback')->once()->andReturn(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new BackgroundQueueAfterCommitInterfaceUniqueJob; DispatchLockContext::registerUnique($job, $container->make(Cache::class), null, 'unique-key', 'owner'); @@ -585,8 +578,8 @@ public function testLaterAddsTransactionCallbackForInterfaceBasedAfterCommitUniq public function testLaterClampsNegativeIntegerDelay(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(0.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(0.0, Argument::type('Closure'))->returns(1); $background = new BackgroundQueue(timer: $timer); $background->setConnectionName('background'); @@ -599,8 +592,8 @@ public function testLaterClampsPastDateTimeInterface(): void { CarbonImmutable::setTestNow('2024-01-01 12:00:00'); - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(0.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(0.0, Argument::type('Closure'))->returns(1); $background = new BackgroundQueue(timer: $timer); $background->setConnectionName('background'); @@ -617,11 +610,10 @@ public function testLaterFailedJobGetsHandledWhenAnExceptionIsThrown(): void $result = null; - $timer = m::mock(Timer::class); - $timer->shouldReceive('after') - ->once() - ->with(5.0, m::type('Closure')) - ->andReturnUsing(function ($delay, $callback) { + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after') + ->with(5.0, Argument::type('Closure')) + ->resolves(function ($delay, $callback) { $callback(); return 1; }); @@ -632,12 +624,12 @@ public function testLaterFailedJobGetsHandledWhenAnExceptionIsThrown(): void }); $background->setConnectionName('background'); $container = $this->getContainer(); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobProcessing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobExceptionOccurred::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobFailed::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobAttempted::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->times(4); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobProcessing::class)->returns(true); + $events->expects('hasListeners')->with(JobExceptionOccurred::class)->returns(true); + $events->expects('hasListeners')->with(JobFailed::class)->returns(true); + $events->expects('hasListeners')->with(JobAttempted::class)->returns(true); + $events->expects('dispatch')->times(4); $container->instance('events', $events); $container->instance(Dispatcher::class, $events); $background->setContainer($container); @@ -660,11 +652,10 @@ public function testLaterDoesNotExecuteJobWhenWorkerIsClosing(): void $this->assertNotNull($metadata); $callback = null; - $timer = m::mock(Timer::class); - $timer->shouldReceive('after') - ->once() - ->with(5.0, m::type('Closure')) - ->andReturnUsing(function ($delay, $scheduledCallback) use (&$callback) { + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after') + ->with(5.0, Argument::type('Closure')) + ->resolves(function ($delay, $scheduledCallback) use (&$callback) { $callback = $scheduledCallback; return 1; @@ -692,7 +683,7 @@ public function testLaterDoesNotExecuteJobWhenWorkerIsClosing(): void protected function getContainer(): Container { $container = new Container; - $container->instance(Cache::class, m::mock(Cache::class)); + $container->instance(Cache::class, Double::for(Cache::class)->strict()); $container->instance(Dispatcher::class, new EventsDispatcher($container)); Container::setInstance($container); diff --git a/tests/Queue/QueueCommandIdentifierTest.php b/tests/Queue/QueueCommandIdentifierTest.php index ef958bd033..8907320e3b 100644 --- a/tests/Queue/QueueCommandIdentifierTest.php +++ b/tests/Queue/QueueCommandIdentifierTest.php @@ -12,13 +12,16 @@ use Hypervel\Queue\Listener; use Hypervel\Queue\QueueManager; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; class QueueCommandIdentifierTest extends TestCase { + use VerifiesDoubles; + protected function defineEnvironment(ApplicationContract $app): void { $config = $app->make('config'); @@ -35,11 +38,11 @@ public function testClearCommandPreservesZeroAndDefaultsEmptyIdentifiers( string $expectedConnection, string $expectedQueue, ): void { - $resolvedQueue = m::mock(Queue::class, ClearableQueue::class); - $resolvedQueue->shouldReceive('clear')->once()->with($expectedQueue)->andReturn(1); + $resolvedQueue = Double::for(Queue::class, ClearableQueue::class)->strict(); + $resolvedQueue->expects('clear')->with($expectedQueue)->returns(1); - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->once()->with($expectedConnection)->andReturn($resolvedQueue); + $manager = Double::for(QueueManager::class)->strict(); + $manager->expects('connection')->with($expectedConnection)->returns($resolvedQueue); $this->app->instance('queue', $manager); $command = new ClearCommand; @@ -64,8 +67,8 @@ public function testListenCommandPreservesZeroAndDefaultsEmptyIdentifiers( ): void { $this->app->make('config')->set("queue.connections.{$expectedConnection}.queue", $expectedQueue); - $listener = m::mock(Listener::class); - $listener->shouldReceive('setOutputHandler')->once(); + $listener = Double::for(Listener::class)->strict(); + $listener->expects('setOutputHandler'); $command = new QueueIdentifierListenCommand($this->app->make('config'), $listener); diff --git a/tests/Queue/QueueConfigTest.php b/tests/Queue/QueueConfigTest.php index ab9ccb43dd..bae0ad2754 100644 --- a/tests/Queue/QueueConfigTest.php +++ b/tests/Queue/QueueConfigTest.php @@ -22,11 +22,14 @@ use Hypervel\Support\ClassInvoker; use Hypervel\Support\Env; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Pheanstalk\Pheanstalk; class QueueConfigTest extends TestCase { + use VerifiesDoubles; + public function testConcurrencyNumberIsLoadedAsIntegerFromEnvironment(): void { $this->withEnvironment(['QUEUE_CONCURRENCY' => '5'], function (): void { @@ -72,13 +75,13 @@ public function testConnectorAfterCommitOmissionDefaultsMatchShippedConnections( 'sync' => new SyncConnector, 'background' => new BackgroundConnector, 'deferred' => new DeferredConnector, - 'database' => new DatabaseConnector(m::mock(ConnectionResolverInterface::class)), + 'database' => new DatabaseConnector(Double::for(ConnectionResolverInterface::class)->strict()), 'beanstalkd' => new BeanstalkdConnector, 'sqs' => new SqsConnector, - 'redis' => new RedisConnector(m::mock(RedisFactory::class)), + 'redis' => new RedisConnector(Double::for(RedisFactory::class)->strict()), 'failover' => new FailoverConnector( - m::mock(QueueManager::class), - m::mock(Dispatcher::class), + Double::for(QueueManager::class)->strict(), + Double::for(Dispatcher::class)->strict(), ), }; $constructionConfig = $connection; @@ -96,7 +99,7 @@ public function testConnectorAfterCommitOmissionDefaultsMatchShippedConnections( public function testConnectorOptionalMemberOmissionUsesOwnedDefaults(): void { - $databaseQueue = (new DatabaseConnector(m::mock(ConnectionResolverInterface::class)))->connect([ + $databaseQueue = (new DatabaseConnector(Double::for(ConnectionResolverInterface::class)->strict()))->connect([ 'table' => 'jobs', 'queue' => 'default', ]); @@ -115,7 +118,7 @@ public function testConnectorOptionalMemberOmissionUsesOwnedDefaults(): void $this->assertSame(Pheanstalk::DEFAULT_TTR, $beanstalkdQueueProperties->timeToRun); $this->assertSame(0, $beanstalkdQueueProperties->blockFor); - $redisQueue = (new RedisConnector(m::mock(RedisFactory::class)))->connect([ + $redisQueue = (new RedisConnector(Double::for(RedisFactory::class)->strict()))->connect([ 'queue' => 'default', ]); $redisQueueProperties = new ClassInvoker($redisQueue); diff --git a/tests/Queue/QueueDeferredQueueTest.php b/tests/Queue/QueueDeferredQueueTest.php index 56fd07c291..82d06eee60 100644 --- a/tests/Queue/QueueDeferredQueueTest.php +++ b/tests/Queue/QueueDeferredQueueTest.php @@ -30,7 +30,9 @@ use Hypervel\Queue\Jobs\SyncJob; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use Throwable; @@ -38,6 +40,8 @@ class QueueDeferredQueueTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; public function testPushShouldDefer(): void @@ -131,12 +135,12 @@ public function testFailedJobGetsHandledWhenAnExceptionIsThrown(): void }); $deferred->setConnectionName('deferred'); $container = $this->getContainer(); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobProcessing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobExceptionOccurred::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobFailed::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobAttempted::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->times(4); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobProcessing::class)->returns(true); + $events->expects('hasListeners')->with(JobExceptionOccurred::class)->returns(true); + $events->expects('hasListeners')->with(JobFailed::class)->returns(true); + $events->expects('hasListeners')->with(JobAttempted::class)->returns(true); + $events->expects('dispatch')->times(4); $container->instance('events', $events); $container->instance(Dispatcher::class, $events); $deferred->setContainer($container); @@ -159,11 +163,11 @@ public function testCancellationDoesNotInvokeDeferredExceptionCallback(): void }); $deferred->setConnectionName('deferred'); $container = $this->getContainer(); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobProcessing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobAttempted::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->once()->with(m::type(JobProcessing::class)); - $events->shouldReceive('dispatch')->once()->with(m::on( + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobProcessing::class)->returns(true); + $events->expects('hasListeners')->with(JobAttempted::class)->returns(true); + $events->expects('dispatch')->with(Argument::type(JobProcessing::class)); + $events->expects('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof JobAttempted && $event->canceled, )); $container->instance('events', $events); @@ -188,9 +192,9 @@ public function testItAddsATransactionCallbackForAfterCommitJobs(): void $deferred = new DeferredQueue; $deferred->setConnectionName('deferred'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback')->once()->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); $container->instance('db.transactions', $transactionManager); $deferred->setContainer($container); @@ -202,9 +206,9 @@ public function testItAddsATransactionCallbackForInterfaceBasedAfterCommitJobs() $deferred = new DeferredQueue; $deferred->setConnectionName('deferred'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback')->once()->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); $container->instance('db.transactions', $transactionManager); $deferred->setContainer($container); @@ -216,10 +220,10 @@ public function testItAddsATransactionCallbackForAfterCommitUniqueJobs(): void $deferred = new DeferredQueue; $deferred->setConnectionName('deferred'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback')->once()->andReturn(null); - $transactionManager->shouldReceive('addCallbackForRollback')->once()->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new DeferredQueueAfterCommitUniqueJob; @@ -234,10 +238,10 @@ public function testItAddsATransactionRollbackCallbackForAfterCommitDebouncedJob $deferred = new DeferredQueue; $deferred->setConnectionName('deferred'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback')->once()->andReturn(null); - $transactionManager->shouldReceive('addCallbackForRollback')->once()->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new DeferredQueueAfterCommitDebouncedJob; @@ -252,10 +256,10 @@ public function testItAddsATransactionCallbackForInterfaceBasedAfterCommitUnique $deferred = new DeferredQueue; $deferred->setConnectionName('deferred'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback')->once()->andReturn(null); - $transactionManager->shouldReceive('addCallbackForRollback')->once()->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new DeferredQueueAfterCommitInterfaceUniqueJob; @@ -267,11 +271,10 @@ public function testItAddsATransactionCallbackForInterfaceBasedAfterCommitUnique public function testLaterSchedulesJobWithDelay(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after') - ->once() - ->with(5.0, m::type('Closure')) - ->andReturnUsing(function ($delay, $callback) { + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after') + ->with(5.0, Argument::type('Closure')) + ->resolves(function ($delay, $callback) { $callback(); return 1; }); @@ -292,11 +295,10 @@ public function testLaterWithDateInterval(): void { CarbonImmutable::setTestNow('2024-01-01 12:00:00'); - $timer = m::mock(Timer::class); - $timer->shouldReceive('after') - ->once() - ->with(10.0, m::type('Closure')) - ->andReturnUsing(function ($delay, $callback) { + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after') + ->with(10.0, Argument::type('Closure')) + ->resolves(function ($delay, $callback) { $callback(); return 1; }); @@ -319,11 +321,10 @@ public function testLaterWithDateTime(): void { CarbonImmutable::setTestNow('2024-01-01 12:00:00'); - $timer = m::mock(Timer::class); - $timer->shouldReceive('after') - ->once() - ->with(15.0, m::type('Closure')) - ->andReturnUsing(function ($delay, $callback) { + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after') + ->with(15.0, Argument::type('Closure')) + ->resolves(function ($delay, $callback) { $callback(); return 1; }); @@ -344,18 +345,17 @@ public function testLaterWithDateTime(): void public function testLaterAddsTransactionCallbackForAfterCommitJobs(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(5.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(5.0, Argument::type('Closure'))->returns(1); $deferred = new DeferredQueue(timer: $timer); $deferred->setConnectionName('deferred'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback') - ->once() - ->andReturnUsing(function ($callback) { + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback') + ->resolves(function ($callback) { $callback(); return null; }); @@ -367,18 +367,17 @@ public function testLaterAddsTransactionCallbackForAfterCommitJobs(): void public function testLaterAddsTransactionCallbackForInterfaceBasedAfterCommitJobs(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(5.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(5.0, Argument::type('Closure'))->returns(1); $deferred = new DeferredQueue(timer: $timer); $deferred->setConnectionName('deferred'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback') - ->once() - ->andReturnUsing(function ($callback) { + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback') + ->resolves(function ($callback) { $callback(); return null; }); @@ -390,22 +389,21 @@ public function testLaterAddsTransactionCallbackForInterfaceBasedAfterCommitJobs public function testLaterAddsTransactionCallbackForAfterCommitUniqueJobs(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(5.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(5.0, Argument::type('Closure'))->returns(1); $deferred = new DeferredQueue(timer: $timer); $deferred->setConnectionName('deferred'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback') - ->once() - ->andReturnUsing(function ($callback) { + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback') + ->resolves(function ($callback) { $callback(); return null; }); - $transactionManager->shouldReceive('addCallbackForRollback')->once()->andReturn(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new DeferredQueueAfterCommitUniqueJob; DispatchLockContext::registerUnique($job, $container->make(Cache::class), null, 'unique-key', 'owner'); @@ -416,22 +414,21 @@ public function testLaterAddsTransactionCallbackForAfterCommitUniqueJobs(): void public function testLaterAddsTransactionRollbackCallbackForAfterCommitDebouncedJobs(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(5.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(5.0, Argument::type('Closure'))->returns(1); $deferred = new DeferredQueue(timer: $timer); $deferred->setConnectionName('deferred'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback') - ->once() - ->andReturnUsing(function ($callback) { + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback') + ->resolves(function ($callback) { $callback(); return null; }); - $transactionManager->shouldReceive('addCallbackForRollback')->once()->andReturn(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new DeferredQueueAfterCommitDebouncedJob; DispatchLockContext::registerDebounce($job, $container->make(Cache::class), 'debounce-key', 'owner'); @@ -442,22 +439,21 @@ public function testLaterAddsTransactionRollbackCallbackForAfterCommitDebouncedJ public function testLaterAddsTransactionCallbackForInterfaceBasedAfterCommitUniqueJobs(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(5.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(5.0, Argument::type('Closure'))->returns(1); $deferred = new DeferredQueue(timer: $timer); $deferred->setConnectionName('deferred'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback') - ->once() - ->andReturnUsing(function ($callback) { + $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict(); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback') + ->resolves(function ($callback) { $callback(); return null; }); - $transactionManager->shouldReceive('addCallbackForRollback')->once()->andReturn(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new DeferredQueueAfterCommitInterfaceUniqueJob; DispatchLockContext::registerUnique($job, $container->make(Cache::class), null, 'unique-key', 'owner'); @@ -468,8 +464,8 @@ public function testLaterAddsTransactionCallbackForInterfaceBasedAfterCommitUniq public function testLaterClampsNegativeIntegerDelay(): void { - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(0.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(0.0, Argument::type('Closure'))->returns(1); $deferred = new DeferredQueue(timer: $timer); $deferred->setConnectionName('deferred'); @@ -482,8 +478,8 @@ public function testLaterClampsPastDateTimeInterface(): void { CarbonImmutable::setTestNow('2024-01-01 12:00:00'); - $timer = m::mock(Timer::class); - $timer->shouldReceive('after')->once()->with(0.0, m::type('Closure'))->andReturn(1); + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after')->with(0.0, Argument::type('Closure'))->returns(1); $deferred = new DeferredQueue(timer: $timer); $deferred->setConnectionName('deferred'); @@ -500,11 +496,10 @@ public function testLaterFailedJobGetsHandledWhenAnExceptionIsThrown(): void $result = null; - $timer = m::mock(Timer::class); - $timer->shouldReceive('after') - ->once() - ->with(5.0, m::type('Closure')) - ->andReturnUsing(function ($delay, $callback) { + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after') + ->with(5.0, Argument::type('Closure')) + ->resolves(function ($delay, $callback) { $callback(); return 1; }); @@ -515,12 +510,12 @@ public function testLaterFailedJobGetsHandledWhenAnExceptionIsThrown(): void }); $deferred->setConnectionName('deferred'); $container = $this->getContainer(); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobProcessing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobExceptionOccurred::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobFailed::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->once()->with(JobAttempted::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->times(4); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobProcessing::class)->returns(true); + $events->expects('hasListeners')->with(JobExceptionOccurred::class)->returns(true); + $events->expects('hasListeners')->with(JobFailed::class)->returns(true); + $events->expects('hasListeners')->with(JobAttempted::class)->returns(true); + $events->expects('dispatch')->times(4); $container->instance('events', $events); $container->instance(Dispatcher::class, $events); $deferred->setContainer($container); @@ -543,11 +538,10 @@ public function testLaterDoesNotExecuteJobWhenWorkerIsClosing(): void $this->assertNotNull($metadata); $callback = null; - $timer = m::mock(Timer::class); - $timer->shouldReceive('after') - ->once() - ->with(5.0, m::type('Closure')) - ->andReturnUsing(function ($delay, $scheduledCallback) use (&$callback) { + $timer = Double::for(Timer::class)->strict(); + $timer->expects('after') + ->with(5.0, Argument::type('Closure')) + ->resolves(function ($delay, $scheduledCallback) use (&$callback) { $callback = $scheduledCallback; return 1; @@ -575,7 +569,7 @@ public function testLaterDoesNotExecuteJobWhenWorkerIsClosing(): void protected function getContainer(): Container { $container = new Container; - $container->instance(Cache::class, m::mock(Cache::class)); + $container->instance(Cache::class, Double::for(Cache::class)->strict()); $container->instance(Dispatcher::class, new EventsDispatcher($container)); Container::setInstance($container); diff --git a/tests/Queue/QueueFlushFailedCommandTest.php b/tests/Queue/QueueFlushFailedCommandTest.php index a19a6c4f39..2ea700ef2e 100644 --- a/tests/Queue/QueueFlushFailedCommandTest.php +++ b/tests/Queue/QueueFlushFailedCommandTest.php @@ -8,19 +8,22 @@ use Hypervel\Queue\Console\FlushFailedCommand; use Hypervel\Queue\Failed\FailedJobProviderInterface; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; class QueueFlushFailedCommandTest extends TestCase { + use VerifiesDoubles; + public function testProhibitedCommandDoesNotFlushFailedJobs(): void { FlushFailedCommand::prohibit(); - $provider = m::mock(FailedJobProviderInterface::class); - $provider->shouldNotReceive('flush'); + $provider = Double::for(FailedJobProviderInterface::class)->strict(); + $provider->expects('flush')->never(); $app = new Application; $app->instance(FailedJobProviderInterface::class, $provider); $command = new FlushFailedCommand; @@ -34,7 +37,7 @@ public function testProhibitedCommandDoesNotFlushFailedJobs(): void #[DataProvider('retentionOptions')] public function testFlushesFailedJobs(array $options, ?int $hours, ?string $queue, string $message): void { - $provider = m::mock(FailedJobProviderInterface::class); + $provider = Double::for(FailedJobProviderInterface::class)->strict(); $provider->expects('flush')->with($hours, $queue); $app = new Application; $app->instance(FailedJobProviderInterface::class, $provider); diff --git a/tests/Queue/QueueJobTest.php b/tests/Queue/QueueJobTest.php index cb44a8c1bb..90866ac55e 100644 --- a/tests/Queue/QueueJobTest.php +++ b/tests/Queue/QueueJobTest.php @@ -20,7 +20,9 @@ use Hypervel\Queue\SyncQueue; use Hypervel\Queue\TimeoutExceededException; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -29,6 +31,8 @@ class QueueJobTest extends TestCase { + use VerifiesDoubles; + public function testValidPayloadIsDecodedOnceAcrossAccessors(): void { $job = new QueueJobPayloadStub(json_encode([ @@ -96,16 +100,15 @@ public function testInvalidPayloadCanStillBeFailedAndDeleted(): void { $exception = new RuntimeException('Queue payload failed.'); $job = new QueueJobPayloadStub('{invalid'); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobFailed::class)->andReturnTrue(); - $events->shouldReceive('dispatch') - ->once() - ->withArgs(fn (JobFailed $event) => $event->job === $job && $event->exception === $exception); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobFailed::class)->returns(true); + $events->expects('dispatch') + ->with(Argument::satisfies(fn (JobFailed $event) => $event->job === $job && $event->exception === $exception)); - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with(Dispatcher::class)->andReturn($events); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(Dispatcher::class)->returns($events); - $job->setContainer($container); + $job->setContainer($container->instance()); $job->setConnectionName('redis'); $job->fail($exception); @@ -118,14 +121,14 @@ public function testFailedEventIsNotDispatchedWithoutListeners(): void { $exception = new RuntimeException('Queue payload failed.'); $job = new QueueJobPayloadStub('{invalid'); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobFailed::class)->andReturnFalse(); - $events->shouldReceive('dispatch')->never(); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobFailed::class)->returns(false); + $events->expects('dispatch')->never(); - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with(Dispatcher::class)->andReturn($events); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(Dispatcher::class)->returns($events); - $job->setContainer($container); + $job->setContainer($container->instance()); $job->setConnectionName('redis'); $job->fail($exception); @@ -143,20 +146,18 @@ public function testInvalidPayloadExceptionFromUserFailedHookStillPropagates(): 'job' => QueueJobFailedHookStub::class, 'data' => ['value' => true], ], JSON_THROW_ON_ERROR)); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobFailed::class)->andReturnTrue(); - $events->shouldReceive('dispatch') - ->once() - ->withArgs(fn (JobFailed $event) => $event->job === $job && $event->exception === $failure); - - $container = m::mock(Container::class); - $container->shouldReceive('make') - ->once() + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobFailed::class)->returns(true); + $events->expects('dispatch') + ->with(Argument::satisfies(fn (JobFailed $event) => $event->job === $job && $event->exception === $failure)); + + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make') ->with(QueueJobFailedHookStub::class) - ->andReturn(new QueueJobFailedHookStub($hookException)); - $container->shouldReceive('make')->once()->with(Dispatcher::class)->andReturn($events); + ->returns(new QueueJobFailedHookStub($hookException)); + $container->expects('make')->with(Dispatcher::class)->returns($events); - $job->setContainer($container); + $job->setContainer($container->instance()); $job->setConnectionName('redis'); try { @@ -185,10 +186,9 @@ public function testBatchRollbackCancellationEscapesBeforeFurtherFailureCleanup( $timeout = TimeoutExceededException::forJob($job); $gate = $this->armCurrentCoroutineCancellation(); $cleanupException = new RuntimeException('Rollback cleanup failed.'); - $batchRepository = m::mock(BatchRepository::class); - $batchRepository->shouldReceive('rollBack') - ->once() - ->andReturnUsing(static function () use ($gate, $cleanupThrows, $cleanupException): never { + $batchRepository = Double::for(BatchRepository::class)->strict(); + $batchRepository->expects('rollBack') + ->resolves(static function () use ($gate, $cleanupThrows, $cleanupException): never { try { $gate->push(true); @@ -200,9 +200,9 @@ public function testBatchRollbackCancellationEscapesBeforeFurtherFailureCleanup( } } }); - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with(BatchRepository::class)->andReturn($batchRepository); - $job->setContainer($container); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(BatchRepository::class)->returns($batchRepository); + $job->setContainer($container->instance()); $job->setConnectionName('redis'); try { @@ -232,13 +232,12 @@ public function testFailedHookCancellationSkipsTheFailedEvent(bool $cleanupThrow ], JSON_THROW_ON_ERROR)); $cleanupException = $cleanupThrows ? new RuntimeException('Failed-hook cleanup failed.') : null; $handler = new QueueJobCancelingFailedHookStub($this->armCurrentCoroutineCancellation(), $cleanupException); - $container = m::mock(Container::class); - $container->shouldReceive('make') - ->once() + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make') ->with(QueueJobCancelingFailedHookStub::class) - ->andReturn($handler); - $container->shouldNotReceive('make')->with(Dispatcher::class); - $job->setContainer($container); + ->returns($handler); + $container->expects('make')->never()->with(Dispatcher::class); + $job->setContainer($container->instance()); $job->setConnectionName('redis'); try { @@ -269,10 +268,9 @@ public function testBatchRollbackFailurePreservesTimeoutForFailedJobCleanup(?str ], JSON_THROW_ON_ERROR)); $timeout = TimeoutExceededException::forJob($job); - $batchRepository = m::mock(BatchRepository::class); - $batchRepository->shouldReceive('rollBack') - ->once() - ->andThrow(new RuntimeException('Batch rollback failed.')); + $batchRepository = Double::for(BatchRepository::class)->strict(); + $batchRepository->expects('rollBack') + ->throws(new RuntimeException('Batch rollback failed.')); $config = new ConfigRepository([ 'queue' => [ @@ -282,29 +280,27 @@ public function testBatchRollbackFailurePreservesTimeoutForFailedJobCleanup(?str ], ], ]); - $connection = m::mock(Connection::class); - $connection->shouldReceive('rollBack')->once()->with(0); - $database = m::mock(ConnectionResolverInterface::class); - $database->shouldReceive('connection')->once()->with($databaseName)->andReturn($connection); - - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobFailed::class)->andReturnTrue(); - $events->shouldReceive('dispatch') - ->once() - ->withArgs(fn (JobFailed $event) => $event->job === $job && $event->exception === $timeout); - - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with(BatchRepository::class)->andReturn($batchRepository); - $container->shouldReceive('make')->with('config')->andReturn($config); - $container->shouldReceive('bound')->once()->with('db')->andReturnTrue(); - $container->shouldReceive('make')->once()->with('db')->andReturn($database); - $container->shouldReceive('make') - ->once() + $connection = Double::for(Connection::class)->strict(); + $connection->expects('rollBack')->with(0); + $database = Double::for(ConnectionResolverInterface::class)->strict(); + $database->expects('connection')->with($databaseName)->returns($connection); + + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobFailed::class)->returns(true); + $events->expects('dispatch') + ->with(Argument::satisfies(fn (JobFailed $event) => $event->job === $job && $event->exception === $timeout)); + + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(BatchRepository::class)->returns($batchRepository); + $container->allows('make')->with('config')->returns($config); + $container->expects('bound')->with('db')->returns(true); + $container->expects('make')->with('db')->returns($database); + $container->expects('make') ->with(QueueJobTimeoutBatchStub::class) - ->andReturn(new QueueJobTimeoutBatchStub); - $container->shouldReceive('make')->once()->with(Dispatcher::class)->andReturn($events); + ->returns(new QueueJobTimeoutBatchStub); + $container->expects('make')->with(Dispatcher::class)->returns($events); - $job->setContainer($container); + $job->setContainer($container->instance()); $job->setConnectionName('redis'); $job->fail($timeout); @@ -334,17 +330,17 @@ public function payloadFor(string $job, array $data): string ['command' => 'backup:run', 'commandName' => 'backup:run'], )); $timeout = TimeoutExceededException::forJob($job); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(JobFailed::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->once() - ->withArgs(fn (JobFailed $event): bool => $event->job === $job && $event->exception === $timeout); - - $container = m::mock(Container::class); - $container->shouldNotReceive('make')->with(BatchRepository::class); - $container->shouldReceive('make')->with('config')->andReturn(new ConfigRepository(['queue' => ['failed' => ['driver' => null]]])); - $container->shouldReceive('make')->once()->with(QueueJobTimeoutBatchStub::class)->andReturn(new QueueJobTimeoutBatchStub); - $container->shouldReceive('make')->once()->with(Dispatcher::class)->andReturn($events); - $job->setContainer($container); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('hasListeners')->with(JobFailed::class)->returns(true); + $events->expects('dispatch') + ->with(Argument::satisfies(fn (JobFailed $event): bool => $event->job === $job && $event->exception === $timeout)); + + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->never()->with(BatchRepository::class); + $container->allows('make')->with('config')->returns(new ConfigRepository(['queue' => ['failed' => ['driver' => null]]])); + $container->expects('make')->with(QueueJobTimeoutBatchStub::class)->returns(new QueueJobTimeoutBatchStub); + $container->expects('make')->with(Dispatcher::class)->returns($events); + $job->setContainer($container->instance()); $job->setConnectionName('redis'); $job->fail($timeout); diff --git a/tests/Queue/QueueManagerTest.php b/tests/Queue/QueueManagerTest.php index 07b0d13b50..92cfb1131b 100644 --- a/tests/Queue/QueueManagerTest.php +++ b/tests/Queue/QueueManagerTest.php @@ -29,7 +29,8 @@ use Hypervel\Queue\SyncQueue; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionProperty; use RuntimeException; @@ -37,6 +38,8 @@ class QueueManagerTest extends TestCase { + use VerifiesDoubles; + public function testIntegerEnumConnectionNamesAreNormalizedWithoutTreatingZeroAsAbsent(): void { $container = $this->getContainer(); @@ -45,12 +48,12 @@ public function testIntegerEnumConnectionNamesAreNormalizedWithoutTreatingZeroAs $config->set('queue.connections.0', ['driver' => 'sync']); $manager = new QueueManager($container); - $connector = m::mock(ConnectorInterface::class); - $queue = m::mock(Queue::class); - $queue->shouldReceive('setConnectionName')->once()->with('0')->andReturnSelf(); - $queue->shouldReceive('setConfig')->once()->andReturnSelf(); - $queue->shouldReceive('setContainer')->once()->with($container)->andReturnSelf(); - $connector->shouldReceive('connect')->once()->with(['driver' => 'sync'])->andReturn($queue); + $connector = Double::for(ConnectorInterface::class)->strict(); + $queue = Double::for(NullQueue::class)->strict(); + $queue->expects('setConnectionName')->with('0'); + $queue->expects('setConfig'); + $queue->expects('setContainer')->with($container); + $connector->expects('connect')->with(['driver' => 'sync'])->returns($queue); $manager->addConnector('sync', fn () => $connector); $this->assertSame('sync', $manager->getName()); @@ -293,7 +296,7 @@ public function testAddPoolableConnector(): void $config->set('queue.connections.foo', ['driver' => 'bar']); $manager = new QueueManager($container); - $connector = m::mock(ConnectorInterface::class); + $connector = Double::for(ConnectorInterface::class)->strict(); $manager->addConnector('bar', function () use ($connector) { return $connector; }); @@ -356,22 +359,22 @@ public function testPoolableConnectionsConvergeByConstructionConfigAndApplyTheir $manager = new QueueManager($container); $manager->addPoolableDriver('custom'); - $connector = m::mock(ConnectorInterface::class); - $queue = m::mock(NullQueue::class)->makePartial(); + $connector = Double::for(ConnectorInterface::class)->strict(); + $queue = Double::for(new NullQueue)->passthru(); $manager->addConnector('custom', fn () => $connector); - $connector->shouldReceive('connect')->once()->with([ + $connector->expects('connect')->with([ 'driver' => 'custom', 'queue' => 'shared', - ])->andReturn($queue); - $queue->shouldReceive('setContainer')->once()->with($container)->andReturnSelf(); - $queue->shouldReceive('setConfig')->once()->with([ + ])->returns($queue); + $queue->expects('setContainer')->with($container); + $queue->expects('setConfig')->with([ 'driver' => 'custom', 'queue' => 'shared', - ])->andReturnSelf(); - $queue->shouldReceive('setConnectionName')->once()->with('foo')->andReturnSelf(); - $queue->shouldReceive('setConnectionName')->once()->with('bar')->andReturnSelf(); - $queue->shouldReceive('size')->twice()->withNoArgs()->andReturn(1); + ]); + $queue->expects('setConnectionName')->with('foo'); + $queue->expects('setConnectionName')->with('bar'); + $queue->expects('size')->times(2)->with()->returns(1); $foo = $manager->connection('foo'); $bar = $manager->connection('bar'); @@ -395,21 +398,21 @@ public function testPurgeInvalidatesCachedAndUncachedQueuePools(): void $manager = new QueueManager($container); $manager->addPoolableDriver('custom'); - $connector = m::mock(ConnectorInterface::class); - $queue = m::mock(NullQueue::class)->makePartial(); + $connector = Double::for(ConnectorInterface::class)->strict(); + $queue = Double::for(new NullQueue)->passthru(); $manager->addConnector('custom', fn () => $connector); - $connector->shouldReceive('connect')->twice()->with([ + $connector->expects('connect')->times(2)->with([ 'driver' => 'custom', 'queue' => 'shared', - ])->andReturn($queue); - $queue->shouldReceive('setContainer')->twice()->with($container)->andReturnSelf(); - $queue->shouldReceive('setConfig')->twice()->with([ + ])->returns($queue); + $queue->expects('setContainer')->times(2)->with($container); + $queue->expects('setConfig')->times(2)->with([ 'driver' => 'custom', 'queue' => 'shared', - ])->andReturnSelf(); - $queue->shouldReceive('setConnectionName')->twice()->with('foo')->andReturnSelf(); - $queue->shouldReceive('size')->twice()->withNoArgs()->andReturn(1); + ]); + $queue->expects('setConnectionName')->times(2)->with('foo'); + $queue->expects('size')->times(2)->with()->returns(1); $connection = $manager->connection('foo'); $this->assertInstanceOf(QueuePoolProxy::class, $connection); @@ -439,22 +442,22 @@ public function testConvergedConnectionsApplyTheirLogicalNameToPoppedJobs(): voi $manager = new QueueManager($container); $manager->addPoolableDriver('custom'); - $connector = m::mock(ConnectorInterface::class); - $queue = m::mock(NullQueue::class)->makePartial(); + $connector = Double::for(ConnectorInterface::class)->strict(); + $queue = Double::for(new NullQueue)->passthru(); $manager->addConnector('custom', fn () => $connector); $currentName = ''; - $connector->shouldReceive('connect')->once()->with($connectionConfig)->andReturn($queue); - $queue->shouldReceive('setContainer')->once()->with($container)->andReturnSelf(); - $queue->shouldReceive('setConfig')->once()->with($connectionConfig)->andReturnSelf(); - $queue->shouldReceive('setConnectionName')->twice() - ->andReturnUsing(function (string $name) use (&$currentName, $queue): Queue { + $connector->expects('connect')->with($connectionConfig)->returns($queue); + $queue->expects('setContainer')->with($container); + $queue->expects('setConfig')->with($connectionConfig); + $queue->expects('setConnectionName')->times(2) + ->resolves(function (string $name) use (&$currentName, $queue): Queue { $currentName = $name; return $queue; }); - $queue->shouldReceive('pop')->twice()->with(null) - ->andReturnUsing(function () use ($container, &$currentName): QueueManagerTestJob { + $queue->expects('pop')->times(2)->with(null) + ->resolves(function () use ($container, &$currentName): QueueManagerTestJob { return new QueueManagerTestJob($container, $currentName); }); @@ -484,16 +487,16 @@ public function testSetApplicationEvictsPooledConnectionsAndRebindsTheirFactory( $manager = new QueueManager($oldContainer); $manager->addPoolableDriver('custom'); - $connector = m::mock(ConnectorInterface::class); - $queue = m::mock(NullQueue::class)->makePartial(); + $connector = Double::for(ConnectorInterface::class)->strict(); + $queue = Double::for(new NullQueue)->passthru(); $manager->addConnector('custom', fn () => $connector); - $connector->shouldReceive('connect')->twice()->andReturn($queue); - $queue->shouldReceive('setContainer')->once()->with($oldContainer)->andReturnSelf(); - $queue->shouldReceive('setContainer')->once()->with($newContainer)->andReturnSelf(); - $queue->shouldReceive('setConfig')->twice()->andReturnSelf(); - $queue->shouldReceive('setConnectionName')->twice()->with('foo')->andReturnSelf(); - $queue->shouldReceive('size')->twice()->withNoArgs()->andReturn(1); + $connector->expects('connect')->times(2)->returns($queue); + $queue->expects('setContainer')->with($oldContainer); + $queue->expects('setContainer')->with($newContainer); + $queue->expects('setConfig')->times(2); + $queue->expects('setConnectionName')->times(2)->with('foo'); + $queue->expects('size')->times(2)->with()->returns(1); $oldConnection = $manager->connection('foo'); $this->assertInstanceOf(QueuePoolProxy::class, $oldConnection); @@ -524,15 +527,15 @@ public function testSetApplicationUpdatesCachedDirectQueueInPlace(): void $newContainer = $this->getContainer(); $manager = new QueueManager($oldContainer); - $connector = m::mock(ConnectorInterface::class); - $queue = m::mock(Queue::class); + $connector = Double::for(ConnectorInterface::class)->strict(); + $queue = Double::for(NullQueue::class)->strict(); $manager->addConnector('sync', fn () => $connector); - $connector->shouldReceive('connect')->once()->with(['driver' => 'sync'])->andReturn($queue); - $queue->shouldReceive('setContainer')->once()->with($oldContainer)->andReturnSelf(); - $queue->shouldReceive('setConfig')->once()->with(['driver' => 'sync'])->andReturnSelf(); - $queue->shouldReceive('setConnectionName')->once()->with('sync')->andReturnSelf(); - $queue->shouldReceive('setContainer')->once()->with($newContainer)->andReturnSelf(); + $connector->expects('connect')->with(['driver' => 'sync'])->returns($queue); + $queue->expects('setContainer')->with($oldContainer); + $queue->expects('setConfig')->with(['driver' => 'sync']); + $queue->expects('setConnectionName')->with('sync'); + $queue->expects('setContainer')->with($newContainer); $this->assertSame($queue, $manager->connection('sync')); $this->assertSame($manager, $manager->setApplication($newContainer)); diff --git a/tests/Queue/QueueNullQueueTest.php b/tests/Queue/QueueNullQueueTest.php index d124c0cf68..b5be67ff7b 100644 --- a/tests/Queue/QueueNullQueueTest.php +++ b/tests/Queue/QueueNullQueueTest.php @@ -18,10 +18,13 @@ use Hypervel\Queue\NullQueue; use Hypervel\Queue\QueueRoutes; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class QueueNullQueueTest extends TestCase { + use VerifiesDoubles; + public function testCreationTimeOfOldestPendingJobReturnsNull(): void { $queue = new NullQueue; @@ -49,9 +52,9 @@ public function testPendingDispatchReleasesUniqueLockWhenNullQueueAcceptsNothing $queue = new NullQueue; $queue->setContainer($container); - $routes = m::mock(QueueRoutes::class); - $routes->shouldReceive('getConnection')->once()->andReturnNull(); - $routes->shouldReceive('getQueue')->once()->andReturnNull(); + $routes = Double::for(QueueRoutes::class)->strict(); + $routes->expects('getConnection')->returns(null); + $routes->expects('getQueue')->returns(null); $container->instance(CacheContract::class, $cache); $container->instance('queue.routes', $routes); diff --git a/tests/Queue/QueuePoolProxyTest.php b/tests/Queue/QueuePoolProxyTest.php index 87ebac8682..2885c4a77a 100644 --- a/tests/Queue/QueuePoolProxyTest.php +++ b/tests/Queue/QueuePoolProxyTest.php @@ -4,10 +4,9 @@ namespace Hypervel\Tests\Queue; +use Aws\MockHandler; use Aws\Sqs\SqsClient; use Closure; -use DateInterval; -use DateTimeInterface; use Exception; use Hypervel\Container\Container; use Hypervel\Contracts\Container\Container as ContainerContract; @@ -15,7 +14,6 @@ use Hypervel\Contracts\Queue\ClearableQueue; use Hypervel\Contracts\Queue\IndexAwareQueue; use Hypervel\Contracts\Queue\Job as JobContract; -use Hypervel\Contracts\Queue\Queue as QueueContract; use Hypervel\ObjectPool\PoolDefinition; use Hypervel\ObjectPool\PoolManager; use Hypervel\ObjectPool\PoolOptions; @@ -23,12 +21,14 @@ use Hypervel\Queue\Jobs\BeanstalkdJob; use Hypervel\Queue\Jobs\Job; use Hypervel\Queue\Jobs\SqsJob; +use Hypervel\Queue\NullQueue; use Hypervel\Queue\Queue as BaseQueue; use Hypervel\Queue\QueuePoolProxy; use Hypervel\Support\Collection; use Hypervel\Tests\Queue\Fixtures\IntegerQueueName; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Pheanstalk\Contract\JobIdInterface; use Pheanstalk\Contract\PheanstalkManagerInterface; use Pheanstalk\Contract\PheanstalkPublisherInterface; @@ -42,6 +42,8 @@ class QueuePoolProxyTest extends TestCase { + use VerifiesDoubles; + /** @var list */ private array $poolManagers = []; @@ -54,31 +56,31 @@ protected function tearDownInCoroutine(): void public function testEnumeratedSynchronousSurfaceUsesBorrowScopedInvocation(): void { - $queue = m::mock(QueuePoolProxyTestQueue::class)->makePartial(); + $queue = Double::for(new QueuePoolProxyTestQueue)->passthru(); [$proxy] = $this->proxy(fn () => $queue); $proxy->setConnectionName('logical'); - $queue->shouldReceive('size')->once()->with('queue')->andReturn(1); - $queue->shouldReceive('pendingSize')->once()->with('queue')->andReturn(2); - $queue->shouldReceive('delayedSize')->once()->with('queue')->andReturn(3); - $queue->shouldReceive('reservedSize')->once()->with('queue')->andReturn(4); - $queue->shouldReceive('totalSize')->once()->withNoArgs()->andReturn(18); - $queue->shouldReceive('totalPendingSize')->once()->withNoArgs()->andReturn(5); - $queue->shouldReceive('totalDelayedSize')->once()->withNoArgs()->andReturn(6); - $queue->shouldReceive('totalReservedSize')->once()->withNoArgs()->andReturn(7); - $queue->shouldReceive('pendingJobs')->once()->with('queue')->andReturn($pending = new Collection(['pending'])); - $queue->shouldReceive('delayedJobs')->once()->with('queue')->andReturn($delayed = new Collection(['delayed'])); - $queue->shouldReceive('reservedJobs')->once()->with('queue')->andReturn($reserved = new Collection(['reserved'])); - $queue->shouldReceive('allPendingJobs')->once()->andReturn($allPending = new Collection(['all-pending'])); - $queue->shouldReceive('allDelayedJobs')->once()->andReturn($allDelayed = new Collection(['all-delayed'])); - $queue->shouldReceive('allReservedJobs')->once()->andReturn($allReserved = new Collection(['all-reserved'])); - $queue->shouldReceive('creationTimeOfOldestPendingJob')->once()->with('queue')->andReturn(5); - $queue->shouldReceive('push')->once()->with('job', 'data', 'queue')->andReturn('pushed'); - $queue->shouldReceive('pushOn')->once()->with('queue', 'job', 'data')->andReturn('pushed-on'); - $queue->shouldReceive('pushRaw')->once()->with('payload', 'queue', ['option' => true])->andReturn('raw'); - $queue->shouldReceive('later')->once()->with(10, 'job', 'data', 'queue')->andReturn('later'); - $queue->shouldReceive('laterOn')->once()->with('queue', 10, 'job', 'data')->andReturn('later-on'); - $queue->shouldReceive('bulk')->once()->with(['job'], 'data', 'queue')->andReturn('bulk'); + $queue->expects('size')->with('queue')->returns(1); + $queue->expects('pendingSize')->with('queue')->returns(2); + $queue->expects('delayedSize')->with('queue')->returns(3); + $queue->expects('reservedSize')->with('queue')->returns(4); + $queue->expects('totalSize')->with()->returns(18); + $queue->expects('totalPendingSize')->with()->returns(5); + $queue->expects('totalDelayedSize')->with()->returns(6); + $queue->expects('totalReservedSize')->with()->returns(7); + $queue->expects('pendingJobs')->with('queue')->returns($pending = new Collection(['pending'])); + $queue->expects('delayedJobs')->with('queue')->returns($delayed = new Collection(['delayed'])); + $queue->expects('reservedJobs')->with('queue')->returns($reserved = new Collection(['reserved'])); + $queue->expects('allPendingJobs')->returns($allPending = new Collection(['all-pending'])); + $queue->expects('allDelayedJobs')->returns($allDelayed = new Collection(['all-delayed'])); + $queue->expects('allReservedJobs')->returns($allReserved = new Collection(['all-reserved'])); + $queue->expects('creationTimeOfOldestPendingJob')->with('queue')->returns(5); + $queue->expects('push')->with('job', 'data', 'queue')->returns('pushed'); + $queue->expects('pushOn')->with('queue', 'job', 'data')->returns('pushed-on'); + $queue->expects('pushRaw')->with('payload', 'queue', ['option' => true])->returns('raw'); + $queue->expects('later')->with(10, 'job', 'data', 'queue')->returns('later'); + $queue->expects('laterOn')->with('queue', 10, 'job', 'data')->returns('later-on'); + $queue->expects('bulk')->with(['job'], 'data', 'queue')->returns('bulk'); $this->assertSame('logical', $proxy->getConnectionName()); $this->assertSame(1, $proxy->size('queue')); @@ -146,7 +148,7 @@ public function testDirectConnectionAccessRejectsNonSqsPoolsBeforeBorrowing(): v public function testPopDoesNotForwardTheQueueIndexToAnOrdinaryConnectionAndPinsItUntilTheJobTerminates(): void { - $job = new QueuePoolProxyTestJob(m::mock(ContainerContract::class)); + $job = new QueuePoolProxyTestJob(Double::for(ContainerContract::class, override: true)->strict()->instance()); $queue = new QueuePoolProxyTestQueue($job); [$proxy, $pools] = $this->proxy(fn () => $queue); $proxy->setConnectionName('logical'); @@ -224,8 +226,8 @@ public function testPopFailureStaysPrimaryWhenReleaseCallbackAlsoFails(): void { $operationException = new Exception('pop failed'); $finalizationException = new Exception('reset failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($finalizationException); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($finalizationException); [$proxy, $pools] = $this->proxy( fn () => new QueuePoolProxyTestQueue(popException: $operationException), function () use ($finalizationException): never { @@ -250,8 +252,8 @@ public function testReleaseCancellationSupersedesAPopFailure(): void { $operationException = new Exception('pop failed'); $releaseCancellation = new CanceledException('release canceled'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); [$proxy, $pools] = $this->proxy( fn () => new QueuePoolProxyTestQueue(popException: $operationException), static function () use ($releaseCancellation): never { @@ -274,8 +276,8 @@ static function () use ($releaseCancellation): never { public function testNonLeaseAwareJobIsRequeuedBeforeFailingClosed(): void { - $job = m::mock(JobContract::class); - $job->shouldReceive('release')->once()->with(0); + $job = Double::for(JobContract::class)->strict(); + $job->expects('release')->with(0); [$proxy, $pools] = $this->proxy(fn () => new QueuePoolProxyTestQueue($job)); try { @@ -293,8 +295,8 @@ public function testNonLeaseAwareJobIsRequeuedBeforeFailingClosed(): void public function testFailedRequeueDiscardsTheBackendAndAReplacementIsCreated(): void { $requeueException = new Exception('requeue failed'); - $job = m::mock(JobContract::class); - $job->shouldReceive('release')->once()->with(0)->andThrow($requeueException); + $job = Double::for(JobContract::class)->strict(); + $job->expects('release')->with(0)->throws($requeueException); $created = 0; [$proxy, $pools] = $this->proxy(function () use (&$created, $job) { ++$created; @@ -320,8 +322,8 @@ public function testFailedRequeueDiscardsTheBackendAndAReplacementIsCreated(): v public function testNonLeaseAwareJobRequeueCancellationIsNotWrapped(): void { $cancellation = new CanceledException('requeue canceled'); - $job = m::mock(JobContract::class); - $job->shouldReceive('release')->once()->with(0)->andThrow($cancellation); + $job = Double::for(JobContract::class)->strict(); + $job->expects('release')->with(0)->throws($cancellation); [$proxy, $pools] = $this->proxy(fn () => new QueuePoolProxyTestQueue($job)); try { @@ -339,10 +341,16 @@ public function testNonLeaseAwareJobRequeueCancellationIsNotWrapped(): void public function testTerminalBackendFailureDiscardsTheQueueAndCreatesAReplacement(): void { $backendException = new Exception('delete failed'); - $client = m::mock(SqsClient::class); - $client->shouldReceive('deleteMessage')->once()->andThrow($backendException); + $handler = new MockHandler; + $handler->append($backendException); + $client = new SqsClient([ + 'region' => 'us-east-1', + 'version' => 'latest', + 'credentials' => false, + 'handler' => $handler, + ]); $job = new SqsJob( - m::mock(ContainerContract::class), + Double::for(ContainerContract::class, override: true)->strict()->instance(), $client, [ 'MessageId' => 'message', @@ -380,7 +388,7 @@ public function testTerminalBackendFailureDiscardsTheQueueAndCreatesAReplacement public function testAbandonedJobReleasesThroughItsLeaseDestructor(): void { - $job = new QueuePoolProxyTestJob(m::mock(ContainerContract::class)); + $job = new QueuePoolProxyTestJob(Double::for(ContainerContract::class, override: true)->strict()->instance()); [$proxy, $pools] = $this->proxy(function () use (&$job) { $queue = new QueuePoolProxyTestQueue($job); $job = null; @@ -405,30 +413,30 @@ public function testBeanstalkAttemptPrimingFailureRecoversTheReservedJob( ): void { $attachmentException = new Exception('stats failed'); $recoveryException = new Exception('release failed'); - $pheanstalk = m::mock(implode(',', [ + $pheanstalk = Double::for( PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class, - ])); - $pheanstalk->shouldReceive('statsJob')->once()->andThrow($attachmentException); + )->strict(); + $pheanstalk->expects('statsJob')->throws($attachmentException); if ($recoveryFails) { - $pheanstalk->shouldReceive('release')->once()->andThrow($recoveryException); + $pheanstalk->expects('release')->throws($recoveryException); } else { - $pheanstalk->shouldReceive('release')->once(); + $pheanstalk->expects('release'); } $job = new BeanstalkdJob( - m::mock(ContainerContract::class), + Double::for(ContainerContract::class, override: true)->strict()->instance(), $pheanstalk, - m::mock(JobIdInterface::class), + Double::for(JobIdInterface::class)->strict(), 'connection', 'jobs', ); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); if ($recoveryFails) { - $handler->shouldReceive('report')->once()->with($recoveryException); + $handler->expects('report')->with($recoveryException); } [$proxy, $pools] = $this->proxy( @@ -466,22 +474,22 @@ public function testAttachmentRecoveryCancellationSupersedesTheAttachmentFailure if ($cleanupThrows) { $recoveryCancellation = new RuntimeException('Recovery cleanup failed.', previous: $recoveryCancellation); } - $pheanstalk = m::mock(implode(',', [ + $pheanstalk = Double::for( PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class, - ])); - $pheanstalk->shouldReceive('statsJob')->once()->andThrow($attachmentException); - $pheanstalk->shouldReceive('release')->once()->andThrow($recoveryCancellation); + )->strict(); + $pheanstalk->expects('statsJob')->throws($attachmentException); + $pheanstalk->expects('release')->throws($recoveryCancellation); $job = new BeanstalkdJob( - m::mock(ContainerContract::class), + Double::for(ContainerContract::class, override: true)->strict()->instance(), $pheanstalk, - m::mock(JobIdInterface::class), + Double::for(JobIdInterface::class)->strict(), 'connection', 'jobs', ); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); [$proxy, $pools] = $this->proxy( fn () => new QueuePoolProxyTestQueue($job), handler: $handler, @@ -507,17 +515,17 @@ public function testAttachmentCancellationDoesNotStartBackendRecovery(bool $clea if ($cleanupThrows) { $attachmentCancellation = new RuntimeException('Attachment cleanup failed.', previous: $attachmentCancellation); } - $pheanstalk = m::mock(implode(',', [ + $pheanstalk = Double::for( PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class, - ])); - $pheanstalk->shouldReceive('statsJob')->once()->andThrow($attachmentCancellation); - $pheanstalk->shouldNotReceive('release'); + )->strict(); + $pheanstalk->expects('statsJob')->throws($attachmentCancellation); + $pheanstalk->expects('release')->never(); $job = new BeanstalkdJob( - m::mock(ContainerContract::class), + Double::for(ContainerContract::class, override: true)->strict()->instance(), $pheanstalk, - m::mock(JobIdInterface::class), + Double::for(JobIdInterface::class)->strict(), 'connection', 'jobs', ); @@ -571,110 +579,23 @@ protected function proxy( } } -class QueuePoolProxyTestQueue extends BaseQueue implements QueueContract +class QueuePoolProxyTestQueue extends NullQueue { /** @var list */ public array $lastPopArguments = []; + /** + * Create a new test queue instance. + */ public function __construct( public ?JobContract $job = null, public ?Throwable $popException = null, ) { } - public function size(UnitEnum|string|null $queue = null): int - { - return 0; - } - - public function pendingSize(UnitEnum|string|null $queue = null): int - { - return 0; - } - - public function delayedSize(UnitEnum|string|null $queue = null): int - { - return 0; - } - - public function reservedSize(UnitEnum|string|null $queue = null): int - { - return 0; - } - - public function pendingJobs(UnitEnum|string|null $queue = null): Collection - { - return new Collection; - } - - public function delayedJobs(UnitEnum|string|null $queue = null): Collection - { - return new Collection; - } - - public function reservedJobs(UnitEnum|string|null $queue = null): Collection - { - return new Collection; - } - - public function allPendingJobs(): Collection - { - return new Collection; - } - - public function allDelayedJobs(): Collection - { - return new Collection; - } - - public function allReservedJobs(): Collection - { - return new Collection; - } - - public function creationTimeOfOldestPendingJob(UnitEnum|string|null $queue = null): ?int - { - return null; - } - - public function push(object|string $job, mixed $data = '', UnitEnum|string|null $queue = null): mixed - { - return null; - } - - public function pushOn(UnitEnum|string|null $queue, object|string $job, mixed $data = ''): mixed - { - return null; - } - - public function pushRaw(string $payload, UnitEnum|string|null $queue = null, array $options = []): mixed - { - return null; - } - - public function later( - DateInterval|DateTimeInterface|int $delay, - object|string $job, - mixed $data = '', - UnitEnum|string|null $queue = null, - ): mixed { - return null; - } - - public function laterOn( - UnitEnum|string|null $queue, - DateInterval|DateTimeInterface|int $delay, - object|string $job, - mixed $data = '', - ): mixed { - return null; - } - - public function bulk(array $jobs, mixed $data = '', UnitEnum|string|null $queue = null): mixed - { - return null; - } - + /** + * Pop the configured job and record the arguments. + */ public function pop(UnitEnum|string|null $queue = null): ?JobContract { $this->lastPopArguments = func_get_args(); @@ -689,18 +610,9 @@ public function pop(UnitEnum|string|null $queue = null): ?JobContract return $job; } - public function getConnectionName(): string - { - return $this->connectionName; - } - - public function setConnectionName(string $name): static - { - $this->connectionName = $name; - - return $this; - } - + /** + * Determine whether an after-commit dispatcher is assigned. + */ public function hasAfterCommitDispatcher(): bool { return $this->afterCommitDispatcher !== null; @@ -712,6 +624,9 @@ class QueuePoolProxyTestIndexAwareQueue extends QueuePoolProxyTestQueue implemen /** @var null|array{null|string|UnitEnum, int} */ public ?array $lastIndexedPop = null; + /** + * Record the queue index and pop the configured job. + */ public function pop(UnitEnum|string|null $queue = null, int $index = 0): ?JobContract { $this->lastIndexedPop = [$queue, $index]; @@ -737,6 +652,9 @@ public function clear(UnitEnum|string|null $queue = null): int class QueuePoolProxyTestJob extends Job { + /** + * Create a new test job instance. + */ public function __construct(ContainerContract $container) { $this->container = $container; @@ -744,27 +662,42 @@ public function __construct(ContainerContract $container) $this->queue = 'queue'; } + /** + * Get the job identifier. + */ public function getJobId(): string { return 'job'; } + /** + * Get the raw job payload. + */ public function getRawBody(): string { return '{"job":"job","data":[]}'; } + /** + * Get the number of job attempts. + */ public function attempts(): int { return 1; } + /** + * Delete the job and release its pool lease. + */ public function delete(): void { parent::delete(); $this->releasePoolLease(); } + /** + * Release the job and its pool lease. + */ public function release(int $delay = 0): void { parent::release($delay); diff --git a/tests/Queue/QueueRedisConnectorTest.php b/tests/Queue/QueueRedisConnectorTest.php index a1f3a55697..7ee160dedb 100644 --- a/tests/Queue/QueueRedisConnectorTest.php +++ b/tests/Queue/QueueRedisConnectorTest.php @@ -9,13 +9,16 @@ use Hypervel\Queue\RedisQueue; use Hypervel\Support\ClassInvoker; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class QueueRedisConnectorTest extends TestCase { + use VerifiesDoubles; + public function testConnectUsesDefaultMigrationBatchSizeWhenOmitted(): void { - $queue = (new RedisConnector(m::mock(Redis::class)))->connect([ + $queue = (new RedisConnector(Double::for(Redis::class)->strict()))->connect([ 'queue' => 'default', ]); @@ -24,7 +27,7 @@ public function testConnectUsesDefaultMigrationBatchSizeWhenOmitted(): void public function testConnectUsesConfiguredMigrationBatchSize(): void { - $queue = (new RedisConnector(m::mock(Redis::class)))->connect([ + $queue = (new RedisConnector(Double::for(Redis::class)->strict()))->connect([ 'queue' => 'default', 'migration_batch_size' => 100, ]); diff --git a/tests/Queue/QueueServiceProviderTest.php b/tests/Queue/QueueServiceProviderTest.php index 2684bb1b5d..468312a06b 100644 --- a/tests/Queue/QueueServiceProviderTest.php +++ b/tests/Queue/QueueServiceProviderTest.php @@ -21,19 +21,23 @@ use Hypervel\Testbench\Attributes\DefineEnvironment; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionProperty; use RuntimeException; class QueueServiceProviderTest extends TestCase { + use VerifiesDoubles; + // REMOVED: DynamoDbFailedJobProviderTest; DynamoDB failed-job storage is unsupported. public function testBackgroundAndDeferredConnectionsAreLazyAndReportExceptions(): void { - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->twice()->with(m::type(RuntimeException::class)); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->times(2)->with(Argument::type(RuntimeException::class)); $this->app->instance(ExceptionHandler::class, $handler); $manager = $this->app->make('queue'); diff --git a/tests/Queue/QueueSqsConnectorTest.php b/tests/Queue/QueueSqsConnectorTest.php index d797155dd4..199641c4bf 100644 --- a/tests/Queue/QueueSqsConnectorTest.php +++ b/tests/Queue/QueueSqsConnectorTest.php @@ -26,7 +26,8 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use Psr\Http\Message\RequestInterface; @@ -38,6 +39,8 @@ class QueueSqsConnectorTest extends TestCase { + use VerifiesDoubles; + protected string $tempDir; /** @@ -298,8 +301,8 @@ public function testCancellationWhileUpdatingTheCredentialCacheReleasesTheRefres if ($cleanupThrows) { $cancellation = new RuntimeException('Cache cleanup failed.', previous: $cancellation); } - $repository = m::mock(Repository::class, [new ArrayStore])->makePartial(); - $repository->shouldReceive($cacheable ? 'put' : 'forget')->once()->andThrow($cancellation); + $repository = Double::for(new Repository(new ArrayStore))->passthru(); + $repository->expects($cacheable ? 'put' : 'forget')->throws($cancellation); $promise = (new AwsCredentialCache(fn () => $repository))->resolve( 'credentials', @@ -381,11 +384,11 @@ public function testRejectedCancellationSurvivesACanceledLockRelease(bool $clean public function testCancellationWhileAcquiringTheRefreshLockDoesNotCallTheProvider(bool $cleanupThrows): void { $failure = $cleanupThrows ? new RuntimeException('Lock cleanup failed.', previous: new CanceledException) : new CanceledException; - $lock = m::mock(ArrayLock::class); - $lock->shouldReceive('block')->once()->andThrow($failure); - $lock->shouldReceive('release')->once()->andReturnFalse(); - $store = m::mock(ArrayStore::class)->makePartial(); - $store->shouldReceive('lock')->once()->andReturn($lock); + $lock = Double::for(ArrayLock::class)->strict(); + $lock->expects('block')->throws($failure); + $lock->expects('release')->returns(false); + $store = Double::for(new ArrayStore)->passthru(); + $store->expects('lock')->returns($lock); $repository = new Repository($store); $providerCalled = false; $caught = null; @@ -805,8 +808,8 @@ protected function credentials(array $config): array */ protected function useCredentialCache(Repository $repository): void { - $cache = m::mock(Factory::class); - $cache->shouldReceive('store')->andReturn($repository); + $cache = Double::for(Factory::class)->strict(); + $cache->allows('store')->returns($repository); Container::getInstance()->instance('cache', $cache); } diff --git a/tests/Queue/RateLimitedTest.php b/tests/Queue/RateLimitedTest.php index 85369f8279..8d81ac64ff 100644 --- a/tests/Queue/RateLimitedTest.php +++ b/tests/Queue/RateLimitedTest.php @@ -5,6 +5,7 @@ namespace Hypervel\Tests\Queue; use Hypervel\Container\Container; +use Hypervel\Queue\InteractsWithQueue; use Hypervel\Queue\Middleware\RateLimited; use Hypervel\RateLimiter\Limit; use Hypervel\RateLimiter\Limiter; @@ -12,8 +13,9 @@ use Hypervel\RateLimiter\RateLimiter; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use stdClass; @@ -39,6 +41,8 @@ enum RateLimitedTestStore: string class RateLimitedTest extends TestCase { + use VerifiesDoubles; + public function testConstructorAcceptsStringsAndEnums(): void { $this->mockRateLimiter(); @@ -62,16 +66,15 @@ public function testDontReleaseSetsShouldReleaseToFalse(): void public function testNamedLimiterUsesItsRegisteredStoreAndLimiterName(): void { $policy = Limit::perMinute(10)->by('user-1'); - $store = m::mock(Limiter::class); - $store->shouldReceive('consumeMany') - ->once() + $store = Double::for(Limiter::class)->strict(); + $store->expects('consumeMany') ->with([$policy], 'uploads') - ->andReturn([new LimitResult(true, 10, 9, 0, 60_000_000)]); + ->returns([new LimitResult(true, 10, 9, 0, 60_000_000)]); $manager = $this->mockRateLimiter(); - $manager->shouldReceive('limiter')->with('uploads')->once()->andReturn(fn () => $policy); - $manager->shouldReceive('limiterStore')->with('uploads')->once()->andReturn('redis'); - $manager->shouldReceive('store')->with('redis')->once()->andReturn($store); + $manager->expects('limiter')->with('uploads')->returns(fn () => $policy); + $manager->expects('limiterStore')->with('uploads')->returns('redis'); + $manager->expects('store')->with('redis')->returns($store); $nextCalls = 0; $result = (new RateLimited('uploads'))->handle( @@ -90,16 +93,15 @@ function () use (&$nextCalls): string { public function testExplicitStoreOverridesTheNamedLimiterStoreAndSurvivesSerialization(): void { $policy = Limit::perMinute(10); - $store = m::mock(Limiter::class); - $store->shouldReceive('consumeMany') - ->once() + $store = Double::for(Limiter::class)->strict(); + $store->expects('consumeMany') ->with([$policy], 'uploads') - ->andReturn([new LimitResult(true, 10, 9, 0, 60_000_000)]); + ->returns([new LimitResult(true, 10, 9, 0, 60_000_000)]); $manager = $this->mockRateLimiter(); - $manager->shouldReceive('limiter')->with('uploads')->once()->andReturn(fn () => $policy); - $manager->shouldReceive('limiterStore')->never(); - $manager->shouldReceive('store')->with('redis')->once()->andReturn($store); + $manager->expects('limiter')->with('uploads')->returns(fn () => $policy); + $manager->expects('limiterStore')->never(); + $manager->expects('store')->with('redis')->returns($store); $middleware = unserialize(serialize( (new RateLimited('uploads'))->store(RateLimitedTestStore::Redis) @@ -117,19 +119,18 @@ public function testDeniedJobUsesConfiguredRetryDelayAfterSerialization( int $expectedDelay, ): void { $policy = Limit::perMinute(1); - $store = m::mock(Limiter::class); - $store->shouldReceive('consumeMany') - ->once() + $store = Double::for(Limiter::class)->strict(); + $store->expects('consumeMany') ->with([$policy], 'uploads') - ->andReturn([new LimitResult(false, 1, 0, $retryMicroseconds, $retryMicroseconds)]); + ->returns([new LimitResult(false, 1, 0, $retryMicroseconds, $retryMicroseconds)]); $manager = $this->mockRateLimiter(); - $manager->shouldReceive('limiter')->andReturn(fn () => $policy); - $manager->shouldReceive('limiterStore')->andReturnNull(); - $manager->shouldReceive('store')->with(null)->andReturn($store); + $manager->allows('limiter')->returns(fn () => $policy); + $manager->allows('limiterStore')->returns(null); + $manager->allows('store')->with(null)->returns($store); - $job = m::mock(); - $job->shouldReceive('release')->once()->with($expectedDelay)->andReturnNull(); + $job = Double::for(RateLimitedTestJob::class)->strict(); + $job->expects('release')->with($expectedDelay)->returns(null); $middleware = new RateLimited('uploads'); @@ -171,22 +172,21 @@ public function testGroupUsesTheFirstDeniedPolicyToReleaseTheJob(): void { $first = Limit::perMinute(2)->by('first'); $second = Limit::perMinute(1)->by('second'); - $store = m::mock(Limiter::class); - $store->shouldReceive('consumeMany') - ->once() + $store = Double::for(Limiter::class)->strict(); + $store->expects('consumeMany') ->with([$first, $second], 'uploads') - ->andReturn([ + ->returns([ new LimitResult(true, 2, 2, 0, 0), new LimitResult(false, 1, 0, 60_000_000, 60_000_000), ]); $manager = $this->mockRateLimiter(); - $manager->shouldReceive('limiter')->andReturn(fn () => [$first, $second]); - $manager->shouldReceive('limiterStore')->andReturnNull(); - $manager->shouldReceive('store')->andReturn($store); + $manager->allows('limiter')->returns(fn () => [$first, $second]); + $manager->allows('limiterStore')->returns(null); + $manager->allows('store')->returns($store); - $job = m::mock(); - $job->shouldReceive('release')->once()->with(63)->andReturnNull(); + $job = Double::for(RateLimitedTestJob::class)->strict(); + $job->expects('release')->with(63)->returns(null); $nextCalls = 0; (new RateLimited('uploads'))->handle($job, function () use (&$nextCalls): void { @@ -199,8 +199,8 @@ public function testGroupUsesTheFirstDeniedPolicyToReleaseTheJob(): void public function testUnlimitedNamedQueueLimiterBypassesStorage(): void { $manager = $this->mockRateLimiter(); - $manager->shouldReceive('limiter')->with('uploads')->once()->andReturn(fn () => Limit::none()); - $manager->shouldReceive('store')->never(); + $manager->expects('limiter')->with('uploads')->returns(fn () => Limit::none()); + $manager->expects('store')->never(); $result = (new RateLimited('uploads'))->handle( new stdClass, @@ -213,14 +213,19 @@ public function testUnlimitedNamedQueueLimiterBypassesStorage(): void /** * Create a mock RateLimiter and set up the container. */ - protected function mockRateLimiter(): RateLimiter&MockInterface + protected function mockRateLimiter(): DoubleInterface { - $limiter = m::mock(RateLimiter::class); + $limiter = Double::for(RateLimiter::class, override: true)->strict(); $container = new Container; - $container->instance(RateLimiter::class, $limiter); + $container->instance(RateLimiter::class, $limiter->instance()); Container::setInstance($container); return $limiter; } } + +class RateLimitedTestJob +{ + use InteractsWithQueue; +} diff --git a/tests/Queue/RelayCommandTest.php b/tests/Queue/RelayCommandTest.php index 3664663f5e..507b650c35 100644 --- a/tests/Queue/RelayCommandTest.php +++ b/tests/Queue/RelayCommandTest.php @@ -9,15 +9,19 @@ use Hypervel\Support\Facades\Artisan; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; class RelayCommandTest extends TestCase { + use VerifiesDoubles; + public function testCommandPassesThePinnedSourceAndTypedOptionsToTheWorker(): void { - $worker = m::mock(OutboxWorker::class); - $worker->expects('run')->with('orders', m::on(function (OutboxWorkerOptions $options): bool { + $worker = Double::for(OutboxWorker::class)->strict(); + $worker->expects('run')->with('orders', Argument::satisfies(function (OutboxWorkerOptions $options): bool { $this->assertEquals(new OutboxWorkerOptions( batch: 50, sleep: 0.25, @@ -30,7 +34,7 @@ public function testCommandPassesThePinnedSourceAndTypedOptionsToTheWorker(): vo ), $options); return true; - }))->andReturn(12); + }))->returns(12); $this->app->instance(OutboxWorker::class, $worker); $this->assertSame(12, Artisan::call('queue:relay', [ @@ -48,8 +52,8 @@ public function testCommandPassesThePinnedSourceAndTypedOptionsToTheWorker(): vo public function testCommandDefaultsToAllConfiguredSources(): void { - $worker = m::mock(OutboxWorker::class); - $worker->expects('run')->with(null, m::on(fn (OutboxWorkerOptions $options): bool => $options == new OutboxWorkerOptions))->andReturn(0); + $worker = Double::for(OutboxWorker::class)->strict(); + $worker->expects('run')->with(null, Argument::satisfies(fn (OutboxWorkerOptions $options): bool => $options == new OutboxWorkerOptions))->returns(0); $this->app->instance(OutboxWorker::class, $worker); $this->assertSame(0, Artisan::call('queue:relay')); @@ -59,8 +63,8 @@ public function testPercentageMemoryLimitIsPassedToTheWorkerUnchanged(): void { $originalLimit = ini_get('memory_limit'); ini_set('memory_limit', (string) (memory_get_usage(true) * 4)); - $worker = m::mock(OutboxWorker::class); - $worker->expects('run')->with(null, m::on(fn (OutboxWorkerOptions $options): bool => $options->memory === '60%'))->andReturn(0); + $worker = Double::for(OutboxWorker::class)->strict(); + $worker->expects('run')->with(null, Argument::satisfies(fn (OutboxWorkerOptions $options): bool => $options->memory === '60%'))->returns(0); $this->app->instance(OutboxWorker::class, $worker); try { @@ -73,7 +77,7 @@ public function testPercentageMemoryLimitIsPassedToTheWorkerUnchanged(): void #[DataProvider('invalidOptions')] public function testInvalidOptionsFailBeforeTheWorkerStarts(array $options): void { - $this->app->instance(OutboxWorker::class, m::mock(OutboxWorker::class)); + $this->app->instance(OutboxWorker::class, Double::for(OutboxWorker::class)->strict()); $this->expectException(InvalidArgumentException::class); Artisan::call('queue:relay', $options); diff --git a/tests/Queue/RetryCommandTest.php b/tests/Queue/RetryCommandTest.php index cc9877ffb3..f2754b0a51 100644 --- a/tests/Queue/RetryCommandTest.php +++ b/tests/Queue/RetryCommandTest.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\Queue; +use Aws\MockHandler; use Aws\Result; use Aws\Sqs\SqsClient; use Closure; @@ -19,8 +20,10 @@ use Hypervel\Queue\QueuePoolProxy; use Hypervel\Queue\SqsQueue; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use JsonException; -use Mockery as m; use RuntimeException; use stdClass; use Symfony\Component\Console\Input\ArrayInput; @@ -29,6 +32,8 @@ class RetryCommandTest extends TestCase { + use VerifiesDoubles; + /** @var list */ private array $poolManagers = []; @@ -68,23 +73,18 @@ public function testRetryPreservesArbitraryPayloadFields(): void $failedJob->queue = 'critical'; $failedJob->payload = json_encode($payload); - $failedJobs = m::mock(FailedJobProviderInterface::class); - $failedJobs->shouldReceive('find')->once()->with('failed-id')->andReturn($failedJob); - $failedJobs->shouldReceive('forget')->once()->with('failed-id')->andReturn(true); - - $pushedPayload = null; - $queue = m::mock(QueueContract::class); - $queue->shouldReceive('pushRaw') - ->once() - ->withArgs(function (string $rawPayload, string $queueName) use (&$pushedPayload): bool { - $pushedPayload = json_decode($rawPayload, true); + $failedJobs = Double::for(FailedJobProviderInterface::class)->strict(); + $failedJobs->expects('find')->with('failed-id')->returns($failedJob); + $failedJobs->expects('forget')->with('failed-id')->returns(true); - return $queueName === 'critical'; - }) - ->andReturn('retried-id'); + $rawPayload = null; + $queue = Double::for(QueueContract::class)->strict(); + $queue->expects('pushRaw') + ->with(Argument::capture($rawPayload), 'critical', Argument::any()) + ->returns('retried-id'); - $queueManager = m::mock(QueueManager::class); - $queueManager->shouldReceive('connection')->once()->with('redis')->andReturn($queue); + $queueManager = Double::for(QueueManager::class)->strict(); + $queueManager->expects('connection')->with('redis')->returns($queue); $this->app->instance('queue.failer', $failedJobs); $this->app->instance('queue', $queueManager); @@ -107,7 +107,7 @@ static function (JobRetryRequested $event) use (&$retryRequested): void { $expected['attempts'] = 0; $expected['retryUntil'] = 987654321; - $this->assertSame($expected, $pushedPayload); + $this->assertSame($expected, json_decode($rawPayload, true)); $this->assertSame($failedJob, $retryRequested->job); } @@ -119,12 +119,12 @@ public function testPassiveObserverDoesNotCauseRetryRequestedEventToDispatch(): 'data' => [], ], JSON_THROW_ON_ERROR); $failedJob = $this->failedJob($payload); - $failedJobs = m::mock(FailedJobProviderInterface::class); - $failedJobs->shouldReceive('find')->once()->with('failed-id')->andReturn($failedJob); - $failedJobs->shouldReceive('forget')->once()->with('failed-id')->andReturn(true); + $failedJobs = Double::for(FailedJobProviderInterface::class)->strict(); + $failedJobs->expects('find')->with('failed-id')->returns($failedJob); + $failedJobs->expects('forget')->with('failed-id')->returns(true); $queue = new NullQueue; - $queueManager = m::mock(QueueManager::class); - $queueManager->shouldReceive('connection')->once()->with('sqs')->andReturn($queue); + $queueManager = Double::for(QueueManager::class)->strict(); + $queueManager->expects('connection')->with('sqs')->returns($queue); $observed = false; $this->app->make('events')->observe( JobRetryRequested::class, @@ -151,27 +151,33 @@ public function testRetryPreservesFifoOptionsOnDirectSqsQueue(): void ], JSON_THROW_ON_ERROR); $failedJob = $this->failedJob($payload); - $failedJobs = m::mock(FailedJobProviderInterface::class); - $failedJobs->shouldReceive('find')->once()->with('failed-id')->andReturn($failedJob); - $failedJobs->shouldReceive('forget')->once()->with('failed-id')->andReturn(true); - - $sqs = m::mock(SqsClient::class); - $sqs->shouldReceive('sendMessage') - ->once() - ->withArgs(function (array $message): bool { - return $message['MessageGroupId'] === '0' - && $message['MessageDeduplicationId'] === '0'; - }) - ->andReturn(new Result(['MessageId' => 'retried-id'])); + $failedJobs = Double::for(FailedJobProviderInterface::class)->strict(); + $failedJobs->expects('find')->with('failed-id')->returns($failedJob); + $failedJobs->expects('forget')->with('failed-id')->returns(true); + + $handler = new MockHandler; + $handler->append(new Result(['MessageId' => 'retried-id'])); + $sqs = new SqsClient([ + 'region' => 'us-east-1', + 'version' => 'latest', + 'credentials' => false, + 'handler' => $handler, + ]); $queue = new SqsQueue($sqs, 'jobs.fifo'); - $queueManager = m::mock(QueueManager::class); - $queueManager->shouldReceive('connection')->once()->with('sqs')->andReturn($queue); + $queueManager = Double::for(QueueManager::class)->strict(); + $queueManager->expects('connection')->with('sqs')->returns($queue); $this->app->instance('queue.failer', $failedJobs); $this->app->instance('queue', $queueManager); $this->runRetryCommand(); + + $this->assertCount(0, $handler); + $this->assertSame('SendMessage', $handler->getLastCommand()->getName()); + $message = $handler->getLastCommand()->toArray(); + $this->assertSame('0', $message['MessageGroupId']); + $this->assertSame('0', $message['MessageDeduplicationId']); } public function testRetryPreservesFifoOptionsThroughPooledSqsQueue(): void @@ -185,28 +191,34 @@ public function testRetryPreservesFifoOptionsThroughPooledSqsQueue(): void ], JSON_THROW_ON_ERROR); $failedJob = $this->failedJob($payload); - $failedJobs = m::mock(FailedJobProviderInterface::class); - $failedJobs->shouldReceive('find')->once()->with('failed-id')->andReturn($failedJob); - $failedJobs->shouldReceive('forget')->once()->with('failed-id')->andReturn(true); - - $sqs = m::mock(SqsClient::class); - $sqs->shouldReceive('sendMessage') - ->once() - ->withArgs(function (array $message): bool { - return json_decode($message['MessageBody'], true, flags: JSON_THROW_ON_ERROR)['attempts'] === 0 - && $message['MessageGroupId'] === '0' - && $message['MessageDeduplicationId'] === '0'; - }) - ->andReturn(new Result(['MessageId' => 'retried-id'])); + $failedJobs = Double::for(FailedJobProviderInterface::class)->strict(); + $failedJobs->expects('find')->with('failed-id')->returns($failedJob); + $failedJobs->expects('forget')->with('failed-id')->returns(true); + + $handler = new MockHandler; + $handler->append(new Result(['MessageId' => 'retried-id'])); + $sqs = new SqsClient([ + 'region' => 'us-east-1', + 'version' => 'latest', + 'credentials' => false, + 'handler' => $handler, + ]); $queue = $this->pooledQueue('sqs', fn () => new SqsQueue($sqs, 'jobs.fifo')); - $queueManager = m::mock(QueueManager::class); - $queueManager->shouldReceive('connection')->once()->with('sqs')->andReturn($queue); + $queueManager = Double::for(QueueManager::class)->strict(); + $queueManager->expects('connection')->with('sqs')->returns($queue); $this->app->instance('queue.failer', $failedJobs); $this->app->instance('queue', $queueManager); $this->runRetryCommand(); + + $this->assertCount(0, $handler); + $this->assertSame('SendMessage', $handler->getLastCommand()->getName()); + $message = $handler->getLastCommand()->toArray(); + $this->assertSame('0', $message['MessageGroupId']); + $this->assertSame('0', $message['MessageDeduplicationId']); + $this->assertSame(0, json_decode($message['MessageBody'], true, flags: JSON_THROW_ON_ERROR)['attempts']); } public function testRetryDoesNotReadSqsOptionsFromPooledBeanstalkdQueue(): void @@ -221,14 +233,14 @@ public function testRetryDoesNotReadSqsOptionsFromPooledBeanstalkdQueue(): void $failedJob = $this->failedJob($payload); $failedJob->connection = 'beanstalkd'; - $failedJobs = m::mock(FailedJobProviderInterface::class); - $failedJobs->shouldReceive('find')->once()->with('failed-id')->andReturn($failedJob); - $failedJobs->shouldReceive('forget')->once()->with('failed-id')->andReturn(true); + $failedJobs = Double::for(FailedJobProviderInterface::class)->strict(); + $failedJobs->expects('find')->with('failed-id')->returns($failedJob); + $failedJobs->expects('forget')->with('failed-id')->returns(true); $beanstalkd = new RetryCommandPooledQueue; $queue = $this->pooledQueue('beanstalkd', fn () => $beanstalkd); - $queueManager = m::mock(QueueManager::class); - $queueManager->shouldReceive('connection')->once()->with('beanstalkd')->andReturn($queue); + $queueManager = Double::for(QueueManager::class)->strict(); + $queueManager->expects('connection')->with('beanstalkd')->returns($queue); $this->app->instance('queue.failer', $failedJobs); $this->app->instance('queue', $queueManager); @@ -251,12 +263,11 @@ public function testSuccessfulSyncRetryExecutesBeforeFailedRecordIsForgotten(): $failedJob->connection = 'sync'; $failedJob->queue = 'sync'; - $failedJobs = m::mock(FailedJobProviderInterface::class); - $failedJobs->shouldReceive('find')->once()->with('failed-id')->andReturn($failedJob); - $failedJobs->shouldReceive('forget') - ->once() + $failedJobs = Double::for(FailedJobProviderInterface::class)->strict(); + $failedJobs->expects('find')->with('failed-id')->returns($failedJob); + $failedJobs->expects('forget') ->with('failed-id') - ->andReturnUsing(function (): bool { + ->resolves(function (): bool { $this->assertTrue(RetryCommandSyncHandler::$handled); return true; @@ -284,9 +295,9 @@ public function testFailedSyncRetryPreservesFailedRecord(): void $failedJob->connection = 'sync'; $failedJob->queue = 'sync'; - $failedJobs = m::mock(FailedJobProviderInterface::class); - $failedJobs->shouldReceive('find')->once()->with('failed-id')->andReturn($failedJob); - $failedJobs->shouldNotReceive('forget'); + $failedJobs = Double::for(FailedJobProviderInterface::class)->strict(); + $failedJobs->expects('find')->with('failed-id')->returns($failedJob); + $failedJobs->expects('forget')->never(); $this->app->instance('queue.failer', $failedJobs); @@ -299,15 +310,15 @@ public function testFailedSyncRetryPreservesFailedRecord(): void public function testMalformedPayloadIsNotForgottenWhenRetryFails(): void { $failedJob = $this->failedJob('{invalid'); - $failedJobs = m::mock(FailedJobProviderInterface::class); - $failedJobs->shouldReceive('find')->once()->with('failed-id')->andReturn($failedJob); - $failedJobs->shouldNotReceive('forget'); + $failedJobs = Double::for(FailedJobProviderInterface::class)->strict(); + $failedJobs->expects('find')->with('failed-id')->returns($failedJob); + $failedJobs->expects('forget')->never(); - $queue = m::mock(QueueContract::class); - $queue->shouldNotReceive('pushRaw'); + $queue = Double::for(QueueContract::class)->strict(); + $queue->expects('pushRaw')->never(); - $queueManager = m::mock(QueueManager::class); - $queueManager->shouldReceive('connection')->once()->with('sqs')->andReturn($queue); + $queueManager = Double::for(QueueManager::class)->strict(); + $queueManager->expects('connection')->with('sqs')->returns($queue); $this->app->instance('queue.failer', $failedJobs); $this->app->instance('queue', $queueManager); diff --git a/tests/Queue/SqsBatchLifecycleTest.php b/tests/Queue/SqsBatchLifecycleTest.php index 2e653fa2f2..b36148df19 100644 --- a/tests/Queue/SqsBatchLifecycleTest.php +++ b/tests/Queue/SqsBatchLifecycleTest.php @@ -4,6 +4,8 @@ namespace Hypervel\Tests\Queue; +use Aws\CommandInterface; +use Aws\MockHandler; use Aws\Result; use Aws\Sqs\Exception\SqsException; use Aws\Sqs\SqsClient; @@ -33,7 +35,9 @@ use Hypervel\Queue\SqsQueue; use Hypervel\Tests\Queue\Fixtures\FakeSqsJob; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -41,11 +45,31 @@ class SqsBatchLifecycleTest extends TestCase { + use VerifiesDoubles; + + protected MockHandler $transport; + + /** + * Verify the queued SDK responses were consumed and clean up the test environment. + */ + protected function tearDown(): void + { + try { + $this->assertCount(0, $this->transport); + + if (($command = $this->transport->getLastCommand()) !== null) { + $this->assertSame('SendMessageBatch', $command->getName()); + } + } finally { + parent::tearDown(); + } + } + #[TestWith([false])] #[TestWith([true])] public function testCustomBulkDispatchRetainsTheAcceptedUniqueLock(bool $afterCommit): void { - [$queue, $client, $events, $container] = $this->queue(); + [$queue, $transport, $events, $container] = $this->queue(); $cache = new Repository(new WorkerArrayStore); $container->instance(Cache::class, $cache); $container->instance(BusContract::class, new BusDispatcher($container, static fn () => $queue)); @@ -53,7 +77,7 @@ public function testCustomBulkDispatchRetainsTheAcceptedUniqueLock(bool $afterCo $container->instance('db.transactions', $transactions); $transactions->begin('testing', 1); $sent = false; - $client->expects('sendMessageBatch')->andReturnUsing(static function () use (&$sent): Result { + $transport->append(static function () use (&$sent): Result { $sent = true; return new Result(['Successful' => [['Id' => '0', 'MessageId' => 'accepted']]]); @@ -76,7 +100,7 @@ public function testCustomBulkDispatchRetainsTheAcceptedUniqueLock(bool $afterCo #[TestWith([JobQueueing::class])] public function testPreparationFailureTerminatesEveryOutstandingMember(string $eventClass): void { - [$queue, $client, $events] = $this->queue(); + [$queue, $transport, $events] = $this->queue(); $exception = new RuntimeException('Second member failed.'); $count = 0; $events->listen($eventClass, static function () use (&$count, $exception): void { @@ -88,7 +112,6 @@ public function testPreparationFailureTerminatesEveryOutstandingMember(string $e $events->listen(JobQueueingFailed::class, static function (JobQueueingFailed $event) use (&$failed): void { $failed[] = $event; }); - $client->shouldNotReceive('sendMessageBatch'); try { $queue->bulk(['first', 'second', 'third']); @@ -97,6 +120,7 @@ public function testPreparationFailureTerminatesEveryOutstandingMember(string $e $this->assertSame($exception, $caught); } + $this->assertNull($transport->getLastCommand()); $this->assertSame(['first', 'second', 'third'], array_column($failed, 'job')); $this->assertSame([$exception, $exception, $exception], array_column($failed, 'exception')); } @@ -105,7 +129,7 @@ public function testPreparationFailureTerminatesEveryOutstandingMember(string $e #[TestWith([JobQueueing::class])] public function testPreparationCancellationNotifiesOutstandingMembersOfTheCancellation(string $eventClass): void { - [$queue, $client, $events] = $this->queue(); + [$queue, $transport, $events] = $this->queue(); $cleanup = new RuntimeException('Preparation cleanup failed.'); $gate = $this->armCurrentCoroutineCancellation(); $events->listen($eventClass, static function () use ($gate, $cleanup): never { @@ -122,7 +146,6 @@ public function testPreparationCancellationNotifiesOutstandingMembersOfTheCancel $events->listen(JobQueueingCanceled::class, static function (JobQueueingCanceled $event) use (&$canceled): void { $canceled[] = $event; }); - $client->shouldNotReceive('sendMessageBatch'); try { $queue->bulk(['first', 'second']); @@ -134,6 +157,7 @@ public function testPreparationCancellationNotifiesOutstandingMembersOfTheCancel $gate->close(); } + $this->assertNull($transport->getLastCommand()); $this->assertSame([], $failed); $this->assertSame(['first', 'second'], array_column($canceled, 'job')); $this->assertSame([$cleanup, $cleanup], array_column($canceled, 'cancellation')); @@ -142,16 +166,16 @@ public function testPreparationCancellationNotifiesOutstandingMembersOfTheCancel public function testFailureNotificationsDrainAndRetainThePrimaryAttemptError(): void { - [$queue, $client, $events, $container] = $this->queue(); + [$queue, $transport, $events, $container] = $this->queue(); $primary = new RuntimeException('Transport failed.'); $listener = new RuntimeException('Listener failed.'); - $client->expects('sendMessageBatch')->andThrow($primary); + $transport->append($primary); $failed = []; $events->listen(JobQueueingFailed::class, static function (JobQueueingFailed $event) use (&$failed): void { $failed[] = $event; }); $events->listen(JobQueueingFailed::class, static fn () => throw $listener); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $handler->expects('report')->with($listener); $container->instance(ExceptionHandler::class, $handler); @@ -170,10 +194,10 @@ public function testFailureNotificationsDrainAndRetainThePrimaryAttemptError(): #[TestWith([JobQueueingFailed::class])] public function testNotificationCancellationStillNotifiesLaterMembersAndReportsTheEarlierFailure(string $eventClass): void { - [$queue, $client, $events, $container] = $this->queue(); + [$queue, $transport, $events, $container] = $this->queue(); $transportFailure = new RuntimeException('Transport failed.'); if ($eventClass === JobQueued::class) { - $client->expects('sendMessageBatch')->andReturn(new Result([ + $transport->append(new Result([ 'Successful' => [ ['Id' => '0', 'MessageId' => 'first'], ['Id' => '1', 'MessageId' => 'second'], @@ -181,7 +205,7 @@ public function testNotificationCancellationStillNotifiesLaterMembersAndReportsT ], ])); } else { - $client->expects('sendMessageBatch')->andThrow($transportFailure); + $transport->append($transportFailure); } $cleanup = new RuntimeException('Notification cleanup failed.'); $listenerFailure = new RuntimeException('First listener failed.'); @@ -204,7 +228,7 @@ public function testNotificationCancellationStillNotifiesLaterMembersAndReportsT $events->listen(JobQueueingCanceled::class, static function (JobQueueingCanceled $event) use (&$canceled): void { $canceled[] = $event; }); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $handler->expects('report')->with($listenerFailure); $container->instance(ExceptionHandler::class, $handler); @@ -229,13 +253,14 @@ public function testNotificationCancellationStillNotifiesLaterMembersAndReportsT #[TestWith([true])] public function testSuccessListenerFailurePreservesAcceptedEntriesAndCleansExplicitRejects(bool $failureListenerCanceled): void { - [$queue, $client, $events, $container] = $this->queue(['enabled' => true, 'always' => true, 'store' => 'overflow']); + [$queue, $transport, $events, $container] = $this->queue(['enabled' => true, 'always' => true, 'store' => 'overflow']); $store = new Repository(new WorkerArrayStore); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('overflow')->andReturn($store); + $cache = Double::for(CacheFactory::class)->strict(); + $cache->expects('store')->with('overflow')->returns($store); $container->instance('cache', $cache); $paths = []; - $client->expects('sendMessageBatch')->once()->andReturnUsing(static function (array $arguments) use (&$paths): Result { + $transport->append(static function (CommandInterface $command) use (&$paths): Result { + $arguments = $command->toArray(); $paths = array_map(static fn (array $entry): string => json_decode($entry['MessageBody'], true)['@pointer'], $arguments['Entries']); return new Result([ @@ -256,10 +281,10 @@ public function testSuccessListenerFailurePreservesAcceptedEntriesAndCleansExpli throw $cancellation; } }); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $handler->expects('report')->with($listener); if ($failureListenerCanceled) { - $handler->expects('report')->with(m::type(SqsException::class)); + $handler->expects('report')->with(Argument::type(SqsException::class)); } $container->instance(ExceptionHandler::class, $handler); @@ -290,8 +315,8 @@ public function testSuccessListenerFailurePreservesAcceptedEntriesAndCleansExpli #[TestWith([true, true])] public function testCancellationDuringReportingStillNotifiesEveryMemberAndReportsTheRejection(bool $cleanupThrows, bool $overflowCleanup): void { - [$queue, $client, $events, $container] = $this->queue(['enabled' => $overflowCleanup, 'always' => true, 'store' => 'overflow']); - $client->expects('sendMessageBatch')->andReturn(new Result([ + [$queue, $transport, $events, $container] = $this->queue(['enabled' => $overflowCleanup, 'always' => true, 'store' => 'overflow']); + $transport->append(new Result([ 'Successful' => [['Id' => '0', 'MessageId' => 'accepted']], 'Failed' => [ ['Id' => '1', 'Code' => 'InvalidParameterValue', 'Message' => 'Rejected', 'SenderFault' => true], @@ -301,9 +326,9 @@ public function testCancellationDuringReportingStillNotifiesEveryMemberAndReport $reportedFailure = new RuntimeException($overflowCleanup ? 'Overflow deletion failed.' : 'Queued listener failed.'); $deleted = []; if ($overflowCleanup) { - $store = m::mock(Cache::class); - $store->expects('put')->times(3)->andReturnTrue(); - $store->expects('forget')->twice()->andReturnUsing(static function (string $path) use (&$deleted, $reportedFailure): bool { + $store = Double::for(Cache::class)->strict(); + $store->expects('put')->times(3)->returns(true); + $store->expects('forget')->times(2)->resolves(static function (string $path) use (&$deleted, $reportedFailure): bool { $deleted[] = $path; if (count($deleted) === 1) { throw $reportedFailure; @@ -311,8 +336,8 @@ public function testCancellationDuringReportingStillNotifiesEveryMemberAndReport return true; }); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('overflow')->andReturn($store); + $cache = Double::for(CacheFactory::class)->strict(); + $cache->expects('store')->with('overflow')->returns($store); $container->instance('cache', $cache); } $queued = []; @@ -328,8 +353,8 @@ public function testCancellationDuringReportingStillNotifiesEveryMemberAndReport }); $gate = $this->armCurrentCoroutineCancellation(); $cleanup = new RuntimeException('Reporting cleanup failed.'); - $handler = m::mock(ExceptionHandler::class); - $handler->expects('report')->with($reportedFailure)->andReturnUsing(static function () use ($gate, $cleanup, $cleanupThrows): void { + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($reportedFailure)->resolves(static function () use ($gate, $cleanup, $cleanupThrows): void { try { $gate->push(true); } finally { @@ -338,7 +363,7 @@ public function testCancellationDuringReportingStillNotifiesEveryMemberAndReport } } }); - $handler->expects('report')->with(m::type(SqsException::class)); + $handler->expects('report')->with(Argument::type(SqsException::class)); $container->instance(ExceptionHandler::class, $handler); try { @@ -380,7 +405,7 @@ private function armCurrentCoroutineCancellation(): Channel /** * Create a queue with real lifecycle dispatch and a controlled SDK boundary. * - * @return array{SqsQueue, SqsClient, Dispatcher, Container} + * @return array{SqsQueue, MockHandler, Dispatcher, Container} */ protected function queue(array $overflow = []): array { @@ -389,12 +414,18 @@ protected function queue(array $overflow = []): array $events = new Dispatcher($container); $container->instance('events', $events); $container->instance(EventsContract::class, $events); - $client = m::mock(SqsClient::class); + $this->transport = $transport = new MockHandler; + $client = new SqsClient([ + 'region' => 'us-east-1', + 'version' => 'latest', + 'credentials' => false, + 'handler' => $transport, + ]); $queue = new SqsQueue($client, 'jobs', overflowStorage: $overflow); $queue->setContainer($container); $queue->setConnectionName('sqs'); - return [$queue, $client, $events, $container]; + return [$queue, $transport, $events, $container]; } } diff --git a/tests/Queue/WorkCommandTest.php b/tests/Queue/WorkCommandTest.php index 248cfaebae..7f3b92f0da 100644 --- a/tests/Queue/WorkCommandTest.php +++ b/tests/Queue/WorkCommandTest.php @@ -17,7 +17,9 @@ use Hypervel\Support\Facades\Artisan; use Hypervel\Support\Facades\Queue; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; @@ -25,6 +27,8 @@ class WorkCommandTest extends TestCase { + use VerifiesDoubles; + /** * Configure the command's application environment. */ @@ -38,17 +42,17 @@ protected function defineEnvironment(Application $app): void #[DataProvider('jobOutputProvider')] public function testJobOutputIncludesVerboseDetailsOnlyWhenRequested(bool $verbose, int|string|null $jobId): void { - $job = m::mock(Job::class); - $job->shouldReceive('getJobId')->andReturn($jobId); - $job->shouldReceive('resolveName')->andReturn('App\Jobs\SendInvoice'); - $job->shouldReceive('getConnectionName')->andReturn('redis'); - $job->shouldReceive('getQueue')->andReturn('invoices'); - $job->shouldReceive('isReleased')->andReturnFalse(); + $job = Double::for(Job::class)->strict(); + $job->allows('getJobId')->returns($jobId); + $job->allows('resolveName')->returns('App\Jobs\SendInvoice'); + $job->allows('getConnectionName')->returns('redis'); + $job->allows('getQueue')->returns('invoices'); + $job->allows('isReleased')->returns(false); $command = new WorkCommandOutputStub( $this->app, $this->app->make('config'), - m::mock(Worker::class), + Double::for(Worker::class)->strict(), $this->app->make('cache'), ); $output = new BufferedOutput($verbose ? OutputInterface::VERBOSITY_VERBOSE : OutputInterface::VERBOSITY_NORMAL); @@ -91,7 +95,7 @@ public function testFractionalSleepAndRestSecondsAreKept(): void $command = new WorkCommandOutputStub( $this->app, $this->app->make('config'), - m::mock(Worker::class), + Double::for(Worker::class)->strict(), $this->app->make('cache'), ); $command->setInput(new ArrayInput(['--sleep' => '0.5', '--rest' => '0.25'], $command->getDefinition())); @@ -107,7 +111,7 @@ public function testPercentageMemoryLimitIsKept(): void $command = new WorkCommandOutputStub( $this->app, $this->app->make('config'), - m::mock(Worker::class), + Double::for(Worker::class)->strict(), $this->app->make('cache'), ); $command->setInput(new ArrayInput(['--memory' => '50%'], $command->getDefinition())); @@ -285,13 +289,12 @@ public function testStopEventsWithoutCommandOptionsDoNotWriteOutput(): void */ private function runWorkerCommand(WorkerStopping $event, BufferedOutput $output, array $arguments = []): void { - $worker = m::mock(Worker::class); - $worker->shouldReceive('setName')->once()->with('default')->andReturnSelf(); - $worker->shouldReceive('setCache')->once()->with(m::type(Repository::class))->andReturnSelf(); - $worker->shouldReceive('daemon') - ->once() - ->with('sync', 'default', m::type(WorkerOptions::class)) - ->andReturnUsing(function (string $connection, string $queue, WorkerOptions $options) use ($event): int { + $worker = Double::for(Worker::class)->strict(); + $worker->expects('setName')->with('default'); + $worker->expects('setCache')->with(Argument::type(Repository::class)); + $worker->expects('daemon') + ->with('sync', 'default', Argument::type(WorkerOptions::class)) + ->resolves(function (string $connection, string $queue, WorkerOptions $options) use ($event): int { $event->workerOptions = $options; $this->app->make('events')->dispatch($event); diff --git a/tests/RateLimiter/DatabaseStoreTest.php b/tests/RateLimiter/DatabaseStoreTest.php index 4970c2ed57..42a4b1819b 100644 --- a/tests/RateLimiter/DatabaseStoreTest.php +++ b/tests/RateLimiter/DatabaseStoreTest.php @@ -13,32 +13,35 @@ use Hypervel\RateLimiter\Limit; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseStoreTest extends TestCase { + use VerifiesDoubles; + public function testInspectionUsesTheConfiguredConnectionTableAndWritePdo(): void { - $connections = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $query = m::mock(Builder::class); - - $connections->shouldReceive('connection')->once()->with('limiter')->andReturn($connection); - $connection->shouldReceive('table')->once()->with('custom_rate_limits')->andReturn($query); - $query->shouldReceive('useWritePdo')->once()->andReturnSelf(); - $query->shouldReceive('where')->once()->with('key', 'physical-key')->andReturnSelf(); - $query->shouldReceive('first')->once()->andReturnNull(); - $connection->shouldReceive('getDriverName')->once()->andReturn('pgsql'); - $connection->shouldReceive('scalar') - ->once() + $connections = Double::for(ConnectionResolverInterface::class)->strict(); + $connection = Double::for(Connection::class)->strict(); + $query = Double::for(Builder::class)->strict(); + + $connections->expects('connection')->with('limiter')->returns($connection); + $connection->expects('table')->with('custom_rate_limits')->returns($query); + $query->expects('useWritePdo'); + $query->expects('where')->with('key', 'physical-key'); + $query->expects('first')->returns(null); + $connection->expects('getDriverName')->returns('pgsql'); + $connection->expects('scalar') ->with( 'SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000)::bigint', [], false, ) - ->andReturn('1000000'); + ->returns('1000000'); $result = (new DatabaseStore($connections, 'limiter', 'custom_rate_limits')) ->inspect('physical-key', Limit::perMinute(10)); @@ -49,32 +52,31 @@ public function testInspectionUsesTheConfiguredConnectionTableAndWritePdo(): voi public function testEstablishedNonSqlMutationLocksBeforeReadingServerTimeWithoutInserting(): void { - $connections = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $locked = m::mock(Builder::class); - $update = m::mock(Builder::class); + $connections = Double::for(ConnectionResolverInterface::class)->strict(); + $connection = Double::for(Connection::class)->strict(); + $locked = Double::for(Builder::class)->strict(); + $update = Double::for(Builder::class)->strict(); $operations = []; - $connections->shouldReceive('connection')->once()->with('limiter')->andReturn($connection); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('transaction') - ->once() - ->with(m::type(Closure::class), 3) - ->andReturnUsing(static fn (Closure $callback): mixed => $callback($connection)); - $connection->shouldReceive('getDriverName') + $connections->expects('connection')->with('limiter')->returns($connection); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('transaction') + ->with(Argument::type(Closure::class), 3) + ->resolves(static fn (Closure $callback): mixed => $callback($connection)); + $connection->expects('getDriverName') ->times(3) - ->andReturnUsing(static function () use (&$operations): string { + ->resolves(static function () use (&$operations): string { $operations[] = 'driver'; return 'mysql'; }); - $connection->shouldReceive('table') - ->twice() + $connection->expects('table') + ->times(2) ->with('custom_rate_limits') - ->andReturn($locked, $update); - $locked->shouldReceive('where')->once()->with('key', 'physical-key')->andReturnSelf(); - $locked->shouldReceive('lockForUpdate')->once()->andReturnSelf(); - $locked->shouldReceive('first')->once()->andReturnUsing(static function () use (&$operations): object { + ->returns($locked, $update); + $locked->expects('where')->with('key', 'physical-key'); + $locked->expects('lockForUpdate'); + $locked->expects('first')->resolves(static function () use (&$operations): object { $operations[] = 'lock'; return (object) [ @@ -83,27 +85,25 @@ public function testEstablishedNonSqlMutationLocksBeforeReadingServerTimeWithout 'expires_at' => 0, ]; }); - $connection->shouldReceive('scalar') - ->once() + $connection->expects('scalar') ->with( 'SELECT FLOOR(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(6)) * 1000000)', [], false, ) - ->andReturnUsing(static function () use (&$operations): string { + ->resolves(static function () use (&$operations): string { $operations[] = 'clock'; return '1000000'; }); - $update->shouldReceive('where')->once()->with('key', 'physical-key')->andReturnSelf(); - $update->shouldReceive('update') - ->once() + $update->expects('where')->with('key', 'physical-key'); + $update->expects('update') ->with([ 'value' => 1, 'secondary_value' => 0, 'expires_at' => 61_000_000, ]) - ->andReturnUsing(static function () use (&$operations): int { + ->resolves(static function () use (&$operations): int { $operations[] = 'update'; return 1; @@ -122,21 +122,21 @@ public function testMissingNonSqliteStateIsInitializedAndMutatedInASecondTransac string $driver, string $clockQuery, ): void { - $connections = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $missing = m::mock(Builder::class); - $initialize = m::mock(Builder::class); - $locked = m::mock(Builder::class); - $update = m::mock(Builder::class); + $connections = Double::for(ConnectionResolverInterface::class)->strict(); + $connection = Double::for(Connection::class)->strict(); + $missing = Double::for(Builder::class)->strict(); + $initialize = Double::for(Builder::class)->strict(); + $locked = Double::for(Builder::class)->strict(); + $update = Double::for(Builder::class)->strict(); $operations = []; $transaction = 0; - $connections->shouldReceive('connection')->once()->with('limiter')->andReturn($connection); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('transaction') - ->twice() - ->with(m::type(Closure::class), 3) - ->andReturnUsing(static function (Closure $callback) use ($connection, &$operations, &$transaction): mixed { + $connections->expects('connection')->with('limiter')->returns($connection); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('transaction') + ->times(2) + ->with(Argument::type(Closure::class), 3) + ->resolves(static function (Closure $callback) use ($connection, &$operations, &$transaction): mixed { ++$transaction; $operations[] = "transaction-{$transaction}-begin"; $result = $callback($connection); @@ -144,36 +144,34 @@ public function testMissingNonSqliteStateIsInitializedAndMutatedInASecondTransac return $result; }); - $connection->shouldReceive('getDriverName') + $connection->expects('getDriverName') ->times(3) - ->andReturnUsing(static function () use ($driver, &$operations): string { + ->resolves(static function () use ($driver, &$operations): string { $operations[] = 'driver'; return $driver; }); if ($driver === 'pgsql') { - $connection->shouldReceive('getConfig') - ->once() + $connection->expects('getConfig') ->with('isolation_level') - ->andReturn('READ COMMITTED'); + ->returns('READ COMMITTED'); } else { - $connection->shouldNotReceive('getConfig'); + $connection->expects('getConfig')->never(); } - $connection->shouldReceive('table') + $connection->expects('table') ->times(4) ->with('custom_rate_limits') - ->andReturn($missing, $initialize, $locked, $update); - $missing->shouldReceive('where')->once()->with('key', 'physical-key')->andReturnSelf(); - $missing->shouldReceive('lockForUpdate')->once()->andReturnSelf(); - $missing->shouldReceive('first')->once()->andReturnUsing(static function () use (&$operations): null { + ->returns($missing, $initialize, $locked, $update); + $missing->expects('where')->with('key', 'physical-key'); + $missing->expects('lockForUpdate'); + $missing->expects('first')->resolves(static function () use (&$operations): null { $operations[] = 'missing-lock'; return null; }); - $initialize->shouldReceive('upsert') - ->once() + $initialize->expects('upsert') ->with( [ 'key' => 'physical-key', @@ -184,14 +182,14 @@ public function testMissingNonSqliteStateIsInitializedAndMutatedInASecondTransac 'key', ['key' => 'physical-key'], ) - ->andReturnUsing(static function () use (&$operations): int { + ->resolves(static function () use (&$operations): int { $operations[] = 'upsert'; return 0; }); - $locked->shouldReceive('where')->once()->with('key', 'physical-key')->andReturnSelf(); - $locked->shouldReceive('lockForUpdate')->once()->andReturnSelf(); - $locked->shouldReceive('first')->once()->andReturnUsing(static function () use (&$operations): object { + $locked->expects('where')->with('key', 'physical-key'); + $locked->expects('lockForUpdate'); + $locked->expects('first')->resolves(static function () use (&$operations): object { $operations[] = 'final-lock'; return (object) [ @@ -200,27 +198,25 @@ public function testMissingNonSqliteStateIsInitializedAndMutatedInASecondTransac 'expires_at' => 0, ]; }); - $connection->shouldReceive('scalar') - ->once() + $connection->expects('scalar') ->with( $clockQuery, [], false, ) - ->andReturnUsing(static function () use (&$operations): string { + ->resolves(static function () use (&$operations): string { $operations[] = 'clock'; return '1000000'; }); - $update->shouldReceive('where')->once()->with('key', 'physical-key')->andReturnSelf(); - $update->shouldReceive('update') - ->once() + $update->expects('where')->with('key', 'physical-key'); + $update->expects('update') ->with([ 'value' => 1, 'secondary_value' => 0, 'expires_at' => 61_000_000, ]) - ->andReturnUsing(static function () use (&$operations): int { + ->resolves(static function () use (&$operations): int { $operations[] = 'update'; return 1; @@ -273,46 +269,44 @@ public static function nonSqliteDrivers(): array public function testSqliteMutationInsertsBeforeReadingTheLockedState(): void { - $connections = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $insert = m::mock(Builder::class); - $locked = m::mock(Builder::class); - $update = m::mock(Builder::class); + $connections = Double::for(ConnectionResolverInterface::class)->strict(); + $connection = Double::for(Connection::class)->strict(); + $insert = Double::for(Builder::class)->strict(); + $locked = Double::for(Builder::class)->strict(); + $update = Double::for(Builder::class)->strict(); $operations = []; - $connections->shouldReceive('connection')->once()->with('limiter')->andReturn($connection); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('transaction') - ->once() - ->with(m::type(Closure::class), 3) - ->andReturnUsing(static fn (Closure $callback): mixed => $callback($connection)); - $connection->shouldReceive('getDriverName') + $connections->expects('connection')->with('limiter')->returns($connection); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('transaction') + ->with(Argument::type(Closure::class), 3) + ->resolves(static fn (Closure $callback): mixed => $callback($connection)); + $connection->expects('getDriverName') ->times(3) - ->andReturnUsing(static function () use (&$operations): string { + ->resolves(static function () use (&$operations): string { $operations[] = 'driver'; return 'sqlite'; }); - $connection->shouldReceive('table') + $connection->expects('table') ->times(3) ->with('custom_rate_limits') - ->andReturn($insert, $locked, $update); - $insert->shouldReceive('insertOrIgnore') - ->once() + ->returns($insert, $locked, $update); + $insert->expects('insertOrIgnore') ->with([ 'key' => 'physical-key', 'value' => 0, 'secondary_value' => 0, 'expires_at' => 0, ]) - ->andReturnUsing(static function () use (&$operations): int { + ->resolves(static function () use (&$operations): int { $operations[] = 'insert'; return 1; }); - $locked->shouldReceive('where')->once()->with('key', 'physical-key')->andReturnSelf(); - $locked->shouldReceive('lockForUpdate')->once()->andReturnSelf(); - $locked->shouldReceive('first')->once()->andReturnUsing(static function () use (&$operations): object { + $locked->expects('where')->with('key', 'physical-key'); + $locked->expects('lockForUpdate'); + $locked->expects('first')->resolves(static function () use (&$operations): object { $operations[] = 'lock'; return (object) [ @@ -321,17 +315,16 @@ public function testSqliteMutationInsertsBeforeReadingTheLockedState(): void 'expires_at' => 0, ]; }); - $update->shouldReceive('where')->once()->with('key', 'physical-key')->andReturnSelf(); - $update->shouldReceive('update') - ->once() - ->with(m::on(static function (array $state) use (&$operations): bool { + $update->expects('where')->with('key', 'physical-key'); + $update->expects('update') + ->with(Argument::satisfies(static function (array $state) use (&$operations): bool { $operations[] = 'update'; return $state['value'] === 1 && $state['secondary_value'] === 0 && $state['expires_at'] > 60_000_000; })) - ->andReturn(1); + ->returns(1); $result = (new DatabaseStore($connections, 'limiter', 'custom_rate_limits')) ->consume('physical-key', Limit::perMinute(10)); @@ -344,20 +337,19 @@ public function testSqliteMutationInsertsBeforeReadingTheLockedState(): void #[DataProvider('mutatingOperations')] public function testMutatingOperationsRejectUnsupportedPostgresIsolation(string $operation): void { - $connections = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - - $connections->shouldReceive('connection')->once()->with('limiter')->andReturn($connection); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('getDriverName')->once()->andReturn('pgsql'); - $connection->shouldReceive('getConfig') - ->once() + $connections = Double::for(ConnectionResolverInterface::class)->strict(); + $connection = Double::for(Connection::class)->strict(); + + $connections->expects('connection')->with('limiter')->returns($connection); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('getDriverName')->returns('pgsql'); + $connection->expects('getConfig') ->with('isolation_level') - ->andReturn('repeatable read'); - $connection->shouldReceive('getName')->once()->andReturn('limiter'); - $connection->shouldNotReceive('transaction'); - $connection->shouldNotReceive('table'); - $connection->shouldNotReceive('scalar'); + ->returns('repeatable read'); + $connection->expects('getName')->returns('limiter'); + $connection->expects('transaction')->never(); + $connection->expects('table')->never(); + $connection->expects('scalar')->never(); $store = new DatabaseStore($connections, 'limiter', 'custom_rate_limits'); @@ -378,15 +370,15 @@ public function testMutatingOperationsRejectUnsupportedPostgresIsolation(string public function testMutationRejectsNonStringPostgresIsolation(): void { - $connections = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); + $connections = Double::for(ConnectionResolverInterface::class)->strict(); + $connection = Double::for(Connection::class)->strict(); - $connections->shouldReceive('connection')->once()->with('limiter')->andReturn($connection); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('getDriverName')->once()->andReturn('pgsql'); - $connection->shouldReceive('getConfig')->once()->with('isolation_level')->andReturn(1); - $connection->shouldReceive('getName')->once()->andReturn('limiter'); - $connection->shouldNotReceive('table'); + $connections->expects('connection')->with('limiter')->returns($connection); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('getDriverName')->returns('pgsql'); + $connection->expects('getConfig')->with('isolation_level')->returns(1); + $connection->expects('getName')->returns('limiter'); + $connection->expects('table')->never(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs( @@ -398,18 +390,18 @@ public function testMutationRejectsNonStringPostgresIsolation(): void public function testPostgresMutationAllowsDefaultIsolation(): void { - $connections = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $query = m::mock(Builder::class); - - $connections->shouldReceive('connection')->once()->with('limiter')->andReturn($connection); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('getDriverName')->once()->andReturn('pgsql'); - $connection->shouldReceive('getConfig')->once()->with('isolation_level')->andReturnNull(); - $connection->shouldNotReceive('getName'); - $connection->shouldReceive('table')->once()->with('custom_rate_limits')->andReturn($query); - $query->shouldReceive('where')->once()->with('key', 'physical-key')->andReturnSelf(); - $query->shouldReceive('delete')->once()->andReturn(1); + $connections = Double::for(ConnectionResolverInterface::class)->strict(); + $connection = Double::for(Connection::class)->strict(); + $query = Double::for(Builder::class)->strict(); + + $connections->expects('connection')->with('limiter')->returns($connection); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('getDriverName')->returns('pgsql'); + $connection->expects('getConfig')->with('isolation_level')->returns(null); + $connection->expects('getName')->never(); + $connection->expects('table')->with('custom_rate_limits')->returns($query); + $query->expects('where')->with('key', 'physical-key'); + $query->expects('delete')->returns(1); $this->assertTrue( (new DatabaseStore($connections, 'limiter', 'custom_rate_limits'))->clear('physical-key') @@ -418,17 +410,17 @@ public function testPostgresMutationAllowsDefaultIsolation(): void public function testMysqlMutationDoesNotInspectPostgresIsolationConfiguration(): void { - $connections = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $query = m::mock(Builder::class); - - $connections->shouldReceive('connection')->once()->with('limiter')->andReturn($connection); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('getDriverName')->once()->andReturn('mysql'); - $connection->shouldNotReceive('getConfig'); - $connection->shouldReceive('table')->once()->with('custom_rate_limits')->andReturn($query); - $query->shouldReceive('where')->once()->with('key', 'physical-key')->andReturnSelf(); - $query->shouldReceive('delete')->once()->andReturn(1); + $connections = Double::for(ConnectionResolverInterface::class)->strict(); + $connection = Double::for(Connection::class)->strict(); + $query = Double::for(Builder::class)->strict(); + + $connections->expects('connection')->with('limiter')->returns($connection); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('getDriverName')->returns('mysql'); + $connection->expects('getConfig')->never(); + $connection->expects('table')->with('custom_rate_limits')->returns($query); + $query->expects('where')->with('key', 'physical-key'); + $query->expects('delete')->returns(1); $this->assertTrue( (new DatabaseStore($connections, 'limiter', 'custom_rate_limits'))->clear('physical-key') @@ -438,15 +430,15 @@ public function testMysqlMutationDoesNotInspectPostgresIsolationConfiguration(): #[DataProvider('mutatingOperations')] public function testMutatingOperationsRejectAnActiveTransactionBeforeLimiterSql(string $operation): void { - $connections = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - - $connections->shouldReceive('connection')->once()->with('limiter')->andReturn($connection); - $connection->shouldReceive('transactionLevel')->once()->andReturn(1); - $connection->shouldNotReceive('transaction'); - $connection->shouldNotReceive('table'); - $connection->shouldNotReceive('getDriverName'); - $connection->shouldNotReceive('scalar'); + $connections = Double::for(ConnectionResolverInterface::class)->strict(); + $connection = Double::for(Connection::class)->strict(); + + $connections->expects('connection')->with('limiter')->returns($connection); + $connection->expects('transactionLevel')->returns(1); + $connection->expects('transaction')->never(); + $connection->expects('table')->never(); + $connection->expects('getDriverName')->never(); + $connection->expects('scalar')->never(); $store = new DatabaseStore($connections, 'limiter', 'custom_rate_limits'); diff --git a/tests/RateLimiter/InitializeSwooleTablesTest.php b/tests/RateLimiter/InitializeSwooleTablesTest.php index 81d1e267f2..0b8cbc33f9 100644 --- a/tests/RateLimiter/InitializeSwooleTablesTest.php +++ b/tests/RateLimiter/InitializeSwooleTablesTest.php @@ -10,10 +10,13 @@ use Hypervel\RateLimiter\Swoole\TableManager; use Hypervel\RateLimiter\Swoole\TableState; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class InitializeSwooleTablesTest extends TestCase { + use VerifiesDoubles; + public function testInitializesEverySwooleStoreAndSealsTheTableManager(): void { $config = new Repository([ @@ -25,10 +28,10 @@ public function testInitializesEverySwooleStoreAndSealsTheTableManager(): void ], ], ]); - $tables = m::mock(TableManager::class); - $tables->shouldReceive('get')->once()->with('first')->andReturn(m::mock(TableState::class)); - $tables->shouldReceive('get')->once()->with('second')->andReturn(m::mock(TableState::class)); - $tables->shouldReceive('seal')->once(); + $tables = Double::for(TableManager::class)->strict(); + $tables->expects('get')->with('first')->returns(Double::for(TableState::class)->strict()); + $tables->expects('get')->with('second')->returns(Double::for(TableState::class)->strict()); + $tables->expects('seal'); (new InitializeSwooleTables($config, $tables))->handle(new BeforeServerStart('server')); } diff --git a/tests/RateLimiter/RateLimiterServiceProviderTest.php b/tests/RateLimiter/RateLimiterServiceProviderTest.php index eeb9c76408..e2d5d56f03 100644 --- a/tests/RateLimiter/RateLimiterServiceProviderTest.php +++ b/tests/RateLimiter/RateLimiterServiceProviderTest.php @@ -13,11 +13,14 @@ use Hypervel\RateLimiter\RateLimiterServiceProvider; use Hypervel\Support\DefaultProviders; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Swoole\Server as SwooleServer; class RateLimiterServiceProviderTest extends TestCase { + use VerifiesDoubles; + public function testRateLimiterIsARequiredFrameworkProvider(): void { $this->assertContains( @@ -28,26 +31,26 @@ public function testRateLimiterIsARequiredFrameworkProvider(): void public function testLifecycleListenersAreResolvedAtEventTime(): void { - $events = m::mock(Dispatcher::class); + $events = Double::for(Dispatcher::class)->strict(); $listeners = []; - $events->shouldReceive('listen') - ->twice() - ->andReturnUsing(function (mixed $event, mixed $listener) use (&$listeners): void { + $events->expects('listen') + ->times(2) + ->resolves(function (mixed $event, mixed $listener) use (&$listeners): void { $listeners[$event] = $listener; }); - $tables = m::mock(InitializeSwooleTables::class); - $timers = m::mock(RegisterPruneTimer::class); - $application = m::mock(Application::class); - $application->shouldReceive('make')->once()->with('events')->andReturn($events); - $application->shouldReceive('make')->once()->with(InitializeSwooleTables::class)->andReturn($tables); - $application->shouldReceive('make')->once()->with(RegisterPruneTimer::class)->andReturn($timers); + $tables = Double::for(InitializeSwooleTables::class)->strict(); + $timers = Double::for(RegisterPruneTimer::class)->strict(); + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('make')->with('events')->returns($events); + $application->expects('make')->with(InitializeSwooleTables::class)->returns($tables); + $application->expects('make')->with(RegisterPruneTimer::class)->returns($timers); $beforeServerStart = new BeforeServerStart('server'); - $server = m::mock(SwooleServer::class); + $server = Double::for(SwooleServer::class)->strict(); $afterWorkerStart = new AfterWorkerStart($server, 0); - $tables->shouldReceive('handle')->once()->with($beforeServerStart); - $timers->shouldReceive('handle')->once()->with($afterWorkerStart); + $tables->expects('handle')->with($beforeServerStart); + $timers->expects('handle')->with($afterWorkerStart); - (new RateLimiterServiceProvider($application))->boot(); + (new RateLimiterServiceProvider($application->instance()))->boot(); $listeners[BeforeServerStart::class]($beforeServerStart); $listeners[AfterWorkerStart::class]($afterWorkerStart); diff --git a/tests/RateLimiter/RedisStoreTest.php b/tests/RateLimiter/RedisStoreTest.php index ecf8feee15..58f7c1d412 100644 --- a/tests/RateLimiter/RedisStoreTest.php +++ b/tests/RateLimiter/RedisStoreTest.php @@ -13,12 +13,18 @@ use Hypervel\RateLimiter\SlidingWindow; use Hypervel\Redis\RedisConnection; use Hypervel\Redis\RedisProxy; +use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; +use Redis; use UnexpectedValueException; class RedisStoreTest extends TestCase { + use VerifiesDoubles; + public function testFixedWindowUsesOneKeyAndCanonicalArguments(): void { $captured = []; @@ -98,16 +104,16 @@ public function testGroupUsesOneScriptAndPreservesRepeatedKeys(): void public function testClusterReusesOneConnectionAndStopsAtTheFirstDenialInEitherPass(): void { foreach ([false, true] as $denyDuringConsume) { - $redis = m::mock(RedisFactory::class); - $proxy = m::mock(RedisProxy::class); - $connection = m::mock(RedisConnection::class); - $redis->shouldReceive('connection')->once()->with('limiter')->andReturn($proxy); - $proxy->shouldReceive('withConnection')->once()->with(m::type('callable'), false) - ->andReturnUsing(static fn (callable $callback): mixed => $callback($connection)); - $connection->shouldReceive('isCluster')->once()->andReturnTrue(); + $redis = Double::for(RedisFactory::class)->strict(); + $proxy = Double::for(RedisProxy::class)->strict(); + $connection = Double::for(RedisConnection::class)->strict(); + $redis->expects('connection')->with('limiter')->returns($proxy); + $proxy->expects('withConnection')->with(Argument::type('callable'), false) + ->resolves(static fn (callable $callback): mixed => $callback($connection)); + $connection->expects('isCluster')->returns(true); $operations = []; - $connection->shouldReceive('evalWithShaCache')->times($denyDuringConsume ? 4 : 2) - ->andReturnUsing(static function (string $script, array $keys, array $arguments) use (&$operations, $denyDuringConsume): array { + $connection->expects('evalWithShaCache')->times($denyDuringConsume ? 4 : 2) + ->resolves(static function (string $script, array $keys, array $arguments) use (&$operations, $denyDuringConsume): array { $operations[] = [$arguments[0], $keys[0]]; $denied = $keys[0] === 'tenant' && (! $denyDuringConsume || $arguments[0] === 'consume'); @@ -169,35 +175,33 @@ public function testMalformedTuplesFailExplicitly(): void public function testClearDeletesThePhysicalKeyOnTheConfiguredConnection(): void { - $redis = m::mock(RedisFactory::class); - $proxy = m::mock(RedisProxy::class); - $connection = m::mock(RedisConnection::class); + $redis = Double::for(RedisFactory::class)->strict(); + $proxy = Double::for(RedisProxy::class)->strict(); + $client = Double::for(Redis::class)->strict(); + $connection = (new PhpRedisConnectionStub)->setActiveConnection($client)->shouldTransform(false); - $redis->shouldReceive('connection')->once()->with('limiter')->andReturn($proxy); - $proxy->shouldReceive('withConnection') - ->once() - ->with(m::type('callable'), false) - ->andReturnUsing(static fn (callable $callback): mixed => $callback($connection)); - $connection->shouldReceive('del')->once()->with('physical-key')->andReturn(1); + $redis->expects('connection')->with('limiter')->returns($proxy); + $proxy->expects('withConnection') + ->with(Argument::type('callable'), false) + ->resolves(static fn (callable $callback): mixed => $callback($connection)); + $client->expects('del')->with('physical-key')->returns(1); $this->assertTrue((new RedisStore($redis, 'limiter'))->clear('physical-key')); } private function store(mixed $response, array &$captured): RedisStore { - $redis = m::mock(RedisFactory::class); - $proxy = m::mock(RedisProxy::class); - $connection = m::mock(RedisConnection::class); - $connection->shouldReceive('isCluster')->andReturnFalse()->byDefault(); - - $redis->shouldReceive('connection')->once()->with('limiter')->andReturn($proxy); - $proxy->shouldReceive('withConnection') - ->once() - ->with(m::type('callable'), false) - ->andReturnUsing(static fn (callable $callback): mixed => $callback($connection)); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturnUsing(static function (string $script, array $keys, array $arguments) use ($response, &$captured): mixed { + $redis = Double::for(RedisFactory::class)->strict(); + $proxy = Double::for(RedisProxy::class)->strict(); + $connection = Double::for(RedisConnection::class)->strict(); + $connection->allows('isCluster')->returns(false); + + $redis->expects('connection')->with('limiter')->returns($proxy); + $proxy->expects('withConnection') + ->with(Argument::type('callable'), false) + ->resolves(static fn (callable $callback): mixed => $callback($connection)); + $connection->expects('evalWithShaCache') + ->resolves(static function (string $script, array $keys, array $arguments) use ($response, &$captured): mixed { $captured = compact('keys', 'arguments'); return $response; diff --git a/tests/RateLimiter/RegisterPruneTimerTest.php b/tests/RateLimiter/RegisterPruneTimerTest.php index d78f45686a..d98f25fb3a 100644 --- a/tests/RateLimiter/RegisterPruneTimerTest.php +++ b/tests/RateLimiter/RegisterPruneTimerTest.php @@ -14,7 +14,8 @@ use Hypervel\RateLimiter\SwooleStore; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Server as SwooleServer; @@ -22,22 +23,24 @@ class RegisterPruneTimerTest extends TestCase { + use VerifiesDoubles; + public function testRegistersPruneTimersForEverySwooleStoreOnWorkerZero(): void { - $firstStore = m::mock(SwooleStore::class); - $firstStore->shouldReceive('maintain')->once()->andReturn(2); - $secondStore = m::mock(SwooleStore::class); - $secondStore->shouldReceive('maintain')->once()->andReturn(3); - $rateLimiter = m::mock(RateLimiter::class); - $rateLimiter->shouldReceive('store')->once()->with('first')->andReturn($this->limiter($firstStore)); - $rateLimiter->shouldReceive('store')->once()->with('second')->andReturn($this->limiter($secondStore)); + $firstStore = Double::for(SwooleStore::class)->strict(); + $firstStore->expects('maintain')->returns(2); + $secondStore = Double::for(SwooleStore::class)->strict(); + $secondStore->expects('maintain')->returns(3); + $rateLimiter = Double::for(RateLimiter::class, override: true)->strict(); + $rateLimiter->expects('store')->with('first')->returns($this->limiter($firstStore)); + $rateLimiter->expects('store')->with('second')->returns($this->limiter($secondStore)); $timer = new FakeRateLimiterTimer; (new RegisterPruneTimer($this->config([ 'first' => ['driver' => 'swoole', 'prune_interval' => 5], 'redis' => ['driver' => 'redis'], 'second' => ['driver' => 'swoole', 'prune_interval' => 30], - ]), $rateLimiter, $timer))->handle($this->workerEvent(workerId: 0)); + ]), $rateLimiter->instance(), $timer))->handle($this->workerEvent(workerId: 0)); $this->assertSame([5.0, 30.0], array_column($timer->ticks, 'seconds')); $this->assertSame(2, $timer->ticks[0]['callback']()); @@ -48,7 +51,7 @@ public function testDoesNotRegisterATimerOnOtherWorkers(): void { $timer = new FakeRateLimiterTimer; - (new RegisterPruneTimer($this->config([]), m::mock(RateLimiter::class), $timer)) + (new RegisterPruneTimer($this->config([]), Double::for(RateLimiter::class, override: true)->strict()->instance(), $timer)) ->handle($this->workerEvent(workerId: 1)); $this->assertSame([], $timer->ticks); @@ -58,7 +61,7 @@ public function testDoesNotRegisterATimerOnTaskWorkers(): void { $timer = new FakeRateLimiterTimer; - (new RegisterPruneTimer($this->config([]), m::mock(RateLimiter::class), $timer)) + (new RegisterPruneTimer($this->config([]), Double::for(RateLimiter::class, override: true)->strict()->instance(), $timer)) ->handle($this->workerEvent(workerId: 0, taskworker: true)); $this->assertSame([], $timer->ticks); @@ -66,11 +69,11 @@ public function testDoesNotRegisterATimerOnTaskWorkers(): void public function testRollsBackEarlierTimersWhenRegistrationFails(): void { - $firstStore = m::mock(SwooleStore::class); - $secondStore = m::mock(SwooleStore::class); - $rateLimiter = m::mock(RateLimiter::class); - $rateLimiter->shouldReceive('store')->once()->with('first')->andReturn($this->limiter($firstStore)); - $rateLimiter->shouldReceive('store')->once()->with('second')->andReturn($this->limiter($secondStore)); + $firstStore = Double::for(SwooleStore::class)->strict(); + $secondStore = Double::for(SwooleStore::class)->strict(); + $rateLimiter = Double::for(RateLimiter::class, override: true)->strict(); + $rateLimiter->expects('store')->with('first')->returns($this->limiter($firstStore)); + $rateLimiter->expects('store')->with('second')->returns($this->limiter($secondStore)); $failure = new RuntimeException('Timer registration failed.'); $timer = new FakeRateLimiterTimer([41, $failure]); @@ -78,7 +81,7 @@ public function testRollsBackEarlierTimersWhenRegistrationFails(): void (new RegisterPruneTimer($this->config([ 'first' => ['driver' => 'swoole', 'prune_interval' => 5], 'second' => ['driver' => 'swoole', 'prune_interval' => 30], - ]), $rateLimiter, $timer))->handle($this->workerEvent(workerId: 0)); + ]), $rateLimiter->instance(), $timer))->handle($this->workerEvent(workerId: 0)); $this->fail('Expected timer registration to fail.'); } catch (RuntimeException $exception) { @@ -99,7 +102,7 @@ public function testRejectsInvalidIntervalsBeforeTimerRegistration(array $interv try { (new RegisterPruneTimer($this->config([ 'invalid' => ['driver' => 'swoole', ...$intervalConfig], - ]), m::mock(RateLimiter::class), $timer))->handle($this->workerEvent(workerId: 0)); + ]), Double::for(RateLimiter::class, override: true)->strict()->instance(), $timer))->handle($this->workerEvent(workerId: 0)); $this->fail('Expected invalid timer configuration to fail.'); } catch (InvalidArgumentException $exception) { @@ -127,15 +130,15 @@ public static function invalidIntervals(): array public function testRejectsAnInvalidLaterStoreBeforeRegisteringEarlierTimers(): void { - $rateLimiter = m::mock(RateLimiter::class); - $rateLimiter->shouldNotReceive('store'); + $rateLimiter = Double::for(RateLimiter::class, override: true)->strict(); + $rateLimiter->expects('store')->never(); $timer = new FakeRateLimiterTimer; try { (new RegisterPruneTimer($this->config([ 'first' => ['driver' => 'swoole', 'prune_interval' => 5], 'second' => ['driver' => 'swoole', 'prune_interval' => 0], - ]), $rateLimiter, $timer))->handle($this->workerEvent(workerId: 0)); + ]), $rateLimiter->instance(), $timer))->handle($this->workerEvent(workerId: 0)); $this->fail('Expected invalid timer configuration to fail.'); } catch (InvalidArgumentException $exception) { @@ -162,15 +165,15 @@ private function config(array $stores): Repository private function limiter(SwooleStore $store): Limiter { - $limiter = m::mock(Limiter::class); - $limiter->shouldReceive('getStore')->once()->andReturn($store); + $limiter = Double::for(Limiter::class)->strict(); + $limiter->expects('getStore')->returns($store); return $limiter; } private function workerEvent(int $workerId, bool $taskworker = false): AfterWorkerStart { - $server = m::mock(SwooleServer::class); + $server = Double::for(SwooleServer::class)->strict(); $server->taskworker = $taskworker; return new AfterWorkerStart($server, $workerId); diff --git a/tests/RateLimiter/SwooleStoreTest.php b/tests/RateLimiter/SwooleStoreTest.php index 8c63cb2195..0bfed648a8 100644 --- a/tests/RateLimiter/SwooleStoreTest.php +++ b/tests/RateLimiter/SwooleStoreTest.php @@ -20,7 +20,9 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\RateLimiter\Fixtures\RateLimiterStoreContract; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use UnexpectedValueException; @@ -29,6 +31,7 @@ class SwooleStoreTest extends TestCase { + use VerifiesDoubles; use InteractsWithSwooleTables; use RateLimiterStoreContract; @@ -173,12 +176,11 @@ public function testPrunesEveryExpiredCollisionRowInOnePass(): void public function testPeriodicMaintenanceReportsPostPrunePressure(): void { - $logger = m::mock(LoggerInterface::class); - $logger->shouldReceive('warning') - ->once() + $logger = Double::for(LoggerInterface::class)->strict(); + $logger->expects('warning') ->with( 'Swoole rate limiter table [swoole] is nearing capacity.', - m::on(fn (array $context): bool => $context['threshold'] === 0.0010000000000000009), + Argument::satisfies(fn (array $context): bool => $context['threshold'] === 0.0010000000000000009), ); [$store] = $this->store(memoryLimitBuffer: 0.999, logger: $logger); diff --git a/tests/Redis/ConcurrencyLimiterBuilderTest.php b/tests/Redis/ConcurrencyLimiterBuilderTest.php index d4f7a672a3..8176c57ee1 100644 --- a/tests/Redis/ConcurrencyLimiterBuilderTest.php +++ b/tests/Redis/ConcurrencyLimiterBuilderTest.php @@ -4,13 +4,22 @@ namespace Hypervel\Tests\Redis; +use Hypervel\Container\Container; use Hypervel\Contracts\Limiters\LimiterTimeoutException; use Hypervel\Redis\Limiters\ConcurrencyLimiterBuilder; +use Hypervel\Redis\Pool\PoolManager; +use Hypervel\Redis\Pool\RedisPool; use Hypervel\Redis\RedisConnection; use Hypervel\Redis\RedisProxy; +use Hypervel\Redis\RedisSentinelFactory; +use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; +use Redis; use RuntimeException; use Swoole\Coroutine\CanceledException; use Throwable; @@ -23,6 +32,8 @@ */ class ConcurrencyLimiterBuilderTest extends TestCase { + use VerifiesDoubles; + public function testLimitSetsMaxLocks(): void { $builder = $this->createBuilder(); @@ -86,20 +97,16 @@ public function testDefaultSleepIs250Milliseconds(): void public function testThenExecutesCallbackWhenLockAcquired(): void { - $redis = $this->mockRedis(); + [$redis, $client] = $this->createRedis(); // ConcurrencyLimiter::acquire() Lua script returns a slot name $this->expectSlotClaim($redis, 'test-key1'); // ConcurrencyLimiter::release() called after callback - $redis->shouldReceive('eval') - ->once() - ->withArgs(function (string $script, int $numKeys, string $key, string $id): bool { - $this->assertSame(1, $numKeys); - $this->assertSame('test-key1', $key); - - return true; - }) - ->andReturn(1); + $client->expects('eval') + ->with(Argument::any(), Argument::satisfies( + static fn (array $arguments): bool => count($arguments) === 2 && $arguments[0] === 'test-key1', + ), 1) + ->returns(1); $builder = new ConcurrencyLimiterBuilder($redis, 'test-key'); $builder->limit(5)->block(0); @@ -113,13 +120,12 @@ public function testThenExecutesCallbackWhenLockAcquired(): void public function testThenPropagatesReleaseFailureAfterSuccessfulCallback(): void { - $redis = $this->mockRedis(); + [$redis, $client] = $this->createRedis(); $releaseException = new RuntimeException('release failed'); $this->expectSlotClaim($redis, 'test-key1'); - $redis->shouldReceive('eval') - ->once() - ->andThrow($releaseException); + $client->expects('eval') + ->throws($releaseException); $builder = new ConcurrencyLimiterBuilder($redis, 'test-key'); $builder->limit(5)->block(0); @@ -138,7 +144,7 @@ public function testThenPropagatesReleaseFailureAfterSuccessfulCallback(): void #[TestWith(['wrapped cancellation'])] public function testThenPreservesCallbackFailureWhenReleaseAlsoFails(string $kind): void { - $redis = $this->mockRedis(); + [$redis, $client] = $this->createRedis(); $callbackException = new RuntimeException('callback failed'); $releaseException = match ($kind) { 'direct cancellation' => new CanceledException, @@ -147,9 +153,8 @@ public function testThenPreservesCallbackFailureWhenReleaseAlsoFails(string $kin }; $this->expectSlotClaim($redis, 'test-key1'); - $redis->shouldReceive('eval') - ->once() - ->andThrow($releaseException); + $client->expects('eval') + ->throws($releaseException); $builder = new ConcurrencyLimiterBuilder($redis, 'test-key'); $builder->limit(5)->block(0); @@ -169,7 +174,7 @@ public function testThenPreservesCallbackFailureWhenReleaseAlsoFails(string $kin public function testThenCallsFailureCallbackOnTimeout(): void { - $redis = $this->mockRedis(); + [$redis] = $this->createRedis(); // ConcurrencyLimiter::acquire() always fails $this->expectSlotClaim($redis, false); @@ -193,7 +198,7 @@ function (LimiterTimeoutException $e) use (&$failureCalled) { public function testThenThrowsExceptionWithoutFailureCallback(): void { - $redis = $this->mockRedis(); + [$redis] = $this->createRedis(); // ConcurrencyLimiter::acquire() always fails $this->expectSlotClaim($redis, false); @@ -209,7 +214,7 @@ public function testThenThrowsExceptionWithoutFailureCallback(): void public function testAcquireReturnsOwnedLease(): void { - $redis = $this->mockRedis(); + [$redis] = $this->createRedis(); $this->expectSlotClaim($redis, 'test-key1'); $builder = new ConcurrencyLimiterBuilder($redis, 'test-key'); @@ -222,11 +227,10 @@ public function testAcquireReturnsOwnedLease(): void public function testThenDoesNotRouteCallbackTimeoutExceptionToFailureCallback(): void { - $redis = $this->mockRedis(); + [$redis, $client] = $this->createRedis(); $this->expectSlotClaim($redis, 'test-key1'); - $redis->shouldReceive('eval') - ->once() - ->andReturn(1); + $client->expects('eval') + ->returns(1); $builder = new ConcurrencyLimiterBuilder($redis, 'test-key'); $builder->limit(5)->block(0); @@ -270,33 +274,45 @@ public function testFluentChaining(): void */ private function createBuilder(): ConcurrencyLimiterBuilder { - return new ConcurrencyLimiterBuilder($this->mockRedis(), 'test-key'); + return new ConcurrencyLimiterBuilder(Double::for(RedisProxy::class)->strict(), 'test-key'); } /** - * Create a mock RedisProxy. + * Create a proxy that borrows a connection wrapping the native client. + * + * @return array{DoubleInterface&RedisProxy, DoubleInterface&Redis} */ - private function mockRedis(): m\MockInterface|RedisProxy + private function createRedis(): array { - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('isCluster')->byDefault()->andReturnFalse(); - - return $redis; + $client = Double::for(Redis::class)->strict(); + $client->allows('getMode')->returns(Redis::ATOMIC); + $connection = Double::for((new PhpRedisConnectionStub)->setActiveConnection($client))->passthru(); + $connection->allows('release'); + $pool = Double::for(RedisPool::class)->strict(); + $pool->allows('borrow')->returns($connection); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('limiter')->returns($pool); + $redis = Double::for(new RedisProxy( + $poolManager, + 'limiter', + new RedisSentinelFactory, + ))->passthru(); + $redis->allows('isCluster')->returns(false); + + return [$redis, $client]; } /** * Expect a slot-claim script evaluation on one held Redis connection. */ - private function expectSlotClaim(m\MockInterface|RedisProxy $redis, false|string $result): void + private function expectSlotClaim(RedisProxy&DoubleInterface $redis, false|string $result): void { - $connection = m::mock(RedisConnection::class); + $connection = Double::for(RedisConnection::class)->strict(); - $redis->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback): mixed => $callback($connection)); + $redis->expects('withConnection') + ->resolves(fn (callable $callback): mixed => $callback($connection)); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn($result); + $connection->expects('evalWithShaCache') + ->returns($result); } } diff --git a/tests/Redis/DurationLimiterBuilderTest.php b/tests/Redis/DurationLimiterBuilderTest.php index 7687ffb109..b4368aae87 100644 --- a/tests/Redis/DurationLimiterBuilderTest.php +++ b/tests/Redis/DurationLimiterBuilderTest.php @@ -9,7 +9,9 @@ use Hypervel\Redis\RedisConnection; use Hypervel\Redis\RedisProxy; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; /** * Tests for DurationLimiterBuilder. @@ -19,6 +21,8 @@ */ class DurationLimiterBuilderTest extends TestCase { + use VerifiesDoubles; + public function testAllowSetsMaxLocks(): void { $builder = $this->createBuilder(); @@ -153,24 +157,22 @@ private function createBuilder(): DurationLimiterBuilder /** * Create a mock RedisProxy. */ - private function mockRedis(): m\MockInterface|RedisProxy + private function mockRedis(): RedisProxy&DoubleInterface { - return m::mock(RedisProxy::class); + return Double::for(RedisProxy::class)->strict(); } /** * Expect a script evaluation on one held Redis connection. */ - private function expectEvaluation(m\MockInterface|RedisProxy $redis, mixed $result): void + private function expectEvaluation(RedisProxy&DoubleInterface $redis, mixed $result): void { - $connection = m::mock(RedisConnection::class); + $connection = Double::for(RedisConnection::class)->strict(); - $redis->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback): mixed => $callback($connection)); + $redis->expects('withConnection') + ->resolves(fn (callable $callback): mixed => $callback($connection)); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn($result); + $connection->expects('evalWithShaCache') + ->returns($result); } } diff --git a/tests/Redis/DurationLimiterTest.php b/tests/Redis/DurationLimiterTest.php index 10d79816d7..c31171ee12 100644 --- a/tests/Redis/DurationLimiterTest.php +++ b/tests/Redis/DurationLimiterTest.php @@ -4,14 +4,23 @@ namespace Hypervel\Tests\Redis; +use Hypervel\Container\Container; use Hypervel\Contracts\Limiters\LimiterTimeoutException; use Hypervel\Redis\Limiters\DurationLimiter; +use Hypervel\Redis\Pool\PoolManager; +use Hypervel\Redis\Pool\RedisPool; use Hypervel\Redis\RedisConnection; use Hypervel\Redis\RedisProxy; +use Hypervel\Redis\RedisSentinelFactory; use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Sleep; +use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; +use Redis; /** * Tests for DurationLimiter. @@ -20,6 +29,8 @@ */ class DurationLimiterTest extends TestCase { + use VerifiesDoubles; + public function testAcquireSucceedsWhenBelowLimit(): void { $redis = $this->mockRedis(); @@ -123,17 +134,22 @@ function (string $script, array $keys, array $arguments): bool { public function testClearDeletesKey(): void { - $redis = $this->mockRedis(); - $redis->shouldReceive('del') - ->once() - ->with('test-key') - ->andReturn(1); - - $limiter = new DurationLimiter($redis, 'test-key', 5, 60); - - $limiter->clear(); + $client = Double::for(Redis::class)->strict(); + $client->allows('getMode')->returns(Redis::ATOMIC); + $client->expects('del')->with('test-key')->returns(1); + $connection = Double::for((new PhpRedisConnectionStub)->setActiveConnection($client))->passthru(); + $connection->allows('release'); + $pool = Double::for(RedisPool::class)->strict(); + $pool->allows('borrow')->returns($connection); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('limiter')->returns($pool); + $redis = new RedisProxy( + $poolManager, + 'limiter', + new RedisSentinelFactory, + ); - // Mockery verifies del() was called + (new DurationLimiter($redis, 'test-key', 5, 60))->clear(); } public function testBlockExecutesCallbackOnSuccess(): void @@ -156,14 +172,14 @@ public function testBlockExecutesCallbackOnSuccess(): void public function testBlockThrowsExceptionAfterTimeout(): void { $redis = $this->mockRedis(); - $connection = m::mock(RedisConnection::class); + $connection = Double::for(RedisConnection::class)->strict(); - $redis->shouldReceive('withConnection') - ->andReturnUsing(fn (callable $callback): mixed => $callback($connection)); + $redis->allows('withConnection') + ->resolves(fn (callable $callback): mixed => $callback($connection)); // Always fail to acquire - $connection->shouldReceive('evalWithShaCache') - ->andReturn([0, time() + 60, '6']); + $connection->allows('evalWithShaCache') + ->returns([0, time() + 60, '6']); $limiter = new DurationLimiter($redis, 'test-key', 5, 60); @@ -178,11 +194,11 @@ public function testBlockCanAcquireAtTheDeadlineWithAShorterFinalSleep(): void Sleep::fake(syncWithCarbon: true); CarbonImmutable::setTestNow(CarbonImmutable::now()); $redis = $this->mockRedis(); - $connection = m::mock(RedisConnection::class); - $redis->shouldReceive('withConnection') - ->andReturnUsing(fn (callable $callback): mixed => $callback($connection)); - $connection->shouldReceive('evalWithShaCache')->times(4) - ->andReturn([0, 0, '1'], [0, 0, '1'], [0, 0, '1'], [1, 10, '1']); + $connection = Double::for(RedisConnection::class)->strict(); + $redis->allows('withConnection') + ->resolves(fn (callable $callback): mixed => $callback($connection)); + $connection->expects('evalWithShaCache')->times(4) + ->returns([0, 0, '1'], [0, 0, '1'], [0, 0, '1'], [1, 10, '1']); $limiter = new DurationLimiter($redis, 'test-key', 1, 10); @@ -201,31 +217,30 @@ public function testBlockCanAcquireAtTheDeadlineWithAShorterFinalSleep(): void /** * Create a mock RedisProxy. */ - private function mockRedis(): m\MockInterface|RedisProxy + private function mockRedis(): RedisProxy&DoubleInterface { - return m::mock(RedisProxy::class); + return Double::for(RedisProxy::class)->strict(); } /** * Expect a script evaluation on one held Redis connection. */ private function expectEvaluation( - m\MockInterface|RedisProxy $redis, + RedisProxy&DoubleInterface $redis, mixed $result, ?callable $assertion = null, ): void { - $connection = m::mock(RedisConnection::class); + $connection = Double::for(RedisConnection::class)->strict(); - $redis->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback): mixed => $callback($connection)); + $redis->expects('withConnection') + ->resolves(fn (callable $callback): mixed => $callback($connection)); - $expectation = $connection->shouldReceive('evalWithShaCache')->once(); + $expectation = $connection->expects('evalWithShaCache'); if ($assertion !== null) { - $expectation->withArgs($assertion); + $expectation->with(Argument::all($assertion)); } - $expectation->andReturn($result); + $expectation->returns($result); } } diff --git a/tests/Redis/Events/CommandExecutedTest.php b/tests/Redis/Events/CommandExecutedTest.php index b5395a32bb..167b3cd704 100644 --- a/tests/Redis/Events/CommandExecutedTest.php +++ b/tests/Redis/Events/CommandExecutedTest.php @@ -9,14 +9,17 @@ use Hypervel\Redis\Events\CommandFailed; use Hypervel\Redis\PhpRedisConnection; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class CommandExecutedTest extends TestCase { + use VerifiesDoubles; + public function testCommandExecutedConstructor(): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getName')->andReturn('default'); + $connection = Double::for(PhpRedisConnection::class)->strict(); + $connection->allows('getName')->returns('default'); $event = new CommandExecuted('GET', ['key1'], 0.1, $connection); @@ -29,8 +32,8 @@ public function testCommandExecutedConstructor(): void public function testCommandExecutedConnectionNameIsDerivedFromConnection(): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getName')->once()->andReturn('cache'); + $connection = Double::for(PhpRedisConnection::class)->strict(); + $connection->expects('getName')->returns('cache'); $event = new CommandExecuted('SET', ['key', 'value'], 0.5, $connection); @@ -39,8 +42,8 @@ public function testCommandExecutedConnectionNameIsDerivedFromConnection(): void public function testCommandFailedConstructor(): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getName')->andReturn('default'); + $connection = Double::for(PhpRedisConnection::class)->strict(); + $connection->allows('getName')->returns('default'); $exception = new Exception('Redis error'); $event = new CommandFailed('GET', ['key1'], $exception, $connection); @@ -55,8 +58,8 @@ public function testCommandFailedConstructor(): void public function testCommandFailedWithTime(): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getName')->andReturn('default'); + $connection = Double::for(PhpRedisConnection::class)->strict(); + $connection->allows('getName')->returns('default'); $exception = new Exception('Redis error'); $event = new CommandFailed('GET', ['key1'], $exception, $connection, 1.5); diff --git a/tests/Redis/Fixtures/CancelTlsConnection.php b/tests/Redis/Fixtures/CancelTlsConnection.php index c35a7fb780..3186fc7136 100644 --- a/tests/Redis/Fixtures/CancelTlsConnection.php +++ b/tests/Redis/Fixtures/CancelTlsConnection.php @@ -6,7 +6,7 @@ use Hypervel\Contracts\ConnectionPool\ConnectionPool; use Hypervel\Redis\PhpRedisConnection; use Hypervel\Tests\Redis\Fixtures\RespServer; -use Mockery as m; +use JMac\Testing\Double; use Swoole\Coroutine; use Swoole\Coroutine\CanceledException; use Swoole\Coroutine\Channel; @@ -51,7 +51,7 @@ try { new PhpRedisConnection( new Container, - m::mock(ConnectionPool::class), + Double::for(ConnectionPool::class)->strict(), [ 'url' => null, 'scheme' => 'tls', diff --git a/tests/Redis/Fixtures/FakeRedisClient.php b/tests/Redis/Fixtures/FakeRedisClient.php index a8aff6f662..a2c45df3b2 100644 --- a/tests/Redis/Fixtures/FakeRedisClient.php +++ b/tests/Redis/Fixtures/FakeRedisClient.php @@ -54,7 +54,7 @@ class FakeRedisClient extends Redis /** * Recorded scan calls for assertions. * - * @var array + * @var array */ private array $scanCalls = []; @@ -79,6 +79,15 @@ class FakeRedisClient extends Redis */ private array $hScanCalls = []; + /** @var array, iterator: int}>> */ + private array $sScanResults; + + /** @var array */ + private array $sScanCallIndex = []; + + /** @var list */ + private array $sScanCalls = []; + /** * Pipeline mode flag. */ @@ -227,6 +236,7 @@ class FakeRedisClient extends Redis * @param array $zCardResults Configured zCard results per key * @param array $zRemRangeByScoreResults Configured zRemRangeByScore results per key * @param array $evalShaResults Configured EVALSHA results in call order + * @param array, iterator: int}>> $sScanResults Configured SSCAN results */ public function __construct( array $scanResults = [], @@ -239,6 +249,7 @@ public function __construct( array $zCardResults = [], array $zRemRangeByScoreResults = [], array $evalShaResults = [], + array $sScanResults = [], ) { // Skip native initialization; this fake never connects to Redis. $this->scanResults = $scanResults; @@ -251,6 +262,7 @@ public function __construct( $this->zCardResults = $zCardResults; $this->zRemRangeByScoreResults = $zRemRangeByScoreResults; $this->evalShaResults = $evalShaResults; + $this->sScanResults = $sScanResults; } /** @@ -265,7 +277,7 @@ public function __construct( public function scan(int|string|null &$iterator, ?string $pattern = null, int $count = 0, ?string $type = null): array|false { // Record the call for assertions - $this->scanCalls[] = ['pattern' => $pattern, 'count' => $count]; + $this->scanCalls[] = ['iterator' => $iterator, 'pattern' => $pattern, 'count' => $count]; if (! isset($this->scanResults[$this->scanCallIndex])) { $iterator = 0; @@ -282,7 +294,7 @@ public function scan(int|string|null &$iterator, ?string $pattern = null, int $c /** * Get recorded scan calls for test assertions. * - * @return array + * @return array */ public function getScanCalls(): array { @@ -346,6 +358,38 @@ public function getHScanCallCount(): int return count($this->hScanCalls); } + /** + * Simulate SSCAN while updating its cursor by reference. + */ + public function sscan(string $key, int|string|null &$iterator, ?string $pattern = null, int $count = 0): array|false + { + $this->sScanCalls[] = compact('key', 'iterator', 'pattern', 'count'); + $index = $this->sScanCallIndex[$key] ?? 0; + $result = $this->sScanResults[$key][$index] ?? null; + $this->sScanCallIndex[$key] = $index + 1; + $iterator = $result['iterator'] ?? 0; + + return $result['members'] ?? false; + } + + /** + * Get recorded SSCAN calls. + * + * @return list + */ + public function getSScanCalls(): array + { + return $this->sScanCalls; + } + + /** + * Report the fake client's current command mode. + */ + public function getMode(): int + { + return $this->inPipeline ? Redis::PIPELINE : Redis::ATOMIC; + } + /** * Simulate getOption() for compression and prefix checks. */ @@ -650,6 +694,8 @@ public function resetFakeState(): void $this->scanCalls = []; $this->hScanCallIndex = []; $this->hScanCalls = []; + $this->sScanCallIndex = []; + $this->sScanCalls = []; $this->hLenCalls = []; $this->zRangeCallCount = 0; $this->zScanCallIndex = []; diff --git a/tests/Redis/Fixtures/PhpRedisClusterConnectionStub.php b/tests/Redis/Fixtures/PhpRedisClusterConnectionStub.php index c60a5137c1..2008c5abaa 100644 --- a/tests/Redis/Fixtures/PhpRedisClusterConnectionStub.php +++ b/tests/Redis/Fixtures/PhpRedisClusterConnectionStub.php @@ -7,8 +7,6 @@ use Hypervel\Contracts\ConnectionPool\ConnectionPool; use Hypervel\Contracts\Container\Container; use Hypervel\Redis\PhpRedisClusterConnection; -use Mockery as m; -use Redis; use RedisCluster; class PhpRedisClusterConnectionStub extends PhpRedisClusterConnection @@ -30,33 +28,40 @@ public function __construct(?Container $container = null, ?ConnectionPool $pool // Skip reconnect() — tests inject connections via setActiveConnection() } + /** + * Keep reconnection under test control. + */ public function reconnect(): bool { return true; } + /** + * Treat the injected client as healthy. + */ public function check(): bool { return true; } + /** + * Restore the injected client without opening a socket. + */ public function getActiveConnection(): static { if ($this->connection !== null) { return $this; } - // Use shouldIgnoreMissing() to prevent falling through to real RedisCluster - // methods when expectations don't match - $connection = $this->redisConnection - ?? m::mock(RedisCluster::class)->shouldIgnoreMissing(); - - $this->connection = $connection; + $this->connection = $this->redisConnection; return $this; } - public function setActiveConnection(Redis|RedisCluster $connection): static + /** + * Set the native client used by the test. + */ + public function setActiveConnection(RedisCluster $connection): static { $this->redisConnection = $connection; $this->connection = $connection; @@ -64,16 +69,6 @@ public function setActiveConnection(Redis|RedisCluster $connection): static return $this; } - /** - * Get the underlying Redis connection for test mocking. - */ - public function getConnection(): Redis|RedisCluster - { - $this->getActiveConnection(); - - return $this->connection; - } - /** * Get the connection configuration. * diff --git a/tests/Redis/Fixtures/PhpRedisConnectionStub.php b/tests/Redis/Fixtures/PhpRedisConnectionStub.php index a66abe1cbe..07b76c9629 100644 --- a/tests/Redis/Fixtures/PhpRedisConnectionStub.php +++ b/tests/Redis/Fixtures/PhpRedisConnectionStub.php @@ -7,9 +7,7 @@ use Hypervel\Contracts\ConnectionPool\ConnectionPool; use Hypervel\Contracts\Container\Container; use Hypervel\Redis\PhpRedisConnection; -use Mockery as m; use Redis; -use RedisCluster; class PhpRedisConnectionStub extends PhpRedisConnection { @@ -30,33 +28,40 @@ public function __construct(?Container $container = null, ?ConnectionPool $pool // Skip reconnect() — tests inject connections via setActiveConnection() } + /** + * Keep reconnection under test control. + */ public function reconnect(): bool { return true; } + /** + * Treat the injected client as healthy. + */ public function check(): bool { return true; } + /** + * Restore the injected client without opening a socket. + */ public function getActiveConnection(): static { if ($this->connection !== null) { return $this; } - // Use shouldIgnoreMissing() to prevent falling through to real Redis - // methods when expectations don't match (which causes "Redis server went away") - $connection = $this->redisConnection - ?? m::mock(Redis::class)->shouldIgnoreMissing(); - - $this->connection = $connection; + $this->connection = $this->redisConnection; return $this; } - public function setActiveConnection(Redis|RedisCluster $connection): static + /** + * Set the native client used by the test. + */ + public function setActiveConnection(Redis $connection): static { $this->redisConnection = $connection; $this->connection = $connection; @@ -67,7 +72,7 @@ public function setActiveConnection(Redis|RedisCluster $connection): static /** * Get the underlying Redis connection for test mocking. */ - public function getConnection(): Redis|RedisCluster + public function nativeClientForTest(): Redis { $this->getActiveConnection(); @@ -84,6 +89,9 @@ public function getConfigForTest(): array return $this->config; } + /** + * Determine whether the connection was invalidated. + */ public function isInvalidForTest(): bool { return $this->invalid; diff --git a/tests/Redis/LimiterConnectionReleaseTest.php b/tests/Redis/LimiterConnectionReleaseTest.php index 1c614be2c1..75c6e423a2 100644 --- a/tests/Redis/LimiterConnectionReleaseTest.php +++ b/tests/Redis/LimiterConnectionReleaseTest.php @@ -12,7 +12,8 @@ use Hypervel\Support\Sleep; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; #[WithConfig('database.connections.wait', [ @@ -22,6 +23,8 @@ ])] class LimiterConnectionReleaseTest extends TestCase { + use VerifiesDoubles; + #[TestWith([false])] #[TestWith([true])] public function testWaitingReturnsIdleSessionsButPreservesTransactionsAndPins(bool $funnel): void @@ -34,14 +37,14 @@ public function testWaitingReturnsIdleSessionsButPreservesTransactionsAndPins(bo $observed[] = $pool->getBorrowedCount(); }); $wait = static function () use ($funnel, $connection): void { - $redis = m::mock(RedisProxy::class); + $redis = Double::for(RedisProxy::class)->strict(); if ($funnel) { - $redis->shouldReceive('isCluster')->once()->andReturnFalse(); - $redis->shouldReceive('withConnection')->twice()->andReturn(false, 'waiting0'); + $redis->expects('isCluster')->returns(false); + $redis->expects('withConnection')->times(2)->returns(false, 'waiting0'); $limiter = new ConcurrencyLimiter($redis, 'waiting', 1, 10); } else { - $redis->shouldReceive('withConnection')->twice()->andReturn([0, time() + 10, '2'], [1, time() + 10, 1]); + $redis->expects('withConnection')->times(2)->returns([0, time() + 10, '2'], [1, time() + 10, 1]); $limiter = new DurationLimiter($redis, 'waiting', 1, 10); } diff --git a/tests/Redis/MultiExecTest.php b/tests/Redis/MultiExecTest.php index cd09db1079..f345a2ad69 100644 --- a/tests/Redis/MultiExecTest.php +++ b/tests/Redis/MultiExecTest.php @@ -4,30 +4,35 @@ namespace Hypervel\Tests\Redis; +use Hypervel\Container\Container; use Hypervel\Context\CoroutineContext; -use Hypervel\Redis\PhpRedisConnection; use Hypervel\Redis\Pool\PoolManager; use Hypervel\Redis\Pool\RedisPool; use Hypervel\Redis\RedisConnection; use Hypervel\Redis\RedisProxy; use Hypervel\Redis\RedisSentinelFactory; +use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Redis as PhpRedis; use RuntimeException; class MultiExecTest extends TestCase { + use VerifiesDoubles; + public function testPipelineWithoutCallbackReturnsInstanceForChaining(): void { - $pipelineInstance = m::mock(PhpRedis::class); + $pipelineInstance = Double::for(PhpRedis::class)->strict(); - $phpRedis = m::mock(PhpRedis::class); - $phpRedis->shouldReceive('pipeline')->once()->andReturn($pipelineInstance); + $phpRedis = Double::for(PhpRedis::class)->strict(); + $phpRedis->expects('pipeline')->returns($pipelineInstance); $connection = $this->createMockConnection($phpRedis); // Connection is stored in context and released via defer() at end of coroutine - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $redis = $this->createRedis($connection); $result = $redis->pipeline(); @@ -40,16 +45,16 @@ public function testPipelineWithCallbackExecutesAndReturnsResults(): void { $execResults = ['OK', 'OK', 'value']; - $pipelineInstance = m::mock(PhpRedis::class); - $pipelineInstance->shouldReceive('set')->twice()->andReturnSelf(); - $pipelineInstance->shouldReceive('get')->once()->andReturnSelf(); - $pipelineInstance->shouldReceive('exec')->once()->andReturn($execResults); + $pipelineInstance = Double::for(PhpRedis::class)->strict(); + $pipelineInstance->expects('set')->times(2)->returns($pipelineInstance); + $pipelineInstance->expects('get')->returns($pipelineInstance); + $pipelineInstance->expects('exec')->returns($execResults); - $phpRedis = m::mock(PhpRedis::class); - $phpRedis->shouldReceive('pipeline')->once()->andReturn($pipelineInstance); + $phpRedis = Double::for(PhpRedis::class)->strict(); + $phpRedis->expects('pipeline')->returns($pipelineInstance); $connection = $this->createMockConnection($phpRedis); - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $redis = $this->createRedis($connection); $result = $redis->pipeline(function ($pipe) { @@ -63,14 +68,14 @@ public function testPipelineWithCallbackExecutesAndReturnsResults(): void public function testPipelineWithCallbackReturnsFalseWhenExecAborts(): void { - $pipelineInstance = m::mock(PhpRedis::class); - $pipelineInstance->shouldReceive('exec')->once()->andReturnFalse(); + $pipelineInstance = Double::for(PhpRedis::class)->strict(); + $pipelineInstance->expects('exec')->returns(false); - $phpRedis = m::mock(PhpRedis::class); - $phpRedis->shouldReceive('pipeline')->once()->andReturn($pipelineInstance); + $phpRedis = Double::for(PhpRedis::class)->strict(); + $phpRedis->expects('pipeline')->returns($pipelineInstance); $connection = $this->createMockConnection($phpRedis); - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $result = $this->createRedis($connection)->pipeline(static function (): void { }); @@ -80,14 +85,14 @@ public function testPipelineWithCallbackReturnsFalseWhenExecAborts(): void public function testTransactionWithoutCallbackReturnsInstanceForChaining(): void { - $multiInstance = m::mock(PhpRedis::class); + $multiInstance = Double::for(PhpRedis::class)->strict(); - $phpRedis = m::mock(PhpRedis::class); - $phpRedis->shouldReceive('multi')->once()->andReturn($multiInstance); + $phpRedis = Double::for(PhpRedis::class)->strict(); + $phpRedis->expects('multi')->returns($multiInstance); $connection = $this->createMockConnection($phpRedis); // Connection is stored in context and released via defer() at end of coroutine - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $redis = $this->createRedis($connection); $result = $redis->transaction(); @@ -100,16 +105,16 @@ public function testTransactionWithCallbackExecutesAndReturnsResults(): void { $execResults = ['OK', 5]; - $multiInstance = m::mock(PhpRedis::class); - $multiInstance->shouldReceive('set')->once()->andReturnSelf(); - $multiInstance->shouldReceive('incr')->once()->andReturnSelf(); - $multiInstance->shouldReceive('exec')->once()->andReturn($execResults); + $multiInstance = Double::for(PhpRedis::class)->strict(); + $multiInstance->expects('set')->returns($multiInstance); + $multiInstance->expects('incr')->returns($multiInstance); + $multiInstance->expects('exec')->returns($execResults); - $phpRedis = m::mock(PhpRedis::class); - $phpRedis->shouldReceive('multi')->once()->andReturn($multiInstance); + $phpRedis = Double::for(PhpRedis::class)->strict(); + $phpRedis->expects('multi')->returns($multiInstance); $connection = $this->createMockConnection($phpRedis); - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $redis = $this->createRedis($connection); $result = $redis->transaction(function ($tx) { @@ -122,14 +127,14 @@ public function testTransactionWithCallbackExecutesAndReturnsResults(): void public function testTransactionWithCallbackReturnsFalseWhenExecAborts(): void { - $multiInstance = m::mock(PhpRedis::class); - $multiInstance->shouldReceive('exec')->once()->andReturnFalse(); + $multiInstance = Double::for(PhpRedis::class)->strict(); + $multiInstance->expects('exec')->returns(false); - $phpRedis = m::mock(PhpRedis::class); - $phpRedis->shouldReceive('multi')->once()->andReturn($multiInstance); + $phpRedis = Double::for(PhpRedis::class)->strict(); + $phpRedis->expects('multi')->returns($multiInstance); $connection = $this->createMockConnection($phpRedis); - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $result = $this->createRedis($connection)->transaction(static function (): void { }); @@ -139,18 +144,18 @@ public function testTransactionWithCallbackReturnsFalseWhenExecAborts(): void public function testPipelineWithCallbackDoesNotReleaseExistingContextConnection(): void { - $pipelineInstance = m::mock(PhpRedis::class); - $pipelineInstance->shouldReceive('exec')->once()->andReturn([]); + $pipelineInstance = Double::for(PhpRedis::class)->strict(); + $pipelineInstance->expects('exec')->returns([]); - $phpRedis = m::mock(PhpRedis::class); - $phpRedis->shouldReceive('pipeline')->once()->andReturn($pipelineInstance); + $phpRedis = Double::for(PhpRedis::class)->strict(); + $phpRedis->expects('pipeline')->returns($pipelineInstance); $connection = $this->createMockConnection($phpRedis); $redis = $this->createRedis($connection); // Set up existing connection in context BEFORE the pipeline call CoroutineContext::set($this->contextKey($redis), $connection); - $connection->shouldNotReceive('release'); + $connection->expects('release')->never(); $redis->pipeline(function ($pipe) { // empty callback @@ -159,16 +164,16 @@ public function testPipelineWithCallbackDoesNotReleaseExistingContextConnection( public function testPipelineWithCallbackInvalidatesAndReleasesOnException(): void { - $pipelineInstance = m::mock(PhpRedis::class); + $pipelineInstance = Double::for(PhpRedis::class)->strict(); // exec throws exception - $pipelineInstance->shouldReceive('exec')->once()->andThrow(new RuntimeException('Redis error')); + $pipelineInstance->expects('exec')->throws(new RuntimeException('Redis error')); - $phpRedis = m::mock(PhpRedis::class); - $phpRedis->shouldReceive('pipeline')->once()->andReturn($pipelineInstance); + $phpRedis = Double::for(PhpRedis::class)->strict(); + $phpRedis->expects('pipeline')->returns($pipelineInstance); $connection = $this->createMockConnection($phpRedis); - $connection->shouldReceive('invalidate')->once(); - $connection->shouldReceive('release')->once(); + $connection->expects('invalidate'); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -182,19 +187,19 @@ public function testPipelineWithCallbackInvalidatesAndReleasesOnException(): voi public function testTransactionWithCallbackDoesNotReleaseExistingContextConnection(): void { - $multiInstance = m::mock(PhpRedis::class); - $multiInstance->shouldReceive('exec')->once()->andReturn([]); + $multiInstance = Double::for(PhpRedis::class)->strict(); + $multiInstance->expects('exec')->returns([]); - $phpRedis = m::mock(PhpRedis::class); - $phpRedis->shouldReceive('multi')->once()->andReturn($multiInstance); + $phpRedis = Double::for(PhpRedis::class)->strict(); + $phpRedis->expects('multi')->returns($multiInstance); $connection = $this->createMockConnection($phpRedis); $redis = $this->createRedis($connection); // Set up existing connection in context BEFORE the transaction call CoroutineContext::set($this->contextKey($redis), $connection); - $connection->shouldNotReceive('release'); - $connection->shouldReceive('clearWatchState')->once(); + $connection->expects('release')->never(); + $connection->expects('clearWatchState'); $redis->transaction(function ($tx) { // empty callback @@ -203,15 +208,15 @@ public function testTransactionWithCallbackDoesNotReleaseExistingContextConnecti public function testTransactionWithCallbackInvalidatesAndReleasesOnException(): void { - $multiInstance = m::mock(PhpRedis::class); - $multiInstance->shouldReceive('exec')->once()->andThrow(new RuntimeException('Transaction failed')); + $multiInstance = Double::for(PhpRedis::class)->strict(); + $multiInstance->expects('exec')->throws(new RuntimeException('Transaction failed')); - $phpRedis = m::mock(PhpRedis::class); - $phpRedis->shouldReceive('multi')->once()->andReturn($multiInstance); + $phpRedis = Double::for(PhpRedis::class)->strict(); + $phpRedis->expects('multi')->returns($multiInstance); $connection = $this->createMockConnection($phpRedis); - $connection->shouldReceive('invalidate')->once(); - $connection->shouldReceive('release')->once(); + $connection->expects('invalidate'); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -226,15 +231,15 @@ public function testTransactionWithCallbackInvalidatesAndReleasesOnException(): public function testTransactionWithCallbackInvalidatesExistingContextConnectionOnException(): void { $exception = new RuntimeException('Transaction failed'); - $multiInstance = m::mock(PhpRedis::class); - $multiInstance->shouldReceive('exec')->once()->andThrow($exception); + $multiInstance = Double::for(PhpRedis::class)->strict(); + $multiInstance->expects('exec')->throws($exception); - $phpRedis = m::mock(PhpRedis::class); - $phpRedis->shouldReceive('multi')->once()->andReturn($multiInstance); + $phpRedis = Double::for(PhpRedis::class)->strict(); + $phpRedis->expects('multi')->returns($multiInstance); $connection = $this->createMockConnection($phpRedis); - $connection->shouldReceive('invalidate')->once(); - $connection->shouldNotReceive('release'); + $connection->expects('invalidate'); + $connection->expects('release')->never(); $redis = $this->createRedis($connection); CoroutineContext::set($this->contextKey($redis), $connection); @@ -252,22 +257,20 @@ public function testTransactionWithCallbackInvalidatesExistingContextConnectionO ); } - public function testShouldTransformIsResetWhenConnectionReleasedAfterCallback(): void + public function testPipelineEnablesTransformationAndReleasesConnectionAfterCallback(): void { $execResults = ['OK']; - $pipelineInstance = m::mock(PhpRedis::class); - $pipelineInstance->shouldReceive('set')->once()->andReturnSelf(); - $pipelineInstance->shouldReceive('exec')->once()->andReturn($execResults); + $pipelineInstance = Double::for(PhpRedis::class)->strict(); + $pipelineInstance->expects('set')->returns($pipelineInstance); + $pipelineInstance->expects('exec')->returns($execResults); - $phpRedis = m::mock(PhpRedis::class); - $phpRedis->shouldReceive('pipeline')->once()->andReturn($pipelineInstance); + $phpRedis = Double::for(PhpRedis::class)->strict(); + $phpRedis->expects('pipeline')->returns($pipelineInstance); $connection = $this->createMockConnection($phpRedis); - // Verify shouldTransform is called with true when getting the connection, - // and that release() is called (which resets shouldTransform to false internally) - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -275,43 +278,35 @@ public function testShouldTransformIsResetWhenConnectionReleasedAfterCallback(): $pipe->set('key', 'value'); }); - // After pipeline callback completes, connection was released. - // The connection should no longer be in context. + $connection->received('shouldTransform')->with(true); $this->assertNull(CoroutineContext::get($this->contextKey($redis))); } /** * Create a mock RedisConnection. */ - private function createMockConnection(m\MockInterface $phpRedis): m\MockInterface|RedisConnection + private function createMockConnection(PhpRedis&DoubleInterface $phpRedis): RedisConnection&DoubleInterface { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getConnection')->andReturn($connection); - $connection->shouldReceive('getEventDispatcher')->andReturnNull(); - $connection->shouldReceive('shouldTransform')->andReturnSelf(); - - // Forward method calls to the phpRedis mock - $connection->shouldReceive('pipeline')->andReturnUsing(fn () => $phpRedis->pipeline()); - $connection->shouldReceive('multi')->andReturnUsing(fn () => $phpRedis->multi()); + $phpRedis->allows('getMode')->returns(PhpRedis::ATOMIC); - return $connection; + return Double::for((new PhpRedisConnectionStub)->setActiveConnection($phpRedis))->passthru(); } /** * Create a RedisProxy instance with the given mock connection. */ - private function createRedis(m\MockInterface|RedisConnection $connection): RedisProxy + private function createRedis(RedisConnection&DoubleInterface $connection): RedisProxy { - $pool = m::mock(RedisPool::class); - $pool->shouldReceive('borrow')->andReturn($connection); + $pool = Double::for(RedisPool::class)->strict(); + $pool->allows('borrow')->returns($connection); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('pool')->with('default')->andReturn($pool); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('default')->returns($pool); return new RedisProxy( $poolManager, 'default', - m::mock(RedisSentinelFactory::class), + Double::for(RedisSentinelFactory::class)->strict(), ); } diff --git a/tests/Redis/Operations/FlushByPatternTest.php b/tests/Redis/Operations/FlushByPatternTest.php index bd53a0e3fd..4551682cad 100644 --- a/tests/Redis/Operations/FlushByPatternTest.php +++ b/tests/Redis/Operations/FlushByPatternTest.php @@ -4,14 +4,13 @@ namespace Hypervel\Tests\Redis\Operations; +use Closure; use Hypervel\Redis\Exceptions\InvalidRedisConnectionException; use Hypervel\Redis\Operations\FlushByPattern; -use Hypervel\Redis\RedisConnection; use Hypervel\Tests\Redis\Fixtures\FakeRedisClient; use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use Redis; use RedisException; /** @@ -20,85 +19,70 @@ class FlushByPatternTest extends TestCase { /** - * Create a RedisConnection wrapping a FakeRedisClient for testing. - * - * Returns both the connection (as a partial mock) and the client so tests - * can set up unlink expectations while using FakeRedisClient for scan behavior. - * - * @return array{MockInterface&PhpRedisConnectionStub, FakeRedisClient} + * Create a raw connection around the fake client. */ - private function createConnectionWithClient(FakeRedisClient $client): array + private function createConnection(FlushingRedisClient $client): PhpRedisConnectionStub { - // Create a real stub, then wrap it in a partial mock to allow shouldReceive - $stub = new PhpRedisConnectionStub; - $stub->setActiveConnection($client); - - // Create a mock that delegates unknown methods to the stub - $connection = m::mock($stub)->makePartial(); - - return [$connection, $client]; + return (new PhpRedisConnectionStub)->setActiveConnection($client); } public function testFlushRejectsTransformedConnectionsBeforeDeleting(): void { - [$connection] = $this->createConnectionWithClient(new FakeRedisClient); - $connection->shouldReceive('getShouldTransform')->once()->andReturnTrue(); - $connection->shouldNotReceive('unlink'); + $client = new FlushingRedisClient; + $connection = $this->createConnection($client)->shouldTransform(); $this->expectException(InvalidRedisConnectionException::class); $this->expectExceptionMessageIsOrContains('SafeScan requires a raw Redis connection.'); - (new FlushByPattern($connection))->execute('cache:test:*'); + try { + (new FlushByPattern($connection))->execute('cache:test:*'); + } finally { + $this->assertSame([], $client->unlinked); + } } public function testFlushDeletesMatchingKeys(): void { - $client = new FakeRedisClient( + $client = new FlushingRedisClient( scanResults: [ ['keys' => ['cache:test:key1', 'cache:test:key2', 'cache:test:key3'], 'iterator' => 0], ], ); - [$connection] = $this->createConnectionWithClient($client); - $connection->shouldReceive('clearLastError') - ->once() - ->andReturnUsing(fn (): bool => $client->clearLastError()); - $connection->shouldNotReceive('getLastError'); - $connection->shouldReceive('unlink') - ->once() - ->with('cache:test:key1', 'cache:test:key2', 'cache:test:key3') - ->andReturn(3); + $connection = $this->createConnection($client); $flushByPattern = new FlushByPattern($connection); $deletedCount = $flushByPattern->execute('cache:test:*'); $this->assertSame(3, $deletedCount); + $this->assertSame([['cache:test:key1', 'cache:test:key2', 'cache:test:key3']], $client->unlinked); + $this->assertSame(1, $client->errorClears); + $this->assertSame(0, $client->errorReads); } public function testFlushReturnsZeroWhenNoKeysMatch(): void { - $client = new FakeRedisClient( + $client = new FlushingRedisClient( scanResults: [ ['keys' => [], 'iterator' => 0], ], ); - [$connection] = $this->createConnectionWithClient($client); - // unlink should NOT be called when no keys found - $connection->shouldNotReceive('unlink'); + $connection = $this->createConnection($client); $flushByPattern = new FlushByPattern($connection); $deletedCount = $flushByPattern->execute('cache:nonexistent:*'); $this->assertSame(0, $deletedCount); + $this->assertSame([], $client->unlinked); } public function testFlushHandlesOptPrefixCorrectly(): void { // Client has OPT_PREFIX set - SafeScan should handle this - $client = new FakeRedisClient( + $client = new FlushingRedisClient( scanResults: [ // Redis returns keys WITH the OPT_PREFIX ['keys' => ['myapp:cache:test:key1', 'myapp:cache:test:key2'], 'iterator' => 0], @@ -106,19 +90,16 @@ public function testFlushHandlesOptPrefixCorrectly(): void optPrefix: 'myapp:', ); - [$connection] = $this->createConnectionWithClient($client); + $connection = $this->createConnection($client); // Keys passed to unlink should have OPT_PREFIX stripped // (phpredis will auto-add it back) - $connection->shouldReceive('unlink') - ->once() - ->with('cache:test:key1', 'cache:test:key2') - ->andReturn(2); $flushByPattern = new FlushByPattern($connection); $deletedCount = $flushByPattern->execute('cache:test:*'); $this->assertSame(2, $deletedCount); + $this->assertSame([['cache:test:key1', 'cache:test:key2']], $client->unlinked); } public function testFlushDeletesInBatches(): void @@ -138,121 +119,110 @@ public function testFlushDeletesInBatches(): void $batch3Keys[] = "cache:test:key{$i}"; } - $client = new FakeRedisClient( + $client = new FlushingRedisClient( scanResults: [ // Return all keys in one scan result to simplify test ['keys' => array_merge($batch1Keys, $batch2Keys, $batch3Keys), 'iterator' => 0], ], ); - [$connection] = $this->createConnectionWithClient($client); - - // Should be called 3 times (1000 + 1000 + 500) - $connection->shouldReceive('unlink') - ->times(3) - ->andReturn(1000, 1000, 500); + $connection = $this->createConnection($client); $flushByPattern = new FlushByPattern($connection); $deletedCount = $flushByPattern->execute('cache:test:*'); $this->assertSame(2500, $deletedCount); + $this->assertSame([$batch1Keys, $batch2Keys, $batch3Keys], $client->unlinked); } public function testFlushHandlesMultipleScanIterations(): void { - $client = new FakeRedisClient( + $client = new FlushingRedisClient( scanResults: [ ['keys' => ['cache:test:key1', 'cache:test:key2'], 'iterator' => 42], // More to scan ['keys' => ['cache:test:key3'], 'iterator' => 0], // Done ], ); - [$connection] = $this->createConnectionWithClient($client); + $connection = $this->createConnection($client); // All keys should be collected and deleted together (under buffer size) - $connection->shouldReceive('unlink') - ->once() - ->with('cache:test:key1', 'cache:test:key2', 'cache:test:key3') - ->andReturn(3); $flushByPattern = new FlushByPattern($connection); $deletedCount = $flushByPattern->execute('cache:test:*'); $this->assertSame(3, $deletedCount); + $this->assertSame([['cache:test:key1', 'cache:test:key2', 'cache:test:key3']], $client->unlinked); } public function testFlushThrowsTheNativeErrorWhenUnlinkFails(): void { - $client = new FakeRedisClient( + $client = new FlushingRedisClient( scanResults: [ ['keys' => ['cache:test:key1'], 'iterator' => 0], ], ); $client->setFakeLastError('stale error'); - [$connection] = $this->createConnectionWithClient($client); - $connection->shouldReceive('clearLastError') - ->once() - ->andReturnUsing(fn (): bool => $client->clearLastError()); - $connection->shouldReceive('getLastError') - ->once() - ->andReturnUsing(fn (): ?string => $client->getLastError()); - $connection->shouldReceive('unlink') - ->once() - ->andReturnUsing(function () use ($client): false { - $this->assertNull($client->getLastError()); + $connection = $this->createConnection($client); + $client->unlinkCallback = function () use ($client): false { + $this->assertSame(1, $client->errorClears); - $client->setFakeLastError('UNLINK is not permitted'); + $client->setFakeLastError('UNLINK is not permitted'); - return false; - }); + return false; + }; $this->expectException(RedisException::class); $this->expectExceptionMessageIs('UNLINK is not permitted'); - (new FlushByPattern($connection))->execute('cache:test:*'); + try { + (new FlushByPattern($connection))->execute('cache:test:*'); + } finally { + $this->assertSame([['cache:test:key1']], $client->unlinked); + $this->assertSame(1, $client->errorClears); + $this->assertSame(1, $client->errorReads); + } } public function testFlushThrowsAStableErrorWhenUnlinkFailsWithoutANativeError(): void { - $client = new FakeRedisClient( + $client = new FlushingRedisClient( scanResults: [ ['keys' => ['cache:test:key1'], 'iterator' => 0], ], ); $client->setFakeLastError('stale error'); - [$connection] = $this->createConnectionWithClient($client); - $connection->shouldReceive('clearLastError') - ->once() - ->andReturnUsing(fn (): bool => $client->clearLastError()); - $connection->shouldReceive('getLastError') - ->once() - ->andReturnUsing(fn (): ?string => $client->getLastError()); - $connection->shouldReceive('unlink') - ->once() - ->andReturnUsing(function () use ($client): false { - $this->assertNull($client->getLastError()); - - return false; - }); + $connection = $this->createConnection($client); + $client->unlinkCallback = function () use ($client): false { + $this->assertSame(1, $client->errorClears); + + return false; + }; $this->expectException(RedisException::class); $this->expectExceptionMessageIs('Redis UNLINK failed while deleting keys by pattern.'); - (new FlushByPattern($connection))->execute('cache:test:*'); + try { + (new FlushByPattern($connection))->execute('cache:test:*'); + } finally { + $this->assertSame([['cache:test:key1']], $client->unlinked); + $this->assertSame(1, $client->errorClears); + $this->assertSame(1, $client->errorReads); + } } public function testFlushPassesPatternToSafeScan(): void { - $client = new FakeRedisClient( + $client = new FlushingRedisClient( scanResults: [ ['keys' => [], 'iterator' => 0], ], ); - [$connection] = $this->createConnectionWithClient($client); + $connection = $this->createConnection($client); $flushByPattern = new FlushByPattern($connection); @@ -263,3 +233,46 @@ public function testFlushPassesPatternToSafeScan(): void $this->assertSame('cache:users:*', $client->getScanCalls()[0]['pattern']); } } + +class FlushingRedisClient extends FakeRedisClient +{ + /** @var list> */ + public array $unlinked = []; + + public int $errorClears = 0; + + public int $errorReads = 0; + + public ?Closure $unlinkCallback = null; + + /** + * Record deletion batches while retaining the real scan cursor updates. + */ + public function unlink(array|string $key, string ...$other_keys): Redis|int|false + { + $keys = is_array($key) ? $key : [$key, ...$other_keys]; + $this->unlinked[] = $keys; + + return $this->unlinkCallback !== null ? ($this->unlinkCallback)() : count($keys); + } + + /** + * Count diagnostic resets before deletion. + */ + public function clearLastError(): bool + { + ++$this->errorClears; + + return parent::clearLastError(); + } + + /** + * Count diagnostic reads after deletion failures. + */ + public function getLastError(): ?string + { + ++$this->errorReads; + + return parent::getLastError(); + } +} diff --git a/tests/Redis/PoolManagerTest.php b/tests/Redis/PoolManagerTest.php index 9ed0cfc673..3b8eac4e9a 100644 --- a/tests/Redis/PoolManagerTest.php +++ b/tests/Redis/PoolManagerTest.php @@ -15,7 +15,9 @@ use Hypervel\Redis\Pool\RedisPool; use Hypervel\Redis\RedisConfig; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine; @@ -26,6 +28,8 @@ class PoolManagerTest extends TestCase { + use VerifiesDoubles; + public function testPoolReturnsSameInstance(): void { $container = $this->mockContainerWithPools(); @@ -388,19 +392,19 @@ public function testPurgeAllClearsCachedPools(): void public function testPurgeAllDetachesPoolsBeforeClosingThem(): void { - $container = m::mock(ContainerContract::class); - $original = m::mock(RedisPool::class); - $replacement = m::mock(RedisPool::class); - $original->shouldReceive('start')->once(); - $replacement->shouldReceive('start')->once(); - $replacement->shouldReceive('isClosed')->andReturnFalse(); - $container->shouldReceive('make') + $container = Double::for(ContainerContract::class, override: true)->strict(); + $original = Double::for(RedisPool::class)->strict(); + $replacement = Double::for(RedisPool::class)->strict(); + $original->expects('start'); + $replacement->expects('start'); + $replacement->allows('isClosed')->returns(false); + $container->expects('make') ->with(RedisPool::class, ['name' => 'default']) - ->twice() - ->andReturn($original, $replacement); - $poolManager = new PoolManager($container); + ->times(2) + ->returns($original, $replacement); + $poolManager = new PoolManager($container->instance()); $resolvedDuringClose = null; - $original->shouldReceive('close')->once()->andReturnUsing( + $original->expects('close')->resolves( function () use ($poolManager, &$resolvedDuringClose): void { $resolvedDuringClose = $poolManager->pool('default'); } @@ -419,21 +423,21 @@ public function testPurgeAllClosesEveryPoolAndPreservesTheFirstCancellation(): v $ordinaryFailure = new RuntimeException('First close failed.'); $cancellation = new CanceledException('Second close canceled.'); $laterCancellation = new CanceledException('Third close canceled.'); - $container = m::mock(ContainerContract::class); - $first = m::mock(RedisPool::class); - $first->shouldReceive('start')->once(); - $first->expects('close')->andThrow($ordinaryFailure); - $second = m::mock(RedisPool::class); - $second->shouldReceive('start')->once(); - $second->expects('close')->andThrow($cancellation); - $third = m::mock(RedisPool::class); - $third->shouldReceive('start')->once(); - $third->expects('close')->andThrow($laterCancellation); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $first = Double::for(RedisPool::class)->strict(); + $first->expects('start'); + $first->expects('close')->throws($ordinaryFailure); + $second = Double::for(RedisPool::class)->strict(); + $second->expects('start'); + $second->expects('close')->throws($cancellation); + $third = Double::for(RedisPool::class)->strict(); + $third->expects('start'); + $third->expects('close')->throws($laterCancellation); $container->expects('make') - ->with(RedisPool::class, m::type('array')) + ->with(RedisPool::class, Argument::type('array')) ->times(3) - ->andReturn($first, $second, $third); - $poolManager = new PoolManager($container); + ->returns($first, $second, $third); + $poolManager = new PoolManager($container->instance()); $poolManager->pool('first'); $poolManager->pool('second'); $poolManager->pool('third'); @@ -479,19 +483,19 @@ public function testPurgeOnlyRemovesNamedPool(): void public function testPurgeDetachesPoolBeforeClosingIt(): void { - $container = m::mock(ContainerContract::class); - $original = m::mock(RedisPool::class); - $replacement = m::mock(RedisPool::class); - $original->shouldReceive('start')->once(); - $replacement->shouldReceive('start')->once(); - $replacement->shouldReceive('isClosed')->andReturnFalse(); - $container->shouldReceive('make') + $container = Double::for(ContainerContract::class, override: true)->strict(); + $original = Double::for(RedisPool::class)->strict(); + $replacement = Double::for(RedisPool::class)->strict(); + $original->expects('start'); + $replacement->expects('start'); + $replacement->allows('isClosed')->returns(false); + $container->expects('make') ->with(RedisPool::class, ['name' => 'default']) - ->twice() - ->andReturn($original, $replacement); - $poolManager = new PoolManager($container); + ->times(2) + ->returns($original, $replacement); + $poolManager = new PoolManager($container->instance()); $resolvedDuringClose = null; - $original->shouldReceive('close')->once()->andReturnUsing( + $original->expects('close')->resolves( function () use ($poolManager, &$resolvedDuringClose): void { $resolvedDuringClose = $poolManager->pool('default'); } @@ -526,7 +530,7 @@ private function publicationContainer(array &$candidates, array $poolOptions = [ /** * Mock a container with Redis pools. */ - private function mockContainerWithPools(): m\MockInterface|ContainerContract + private function mockContainerWithPools(): ContainerContract { $connectionConfig = [ 'host' => 'localhost', @@ -543,18 +547,18 @@ private function mockContainerWithPools(): m\MockInterface|ContainerContract ], ]; - $redisConfig = m::mock(RedisConfig::class); - $redisConfig->shouldReceive('connectionConfig')->andReturn($connectionConfig); + $redisConfig = Double::for(RedisConfig::class)->strict(); + $redisConfig->allows('connectionConfig')->returns($connectionConfig); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make')->with(RedisConfig::class)->andReturn($redisConfig); - $container->shouldReceive('has')->andReturn(false); - $container->shouldReceive('bound')->with('events')->andReturn(false); - $container->shouldReceive('make')->with(RedisPool::class, m::any())->andReturnUsing( - fn ($class, $arguments) => new PoolManagerTestPool($container, $arguments['name']) + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->allows('make')->with(RedisConfig::class)->returns($redisConfig); + $container->allows('has')->returns(false); + $container->allows('bound')->with('events')->returns(false); + $container->allows('make')->with(RedisPool::class, Argument::any())->resolves( + fn ($class, $arguments) => new PoolManagerTestPool($container->instance(), $arguments['name']) ); - return $container; + return $container->instance(); } } diff --git a/tests/Redis/RedisConfigTest.php b/tests/Redis/RedisConfigTest.php index 440058897a..33181f5581 100644 --- a/tests/Redis/RedisConfigTest.php +++ b/tests/Redis/RedisConfigTest.php @@ -8,19 +8,17 @@ use Hypervel\Redis\RedisConfig; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; class RedisConfigTest extends TestCase { public function testConnectionConfigAppliesOptionalStandaloneDefaults(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'client' => 'phpredis', 'options' => ['prefix' => 'shared:'], 'default' => ['host' => '127.0.0.1', 'port' => 6379], - ]); + ]]]); $connection = (new RedisConfig($config))->connectionConfig('default'); @@ -69,11 +67,10 @@ public function testConnectionConfigRejectsUnsupportedClient(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The phpredis Redis client is the only supported client.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'client' => 'predis', 'default' => ['host' => '127.0.0.1', 'port' => 6379], - ]); + ]]]); (new RedisConfig($config))->connectionConfig('default'); } @@ -85,11 +82,10 @@ public function testConnectionConfigRejectsLaravelClusterNamespace(): void 'The redis.clusters configuration is not supported. Configure cluster settings on a named Redis connection.' ); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'clusters' => ['cache' => []], 'default' => ['host' => '127.0.0.1', 'port' => 6379], - ]); + ]]]); (new RedisConfig($config))->connectionConfig('default'); } @@ -99,10 +95,9 @@ public function testConnectionConfigThrowsForNonArrayConnectionEntry(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The redis connection [default] must be an array.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'default' => 'tcp://127.0.0.1:6379', - ]); + ]]]); (new RedisConfig($config))->connectionConfig('default'); } @@ -112,10 +107,9 @@ public function testConnectionConfigThrowsWhenHostPortMissingForDirectConnection $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The redis connection [custom] must define host and port.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'custom' => ['foo' => 'bar'], - ]); + ]]]); (new RedisConfig($config))->connectionConfig('custom'); } @@ -125,14 +119,13 @@ public function testConnectionConfigRejectsUnsupportedScheme(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The redis connection [default] scheme must be tcp or tls.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'default' => [ 'scheme' => 'ssl', 'host' => '127.0.0.1', 'port' => 6379, ], - ]); + ]]]); (new RedisConfig($config))->connectionConfig('default'); } @@ -142,14 +135,13 @@ public function testConnectionConfigRejectsInvalidContext(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The redis connection [default] context must be an array.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'default' => [ 'context' => 'invalid', 'host' => '127.0.0.1', 'port' => 6379, ], - ]); + ]]]); (new RedisConfig($config))->connectionConfig('default'); } @@ -166,8 +158,7 @@ public function testConnectionConfigMergesSharedAndConnectionOptions(): void ], ]; - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn($redisConfig); + $config = new Repository(['database' => ['redis' => $redisConfig]]); $connectionConfig = (new RedisConfig($config))->connectionConfig('default'); @@ -179,8 +170,7 @@ public function testConnectionConfigMergesSharedAndConnectionOptions(): void public function testTopLevelConnectionPrefixOverridesSharedAndLocalOptions(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => ['prefix' => 'shared:', 'serializer' => 1], 'default' => [ 'host' => '127.0.0.1', @@ -188,7 +178,7 @@ public function testTopLevelConnectionPrefixOverridesSharedAndLocalOptions(): vo 'prefix' => 'top-level:', 'options' => ['prefix' => 'local:', 'scan' => 1], ], - ]); + ]]]); $connection = (new RedisConfig($config))->connectionConfig('default'); @@ -204,8 +194,7 @@ public function testTopLevelConnectionPrefixOverridesSharedAndLocalOptions(): vo public function testEventOverridePreservesConfigUntilExplicitlyChanged(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => [], 'default' => [ 'host' => '127.0.0.1', @@ -213,7 +202,7 @@ public function testEventOverridePreservesConfigUntilExplicitlyChanged(): void 'events' => true, 'options' => [], ], - ]); + ]]]); $redisConfig = new RedisConfig($config); $this->assertTrue($redisConfig->connectionConfig('default')['events']); @@ -227,15 +216,14 @@ public function testEventOverridePreservesConfigUntilExplicitlyChanged(): void public function testEventOverrideCreatesEventConfigForFutureAssemblies(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => [], 'default' => [ 'host' => '127.0.0.1', 'port' => 6379, 'options' => [], ], - ]); + ]]]); $redisConfig = new RedisConfig($config); $redisConfig->enableEvents(); @@ -248,8 +236,7 @@ public function testConnectionConfigThrowsForMissingConnection(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The redis connection [default] must be an array.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([]); + $config = new Repository(['database' => ['redis' => []]]); (new RedisConfig($config))->connectionConfig('default'); } @@ -259,8 +246,7 @@ public function testConnectionConfigThrowsForInvalidConnectionOptions(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The redis connection [default] options must be an array.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => ['prefix' => 'global:'], 'default' => [ 'host' => '127.0.0.1', @@ -268,15 +254,14 @@ public function testConnectionConfigThrowsForInvalidConnectionOptions(): void 'database' => 0, 'options' => 'invalid', ], - ]); + ]]]); (new RedisConfig($config))->connectionConfig('default'); } public function testNullConnectionPrefixInheritsSharedPrefix(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => ['prefix' => 'shared:'], 'default' => [ 'host' => '127.0.0.1', @@ -284,7 +269,7 @@ public function testNullConnectionPrefixInheritsSharedPrefix(): void 'options' => ['scan' => 1], 'prefix' => null, ], - ]); + ]]]); $connection = (new RedisConfig($config))->connectionConfig('default'); @@ -293,8 +278,7 @@ public function testNullConnectionPrefixInheritsSharedPrefix(): void public function testConnectionConfigAcceptsClusterConnectionWithoutHostAndPort(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => [], 'clustered' => [ 'cluster' => [ @@ -302,7 +286,7 @@ public function testConnectionConfigAcceptsClusterConnectionWithoutHostAndPort() 'seeds' => ['127.0.0.1:7000', '127.0.0.1:7001'], ], ], - ]); + ]]]); $connection = (new RedisConfig($config))->connectionConfig('clustered'); @@ -323,15 +307,14 @@ public function testConnectionConfigThrowsWhenClusterEnabledWithoutSeeds(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The redis connection [clustered] cluster seeds must be a non-empty array.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'clustered' => [ 'cluster' => [ 'enabled' => true, 'seeds' => [], ], ], - ]); + ]]]); (new RedisConfig($config))->connectionConfig('clustered'); } @@ -342,23 +325,21 @@ public function testConnectionConfigRejectsInvalidClusterSeeds(mixed $seed): voi $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The redis connection [clustered] cluster seeds must all be non-empty strings.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'clustered' => [ 'cluster' => [ 'enabled' => true, 'seeds' => [$seed], ], ], - ]); + ]]]); (new RedisConfig($config))->connectionConfig('clustered'); } public function testConfiguredTlsSchemeSecuresBareClusterSeeds(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => [], 'clustered' => [ 'scheme' => 'tls', @@ -368,7 +349,7 @@ public function testConfiguredTlsSchemeSecuresBareClusterSeeds(): void 'seeds' => ['127.0.0.1:7000'], ], ], - ]); + ]]]); $connection = (new RedisConfig($config))->connectionConfig('clustered'); @@ -379,8 +360,7 @@ public function testConfiguredTlsSchemeSecuresBareClusterSeeds(): void public function testSecureClusterSeedSelectsTlsTransport(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => [], 'clustered' => [ 'options' => [], @@ -389,7 +369,7 @@ public function testSecureClusterSeedSelectsTlsTransport(): void 'seeds' => ['ssl://127.0.0.1:7000', '127.0.0.1:7001'], ], ], - ]); + ]]]); $connection = (new RedisConfig($config))->connectionConfig('clustered'); @@ -403,8 +383,7 @@ public function testSecureClusterSeedSelectsTlsTransport(): void public function testNonEmptyClusterContextSelectsTlsTransport(): void { $context = ['ssl' => ['verify_peer' => true]]; - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => [], 'clustered' => [ 'context' => $context, @@ -414,7 +393,7 @@ public function testNonEmptyClusterContextSelectsTlsTransport(): void 'seeds' => ['127.0.0.1:7000'], ], ], - ]); + ]]]); $connection = (new RedisConfig($config))->connectionConfig('clustered'); @@ -431,10 +410,9 @@ public function testConnectionConfigRejectsInconsistentClusterTransport(array $c 'PhpRedis applies one stream context to every discovered node; use a single tcp or tls transport across scheme, context, and seeds.' ); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'clustered' => $connection, - ]); + ]]]); (new RedisConfig($config))->connectionConfig('clustered'); } @@ -478,23 +456,21 @@ public function testConnectionConfigRejectsUnsupportedClusterSeedScheme(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The redis connection [clustered] cluster seeds may only use tcp, tls, or ssl schemes.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'clustered' => [ 'cluster' => [ 'enabled' => true, 'seeds' => ['redis://127.0.0.1:7000'], ], ], - ]); + ]]]); (new RedisConfig($config))->connectionConfig('clustered'); } public function testConnectionConfigNormalizesOptionalSentinelSettings(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => [], 'sentinel' => [ 'options' => [], @@ -504,7 +480,7 @@ public function testConnectionConfigNormalizesOptionalSentinelSettings(): void 'master_name' => 'mymaster', ], ], - ]); + ]]]); $connection = (new RedisConfig($config))->connectionConfig('sentinel'); @@ -525,8 +501,7 @@ public function testConnectionConfigThrowsWhenSentinelEnabledWithoutNodes(): voi $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The redis connection [sentinel] sentinel nodes must be a non-empty array.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'sentinel' => [ 'sentinel' => [ 'enabled' => true, @@ -534,7 +509,7 @@ public function testConnectionConfigThrowsWhenSentinelEnabledWithoutNodes(): voi 'master_name' => 'mymaster', ], ], - ]); + ]]]); (new RedisConfig($config))->connectionConfig('sentinel'); } @@ -545,8 +520,7 @@ public function testConnectionConfigRejectsInvalidSentinelNodes(mixed $node): vo $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The redis connection [sentinel] sentinel nodes must all be non-empty strings.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'sentinel' => [ 'sentinel' => [ 'enabled' => true, @@ -554,7 +528,7 @@ public function testConnectionConfigRejectsInvalidSentinelNodes(mixed $node): vo 'master_name' => 'mymaster', ], ], - ]); + ]]]); (new RedisConfig($config))->connectionConfig('sentinel'); } @@ -572,8 +546,7 @@ public function testConnectionConfigThrowsWhenSentinelEnabledWithoutMasterName() $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The redis connection [sentinel] sentinel master name must be configured.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'sentinel' => [ 'sentinel' => [ 'enabled' => true, @@ -581,21 +554,20 @@ public function testConnectionConfigThrowsWhenSentinelEnabledWithoutMasterName() 'master_name' => '', ], ], - ]); + ]]]); (new RedisConfig($config))->connectionConfig('sentinel'); } public function testConnectionConfigParsesUrl(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => [], 'default' => [ 'url' => 'redis://myuser:secret@redis.example.com:6380/3', 'options' => [], ], - ]); + ]]]); $connectionConfig = (new RedisConfig($config))->connectionConfig('default'); @@ -608,8 +580,7 @@ public function testConnectionConfigParsesUrl(): void public function testConnectionConfigUrlOverridesExplicitValues(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => [], 'default' => [ 'url' => 'redis://urlhost:6380/2', @@ -618,7 +589,7 @@ public function testConnectionConfigUrlOverridesExplicitValues(): void 'database' => 0, 'options' => [], ], - ]); + ]]]); $connectionConfig = (new RedisConfig($config))->connectionConfig('default'); @@ -629,8 +600,7 @@ public function testConnectionConfigUrlOverridesExplicitValues(): void public function testConnectionConfigWithoutUrlPreservesExplicitValues(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => [], 'default' => [ 'host' => '127.0.0.1', @@ -638,7 +608,7 @@ public function testConnectionConfigWithoutUrlPreservesExplicitValues(): void 'database' => 0, 'options' => [], ], - ]); + ]]]); $connectionConfig = (new RedisConfig($config))->connectionConfig('default'); @@ -649,8 +619,7 @@ public function testConnectionConfigWithoutUrlPreservesExplicitValues(): void public function testConnectionConfigNormalizesExplicitStringDatabase(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => [], 'default' => [ 'host' => '127.0.0.1', @@ -658,7 +627,7 @@ public function testConnectionConfigNormalizesExplicitStringDatabase(): void 'database' => '4', 'options' => [], ], - ]); + ]]]); $connectionConfig = (new RedisConfig($config))->connectionConfig('default'); @@ -667,14 +636,13 @@ public function testConnectionConfigNormalizesExplicitStringDatabase(): void public function testConnectionConfigAcceptsUrlOnlyConnection(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'options' => [], 'default' => [ 'url' => 'redis://127.0.0.1:6379/0', 'options' => [], ], - ]); + ]]]); $connection = (new RedisConfig($config))->connectionConfig('default'); @@ -687,8 +655,7 @@ public function testConnectionConfigThrowsWhenClusterAndSentinelBothEnabled(): v $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The redis connection [mixed] cannot enable both cluster and sentinel.'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->with('database.redis')->andReturn([ + $config = new Repository(['database' => ['redis' => [ 'mixed' => [ 'cluster' => [ 'enabled' => true, @@ -700,7 +667,7 @@ public function testConnectionConfigThrowsWhenClusterAndSentinelBothEnabled(): v 'master_name' => 'mymaster', ], ], - ]); + ]]]); (new RedisConfig($config))->connectionConfig('mixed'); } diff --git a/tests/Redis/RedisConnectionLifecycleListenerTest.php b/tests/Redis/RedisConnectionLifecycleListenerTest.php index 41a3b59af5..0d568f396a 100644 --- a/tests/Redis/RedisConnectionLifecycleListenerTest.php +++ b/tests/Redis/RedisConnectionLifecycleListenerTest.php @@ -9,7 +9,8 @@ use Hypervel\Redis\Pool\PoolManager; use Hypervel\Redis\RedisManager; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use stdClass; use Swoole\Coroutine\CanceledException; @@ -17,76 +18,78 @@ class RedisConnectionLifecycleListenerTest extends TestCase { + use VerifiesDoubles; + public function testTaskCleanupDoesNotResolveAnUnusedManager(): void { - $container = m::mock(Container::class); - $container->expects('resolved')->with('redis')->andReturnFalse(); - $container->shouldNotReceive('make'); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('resolved')->with('redis')->returns(false); + $container->expects('make')->never(); - (new RedisConnectionLifecycleListener($container))->releaseTaskConnections(); + (new RedisConnectionLifecycleListener($container->instance()))->releaseTaskConnections(); } public function testTaskCleanupReleasesTheConcreteManager(): void { - $manager = m::mock(RedisManager::class); + $manager = Double::for(RedisManager::class)->strict(); $manager->expects('releaseConnections'); - $container = m::mock(Container::class); - $container->expects('resolved')->with('redis')->andReturnTrue(); - $container->expects('make')->with('redis')->andReturn($manager); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('resolved')->with('redis')->returns(true); + $container->expects('make')->with('redis')->returns($manager); - (new RedisConnectionLifecycleListener($container))->releaseTaskConnections(); + (new RedisConnectionLifecycleListener($container->instance()))->releaseTaskConnections(); } public function testTaskCleanupLeavesCustomManagersAlone(): void { $manager = new stdClass; - $container = m::mock(Container::class); - $container->expects('resolved')->with('redis')->andReturnTrue(); - $container->expects('make')->with('redis')->andReturn($manager); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('resolved')->with('redis')->returns(true); + $container->expects('make')->with('redis')->returns($manager); - (new RedisConnectionLifecycleListener($container))->releaseTaskConnections(); + (new RedisConnectionLifecycleListener($container->instance()))->releaseTaskConnections(); } public function testProcessCleanupDoesNotResolveUnusedOwners(): void { - $container = m::mock(Container::class); - $container->expects('resolved')->with('redis')->andReturnFalse(); - $container->expects('resolved')->with(PoolManager::class)->andReturnFalse(); - $container->shouldNotReceive('make'); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('resolved')->with('redis')->returns(false); + $container->expects('resolved')->with(PoolManager::class)->returns(false); + $container->expects('make')->never(); - (new RedisConnectionLifecycleListener($container))->discardProcessConnections(); + (new RedisConnectionLifecycleListener($container->instance()))->discardProcessConnections(); } public function testProcessCleanupDiscardsManagerAndPurgesPools(): void { - $manager = m::mock(RedisManager::class); + $manager = Double::for(RedisManager::class)->strict(); $manager->expects('discardConnections'); - $poolManager = m::mock(PoolManager::class); + $poolManager = Double::for(PoolManager::class)->strict(); $poolManager->expects('purgeAll'); - $container = m::mock(Container::class); - $container->expects('resolved')->with('redis')->andReturnTrue(); - $container->expects('make')->with('redis')->andReturn($manager); - $container->expects('resolved')->with(PoolManager::class)->andReturnTrue(); - $container->expects('make')->with(PoolManager::class)->andReturn($poolManager); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('resolved')->with('redis')->returns(true); + $container->expects('make')->with('redis')->returns($manager); + $container->expects('resolved')->with(PoolManager::class)->returns(true); + $container->expects('make')->with(PoolManager::class)->returns($poolManager); - (new RedisConnectionLifecycleListener($container))->discardProcessConnections(); + (new RedisConnectionLifecycleListener($container->instance()))->discardProcessConnections(); } public function testManagerFailureDoesNotSkipPoolPurgeAndRemainsPrimary(): void { $managerException = new RuntimeException('Manager discard failed.'); - $manager = m::mock(RedisManager::class); - $manager->expects('discardConnections')->andThrow($managerException); - $poolManager = m::mock(PoolManager::class); - $poolManager->expects('purgeAll')->andThrow(new RuntimeException('Pool purge failed.')); - $container = m::mock(Container::class); - $container->expects('resolved')->with('redis')->andReturnTrue(); - $container->expects('make')->with('redis')->andReturn($manager); - $container->expects('resolved')->with(PoolManager::class)->andReturnTrue(); - $container->expects('make')->with(PoolManager::class)->andReturn($poolManager); + $manager = Double::for(RedisManager::class)->strict(); + $manager->expects('discardConnections')->throws($managerException); + $poolManager = Double::for(PoolManager::class)->strict(); + $poolManager->expects('purgeAll')->throws(new RuntimeException('Pool purge failed.')); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('resolved')->with('redis')->returns(true); + $container->expects('make')->with('redis')->returns($manager); + $container->expects('resolved')->with(PoolManager::class)->returns(true); + $container->expects('make')->with(PoolManager::class)->returns($poolManager); try { - (new RedisConnectionLifecycleListener($container))->discardProcessConnections(); + (new RedisConnectionLifecycleListener($container->instance()))->discardProcessConnections(); $this->fail('Expected the manager failure to propagate.'); } catch (RuntimeException $throwable) { $this->assertSame($managerException, $throwable); @@ -96,18 +99,18 @@ public function testManagerFailureDoesNotSkipPoolPurgeAndRemainsPrimary(): void public function testPoolPurgeCancellationSupersedesOrdinaryManagerFailure(): void { $cancellation = new CanceledException('Pool purge canceled.'); - $manager = m::mock(RedisManager::class); - $manager->expects('discardConnections')->andThrow(new RuntimeException('Manager discard failed.')); - $poolManager = m::mock(PoolManager::class); - $poolManager->expects('purgeAll')->andThrow($cancellation); - $container = m::mock(Container::class); - $container->expects('resolved')->with('redis')->andReturnTrue(); - $container->expects('make')->with('redis')->andReturn($manager); - $container->expects('resolved')->with(PoolManager::class)->andReturnTrue(); - $container->expects('make')->with(PoolManager::class)->andReturn($poolManager); + $manager = Double::for(RedisManager::class)->strict(); + $manager->expects('discardConnections')->throws(new RuntimeException('Manager discard failed.')); + $poolManager = Double::for(PoolManager::class)->strict(); + $poolManager->expects('purgeAll')->throws($cancellation); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('resolved')->with('redis')->returns(true); + $container->expects('make')->with('redis')->returns($manager); + $container->expects('resolved')->with(PoolManager::class)->returns(true); + $container->expects('make')->with(PoolManager::class)->returns($poolManager); try { - (new RedisConnectionLifecycleListener($container))->discardProcessConnections(); + (new RedisConnectionLifecycleListener($container->instance()))->discardProcessConnections(); $this->fail('Expected the cancellation to propagate.'); } catch (Throwable $throwable) { $this->assertSame($cancellation, $throwable); @@ -117,18 +120,18 @@ public function testPoolPurgeCancellationSupersedesOrdinaryManagerFailure(): voi public function testPoolPurgeFailurePropagatesAfterManagerCleanup(): void { $exception = new RuntimeException('Pool purge failed.'); - $manager = m::mock(RedisManager::class); + $manager = Double::for(RedisManager::class)->strict(); $manager->expects('discardConnections'); - $poolManager = m::mock(PoolManager::class); - $poolManager->expects('purgeAll')->andThrow($exception); - $container = m::mock(Container::class); - $container->expects('resolved')->with('redis')->andReturnTrue(); - $container->expects('make')->with('redis')->andReturn($manager); - $container->expects('resolved')->with(PoolManager::class)->andReturnTrue(); - $container->expects('make')->with(PoolManager::class)->andReturn($poolManager); + $poolManager = Double::for(PoolManager::class)->strict(); + $poolManager->expects('purgeAll')->throws($exception); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('resolved')->with('redis')->returns(true); + $container->expects('make')->with('redis')->returns($manager); + $container->expects('resolved')->with(PoolManager::class)->returns(true); + $container->expects('make')->with(PoolManager::class)->returns($poolManager); try { - (new RedisConnectionLifecycleListener($container))->discardProcessConnections(); + (new RedisConnectionLifecycleListener($container->instance()))->discardProcessConnections(); $this->fail('Expected the pool purge failure to propagate.'); } catch (RuntimeException $throwable) { $this->assertSame($exception, $throwable); diff --git a/tests/Redis/RedisConnectionTest.php b/tests/Redis/RedisConnectionTest.php index c75517bce5..9a069f1fb3 100644 --- a/tests/Redis/RedisConnectionTest.php +++ b/tests/Redis/RedisConnectionTest.php @@ -24,12 +24,15 @@ use Hypervel\Redis\RedisConnection; use Hypervel\Redis\RedisSentinelFactory; use Hypervel\Support\ClassInvoker; +use Hypervel\Tests\Redis\Fixtures\FakeRedisClient; use Hypervel\Tests\Redis\Fixtures\PhpRedisClusterConnectionStub; use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; use Hypervel\Tests\Redis\Fixtures\RespServer; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use Psr\Log\LogLevel; @@ -47,6 +50,8 @@ class RedisConnectionTest extends TestCase { + use VerifiesDoubles; + public function testShouldTransform(): void { $connection = $this->mockRedisConnection(); @@ -61,11 +66,11 @@ public function testShouldTransform(): void public function testRelease(): void { $pool = $this->getMockedPool(); - $pool->shouldReceive('release')->once(); + $pool->expects('release'); $connection = $this->mockRedisConnection(pool: $pool); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andReturn(Redis::ATOMIC); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->returns(Redis::ATOMIC); $connection->setActiveConnection($redis); $connection->shouldTransform(true); @@ -76,8 +81,8 @@ public function testRelease(): void public function testSuccessfulAtomicSelectTracksTheAppliedDatabase(): void { - $redis = m::mock(Redis::class); - $redis->expects('select')->with(2)->andReturnTrue(); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('select')->with(2)->returns(true); $connection = $this->mockRedisConnection(); $connection->setActiveConnection($redis); @@ -90,9 +95,9 @@ public function testSuccessfulAtomicSelectTracksTheAppliedDatabase(): void public function testFailedAndQueuedSelectResultsAreNotTrackedAsApplied(): void { - $redis = m::mock(Redis::class); - $redis->expects('select')->with(2)->andReturnFalse(); - $redis->expects('select')->with(3)->andReturnSelf(); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('select')->with(2)->returns(false); + $redis->expects('select')->with(3)->returns($redis); $connection = $this->mockRedisConnection(); $connection->setActiveConnection($redis); $database = new ReflectionProperty(RedisConnection::class, 'database'); @@ -106,17 +111,16 @@ public function testFailedAndQueuedSelectResultsAreNotTrackedAsApplied(): void public function testReleaseResetsDatabaseToConfiguredDefault(): void { $pool = $this->getMockedPool(); - $pool->shouldReceive('release')->once(); + $pool->expects('release'); - $redis = m::mock(Redis::class); - $redis->shouldReceive('select')->once()->with(1)->andReturn(true); - $redis->shouldReceive('select')->once()->with(1)->andReturn(true); - $redis->expects('select')->with(2)->andReturnTrue(); - $redis->shouldReceive('getMode')->once()->andReturn(Redis::ATOMIC); - $redis->expects('isConnected')->andReturnTrue(); - $redis->expects('getDBNum')->andReturn(2); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('select')->times(2)->with(1)->returns(true); + $redis->expects('select')->with(2)->returns(true); + $redis->expects('getMode')->returns(Redis::ATOMIC); + $redis->expects('isConnected')->returns(true); + $redis->expects('getDBNum')->returns(2); - $redis->shouldReceive('setOption')->andReturnTrue(); + $redis->allows('setOption')->returns(true); $connection = new class($this->getContainer(), $pool, $this->standaloneConfig(['database' => 1]), $redis) extends PhpRedisConnection { public function __construct( @@ -141,12 +145,12 @@ protected function createRedis(array $config): Redis public function testReleaseRestoresTheNativeDatabaseWithoutTrackedSelection(): void { $pool = $this->getMockedPool(); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andReturn(Redis::ATOMIC); - $redis->expects('isConnected')->andReturnTrue(); - $redis->expects('getDBNum')->andReturn(2); - $redis->expects('select')->with(0)->andReturnTrue(); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->returns(Redis::ATOMIC); + $redis->expects('isConnected')->returns(true); + $redis->expects('getDBNum')->returns(2); + $redis->expects('select')->with(0)->returns(true); $connection = $this->mockRedisConnection(pool: $pool); $connection->setActiveConnection($redis); @@ -160,12 +164,12 @@ public function testReleaseRestoresTheNativeDatabaseWithoutTrackedSelection(): v public function testReleaseInvalidatesDisconnectedStandaloneConnectionWithoutInspectingItsDatabase(): void { $pool = $this->getMockedPool(); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andReturn(Redis::ATOMIC); - $redis->expects('isConnected')->andReturnFalse(); - $redis->shouldNotReceive('getDBNum'); - $redis->shouldNotReceive('select'); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->returns(Redis::ATOMIC); + $redis->expects('isConnected')->returns(false); + $redis->expects('getDBNum')->never(); + $redis->expects('select')->never(); $connection = $this->mockRedisConnection(pool: $pool); $connection->setActiveConnection($redis); @@ -177,9 +181,9 @@ public function testReleaseInvalidatesDisconnectedStandaloneConnectionWithoutIns public function testReleaseDiscardsAConnectionInMultiMode(): void { $pool = $this->getMockedPool(); - $pool->expects('discard')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andReturn(Redis::MULTI); + $pool->expects('discard')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->returns(Redis::MULTI); $connection = $this->mockRedisConnection(pool: $pool); $connection->setActiveConnection($redis); @@ -188,15 +192,15 @@ public function testReleaseDiscardsAConnectionInMultiMode(): void public function testReleaseDiscardsAnInvalidatedTransactionWithoutReportingAbandonment(): void { - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldNotReceive('log'); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('log')->never(); $container = $this->getContainer(); $container->instance(StdoutLoggerInterface::class, $logger); $pool = $this->getMockedPool(); - $pool->expects('discard')->with(m::type(RedisConnection::class)); - $pool->shouldNotReceive('release'); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andReturn(Redis::MULTI); + $pool->expects('discard')->with(Argument::type(RedisConnection::class)); + $pool->expects('release')->never(); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->returns(Redis::MULTI); $connection = $this->mockRedisConnection(container: $container, pool: $pool); $connection->setActiveConnection($redis); $connection->invalidate(); @@ -207,9 +211,9 @@ public function testReleaseDiscardsAnInvalidatedTransactionWithoutReportingAband public function testReleaseDiscardsAConnectionInPipelineMode(): void { $pool = $this->getMockedPool(); - $pool->expects('discard')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andReturn(Redis::PIPELINE); + $pool->expects('discard')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->returns(Redis::PIPELINE); $connection = $this->mockRedisConnection(pool: $pool); $connection->setActiveConnection($redis); @@ -219,10 +223,10 @@ public function testReleaseDiscardsAConnectionInPipelineMode(): void public function testReleaseDiscardsAConnectionWithAnActiveWatch(): void { $pool = $this->getMockedPool(); - $pool->expects('discard')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); - $redis->expects('watch')->with('key')->andReturnTrue(); - $redis->expects('getMode')->andReturn(Redis::ATOMIC); + $pool->expects('discard')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('watch')->with('key')->returns(true); + $redis->expects('getMode')->returns(Redis::ATOMIC); $connection = $this->mockRedisConnection(pool: $pool); $connection->setActiveConnection($redis); @@ -237,11 +241,11 @@ public function testSuccessfulTerminalCommandsClearTrackedWatchState( mixed $result, ): void { $pool = $this->getMockedPool(); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); - $redis->expects('watch')->with('key')->andReturnTrue(); - $redis->expects(strtolower($command))->andReturn($result); - $redis->expects('getMode')->andReturn(Redis::ATOMIC); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('watch')->with('key')->returns(true); + $redis->expects(strtolower($command))->returns($result); + $redis->expects('getMode')->returns(Redis::ATOMIC); $connection = $this->mockRedisConnection(pool: $pool); $connection->setActiveConnection($redis); @@ -261,11 +265,11 @@ public static function watchTerminalCommandProvider(): array public function testFailedUnwatchRetainsTrackedWatchState(): void { $pool = $this->getMockedPool(); - $pool->expects('discard')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); - $redis->expects('watch')->with('key')->andReturnTrue(); - $redis->expects('unwatch')->andReturnFalse(); - $redis->expects('getMode')->andReturn(Redis::ATOMIC); + $pool->expects('discard')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('watch')->with('key')->returns(true); + $redis->expects('unwatch')->returns(false); + $redis->expects('getMode')->returns(Redis::ATOMIC); $connection = $this->mockRedisConnection(pool: $pool); $connection->setActiveConnection($redis); @@ -277,11 +281,11 @@ public function testFailedUnwatchRetainsTrackedWatchState(): void public function testNativeDiscardClearsTrackedWatchState(): void { $pool = $this->getMockedPool(); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); - $redis->expects('watch')->with('key')->andReturnTrue(); - $redis->expects('discard')->andReturnTrue(); - $redis->expects('getMode')->andReturn(Redis::ATOMIC); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('watch')->with('key')->returns(true); + $redis->expects('discard')->returns(true); + $redis->expects('getMode')->returns(Redis::ATOMIC); $connection = $this->mockRedisConnection(pool: $pool); $connection->setActiveConnection($redis); @@ -293,10 +297,10 @@ public function testNativeDiscardClearsTrackedWatchState(): void public function testClearWatchStateAllowsOrdinaryRelease(): void { $pool = $this->getMockedPool(); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); - $redis->expects('watch')->with('key')->andReturnTrue(); - $redis->expects('getMode')->andReturn(Redis::ATOMIC); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('watch')->with('key')->returns(true); + $redis->expects('getMode')->returns(Redis::ATOMIC); $connection = $this->mockRedisConnection(pool: $pool); $connection->setActiveConnection($redis); @@ -308,12 +312,12 @@ public function testClearWatchStateAllowsOrdinaryRelease(): void public function testReconnectBeginsWithNoTrackedWatchState(): void { $pool = $this->getMockedPool(); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); - $redis->expects('watch')->with('key')->andReturnTrue(); - $redis->expects('getMode')->andReturn(Redis::ATOMIC); - $redis->expects('isConnected')->twice()->andReturnFalse(); - $redis->shouldReceive('setOption')->andReturnTrue(); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('watch')->with('key')->returns(true); + $redis->expects('getMode')->returns(Redis::ATOMIC); + $redis->expects('isConnected')->times(2)->returns(false); + $redis->allows('setOption')->returns(true); $connection = new class($this->getContainer(), $pool, $this->standaloneConfig(), $redis) extends PhpRedisConnection { public function __construct( @@ -339,7 +343,7 @@ protected function createRedis(array $config): Redis public function testReconnectPreservesExactCancellation(): void { $cancellation = new CanceledException('reconnect canceled'); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); $connection = new class($this->getContainer(), $this->getMockedPool(), $this->standaloneConfig(), $redis, $cancellation) extends PhpRedisConnection { public function __construct( ContainerContract $container, @@ -373,10 +377,10 @@ protected function setOptions(Redis|RedisCluster $redis): void public function testCloseClearsTrackedWatchState(): void { $pool = $this->getMockedPool(); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); - $redis->expects('watch')->with('key')->andReturnTrue(); - $redis->expects('close')->andReturnTrue(); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('watch')->with('key')->returns(true); + $redis->expects('close')->returns(true); $connection = $this->mockRedisConnection(pool: $pool); $connection->setActiveConnection($redis); @@ -388,30 +392,25 @@ public function testCloseClearsTrackedWatchState(): void public function testReleaseChecksNativeModeBeforeRestoringDatabase(): void { $pool = $this->getMockedPool(); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); $redis->expects('select') ->with(2) - ->globally() ->ordered() - ->andReturnTrue(); + ->returns(true); $redis->expects('getMode') - ->globally() ->ordered() - ->andReturn(Redis::ATOMIC); + ->returns(Redis::ATOMIC); $redis->expects('isConnected') - ->globally() ->ordered() - ->andReturnTrue(); + ->returns(true); $redis->expects('getDBNum') - ->globally() ->ordered() - ->andReturn(2); + ->returns(2); $redis->expects('select') ->with(0) - ->globally() ->ordered() - ->andReturnTrue(); + ->returns(true); $connection = $this->mockRedisConnection(pool: $pool, options: ['database' => 0]); $connection->setActiveConnection($redis); $connection->__call('select', [2]); @@ -422,9 +421,9 @@ public function testReleaseChecksNativeModeBeforeRestoringDatabase(): void public function testModeDetectionFailureInvalidatesAndReleasesConnection(): void { $pool = $this->getMockedPool(); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andThrow(new RuntimeException('Mode failed.')); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->throws(new RuntimeException('Mode failed.')); $connection = new class($this->getContainer(), $pool, $this->standaloneConfig()) extends PhpRedisConnectionStub { public function isInvalidForTest(): bool { @@ -448,13 +447,13 @@ public function testReleasePreservesExactCancellationWithoutDispatchingReleaseOb $releaseObserved = true; }); $container->instance('events', $dispatcher); - $pool = m::mock(ConnectionPool::class); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $pool->shouldNotReceive('discard'); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andThrow($cancellation); - $redis->shouldNotReceive('close'); + $pool = Double::for(ConnectionPool::class)->strict(); + $pool->allows('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $pool->expects('discard')->never(); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->throws($cancellation); + $redis->expects('close')->never(); $connection = $this->mockRedisConnection(container: $container, pool: $pool); $connection->setActiveConnection($redis); @@ -482,16 +481,16 @@ public function testReleaseNormalizesWrappedPhpRedisCancellation(): void $releaseObserved = true; }); $container->instance('events', $dispatcher); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldNotReceive('log'); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('log')->never(); $container->instance(StdoutLoggerInterface::class, $logger); - $pool = m::mock(ConnectionPool::class); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $pool->shouldNotReceive('discard'); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andThrow($nativeFailure); - $redis->shouldNotReceive('close'); + $pool = Double::for(ConnectionPool::class)->strict(); + $pool->allows('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $pool->expects('discard')->never(); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->throws($nativeFailure); + $redis->expects('close')->never(); $connection = $this->mockRedisConnection(container: $container, pool: $pool); $connection->setActiveConnection($redis); @@ -510,9 +509,9 @@ public function testReleasePreservesOperationCancellationOverPoolCleanupCancella $cancellation = new CanceledException('mode canceled'); $cleanupCancellation = new CanceledException('pool release canceled'); $pool = $this->getMockedPool(); - $pool->expects('release')->andThrow($cleanupCancellation); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andThrow($cancellation); + $pool->expects('release')->throws($cleanupCancellation); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->throws($cancellation); $connection = $this->mockRedisConnection(pool: $pool); $connection->setActiveConnection($redis); @@ -531,21 +530,21 @@ public function testCancellationFromQueueingWarningInvalidatesAndReleasesWithout $cancellation = $carried ? new RuntimeException('logging failed', previous: new CanceledException('logging canceled')) : new CanceledException('logging canceled'); - $logger = m::mock(StdoutLoggerInterface::class); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); $logger->expects('log') ->with( LogLevel::CRITICAL, 'Discarding Redis connection left in MULTI or PIPELINE mode.' ) - ->andThrow($cancellation); + ->throws($cancellation); $container = $this->getContainer(); $container->instance(StdoutLoggerInterface::class, $logger); $pool = $this->getMockedPool(); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $pool->shouldNotReceive('discard'); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andReturn(Redis::MULTI); - $redis->shouldNotReceive('close'); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $pool->expects('discard')->never(); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->returns(Redis::MULTI); + $redis->expects('close')->never(); $connection = $this->mockRedisConnection(container: $container, pool: $pool); $connection->setActiveConnection($redis); $caught = null; @@ -563,17 +562,17 @@ public function testCancellationFromQueueingWarningInvalidatesAndReleasesWithout public function testReleaseNormalizesWrappedCancellationFromNativeClose(): void { $nativeFailure = new RedisException('close canceled'); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldNotReceive('log'); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('log')->never(); $container = $this->getContainer(); $container->instance(StdoutLoggerInterface::class, $logger); $pool = $this->getMockedPool(); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $pool->shouldNotReceive('discard'); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andReturn(Redis::ATOMIC); - $redis->expects('isConnected')->andThrow(new RuntimeException('validation failed')); - $redis->expects('close')->andThrow($nativeFailure); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $pool->expects('discard')->never(); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->returns(Redis::ATOMIC); + $redis->expects('isConnected')->throws(new RuntimeException('validation failed')); + $redis->expects('close')->throws($nativeFailure); $connection = $this->mockRedisConnection(container: $container, pool: $pool); $connection->setActiveConnection($redis); @@ -590,33 +589,33 @@ public function testReleaseNormalizesWrappedCancellationFromNativeClose(): void public function testDatabaseRestoreFailureClosesTheNativeGenerationBeforeReconnect(string $failureMode): void { $pool = $this->getMockedPool(); - $pool->shouldReceive('getName')->andReturn('default'); - $pool->expects('release')->with(m::type(RedisConnection::class)); - $logger = m::mock(StdoutLoggerInterface::class); + $pool->allows('getName')->returns('default'); + $pool->expects('release')->with(Argument::type(RedisConnection::class)); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); $logger->expects('log')->with( LogLevel::CRITICAL, - m::on(static fn (string $message): bool => str_starts_with($message, 'Release connection failed, caused by ')), + Argument::satisfies(static fn (string $message): bool => str_starts_with($message, 'Release connection failed, caused by ')), ); $container = $this->getContainer(); $container->instance(StdoutLoggerInterface::class, $logger); - $oldRedis = m::mock(Redis::class); - $newRedis = m::mock(Redis::class); + $oldRedis = Double::for(Redis::class)->strict(); + $newRedis = Double::for(Redis::class)->strict(); $this->expectDefaultConnectionOptions($oldRedis); $this->expectDefaultConnectionOptions($newRedis); - $oldRedis->expects('select')->with(2)->andReturnTrue(); - $oldRedis->expects('getMode')->andReturn(Redis::ATOMIC); - $oldRedis->expects('isConnected')->andReturnTrue(); - $oldRedis->expects('getDBNum')->once()->andReturn(2); + $oldRedis->expects('select')->with(2)->returns(true); + $oldRedis->expects('getMode')->returns(Redis::ATOMIC); + $oldRedis->expects('isConnected')->returns(true); + $oldRedis->expects('getDBNum')->returns(2); $restore = $oldRedis->expects('select')->with(0); if ($failureMode === 'false') { - $restore->andReturnFalse(); + $restore->returns(false); } else { - $restore->andThrow(new RuntimeException('Select failed.')); + $restore->throws(new RuntimeException('Select failed.')); } - $oldRedis->expects('close')->andReturnTrue(); - $newRedis->shouldNotReceive('select'); + $oldRedis->expects('close')->returns(true); + $newRedis->expects('select')->never(); $connection = new class($container, $pool, $this->standaloneConfig(), [$oldRedis, $newRedis]) extends PhpRedisConnection { /** * @param Redis[] $clients @@ -662,18 +661,18 @@ public static function databaseRestoreFailureProvider(): array public function testReportingFailureCannotPreventQueueingModeDiscard(): void { $pool = $this->getMockedPool(); - $pool->expects('discard')->with(m::type(RedisConnection::class)); - $logger = m::mock(StdoutLoggerInterface::class); + $pool->expects('discard')->with(Argument::type(RedisConnection::class)); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); $logger->expects('log') ->with( LogLevel::CRITICAL, 'Discarding Redis connection left in MULTI or PIPELINE mode.' ) - ->andThrow(new RuntimeException('Logging failed.')); + ->throws(new RuntimeException('Logging failed.')); $container = $this->getContainer(); $container->instance(StdoutLoggerInterface::class, $logger); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andReturn(Redis::MULTI); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->returns(Redis::MULTI); $connection = $this->mockRedisConnection(container: $container, pool: $pool); $connection->setActiveConnection($redis); @@ -684,9 +683,9 @@ public function testDiscardOwnershipFailurePropagates(): void { $exception = new RuntimeException('Discard ownership failed.'); $pool = $this->getMockedPool(); - $pool->expects('discard')->andThrow($exception); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andReturn(Redis::MULTI); + $pool->expects('discard')->throws($exception); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->returns(Redis::MULTI); $connection = $this->mockRedisConnection(pool: $pool); $connection->setActiveConnection($redis); @@ -701,12 +700,12 @@ public function testDiscardOwnershipFailurePropagates(): void public function testReconnectUsesCurrentDatabaseWhenSet(): void { $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); - $redis->shouldReceive('select')->twice()->with(2)->andReturn(true); - $redis->expects('isConnected')->andReturnTrue(); - $redis->expects('getDBNum')->andReturn(2); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('select')->times(2)->with(2)->returns(true); + $redis->expects('isConnected')->returns(true); + $redis->expects('getDBNum')->returns(2); - $redis->shouldReceive('setOption')->andReturnTrue(); + $redis->allows('setOption')->returns(true); $connection = new class($this->getContainer(), $pool, $this->standaloneConfig(), $redis) extends PhpRedisConnection { public function __construct( @@ -731,18 +730,18 @@ protected function createRedis(array $config): Redis public function testReconnectCarriesTheConnectedNativeClientsActualDatabaseAcrossAReplacement(): void { $pool = $this->getMockedPool(); - $oldRedis = m::mock(Redis::class); - $newRedis = m::mock(Redis::class); - $secondNewRedis = m::mock(Redis::class); + $oldRedis = Double::for(Redis::class)->strict(); + $newRedis = Double::for(Redis::class)->strict(); + $secondNewRedis = Double::for(Redis::class)->strict(); $this->expectDefaultConnectionOptions($oldRedis); $this->expectDefaultConnectionOptions($newRedis); $this->expectDefaultConnectionOptions($secondNewRedis); - $oldRedis->expects('isConnected')->andReturnTrue(); - $oldRedis->expects('getDBNum')->andReturn(2); - $newRedis->expects('select')->with(2)->andReturnTrue(); - $newRedis->expects('isConnected')->andReturnFalse(); - $newRedis->shouldNotReceive('getDBNum'); - $secondNewRedis->expects('select')->with(2)->andReturnTrue(); + $oldRedis->expects('isConnected')->returns(true); + $oldRedis->expects('getDBNum')->returns(2); + $newRedis->expects('select')->with(2)->returns(true); + $newRedis->expects('isConnected')->returns(false); + $newRedis->expects('getDBNum')->never(); + $secondNewRedis->expects('select')->with(2)->returns(true); $connection = new class($this->getContainer(), $pool, $this->standaloneConfig(), [$oldRedis, $newRedis, $secondNewRedis]) extends PhpRedisConnection { /** @@ -772,15 +771,15 @@ protected function createRedis(array $config): Redis public function testReconnectRejectsARefusedDatabaseBeforePublishingTheNewClient(): void { $pool = $this->getMockedPool(); - $pool->expects('getName')->andReturn('default'); - $oldRedis = m::mock(Redis::class); - $newRedis = m::mock(Redis::class); + $pool->expects('getName')->returns('default'); + $oldRedis = Double::for(Redis::class)->strict(); + $newRedis = Double::for(Redis::class)->strict(); $this->expectDefaultConnectionOptions($oldRedis); $this->expectDefaultConnectionOptions($newRedis); - $oldRedis->expects('select')->with(2)->andReturnTrue(); - $oldRedis->shouldNotReceive('isConnected'); - $oldRedis->shouldNotReceive('getDBNum'); - $newRedis->expects('select')->with(2)->andReturnFalse(); + $oldRedis->expects('select')->with(2)->returns(true); + $oldRedis->expects('isConnected')->never(); + $oldRedis->expects('getDBNum')->never(); + $newRedis->expects('select')->with(2)->returns(false); $connection = new class($this->getContainer(), $pool, $this->standaloneConfig(['database' => 2]), [$oldRedis, $newRedis]) extends PhpRedisConnection { /** * @param Redis[] $clients @@ -820,9 +819,9 @@ public function isInvalidForTest(): bool public function testReconnectToDatabaseZeroDoesNotIssueSelect(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); $this->expectDefaultConnectionOptions($redis); - $redis->shouldNotReceive('select'); + $redis->expects('select')->never(); $connection = new class($this->getContainer(), $this->getMockedPool(), $this->standaloneConfig(), $redis) extends PhpRedisConnection { public function __construct( ContainerContract $container, @@ -845,14 +844,14 @@ protected function createRedis(array $config): Redis public function testReconnectDoesNotInspectADisconnectedClientAndUsesTrackedSelection(): void { $pool = $this->getMockedPool(); - $oldRedis = m::mock(Redis::class); - $newRedis = m::mock(Redis::class); + $oldRedis = Double::for(Redis::class)->strict(); + $newRedis = Double::for(Redis::class)->strict(); $this->expectDefaultConnectionOptions($oldRedis); $this->expectDefaultConnectionOptions($newRedis); - $oldRedis->expects('select')->with(2)->andReturnTrue(); - $oldRedis->expects('isConnected')->andReturnFalse(); - $oldRedis->shouldNotReceive('getDBNum'); - $newRedis->expects('select')->with(2)->andReturnTrue(); + $oldRedis->expects('select')->with(2)->returns(true); + $oldRedis->expects('isConnected')->returns(false); + $oldRedis->expects('getDBNum')->never(); + $newRedis->expects('select')->with(2)->returns(true); $connection = new class($this->getContainer(), $pool, $this->standaloneConfig(), [$oldRedis, $newRedis]) extends PhpRedisConnection { /** @@ -882,14 +881,14 @@ protected function createRedis(array $config): Redis public function testReconnectDoesNotInspectAnInvalidClientAndUsesTrackedSelection(): void { $pool = $this->getMockedPool(); - $oldRedis = m::mock(Redis::class); - $newRedis = m::mock(Redis::class); + $oldRedis = Double::for(Redis::class)->strict(); + $newRedis = Double::for(Redis::class)->strict(); $this->expectDefaultConnectionOptions($oldRedis); $this->expectDefaultConnectionOptions($newRedis); - $oldRedis->expects('select')->with(2)->andReturnTrue(); - $oldRedis->shouldNotReceive('isConnected'); - $oldRedis->shouldNotReceive('getDBNum'); - $newRedis->expects('select')->with(2)->andReturnTrue(); + $oldRedis->expects('select')->with(2)->returns(true); + $oldRedis->expects('isConnected')->never(); + $oldRedis->expects('getDBNum')->never(); + $newRedis->expects('select')->with(2)->returns(true); $connection = new class($this->getContainer(), $pool, $this->standaloneConfig(), [$oldRedis, $newRedis]) extends PhpRedisConnection { /** * @param Redis[] $clients @@ -918,18 +917,18 @@ protected function createRedis(array $config): Redis public function testSentinelResolvedMasterUsesStandaloneDataConnectionSettings(): void { - $sentinelFactory = m::mock(RedisSentinelFactory::class); - $sentinelFactory->expects('resolveMaster')->andReturn(['127.0.0.1', 6380]); - $container = m::mock(ContainerContract::class); + $sentinelFactory = Double::for(RedisSentinelFactory::class)->strict(); + $sentinelFactory->expects('resolveMaster')->returns(['127.0.0.1', 6380]); + $container = Double::for(ContainerContract::class, override: true)->strict(); $container->expects('make') ->with(RedisSentinelFactory::class) - ->andReturn($sentinelFactory); - $container->shouldReceive('bound')->with('events')->andReturnFalse(); - $container->shouldReceive('has')->andReturnFalse(); - $redis = m::mock(Redis::class); - $redis->expects('setOption')->with(Redis::OPT_READ_TIMEOUT, 2.5)->andReturnTrue(); + ->returns($sentinelFactory); + $container->allows('bound')->with('events')->returns(false); + $container->allows('has')->returns(false); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('setOption')->with(Redis::OPT_READ_TIMEOUT, 2.5)->returns(true); $this->expectDefaultConnectionOptions($redis); - $connection = new class($container, $this->getMockedPool(), $this->sentinelConfig(['timeout' => 1.5, 'read_timeout' => 2.5, 'context' => ['stream' => ['tcp_nodelay' => true]]]), $redis) extends PhpRedisConnection { + $connection = new class($container->instance(), $this->getMockedPool(), $this->sentinelConfig(['timeout' => 1.5, 'read_timeout' => 2.5, 'context' => ['stream' => ['tcp_nodelay' => true]]]), $redis) extends PhpRedisConnection { private array $createdConfig = []; public function __construct( @@ -965,17 +964,17 @@ protected function createRedis(array $config): Redis public function testSentinelResolutionPreservesExactCancellation(): void { $cancellation = new CanceledException('sentinel canceled'); - $sentinelFactory = m::mock(RedisSentinelFactory::class); - $sentinelFactory->expects('resolveMaster')->andThrow($cancellation); - $container = m::mock(ContainerContract::class); + $sentinelFactory = Double::for(RedisSentinelFactory::class)->strict(); + $sentinelFactory->expects('resolveMaster')->throws($cancellation); + $container = Double::for(ContainerContract::class, override: true)->strict(); $container->expects('make') ->with(RedisSentinelFactory::class) - ->andReturn($sentinelFactory); - $container->shouldReceive('bound')->with('events')->andReturnFalse(); - $container->shouldReceive('has')->andReturnFalse(); + ->returns($sentinelFactory); + $container->allows('bound')->with('events')->returns(false); + $container->allows('has')->returns(false); try { - new PhpRedisConnection($container, $this->getMockedPool(), $this->sentinelConfig()); + new PhpRedisConnection($container->instance(), $this->getMockedPool(), $this->sentinelConfig()); $this->fail('Expected the cancellation to escape.'); } catch (CanceledException $exception) { $this->assertSame($cancellation, $exception); @@ -985,17 +984,17 @@ public function testSentinelResolutionPreservesExactCancellation(): void public function testSentinelResolutionPreservesTheUnderlyingFailure(): void { $failure = new RuntimeException('sentinel unavailable'); - $sentinelFactory = m::mock(RedisSentinelFactory::class); - $sentinelFactory->expects('resolveMaster')->andThrow($failure); - $container = m::mock(ContainerContract::class); + $sentinelFactory = Double::for(RedisSentinelFactory::class)->strict(); + $sentinelFactory->expects('resolveMaster')->throws($failure); + $container = Double::for(ContainerContract::class, override: true)->strict(); $container->expects('make') ->with(RedisSentinelFactory::class) - ->andReturn($sentinelFactory); - $container->shouldReceive('bound')->with('events')->andReturnFalse(); - $container->shouldReceive('has')->andReturnFalse(); + ->returns($sentinelFactory); + $container->allows('bound')->with('events')->returns(false); + $container->allows('has')->returns(false); try { - new PhpRedisConnection($container, $this->getMockedPool(), $this->sentinelConfig()); + new PhpRedisConnection($container->instance(), $this->getMockedPool(), $this->sentinelConfig()); $this->fail('Expected Sentinel resolution to fail.'); } catch (ConnectionException $exception) { $this->assertSame('Connection reconnect failed: sentinel unavailable', $exception->getMessage()); @@ -1177,10 +1176,10 @@ public function testClusterReconnectFailureThrowsConnectionException(): void public function testQueueingModeBypassesTransformedSet(): void { $connection = $this->mockRedisConnection(transform: true); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('getMode')->once()->andReturn(Redis::MULTI); - $redis->shouldReceive('set')->once()->with('key', 'value', 600)->andReturnSelf(); + $redis->expects('getMode')->returns(Redis::MULTI); + $redis->expects('set')->with('key', 'value', 600)->returns($redis); $connection->setActiveConnection($redis); @@ -1192,10 +1191,10 @@ public function testQueueingModeBypassesTransformedSet(): void public function testPipelineModeBypassesTransformedSet(): void { $connection = $this->mockRedisConnection(transform: true); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('getMode')->once()->andReturn(Redis::PIPELINE); - $redis->shouldReceive('set')->once()->with('key', 'value', 600)->andReturnSelf(); + $redis->expects('getMode')->returns(Redis::PIPELINE); + $redis->expects('set')->with('key', 'value', 600)->returns($redis); $connection->setActiveConnection($redis); @@ -1207,13 +1206,12 @@ public function testPipelineModeBypassesTransformedSet(): void public function testQueueingModeReshapesSetArgumentsButPreservesRawQueuedReturn(): void { $connection = $this->mockRedisConnection(transform: true); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('getMode')->once()->andReturn(Redis::MULTI); - $redis->shouldReceive('set') - ->once() + $redis->expects('getMode')->returns(Redis::MULTI); + $redis->expects('set') ->with('key', 'value', ['NX', 'EX' => 600]) - ->andReturnSelf(); + ->returns($redis); $connection->setActiveConnection($redis); @@ -1225,13 +1223,12 @@ public function testQueueingModeReshapesSetArgumentsButPreservesRawQueuedReturn( public function testQueueingModePreservesNativeSetOptionsAndRawQueuedReturn(): void { $connection = $this->mockRedisConnection(transform: true); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('getMode')->once()->andReturn(Redis::MULTI); - $redis->shouldReceive('set') - ->once() + $redis->expects('getMode')->returns(Redis::MULTI); + $redis->expects('set') ->with('key', 'value', ['GET', 'EX' => 600]) - ->andReturnSelf(); + ->returns($redis); $connection->setActiveConnection($redis); @@ -1243,13 +1240,12 @@ public function testQueueingModePreservesNativeSetOptionsAndRawQueuedReturn(): v public function testQueueingModeReshapesHmsetArgumentsButPreservesRawQueuedReturn(): void { $connection = $this->mockRedisConnection(transform: true); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('getMode')->once()->andReturn(Redis::MULTI); - $redis->shouldReceive('hMSet') - ->once() + $redis->expects('getMode')->returns(Redis::MULTI); + $redis->expects('hMSet') ->with('hash', ['field1' => 'value1', 'field2' => 'value2']) - ->andReturnSelf(); + ->returns($redis); $connection->setActiveConnection($redis); @@ -1261,13 +1257,12 @@ public function testQueueingModeReshapesHmsetArgumentsButPreservesRawQueuedRetur public function testQueueingModeReshapesLremArgumentsButPreservesRawQueuedReturn(): void { $connection = $this->mockRedisConnection(transform: true); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('getMode')->once()->andReturn(Redis::MULTI); - $redis->shouldReceive('lRem') - ->once() + $redis->expects('getMode')->returns(Redis::MULTI); + $redis->expects('lRem') ->with('list', 'value', 2) - ->andReturnSelf(); + ->returns($redis); $connection->setActiveConnection($redis); @@ -1279,13 +1274,12 @@ public function testQueueingModeReshapesLremArgumentsButPreservesRawQueuedReturn public function testQueueingModeReshapesZaddArgumentsButPreservesRawQueuedReturn(): void { $connection = $this->mockRedisConnection(transform: true); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('getMode')->once()->andReturn(Redis::MULTI); - $redis->shouldReceive('zAdd') - ->once() + $redis->expects('getMode')->returns(Redis::MULTI); + $redis->expects('zAdd') ->with('sortedset', ['NX', 'CH'], 1.0, 'member1', 2.0, 'member2') - ->andReturnSelf(); + ->returns($redis); $connection->setActiveConnection($redis); @@ -1297,13 +1291,12 @@ public function testQueueingModeReshapesZaddArgumentsButPreservesRawQueuedReturn public function testQueueingModeReshapesZrangebyscoreArgumentsButPreservesRawQueuedReturn(): void { $connection = $this->mockRedisConnection(transform: true); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('getMode')->once()->andReturn(Redis::MULTI); - $redis->shouldReceive('zRangeByScore') - ->once() + $redis->expects('getMode')->returns(Redis::MULTI); + $redis->expects('zRangeByScore') ->with('sortedset', '1', '5', ['limit' => [0, 10]]) - ->andReturnSelf(); + ->returns($redis); $connection->setActiveConnection($redis); @@ -1315,13 +1308,12 @@ public function testQueueingModeReshapesZrangebyscoreArgumentsButPreservesRawQue public function testQueueingModeReshapesZinterstoreArgumentsButPreservesRawQueuedReturn(): void { $connection = $this->mockRedisConnection(transform: true); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('getMode')->once()->andReturn(Redis::MULTI); - $redis->shouldReceive('zinterstore') - ->once() + $redis->expects('getMode')->returns(Redis::MULTI); + $redis->expects('zinterstore') ->with('output', ['set1', 'set2'], [1, 2], 'max') - ->andReturnSelf(); + ->returns($redis); $connection->setActiveConnection($redis); @@ -1335,10 +1327,10 @@ public function testNumericArgumentsPreserveFailuresAndQueuedReturns(string $met { foreach ([Redis::ATOMIC, Redis::MULTI, Redis::PIPELINE] as $mode) { $connection = $this->mockRedisConnection(transform: true); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andReturn($mode); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->returns($mode); $result = $mode === Redis::ATOMIC ? false : $redis; - $redis->expects($method)->with(...$expected)->andReturn($result); + $redis->expects($method)->with(...$expected)->returns($result); $connection->setActiveConnection($redis); $this->assertSame($result, $connection->__call($method, $arguments)); @@ -1373,10 +1365,10 @@ public function testClusterScoreRemovalPreservesNamedBoundsAndQueuedReturns(): v foreach ([Redis::ATOMIC, Redis::MULTI] as $mode) { $connection = new PhpRedisClusterConnectionStub; $connection->shouldTransform(); - $redis = m::mock(RedisCluster::class); - $redis->expects('getMode')->andReturn($mode); + $redis = Double::for(RedisCluster::class)->strict(); + $redis->expects('getMode')->returns($mode); $result = $mode === Redis::ATOMIC ? false : $redis; - $redis->expects('zRemRangeByScore')->with('set', '1.5', '(2')->andReturn($result); + $redis->expects('zRemRangeByScore')->with('set', '1.5', '(2')->returns($result); $connection->setActiveConnection($redis); $this->assertSame($result, $connection->zRemRangeByScore('set', min: 1.5, max: '(2')); @@ -1416,13 +1408,12 @@ public function prepareEvalshaForTest(mixed ...$arguments): array public function testQueueingModeReshapesExecuteRawArgumentsButPreservesRawQueuedReturn(): void { $connection = $this->mockRedisConnection(transform: true); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('getMode')->once()->andReturn(Redis::MULTI); - $redis->shouldReceive('rawCommand') - ->once() + $redis->expects('getMode')->returns(Redis::MULTI); + $redis->expects('rawCommand') ->with('CUSTOM', 'arg1', 'arg2') - ->andReturnSelf(); + ->returns($redis); $connection->setActiveConnection($redis); @@ -1434,10 +1425,10 @@ public function testQueueingModeReshapesExecuteRawArgumentsButPreservesRawQueued public function testTransformDisabledSetUsesNativeSignatureWithoutInspectingMode(): void { $connection = $this->mockRedisConnection(transform: false); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('getMode')->never(); - $redis->shouldReceive('set')->once()->with('key', 'value', 600)->andReturn(true); + $redis->expects('getMode')->never(); + $redis->expects('set')->with('key', 'value', 600)->returns(true); $connection->setActiveConnection($redis); @@ -1449,13 +1440,12 @@ public function testTransformDisabledSetUsesNativeSignatureWithoutInspectingMode public function testTypeErrorsAreNotRetried(): void { $connection = $this->mockRedisConnection(transform: true); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('getMode')->once()->andReturn(Redis::ATOMIC); - $redis->shouldReceive('set') - ->once() + $redis->expects('getMode')->returns(Redis::ATOMIC); + $redis->expects('set') ->with('key', 'value', 600) - ->andThrow(new TypeError('Invalid native Redis argument.')); + ->throws(new TypeError('Invalid native Redis argument.')); $connection->setActiveConnection($redis); $this->expectException(TypeError::class); @@ -1493,16 +1483,16 @@ protected function greeting(): callable public function testMacroLookupPreservesExactNamesAndMayShadowNativeCommands(): void { - RedisConnection::macro('CustomCommand', fn () => 'exact'); + RedisConnection::macro('GET', fn () => 'exact'); RedisConnection::macro('reset', fn () => 'shadowed'); $connection = $this->mockRedisConnection(); - $redis = m::mock(Redis::class); - $redis->expects('customcommand')->once()->andReturn('native'); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('get')->with('key')->returns('native'); $redis->expects('reset')->never(); $connection->setActiveConnection($redis); - $this->assertSame('exact', $connection->__call('CustomCommand', [])); - $this->assertSame('native', $connection->__call('customcommand', [])); + $this->assertSame('exact', $connection->__call('GET', [])); + $this->assertSame('native', $connection->__call('get', ['key'])); $this->assertSame('shadowed', $connection->__call('reset', [])); } @@ -1516,9 +1506,9 @@ public function testRedisExceptionInsideMacroUsesConnectionDispositionRule(): vo $this->getContainer(), $this->getMockedPool(), ); - $redis = m::mock(Redis::class); - $redis->expects('get')->once()->with('key')->andThrow($exception); - $redis->expects('getLastError')->andReturnNull(); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('get')->with('key')->throws($exception); + $redis->expects('getLastError')->returns(null); $connection->setActiveConnection($redis); try { @@ -1534,12 +1524,11 @@ public function testRedisExceptionInsideMacroUsesConnectionDispositionRule(): vo public function testTransportFailureInvalidatesWithoutReplayingCommand(): void { $exception = new RedisException('Connection lost.'); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); $redis->expects('get') - ->once() ->with('foo') - ->andThrow($exception); - $redis->expects('getLastError')->andReturnNull(); + ->throws($exception); + $redis->expects('getLastError')->returns(null); $connection = new PhpRedisConnectionStub( $this->getContainer(), $this->getMockedPool(), @@ -1559,11 +1548,10 @@ public function testTransportFailureInvalidatesWithoutReplayingCommand(): void public function testClusterTransportFailureInvalidatesWithoutReplayingCommand(): void { $exception = new RedisClusterException('Error processing EXEC across the cluster'); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); $redis->expects('exec') - ->once() - ->andThrow($exception); - $redis->expects('getLastError')->andReturn("CROSSSLOT Keys in request don't hash to the same slot"); + ->throws($exception); + $redis->expects('getLastError')->returns("CROSSSLOT Keys in request don't hash to the same slot"); $connection = new PhpRedisConnectionStub( $this->getContainer(), $this->getMockedPool(), @@ -1588,16 +1576,16 @@ public function testConnectionRebuildsItsClientOnNextAcquisitionWithoutReplaying array $arguments, bool $synchronized, ): void { - $failedClient = m::mock(Redis::class); - $healthyClient = m::mock(Redis::class); + $failedClient = Double::for(Redis::class)->strict(); + $healthyClient = Double::for(Redis::class)->strict(); $this->expectDefaultConnectionOptions($failedClient); $this->expectDefaultConnectionOptions($healthyClient); - $failedClient->expects($command)->once()->with(...$arguments)->andThrow($exception); + $failedClient->expects($command)->with(...$arguments)->throws($exception); if (! $exception instanceof ErrorException) { - $failedClient->expects('getLastError')->andReturn($synchronized ? $exception->getMessage() : null); + $failedClient->expects('getLastError')->returns($synchronized ? $exception->getMessage() : null); } - $failedClient->shouldNotReceive('isConnected'); - $healthyClient->expects('get')->once()->with('foo')->andReturn('bar'); + $failedClient->expects('isConnected')->never(); + $healthyClient->expects('get')->with('foo')->returns('bar'); $connection = new class($this->getContainer(), $this->getMockedPool(), $this->standaloneConfig(), [$failedClient, $healthyClient]) extends PhpRedisConnection { /** @@ -1663,9 +1651,9 @@ public static function connectionFailureProvider(): array public function testConnectionDoesNotRetryUnrelatedWarnings(): void { $exception = new ErrorException('Redis::get(): Undefined variable'); - $redis = m::mock(Redis::class); - $redis->expects('get')->once()->with('foo')->andThrow($exception); - $redis->shouldNotReceive('getLastError'); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('get')->with('foo')->throws($exception); + $redis->expects('getLastError')->never(); $connection = new PhpRedisConnectionStub($this->getContainer(), $this->getMockedPool()); $connection->setActiveConnection($redis); @@ -1686,9 +1674,9 @@ public function testSynchronizedServerErrorDispositionDoesNotReplayCommand( bool $invalid, ): void { $exception = new RedisException($message); - $redis = m::mock(Redis::class); - $redis->expects('set')->once()->with('key', 'value')->andThrow($exception); - $redis->expects('getLastError')->andReturn($message); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('set')->with('key', 'value')->throws($exception); + $redis->expects('getLastError')->returns($message); $connection = new PhpRedisConnectionStub( $this->getContainer(), $this->getMockedPool(), @@ -1724,20 +1712,19 @@ public static function synchronizedServerErrorDispositionProvider(): array public function testLogWritesToStdoutLogger(): void { $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('log') - ->once() + $redis = Double::for(Redis::class)->strict(); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('log') ->with(LogLevel::ERROR, 'unit'); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->andReturn(true); - $container->shouldReceive('make')->with(StdoutLoggerInterface::class)->andReturn($logger); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->allows('bound')->with('events')->returns(false); + $container->allows('has')->with(StdoutLoggerInterface::class)->returns(true); + $container->allows('make')->with(StdoutLoggerInterface::class)->returns($logger); - $redis->shouldReceive('setOption')->andReturnTrue(); + $redis->allows('setOption')->returns(true); - $connection = new class($container, $pool, $this->standaloneConfig(), $redis) extends PhpRedisConnection { + $connection = new class($container->instance(), $pool, $this->standaloneConfig(), $redis) extends PhpRedisConnection { public function __construct( ContainerContract $container, ConnectionPool $pool, @@ -1765,11 +1752,10 @@ public function testCallGet(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('get') + $connection->nativeClientForTest() + ->expects('get') ->with($key = 'foo') - ->once() - ->andReturn($value = 'bar'); + ->returns($value = 'bar'); $result = $connection->__call('get', [$key]); @@ -1783,11 +1769,10 @@ public function testGetPreservesDecodedValues(): void foreach ([['nested' => true], $object, 42] as $index => $value) { $key = "key-{$index}"; - $connection->getConnection() - ->shouldReceive('get') + $connection->nativeClientForTest() + ->expects('get') ->with($key) - ->once() - ->andReturn($value); + ->returns($value); $this->assertSame($value, $connection->__call('get', [$key])); } @@ -1797,11 +1782,10 @@ public function testMget(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('mGet') + $connection->nativeClientForTest() + ->expects('mGet') ->with(['key1', 'key2', 'key3']) - ->once() - ->andReturn(['value1', false, 'value3']); + ->returns(['value1', false, 'value3']); $result = $connection->__call('mget', [['key1', 'key2', 'key3']]); @@ -1812,11 +1796,10 @@ public function testMgetPreservesWholeCallFailure(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('mGet') + $connection->nativeClientForTest() + ->expects('mGet') ->with(['key1', 'key2']) - ->once() - ->andReturnFalse(); + ->returns(false); $this->assertFalse($connection->__call('mget', [['key1', 'key2']])); } @@ -1824,7 +1807,7 @@ public function testMgetPreservesWholeCallFailure(): void public function testMgetReturnsAnEmptyArrayWithoutCallingRedisForEmptyKeys(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection()->shouldReceive('mGet')->never(); + $connection->nativeClientForTest()->expects('mGet')->never(); $this->assertSame([], $connection->__call('mget', [[]])); } @@ -1833,11 +1816,10 @@ public function testSet(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('set') + $connection->nativeClientForTest() + ->expects('set') ->with('key', 'value', ['NX', 'EX' => 3600]) - ->once() - ->andReturn(true); + ->returns(true); $result = $connection->__call('set', ['key', 'value', 'EX', 3600, 'NX']); @@ -1885,11 +1867,10 @@ public function testSetPreservesBooleanNativeResults(): void foreach ([true, false] as $index => $result) { $key = "key-{$index}"; - $connection->getConnection() - ->shouldReceive('set') + $connection->nativeClientForTest() + ->expects('set') ->with($key, 'value', ['GET']) - ->once() - ->andReturn($result); + ->returns($result); $this->assertSame($result, $connection->__call('set', [$key, 'value', ['GET']])); } @@ -1899,11 +1880,10 @@ public function testSetnxAcceptsNonStringValues(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('setNx') + $connection->nativeClientForTest() + ->expects('setNx') ->with('key', 123) - ->once() - ->andReturn(true); + ->returns(true); $result = $connection->__call('setnx', ['key', 123]); @@ -1914,11 +1894,10 @@ public function testHmgetSingleArray(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('hMGet') + $connection->nativeClientForTest() + ->expects('hMGet') ->with('hash', ['field1', 'field2']) - ->once() - ->andReturn(['field1' => 'value1', 'field2' => 'value2']); + ->returns(['field1' => 'value1', 'field2' => 'value2']); $result = $connection->__call('hmget', ['hash', ['field1', 'field2']]); @@ -1929,11 +1908,10 @@ public function testHmgetMultipleArgs(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('hMGet') + $connection->nativeClientForTest() + ->expects('hMGet') ->with('hash', ['field1', 'field2']) - ->once() - ->andReturn(['field1' => 'value1', 'field2' => 'value2']); + ->returns(['field1' => 'value1', 'field2' => 'value2']); $result = $connection->__call('hmget', ['hash', 'field1', 'field2']); @@ -1944,11 +1922,10 @@ public function testHmgetPreservesWholeCallFailure(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('hMGet') + $connection->nativeClientForTest() + ->expects('hMGet') ->with('hash', ['field1', 'field2']) - ->once() - ->andReturnFalse(); + ->returns(false); $this->assertFalse($connection->__call('hmget', ['hash', ['field1', 'field2']])); } @@ -1957,11 +1934,10 @@ public function testHmset(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('hMSet') + $connection->nativeClientForTest() + ->expects('hMSet') ->with('hash', ['field1' => 'value1', 'field2' => 'value2']) - ->once() - ->andReturn(true); + ->returns(true); $result = $connection->__call('hmset', ['hash', ['field1' => 'value1', 'field2' => 'value2']]); @@ -1973,11 +1949,10 @@ public function testHsetnxAcceptsNonStringValues(): void $connection = $this->mockRedisConnection(transform: true); $value = ['nested' => 'value']; - $connection->getConnection() - ->shouldReceive('hSetNx') + $connection->nativeClientForTest() + ->expects('hSetNx') ->with('hash', 'field', $value) - ->once() - ->andReturn(true); + ->returns(true); $result = $connection->__call('hsetnx', ['hash', 'field', $value]); @@ -1988,11 +1963,10 @@ public function testLrem(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('lRem') + $connection->nativeClientForTest() + ->expects('lRem') ->with('list', 'value', 2) - ->once() - ->andReturn(1); + ->returns(1); $result = $connection->__call('lrem', ['list', 2, 'value']); @@ -2003,11 +1977,10 @@ public function testBlpopWithResult(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('blPop') + $connection->nativeClientForTest() + ->expects('blPop') ->with('list1', 'list2', 10) - ->once() - ->andReturn(['list1', 'value']); + ->returns(['list1', 'value']); $result = $connection->__call('blpop', ['list1', 'list2', 10]); @@ -2018,11 +1991,10 @@ public function testBlpopEmpty(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('blPop') + $connection->nativeClientForTest() + ->expects('blPop') ->with('list1', 10) - ->once() - ->andReturn([]); + ->returns([]); $result = $connection->__call('blpop', ['list1', 10]); @@ -2033,11 +2005,10 @@ public function testBrpopWithResult(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('brPop') + $connection->nativeClientForTest() + ->expects('brPop') ->with('list1', 'list2', 10) - ->once() - ->andReturn(['list2', 'value']); + ->returns(['list2', 'value']); $result = $connection->__call('brpop', ['list1', 'list2', 10]); @@ -2048,11 +2019,10 @@ public function testBrpopEmpty(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('brPop') + $connection->nativeClientForTest() + ->expects('brPop') ->with('list1', 10) - ->once() - ->andReturn([]); + ->returns([]); $result = $connection->__call('brpop', ['list1', 10]); @@ -2063,11 +2033,10 @@ public function testSpop(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('sPop') + $connection->nativeClientForTest() + ->expects('sPop') ->with('myset', 2) - ->once() - ->andReturn(['member1', 'member2']); + ->returns(['member1', 'member2']); $result = $connection->__call('spop', ['myset', 2]); @@ -2077,23 +2046,16 @@ public function testSpop(): void #[DataProvider('scanOptions')] public function testScan(array $options, string $pattern, int $count): void { + $client = new FakeRedisClient(scanResults: [['keys' => ['key1', 'key2'], 'iterator' => 0]]); $connection = $this->mockRedisConnection(transform: true); + $connection->setActiveConnection($client); $cursor = null; - $connection->getConnection() - ->shouldReceive('scan') - ->with(null, $pattern, $count) - ->once() - ->andReturnUsing(function (?int &$cursor): array { - $cursor = 0; - - return ['key1', 'key2']; - }); - $result = $connection->scan($cursor, ...$options); $this->assertSame([0, ['key1', 'key2']], $result); $this->assertSame(0, $cursor); + $this->assertSame([['iterator' => null, 'pattern' => $pattern, 'count' => $count]], $client->getScanCalls()); } /** @@ -2113,10 +2075,10 @@ public static function scanOptions(): array public function testTransformedScanInvalidatesOnTransportFailure(): void { $exception = new RedisException('Connection lost'); - $redis = m::mock(Redis::class); - $redis->expects('getMode')->andReturn(Redis::ATOMIC); - $redis->expects('scan')->once()->with(null, '*', 10)->andThrow($exception); - $redis->expects('getLastError')->andReturnNull(); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('getMode')->returns(Redis::ATOMIC); + $redis->expects('scan')->with(null, '*', 10)->throws($exception); + $redis->expects('getLastError')->returns(null); $connection = new PhpRedisConnectionStub($this->getContainer(), $this->getMockedPool()); $connection->setActiveConnection($redis); $connection->shouldTransform(true); @@ -2134,113 +2096,82 @@ public function testTransformedScanInvalidatesOnTransportFailure(): void public function testScanWithOptions(): void { + $client = new FakeRedisClient(scanResults: [['keys' => ['key1', 'key2'], 'iterator' => 0]]); $connection = $this->mockRedisConnection(transform: true); + $connection->setActiveConnection($client); $cursor = 0; - $connection->getConnection() - ->shouldReceive('scan') - ->with(0, 'prefix:*', 20) - ->once() - ->andReturn(['key1', 'key2']); - $result = $connection->scan($cursor, 'prefix:*', 20); - $this->assertEquals([0, ['key1', 'key2']], $result); + $this->assertSame([0, ['key1', 'key2']], $result); + $this->assertSame([['iterator' => 0, 'pattern' => 'prefix:*', 'count' => 20]], $client->getScanCalls()); } public function testScanWithEmptyResult(): void { + $client = new FakeRedisClient; $connection = $this->mockRedisConnection(transform: true); + $connection->setActiveConnection($client); $cursor = 0; - $connection->getConnection() - ->shouldReceive('scan') - ->with(0, '*', 10) - ->once() - ->andReturn(false); - - $result = $connection->scan($cursor, '*', 10); - - $this->assertFalse($result); + $this->assertFalse($connection->scan($cursor, '*', 10)); + $this->assertSame([['iterator' => 0, 'pattern' => '*', 'count' => 10]], $client->getScanCalls()); } public function testZscan(): void { + $client = new FakeRedisClient(zScanResults: ['sortedset' => [['members' => ['member1' => 1.0, 'member2' => 2.0], 'iterator' => 0]]]); $connection = $this->mockRedisConnection(transform: true); + $connection->setActiveConnection($client); $cursor = 5; - $connection->getConnection() - ->shouldReceive('zscan') - ->with('sortedset', 5, '*', 10) - ->once() - ->andReturnUsing(function (string $key, int &$cursor): array { - $cursor = 0; - - return ['member1' => 1.0, 'member2' => 2.0]; - }); - $result = $connection->zscan('sortedset', $cursor); $this->assertSame([0, ['member1' => 1.0, 'member2' => 2.0]], $result); $this->assertSame(0, $cursor); + $this->assertSame([['key' => 'sortedset', 'iterator' => 5, 'pattern' => '*', 'count' => 10]], $client->getZScanCalls()); } public function testHscan(): void { + $client = new FakeRedisClient(hScanResults: ['hash' => [['fields' => ['field1' => 'value1', 'field2' => 'value2'], 'iterator' => 0]]]); $connection = $this->mockRedisConnection(transform: true); + $connection->setActiveConnection($client); $cursor = 5; - $connection->getConnection() - ->shouldReceive('hscan') - ->with('hash', 5, '*', 10) - ->once() - ->andReturnUsing(function (string $key, int &$cursor): array { - $cursor = 0; - - return ['field1' => 'value1', 'field2' => 'value2']; - }); - $result = $connection->hscan('hash', $cursor); $this->assertSame([0, ['field1' => 'value1', 'field2' => 'value2']], $result); $this->assertSame(0, $cursor); + $this->assertSame([['key' => 'hash', 'iterator' => 5, 'pattern' => '*', 'count' => 10]], $client->getHScanCalls()); } public function testSscan(): void { + $client = new FakeRedisClient(sScanResults: ['set' => [['members' => ['member1', 'member2'], 'iterator' => 0]]]); $connection = $this->mockRedisConnection(transform: true); + $connection->setActiveConnection($client); $cursor = 5; - $connection->getConnection() - ->shouldReceive('sscan') - ->with('set', 5, '*', 10) - ->once() - ->andReturnUsing(function (string $key, int &$cursor): array { - $cursor = 0; - - return ['member1', 'member2']; - }); - $result = $connection->sscan('set', $cursor); $this->assertSame([0, ['member1', 'member2']], $result); $this->assertSame(0, $cursor); + $this->assertSame([['key' => 'set', 'iterator' => 5, 'pattern' => '*', 'count' => 10]], $client->getSScanCalls()); } public function testEvalsha(): void { $connection = $this->mockRedisConnection(transform: true); - $redisConnection = $connection->getConnection(); - $redisConnection->shouldReceive('script') + $redisConnection = $connection->nativeClientForTest(); + $redisConnection->expects('script') ->with('load', 'script') - ->once() - ->andReturn('sha1'); + ->returns('sha1'); - $redisConnection->shouldReceive('evalSha') + $redisConnection->expects('evalSha') ->with('sha1', ['key1', 'key2'], 2) - ->once() - ->andReturn('result'); + ->returns('result'); $result = $connection->__call('evalsha', ['script', 2, 'key1', 'key2']); @@ -2251,11 +2182,10 @@ public function testZaddWithOptions(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('zAdd') + $connection->nativeClientForTest() + ->expects('zAdd') ->with('sortedset', ['NX', 'CH'], 1.0, 'member1', 2.0, 'member2') - ->once() - ->andReturn(2); + ->returns(2); $result = $connection->__call('zadd', ['sortedset', 'NX', 'CH', 1.0, 'member1', 2.0, 'member2']); @@ -2266,16 +2196,14 @@ public function testZaddPreservesIncrementScoreAndFailure(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('zAdd') + $connection->nativeClientForTest() + ->expects('zAdd') ->with('sortedset', ['INCR'], 1.5, 'member') - ->once() - ->andReturn(2.5); - $connection->getConnection() - ->shouldReceive('zAdd') + ->returns(2.5); + $connection->nativeClientForTest() + ->expects('zAdd') ->with('sortedset', ['XX'], 1.5, 'missing') - ->once() - ->andReturnFalse(); + ->returns(false); $this->assertSame(2.5, $connection->__call('zadd', ['sortedset', 'INCR', 1.5, 'member'])); $this->assertFalse($connection->__call('zadd', ['sortedset', 'XX', 1.5, 'missing'])); @@ -2285,11 +2213,10 @@ public function testZaddWithArray(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('zAdd') + $connection->nativeClientForTest() + ->expects('zAdd') ->with('sortedset', [], 1.0, 'member1', 2.0, 'member2') - ->once() - ->andReturn(2); + ->returns(2); $result = $connection->__call('zadd', ['sortedset', ['member1' => 1.0, 'member2' => 2.0]]); @@ -2300,11 +2227,10 @@ public function testZrangebyscoreWithOptions(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('zRangeByScore') + $connection->nativeClientForTest() + ->expects('zRangeByScore') ->with('sortedset', '1', '5', ['limit' => [0, 10]]) - ->once() - ->andReturn(['member1', 'member2']); + ->returns(['member1', 'member2']); $result = $connection->__call('zrangebyscore', ['sortedset', '1', '5', ['limit' => ['offset' => 0, 'count' => 10]]]); @@ -2315,11 +2241,10 @@ public function testZrangebyscorePreservesFailure(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('zRangeByScore') + $connection->nativeClientForTest() + ->expects('zRangeByScore') ->with('sortedset', '1', '5', []) - ->once() - ->andReturnFalse(); + ->returns(false); $this->assertFalse($connection->__call('zrangebyscore', ['sortedset', '1', '5'])); } @@ -2328,11 +2253,10 @@ public function testFlushdbAsync(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('flushdb') + $connection->nativeClientForTest() + ->expects('flushdb') ->with(true) - ->once() - ->andReturn(true); + ->returns(true); $result = $connection->__call('flushdb', ['ASYNC']); @@ -2343,11 +2267,10 @@ public function testFlushdbSync(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('flushdb') + $connection->nativeClientForTest() + ->expects('flushdb') ->with() - ->once() - ->andReturn(true); + ->returns(true); $result = $connection->__call('flushdb', []); @@ -2358,11 +2281,10 @@ public function testExecuteRaw(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('rawCommand') + $connection->nativeClientForTest() + ->expects('rawCommand') ->with('CUSTOM', 'arg1', 'arg2') - ->once() - ->andReturn('result'); + ->returns('result'); $result = $connection->__call('executeRaw', [['CUSTOM', 'arg1', 'arg2']]); @@ -2373,11 +2295,10 @@ public function testZinterstoreWithOptions(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('zinterstore') + $connection->nativeClientForTest() + ->expects('zinterstore') ->with('output', ['set1', 'set2'], [1, 2], 'max') - ->once() - ->andReturn(3); + ->returns(3); $result = $connection->__call('zinterstore', ['output', ['set1', 'set2'], ['weights' => [1, 2], 'aggregate' => 'max']]); @@ -2388,11 +2309,10 @@ public function testZinterstorePreservesFailure(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('zinterstore') + $connection->nativeClientForTest() + ->expects('zinterstore') ->with('output', ['set1', 'set2'], null, 'sum') - ->once() - ->andReturnFalse(); + ->returns(false); $this->assertFalse($connection->__call('zinterstore', ['output', ['set1', 'set2']])); } @@ -2401,11 +2321,10 @@ public function testZunionstorePreservesFailure(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('zunionstore') + $connection->nativeClientForTest() + ->expects('zunionstore') ->with('output', ['set1', 'set2'], null, 'sum') - ->once() - ->andReturnFalse(); + ->returns(false); $this->assertFalse($connection->__call('zunionstore', ['output', ['set1', 'set2']])); } @@ -2415,11 +2334,9 @@ public function testZunionstoreSimple(): void $connection = $this->mockRedisConnection(); $connection->shouldTransform(false); - $connection->getConnection() - ->shouldReceive('zunionstore') - ->withAnyArgs() - ->once() - ->andReturn(5); + $connection->nativeClientForTest() + ->expects('zunionstore') + ->returns(5); $result = $connection->__call('zunionstore', ['output', ['set1', 'set2']]); @@ -2430,11 +2347,10 @@ public function testGetTransformsFalseToNull(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('get') + $connection->nativeClientForTest() + ->expects('get') ->with('key') - ->once() - ->andReturn(false); + ->returns(false); $result = $connection->__call('get', ['key']); @@ -2445,11 +2361,10 @@ public function testSetWithoutOptions(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('set') + $connection->nativeClientForTest() + ->expects('set') ->with('key', 'value', null) - ->once() - ->andReturn(true); + ->returns(true); $result = $connection->__call('set', ['key', 'value']); @@ -2460,11 +2375,10 @@ public function testSetnxReturnsZeroOnFailure(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('setNx') + $connection->nativeClientForTest() + ->expects('setNx') ->with('key', 'value') - ->once() - ->andReturn(false); + ->returns(false); $result = $connection->__call('setnx', ['key', 'value']); @@ -2475,11 +2389,10 @@ public function testHmsetWithAlternatingKeyValuePairs(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('hMSet') + $connection->nativeClientForTest() + ->expects('hMSet') ->with('hash', ['field1' => 'value1', 'field2' => 'value2']) - ->once() - ->andReturn(true); + ->returns(true); // Laravel style: key, value, key, value $result = $connection->__call('hmset', ['hash', 'field1', 'value1', 'field2', 'value2']); @@ -2491,11 +2404,10 @@ public function testZaddWithScoreMemberPairs(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('zAdd') + $connection->nativeClientForTest() + ->expects('zAdd') ->with('zset', [], 1.0, 'member1', 2.0, 'member2') - ->once() - ->andReturn(2); + ->returns(2); $result = $connection->__call('zadd', ['zset', 1.0, 'member1', 2.0, 'member2']); @@ -2506,11 +2418,10 @@ public function testZrangebyscoreWithListLimitPassesThrough(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('zRangeByScore') + $connection->nativeClientForTest() + ->expects('zRangeByScore') ->with('zset', '-inf', '+inf', ['limit' => [5, 20]]) - ->once() - ->andReturn(['member1']); + ->returns(['member1']); // Already in list format - passes through $result = $connection->__call('zrangebyscore', ['zset', '-inf', '+inf', ['limit' => [5, 20]]]); @@ -2522,11 +2433,10 @@ public function testZrevrangebyscoreWithLimitOption(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('zRevRangeByScore') + $connection->nativeClientForTest() + ->expects('zRevRangeByScore') ->with('zset', '+inf', '-inf', ['limit' => [0, 5]]) - ->once() - ->andReturn(['member2', 'member1']); + ->returns(['member2', 'member1']); $result = $connection->__call('zrevrangebyscore', ['zset', '+inf', '-inf', ['limit' => ['offset' => 0, 'count' => 5]]]); @@ -2537,11 +2447,10 @@ public function testZrevrangebyscorePreservesFailure(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('zRevRangeByScore') + $connection->nativeClientForTest() + ->expects('zRevRangeByScore') ->with('zset', '+inf', '-inf', []) - ->once() - ->andReturnFalse(); + ->returns(false); $this->assertFalse($connection->__call('zrevrangebyscore', ['zset', '+inf', '-inf'])); } @@ -2550,11 +2459,10 @@ public function testZinterstoreDefaultsAggregate(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('zinterstore') + $connection->nativeClientForTest() + ->expects('zinterstore') ->with('output', ['set1', 'set2'], null, 'sum') - ->once() - ->andReturn(2); + ->returns(2); $result = $connection->__call('zinterstore', ['output', ['set1', 'set2']]); @@ -2566,11 +2474,10 @@ public function testCallWithoutTransformPassesDirectly(): void $connection = $this->mockRedisConnection(transform: false); // Without transform, get() returns false (not null) - $connection->getConnection() - ->shouldReceive('get') + $connection->nativeClientForTest() + ->expects('get') ->with('key') - ->once() - ->andReturn(false); + ->returns(false); $result = $connection->__call('get', ['key']); @@ -2581,10 +2488,10 @@ public function testSerializedReturnsTrueWhenSerializerConfigured(): void { $connection = $this->mockRedisConnection(); - $connection->getConnection() - ->shouldReceive('getOption') + $connection->nativeClientForTest() + ->allows('getOption') ->with(Redis::OPT_SERIALIZER) - ->andReturn(Redis::SERIALIZER_PHP); + ->returns(Redis::SERIALIZER_PHP); $this->assertTrue($connection->serialized()); } @@ -2593,10 +2500,10 @@ public function testSerializedReturnsFalseWhenNoSerializer(): void { $connection = $this->mockRedisConnection(); - $connection->getConnection() - ->shouldReceive('getOption') + $connection->nativeClientForTest() + ->allows('getOption') ->with(Redis::OPT_SERIALIZER) - ->andReturn(Redis::SERIALIZER_NONE); + ->returns(Redis::SERIALIZER_NONE); $this->assertFalse($connection->serialized()); } @@ -2609,10 +2516,10 @@ public function testCompressedReturnsTrueWhenCompressionConfigured(): void $connection = $this->mockRedisConnection(); - $connection->getConnection() - ->shouldReceive('getOption') + $connection->nativeClientForTest() + ->allows('getOption') ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_LZF); + ->returns(Redis::COMPRESSION_LZF); $this->assertTrue($connection->compressed()); } @@ -2621,10 +2528,10 @@ public function testCompressedReturnsFalseWhenNoCompression(): void { $connection = $this->mockRedisConnection(); - $connection->getConnection() - ->shouldReceive('getOption') + $connection->nativeClientForTest() + ->allows('getOption') ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_NONE); + ->returns(Redis::COMPRESSION_NONE); $this->assertFalse($connection->compressed()); } @@ -2718,26 +2625,24 @@ public function testWithoutScanPrefixRestoresOptionsWhenCallbackThrows(): void public function testWithoutSerializationOrCompressionDisablesSerializerAndRestores(): void { $connection = $this->mockRedisConnection(); - $redis = $connection->getConnection(); + $redis = $connection->nativeClientForTest(); // serialized() check + saving old value - $redis->shouldReceive('getOption') + $redis->allows('getOption') ->with(Redis::OPT_SERIALIZER) - ->andReturn(Redis::SERIALIZER_PHP); + ->returns(Redis::SERIALIZER_PHP); // compressed() check - $redis->shouldReceive('getOption') + $redis->allows('getOption') ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_NONE); + ->returns(Redis::COMPRESSION_NONE); // Disable serialization - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); // Restore serialization - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); $result = $connection->withoutSerializationOrCompression(fn () => 'callback-result'); @@ -2752,26 +2657,24 @@ public function testWithoutSerializationOrCompressionDisablesCompressionAndResto } $connection = $this->mockRedisConnection(); - $redis = $connection->getConnection(); + $redis = $connection->nativeClientForTest(); // serialized() check - $redis->shouldReceive('getOption') + $redis->allows('getOption') ->with(Redis::OPT_SERIALIZER) - ->andReturn(Redis::SERIALIZER_NONE); + ->returns(Redis::SERIALIZER_NONE); // compressed() check + saving old value - $redis->shouldReceive('getOption') + $redis->allows('getOption') ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_LZF); + ->returns(Redis::COMPRESSION_LZF); // Disable compression - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_COMPRESSION, Redis::COMPRESSION_NONE); // Restore compression - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_COMPRESSION, Redis::COMPRESSION_LZF); $result = $connection->withoutSerializationOrCompression(fn () => 'compressed-result'); @@ -2786,32 +2689,28 @@ public function testWithoutSerializationOrCompressionDisablesBothAndRestores(): } $connection = $this->mockRedisConnection(); - $redis = $connection->getConnection(); + $redis = $connection->nativeClientForTest(); // serialized() check + saving old value - $redis->shouldReceive('getOption') + $redis->allows('getOption') ->with(Redis::OPT_SERIALIZER) - ->andReturn(Redis::SERIALIZER_PHP); + ->returns(Redis::SERIALIZER_PHP); // compressed() check + saving old value - $redis->shouldReceive('getOption') + $redis->allows('getOption') ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_LZF); + ->returns(Redis::COMPRESSION_LZF); // Disable both - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_COMPRESSION, Redis::COMPRESSION_NONE); // Restore both - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_COMPRESSION, Redis::COMPRESSION_LZF); $result = $connection->withoutSerializationOrCompression(fn () => 'both-result'); @@ -2822,18 +2721,18 @@ public function testWithoutSerializationOrCompressionDisablesBothAndRestores(): public function testWithoutSerializationOrCompressionSkipsWhenNeitherConfigured(): void { $connection = $this->mockRedisConnection(); - $redis = $connection->getConnection(); + $redis = $connection->nativeClientForTest(); // Neither serialized nor compressed - $redis->shouldReceive('getOption') + $redis->allows('getOption') ->with(Redis::OPT_SERIALIZER) - ->andReturn(Redis::SERIALIZER_NONE); - $redis->shouldReceive('getOption') + ->returns(Redis::SERIALIZER_NONE); + $redis->allows('getOption') ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_NONE); + ->returns(Redis::COMPRESSION_NONE); // setOption should never be called - $redis->shouldNotReceive('setOption'); + $redis->expects('setOption')->never(); $result = $connection->withoutSerializationOrCompression(fn () => 'no-change'); @@ -2843,26 +2742,24 @@ public function testWithoutSerializationOrCompressionSkipsWhenNeitherConfigured( public function testWithoutSerializationOrCompressionRestoresOnException(): void { $connection = $this->mockRedisConnection(); - $redis = $connection->getConnection(); + $redis = $connection->nativeClientForTest(); // serialized() check + saving old value - $redis->shouldReceive('getOption') + $redis->allows('getOption') ->with(Redis::OPT_SERIALIZER) - ->andReturn(Redis::SERIALIZER_PHP); + ->returns(Redis::SERIALIZER_PHP); // compressed() check - $redis->shouldReceive('getOption') + $redis->allows('getOption') ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_NONE); + ->returns(Redis::COMPRESSION_NONE); // Disable serialization - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); // Restore serialization even on exception - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); try { @@ -2925,16 +2822,14 @@ public function testPackUsesNativePackMethod(): void { $connection = $this->mockRedisConnection(); - $connection->getConnection() - ->shouldReceive('_pack') + $connection->nativeClientForTest() + ->expects('_pack') ->with('value1') - ->once() - ->andReturn('packed1'); - $connection->getConnection() - ->shouldReceive('_pack') + ->returns('packed1'); + $connection->nativeClientForTest() + ->expects('_pack') ->with('value2') - ->once() - ->andReturn('packed2'); + ->returns('packed2'); $result = $connection->pack(['value1', 'value2']); @@ -2945,16 +2840,14 @@ public function testPackPreservesArrayKeys(): void { $connection = $this->mockRedisConnection(); - $connection->getConnection() - ->shouldReceive('_pack') + $connection->nativeClientForTest() + ->expects('_pack') ->with('value1') - ->once() - ->andReturn('packed1'); - $connection->getConnection() - ->shouldReceive('_pack') + ->returns('packed1'); + $connection->nativeClientForTest() + ->expects('_pack') ->with('value2') - ->once() - ->andReturn('packed2'); + ->returns('packed2'); $result = $connection->pack(['key1' => 'value1', 'key2' => 'value2']); @@ -2967,14 +2860,14 @@ public function testPackPreservesArrayKeys(): void public function testEvalWithShaCacheSucceedsOnFirstTry(): void { $connection = $this->mockRedisConnection(); + $connection->nativeClientForTest()->allows('clearLastError')->returns(true); $script = 'return KEYS[1]'; $sha = sha1($script); - $connection->getConnection() - ->shouldReceive('evalSha') + $connection->nativeClientForTest() + ->expects('evalSha') ->with($sha, ['mykey', 'arg1', 'arg2'], 1) - ->once() - ->andReturn('mykey'); + ->returns('mykey'); $result = $connection->evalWithShaCache($script, ['mykey'], ['arg1', 'arg2']); @@ -2984,19 +2877,18 @@ public function testEvalWithShaCacheSucceedsOnFirstTry(): void public function testEvalWithShaCacheThrowsOnNonNoscriptError(): void { $connection = $this->mockRedisConnection(); + $connection->nativeClientForTest()->allows('clearLastError')->returns(true); $script = 'invalid lua syntax'; $sha = sha1($script); - $redisConnection = $connection->getConnection(); + $redisConnection = $connection->nativeClientForTest(); - $redisConnection->shouldReceive('evalSha') + $redisConnection->expects('evalSha') ->with($sha, ['mykey'], 1) - ->once() - ->andReturn(false); + ->returns(false); - $redisConnection->shouldReceive('getLastError') - ->once() - ->andReturn('ERR Error compiling script'); + $redisConnection->expects('getLastError') + ->returns('ERR Error compiling script'); $this->expectException(LuaScriptException::class); $this->expectExceptionMessageIs('Lua script execution failed: ERR Error compiling script'); @@ -3007,11 +2899,11 @@ public function testEvalWithShaCacheThrowsOnNonNoscriptError(): void public function testEvalWithShaCacheInvalidatesAReadOnlyReplica(): void { $exception = new RedisException('READONLY replica is read-only'); - $redis = m::mock(Redis::class); - $redis->expects('clearLastError')->once(); - $redis->expects('evalSha')->once()->with(sha1('return 1'), [], 0)->andThrow($exception); - $redis->expects('getLastError')->andReturn($exception->getMessage()); - $redis->shouldNotReceive('eval'); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('clearLastError'); + $redis->expects('evalSha')->with(sha1('return 1'), [], 0)->throws($exception); + $redis->expects('getLastError')->returns($exception->getMessage()); + $redis->expects('eval')->never(); $connection = new PhpRedisConnectionStub($this->getContainer(), $this->getMockedPool()); $connection->setActiveConnection($redis); @@ -3028,20 +2920,19 @@ public function testEvalWithShaCacheInvalidatesAReadOnlyReplica(): void public function testEvalWithShaCacheReturnsLegitimatelyFalseResult(): void { $connection = $this->mockRedisConnection(); + $connection->nativeClientForTest()->allows('clearLastError')->returns(true); $script = 'return false'; $sha = sha1($script); - $redisConnection = $connection->getConnection(); + $redisConnection = $connection->nativeClientForTest(); // Script returns false legitimately (no error) - $redisConnection->shouldReceive('evalSha') + $redisConnection->expects('evalSha') ->with($sha, [], 0) - ->once() - ->andReturn(false); + ->returns(false); - $redisConnection->shouldReceive('getLastError') - ->once() - ->andReturn(null); // No error - script legitimately returned false + $redisConnection->expects('getLastError') + ->returns(null); // No error - script legitimately returned false $result = $connection->evalWithShaCache($script); @@ -3051,14 +2942,14 @@ public function testEvalWithShaCacheReturnsLegitimatelyFalseResult(): void public function testEvalWithShaCacheWorksWithNoKeysOrArgs(): void { $connection = $this->mockRedisConnection(); + $connection->nativeClientForTest()->allows('clearLastError')->returns(true); $script = 'return 42'; $sha = sha1($script); - $connection->getConnection() - ->shouldReceive('evalSha') + $connection->nativeClientForTest() + ->expects('evalSha') ->with($sha, [], 0) - ->once() - ->andReturn(42); + ->returns(42); $result = $connection->evalWithShaCache($script); @@ -3068,14 +2959,14 @@ public function testEvalWithShaCacheWorksWithNoKeysOrArgs(): void public function testEvalWithShaCacheWorksWithMultipleKeysAndArgs(): void { $connection = $this->mockRedisConnection(); + $connection->nativeClientForTest()->allows('clearLastError')->returns(true); $script = 'return {KEYS[1], KEYS[2], ARGV[1], ARGV[2]}'; $sha = sha1($script); - $connection->getConnection() - ->shouldReceive('evalSha') + $connection->nativeClientForTest() + ->expects('evalSha') ->with($sha, ['key1', 'key2', 'arg1', 'arg2'], 2) - ->once() - ->andReturn(['key1', 'key2', 'arg1', 'arg2']); + ->returns(['key1', 'key2', 'arg1', 'arg2']); $result = $connection->evalWithShaCache($script, ['key1', 'key2'], ['arg1', 'arg2']); @@ -3088,20 +2979,16 @@ public function testEvalWithShaCacheClearsLastErrorBeforeEvalSha(): void $script = 'return "ok"'; $sha = sha1($script); - $redisConnection = $connection->getConnection(); + $redisConnection = $connection->nativeClientForTest(); // Verify clearLastError is called before evalSha using ordered expectations - $redisConnection->shouldReceive('clearLastError') - ->once() - ->globally() + $redisConnection->expects('clearLastError') ->ordered(); - $redisConnection->shouldReceive('evalSha') + $redisConnection->expects('evalSha') ->with($sha, [], 0) - ->once() - ->globally() ->ordered() - ->andReturn('ok'); + ->returns('ok'); $result = $connection->evalWithShaCache($script); @@ -3113,11 +3000,10 @@ public function testSpopWithoutCountReturnsSingleElement(): void $connection = $this->mockRedisConnection(transform: true); // Without count, phpredis sPop returns a single string - $connection->getConnection() - ->shouldReceive('sPop') - ->once() + $connection->nativeClientForTest() + ->expects('sPop') ->with('myset') - ->andReturn('member1'); + ->returns('member1'); $result = $connection->__call('spop', ['myset']); @@ -3129,11 +3015,10 @@ public function testSpopWithCountReturnsArray(): void $connection = $this->mockRedisConnection(transform: true); // With count, phpredis sPop returns an array - $connection->getConnection() - ->shouldReceive('sPop') - ->once() + $connection->nativeClientForTest() + ->expects('sPop') ->with('myset', 3) - ->andReturn(['member1', 'member2', 'member3']); + ->returns(['member1', 'member2', 'member3']); $result = $connection->__call('spop', ['myset', 3]); @@ -3144,11 +3029,10 @@ public function testSpopWithoutCountReturnsFalseForEmptySet(): void { $connection = $this->mockRedisConnection(transform: true); - $connection->getConnection() - ->shouldReceive('sPop') - ->once() + $connection->nativeClientForTest() + ->expects('sPop') ->with('emptyset') - ->andReturn(false); + ->returns(false); $result = $connection->__call('spop', ['emptyset']); @@ -3157,128 +3041,32 @@ public function testSpopWithoutCountReturnsFalseForEmptySet(): void public function testEvalReordersArguments(): void { - // Can't mock eval() on phpredis — Mockery's proxy falls through to the - // C extension which tries a real connection. Instead, override callEval - // to capture the arguments it receives after __call dispatches to it. - $captured = []; - $connection = new class($this->getContainer(), $this->getMockedPool(), $this->standaloneConfig(), $captured) extends PhpRedisConnection { - public function __construct( - ContainerContract $container, - ConnectionPool $pool, - array $config, - private array &$captured, - ) { - parent::__construct($container, $pool, $config); - } - - protected function createRedis(array $config): Redis - { - return m::mock(Redis::class)->shouldIgnoreMissing(); - } - - protected function callEval(string $script, int $numberOfKeys, mixed ...$arguments): mixed - { - $this->captured = [ - 'script' => $script, - 'numberOfKeys' => $numberOfKeys, - 'arguments' => $arguments, - ]; - - return 'captured'; - } - }; - - $connection->shouldTransform(true); - - // User calls: eval('return KEYS[1]', 1, 'mykey') - $result = $connection->__call('eval', ['return KEYS[1]', 1, 'mykey']); + $connection = $this->mockRedisConnection(transform: true); + $connection->nativeClientForTest()->expects('eval') + ->with('return KEYS[1]', ['mykey'], 1) + ->returns('result'); - $this->assertSame('captured', $result); - $this->assertSame('return KEYS[1]', $captured['script']); - $this->assertSame(1, $captured['numberOfKeys']); - $this->assertSame(['mykey'], $captured['arguments']); + $this->assertSame('result', $connection->eval('return KEYS[1]', 1, 'mykey')); } public function testEvalReordersMultipleArguments(): void { - $captured = []; - $connection = new class($this->getContainer(), $this->getMockedPool(), $this->standaloneConfig(), $captured) extends PhpRedisConnection { - public function __construct( - ContainerContract $container, - ConnectionPool $pool, - array $config, - private array &$captured, - ) { - parent::__construct($container, $pool, $config); - } - - protected function createRedis(array $config): Redis - { - return m::mock(Redis::class)->shouldIgnoreMissing(); - } - - protected function callEval(string $script, int $numberOfKeys, mixed ...$arguments): mixed - { - $this->captured = [ - 'script' => $script, - 'numberOfKeys' => $numberOfKeys, - 'arguments' => $arguments, - ]; - - return 'captured'; - } - }; - - $connection->shouldTransform(true); - - // User calls: eval('return {KEYS[1], ARGV[1]}', 1, 'mykey', 'myarg') - $result = $connection->__call('eval', ['return {KEYS[1], ARGV[1]}', 1, 'mykey', 'myarg']); + $connection = $this->mockRedisConnection(transform: true); + $connection->nativeClientForTest()->expects('eval') + ->with('return {KEYS[1], ARGV[1]}', ['mykey', 'myarg'], 1) + ->returns('result'); - $this->assertSame('captured', $result); - $this->assertSame('return {KEYS[1], ARGV[1]}', $captured['script']); - $this->assertSame(1, $captured['numberOfKeys']); - $this->assertSame(['mykey', 'myarg'], $captured['arguments']); + $this->assertSame('result', $connection->eval('return {KEYS[1], ARGV[1]}', 1, 'mykey', 'myarg')); } public function testEvalWithNoKeysOrArguments(): void { - $captured = []; - $connection = new class($this->getContainer(), $this->getMockedPool(), $this->standaloneConfig(), $captured) extends PhpRedisConnection { - public function __construct( - ContainerContract $container, - ConnectionPool $pool, - array $config, - private array &$captured, - ) { - parent::__construct($container, $pool, $config); - } - - protected function createRedis(array $config): Redis - { - return m::mock(Redis::class)->shouldIgnoreMissing(); - } - - protected function callEval(string $script, int $numberOfKeys, mixed ...$arguments): mixed - { - $this->captured = [ - 'script' => $script, - 'numberOfKeys' => $numberOfKeys, - 'arguments' => $arguments, - ]; - - return 'captured'; - } - }; - - $connection->shouldTransform(true); - - // User calls: eval('return 42', 0) - $result = $connection->__call('eval', ['return 42', 0]); + $connection = $this->mockRedisConnection(transform: true); + $connection->nativeClientForTest()->expects('eval') + ->with('return 42', [], 0) + ->returns('result'); - $this->assertSame('captured', $result); - $this->assertSame('return 42', $captured['script']); - $this->assertSame(0, $captured['numberOfKeys']); - $this->assertSame([], $captured['arguments']); + $this->assertSame('result', $connection->eval('return 42', 0)); } #[DataProvider('unsupportedSubscriptionProvider')] @@ -3304,11 +3092,11 @@ public static function unsupportedSubscriptionProvider(): array public function testResetIsRejectedBeforeNativeDispatchAndPreservesWatchState(): void { $pool = $this->getMockedPool(); - $pool->expects('discard')->with(m::type(RedisConnection::class)); - $redis = m::mock(Redis::class); - $redis->expects('watch')->with('key')->andReturnTrue(); + $pool->expects('discard')->with(Argument::type(RedisConnection::class)); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('watch')->with('key')->returns(true); $redis->expects('reset')->never(); - $redis->expects('getMode')->andReturn(Redis::ATOMIC); + $redis->expects('getMode')->returns(Redis::ATOMIC); $connection = $this->mockRedisConnection(pool: $pool); $connection->setActiveConnection($redis); $connection->shouldTransform(false); @@ -3335,9 +3123,8 @@ public function testResetIsRejectedBeforeNativeDispatchAndPreservesWatchState(): public function testReconnectSetsSerializerOption(): void { $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); - $redis->shouldReceive('setOption') - ->once() + $redis = Double::for(Redis::class)->strict(); + $redis->expects('setOption') ->with(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); $this->expectDefaultConnectionOptions($redis); @@ -3362,9 +3149,8 @@ protected function createRedis(array $config): Redis public function testReconnectSetsPrefixOption(): void { $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); - $redis->shouldReceive('setOption') - ->once() + $redis = Double::for(Redis::class)->strict(); + $redis->expects('setOption') ->with(Redis::OPT_PREFIX, 'myapp:'); $this->expectDefaultConnectionOptions($redis); @@ -3393,10 +3179,10 @@ public function testReconnectSetsPackIgnoreNumbersOnStandaloneConnection(): void } $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); $redis->expects('setOption') ->with(Redis::OPT_PACK_IGNORE_NUMBERS, true) - ->andReturnTrue(); + ->returns(true); $this->expectDefaultConnectionOptions($redis); @@ -3424,8 +3210,8 @@ public function testReconnectRejectsNamedPackIgnoreNumbersWhenPhpRedisDoesNotSup } $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); - $redis->shouldReceive('setOption')->andReturnTrue(); + $redis = Double::for(Redis::class)->strict(); + $redis->allows('setOption')->returns(true); $this->expectException(InvalidRedisOptionException::class); $this->expectExceptionMessageIs('The redis option `pack_ignore_numbers` requires PhpRedis 6.2 or later.'); @@ -3450,21 +3236,16 @@ protected function createRedis(array $config): Redis public function testReconnectSetsConnectionLevelPhpRedisOptions(): void { $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); - $redis->shouldReceive('setOption') - ->once() + $redis = Double::for(Redis::class)->strict(); + $redis->expects('setOption') ->with(Redis::OPT_READ_TIMEOUT, 5.0); - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_MAX_RETRIES, 4); - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_BACKOFF_ALGORITHM, Redis::BACKOFF_ALGORITHM_CONSTANT); - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_BACKOFF_BASE, 200); - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_BACKOFF_CAP, 2000); new class($this->getContainer(), $pool, $this->standaloneConfig(['read_timeout' => 5.0, 'max_retries' => 4, 'backoff_algorithm' => 'constant', 'backoff_base' => 200, 'backoff_cap' => 2000]), $redis) extends PhpRedisConnection { @@ -3487,7 +3268,7 @@ protected function createRedis(array $config): Redis public function testReconnectDoesNotSetReadTimeoutOptionWhenEmpty(): void { $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); $this->expectDefaultConnectionOptions($redis); new class($this->getContainer(), $pool, $this->standaloneConfig(['read_timeout' => 0.0]), $redis) extends PhpRedisConnection { @@ -3510,11 +3291,11 @@ protected function createRedis(array $config): Redis public function testParseBackoffAlgorithmReturnsIntegerAsIs(): void { $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); $redis->expects('setOption') ->with(Redis::OPT_BACKOFF_ALGORITHM, Redis::BACKOFF_ALGORITHM_DEFAULT); - $redis->shouldReceive('setOption')->andReturnTrue(); + $redis->allows('setOption')->with(Argument::not(Redis::OPT_BACKOFF_ALGORITHM), Argument::any())->returns(true); new class($this->getContainer(), $pool, $this->standaloneConfig(['backoff_algorithm' => Redis::BACKOFF_ALGORITHM_DEFAULT]), $redis) extends PhpRedisConnection { /** @@ -3554,11 +3335,11 @@ public function testParseBackoffAlgorithmParsesValidNames(): void public function testParseBackoffAlgorithmThrowsForInvalidName(): void { $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); $this->expectExceptionObject(new InvalidRedisOptionException('Algorithm [bogus] is not a valid PhpRedis backoff algorithm.')); - $redis->shouldReceive('setOption')->andReturnTrue(); + $redis->allows('setOption')->returns(true); new class($this->getContainer(), $pool, $this->standaloneConfig(['backoff_algorithm' => 'bogus']), $redis) extends PhpRedisConnection { /** @@ -3662,12 +3443,12 @@ public function testFormatHostThrowsWhenHostIsEmpty(): void public function testReconnectThrowsOnUnknownOption(): void { $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); $this->expectException(InvalidRedisOptionException::class); $this->expectExceptionMessageIs('The redis option key `bogus` is invalid.'); - $redis->shouldReceive('setOption')->andReturnTrue(); + $redis->allows('setOption')->returns(true); new class($this->getContainer(), $pool, $this->standaloneConfig(['options' => ['bogus' => 'value']]), $redis) extends PhpRedisConnection { public function __construct( @@ -3689,11 +3470,10 @@ protected function createRedis(array $config): Redis public function testReconnectSetsNumericOptions(): void { $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); // Numeric keys bypass the match statement and pass directly - $redis->shouldReceive('setOption') - ->once() + $redis->expects('setOption') ->with(Redis::OPT_SERIALIZER, Redis::SERIALIZER_JSON); $this->expectDefaultConnectionOptions($redis); @@ -3718,9 +3498,8 @@ protected function createRedis(array $config): Redis public function testReconnectAuthenticatesWhenAuthConfigured(): void { $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); - $redis->shouldReceive('auth') - ->once() + $redis = Double::for(Redis::class)->strict(); + $redis->expects('auth') ->with('secret'); $this->expectDefaultConnectionOptions($redis); @@ -3745,8 +3524,8 @@ protected function createRedis(array $config): Redis public function testReconnectDoesNotAuthenticateWhenAuthEmpty(): void { $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); - $redis->shouldNotReceive('auth'); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('auth')->never(); $this->expectDefaultConnectionOptions($redis); @@ -3767,25 +3546,11 @@ protected function createRedis(array $config): Redis }; } - public function testCloseNullsConnection(): void - { - $connection = $this->mockRedisConnection(); - - // getActiveConnection() lazily creates the connection - $connection->getActiveConnection(); - $this->assertNotNull($connection->client()); - - $result = $connection->close(); - - $this->assertTrue($result); - $this->assertNull($connection->client()); - } - public function testCloseInvokesNativeRedisClose(): void { $connection = $this->mockRedisConnection(); - $redis = m::mock(Redis::class); - $redis->shouldReceive('close')->once()->andReturnTrue(); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('close')->returns(true); $connection->setActiveConnection($redis); $this->assertNotNull($connection->client()); @@ -3799,10 +3564,9 @@ public function testCloseInvokesNativeRedisClose(): void public function testCloseSwallowsExceptionFromNativeRedisClose(): void { $connection = $this->mockRedisConnection(); - $redis = m::mock(Redis::class); - $redis->shouldReceive('close') - ->once() - ->andThrow(new RedisException('connection already closed')); + $redis = Double::for(Redis::class)->strict(); + $redis->expects('close') + ->throws(new RedisException('connection already closed')); $connection->setActiveConnection($redis); @@ -3818,12 +3582,11 @@ public function testClusterTransformFiresInAtomicMode(): void $connection->shouldTransform(true); // In atomic mode, isQueueingMode() returns false, so transforms fire - $clusterMock = m::mock(RedisCluster::class); - $clusterMock->shouldReceive('getMode')->andReturn(Redis::ATOMIC); - $clusterMock->shouldReceive('setNx') - ->once() + $clusterMock = Double::for(RedisCluster::class)->strict(); + $clusterMock->allows('getMode')->returns(Redis::ATOMIC); + $clusterMock->expects('setNx') ->with('key', 'value') - ->andReturn(true); + ->returns(true); $connection->setActiveConnection($clusterMock); @@ -3835,11 +3598,11 @@ public function testClusterTransformFiresInAtomicMode(): void public function testReconnectClearsInvalidState(): void { $pool = $this->getMockedPool(); - $redis = m::mock(Redis::class); - $redis->shouldReceive('select')->andReturn(true); - $redis->shouldNotReceive('isConnected'); + $redis = Double::for(Redis::class)->strict(); + $redis->allows('select')->returns(true); + $redis->expects('isConnected')->never(); - $redis->shouldReceive('setOption')->andReturnTrue(); + $redis->allows('setOption')->returns(true); $connection = new class($this->getContainer(), $pool, $this->standaloneConfig(['database' => 1]), $redis) extends PhpRedisConnection { public function __construct( @@ -3873,12 +3636,12 @@ public function isInvalidForTest(): bool public function testInvalidStateIsNotMaskedByFreshReleaseTime(): void { - $pool = m::mock(ConnectionPool::class); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray(['max_idle_time' => 60.0])); + $pool = Double::for(ConnectionPool::class)->strict(); + $pool->allows('getOptions')->returns(PoolOptions::fromArray(['max_idle_time' => 60.0])); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('setOption')->andReturnTrue(); + $redis->allows('setOption')->returns(true); $connection = new class($this->getContainer(), $pool, $this->standaloneConfig(), $redis) extends PhpRedisConnection { public function __construct( @@ -3909,11 +3672,11 @@ public function setLastReleaseTimeForTest(float $lastReleaseTime): void public function testCheckDoesNotResetActivityTimestamp(): void { - $pool = m::mock(ConnectionPool::class); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray(['max_idle_time' => 60.0])); - $redis = m::mock(Redis::class); + $pool = Double::for(ConnectionPool::class)->strict(); + $pool->allows('getOptions')->returns(PoolOptions::fromArray(['max_idle_time' => 60.0])); + $redis = Double::for(Redis::class)->strict(); - $redis->shouldReceive('setOption')->andReturnTrue(); + $redis->allows('setOption')->returns(true); $connection = new class($this->getContainer(), $pool, $this->standaloneConfig(), $redis) extends PhpRedisConnection { public function __construct( @@ -3952,18 +3715,15 @@ public function getLastUseTimeForTest(): float public function testScanWithArrayOptions(): void { + $client = new FakeRedisClient(scanResults: [['keys' => ['key1', 'key2'], 'iterator' => 0]]); $connection = $this->mockRedisConnection(transform: true); + $connection->setActiveConnection($client); $cursor = 0; - $connection->getConnection() - ->shouldReceive('scan') - ->with(0, 'prefix:*', 20) - ->once() - ->andReturn(['key1', 'key2']); - $result = $connection->scan($cursor, ['match' => 'prefix:*', 'count' => 20]); - $this->assertEquals([0, ['key1', 'key2']], $result); + $this->assertSame([0, ['key1', 'key2']], $result); + $this->assertSame([['iterator' => 0, 'pattern' => 'prefix:*', 'count' => 20]], $client->getScanCalls()); } /** @@ -4053,12 +3813,12 @@ protected function baseConnectionConfig(): array */ protected function expectDefaultConnectionOptions(Redis $redis): void { - $redis->expects('setOption')->with(Redis::OPT_MAX_RETRIES, 3)->andReturnTrue(); + $redis->expects('setOption')->with(Redis::OPT_MAX_RETRIES, 3)->returns(true); $redis->expects('setOption') ->with(Redis::OPT_BACKOFF_ALGORITHM, Redis::BACKOFF_ALGORITHM_DECORRELATED_JITTER) - ->andReturnTrue(); - $redis->expects('setOption')->with(Redis::OPT_BACKOFF_BASE, 100)->andReturnTrue(); - $redis->expects('setOption')->with(Redis::OPT_BACKOFF_CAP, 1000)->andReturnTrue(); + ->returns(true); + $redis->expects('setOption')->with(Redis::OPT_BACKOFF_BASE, 100)->returns(true); + $redis->expects('setOption')->with(Redis::OPT_BACKOFF_CAP, 1000)->returns(true); } /** @@ -4072,6 +3832,10 @@ protected function mockRedisConnection(?ContainerContract $container = null, ?Co $this->standaloneConfig($options) ); + $client = Double::for(Redis::class)->strict(); + $client->allows('getMode')->returns(Redis::ATOMIC); + $connection->setActiveConnection($client); + if ($transform) { $connection->shouldTransform(true); } @@ -4081,9 +3845,9 @@ protected function mockRedisConnection(?ContainerContract $container = null, ?Co protected function getMockedPool(): ConnectionPool { - $pool = m::mock(ConnectionPool::class); - $pool->shouldReceive('getOptions') - ->andReturn(PoolOptions::fromArray([])); + $pool = Double::for(ConnectionPool::class)->strict(); + $pool->allows('getOptions') + ->returns(PoolOptions::fromArray([])); return $pool; } diff --git a/tests/Redis/RedisManagerTest.php b/tests/Redis/RedisManagerTest.php index 299c3ba966..d6ecc99a15 100644 --- a/tests/Redis/RedisManagerTest.php +++ b/tests/Redis/RedisManagerTest.php @@ -5,6 +5,7 @@ namespace Hypervel\Tests\Redis; use Hypervel\Config\Repository; +use Hypervel\Container\Container; use Hypervel\Context\CoroutineContext; use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\Contracts\Events\Dispatcher; @@ -19,7 +20,9 @@ use Hypervel\Redis\RedisSentinelFactory; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use Swoole\Coroutine\CanceledException; use Throwable; @@ -29,6 +32,8 @@ */ class RedisManagerTest extends TestCase { + use VerifiesDoubles; + public function testConnectionReturnsRedisProxy(): void { $manager = $this->createManager(['default']); @@ -72,7 +77,7 @@ public function testConnectionDefaultsToDefault(): void public function testPurgeAcceptsUnitEnum(): void { - $poolManager = m::mock(PoolManager::class)->makePartial(); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); $poolManager->expects('purge')->with('default'); $manager = $this->createManager(['default'], poolManager: $poolManager); $manager->connection('default'); @@ -86,8 +91,8 @@ public function testPurgeAcceptsUnitEnum(): void public function testIntegerBackedEnumConnectionNameIsNormalizedForResolutionAndPurge(): void { - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('purge')->once()->with('0'); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->expects('purge')->with('0'); $manager = $this->createManager(['0'], poolManager: $poolManager); $connection = $manager->connection(RedisConnectionName::Zero); @@ -103,8 +108,8 @@ public function testIntegerBackedEnumConnectionNameIsNormalizedForResolutionAndP public function testPurgeClearsProxyContextAndPool(): void { - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('purge')->once()->with('default'); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->expects('purge')->with('default'); $manager = $this->createManager(['default'], poolManager: $poolManager); @@ -122,10 +127,10 @@ public function testPurgeClearsProxyContextAndPool(): void public function testPurgeDiscardsContextPinnedConnection(): void { - $pinnedConnection = m::mock(PhpRedisConnection::class); + $pinnedConnection = Double::for(PhpRedisConnection::class)->strict(); $pinnedConnection->expects('discard'); - $poolManager = m::mock(PoolManager::class)->makePartial(); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); $poolManager->expects('purge')->with('default'); $manager = $this->createManager(['default'], poolManager: $poolManager); $contextKey = $this->contextKey($manager->connection('default')); @@ -139,9 +144,9 @@ public function testPurgeDiscardsContextPinnedConnection(): void public function testReleaseConnectionsExhaustsProxiesAndPreservesFirstFailure(): void { $firstException = new RuntimeException('First release failed.'); - $first = m::mock(PhpRedisConnection::class); - $first->expects('release')->andThrow($firstException); - $second = m::mock(PhpRedisConnection::class); + $first = Double::for(PhpRedisConnection::class)->strict(); + $first->expects('release')->throws($firstException); + $second = Double::for(PhpRedisConnection::class)->strict(); $second->expects('release'); $manager = $this->createManager(['first', 'second']); CoroutineContext::set($this->contextKey($manager->connection('first')), $first); @@ -160,12 +165,12 @@ public function testReleaseConnectionsExhaustsProxiesAndPreservesFirstCancellati $ordinaryFailure = new RuntimeException('First release failed.'); $cancellation = new CanceledException('Second release canceled.'); $laterCancellation = new CanceledException('Third release canceled.'); - $first = m::mock(PhpRedisConnection::class); - $first->expects('release')->andThrow($ordinaryFailure); - $second = m::mock(PhpRedisConnection::class); - $second->expects('release')->andThrow($cancellation); - $third = m::mock(PhpRedisConnection::class); - $third->expects('release')->andThrow($laterCancellation); + $first = Double::for(PhpRedisConnection::class)->strict(); + $first->expects('release')->throws($ordinaryFailure); + $second = Double::for(PhpRedisConnection::class)->strict(); + $second->expects('release')->throws($cancellation); + $third = Double::for(PhpRedisConnection::class)->strict(); + $third->expects('release')->throws($laterCancellation); $manager = $this->createManager(['first', 'second', 'third']); CoroutineContext::set($this->contextKey($manager->connection('first')), $first); CoroutineContext::set($this->contextKey($manager->connection('second')), $second); @@ -181,9 +186,9 @@ public function testReleaseConnectionsExhaustsProxiesAndPreservesFirstCancellati public function testDiscardConnectionsExhaustsEveryCreatedProxy(): void { - $first = m::mock(PhpRedisConnection::class); + $first = Double::for(PhpRedisConnection::class)->strict(); $first->expects('discard'); - $second = m::mock(PhpRedisConnection::class); + $second = Double::for(PhpRedisConnection::class)->strict(); $second->expects('discard'); $manager = $this->createManager(['first', 'second']); CoroutineContext::set($this->contextKey($manager->connection('first')), $first); @@ -195,12 +200,12 @@ public function testDiscardConnectionsExhaustsEveryCreatedProxy(): void public function testPurgeClosesPoolAfterDiscardFailureAndPreservesFirstFailure(): void { $discardException = new RuntimeException('Discard failed.'); - $connection = m::mock(PhpRedisConnection::class); - $connection->expects('discard')->andThrow($discardException); - $poolManager = m::mock(PoolManager::class)->makePartial(); + $connection = Double::for(PhpRedisConnection::class)->strict(); + $connection->expects('discard')->throws($discardException); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); $poolManager->expects('purge') ->with('alias') - ->andThrow(new RuntimeException('Purge failed.')); + ->throws(new RuntimeException('Purge failed.')); $manager = $this->createManager(['alias'], poolManager: $poolManager); CoroutineContext::set($this->contextKey($manager->connection('alias')), $connection); @@ -217,12 +222,12 @@ public function testPurgeClosesPoolAfterDiscardFailureAndPreservesFirstFailure() public function testPurgeClosesPoolAndLetsCancellationSupersedeDiscardFailure(): void { $cancellation = new CanceledException('Purge canceled.'); - $connection = m::mock(PhpRedisConnection::class); - $connection->expects('discard')->andThrow(new RuntimeException('Discard failed.')); - $poolManager = m::mock(PoolManager::class)->makePartial(); + $connection = Double::for(PhpRedisConnection::class)->strict(); + $connection->expects('discard')->throws(new RuntimeException('Discard failed.')); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); $poolManager->expects('purge') ->with('alias') - ->andThrow($cancellation); + ->throws($cancellation); $manager = $this->createManager(['alias'], poolManager: $poolManager); CoroutineContext::set($this->contextKey($manager->connection('alias')), $connection); @@ -248,76 +253,76 @@ public function testConnectorDriverExtensionsAreIntentionallyUnavailable(): void public function testEnableEventsRefreshesOnlyExistingPoolsWithDisabledEvents(): void { - $app = m::mock(ContainerContract::class); - $disabledPool = m::mock(RedisPool::class); - $disabledPool->expects('getConfig')->andReturn(['events' => false]); - $enabledPool = m::mock(RedisPool::class); - $enabledPool->expects('getConfig')->andReturn(['events' => true]); - - $config = m::mock(RedisConfig::class); - $config->expects('enableEvents') - ->globally() - ->ordered(); - - $poolManager = m::mock(PoolManager::class); + $app = Double::for(ContainerContract::class, override: true)->strict(); + $disabledPool = Double::for(RedisPool::class)->strict(); + $disabledPool->expects('getConfig')->returns(['events' => false]); + $enabledPool = Double::for(RedisPool::class)->strict(); + $enabledPool->expects('getConfig')->returns(['events' => true]); + + $operations = []; + $config = Double::for(RedisConfig::class)->strict(); + $config->expects('enableEvents')->resolves(static function () use (&$operations): void { + $operations[] = 'enableEvents'; + }); + + $poolManager = Double::for(PoolManager::class)->strict(); $poolManager->expects('pool')->never(); - $poolManager->expects('getPools') - ->globally() - ->ordered() - ->andReturn([ - 'disabled' => $disabledPool, - 'enabled' => $enabledPool, - ]); - $poolManager->expects('purge') - ->with('disabled') - ->globally() - ->ordered(); + $poolManager->expects('getPools')->resolves(static function () use (&$operations, $disabledPool, $enabledPool): array { + $operations[] = 'getPools'; + + return ['disabled' => $disabledPool, 'enabled' => $enabledPool]; + }); + $poolManager->expects('purge')->with('disabled')->resolves(static function () use (&$operations): void { + $operations[] = 'purge'; + }); $manager = new RedisManager( - $app, + $app->instance(), $poolManager, $config, - m::mock(RedisSentinelFactory::class), + Double::for(RedisSentinelFactory::class)->strict(), ); $manager->enableEvents(); + + $this->assertSame(['enableEvents', 'getPools', 'purge'], $operations); } public function testDisableEventsRefreshesOnlyExistingPoolsWithEnabledEvents(): void { - $app = m::mock(ContainerContract::class); - $enabledPool = m::mock(RedisPool::class); - $enabledPool->expects('getConfig')->andReturn(['events' => true]); - $disabledPool = m::mock(RedisPool::class); - $disabledPool->expects('getConfig')->andReturn(['events' => false]); - - $config = m::mock(RedisConfig::class); - $config->expects('disableEvents') - ->globally() - ->ordered(); - - $poolManager = m::mock(PoolManager::class); + $app = Double::for(ContainerContract::class, override: true)->strict(); + $enabledPool = Double::for(RedisPool::class)->strict(); + $enabledPool->expects('getConfig')->returns(['events' => true]); + $disabledPool = Double::for(RedisPool::class)->strict(); + $disabledPool->expects('getConfig')->returns(['events' => false]); + + $operations = []; + $config = Double::for(RedisConfig::class)->strict(); + $config->expects('disableEvents')->resolves(static function () use (&$operations): void { + $operations[] = 'disableEvents'; + }); + + $poolManager = Double::for(PoolManager::class)->strict(); $poolManager->expects('pool')->never(); - $poolManager->expects('getPools') - ->globally() - ->ordered() - ->andReturn([ - 'enabled' => $enabledPool, - 'disabled' => $disabledPool, - ]); - $poolManager->expects('purge') - ->with('enabled') - ->globally() - ->ordered(); + $poolManager->expects('getPools')->resolves(static function () use (&$operations, $disabledPool, $enabledPool): array { + $operations[] = 'getPools'; + + return ['enabled' => $enabledPool, 'disabled' => $disabledPool]; + }); + $poolManager->expects('purge')->with('enabled')->resolves(static function () use (&$operations): void { + $operations[] = 'purge'; + }); $manager = new RedisManager( - $app, + $app->instance(), $poolManager, $config, - m::mock(RedisSentinelFactory::class), + Double::for(RedisSentinelFactory::class)->strict(), ); $manager->disableEvents(); + + $this->assertSame(['disableEvents', 'getPools', 'purge'], $operations); } public function testCallDelegatesToDefaultConnection(): void @@ -331,20 +336,19 @@ public function testCallDelegatesToDefaultConnection(): void public function testListenRegistersCommandExecutedListener(): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('listen') - ->once() - ->with(CommandExecuted::class, m::type('Closure')); + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('listen') + ->with(CommandExecuted::class, Argument::type('Closure')); - $app = m::mock(ContainerContract::class); - $app->shouldReceive('bound')->with('events')->andReturn(true); - $app->shouldReceive('make')->with('events')->andReturn($dispatcher); + $app = Double::for(ContainerContract::class, override: true)->strict(); + $app->allows('bound')->with('events')->returns(true); + $app->allows('make')->with('events')->returns($dispatcher); $manager = new RedisManager( - $app, - m::mock(PoolManager::class), + $app->instance(), + Double::for(PoolManager::class)->strict(), $this->createRedisConfig(['default']), - m::mock(RedisSentinelFactory::class), + Double::for(RedisSentinelFactory::class)->strict(), ); $manager->listen(function () {}); @@ -352,20 +356,19 @@ public function testListenRegistersCommandExecutedListener(): void public function testListenForFailuresRegistersCommandFailedListener(): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('listen') - ->once() - ->with(CommandFailed::class, m::type('Closure')); + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('listen') + ->with(CommandFailed::class, Argument::type('Closure')); - $app = m::mock(ContainerContract::class); - $app->shouldReceive('bound')->with('events')->andReturn(true); - $app->shouldReceive('make')->with('events')->andReturn($dispatcher); + $app = Double::for(ContainerContract::class, override: true)->strict(); + $app->allows('bound')->with('events')->returns(true); + $app->allows('make')->with('events')->returns($dispatcher); $manager = new RedisManager( - $app, - m::mock(PoolManager::class), + $app->instance(), + Double::for(PoolManager::class)->strict(), $this->createRedisConfig(['default']), - m::mock(RedisSentinelFactory::class), + Double::for(RedisSentinelFactory::class)->strict(), ); $manager->listenForFailures(function () {}); @@ -396,15 +399,15 @@ private function createManager( array $configuredConnections, ?PoolManager $poolManager = null ): RedisManager { - $app = m::mock(ContainerContract::class); - $poolManager ??= m::mock(PoolManager::class)->makePartial(); + $app = Double::for(ContainerContract::class, override: true)->strict(); + $poolManager ??= new PoolManager(new Container); $config = $this->createRedisConfig($configuredConnections); return new RedisManager( - $app, + $app->instance(), $poolManager, $config, - m::mock(RedisSentinelFactory::class), + Double::for(RedisSentinelFactory::class)->strict(), ); } @@ -417,7 +420,7 @@ private function contextKey(RedisProxy $redis): string } /** - * Create a RedisConfig mock that validates connection names. + * Create Redis configuration for the given connection names. * * @param list $validNames */ diff --git a/tests/Redis/RedisPoolHeartbeatTest.php b/tests/Redis/RedisPoolHeartbeatTest.php index bb89fa1a7f..ab2830cb88 100644 --- a/tests/Redis/RedisPoolHeartbeatTest.php +++ b/tests/Redis/RedisPoolHeartbeatTest.php @@ -24,7 +24,8 @@ use Hypervel\Redis\RedisSentinelFactory; use Hypervel\Support\ClassInvoker; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Redis; use RedisCluster; @@ -37,6 +38,8 @@ class RedisPoolHeartbeatTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; /** @@ -44,6 +47,9 @@ class RedisPoolHeartbeatTest extends TestCase */ protected array $pools = []; + /** + * Close the test pools and clean up the test environment. + */ protected function tearDown(): void { foreach ($this->pools as $pool) { @@ -94,8 +100,8 @@ public function testHeartbeatStartupCanBeRetriedAfterTimerCreationFails(): void $property = new ReflectionProperty(RedisPool::class, 'heartbeatTimer'); $timer = $property->getValue($pool); $failure = new RuntimeException('Timer creation failed.'); - $failingTimer = m::mock(Timer::class); - $failingTimer->shouldReceive('tick')->once()->andThrow($failure); + $failingTimer = Double::for(Timer::class)->strict(); + $failingTimer->expects('tick')->throws($failure); $property->setValue($pool, $failingTimer); $caught = null; @@ -471,7 +477,7 @@ public function testHeartbeatThrowingCancellationStopsTheChildAndEscapes(): void public function testHeartbeatCancellationDuringStartupReportingStopsThePublishedChild(): void { run(function (): void { - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); Container::getInstance()->instance(ExceptionHandlerContract::class, $handler); $pool = $this->createPool([ 'min_retained_connections' => 1, @@ -489,10 +495,9 @@ public function testHeartbeatCancellationDuringStartupReportingStopsThePublished $parentCancellation = null; $childCoroutineId = null; - $handler->shouldReceive('report') - ->once() + $handler->expects('report') ->with($hookFailure) - ->andReturnUsing(static function () use ($reportStarted, $releaseReport, $cleanupStarted, $releaseCleanup, &$childCoroutineId): void { + ->resolves(static function () use ($reportStarted, $releaseReport, $cleanupStarted, $releaseCleanup, &$childCoroutineId): void { $childCoroutineId = Coroutine::id(); $reportStarted->push(true); @@ -612,12 +617,12 @@ public function testHeartbeatCancellationDisposesOnceAndLeavesLaterIdleConnectio ? new RuntimeException('close failed') : new CanceledException('secondary close cancellation'); $pool = $this->createPool([], CancellableDisposalRedisPool::class); - $logger = m::mock(StdoutLoggerInterface::class); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); if ($path === 'evaluation with failed close') { - $logger->shouldReceive('error')->once()->with((string) $secondary); + $logger->expects('error')->with((string) $secondary); } else { - $logger->shouldNotReceive('error'); + $logger->expects('error')->never(); } (new ClassInvoker($pool))->container->instance(StdoutLoggerInterface::class, $logger); @@ -731,11 +736,13 @@ public function testReleaseResetFailureReturnsInvalidConnectionToPool(): void $connection = $pool->borrow(); $this->assertInstanceOf(HeartbeatRedisConnection::class, $connection); - $redis = m::mock(Redis::class); - $redis->expects('select')->once()->with(2)->andReturnTrue(); - $redis->expects('isConnected')->andReturnTrue(); - $redis->expects('getDBNum')->andReturn(2); - $redis->shouldReceive('select')->once()->with(0)->andThrow(new RuntimeException('select failed')); + $redis = Double::for(Redis::class)->strict(); + $redis->allows('getMode')->returns(Redis::ATOMIC); + $redis->allows('close')->returns(true); + $redis->expects('select')->with(2)->returns(true); + $redis->expects('isConnected')->returns(true); + $redis->expects('getDBNum')->returns(2); + $redis->expects('select')->with(0)->throws(new RuntimeException('select failed')); $connection->setNativeClientForTest($redis); $connection->__call('select', [2]); @@ -805,6 +812,8 @@ public function testPinnedConnectionDoesNotRecycleExpiredGenerationMidBorrow(): $this->assertSame(2, $connection->reconnectCount); $client = $connection->nativeClientForTest(); + $client->expects('get')->with('first')->returns(false); + $client->expects('get')->with('second')->returns(false); $this->ageConnectionGeneration($connection); $redis->get('first'); @@ -846,6 +855,8 @@ public function testClusterHeartbeatChecksAllMasters(): void } /** + * Create and track a test pool. + * * @param array $poolOptions * @param array $config */ @@ -871,8 +882,8 @@ protected function createPool(array $poolOptions = [], string $poolClass = Inspe ], $config); $container = new Container; - $redisConfig = m::mock(RedisConfig::class); - $redisConfig->shouldReceive('connectionConfig')->once()->with('heartbeat_test')->andReturn($connectionConfig); + $redisConfig = Double::for(RedisConfig::class)->strict(); + $redisConfig->expects('connectionConfig')->with('heartbeat_test')->returns($connectionConfig); $container->instance(RedisConfig::class, $redisConfig); $pool = new $poolClass($container, 'heartbeat_test'); @@ -881,24 +892,33 @@ protected function createPool(array $poolOptions = [], string $poolClass = Inspe return $pool; } + /** + * Create a proxy backed by the test pool. + */ protected function createProxy(RedisPool $pool): RedisProxy { - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('pool')->with('heartbeat_test')->andReturn($pool); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('heartbeat_test')->returns($pool); return new RedisProxy( $poolManager, 'heartbeat_test', - m::mock(RedisSentinelFactory::class), + Double::for(RedisSentinelFactory::class)->strict(), ); } + /** + * Age the release and last-use timestamps. + */ protected function ageReleasedConnection(RedisConnection $connection): void { (new ReflectionProperty(BaseConnection::class, 'lastReleaseTime'))->setValue($connection, hrtime(true) / 1e9 - 5.0); (new ReflectionProperty(BaseConnection::class, 'lastUseTime'))->setValue($connection, hrtime(true) / 1e9 - 5.0); } + /** + * Expire the current connection generation. + */ protected function ageConnectionGeneration(RedisConnection $connection): void { (new ReflectionProperty(RedisConnection::class, 'createdAt'))->setValue($connection, hrtime(true) / 1e9 - 5.0); @@ -910,6 +930,9 @@ protected function ageConnectionGeneration(RedisConnection $connection): void } } + /** + * Age the release timestamp while preserving recent activity. + */ protected function ageReleaseTimeButKeepLastUseFresh(RedisConnection $connection): void { (new ReflectionProperty(BaseConnection::class, 'lastReleaseTime'))->setValue($connection, hrtime(true) / 1e9 - 5.0); @@ -919,11 +942,17 @@ protected function ageReleaseTimeButKeepLastUseFresh(RedisConnection $connection class InspectableRedisPool extends RedisPool { + /** + * Run the pool heartbeat. + */ public function runHeartbeatForTest(): void { $this->heartbeat(); } + /** + * Get the number of heartbeat timer coroutines. + */ public function heartbeatTimerCount(): int { $timer = (new ReflectionProperty(RedisPool::class, 'heartbeatTimer'))->getValue($this); @@ -931,6 +960,9 @@ public function heartbeatTimerCount(): int return $timer === null ? 0 : count((new ClassInvoker($timer))->coroutines); } + /** + * Create a connection for the heartbeat test. + */ protected function createConnection(): Connection { return new HeartbeatRedisConnection($this->container, $this, $this->config); @@ -947,6 +979,9 @@ class HeartbeatRedisConnection extends RedisConnection public bool $useNativeHeartbeat = false; + /** + * Create a heartbeat test connection. + */ public function __construct(Container $container, ConnectionPool $pool, array $config) { parent::__construct($container, $pool, $config); @@ -954,11 +989,16 @@ public function __construct(Container $container, ConnectionPool $pool, array $c $this->reconnect(); } + /** + * Create a fresh native client and mark the connection reconnected. + */ public function reconnect(): bool { - $redis = m::mock(Redis::class)->shouldIgnoreMissing(); - $redis->shouldReceive('isConnected')->andReturnTrue(); - $redis->shouldReceive('getDBNum')->andReturn($this->config['database']); + $redis = Double::for(Redis::class)->strict(); + $redis->allows('isConnected')->returns(true); + $redis->allows('getDBNum')->returns($this->config['database']); + $redis->allows('getMode')->returns(Redis::ATOMIC); + $redis->allows('close')->returns(true); $this->connection = $redis; ++$this->reconnectCount; $this->markReconnected(); @@ -966,11 +1006,17 @@ public function reconnect(): bool return true; } + /** + * Replace the native client. + */ public function setNativeClientForTest(Redis $redis): void { $this->connection = $redis; } + /** + * Get the active native client. + */ public function nativeClientForTest(): Redis { $this->getConnection(); @@ -980,6 +1026,9 @@ public function nativeClientForTest(): Redis return $this->connection; } + /** + * Perform the configured heartbeat check. + */ protected function pingForHeartbeat(): bool { if ($this->useNativeHeartbeat) { @@ -991,6 +1040,9 @@ protected function pingForHeartbeat(): bool return $this->heartbeatResult; } + /** + * Ensure the active client is a Redis instance. + */ private function assertNativeClientForTest(): void { if (! $this->connection instanceof Redis) { @@ -1001,6 +1053,9 @@ private function assertNativeClientForTest(): void class CancellableDisposalRedisPool extends InspectableRedisPool { + /** + * Create a connection for the heartbeat test. + */ protected function createConnection(): Connection { return new CancellableDisposalRedisConnection($this->container, $this, $this->config); @@ -1015,6 +1070,9 @@ class CancellableDisposalRedisConnection extends HeartbeatRedisConnection public int $closeCount = 0; + /** + * Record the heartbeat and return or throw its configured result. + */ public function heartbeatCheck(float $timeout): bool { ++$this->heartbeatChecks; @@ -1026,6 +1084,9 @@ public function heartbeatCheck(float $timeout): bool return $this->heartbeatResult; } + /** + * Close the test connection. + */ public function close(): bool { ++$this->closeCount; @@ -1041,6 +1102,9 @@ public function close(): bool class FailingHeartbeatRedisPool extends InspectableRedisPool { + /** + * Create a connection for the heartbeat test. + */ protected function createConnection(): Connection { $connection = new HeartbeatRedisConnection($this->container, $this, $this->config); @@ -1052,6 +1116,9 @@ protected function createConnection(): Connection class SlowHeartbeatRedisPool extends InspectableRedisPool { + /** + * Create a connection for the heartbeat test. + */ protected function createConnection(): Connection { return new SlowHeartbeatRedisConnection($this->container, $this, $this->config); @@ -1060,6 +1127,9 @@ protected function createConnection(): Connection class CancellableHeartbeatRedisPool extends InspectableRedisPool { + /** + * Create a connection for the heartbeat test. + */ protected function createConnection(): Connection { return new CancellableHeartbeatRedisConnection($this->container, $this, $this->config); @@ -1076,6 +1146,9 @@ class CancellableHeartbeatRedisConnection extends HeartbeatRedisConnection public ?int $coroutineId = null; + /** + * Create a heartbeat test connection. + */ public function __construct(Container $container, ConnectionPool $pool, array $config) { parent::__construct($container, $pool, $config); @@ -1084,6 +1157,9 @@ public function __construct(Container $container, ConnectionPool $pool, array $c $this->blocker = new Channel(1); } + /** + * Perform the configured heartbeat check. + */ protected function pingForHeartbeat(): bool { $this->coroutineId = Coroutine::id(); @@ -1110,6 +1186,9 @@ class SlowHeartbeatRedisConnection extends HeartbeatRedisConnection public Channel $releaseCleanup; + /** + * Create a heartbeat test connection. + */ public function __construct(Container $container, ConnectionPool $pool, array $config) { parent::__construct($container, $pool, $config); @@ -1119,6 +1198,9 @@ public function __construct(Container $container, ConnectionPool $pool, array $c $this->releaseCleanup = new Channel(1); } + /** + * Perform the configured heartbeat check. + */ protected function pingForHeartbeat(): bool { $this->coroutineId = Coroutine::id(); @@ -1136,6 +1218,9 @@ protected function pingForHeartbeat(): bool class ClosingHeartbeatRedisPool extends InspectableRedisPool { + /** + * Create a connection for the heartbeat test. + */ protected function createConnection(): Connection { return new ClosingHeartbeatRedisConnection($this->container, $this, $this->config); @@ -1144,6 +1229,9 @@ protected function createConnection(): Connection class ClosingHeartbeatRedisConnection extends HeartbeatRedisConnection { + /** + * Perform the configured heartbeat check. + */ protected function pingForHeartbeat(): bool { $this->pool->close(); @@ -1154,6 +1242,9 @@ protected function pingForHeartbeat(): bool class ClusterHeartbeatRedisPool extends InspectableRedisPool { + /** + * Create a connection for the heartbeat test. + */ protected function createConnection(): Connection { return new ClusterHeartbeatRedisConnection($this->container, $this, $this->config); @@ -1164,6 +1255,9 @@ class ClusterHeartbeatRedisConnection extends HeartbeatRedisConnection { public TestHeartbeatRedisClusterClient $clusterClient; + /** + * Create a fresh native client and mark the connection reconnected. + */ public function reconnect(): bool { $redis = new TestHeartbeatRedisClusterClient([ @@ -1188,6 +1282,8 @@ class TestHeartbeatRedisClusterClient extends RedisCluster public array $pingedMasters = []; /** + * Create a cluster client with the configured masters. + * * @param array $masters */ public function __construct(private array $masters) @@ -1195,6 +1291,8 @@ public function __construct(private array $masters) } /** + * Get the configured cluster masters. + * * @return array */ public function _masters(): array @@ -1202,6 +1300,9 @@ public function _masters(): array return $this->masters; } + /** + * Record the master being pinged. + */ public function ping(array|string $key_or_address, ?string $message = null): mixed { if (is_array($key_or_address)) { @@ -1211,6 +1312,9 @@ public function ping(array|string $key_or_address, ?string $message = null): mix return true; } + /** + * Close the test connection. + */ public function close(): bool { return true; diff --git a/tests/Redis/RedisPoolTest.php b/tests/Redis/RedisPoolTest.php index bcba131d6c..75fb27dbb0 100644 --- a/tests/Redis/RedisPoolTest.php +++ b/tests/Redis/RedisPoolTest.php @@ -13,10 +13,14 @@ use Hypervel\Redis\Pool\RedisPool; use Hypervel\Redis\RedisConfig; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class RedisPoolTest extends TestCase { + use VerifiesDoubles; + public function testPoolConnectTimeoutConfiguresTheNativeRedisTimeout(): void { $connectionConfig = [ @@ -35,7 +39,7 @@ public function testPoolConnectTimeoutConfiguresTheNativeRedisTimeout(): void ]; $container = $this->mockContainerWithRedisConfig($connectionConfig); - $pool = new RedisPool($container, 'default'); + $pool = new RedisPool($container->instance(), 'default'); $expectedConfig = $connectionConfig; $expectedConfig['timeout'] = 1.25; @@ -60,7 +64,7 @@ public function testPoolConnectTimeoutDoesNotOverrideTheNativeRedisTimeout(): vo ]; $container = $this->mockContainerWithRedisConfig($connectionConfig); - $pool = new RedisPool($container, 'default'); + $pool = new RedisPool($container->instance(), 'default'); $this->assertSame($connectionConfig, $pool->getConfig()); } @@ -90,10 +94,10 @@ public function testEventOverrideDoesNotRetrofitExistingPoolConfiguration(): voi ], ], ])); - $container = m::mock(Container::class); - $container->shouldReceive('make')->with(RedisConfig::class)->once()->andReturn($redisConfig); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->andReturn(false); - $pool = new RedisPool($container, 'default'); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(RedisConfig::class)->returns($redisConfig); + $container->allows('has')->with(StdoutLoggerInterface::class)->returns(false); + $pool = new RedisPool($container->instance(), 'default'); $redisConfig->enableEvents(); @@ -121,10 +125,10 @@ public function testUsagePolicyTrimsExcessIdleConnections(): void ]; $container = $this->mockContainerWithRedisConfig($connectionConfig); - $container->shouldReceive('has')->andReturn(false); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container->allows('has')->returns(false); + $container->allows('bound')->with('events')->returns(false); - $pool = new TestRedisPool($container, 'default'); + $pool = new TestRedisPool($container->instance(), 'default'); $connection1 = $pool->borrow(); $connection2 = $pool->borrow(); @@ -155,14 +159,14 @@ public function testUsagePolicyTrimsExcessIdleConnections(): void * * @param array $connectionConfig */ - private function mockContainerWithRedisConfig(array $connectionConfig): m\MockInterface|Container + private function mockContainerWithRedisConfig(array $connectionConfig): DoubleInterface { - $redisConfig = m::mock(RedisConfig::class); - $redisConfig->shouldReceive('connectionConfig')->once()->with('default')->andReturn($connectionConfig); + $redisConfig = Double::for(RedisConfig::class)->strict(); + $redisConfig->expects('connectionConfig')->with('default')->returns($connectionConfig); - $container = m::mock(Container::class); - $container->shouldReceive('make')->with(RedisConfig::class)->once()->andReturn($redisConfig); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->andReturn(false); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(RedisConfig::class)->returns($redisConfig); + $container->allows('has')->with(StdoutLoggerInterface::class)->returns(false); return $container; } @@ -170,12 +174,18 @@ private function mockContainerWithRedisConfig(array $connectionConfig): m\MockIn class TestRedisPool extends RedisPool { + /** + * Set the usage tracker for the test. + */ public function setUsageTrackerForTest(UsageTracker $tracker): void { $this->usageTracker = $tracker; $this->usageTrackerInitialized = true; } + /** + * Create a tracked test connection. + */ protected function createConnection(): PoolConnection { return new TestPoolConnection($this->container, $this); @@ -186,11 +196,17 @@ class TestPoolConnection extends Connection { public static int $closeCount = 0; + /** + * Reset the close count. + */ public static function reset(): void { self::$closeCount = 0; } + /** + * Record closing the connection. + */ public function close(): bool { ++self::$closeCount; @@ -198,11 +214,17 @@ public function close(): bool return true; } + /** + * Report a successful test reconnection. + */ public function reconnect(): bool { return true; } + /** + * Return the test connection. + */ public function getActiveConnection(): static { return $this; @@ -211,10 +233,16 @@ public function getActiveConnection(): static class AlwaysTrimIdle implements UsageTracker { + /** + * Leave the test policy unchanged on borrow. + */ public function recordBorrow(): void { } + /** + * Always request trimming excess idle connections. + */ public function shouldTrimExcessIdle(): bool { return true; diff --git a/tests/Redis/RedisProxyNonCoroutineTest.php b/tests/Redis/RedisProxyNonCoroutineTest.php index e663ec5548..25f34abfe1 100644 --- a/tests/Redis/RedisProxyNonCoroutineTest.php +++ b/tests/Redis/RedisProxyNonCoroutineTest.php @@ -4,28 +4,32 @@ namespace Hypervel\Tests\Redis; +use Hypervel\Container\Container; use Hypervel\Context\CoroutineContext; -use Hypervel\Redis\PhpRedisConnection; use Hypervel\Redis\Pool\PoolManager; use Hypervel\Redis\Pool\RedisPool; use Hypervel\Redis\RedisProxy; use Hypervel\Redis\RedisSentinelFactory; +use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; use Hypervel\Tests\TestCase; -use Mockery as m; -use stdClass; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use Redis; class RedisProxyNonCoroutineTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; public function testMultiPinsConnectionUntilTerminalCleanup(): void { - $this->assertCommandPinsConnection('multi', [], new stdClass); + $this->assertCommandPinsConnection('multi', [], Double::for(Redis::class)->strict()); } public function testPipelinePinsConnectionUntilTerminalCleanup(): void { - $this->assertCommandPinsConnection('pipeline', [], new stdClass); + $this->assertCommandPinsConnection('pipeline', [], Double::for(Redis::class)->strict()); } public function testSelectPinsConnectionUntilTerminalCleanup(): void @@ -46,21 +50,20 @@ private function assertCommandPinsConnection( array $arguments, mixed $result, ): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('shouldTransform')->andReturnSelf(); - $connection->shouldReceive('getConnection')->andReturnSelf(); - $connection->shouldReceive('getEventDispatcher')->andReturnNull(); - $connection->expects($command)->with(...$arguments)->andReturn($result); + $client = Double::for(Redis::class)->strict(); + $client->allows('getMode')->returns(Redis::ATOMIC); + $client->expects($command)->with(...$arguments)->returns($result); + $connection = Double::for((new PhpRedisConnectionStub)->setActiveConnection($client))->passthru(); $connection->expects('release'); - $pool = m::mock(RedisPool::class); - $pool->expects('borrow')->andReturn($connection); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->expects('pool')->with('default')->andReturn($pool); + $pool = Double::for(RedisPool::class)->strict(); + $pool->expects('borrow')->returns($connection); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->expects('pool')->with('default')->returns($pool); $redis = new RedisProxy( $poolManager, 'default', - m::mock(RedisSentinelFactory::class), + Double::for(RedisSentinelFactory::class)->strict(), ); $contextKey = (fn (): string => $this->getContextKey())->call($redis); diff --git a/tests/Redis/RedisProxyTest.php b/tests/Redis/RedisProxyTest.php index f69569551d..bca2ae1ea6 100644 --- a/tests/Redis/RedisProxyTest.php +++ b/tests/Redis/RedisProxyTest.php @@ -7,6 +7,7 @@ use BadMethodCallException; use Exception; use Hypervel\ConnectionPool\PoolOptions; +use Hypervel\Container\Container; use Hypervel\Context\CoroutineContext; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Coroutine\Coroutine; @@ -25,9 +26,13 @@ use Hypervel\Redis\Subscriber\CommandBuilder; use Hypervel\Redis\Subscriber\Message; use Hypervel\Redis\Subscriber\Subscriber; +use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; use Hypervel\Tests\Redis\Fixtures\RespServer; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use Redis as PhpRedis; use RedisCluster; @@ -45,16 +50,18 @@ /** * Tests for RedisProxy — the pool-aware connection proxy. * - * We mock RedisConnection entirely and verify the proxy properly - * manages connections, context storage, and command proxying. + * Verify connection ownership and command forwarding through real wrappers + * around isolated native clients. */ class RedisProxyTest extends TestCase { + use VerifiesDoubles; + public function testCommandIsProxiedToConnection(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('foo')->andReturn('bar'); - $connection->shouldReceive('release')->once(); + $connection->nativeClientForTest()->expects('get')->with('foo')->returns('bar'); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -65,12 +72,15 @@ public function testCommandIsProxiedToConnection(): void public function testMacroRegistrationMethodsDoNotCheckoutRedis(): void { - $poolManager = m::mock(PoolManager::class)->makePartial(); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); $poolManager->expects('pool')->never(); $redis = new RedisProxy($poolManager, 'default', $this->sentinelFactory()); $redis->macro('greeting', fn (string $name) => "Hello {$name}"); $redis->mixin(new class { + /** + * Provide the farewell macro. + */ protected function farewell(): callable { return fn (string $name) => "Goodbye {$name}"; @@ -88,11 +98,14 @@ protected function farewell(): callable public function testMixedCaseSubscriptionsUseDedicatedProxyRoute(): void { - $poolManager = m::mock(PoolManager::class)->makePartial(); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); $poolManager->expects('pool')->never(); $redis = new class($poolManager, 'default', $this->sentinelFactory()) extends RedisProxy { public array $subscriptions = []; + /** + * Record the subscription route. + */ protected function handleSubscribe(string $name, array $arguments): void { $this->subscriptions[] = [$name, $arguments]; @@ -116,9 +129,9 @@ protected function handleSubscribe(string $name, array $arguments): void public function testSubscriberLoopDeliversMessagesUntilTheChannelCloses(): void { $message = new Message('updates', 'payload'); - $channel = m::mock(Channel::class); - $channel->expects('pop')->twice()->andReturn($message, false); - $channel->expects('isCanceled')->andReturnFalse(); + $channel = Double::for(Channel::class)->strict(); + $channel->expects('pop')->times(2)->returns($message, false); + $channel->expects('isCanceled')->returns(false); $subscriber = $this->mockSubscriber($channel); $redis = $this->createRedisWithSubscriber($subscriber); $received = []; @@ -134,10 +147,10 @@ public function testSubscriberLoopConvertsNonThrowingMessageWaitCancellation(): { $messageChannel = new Channel(1); $ready = new SwooleChannel(1); - $subscriber = m::mock(Subscriber::class); + $subscriber = Double::for(Subscriber::class)->strict(); $subscriber->closed = false; $subscriber->expects('subscribe')->with('updates'); - $subscriber->expects('channel')->andReturnUsing(function () use ($messageChannel, $ready): Channel { + $subscriber->expects('channel')->resolves(function () use ($messageChannel, $ready): Channel { $ready->push(true); return $messageChannel; @@ -172,8 +185,8 @@ public function testSubscriberLoopPreservesCallbackCancellationOverOrdinaryClose if ($wrapped) { $cancellation = new RuntimeException('Callback cleanup failed.', previous: $cancellation); } - $channel = m::mock(Channel::class); - $channel->expects('pop')->andReturn(new Message('updates', 'payload')); + $channel = Double::for(Channel::class)->strict(); + $channel->expects('pop')->returns(new Message('updates', 'payload')); $subscriber = $this->mockSubscriber($channel, new RuntimeException('close failed')); $redis = $this->createRedisWithSubscriber($subscriber); @@ -190,8 +203,8 @@ public function testSubscriberLoopPreservesCallbackCancellationOverOrdinaryClose public function testSubscriberLoopLetsCloseCancellationSupersedeOrdinaryCallbackFailure(): void { $cancellation = new CanceledException('close canceled'); - $channel = m::mock(Channel::class); - $channel->expects('pop')->andReturn(new Message('updates', 'payload')); + $channel = Double::for(Channel::class)->strict(); + $channel->expects('pop')->returns(new Message('updates', 'payload')); $subscriber = $this->mockSubscriber($channel, $cancellation); $redis = $this->createRedisWithSubscriber($subscriber); @@ -209,8 +222,8 @@ public function testSubscriberLoopPreservesCallbackCancellationOverCloseCancella { $callbackCancellation = new CanceledException('callback canceled'); $closeCancellation = new CanceledException('close canceled'); - $channel = m::mock(Channel::class); - $channel->expects('pop')->andReturn(new Message('updates', 'payload')); + $channel = Double::for(Channel::class)->strict(); + $channel->expects('pop')->returns(new Message('updates', 'payload')); $subscriber = $this->mockSubscriber($channel, $closeCancellation); $redis = $this->createRedisWithSubscriber($subscriber); @@ -227,8 +240,8 @@ public function testSubscriberLoopPreservesCallbackCancellationOverCloseCancella public function testSubscriberLoopRetainsOrdinaryCloseFailurePrecedence(): void { $closeFailure = new RuntimeException('close failed'); - $channel = m::mock(Channel::class); - $channel->expects('pop')->andReturn(new Message('updates', 'payload')); + $channel = Double::for(Channel::class)->strict(); + $channel->expects('pop')->returns(new Message('updates', 'payload')); $subscriber = $this->mockSubscriber($channel, $closeFailure); $redis = $this->createRedisWithSubscriber($subscriber); @@ -245,7 +258,7 @@ public function testSubscriberLoopRetainsOrdinaryCloseFailurePrecedence(): void public function testConnectionBoundMethodsCannotBeCalledThroughProxy(): void { $redis = new RedisProxy( - m::mock(PoolManager::class), + Double::for(PoolManager::class)->strict(), 'default', $this->sentinelFactory(), ); @@ -271,12 +284,12 @@ public function testConnectionBoundMethodsCannotBeCalledThroughProxy(): void public function testMixedCaseMultiStoresConnectionInContext(): void { - $multiInstance = m::mock(PhpRedis::class); + $multiInstance = Double::for(PhpRedis::class)->strict(); $connection = $this->mockConnection(); - $connection->shouldReceive('multi')->once()->andReturn($multiInstance); + $connection->nativeClientForTest()->expects('multi')->returns($multiInstance); // Connection is released via defer() at end of coroutine - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -289,12 +302,12 @@ public function testMixedCaseMultiStoresConnectionInContext(): void public function testMixedCasePipelineStoresConnectionInContext(): void { - $pipelineInstance = m::mock(PhpRedis::class); + $pipelineInstance = Double::for(PhpRedis::class)->strict(); $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($pipelineInstance); + $connection->nativeClientForTest()->expects('pipeline')->returns($pipelineInstance); // Connection is released via defer() at end of coroutine - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -307,9 +320,9 @@ public function testMixedCasePipelineStoresConnectionInContext(): void public function testMixedCaseSelectStoresConnectionInContext(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('select')->once()->with(1)->andReturn(true); + $connection->nativeClientForTest()->expects('select')->with(1)->returns(true); // Connection is released via defer() at end of coroutine - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -322,8 +335,8 @@ public function testMixedCaseSelectStoresConnectionInContext(): void public function testConnectionIsStoredInContextForSelectZeroDatabase(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('select')->once()->with(0)->andReturn(true); - $connection->shouldReceive('release')->once(); + $connection->nativeClientForTest()->expects('select')->with(0)->returns(true); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -336,8 +349,8 @@ public function testConnectionIsStoredInContextForSelectZeroDatabase(): void public function testMixedCaseWatchStoresConnectionInContext(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('watch')->once()->with('key')->andReturn(true); - $connection->shouldReceive('release')->once(); + $connection->nativeClientForTest()->expects('watch')->with('key')->returns(true); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -351,9 +364,9 @@ public function testMixedCaseWatchStoresConnectionInContext(): void public function testNativeDiscardDoesNotInvokePoolDiscard(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('discardTransaction')->once()->andReturn(true); - $connection->shouldReceive('discard')->never(); - $connection->shouldReceive('release')->never(); + $connection->expects('discardTransaction')->returns(true); + $connection->expects('discard')->never(); + $connection->expects('release')->never(); $redis = $this->createRedis($connection); CoroutineContext::set($this->contextKey($redis), $connection); @@ -366,14 +379,14 @@ public function testNativeDiscardDoesNotInvokePoolDiscard(): void public function testRepeatedCallbackTransactionsRegisterOneTerminalRelease(): void { - $firstTransaction = m::mock(PhpRedis::class); - $firstTransaction->expects('exec')->andReturn([]); - $secondTransaction = m::mock(PhpRedis::class); - $secondTransaction->expects('exec')->andReturn([]); + $firstTransaction = Double::for(PhpRedis::class)->strict(); + $firstTransaction->expects('exec')->returns([]); + $secondTransaction = Double::for(PhpRedis::class)->strict(); + $secondTransaction->expects('exec')->returns([]); $connection = $this->mockConnection(); - $connection->expects('multi')->twice()->andReturn($firstTransaction, $secondTransaction); - $connection->expects('release')->twice(); + $connection->nativeClientForTest()->expects('multi')->times(2)->returns($firstTransaction, $secondTransaction); + $connection->expects('release')->times(2); $redis = $this->createCountingRedis($connection); $completed = new Channel(1); @@ -394,15 +407,15 @@ public function testRepeatedCallbackTransactionsRegisterOneTerminalRelease(): vo public function testExistingTerminalReleaseOwnsALaterRawPin(): void { - $transaction = m::mock(PhpRedis::class); - $transaction->expects('exec')->andReturn([]); - $rawTransaction = m::mock(PhpRedis::class); + $transaction = Double::for(PhpRedis::class)->strict(); + $transaction->expects('exec')->returns([]); + $rawTransaction = Double::for(PhpRedis::class)->strict(); $callbackConnection = $this->mockConnection(); - $callbackConnection->expects('multi')->andReturn($transaction); + $callbackConnection->nativeClientForTest()->expects('multi')->returns($transaction); $callbackConnection->expects('release'); $rawConnection = $this->mockConnection(); - $rawConnection->expects('multi')->andReturn($rawTransaction); + $rawConnection->nativeClientForTest()->expects('multi')->returns($rawTransaction); $rawConnection->expects('release'); $redis = $this->createCountingRedis($callbackConnection, $rawConnection); @@ -423,18 +436,18 @@ public function testExistingTerminalReleaseOwnsALaterRawPin(): void public function testCopiedSiblingContextsBorrowDistinctPinnedConnectionsAndOwnTheirReleases(): void { - $parentTransaction = m::mock(PhpRedis::class); - $firstChildTransaction = m::mock(PhpRedis::class); - $secondChildTransaction = m::mock(PhpRedis::class); + $parentTransaction = Double::for(PhpRedis::class)->strict(); + $firstChildTransaction = Double::for(PhpRedis::class)->strict(); + $secondChildTransaction = Double::for(PhpRedis::class)->strict(); $parentConnection = $this->mockConnection(); - $parentConnection->expects('multi')->andReturn($parentTransaction); + $parentConnection->nativeClientForTest()->expects('multi')->returns($parentTransaction); $parentConnection->expects('release'); $firstChildConnection = $this->mockConnection(); - $firstChildConnection->expects('multi')->andReturn($firstChildTransaction); + $firstChildConnection->nativeClientForTest()->expects('multi')->returns($firstChildTransaction); $firstChildConnection->expects('release'); $secondChildConnection = $this->mockConnection(); - $secondChildConnection->expects('multi')->andReturn($secondChildTransaction); + $secondChildConnection->nativeClientForTest()->expects('multi')->returns($secondChildTransaction); $secondChildConnection->expects('release'); $redis = $this->createCountingRedis( @@ -481,19 +494,19 @@ public function testCopiedSiblingContextsBorrowDistinctPinnedConnectionsAndOwnTh public function testDetachedCopiedChildBorrowsAfterItsParentReleases(): void { - $parentTransaction = m::mock(PhpRedis::class); - $childTransaction = m::mock(PhpRedis::class); + $parentTransaction = Double::for(PhpRedis::class)->strict(); + $childTransaction = Double::for(PhpRedis::class)->strict(); $parentReleased = new Channel(1); $childReleased = new Channel(1); $parentConnection = $this->mockConnection(); - $parentConnection->expects('multi')->andReturn($parentTransaction); - $parentConnection->expects('release')->andReturnUsing(static function () use ($parentReleased): void { + $parentConnection->nativeClientForTest()->expects('multi')->returns($parentTransaction); + $parentConnection->expects('release')->resolves(static function () use ($parentReleased): void { $parentReleased->push(true); }); $childConnection = $this->mockConnection(); - $childConnection->expects('multi')->andReturn($childTransaction); - $childConnection->expects('release')->andReturnUsing(static function () use ($childReleased): void { + $childConnection->nativeClientForTest()->expects('multi')->returns($childTransaction); + $childConnection->expects('release')->resolves(static function () use ($childReleased): void { $childReleased->push(true); }); @@ -538,28 +551,28 @@ public function testDetachedCopiedChildBorrowsAfterItsParentReleases(): void public function testSelectPinnedConnectionDoesNotLeakAcrossCoroutines(): void { $setConnection = $this->mockConnection(); - $setConnection->shouldReceive('set')->once()->with('xxxx', 'yyyy')->andReturn('db:0 name:set argument:xxxx,yyyy'); - $setConnection->shouldReceive('release')->once(); + $setConnection->nativeClientForTest()->expects('set')->with('xxxx', 'yyyy', null)->returns('db:0 name:set argument:xxxx,yyyy'); + $setConnection->expects('release'); $selectedConnection = $this->mockConnection(); - $selectedConnection->shouldReceive('select')->once()->with(2)->andReturn(true); - $selectedConnection->shouldReceive('get')->once()->with('xxxx')->andReturn('db:2 name:get argument:xxxx'); - $selectedConnection->shouldReceive('release')->once(); + $selectedConnection->nativeClientForTest()->expects('select')->with(2)->returns(true); + $selectedConnection->nativeClientForTest()->expects('get')->with('xxxx')->returns('db:2 name:get argument:xxxx'); + $selectedConnection->expects('release'); $otherCoroutineConnection = $this->mockConnection(); - $otherCoroutineConnection->shouldReceive('get')->once()->with('xxxx')->andReturn('db:0 name:get argument:xxxx'); - $otherCoroutineConnection->shouldReceive('release')->once(); + $otherCoroutineConnection->nativeClientForTest()->expects('get')->with('xxxx')->returns('db:0 name:get argument:xxxx'); + $otherCoroutineConnection->expects('release'); - $pool = m::mock(RedisPool::class); - $pool->shouldReceive('borrow')->times(3)->andReturn( + $pool = Double::for(RedisPool::class)->strict(); + $pool->expects('borrow')->times(3)->returns( $setConnection, $selectedConnection, $otherCoroutineConnection, ); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray([])); + $pool->allows('getOptions')->returns(PoolOptions::fromArray([])); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('pool')->with('default')->andReturn($pool); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('default')->returns($pool); $redis = new RedisProxy($poolManager, 'default', $this->sentinelFactory()); @@ -577,24 +590,24 @@ public function testSelectPinnedConnectionDoesNotLeakAcrossCoroutines(): void public function testPinnedConnectionInOneCoroutineIsNotReusedInAnotherCoroutine(): void { - $pipeline = m::mock(PhpRedis::class); + $pipeline = Double::for(PhpRedis::class)->strict(); $pinnedConnection = $this->mockConnection(); - $pinnedConnection->shouldReceive('multi')->once()->andReturn($pipeline); - $pinnedConnection->shouldReceive('set')->once()->with('id', '123')->andReturnSelf(); - $pinnedConnection->shouldReceive('exec')->once()->andReturn([]); - $pinnedConnection->shouldReceive('release')->once(); + $pinnedConnection->nativeClientForTest()->expects('multi')->returns($pipeline); + $pinnedConnection->nativeClientForTest()->expects('set')->with('id', '123', null)->returns($pinnedConnection->nativeClientForTest()); + $pinnedConnection->nativeClientForTest()->expects('exec')->returns([]); + $pinnedConnection->expects('release'); $otherCoroutineConnection = $this->mockConnection(); - $otherCoroutineConnection->shouldReceive('get')->once()->with('id')->andReturn('from-other-connection'); - $otherCoroutineConnection->shouldReceive('release')->once(); + $otherCoroutineConnection->nativeClientForTest()->expects('get')->with('id')->returns('from-other-connection'); + $otherCoroutineConnection->expects('release'); - $pool = m::mock(RedisPool::class); - $pool->shouldReceive('borrow')->times(2)->andReturn($pinnedConnection, $otherCoroutineConnection); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray([])); + $pool = Double::for(RedisPool::class)->strict(); + $pool->expects('borrow')->times(2)->returns($pinnedConnection, $otherCoroutineConnection); + $pool->allows('getOptions')->returns(PoolOptions::fromArray([])); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('pool')->with('default')->andReturn($pool); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('default')->returns($pool); $redis = new RedisProxy($poolManager, 'default', $this->sentinelFactory()); @@ -614,10 +627,8 @@ public function testPinnedConnectionInOneCoroutineIsNotReusedInAnotherCoroutine( public function testExistingContextConnectionIsReused(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->twice()->andReturn('value1', 'value2'); - // Connection is NOT released during the test (it already existed in context), - // but allow release() call for test cleanup - $connection->shouldReceive('release')->zeroOrMoreTimes(); + $connection->nativeClientForTest()->expects('get')->times(2)->returns('value1', 'value2'); + $connection->expects('release')->never(); $redis = $this->createRedis($connection); @@ -635,10 +646,9 @@ public function testExistingContextConnectionIsReused(): void public function testExceptionIsPropagated(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get') - ->once() - ->andThrow(new RuntimeException('Redis error')); - $connection->shouldReceive('release')->once(); + $connection->nativeClientForTest()->expects('get') + ->throws(new RuntimeException('Redis error')); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -650,13 +660,12 @@ public function testExceptionIsPropagated(): void public function testReleasesConnectionWhenUnderlyingGetConnectionFails(): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('shouldTransform')->andReturnSelf(); - $connection->shouldReceive('getEventDispatcher')->andReturnNull(); - $connection->shouldReceive('getConnection') - ->once() - ->andThrow(new RuntimeException('Get connection failed.')); - $connection->shouldReceive('release')->once(); + $connection = Double::for(PhpRedisConnection::class)->strict(); + $connection->allows('shouldTransform'); + $connection->allows('getEventDispatcher')->returns(null); + $connection->expects('getConnection') + ->throws(new RuntimeException('Get connection failed.')); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -671,7 +680,7 @@ public function testExceptionWithContextConnectionDoesNotReleaseConnection(): vo $expectedException = new Exception('Redis error'); $mockRedisConnection = $this->createMockRedisConnection('get', null, $expectedException); - $mockRedisConnection->shouldReceive('release')->never(); + $mockRedisConnection->expects('release')->never(); $redis = $this->createRedis($mockRedisConnection); @@ -692,7 +701,7 @@ public function testExceptionWithSameConnectionCommandReleasesConnectionInsteadO $mockRedisConnection = $this->createMockRedisConnection('multi', null, $expectedException); // On error, connection should be released, NOT stored in context - $mockRedisConnection->shouldReceive('release')->once(); + $mockRedisConnection->expects('release'); $redis = $this->createRedis($mockRedisConnection); @@ -709,16 +718,15 @@ public function testExceptionWithSameConnectionCommandReleasesConnectionInsteadO public function testEventDispatchedOnSuccess(): void { - $mockEventDispatcher = m::mock(Dispatcher::class); - $mockEventDispatcher->shouldReceive('hasListeners') + $mockEventDispatcher = Double::for(Dispatcher::class)->strict(); + $mockEventDispatcher->allows('hasListeners') ->with(CommandFailed::class) - ->andReturn(false); - $mockEventDispatcher->shouldReceive('hasListeners') + ->returns(false); + $mockEventDispatcher->allows('hasListeners') ->with(CommandExecuted::class) - ->andReturn(true); - $mockEventDispatcher->shouldReceive('dispatch') - ->once() - ->with(m::on(function (CommandExecuted $event) { + ->returns(true); + $mockEventDispatcher->expects('dispatch') + ->with(Argument::satisfies(function (CommandExecuted $event) { return $event->command === 'get' && $event->parameters === ['key'] && $event->connectionName === 'default' @@ -726,7 +734,7 @@ public function testEventDispatchedOnSuccess(): void })); $mockRedisConnection = $this->createMockRedisConnection('get', 'value', null, $mockEventDispatcher); - $mockRedisConnection->shouldReceive('release')->once(); + $mockRedisConnection->expects('release'); $redis = $this->createRedis($mockRedisConnection); @@ -735,13 +743,13 @@ public function testEventDispatchedOnSuccess(): void public function testSuccessEventTemporarilyPublishesTheOwnedConnection(): void { - $dispatcher = m::mock(Dispatcher::class); + $dispatcher = Double::for(Dispatcher::class)->strict(); $connection = $this->createMockRedisConnection('get', 'value', eventDispatcher: $dispatcher); $redis = $this->createRedis($connection); - $dispatcher->expects('hasListeners')->with(CommandExecuted::class)->andReturnTrue(); + $dispatcher->expects('hasListeners')->with(CommandExecuted::class)->returns(true); $dispatcher->expects('dispatch') - ->with(m::type(CommandExecuted::class)) - ->andReturnUsing(function () use ($connection, $redis): void { + ->with(Argument::type(CommandExecuted::class)) + ->resolves(function () use ($connection, $redis): void { $this->assertSame( $connection, CoroutineContext::get($this->contextKey($redis)), @@ -755,19 +763,19 @@ public function testSuccessEventTemporarilyPublishesTheOwnedConnection(): void public function testSuccessEventPreservesAPreExistingContextConnection(): void { - $dispatcher = m::mock(Dispatcher::class); + $dispatcher = Double::for(Dispatcher::class)->strict(); $connection = $this->createMockRedisConnection('get', 'value', eventDispatcher: $dispatcher); $redis = $this->createRedis($connection); - $dispatcher->expects('hasListeners')->with(CommandExecuted::class)->andReturnTrue(); + $dispatcher->expects('hasListeners')->with(CommandExecuted::class)->returns(true); $dispatcher->expects('dispatch') - ->with(m::type(CommandExecuted::class)) - ->andReturnUsing(function () use ($connection, $redis): void { + ->with(Argument::type(CommandExecuted::class)) + ->resolves(function () use ($connection, $redis): void { $this->assertSame( $connection, CoroutineContext::get($this->contextKey($redis)), ); }); - $connection->shouldNotReceive('release'); + $connection->expects('release')->never(); CoroutineContext::set($this->contextKey($redis), $connection); $this->assertSame('value', $redis->get('key')); @@ -779,18 +787,18 @@ public function testSuccessEventPreservesAPreExistingContextConnection(): void public function testSuccessEventCanRunANestedCommandOnTheOwnedConnection(): void { - $dispatcher = m::mock(Dispatcher::class); + $dispatcher = Double::for(Dispatcher::class)->strict(); $connection = $this->createMockRedisConnection('get', 'outer', eventDispatcher: $dispatcher); - $connection->expects('set')->with('nested', 'value')->andReturnTrue(); + $connection->nativeClientForTest()->expects('set')->with('nested', 'value', null)->returns(true); $connection->expects('release'); $dispatcher->expects('hasListeners') - ->twice() + ->times(2) ->with(CommandExecuted::class) - ->andReturn(true, false); + ->returns(true, false); $redis = $this->createRedis($connection); $dispatcher->expects('dispatch') - ->with(m::type(CommandExecuted::class)) - ->andReturnUsing(function () use ($redis): void { + ->with(Argument::type(CommandExecuted::class)) + ->resolves(function () use ($redis): void { $this->assertTrue($redis->set('nested', 'value')); }); @@ -802,16 +810,15 @@ public function testEventDispatchedOnErrorWithExceptionInfo(): void { $expectedException = new Exception('Redis error'); - $mockEventDispatcher = m::mock(Dispatcher::class); - $mockEventDispatcher->shouldReceive('hasListeners') + $mockEventDispatcher = Double::for(Dispatcher::class)->strict(); + $mockEventDispatcher->allows('hasListeners') ->with(CommandFailed::class) - ->andReturn(true); - $mockEventDispatcher->shouldReceive('hasListeners') + ->returns(true); + $mockEventDispatcher->allows('hasListeners') ->with(CommandExecuted::class) - ->andReturn(false); - $mockEventDispatcher->shouldReceive('dispatch') - ->once() - ->with(m::on(function (CommandFailed $event) use ($expectedException) { + ->returns(false); + $mockEventDispatcher->expects('dispatch') + ->with(Argument::satisfies(function (CommandFailed $event) use ($expectedException) { return $event->command === 'get' && $event->parameters === ['key'] && $event->exception === $expectedException @@ -821,7 +828,7 @@ public function testEventDispatchedOnErrorWithExceptionInfo(): void })); $mockRedisConnection = $this->createMockRedisConnection('get', null, $expectedException, $mockEventDispatcher); - $mockRedisConnection->shouldReceive('release')->once(); + $mockRedisConnection->expects('release'); $redis = $this->createRedis($mockRedisConnection); @@ -840,8 +847,8 @@ public function testCommandCancellationSkipsFailureEventAndStillReleasesTheConne if ($wrapped) { $cancellation = new RuntimeException('Command cleanup failed.', previous: $cancellation); } - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldNotReceive('hasListeners'); + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('hasListeners')->never(); $connection = $this->createMockRedisConnection( 'get', exception: $cancellation, @@ -860,13 +867,14 @@ public function testCommandCancellationSkipsFailureEventAndStillReleasesTheConne public function testCommandNormalizesWrappedPhpRedisCancellation(): void { $nativeFailure = new RedisException('command canceled'); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldNotReceive('hasListeners'); + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('hasListeners')->never(); $connection = $this->createMockRedisConnection( 'get', exception: $nativeFailure, eventDispatcher: $dispatcher, ); + $connection->nativeClientForTest()->expects('getLastError')->returns(null); $connection->expects('release'); $redis = $this->createRedis($connection); @@ -881,13 +889,13 @@ public function testCommandNormalizesWrappedPhpRedisCancellation(): void public function testFailureEventTemporarilyPublishesTheOwnedConnection(): void { $commandException = new RuntimeException('Command failed.'); - $dispatcher = m::mock(Dispatcher::class); + $dispatcher = Double::for(Dispatcher::class)->strict(); $connection = $this->createMockRedisConnection('get', exception: $commandException, eventDispatcher: $dispatcher); $redis = $this->createRedis($connection); - $dispatcher->expects('hasListeners')->with(CommandFailed::class)->andReturnTrue(); + $dispatcher->expects('hasListeners')->with(CommandFailed::class)->returns(true); $dispatcher->expects('dispatch') - ->with(m::type(CommandFailed::class)) - ->andReturnUsing(function () use ($connection, $redis): void { + ->with(Argument::type(CommandFailed::class)) + ->resolves(function () use ($connection, $redis): void { $this->assertSame( $connection, CoroutineContext::get($this->contextKey($redis)), @@ -908,16 +916,16 @@ public function testFailureEventTemporarilyPublishesTheOwnedConnection(): void public function testFailureEventCanRunANestedCommandOnTheOwnedConnection(): void { $commandException = new RuntimeException('Command failed.'); - $dispatcher = m::mock(Dispatcher::class); + $dispatcher = Double::for(Dispatcher::class)->strict(); $connection = $this->createMockRedisConnection('get', exception: $commandException, eventDispatcher: $dispatcher); - $connection->expects('set')->with('nested', 'recovered')->andReturnTrue(); + $connection->nativeClientForTest()->expects('set')->with('nested', 'recovered', null)->returns(true); $connection->expects('release'); - $dispatcher->expects('hasListeners')->with(CommandFailed::class)->andReturnTrue(); - $dispatcher->expects('hasListeners')->with(CommandExecuted::class)->andReturnFalse(); + $dispatcher->expects('hasListeners')->with(CommandFailed::class)->returns(true); + $dispatcher->expects('hasListeners')->with(CommandExecuted::class)->returns(false); $redis = $this->createRedis($connection); $dispatcher->expects('dispatch') - ->with(m::type(CommandFailed::class)) - ->andReturnUsing(function () use ($redis): void { + ->with(Argument::type(CommandFailed::class)) + ->resolves(function () use ($redis): void { $this->assertTrue($redis->set('nested', 'recovered')); }); @@ -933,19 +941,19 @@ public function testFailureEventCanRunANestedCommandOnTheOwnedConnection(): void public function testMultiListenerQueuesNestedCommandsOnTheOwnedTransaction(): void { - $transaction = m::mock(PhpRedis::class); - $dispatcher = m::mock(Dispatcher::class); + $transaction = Double::for(PhpRedis::class)->strict(); + $dispatcher = Double::for(Dispatcher::class)->strict(); $connection = $this->createMockRedisConnection('multi', $transaction, eventDispatcher: $dispatcher); - $connection->expects('set')->with('nested', 'queued')->andReturn($transaction); + $connection->nativeClientForTest()->expects('set')->with('nested', 'queued', null)->returns($transaction); $connection->expects('release'); $dispatcher->expects('hasListeners') - ->twice() + ->times(2) ->with(CommandExecuted::class) - ->andReturn(true, false); + ->returns(true, false); $redis = $this->createRedis($connection); $dispatcher->expects('dispatch') - ->with(m::type(CommandExecuted::class)) - ->andReturnUsing(function () use ($redis, $transaction): void { + ->with(Argument::type(CommandExecuted::class)) + ->resolves(function () use ($redis, $transaction): void { $this->assertSame($transaction, $redis->set('nested', 'queued')); }); @@ -959,9 +967,9 @@ public function testMultiListenerQueuesNestedCommandsOnTheOwnedTransaction(): vo public function testThrowingSuccessListenerStillReleasesOrdinaryConnection(): void { $eventException = new RuntimeException('Success listener failed.'); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->expects('hasListeners')->with(CommandExecuted::class)->andReturnTrue(); - $dispatcher->expects('dispatch')->andThrow($eventException); + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('hasListeners')->with(CommandExecuted::class)->returns(true); + $dispatcher->expects('dispatch')->throws($eventException); $connection = $this->createMockRedisConnection('get', 'value', null, $dispatcher); $connection->expects('release'); $redis = $this->createRedis($connection); @@ -979,10 +987,10 @@ public function testThrowingSuccessListenerStillReleasesOrdinaryConnection(): vo public function testThrowingSuccessListenerDoesNotSkipSameConnectionHandoff(): void { $eventException = new RuntimeException('Success listener failed.'); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->expects('hasListeners')->with(CommandExecuted::class)->andReturnTrue(); - $dispatcher->expects('dispatch')->andThrow($eventException); - $transaction = m::mock(PhpRedis::class); + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('hasListeners')->with(CommandExecuted::class)->returns(true); + $dispatcher->expects('dispatch')->throws($eventException); + $transaction = Double::for(PhpRedis::class)->strict(); $connection = $this->createMockRedisConnection('multi', $transaction, null, $dispatcher); $connection->expects('release'); $redis = $this->createRedis($connection); @@ -1004,9 +1012,9 @@ public function testThrowingFailureListenerStillReleasesAndReplacesCommandFailur { $commandException = new RuntimeException('Command failed.'); $eventException = new RuntimeException('Failure listener failed.'); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->expects('hasListeners')->with(CommandFailed::class)->andReturnTrue(); - $dispatcher->expects('dispatch')->andThrow($eventException); + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('hasListeners')->with(CommandFailed::class)->returns(true); + $dispatcher->expects('dispatch')->throws($eventException); $connection = $this->createMockRedisConnection('get', null, $commandException, $dispatcher); $connection->expects('release'); $redis = $this->createRedis($connection); @@ -1025,7 +1033,7 @@ public function testCommandFailureRemainsPrimaryOverCleanupFailure(): void { $commandException = new RuntimeException('Command failed.'); $connection = $this->createMockRedisConnection('get', null, $commandException); - $connection->expects('release')->andThrow(new RuntimeException('Cleanup failed.')); + $connection->expects('release')->throws(new RuntimeException('Cleanup failed.')); try { $this->createRedis($connection)->get('key'); @@ -1047,7 +1055,7 @@ public function testCleanupCancellationSupersedesOrdinaryCommandFailure(bool $wr 'get', exception: new RuntimeException('Command failed.'), ); - $connection->expects('release')->andThrow($cancellation); + $connection->expects('release')->throws($cancellation); try { $this->createRedis($connection)->get('key'); @@ -1065,15 +1073,15 @@ public function testEventCancellationRemainsPrimaryOverOrdinaryCleanupFailure(bo if ($wrapped) { $cancellation = new RuntimeException('Event cleanup failed.', previous: $cancellation); } - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->expects('hasListeners')->with(CommandExecuted::class)->andReturnTrue(); - $dispatcher->expects('dispatch')->andThrow($cancellation); + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('hasListeners')->with(CommandExecuted::class)->returns(true); + $dispatcher->expects('dispatch')->throws($cancellation); $connection = $this->createMockRedisConnection( 'get', 'value', eventDispatcher: $dispatcher, ); - $connection->expects('release')->andThrow(new RuntimeException('Cleanup failed.')); + $connection->expects('release')->throws(new RuntimeException('Cleanup failed.')); try { $this->createRedis($connection)->get('key'); @@ -1087,7 +1095,7 @@ public function testCleanupFailurePropagatesAfterSuccessfulCommand(): void { $cleanupException = new RuntimeException('Cleanup failed.'); $connection = $this->createMockRedisConnection(); - $connection->expects('release')->andThrow($cleanupException); + $connection->expects('release')->throws($cleanupException); try { $this->createRedis($connection)->get('key'); @@ -1099,12 +1107,12 @@ public function testCleanupFailurePropagatesAfterSuccessfulCommand(): void public function testCallbackTransactionClearsWatchStateAfterSuccessfulExec(): void { - $transaction = m::mock(PhpRedis::class); - $transaction->expects('exec')->andReturn([]); + $transaction = Double::for(PhpRedis::class)->strict(); + $transaction->expects('exec')->returns([]); $connection = $this->mockConnection(); - $connection->expects('multi')->andReturn($transaction); + $connection->nativeClientForTest()->expects('multi')->returns($transaction); $connection->expects('clearWatchState'); - $connection->shouldNotReceive('release'); + $connection->expects('release')->never(); $redis = $this->createRedis($connection); CoroutineContext::set($this->contextKey($redis), $connection); @@ -1117,12 +1125,12 @@ public function testCallbackTransactionClearsWatchStateAfterSuccessfulExec(): vo public function testCallbackTransactionClearsWatchStateAfterOptimisticLockConflict(): void { - $transaction = m::mock(PhpRedis::class); - $transaction->expects('exec')->andReturnFalse(); + $transaction = Double::for(PhpRedis::class)->strict(); + $transaction->expects('exec')->returns(false); $connection = $this->mockConnection(); - $connection->expects('multi')->andReturn($transaction); + $connection->nativeClientForTest()->expects('multi')->returns($transaction); $connection->expects('clearWatchState'); - $connection->shouldNotReceive('release'); + $connection->expects('release')->never(); $redis = $this->createRedis($connection); CoroutineContext::set($this->contextKey($redis), $connection); @@ -1134,13 +1142,13 @@ public function testCallbackTransactionClearsWatchStateAfterOptimisticLockConfli public function testCallbackTransactionInvalidatesWithoutClearingWatchStateWhenExecThrows(): void { - $transaction = m::mock(PhpRedis::class); - $transaction->expects('exec')->andThrow(new RuntimeException('Exec failed.')); + $transaction = Double::for(PhpRedis::class)->strict(); + $transaction->expects('exec')->throws(new RuntimeException('Exec failed.')); $connection = $this->mockConnection(); - $connection->expects('multi')->andReturn($transaction); + $connection->nativeClientForTest()->expects('multi')->returns($transaction); $connection->expects('invalidate'); - $connection->shouldNotReceive('clearWatchState'); - $connection->shouldNotReceive('release'); + $connection->expects('clearWatchState')->never(); + $connection->expects('release')->never(); $redis = $this->createRedis($connection); CoroutineContext::set($this->contextKey($redis), $connection); @@ -1154,12 +1162,12 @@ public function testCallbackTransactionInvalidatesWithoutClearingWatchStateWhenE public function testCallbackTransactionPreservesOperationCancellationOverCleanupFailure(): void { $cancellation = new CanceledException('exec canceled'); - $transaction = m::mock(PhpRedis::class); - $transaction->expects('exec')->andThrow($cancellation); + $transaction = Double::for(PhpRedis::class)->strict(); + $transaction->expects('exec')->throws($cancellation); $connection = $this->mockConnection(); - $connection->expects('multi')->andReturn($transaction); + $connection->nativeClientForTest()->expects('multi')->returns($transaction); $connection->expects('invalidate'); - $connection->expects('release')->andThrow(new RuntimeException('Cleanup failed.')); + $connection->expects('release')->throws(new RuntimeException('Cleanup failed.')); try { $this->createRedis($connection)->transaction(static function (): void { @@ -1173,10 +1181,10 @@ public function testCallbackTransactionPreservesOperationCancellationOverCleanup public function testCallbackTransactionNormalizesWrappedPhpRedisCancellation(): void { $nativeFailure = new RedisException('exec canceled'); - $transaction = m::mock(PhpRedis::class); - $transaction->expects('exec')->andThrow($nativeFailure); + $transaction = Double::for(PhpRedis::class)->strict(); + $transaction->expects('exec')->throws($nativeFailure); $connection = $this->mockConnection(); - $connection->expects('multi')->andReturn($transaction); + $connection->nativeClientForTest()->expects('multi')->returns($transaction); $connection->expects('invalidate'); $connection->expects('release'); $redis = $this->createRedis($connection); @@ -1193,12 +1201,12 @@ public function testCallbackTransactionNormalizesWrappedPhpRedisCancellation(): public function testCallbackTransactionCleanupCancellationSupersedesOrdinaryOperationFailure(): void { $cancellation = new CanceledException('cleanup canceled'); - $transaction = m::mock(PhpRedis::class); - $transaction->expects('exec')->andThrow(new RuntimeException('Exec failed.')); + $transaction = Double::for(PhpRedis::class)->strict(); + $transaction->expects('exec')->throws(new RuntimeException('Exec failed.')); $connection = $this->mockConnection(); - $connection->expects('multi')->andReturn($transaction); + $connection->nativeClientForTest()->expects('multi')->returns($transaction); $connection->expects('invalidate'); - $connection->expects('release')->andThrow($cancellation); + $connection->expects('release')->throws($cancellation); try { $this->createRedis($connection)->transaction(static function (): void { @@ -1212,12 +1220,12 @@ public function testCallbackTransactionCleanupCancellationSupersedesOrdinaryOper public function testCallbackTransactionOrdinaryCleanupFailureRetainsFinallyPrecedence(): void { $cleanupFailure = new RuntimeException('Cleanup failed.'); - $transaction = m::mock(PhpRedis::class); - $transaction->expects('exec')->andThrow(new RuntimeException('Exec failed.')); + $transaction = Double::for(PhpRedis::class)->strict(); + $transaction->expects('exec')->throws(new RuntimeException('Exec failed.')); $connection = $this->mockConnection(); - $connection->expects('multi')->andReturn($transaction); + $connection->nativeClientForTest()->expects('multi')->returns($transaction); $connection->expects('invalidate'); - $connection->expects('release')->andThrow($cleanupFailure); + $connection->expects('release')->throws($cleanupFailure); try { $this->createRedis($connection)->transaction(static function (): void { @@ -1230,12 +1238,12 @@ public function testCallbackTransactionOrdinaryCleanupFailureRetainsFinallyPrece public function testCallbackPipelineDoesNotClearWatchState(): void { - $pipeline = m::mock(PhpRedis::class); - $pipeline->expects('exec')->andReturn([]); + $pipeline = Double::for(PhpRedis::class)->strict(); + $pipeline->expects('exec')->returns([]); $connection = $this->mockConnection(); - $connection->expects('pipeline')->andReturn($pipeline); - $connection->shouldNotReceive('clearWatchState'); - $connection->shouldNotReceive('release'); + $connection->nativeClientForTest()->expects('pipeline')->returns($pipeline); + $connection->expects('clearWatchState')->never(); + $connection->expects('release')->never(); $redis = $this->createRedis($connection); CoroutineContext::set($this->contextKey($redis), $connection); @@ -1249,11 +1257,11 @@ public function testCallbackPipelineDoesNotClearWatchState(): void public function testRegularCommandDoesNotStoreConnectionInContext(): void { $mockRedisConnection = $this->mockConnection(); - $mockRedisConnection->shouldReceive('release')->once(); + $mockRedisConnection->expects('release'); $redis = $this->createRedis($mockRedisConnection); - $mockRedisConnection->expects('get') + $mockRedisConnection->nativeClientForTest()->expects('get') ->with('key') - ->andReturnUsing(function () use ($redis): string { + ->resolves(function () use ($redis): string { $this->assertFalse(CoroutineContext::has($this->contextKey($redis))); return 'value'; @@ -1267,7 +1275,7 @@ public function testRegularCommandDoesNotStoreConnectionInContext(): void public function testWithConnectionExecutesCallbackAndReleasesConnection(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -1284,7 +1292,7 @@ public function testWithConnectionReusesExistingContextConnection(): void { $connection = $this->mockConnection(); // Should NOT release since connection was already in context - $connection->shouldReceive('release')->never(); + $connection->expects('release')->never(); $redis = $this->createRedis($connection); @@ -1306,7 +1314,7 @@ public function testWithConnectionReleasesOnException(): void { $connection = $this->mockConnection(); // Should release even on exception - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -1327,7 +1335,7 @@ public function testWithConnectionPreservesCallbackCancellationOverCleanupFailur $cancellation = new RuntimeException('Callback cleanup failed.', previous: $cancellation); } $connection = $this->mockConnection(); - $connection->expects('release')->andThrow(new RuntimeException('Cleanup failed.')); + $connection->expects('release')->throws(new RuntimeException('Cleanup failed.')); try { $this->createRedis($connection)->withConnection( @@ -1345,7 +1353,7 @@ public function testWithConnectionCleanupCancellationSupersedesOrdinaryCallbackF { $cancellation = new CanceledException('Cleanup canceled.'); $connection = $this->mockConnection(); - $connection->expects('release')->andThrow($cancellation); + $connection->expects('release')->throws($cancellation); try { $this->createRedis($connection)->withConnection( @@ -1363,7 +1371,7 @@ public function testWithConnectionOrdinaryCleanupFailureRetainsFinallyPrecedence { $cleanupFailure = new RuntimeException('Cleanup failed.'); $connection = $this->mockConnection(); - $connection->expects('release')->andThrow($cleanupFailure); + $connection->expects('release')->throws($cleanupFailure); try { $this->createRedis($connection)->withConnection( @@ -1381,7 +1389,7 @@ public function testWithConnectionDoesNotReleaseContextConnectionOnException(): { $connection = $this->mockConnection(); // Should NOT release since connection was in context - $connection->shouldReceive('release')->never(); + $connection->expects('release')->never(); $redis = $this->createRedis($connection); @@ -1402,14 +1410,12 @@ public function testWithConnectionDoesNotReleaseContextConnectionOnException(): public function testWithConnectionDefaultsToTransformTrue(): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getConnection')->andReturn($connection); - $connection->shouldReceive('getEventDispatcher')->andReturnNull(); - $connection->shouldReceive('shouldTransform') - ->once() - ->with(true) - ->andReturnSelf(); - $connection->shouldReceive('release')->once(); + $connection = Double::for(PhpRedisConnection::class)->strict(); + $connection->allows('getConnection')->returns($connection); + $connection->allows('getEventDispatcher')->returns(null); + $connection->expects('shouldTransform') + ->with(true); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -1420,14 +1426,12 @@ public function testWithConnectionDefaultsToTransformTrue(): void public function testWithConnectionRespectsTransformFalse(): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getConnection')->andReturn($connection); - $connection->shouldReceive('getEventDispatcher')->andReturnNull(); - $connection->shouldReceive('shouldTransform') - ->once() - ->with(false) - ->andReturnSelf(); - $connection->shouldReceive('release')->once(); + $connection = Double::for(PhpRedisConnection::class)->strict(); + $connection->allows('getConnection')->returns($connection); + $connection->allows('getEventDispatcher')->returns(null); + $connection->expects('shouldTransform') + ->with(false); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -1438,14 +1442,12 @@ public function testWithConnectionRespectsTransformFalse(): void public function testWithConnectionRespectsTransformTrueExplicit(): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getConnection')->andReturn($connection); - $connection->shouldReceive('getEventDispatcher')->andReturnNull(); - $connection->shouldReceive('shouldTransform') - ->once() - ->with(true) - ->andReturnSelf(); - $connection->shouldReceive('release')->once(); + $connection = Double::for(PhpRedisConnection::class)->strict(); + $connection->allows('getConnection')->returns($connection); + $connection->allows('getEventDispatcher')->returns(null); + $connection->expects('shouldTransform') + ->with(true); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -1456,18 +1458,15 @@ public function testWithConnectionRespectsTransformTrueExplicit(): void public function testWithConnectionAllowsMultipleOperationsOnSameConnection(): void { - $mockPhpRedis = m::mock(PhpRedis::class); - $mockPhpRedis->shouldReceive('evalSha') - ->once() + $connection = $this->mockConnection(); + $client = $connection->nativeClientForTest(); + $client->expects('evalSha') ->with('sha123', ['key'], 1) - ->andReturn(false); - $mockPhpRedis->shouldReceive('getLastError') - ->once() - ->andReturn('NOSCRIPT No matching script'); + ->returns(false); + $client->expects('getLastError') + ->returns('NOSCRIPT No matching script'); - $connection = $this->mockConnection(); - $connection->shouldReceive('client')->andReturn($mockPhpRedis); - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -1488,10 +1487,9 @@ public function testWithConnectionAllowsMultipleOperationsOnSameConnection(): vo public function testWithoutSerializationOrCompressionPinsConnectionAndDelegates(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('withoutSerializationOrCompression') - ->once() - ->andReturnUsing(fn (callable $callback) => $callback()); - $connection->shouldReceive('release')->once(); + $connection->expects('withoutSerializationOrCompression') + ->resolves(fn (callable $callback) => $callback()); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -1512,7 +1510,7 @@ public function testWithPinnedConnectionPreservesCallbackCancellationAndUnpinsBe $cancellation = new CanceledException('Callback canceled.'); $connection = $this->mockConnection(); $redis = $this->createRedis($connection); - $connection->expects('release')->andReturnUsing(function () use ($redis): void { + $connection->expects('release')->resolves(function () use ($redis): void { $this->assertFalse(CoroutineContext::has($this->contextKey($redis))); throw new RuntimeException('Cleanup failed.'); @@ -1535,11 +1533,10 @@ static function () use ($cancellation): never { public function testWithoutSerializationOrCompressionReusesExistingContextConnection(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('withoutSerializationOrCompression') - ->once() - ->andReturnUsing(fn (callable $callback) => $callback()); + $connection->expects('withoutSerializationOrCompression') + ->resolves(fn (callable $callback) => $callback()); // Should NOT release since connection was already in context - $connection->shouldReceive('release')->never(); + $connection->expects('release')->never(); $redis = $this->createRedis($connection); @@ -1561,12 +1558,11 @@ public function testWithoutSerializationOrCompressionReusesExistingContextConnec public function testWithoutSerializationOrCompressionCleansUpOnException(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('withoutSerializationOrCompression') - ->once() - ->andReturnUsing(function (callable $callback) { + $connection->expects('withoutSerializationOrCompression') + ->resolves(function (callable $callback) { return $callback(); }); - $connection->shouldReceive('release')->once(); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -1589,13 +1585,12 @@ public function testWithoutSerializationOrCompressionCleansUpOnException(): void public function testWithoutSerializationOrCompressionDoesNotReleaseContextConnectionOnException(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('withoutSerializationOrCompression') - ->once() - ->andReturnUsing(function (callable $callback) { + $connection->expects('withoutSerializationOrCompression') + ->resolves(function (callable $callback) { return $callback(); }); // Should NOT release since connection was already in context - $connection->shouldReceive('release')->never(); + $connection->expects('release')->never(); $redis = $this->createRedis($connection); @@ -1623,16 +1618,16 @@ public function testSubscriberUsesTheCompleteStandaloneConfiguration(): void $server->start(static function ($client): void { fread($client, 1); }); - $pool = m::mock(RedisPool::class); - $pool->expects('getConfig')->andReturn($this->standaloneConfig([ + $pool = Double::for(RedisPool::class)->strict(); + $pool->expects('getConfig')->returns($this->standaloneConfig([ 'host' => $server->endpoint(), 'port' => 6379, 'timeout' => 2.5, 'options' => ['prefix' => 'app:'], ])); - $pool->shouldNotReceive('borrow'); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->expects('pool')->with('default')->andReturn($pool); + $pool->expects('borrow')->never(); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->expects('pool')->with('default')->returns($pool); $subscriber = (new RedisProxy( $poolManager, 'default', @@ -1670,16 +1665,16 @@ public function testSubscriberResolvesSentinelMasterFreshWithConnectionCredentia 'timeout' => 1.0, 'options' => ['prefix' => 'sentinel:'], ]); - $pool = m::mock(RedisPool::class); - $pool->expects('getConfig')->twice()->andReturn($config); - $pool->shouldNotReceive('borrow'); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->expects('pool')->twice()->with('default')->andReturn($pool); - $sentinelFactory = m::mock(RedisSentinelFactory::class); + $pool = Double::for(RedisPool::class)->strict(); + $pool->expects('getConfig')->times(2)->returns($config); + $pool->expects('borrow')->never(); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->expects('pool')->times(2)->with('default')->returns($pool); + $sentinelFactory = Double::for(RedisSentinelFactory::class)->strict(); $sentinelFactory->expects('resolveMaster') - ->twice() + ->times(2) ->with($config) - ->andReturn([$firstHost, $firstPort], [$secondHost, $secondPort]); + ->returns([$firstHost, $firstPort], [$secondHost, $secondPort]); $proxy = new RedisProxy($poolManager, 'default', $sentinelFactory); $first = $proxy->subscriber(); $second = $proxy->subscriber(); @@ -1720,20 +1715,20 @@ public function testClusterSubscriberUsesConnectionTransportAndReleasesDiscovery 'timeout' => 0.1, 'options' => ['prefix' => 'cluster:'], ]); - $connection = m::mock(PhpRedisClusterConnection::class); - $connection->expects('getConnection')->andReturnSelf(); - $connection->expects('masters')->andReturn([ + $connection = Double::for(PhpRedisClusterConnection::class)->strict(); + $connection->expects('getConnection'); + $connection->expects('masters')->returns([ ['127.0.0.1', 1], [$host, $port], ]); - $connection->expects('release')->andReturnUsing(static function () use (&$released): void { + $connection->expects('release')->resolves(static function () use (&$released): void { $released = true; }); - $pool = m::mock(RedisPool::class); - $pool->expects('getConfig')->andReturn($config); - $pool->expects('borrow')->andReturn($connection); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->expects('pool')->with('default')->andReturn($pool); + $pool = Double::for(RedisPool::class)->strict(); + $pool->expects('getConfig')->returns($config); + $pool->expects('borrow')->returns($connection); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->expects('pool')->with('default')->returns($pool); $subscriber = (new RedisProxy( $poolManager, 'default', @@ -1786,17 +1781,17 @@ public function testClusterSubscriberUsesTlsConnectionTransportForMaster(): void ], 'timeout' => 0.1, ]); - $connection = m::mock(PhpRedisClusterConnection::class); - $connection->expects('getConnection')->andReturnSelf(); - $connection->expects('masters')->andReturn([[$host, $port]]); - $connection->expects('release')->andReturnUsing(static function () use (&$released): void { + $connection = Double::for(PhpRedisClusterConnection::class)->strict(); + $connection->expects('getConnection'); + $connection->expects('masters')->returns([[$host, $port]]); + $connection->expects('release')->resolves(static function () use (&$released): void { $released = true; }); - $pool = m::mock(RedisPool::class); - $pool->expects('getConfig')->andReturn($config); - $pool->expects('borrow')->andReturn($connection); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->expects('pool')->with('default')->andReturn($pool); + $pool = Double::for(RedisPool::class)->strict(); + $pool->expects('getConfig')->returns($config); + $pool->expects('borrow')->returns($connection); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->expects('pool')->with('default')->returns($pool); $subscriber = (new RedisProxy( $poolManager, 'default', @@ -1822,18 +1817,18 @@ public function testClusterSubscriberAggregatesEndpointFailures(): void ], 'timeout' => 0.01, ]); - $connection = m::mock(PhpRedisClusterConnection::class); - $connection->expects('getConnection')->andReturnSelf(); - $connection->expects('masters')->andReturn([ + $connection = Double::for(PhpRedisClusterConnection::class)->strict(); + $connection->expects('getConnection'); + $connection->expects('masters')->returns([ ['127.0.0.1', 1], ['127.0.0.1', 2], ]); $connection->expects('release'); - $pool = m::mock(RedisPool::class); - $pool->expects('getConfig')->andReturn($config); - $pool->expects('borrow')->andReturn($connection); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->expects('pool')->with('default')->andReturn($pool); + $pool = Double::for(RedisPool::class)->strict(); + $pool->expects('getConfig')->returns($config); + $pool->expects('borrow')->returns($connection); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->expects('pool')->with('default')->returns($pool); try { (new RedisProxy( @@ -1851,20 +1846,20 @@ public function testClusterSubscriberAggregatesEndpointFailures(): void public function testClusterDiscoveryFailureRemainsPrimaryOverReleaseFailure(): void { $discoveryException = new RuntimeException('Master discovery failed.'); - $connection = m::mock(PhpRedisClusterConnection::class); - $connection->expects('getConnection')->andReturnSelf(); - $connection->expects('masters')->andThrow($discoveryException); - $connection->expects('release')->andThrow(new RuntimeException('Release failed.')); - $pool = m::mock(RedisPool::class); - $pool->expects('getConfig')->andReturn([ + $connection = Double::for(PhpRedisClusterConnection::class)->strict(); + $connection->expects('getConnection'); + $connection->expects('masters')->throws($discoveryException); + $connection->expects('release')->throws(new RuntimeException('Release failed.')); + $pool = Double::for(RedisPool::class)->strict(); + $pool->expects('getConfig')->returns([ 'cluster' => [ 'enabled' => true, 'seeds' => ['tcp://127.0.0.1:6379'], ], ]); - $pool->expects('borrow')->andReturn($connection); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->expects('pool')->with('default')->andReturn($pool); + $pool->expects('borrow')->returns($connection); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->expects('pool')->with('default')->returns($pool); try { (new RedisProxy( @@ -1881,16 +1876,16 @@ public function testClusterDiscoveryFailureRemainsPrimaryOverReleaseFailure(): v public function testPinnedClusterDiscoveryFailureKeepsTheCallersConnection(): void { $failure = new RuntimeException('Master discovery failed.'); - $connection = m::mock(PhpRedisClusterConnection::class); - $connection->expects('shouldTransform')->with(true)->andReturnSelf(); - $connection->expects('getConnection')->twice()->andReturnSelf(); - $connection->expects('masters')->andThrow($failure); + $connection = Double::for(PhpRedisClusterConnection::class)->strict(); + $connection->expects('shouldTransform')->with(true); + $connection->expects('getConnection')->times(2); + $connection->expects('masters')->throws($failure); $connection->expects('release'); - $pool = m::mock(RedisPool::class); - $pool->expects('getConfig')->andReturn($this->clusterConfig()); - $pool->expects('borrow')->andReturn($connection); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->allows('pool')->with('default')->andReturn($pool); + $pool = Double::for(RedisPool::class)->strict(); + $pool->expects('getConfig')->returns($this->clusterConfig()); + $pool->expects('borrow')->returns($connection); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('default')->returns($pool); $redis = new RedisProxy($poolManager, 'default', $this->sentinelFactory()); $redis->withPinnedConnection(function () use ($redis, $failure, $connection): void { @@ -1911,20 +1906,20 @@ public function testPinnedClusterDiscoveryFailureKeepsTheCallersConnection(): vo public function testClusterDiscoveryNormalizesWrappedCancellationAndStillReleases(): void { $nativeFailure = new RedisClusterException('Master discovery canceled.'); - $connection = m::mock(PhpRedisClusterConnection::class); - $connection->expects('getConnection')->andReturnSelf(); - $connection->expects('masters')->andThrow($nativeFailure); - $connection->expects('release')->andThrow(new RuntimeException('Release failed.')); - $pool = m::mock(RedisPool::class); - $pool->expects('getConfig')->andReturn([ + $connection = Double::for(PhpRedisClusterConnection::class)->strict(); + $connection->expects('getConnection'); + $connection->expects('masters')->throws($nativeFailure); + $connection->expects('release')->throws(new RuntimeException('Release failed.')); + $pool = Double::for(RedisPool::class)->strict(); + $pool->expects('getConfig')->returns([ 'cluster' => [ 'enabled' => true, 'seeds' => ['tcp://127.0.0.1:6379'], ], ]); - $pool->expects('borrow')->andReturn($connection); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->expects('pool')->with('default')->andReturn($pool); + $pool->expects('borrow')->returns($connection); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->expects('pool')->with('default')->returns($pool); $redis = new RedisProxy($poolManager, 'default', $this->sentinelFactory()); $exception = $this->captureCancellationAtBoundary(function () use ($redis): void { @@ -1943,20 +1938,20 @@ public function testClusterDiscoveryReleaseCancellationSupersedesOrdinaryDiscove if ($wrapped) { $cancellation = new RuntimeException('Release cleanup failed.', previous: $cancellation); } - $connection = m::mock(PhpRedisClusterConnection::class); - $connection->expects('getConnection')->andReturnSelf(); - $connection->expects('masters')->andThrow(new RuntimeException('Master discovery failed.')); - $connection->expects('release')->andThrow($cancellation); - $pool = m::mock(RedisPool::class); - $pool->expects('getConfig')->andReturn([ + $connection = Double::for(PhpRedisClusterConnection::class)->strict(); + $connection->expects('getConnection'); + $connection->expects('masters')->throws(new RuntimeException('Master discovery failed.')); + $connection->expects('release')->throws($cancellation); + $pool = Double::for(RedisPool::class)->strict(); + $pool->expects('getConfig')->returns([ 'cluster' => [ 'enabled' => true, 'seeds' => ['tcp://127.0.0.1:6379'], ], ]); - $pool->expects('borrow')->andReturn($connection); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->expects('pool')->with('default')->andReturn($pool); + $pool->expects('borrow')->returns($connection); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->expects('pool')->with('default')->returns($pool); try { (new RedisProxy( @@ -1988,14 +1983,9 @@ public function testRedisClusterConstructorSignature(): void [$name, $type] = array_shift($names); $this->assertSame($name, $parameter->getName()); - if ($parameter->getName() === 'seeds') { - $this->assertSame('array', $parameter->getType()?->getName()); - continue; - } - if (is_array($type)) { foreach ($parameter->getType()?->getTypes() ?? [] as $namedType) { - $this->assertTrue(in_array($namedType->getName(), $type, true)); + $this->assertContains($namedType->getName(), $type); } continue; @@ -2003,6 +1993,8 @@ public function testRedisClusterConstructorSignature(): void $this->assertSame($type, $parameter->getType()?->getName()); } + + $this->assertSame([], $names); } public function testRedisSentinelConstructorSignature(): void @@ -2013,24 +2005,13 @@ public function testRedisSentinelConstructorSignature(): void $this->assertSame('options', $method->getParameters()[0]->getName()); } - public function testShuffleNodesMaintainsNodeCount(): void - { - $nodes = ['127.0.0.1:6379', '127.0.0.1:6378', '127.0.0.1:6377']; - - shuffle($nodes); - - $this->assertIsArray($nodes); - $this->assertSame(3, count($nodes)); - } - public function testFlushByPatternDelegatesToConnection(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('flushByPattern') - ->once() + $connection->expects('flushByPattern') ->with('cache:*') - ->andReturn(42); - $connection->shouldReceive('release')->once(); + ->returns(42); + $connection->expects('release'); $redis = $this->createRedis($connection); @@ -2041,15 +2022,15 @@ public function testFlushByPatternDelegatesToConnection(): void public function testIsClusterReturnsFalseForStandardConfig(): void { - $pool = m::mock(RedisPool::class); - $pool->shouldReceive('getConfig')->andReturn([ + $pool = Double::for(RedisPool::class)->strict(); + $pool->allows('getConfig')->returns([ 'host' => '127.0.0.1', 'port' => 6379, ]); - $pool->shouldReceive('borrow')->never(); + $pool->expects('borrow')->never(); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('pool')->with('default')->andReturn($pool); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('default')->returns($pool); $redis = new RedisProxy($poolManager, 'default', $this->sentinelFactory()); @@ -2058,14 +2039,14 @@ public function testIsClusterReturnsFalseForStandardConfig(): void public function testIsClusterReturnsTrueForClusterConfig(): void { - $pool = m::mock(RedisPool::class); - $pool->shouldReceive('getConfig')->andReturn([ + $pool = Double::for(RedisPool::class)->strict(); + $pool->allows('getConfig')->returns([ 'cluster' => ['enabled' => true, 'seeds' => ['tcp://127.0.0.1:6379']], ]); - $pool->shouldReceive('borrow')->never(); + $pool->expects('borrow')->never(); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('pool')->with('cache')->andReturn($pool); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('cache')->returns($pool); $proxy = new RedisProxy($poolManager, 'cache', $this->sentinelFactory()); @@ -2075,14 +2056,14 @@ public function testIsClusterReturnsTrueForClusterConfig(): void public function testProxyUsesSpecifiedPoolName(): void { $cacheConnection = $this->mockConnection(); - $cacheConnection->shouldReceive('get')->once()->with('key')->andReturn('cached'); - $cacheConnection->shouldReceive('release')->once(); + $cacheConnection->nativeClientForTest()->expects('get')->with('key')->returns('cached'); + $cacheConnection->expects('release'); - $cachePool = m::mock(RedisPool::class); - $cachePool->shouldReceive('borrow')->andReturn($cacheConnection); + $cachePool = Double::for(RedisPool::class)->strict(); + $cachePool->allows('borrow')->returns($cacheConnection); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('pool')->with('cache')->andReturn($cachePool); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('cache')->returns($cachePool); $proxy = new RedisProxy($poolManager, 'cache', $this->sentinelFactory()); @@ -2094,15 +2075,15 @@ public function testProxyUsesSpecifiedPoolName(): void public function testProxyContextKeyUsesPoolName(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn(m::mock(PhpRedis::class)); + $connection->nativeClientForTest()->expects('pipeline')->returns(Double::for(PhpRedis::class)->strict()); // Connection is released via defer() at end of coroutine - $connection->shouldReceive('release')->once(); + $connection->expects('release'); - $pool = m::mock(RedisPool::class); - $pool->shouldReceive('borrow')->andReturn($connection); + $pool = Double::for(RedisPool::class)->strict(); + $pool->allows('borrow')->returns($connection); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('pool')->with('cache')->andReturn($pool); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('cache')->returns($pool); $proxy = new RedisProxy($poolManager, 'cache', $this->sentinelFactory()); $defaultProxy = new RedisProxy($poolManager, 'default', $this->sentinelFactory()); @@ -2117,11 +2098,11 @@ public function testProxyContextKeyUsesPoolName(): void public function testSameNamedConnectionsOnDifferentPoolManagersKeepSeparatePins(): void { $firstConnection = $this->mockConnection(); - $firstConnection->expects('multi')->andReturn(m::mock(PhpRedis::class)); - $firstConnection->expects('get')->with('key')->andReturn('first'); + $firstConnection->nativeClientForTest()->expects('multi')->returns(Double::for(PhpRedis::class)->strict()); + $firstConnection->nativeClientForTest()->expects('get')->with('key')->returns('first'); $firstConnection->expects('release'); $secondConnection = $this->mockConnection(); - $secondConnection->expects('multi')->andReturn(m::mock(PhpRedis::class)); + $secondConnection->nativeClientForTest()->expects('multi')->returns(Double::for(PhpRedis::class)->strict()); $secondConnection->expects('discard'); $first = $this->createRedis($firstConnection); $second = $this->createRedis($secondConnection); @@ -2136,14 +2117,14 @@ public function testSameNamedConnectionsOnDifferentPoolManagersKeepSeparatePins( public function testProxiesForTheSamePoolManagerAndNameSharePins(): void { $connection = $this->mockConnection(); - $connection->expects('multi')->andReturn(m::mock(PhpRedis::class)); - $connection->expects('get')->with('key')->andReturn('value'); + $connection->nativeClientForTest()->expects('multi')->returns(Double::for(PhpRedis::class)->strict()); + $connection->nativeClientForTest()->expects('get')->with('key')->returns('value'); $connection->expects('release'); - $pool = m::mock(RedisPool::class); - $pool->expects('borrow')->andReturn($connection); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray([])); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('pool')->with('default')->andReturn($pool); + $pool = Double::for(RedisPool::class)->strict(); + $pool->expects('borrow')->returns($connection); + $pool->allows('getOptions')->returns(PoolOptions::fromArray([])); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('default')->returns($pool); $first = new RedisProxy($poolManager, 'default', $this->sentinelFactory()); $second = new RedisProxy($poolManager, 'default', $this->sentinelFactory()); @@ -2155,10 +2136,10 @@ public function testProxiesForTheSamePoolManagerAndNameSharePins(): void public function testDeferredCleanupReleasesEachPoolManagersPinnedConnection(): void { $firstConnection = $this->mockConnection(); - $firstConnection->expects('multi')->andReturn(m::mock(PhpRedis::class)); + $firstConnection->nativeClientForTest()->expects('multi')->returns(Double::for(PhpRedis::class)->strict()); $firstConnection->expects('release'); $secondConnection = $this->mockConnection(); - $secondConnection->expects('multi')->andReturn(m::mock(PhpRedis::class)); + $secondConnection->nativeClientForTest()->expects('multi')->returns(Double::for(PhpRedis::class)->strict()); $secondConnection->expects('release'); $first = $this->createRedis($firstConnection); $second = $this->createRedis($secondConnection); @@ -2174,29 +2155,27 @@ public function testDeferredCleanupReleasesEachPoolManagersPinnedConnection(): v } /** - * Create a mock RedisConnection with standard expectations. + * Create a real connection wrapper with a strict native client. */ - private function mockConnection(): m\MockInterface|RedisConnection + private function mockConnection(): PhpRedisConnectionStub&DoubleInterface { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getConnection')->andReturn($connection); - $connection->shouldReceive('getEventDispatcher')->andReturnNull(); - $connection->shouldReceive('shouldTransform')->andReturnSelf(); + $client = Double::for(PhpRedis::class)->strict(); + $client->allows('getMode')->returns(PhpRedis::ATOMIC); - return $connection; + return Double::for((new PhpRedisConnectionStub)->setActiveConnection($client))->passthru(); } /** * Create a RedisProxy instance with the given mock connection. */ - private function createRedis(m\MockInterface|RedisConnection $connection): RedisProxy + private function createRedis(RedisConnection&DoubleInterface $connection): RedisProxy { - $pool = m::mock(RedisPool::class); - $pool->shouldReceive('borrow')->andReturn($connection); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray([])); + $pool = Double::for(RedisPool::class)->strict(); + $pool->allows('borrow')->returns($connection); + $pool->allows('getOptions')->returns(PoolOptions::fromArray([])); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('pool')->with('default')->andReturn($pool); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('default')->returns($pool); return new RedisProxy($poolManager, 'default', $this->sentinelFactory()); } @@ -2214,10 +2193,13 @@ private function contextKey(RedisProxy $redis): string */ private function createRedisWithSubscriber(Subscriber $subscriber): RedisProxy { - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldNotReceive('pool'); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->expects('pool')->never(); return new class($poolManager, 'default', $this->sentinelFactory(), $subscriber) extends RedisProxy { + /** + * Create a proxy with the configured subscriber. + */ public function __construct( PoolManager $poolManager, string $name, @@ -2227,6 +2209,9 @@ public function __construct( parent::__construct($poolManager, $name, $sentinelFactory); } + /** + * Return the configured subscriber. + */ public function subscriber(): Subscriber { return $this->subscriber; @@ -2240,15 +2225,15 @@ public function subscriber(): Subscriber private function mockSubscriber( Channel $channel, ?Throwable $closeFailure = null, - ): Subscriber&m\MockInterface { - $subscriber = m::mock(Subscriber::class); + ): Subscriber&DoubleInterface { + $subscriber = Double::for(Subscriber::class)->strict(); $subscriber->closed = false; $subscriber->expects('subscribe')->with('updates'); - $subscriber->expects('channel')->andReturn($channel); + $subscriber->expects('channel')->returns($channel); $close = $subscriber->expects('close'); if ($closeFailure !== null) { - $close->andThrow($closeFailure); + $close->throws($closeFailure); } return $subscriber; @@ -2283,14 +2268,14 @@ private function captureCancellationAtBoundary(callable $callback): Throwable * Create a release-counting Redis proxy with the given mock connections. */ private function createCountingRedis( - m\MockInterface|RedisConnection ...$connections + RedisConnection&DoubleInterface ...$connections ): RedisProxyReleaseCountingStub { - $pool = m::mock(RedisPool::class); - $pool->shouldReceive('borrow')->andReturn(...$connections); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray([])); + $pool = Double::for(RedisPool::class)->strict(); + $pool->allows('borrow')->returns(...$connections); + $pool->allows('getOptions')->returns(PoolOptions::fromArray([])); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('pool')->with('default')->andReturn($pool); + $poolManager = Double::for(new PoolManager(new Container))->passthru(); + $poolManager->allows('pool')->with('default')->returns($pool); return new RedisProxyReleaseCountingStub( $poolManager, @@ -2307,30 +2292,20 @@ private function createMockRedisConnection( mixed $returnValue = 'value', ?Throwable $exception = null, ?Dispatcher $eventDispatcher = null - ): RedisConnection&m\MockInterface { - $mockPhpRedis = m::mock(PhpRedis::class); + ): PhpRedisConnectionStub&DoubleInterface { + $connection = $this->mockConnection(); + $expectation = $connection->nativeClientForTest()->allows($command); if ($exception !== null) { - $mockPhpRedis->shouldReceive($command) - ->andThrow($exception); + $expectation->throws($exception); } else { - $mockPhpRedis->shouldReceive($command) - ->andReturn($returnValue); + $expectation->returns($returnValue); } - $mockRedisConnection = m::mock(PhpRedisConnection::class); - $mockRedisConnection->shouldReceive('shouldTransform')->andReturnSelf(); - $mockRedisConnection->shouldReceive('getConnection')->andReturn($mockRedisConnection); - $mockRedisConnection->shouldReceive('getEventDispatcher')->andReturn($eventDispatcher); - $mockRedisConnection->shouldReceive('getName')->andReturn('default'); + $connection->allows('getEventDispatcher')->returns($eventDispatcher); + $connection->allows('getName')->returns('default'); - // Forward the command call to the mock PHP Redis - $mockRedisConnection->shouldReceive($command) - ->andReturnUsing(function (...$arguments) use ($mockPhpRedis, $command) { - return $mockPhpRedis->{$command}(...$arguments); - }); - - return $mockRedisConnection; + return $connection; } /** @@ -2420,7 +2395,7 @@ private function baseConnectionConfig(): array */ private function sentinelFactory(): RedisSentinelFactory { - return m::mock(RedisSentinelFactory::class); + return Double::for(RedisSentinelFactory::class)->strict(); } } @@ -2428,6 +2403,9 @@ class RedisProxyReleaseCountingStub extends RedisProxy { public int $contextAbsentReleaseCalls = 0; + /** + * Record cleanup calls made without a pinned connection. + */ public function releaseContextConnection(): void { $hasContextConnection = CoroutineContext::has($this->getContextKey()); diff --git a/tests/Redis/RedisSentinelFactoryTest.php b/tests/Redis/RedisSentinelFactoryTest.php index c9f695e6c5..145b5866f8 100644 --- a/tests/Redis/RedisSentinelFactoryTest.php +++ b/tests/Redis/RedisSentinelFactoryTest.php @@ -9,7 +9,8 @@ use Hypervel\Redis\RedisConfig; use Hypervel\Redis\RedisSentinelFactory; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RedisSentinel; use RuntimeException; @@ -17,26 +18,15 @@ class RedisSentinelFactoryTest extends TestCase { + use VerifiesDoubles; + public function testResolveMasterAcceptsDocumentedMinimalSentinelConfiguration(): void { - $sentinel = m::mock(RedisSentinel::class); + $sentinel = Double::for(RedisSentinel::class)->strict(); $sentinel->expects('getMasterAddrByName') ->with('primary') - ->andReturn(['10.0.0.1', 6380]); - $factory = new class($sentinel) extends RedisSentinelFactory { - public array $createdWith = []; - - public function __construct(private RedisSentinel $sentinel) - { - } - - public function create(array $options = []): RedisSentinel - { - $this->createdWith[] = $options; - - return $this->sentinel; - } - }; + ->returns(['10.0.0.1', 6380]); + $factory = new RedisSentinelFactoryFixture($sentinel); $config = (new RedisConfig(new Repository([ 'database' => [ 'redis' => [ @@ -66,28 +56,15 @@ public function create(array $options = []): RedisSentinel public function testResolveMasterFallsBackAcrossNodesAndUsesSentinelSettings(): void { - $first = m::mock(RedisSentinel::class); + $first = Double::for(RedisSentinel::class)->strict(); $first->expects('getMasterAddrByName') ->with('primary') - ->andThrow(new RuntimeException('Unavailable.')); - $second = m::mock(RedisSentinel::class); + ->throws(new RuntimeException('Unavailable.')); + $second = Double::for(RedisSentinel::class)->strict(); $second->expects('getMasterAddrByName') ->with('primary') - ->andReturn(['10.0.0.1', '6380']); - $factory = new class([$first, $second]) extends RedisSentinelFactory { - public array $createdWith = []; - - public function __construct(private array $sentinels) - { - } - - public function create(array $options = []): RedisSentinel - { - $this->createdWith[] = $options; - - return array_shift($this->sentinels); - } - }; + ->returns(['10.0.0.1', '6380']); + $factory = new RedisSentinelFactoryFixture($first, $second); $master = $factory->resolveMaster($this->sentinelConfig([ 'nodes' => ['tcp://127.0.0.1:26379', 'tcp://127.0.0.2:26380'], @@ -112,20 +89,11 @@ public function create(array $options = []): RedisSentinel public function testResolveMasterPreservesExactCancellation(): void { $cancellation = new CanceledException('sentinel canceled'); - $sentinel = m::mock(RedisSentinel::class); + $sentinel = Double::for(RedisSentinel::class)->strict(); $sentinel->expects('getMasterAddrByName') ->with('primary') - ->andThrow($cancellation); - $factory = new class($sentinel) extends RedisSentinelFactory { - public function __construct(private RedisSentinel $sentinel) - { - } - - public function create(array $options = []): RedisSentinel - { - return $this->sentinel; - } - }; + ->throws($cancellation); + $factory = new RedisSentinelFactoryFixture($sentinel); try { $factory->resolveMaster($this->sentinelConfig()); @@ -137,24 +105,11 @@ public function create(array $options = []): RedisSentinel public function testResolveMasterUsesSentinelPasswordWithoutUsername(): void { - $sentinel = m::mock(RedisSentinel::class); + $sentinel = Double::for(RedisSentinel::class)->strict(); $sentinel->expects('getMasterAddrByName') ->with('primary') - ->andReturn(['10.0.0.1', 6380]); - $factory = new class($sentinel) extends RedisSentinelFactory { - public array $createdWith = []; - - public function __construct(private RedisSentinel $sentinel) - { - } - - public function create(array $options = []): RedisSentinel - { - $this->createdWith[] = $options; - - return $this->sentinel; - } - }; + ->returns(['10.0.0.1', 6380]); + $factory = new RedisSentinelFactoryFixture($sentinel); $factory->resolveMaster($this->sentinelConfig([ 'password' => 'secret', @@ -166,24 +121,11 @@ public function create(array $options = []): RedisSentinel #[DataProvider('sentinelEndpoints')] public function testResolveMasterPreservesSentinelEndpoint(string $node, string $host): void { - $sentinel = m::mock(RedisSentinel::class); + $sentinel = Double::for(RedisSentinel::class)->strict(); $sentinel->expects('getMasterAddrByName') ->with('primary') - ->andReturn(['10.0.0.1', 6380]); - $factory = new class($sentinel) extends RedisSentinelFactory { - public array $createdWith = []; - - public function __construct(private RedisSentinel $sentinel) - { - } - - public function create(array $options = []): RedisSentinel - { - $this->createdWith[] = $options; - - return $this->sentinel; - } - }; + ->returns(['10.0.0.1', 6380]); + $factory = new RedisSentinelFactoryFixture($sentinel); $factory->resolveMaster($this->sentinelConfig([ 'nodes' => [$node], @@ -206,22 +148,9 @@ public static function sentinelEndpoints(): array #[DataProvider('sentinelContexts')] public function testResolveMasterNormalizesSentinelContext(array $context, ?array $expected): void { - $sentinel = m::mock(RedisSentinel::class); - $sentinel->expects('getMasterAddrByName')->andReturn(['10.0.0.1', 6380]); - $factory = new class($sentinel) extends RedisSentinelFactory { - public array $createdWith = []; - - public function __construct(private RedisSentinel $sentinel) - { - } - - public function create(array $options = []): RedisSentinel - { - $this->createdWith[] = $options; - - return $this->sentinel; - } - }; + $sentinel = Double::for(RedisSentinel::class)->strict(); + $sentinel->expects('getMasterAddrByName')->returns(['10.0.0.1', 6380]); + $factory = new RedisSentinelFactoryFixture($sentinel); $factory->resolveMaster($this->sentinelConfig([ 'context' => $context, @@ -293,20 +222,11 @@ public function testResolveMasterRejectsUnbracketedIpv6Nodes(): void public function testResolveMasterAggregatesEveryNodeFailure(): void { - $sentinel = m::mock(RedisSentinel::class); + $sentinel = Double::for(RedisSentinel::class)->strict(); $sentinel->expects('getMasterAddrByName') ->with('primary') - ->andThrow(new RuntimeException('Connection refused.')); - $factory = new class($sentinel) extends RedisSentinelFactory { - public function __construct(private RedisSentinel $sentinel) - { - } - - public function create(array $options = []): RedisSentinel - { - return $this->sentinel; - } - }; + ->throws(new RuntimeException('Connection refused.')); + $factory = new RedisSentinelFactoryFixture($sentinel); try { $factory->resolveMaster($this->sentinelConfig([ @@ -324,18 +244,9 @@ public function create(array $options = []): RedisSentinel public function testResolveMasterRejectsMalformedMasterResponse(): void { - $sentinel = m::mock(RedisSentinel::class); - $sentinel->expects('getMasterAddrByName')->andReturn(['', 'not-a-port']); - $factory = new class($sentinel) extends RedisSentinelFactory { - public function __construct(private RedisSentinel $sentinel) - { - } - - public function create(array $options = []): RedisSentinel - { - return $this->sentinel; - } - }; + $sentinel = Double::for(RedisSentinel::class)->strict(); + $sentinel->expects('getMasterAddrByName')->returns(['', 'not-a-port']); + $factory = new RedisSentinelFactoryFixture($sentinel); $this->expectException(InvalidRedisConnectionException::class); $this->expectExceptionMessageIsOrContains( @@ -364,3 +275,31 @@ private function sentinelConfig(array $overrides = []): array ]; } } + +class RedisSentinelFactoryFixture extends RedisSentinelFactory +{ + public array $createdWith = []; + + /** + * @var list + */ + private array $sentinels; + + /** + * Create a factory with configured Sentinel clients. + */ + public function __construct(RedisSentinel ...$sentinels) + { + $this->sentinels = $sentinels; + } + + /** + * Return the next configured Sentinel client. + */ + public function create(array $options = []): RedisSentinel + { + $this->createdWith[] = $options; + + return array_shift($this->sentinels); + } +} diff --git a/tests/Redis/Subscriber/CommandInvokerTest.php b/tests/Redis/Subscriber/CommandInvokerTest.php index d12675bf37..6290ba99d5 100644 --- a/tests/Redis/Subscriber/CommandInvokerTest.php +++ b/tests/Redis/Subscriber/CommandInvokerTest.php @@ -16,7 +16,9 @@ use Hypervel\Redis\Subscriber\Message; use Hypervel\Tests\Redis\Fixtures\RespServer; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionProperty; use RuntimeException; use stdClass; @@ -26,6 +28,8 @@ class CommandInvokerTest extends TestCase { + use VerifiesDoubles; + public function testInvokeSendsCommandAndCollectsDecodedResults(): void { $command = CommandBuilder::build(['subscribe', 'foo']); @@ -379,16 +383,14 @@ public function testZeroPingTimeoutWaitsWithoutPolling(): void public function testMessageCapacityFailureLogsOnceAndRemainsPrimaryWhenLoggingFails(): void { - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('error') - ->once() - ->andThrow(new RuntimeException('logger failed')); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('error')->throws(new RuntimeException('logger failed')); $connection = new ControlledConnection; $invoker = new CommandInvoker($connection, $logger); - $messageChannel = m::mock(Channel::class); - $messageChannel->shouldReceive('push')->once()->with(m::type(Message::class), 30.0)->andReturn(false); - $messageChannel->shouldReceive('isTimeout')->once()->andReturn(true); - $messageChannel->shouldReceive('close')->once()->andReturn(true); + $messageChannel = Double::for(Channel::class)->strict(); + $messageChannel->expects('push')->with(Argument::type(Message::class), 30.0)->returns(false); + $messageChannel->expects('isTimeout')->returns(true); + $messageChannel->expects('close')->returns(true); (new ReflectionProperty(CommandInvoker::class, 'messageChannel')) ->setValue($invoker, $messageChannel); $connection->pushResponse(['message', 'foo', 'payload']); @@ -405,8 +407,8 @@ public function testMessageCapacityFailureLogsOnceAndRemainsPrimaryWhenLoggingFa public function testConcurrentMessageChannelCloseIsTerminalWithoutLoggingCapacityFailure(): void { - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldNotReceive('error'); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('error')->never(); $connection = new ControlledConnection; $invoker = new CommandInvoker($connection, $logger); $messageChannel = $invoker->channel(); diff --git a/tests/Redis/Subscriber/SubscriberTest.php b/tests/Redis/Subscriber/SubscriberTest.php index ec67370127..701ae7151a 100644 --- a/tests/Redis/Subscriber/SubscriberTest.php +++ b/tests/Redis/Subscriber/SubscriberTest.php @@ -11,19 +11,21 @@ use Hypervel\Redis\Subscriber\Subscriber; use Hypervel\Tests\Redis\Fixtures\RespServer; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionClass; class SubscriberTest extends TestCase { + use VerifiesDoubles; + public function testSubscribeDelegatesToCommandInvoker(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('invoke') - ->once() + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('invoke') ->with(['subscribe', 'foo', 'bar'], 2) - ->andReturn([ + ->returns([ ['subscribe', 'foo', 1], ['subscribe', 'bar', 2], ]); @@ -34,11 +36,10 @@ public function testSubscribeDelegatesToCommandInvoker(): void public function testSubscribePrependsPrefix(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('invoke') - ->once() + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('invoke') ->with(['subscribe', 'app:foo', 'app:bar'], 2) - ->andReturn([ + ->returns([ ['subscribe', 'app:foo', 1], ['subscribe', 'app:bar', 2], ]); @@ -49,8 +50,8 @@ public function testSubscribePrependsPrefix(): void public function testSubscribeRejectsAnEmptyChannelListBeforeSending(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldNotReceive('invoke'); + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('invoke')->never(); $subscriber = $this->createSubscriber($invoker); @@ -62,11 +63,10 @@ public function testSubscribeRejectsAnEmptyChannelListBeforeSending(): void public function testUnsubscribeDelegatesToCommandInvoker(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('invoke') - ->once() + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('invoke') ->with(['unsubscribe', 'foo'], 1) - ->andReturn([['unsubscribe', 'foo', 0]]); + ->returns([['unsubscribe', 'foo', 0]]); $subscriber = $this->createSubscriber($invoker); $subscriber->unsubscribe('foo'); @@ -74,11 +74,10 @@ public function testUnsubscribeDelegatesToCommandInvoker(): void public function testUnsubscribePrependsPrefix(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('invoke') - ->once() + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('invoke') ->with(['unsubscribe', 'app:foo'], 1) - ->andReturn([['unsubscribe', 'app:foo', 0]]); + ->returns([['unsubscribe', 'app:foo', 0]]); $subscriber = $this->createSubscriber($invoker, prefix: 'app:'); $subscriber->unsubscribe('foo'); @@ -86,33 +85,28 @@ public function testUnsubscribePrependsPrefix(): void public function testUnsubscribeAllWaitsForEveryTrackedChannelAndKeepsPatternsSeparate(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('invoke') - ->once() + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('invoke') ->with(['subscribe', 'app:one', 'app:two'], 2) - ->andReturn([ + ->returns([ ['subscribe', 'app:one', 1], ['subscribe', 'app:two', 2], ]); - $invoker->shouldReceive('invoke') - ->once() + $invoker->expects('invoke') ->with(['psubscribe', 'app:events.*'], 1) - ->andReturn([['psubscribe', 'app:events.*', 3]]); - $invoker->shouldReceive('invoke') - ->once() + ->returns([['psubscribe', 'app:events.*', 3]]); + $invoker->expects('invoke') ->with(['unsubscribe'], 2) - ->andReturn([ + ->returns([ ['unsubscribe', 'app:one', 2], ['unsubscribe', 'app:two', 1], ]); - $invoker->shouldReceive('invoke') - ->once() + $invoker->expects('invoke') ->with(['unsubscribe'], 1) - ->andReturn([['unsubscribe', null, 1]]); - $invoker->shouldReceive('invoke') - ->once() + ->returns([['unsubscribe', null, 1]]); + $invoker->expects('invoke') ->with(['punsubscribe'], 1) - ->andReturn([['punsubscribe', 'app:events.*', 0]]); + ->returns([['punsubscribe', 'app:events.*', 0]]); $subscriber = $this->createSubscriber($invoker, prefix: 'app:'); $subscriber->subscribe('one', 'two'); @@ -124,22 +118,20 @@ public function testUnsubscribeAllWaitsForEveryTrackedChannelAndKeepsPatternsSep public function testAllUnsubscribeWithNoTrackedChannelsWaitsForOneAcknowledgement(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('invoke') - ->once() + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('invoke') ->with(['unsubscribe'], 1) - ->andReturn([['unsubscribe', null, 0]]); + ->returns([['unsubscribe', null, 0]]); $this->createSubscriber($invoker)->unsubscribe(); } public function testPsubscribeDelegatesToCommandInvoker(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('invoke') - ->once() + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('invoke') ->with(['psubscribe', 'foo.*', 'bar.*'], 2) - ->andReturn([ + ->returns([ ['psubscribe', 'foo.*', 1], ['psubscribe', 'bar.*', 2], ]); @@ -150,11 +142,10 @@ public function testPsubscribeDelegatesToCommandInvoker(): void public function testPsubscribePrependsPrefix(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('invoke') - ->once() + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('invoke') ->with(['psubscribe', 'app:events.*'], 1) - ->andReturn([['psubscribe', 'app:events.*', 1]]); + ->returns([['psubscribe', 'app:events.*', 1]]); $subscriber = $this->createSubscriber($invoker, prefix: 'app:'); $subscriber->psubscribe('events.*'); @@ -162,8 +153,8 @@ public function testPsubscribePrependsPrefix(): void public function testPsubscribeRejectsAnEmptyPatternListBeforeSending(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldNotReceive('invoke'); + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('invoke')->never(); $subscriber = $this->createSubscriber($invoker); @@ -175,11 +166,10 @@ public function testPsubscribeRejectsAnEmptyPatternListBeforeSending(): void public function testPunsubscribeDelegatesToCommandInvoker(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('invoke') - ->once() + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('invoke') ->with(['punsubscribe', 'foo.*'], 1) - ->andReturn([['punsubscribe', 'foo.*', 0]]); + ->returns([['punsubscribe', 'foo.*', 0]]); $subscriber = $this->createSubscriber($invoker); $subscriber->punsubscribe('foo.*'); @@ -187,11 +177,10 @@ public function testPunsubscribeDelegatesToCommandInvoker(): void public function testPunsubscribePrependsPrefix(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('invoke') - ->once() + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('invoke') ->with(['punsubscribe', 'app:foo.*'], 1) - ->andReturn([['punsubscribe', 'app:foo.*', 0]]); + ->returns([['punsubscribe', 'app:foo.*', 0]]); $subscriber = $this->createSubscriber($invoker, prefix: 'app:'); $subscriber->punsubscribe('foo.*'); @@ -199,11 +188,10 @@ public function testPunsubscribePrependsPrefix(): void public function testAllPunsubscribeWithNoTrackedPatternsWaitsForOneAcknowledgement(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('invoke') - ->once() + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('invoke') ->with(['punsubscribe'], 1) - ->andReturn([['punsubscribe', null, 0]]); + ->returns([['punsubscribe', null, 0]]); $this->createSubscriber($invoker)->punsubscribe(); } @@ -211,8 +199,8 @@ public function testAllPunsubscribeWithNoTrackedPatternsWaitsForOneAcknowledgeme public function testChannelDelegatesToCommandInvoker(): void { $channel = new Channel(1); - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('channel')->once()->andReturn($channel); + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('channel')->returns($channel); $subscriber = $this->createSubscriber($invoker); @@ -221,8 +209,8 @@ public function testChannelDelegatesToCommandInvoker(): void public function testCloseSetsClosedAndInterrupts(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('interrupt')->once()->andReturn(true); + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('interrupt')->returns(true); $subscriber = $this->createSubscriber($invoker); @@ -235,8 +223,8 @@ public function testCloseSetsClosedAndInterrupts(): void public function testPingDelegatesToCommandInvoker(): void { - $invoker = m::mock(CommandInvoker::class); - $invoker->shouldReceive('ping')->once()->with(2.5)->andReturn('pong'); + $invoker = Double::for(CommandInvoker::class)->strict(); + $invoker->expects('ping')->with(2.5)->returns('pong'); $subscriber = $this->createSubscriber($invoker); diff --git a/tests/Reverb/Console/Commands/ClearStateCommandTest.php b/tests/Reverb/Console/Commands/ClearStateCommandTest.php index ee565915c3..f669e42e99 100644 --- a/tests/Reverb/Console/Commands/ClearStateCommandTest.php +++ b/tests/Reverb/Console/Commands/ClearStateCommandTest.php @@ -10,27 +10,28 @@ use Hypervel\Redis\RedisProxy; use Hypervel\Reverb\Servers\Hypervel\Scaling\RedisSharedState; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; class ClearStateCommandTest extends ReverbTestCase { public function testDryRunCountsKeysWithoutConfirmationOrDeletion(): void { - $rawConnection = m::mock(RedisConnection::class); + $rawConnection = Double::for(RedisConnection::class)->strict(); $rawConnection->expects('safeScan') ->with(RedisSharedState::KEY_PATTERN) - ->andReturn((static function () { + ->returns((static function () { yield 'first'; yield 'second'; })()); - $connection = m::mock(RedisProxy::class); + $connection = Double::for(RedisProxy::class)->strict(); $connection->expects('withConnection') - ->withArgs(fn (callable $callback, bool $transform): bool => $transform === false) - ->andReturnUsing( + ->with(Argument::type('callable'), false) + ->resolves( fn (callable $callback, bool $transform): int => $callback($rawConnection), ); - $connection->shouldNotReceive('flushByPattern'); + $connection->expects('flushByPattern')->never(); $this->bindRedisConnection($connection); $this->artisan('reverb:clear-state', ['--dry-run' => true]) @@ -40,8 +41,8 @@ public function testDryRunCountsKeysWithoutConfirmationOrDeletion(): void public function testDestructiveRunCanBeCancelledInAnyEnvironment(): void { - $connection = m::mock(RedisProxy::class); - $connection->shouldNotReceive('flushByPattern'); + $connection = Double::for(RedisProxy::class)->strict(); + $connection->expects('flushByPattern')->never(); $this->bindRedisConnection($connection); $this->artisan('reverb:clear-state') @@ -52,10 +53,10 @@ public function testDestructiveRunCanBeCancelledInAnyEnvironment(): void public function testConfirmedDestructiveRunClearsSharedState(): void { - $connection = m::mock(RedisProxy::class); + $connection = Double::for(RedisProxy::class)->strict(); $connection->expects('flushByPattern') ->with(RedisSharedState::KEY_PATTERN) - ->andReturn(7); + ->returns(7); $this->bindRedisConnection($connection); $this->artisan('reverb:clear-state') @@ -66,10 +67,10 @@ public function testConfirmedDestructiveRunClearsSharedState(): void public function testForceSkipsConfirmation(): void { - $connection = m::mock(RedisProxy::class); + $connection = Double::for(RedisProxy::class)->strict(); $connection->expects('flushByPattern') ->with(RedisSharedState::KEY_PATTERN) - ->andReturn(7); + ->returns(7); $this->bindRedisConnection($connection); $this->artisan('reverb:clear-state', ['--force' => true]) @@ -77,12 +78,15 @@ public function testForceSkipsConfirmation(): void ->assertExitCode(HypervelCommand::SUCCESS); } + /** + * Bind the configured Redis connection for the command. + */ private function bindRedisConnection(RedisProxy $connection): void { config()->set('reverb.servers.reverb.scaling.connection', 'queue'); - $redis = m::mock(RedisFactory::class); - $redis->expects('connection')->with('queue')->andReturn($connection); + $redis = Double::for(RedisFactory::class)->strict(); + $redis->expects('connection')->with('queue')->returns($connection); $this->app->instance('redis', $redis); } diff --git a/tests/Reverb/EventDispatcherTest.php b/tests/Reverb/EventDispatcherTest.php index d87bc26a9c..432d1a9378 100644 --- a/tests/Reverb/EventDispatcherTest.php +++ b/tests/Reverb/EventDispatcherTest.php @@ -18,7 +18,8 @@ use Hypervel\Reverb\Servers\Hypervel\Contracts\SharedState; use Hypervel\Reverb\Webhooks\Jobs\WebhookDeliveryJob; use Hypervel\Support\Facades\Queue; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -31,8 +32,8 @@ public function testCanPublishAnEventWhenEnabled(): void $app = app(ApplicationProvider::class)->findByKey('reverb-key'); app(ServerProviderManager::class)->withPublishing(); - $pubSub = m::mock(PubSubProvider::class); - $pubSub->shouldReceive('publish')->once() + $pubSub = Double::for(PubSubProvider::class)->strict(); + $pubSub->expects('publish') ->with(['type' => 'message', 'app_id' => $app->id(), 'payload' => ['channel' => 'test-channel']]); $this->app->instance(PubSubProvider::class, $pubSub); @@ -44,7 +45,7 @@ public function testPublishedEventRetainsARemoteSocketId(): void { $app = app(ApplicationProvider::class)->findByKey('reverb-key'); app(ServerProviderManager::class)->withPublishing(); - $pubSub = m::mock(PubSubProvider::class); + $pubSub = Double::for(PubSubProvider::class)->strict(); $pubSub->expects('publish')->with([ 'type' => 'message', 'app_id' => $app->id(), @@ -63,15 +64,15 @@ public function testPublishedEventRetainsARemoteSocketId(): void public function testPipeFanOutRetainsARemoteSocketId(): void { $app = app(ApplicationProvider::class)->findByKey('reverb-key'); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $server->setting = ['worker_num' => 2]; $server->worker_id = 0; $server->expects('sendMessage') ->with( - m::on(fn (ChannelBroadcastPipeMessage $message): bool => $message->exceptSocketId === 'remote-socket'), + Argument::satisfies(fn (ChannelBroadcastPipeMessage $message): bool => $message->exceptSocketId === 'remote-socket'), 1, ) - ->andReturnTrue(); + ->returns(true); $this->app->instance(Server::class, $server); EventDispatcher::dispatch( @@ -84,13 +85,13 @@ public function testPipeFanOutRetainsARemoteSocketId(): void public function testPipeFanOutAttemptsEveryWorkerAndPreservesTheFirstFailure(): void { $app = app(ApplicationProvider::class)->findByKey('reverb-key'); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $server->setting = ['worker_num' => 4]; $server->worker_id = 1; $workerIds = []; $server->expects('sendMessage') ->times(3) - ->andReturnUsing(function (ChannelBroadcastPipeMessage $message, int $workerId) use (&$workerIds): bool { + ->resolves(function (ChannelBroadcastPipeMessage $message, int $workerId) use (&$workerIds): bool { $workerIds[] = $workerId; return match ($workerId) { @@ -113,11 +114,11 @@ public function testPipeFanOutAttemptsEveryWorkerAndPreservesTheFirstFailure(): public function testCanBroadcastAnEventDirectlyWhenPublishingDisabled(): void { - $channelConnectionManager = m::mock(ChannelConnectionManager::class); - $channelConnectionManager->shouldReceive('for') - ->andReturn($channelConnectionManager); - $channelConnectionManager->shouldReceive('all')->once() - ->andReturn([]); + $channelConnectionManager = Double::for(ChannelConnectionManager::class)->strict(); + $channelConnectionManager->allows('for') + ->returns($channelConnectionManager); + $channelConnectionManager->expects('all') + ->returns([]); $this->app->bind(ChannelConnectionManager::class, fn () => $channelConnectionManager); @@ -128,11 +129,11 @@ public function testCanBroadcastAnEventDirectlyWhenPublishingDisabled(): void public function testCanBroadcastAnEventForMultipleChannels(): void { - $channelConnectionManager = m::mock(ChannelConnectionManager::class); - $channelConnectionManager->shouldReceive('for') - ->andReturn($channelConnectionManager); - $channelConnectionManager->shouldReceive('all')->twice() - ->andReturn([]); + $channelConnectionManager = Double::for(ChannelConnectionManager::class)->strict(); + $channelConnectionManager->allows('for') + ->returns($channelConnectionManager); + $channelConnectionManager->expects('all')->times(2) + ->returns([]); $this->app->bind(ChannelConnectionManager::class, fn () => $channelConnectionManager); @@ -147,19 +148,19 @@ public function testCanceledDispatchStopsBeforeLaterChannelsAndWorkers(string $m { $app = app(ApplicationProvider::class)->findByKey('reverb-key'); $cancellation = new CanceledException; - $channel = m::mock(Channel::class); - $channel->allows('name')->andReturn('first'); - $channel->expects($broadcast)->andThrow($cancellation); - $channels = m::mock(ScopedChannelManager::class); - $channels->expects('find')->with('first')->andReturn($channel); - $channels->shouldNotReceive('find')->with('later'); - $manager = m::mock(ChannelManager::class); - $manager->expects('for')->with($app)->andReturn($channels); + $channel = Double::for(Channel::class)->strict(); + $channel->allows('name')->returns('first'); + $channel->expects($broadcast)->throws($cancellation); + $channels = Double::for(ScopedChannelManager::class)->strict(); + $channels->expects('find')->with('first')->returns($channel); + $channels->expects('find')->never()->with('later'); + $manager = Double::for(ChannelManager::class)->strict(); + $manager->expects('for')->with($app)->returns($channels); $this->app->instance(ChannelManager::class, $manager); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $server->setting = ['worker_num' => 2]; $server->worker_id = 0; - $server->shouldNotReceive('sendMessage'); + $server->expects('sendMessage')->never(); $this->app->instance(Server::class, $server); $caught = null; @@ -188,24 +189,24 @@ public function testInternalChannelCancellationIsNotReported(bool $publish): voi { $app = app(ApplicationProvider::class)->findByKey('reverb-key'); $cancellation = new CanceledException; - $channel = m::mock(Channel::class); - $channel->allows('name')->andReturn('presence-test'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $channel = Double::for(Channel::class)->strict(); + $channel->allows('name')->returns('presence-test'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); $this->app->instance(ExceptionHandler::class, $handler); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $server->setting = ['worker_num' => 2]; $server->worker_id = 0; - $server->shouldNotReceive('sendMessage'); + $server->expects('sendMessage')->never(); $this->app->instance(Server::class, $server); if ($publish) { app(ServerProviderManager::class)->withPublishing(); - $provider = m::mock(PubSubProvider::class); - $provider->expects('publish')->andThrow($cancellation); + $provider = Double::for(PubSubProvider::class)->strict(); + $provider->expects('publish')->throws($cancellation); $this->app->instance(PubSubProvider::class, $provider); } else { - $channel->expects('broadcastInternally')->andThrow($cancellation); + $channel->expects('broadcastInternally')->throws($cancellation); } $caught = null; @@ -231,27 +232,27 @@ public function testSynchronousDispatchAttemptsEveryChannelAndFanOutBeforeThrowi { $app = app(ApplicationProvider::class)->findByKey('reverb-key'); $failure = new RuntimeException('cache lock failed'); - $cacheChannel = m::mock(CacheChannel::class); - $cacheChannel->allows('name')->andReturn('cache-first'); - $cacheChannel->expects('broadcast')->once(); - $laterChannel = m::mock(Channel::class); - $laterChannel->allows('name')->andReturn('later'); - $laterChannel->expects('broadcast')->once(); - $channels = m::mock(ScopedChannelManager::class); - $channels->expects('find')->with('cache-first')->andReturn($cacheChannel); - $channels->expects('find')->with('later')->andReturn($laterChannel); - $manager = m::mock(ChannelManager::class); - $manager->expects('for')->twice()->with($app)->andReturn($channels); + $cacheChannel = Double::for(CacheChannel::class)->strict(); + $cacheChannel->allows('name')->returns('cache-first'); + $cacheChannel->expects('broadcast'); + $laterChannel = Double::for(Channel::class)->strict(); + $laterChannel->allows('name')->returns('later'); + $laterChannel->expects('broadcast'); + $channels = Double::for(ScopedChannelManager::class)->strict(); + $channels->expects('find')->with('cache-first')->returns($cacheChannel); + $channels->expects('find')->with('later')->returns($laterChannel); + $manager = Double::for(ChannelManager::class)->strict(); + $manager->expects('for')->times(2)->with($app)->returns($channels); $this->app->instance(ChannelManager::class, $manager); - $sharedState = m::mock(SharedState::class); + $sharedState = Double::for(SharedState::class)->strict(); $sharedState->expects('clearCacheMissLock') ->with($app->id(), 'cache-first') - ->andThrow($failure); + ->throws($failure); $this->app->instance(SharedState::class, $sharedState); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $server->setting = ['worker_num' => 2]; $server->worker_id = 0; - $server->expects('sendMessage')->once()->andReturnTrue(); + $server->expects('sendMessage')->returns(true); $this->app->instance(Server::class, $server); try { diff --git a/tests/Reverb/Jobs/PruneStaleConnectionsTest.php b/tests/Reverb/Jobs/PruneStaleConnectionsTest.php index 027ead52d9..f80df923f2 100644 --- a/tests/Reverb/Jobs/PruneStaleConnectionsTest.php +++ b/tests/Reverb/Jobs/PruneStaleConnectionsTest.php @@ -10,7 +10,7 @@ use Hypervel\Reverb\Servers\Hypervel\ConnectionLifecycle; use Hypervel\Reverb\Servers\Hypervel\WebSocketHandler; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; use ReflectionProperty; class PruneStaleConnectionsTest extends ReverbTestCase @@ -38,7 +38,7 @@ public function testDoesNotCallUnsubscribeFromAllDirectly(): void { $connections = static::factory(1); - $channelManager = m::spy(ChannelManager::class); + $channelManager = Double::for(ChannelManager::class)->strict(); $this->app->singleton(ChannelManager::class, fn () => $channelManager); collect($connections)->each(function ($connection): void { @@ -54,7 +54,7 @@ public function testDoesNotCallUnsubscribeFromAllDirectly(): void // It should only disconnect the connection, and the onClose → Server::close() // path handles the unsubscribe. Calling it directly causes double-unsubscribe // which decrements SharedState counters twice. - $channelManager->shouldNotHaveReceived('for'); + $channelManager->received('for')->never(); } public function testDispatchesConnectionPrunedWithTheStaleConnection(): void diff --git a/tests/Reverb/Protocols/Pusher/Channels/ChannelTest.php b/tests/Reverb/Protocols/Pusher/Channels/ChannelTest.php index 6a0a2a75a8..8c4a7c16d2 100644 --- a/tests/Reverb/Protocols/Pusher/Channels/ChannelTest.php +++ b/tests/Reverb/Protocols/Pusher/Channels/ChannelTest.php @@ -25,7 +25,7 @@ use Hypervel\Support\Facades\Queue; use Hypervel\Tests\Reverb\Fixtures\FakeConnection; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; use RuntimeException; use Swoole\Coroutine\Channel as CoroutineChannel; @@ -37,6 +37,9 @@ class ChannelTest extends ReverbTestCase protected ChannelConnectionManager $channelConnectionManager; + /** + * Set up the test environment. + */ protected function setUp(): void { parent::setUp(); @@ -67,9 +70,10 @@ public function testCanUnsubscribeAConnectionFromAChannel(): void public function testRemovesAChannelWhenNoSubscribersRemain(): void { - $scopedManager = m::spy(ScopedChannelManager::class); - $channelManager = m::mock(ChannelManager::class); - $channelManager->shouldReceive('for')->andReturn($scopedManager); + $scopedManager = Double::for(ScopedChannelManager::class)->strict(); + $scopedManager->allows('remove'); + $channelManager = Double::for(ChannelManager::class)->strict(); + $channelManager->allows('for')->returns($scopedManager); $this->app->singleton(ChannelManager::class, fn () => $channelManager); $channel = new Channel('test-channel'); @@ -77,18 +81,16 @@ public function testRemovesAChannelWhenNoSubscribersRemain(): void $channel->subscribe($this->connection); $channel->unsubscribe($this->connection); - $scopedManager->shouldHaveReceived('remove') - ->once() + $scopedManager->received('remove')->times(1) ->with($channel); } public function testDuplicateSubscribeAndNonmemberUnsubscribeDoNotPublishSharedState(): void { - $sharedState = m::mock(SharedState::class); - $sharedState->shouldReceive('subscribe') - ->once() - ->andReturn(new SubscriptionResult(false, false, false, false, 1)); - $sharedState->shouldNotReceive('unsubscribe'); + $sharedState = Double::for(SharedState::class)->strict(); + $sharedState->expects('subscribe') + ->returns(new SubscriptionResult(false, false, false, false, 1)); + $sharedState->expects('unsubscribe')->never(); $this->app->instance(SharedState::class, $sharedState); $channel = new Channel('test-channel'); @@ -104,8 +106,8 @@ public function testDuplicateSubscribeAndNonmemberUnsubscribeDoNotPublishSharedS public function testSharedSubscribeFailureDoesNotPublishLocalMembership(): void { - $sharedState = m::mock(SharedState::class); - $sharedState->shouldReceive('subscribe')->once()->andThrow(new RuntimeException('subscribe failed')); + $sharedState = Double::for(SharedState::class)->strict(); + $sharedState->expects('subscribe')->throws(new RuntimeException('subscribe failed')); $this->app->instance(SharedState::class, $sharedState); $channel = $this->channels()->findOrCreate('test-channel'); @@ -125,8 +127,8 @@ public function testSharedUnsubscribeFailureRetainsLocalMembership(): void $channel = $this->channels()->findOrCreate('test-channel'); $channel->subscribe($this->connection); - $sharedState = m::mock(SharedState::class); - $sharedState->shouldReceive('unsubscribe')->once()->andThrow(new RuntimeException('unsubscribe failed')); + $sharedState = Double::for(SharedState::class)->strict(); + $sharedState->expects('unsubscribe')->throws(new RuntimeException('unsubscribe failed')); $this->app->instance(SharedState::class, $sharedState); $this->expectException(RuntimeException::class); @@ -148,18 +150,16 @@ public function testPendingJoinKeepsAnOtherwiseEmptyChannelDiscoverable(): void $joinStarted = new CoroutineChannel(1); $releaseJoin = new CoroutineChannel(1); $joinFinished = new CoroutineChannel(1); - $sharedState = m::mock(SharedState::class); - $sharedState->shouldReceive('subscribe') - ->once() - ->andReturnUsing(function () use ($joinStarted, $releaseJoin): SubscriptionResult { + $sharedState = Double::for(SharedState::class)->strict(); + $sharedState->expects('subscribe') + ->resolves(function () use ($joinStarted, $releaseJoin): SubscriptionResult { $joinStarted->push(true); $releaseJoin->pop(); return new SubscriptionResult(false, false, false, false, 1); }); - $sharedState->shouldReceive('unsubscribe') - ->once() - ->andReturn(new SubscriptionResult(false, false, false, false, 0)); + $sharedState->expects('unsubscribe') + ->returns(new SubscriptionResult(false, false, false, false, 0)); $this->app->instance(SharedState::class, $sharedState); go(function () use ($channel, $joiningConnection, $joinFinished): void { @@ -186,10 +186,9 @@ public function testFailedPendingJoinReclaimsTheIdleChannel(): void $joinStarted = new CoroutineChannel(1); $releaseJoin = new CoroutineChannel(1); $joinFailed = new CoroutineChannel(1); - $sharedState = m::mock(SharedState::class); - $sharedState->shouldReceive('subscribe') - ->once() - ->andReturnUsing(function () use ($joinStarted, $releaseJoin): never { + $sharedState = Double::for(SharedState::class)->strict(); + $sharedState->expects('subscribe') + ->resolves(function () use ($joinStarted, $releaseJoin): never { $joinStarted->push(true); $releaseJoin->pop(); @@ -232,15 +231,15 @@ public function testCanBroadcastToAllConnectionsOfAChannel(): void public function testTimedOutSendListenerStopsDeliveryToLaterConnections(): void { $app = $this->app->make(ApplicationProvider::class)->findByKey('reverb-key'); - $transport = m::mock(WebSocketConnection::class); - $transport->shouldReceive('id')->andReturn(42); + $transport = Double::for(WebSocketConnection::class)->strict(); + $transport->allows('id')->returns(42); $transport->expects('send')->with('{"foo":"bar"}'); $first = new Connection($transport, $app, null); $second = new FakeConnection; $this->channelConnectionManager->add($first, []); $this->channelConnectionManager->add($second, []); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); $this->app->instance(ExceptionHandler::class, $handler); $this->app->make('events')->listen(MessageSent::class, static function (): void { Coroutine::sleep(1); @@ -265,11 +264,17 @@ public function testBroadcastAttemptsEveryConnectionAndReportsTheFirstFailure(): $failingConnection = static fn (RuntimeException $failure): FakeConnection => new class($failure) extends FakeConnection { public bool $attempted = false; + /** + * Create a connection with a configured send failure. + */ public function __construct(private RuntimeException $failure) { parent::__construct(); } + /** + * Record the send attempt and throw its configured failure. + */ public function send(string $message): void { $this->attempted = true; @@ -281,8 +286,8 @@ public function send(string $message): void $middle = new FakeConnection; $second = $failingConnection($secondFailure); $last = new FakeConnection; - $handler = m::mock(ExceptionHandler::class); - $handler->expects('report')->once()->with($firstFailure); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($firstFailure); $this->app->instance(ExceptionHandler::class, $handler); foreach ([$first, $middle, $second, $last] as $connection) { @@ -611,19 +616,19 @@ public function testSubscriptionCountThrottledAbove100Subscribers(): void ])); // Mock SharedState to return count >100 and lock already held - $sharedState = m::mock(SharedState::class); - $sharedState->shouldReceive('subscribe') - ->andReturn(new SubscriptionResult( + $sharedState = Double::for(SharedState::class)->strict(); + $sharedState->allows('subscribe') + ->returns(new SubscriptionResult( channelOccupied: true, channelVacated: false, memberAdded: false, memberRemoved: false, subscriptionCount: 150, )); - $sharedState->shouldReceive('trySubscriptionCountLock') + $sharedState->allows('trySubscriptionCountLock') ->with('123456', 'test-channel') - ->andReturn(false); - $sharedState->shouldReceive('clearSmoothingPending')->andReturn(false); + ->returns(false); + $sharedState->allows('clearSmoothingPending')->returns(false); $this->app->instance(SharedState::class, $sharedState); $channel = new Channel('test-channel'); @@ -646,19 +651,19 @@ public function testSubscriptionCountFiresAbove100WhenLockAcquired(): void ])); // Mock SharedState to return count >100 and lock acquired - $sharedState = m::mock(SharedState::class); - $sharedState->shouldReceive('subscribe') - ->andReturn(new SubscriptionResult( + $sharedState = Double::for(SharedState::class)->strict(); + $sharedState->allows('subscribe') + ->returns(new SubscriptionResult( channelOccupied: true, channelVacated: false, memberAdded: false, memberRemoved: false, subscriptionCount: 150, )); - $sharedState->shouldReceive('trySubscriptionCountLock') + $sharedState->allows('trySubscriptionCountLock') ->with('123456', 'test-channel') - ->andReturn(true); - $sharedState->shouldReceive('clearSmoothingPending')->andReturn(false); + ->returns(true); + $sharedState->allows('clearSmoothingPending')->returns(false); $this->app->instance(SharedState::class, $sharedState); $channel = new Channel('test-channel'); diff --git a/tests/Reverb/Protocols/Pusher/Channels/PresenceCacheChannelTest.php b/tests/Reverb/Protocols/Pusher/Channels/PresenceCacheChannelTest.php index 95f34709ca..f5695550e7 100644 --- a/tests/Reverb/Protocols/Pusher/Channels/PresenceCacheChannelTest.php +++ b/tests/Reverb/Protocols/Pusher/Channels/PresenceCacheChannelTest.php @@ -12,7 +12,7 @@ use Hypervel\Reverb\Protocols\Pusher\Managers\ArrayChannelConnectionManager; use Hypervel\Tests\Reverb\Fixtures\FakeConnection; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; class PresenceCacheChannelTest extends ReverbTestCase { @@ -20,12 +20,15 @@ class PresenceCacheChannelTest extends ReverbTestCase protected ChannelConnectionManager $channelConnectionManager; + /** + * Set up the test environment. + */ protected function setUp(): void { parent::setUp(); $this->connection = new FakeConnection; - $this->channelConnectionManager = m::mock(ArrayChannelConnectionManager::class)->makePartial(); + $this->channelConnectionManager = Double::for(new ArrayChannelConnectionManager)->passthru(); $this->app->bind(ChannelConnectionManager::class, fn () => $this->channelConnectionManager); } @@ -52,9 +55,8 @@ public function testCanBroadcastToAllConnectionsOfAChannel(): void { $channel = new PresenceCacheChannel('presence-cache-test-channel'); - $this->channelConnectionManager->shouldReceive('all') - ->once() - ->andReturn($connections = static::factory(3)); + $this->channelConnectionManager->expects('all') + ->returns($connections = static::factory(3)); $channel->broadcast(['foo' => 'bar']); @@ -83,9 +85,9 @@ public function testCanReturnDataStoredOnTheConnection(): void collect(static::factory(data: ['user_info' => ['name' => 'Joe'], 'user_id' => 2]))->first(), ]; - $this->channelConnectionManager->shouldReceive('all') - ->twice() - ->andReturn($connections); + $this->channelConnectionManager->expects('all') + ->times(2) + ->returns($connections); $this->assertSame([ 'presence' => [ @@ -103,12 +105,11 @@ public function testSendsNotificationOfSubscription(): void { $channel = $this->channels()->findOrCreate('presence-cache-test-channel'); - $this->channelConnectionManager->shouldReceive('add') - ->once() + $this->channelConnectionManager->expects('add') ->with($this->connection, []); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn($connections = static::factory(3)); + $this->channelConnectionManager->allows('all') + ->returns($connections = static::factory(3)); $channel->subscribe($this->connection, static::validAuth($this->connection->id(), 'presence-cache-test-channel')); @@ -124,12 +125,11 @@ public function testSendsNotificationOfSubscriptionWithData(): void $channel = $this->channels()->findOrCreate('presence-cache-test-channel'); $data = json_encode(['name' => 'Joe']); - $this->channelConnectionManager->shouldReceive('add') - ->once() + $this->channelConnectionManager->expects('add') ->with($this->connection, ['name' => 'Joe']); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn($connections = static::factory(3)); + $this->channelConnectionManager->allows('all') + ->returns($connections = static::factory(3)); $channel->subscribe( $this->connection, @@ -155,14 +155,13 @@ public function testSendsNotificationOfAnUnsubscribe(): void $data ); - $this->channelConnectionManager->shouldReceive('find') - ->andReturn(new ChannelConnection($this->connection, ['user_info' => ['name' => 'Joe'], 'user_id' => 1])); + $this->channelConnectionManager->allows('find') + ->returns(new ChannelConnection($this->connection, ['user_info' => ['name' => 'Joe'], 'user_id' => 1])); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn($connections = static::factory(3)); + $this->channelConnectionManager->allows('all') + ->returns($connections = static::factory(3)); - $this->channelConnectionManager->shouldReceive('remove') - ->once() + $this->channelConnectionManager->expects('remove') ->with($this->connection); $channel->unsubscribe($this->connection); @@ -178,8 +177,7 @@ public function testReceivesNoDataWhenNoPreviousEventTriggered(): void { $channel = $this->channels()->findOrCreate('presence-cache-test-channel'); - $this->channelConnectionManager->shouldReceive('add') - ->once() + $this->channelConnectionManager->expects('add') ->with($this->connection, []); $channel->subscribe($this->connection, static::validAuth($this->connection->id(), 'presence-cache-test-channel')); @@ -204,7 +202,7 @@ public function testDoesNotCacheInternalEventsOnAPresenceCacheChannel(): void $channel = $this->channels()->findOrCreate('presence-cache-test-channel'); $data = json_encode(['user_info' => ['name' => 'Joe'], 'user_id' => 1]); - $this->channelConnectionManager->shouldReceive('all')->andReturn([]); + $this->channelConnectionManager->allows('all')->returns([]); $channel->subscribe( $this->connection, @@ -224,8 +222,8 @@ public function testDoesNotCacheInternalEventsOnAPresenceCacheChannel(): void $this->assertFalse($channel->hasCachedPayload()); - $this->channelConnectionManager->shouldReceive('find') - ->andReturn(new ChannelConnection($this->connection, ['user_info' => ['name' => 'Joe'], 'user_id' => 1])); + $this->channelConnectionManager->allows('find') + ->returns(new ChannelConnection($this->connection, ['user_info' => ['name' => 'Joe'], 'user_id' => 1])); $channel->unsubscribe($this->connection); diff --git a/tests/Reverb/Protocols/Pusher/Channels/PresenceChannelTest.php b/tests/Reverb/Protocols/Pusher/Channels/PresenceChannelTest.php index 5ff89f4b4b..cce41e3d40 100644 --- a/tests/Reverb/Protocols/Pusher/Channels/PresenceChannelTest.php +++ b/tests/Reverb/Protocols/Pusher/Channels/PresenceChannelTest.php @@ -14,7 +14,7 @@ use Hypervel\Support\Facades\Queue; use Hypervel\Tests\Reverb\Fixtures\FakeConnection; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; class PresenceChannelTest extends ReverbTestCase { @@ -22,12 +22,15 @@ class PresenceChannelTest extends ReverbTestCase protected ChannelConnectionManager $channelConnectionManager; + /** + * Set up the test environment. + */ protected function setUp(): void { parent::setUp(); $this->connection = new FakeConnection; - $this->channelConnectionManager = m::mock(ArrayChannelConnectionManager::class)->makePartial(); + $this->channelConnectionManager = Double::for(new ArrayChannelConnectionManager)->passthru(); $this->app->bind(ChannelConnectionManager::class, fn () => $this->channelConnectionManager); } @@ -54,9 +57,8 @@ public function testCanBroadcastToAllConnectionsOfAChannel(): void { $channel = new PresenceChannel('presence-test-channel'); - $this->channelConnectionManager->shouldReceive('all') - ->once() - ->andReturn($connections = static::factory(3)); + $this->channelConnectionManager->expects('all') + ->returns($connections = static::factory(3)); $channel->broadcast(['foo' => 'bar']); @@ -85,9 +87,9 @@ public function testCanReturnDataStoredOnTheConnection(): void collect(static::factory(data: ['user_info' => ['name' => 'Joe'], 'user_id' => 2]))->first(), ]; - $this->channelConnectionManager->shouldReceive('all') - ->twice() - ->andReturn($connections); + $this->channelConnectionManager->expects('all') + ->times(2) + ->returns($connections); $this->assertSame([ 'presence' => [ @@ -111,9 +113,9 @@ public function testCanReturnDataForAConnectionWithoutUserInfo(): void collect(static::factory(data: ['user_id' => 2, 'user_info' => []]))->first(), ]; - $this->channelConnectionManager->shouldReceive('all') - ->twice() - ->andReturn($connections); + $this->channelConnectionManager->expects('all') + ->times(2) + ->returns($connections); $this->assertSame( '{"presence":{"count":2,"ids":[1,2],"hash":{"1":{},"2":{}}}}', @@ -125,12 +127,11 @@ public function testSendsNotificationOfSubscription(): void { $channel = $this->channels()->findOrCreate('presence-test-channel'); - $this->channelConnectionManager->shouldReceive('add') - ->once() + $this->channelConnectionManager->expects('add') ->with($this->connection, []); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn($connections = static::factory(3)); + $this->channelConnectionManager->allows('all') + ->returns($connections = static::factory(3)); $channel->subscribe($this->connection, static::validAuth($this->connection->id(), 'presence-test-channel')); @@ -146,12 +147,11 @@ public function testSendsNotificationOfSubscriptionWithData(): void $channel = $this->channels()->findOrCreate('presence-test-channel'); $data = json_encode(['name' => 'Joe']); - $this->channelConnectionManager->shouldReceive('add') - ->once() + $this->channelConnectionManager->expects('add') ->with($this->connection, ['name' => 'Joe']); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn($connections = static::factory(3)); + $this->channelConnectionManager->allows('all') + ->returns($connections = static::factory(3)); $channel->subscribe( $this->connection, @@ -177,14 +177,13 @@ public function testSendsNotificationOfAnUnsubscribe(): void $data ); - $this->channelConnectionManager->shouldReceive('find') - ->andReturn(new ChannelConnection($this->connection, ['user_info' => ['name' => 'Joe'], 'user_id' => 1])); + $this->channelConnectionManager->allows('find') + ->returns(new ChannelConnection($this->connection, ['user_info' => ['name' => 'Joe'], 'user_id' => 1])); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn($connections = static::factory(3)); + $this->channelConnectionManager->allows('all') + ->returns($connections = static::factory(3)); - $this->channelConnectionManager->shouldReceive('remove') - ->once() + $this->channelConnectionManager->expects('remove') ->with($this->connection); $channel->unsubscribe($this->connection); @@ -222,10 +221,10 @@ public function testSubscriptionAndUnsubscriptionPreserveZeroUserId(): void && $event['user_id'] === '0'; }); - $this->channelConnectionManager->shouldReceive('find') - ->andReturn(new ChannelConnection($this->connection, ['user_info' => ['name' => 'Zero'], 'user_id' => 0])); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn([]); + $this->channelConnectionManager->allows('find') + ->returns(new ChannelConnection($this->connection, ['user_info' => ['name' => 'Zero'], 'user_id' => 0])); + $this->channelConnectionManager->allows('all') + ->returns([]); Queue::fake(); @@ -246,8 +245,8 @@ public function testEnsuresTheMemberAddedEventIsOnlyFiredOnce(): void $connectionOne = collect(static::factory(data: ['user_info' => ['name' => 'Joe'], 'user_id' => 1]))->first(); $connectionTwo = collect(static::factory(data: ['user_info' => ['name' => 'Joe'], 'user_id' => 1]))->first(); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn([$connectionOne, $connectionTwo]); + $this->channelConnectionManager->allows('all') + ->returns([$connectionOne, $connectionTwo]); $channel->subscribe($connectionOne->connection(), static::validAuth($connectionOne->id(), 'presence-test-channel', $data = json_encode($connectionOne->data())), $data); $channel->subscribe($connectionTwo->connection(), static::validAuth($connectionTwo->id(), 'presence-test-channel', $data = json_encode($connectionTwo->data())), $data); @@ -267,11 +266,11 @@ public function testEnsuresTheMemberRemovedEventIsOnlyFiredOnce(): void $channel->subscribe($connectionOne->connection(), static::validAuth($connectionOne->id(), 'presence-test-channel', $data = json_encode($connectionOne->data())), $data); $channel->subscribe($connectionTwo->connection(), static::validAuth($connectionTwo->id(), 'presence-test-channel', $data = json_encode($connectionTwo->data())), $data); - $this->channelConnectionManager->shouldReceive('find') - ->andReturn($connectionTwo); + $this->channelConnectionManager->allows('find') + ->returns($connectionTwo); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn([$connectionOne, $connectionTwo]); + $this->channelConnectionManager->allows('all') + ->returns([$connectionOne, $connectionTwo]); // First unsubscribe — user still has another connection, so no member_removed $channel->unsubscribe($connectionTwo->connection()); @@ -300,8 +299,8 @@ public function testDisconnectDefersMemberRemovedWebhook(): void $data ); - $this->channelConnectionManager->shouldReceive('find') - ->andReturn(new ChannelConnection($this->connection, ['user_info' => ['name' => 'Test'], 'user_id' => '1'])); + $this->channelConnectionManager->allows('find') + ->returns(new ChannelConnection($this->connection, ['user_info' => ['name' => 'Test'], 'user_id' => '1'])); Queue::fake(); @@ -334,8 +333,8 @@ public function testExplicitUnsubscribeFiresMemberRemovedImmediately(): void $data ); - $this->channelConnectionManager->shouldReceive('find') - ->andReturn(new ChannelConnection($this->connection, ['user_info' => ['name' => 'Test'], 'user_id' => '1'])); + $this->channelConnectionManager->allows('find') + ->returns(new ChannelConnection($this->connection, ['user_info' => ['name' => 'Test'], 'user_id' => '1'])); Queue::fake(); @@ -418,8 +417,8 @@ public function testReconnectStillSendsInternalMemberAddedEvent(): void // Set up mock to return connections for the internal broadcast $listener = new FakeConnection; $listenerChannelConnection = new ChannelConnection($listener); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn([$listenerChannelConnection]); + $this->channelConnectionManager->allows('all') + ->returns([$listenerChannelConnection]); // Reconnect $newConnection = new FakeConnection; diff --git a/tests/Reverb/Protocols/Pusher/ClientEventTest.php b/tests/Reverb/Protocols/Pusher/ClientEventTest.php index 64cb622f6c..ecc194f771 100644 --- a/tests/Reverb/Protocols/Pusher/ClientEventTest.php +++ b/tests/Reverb/Protocols/Pusher/ClientEventTest.php @@ -11,19 +11,22 @@ use Hypervel\Support\Facades\Queue; use Hypervel\Tests\Reverb\Fixtures\FakeConnection; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; class ClientEventTest extends ReverbTestCase { protected ChannelConnectionManager $channelConnectionManager; + /** + * Set up the test environment. + */ protected function setUp(): void { parent::setUp(); - $this->channelConnectionManager = m::spy(ChannelConnectionManager::class); - $this->channelConnectionManager->shouldReceive('for') - ->andReturn($this->channelConnectionManager); + $this->channelConnectionManager = Double::for(ChannelConnectionManager::class)->strict(); + $this->channelConnectionManager->allows('for') + ->returns($this->channelConnectionManager); $this->app->bind(ChannelConnectionManager::class, fn () => $this->channelConnectionManager); } @@ -34,10 +37,10 @@ public function testCanForwardAClientMessage(): void $connectionOne = collect(static::factory(data: ['user_info' => ['name' => 'Joe'], 'user_id' => '1']))->first(); $connectionTwo = collect(static::factory(data: ['user_info' => ['name' => 'Joe'], 'user_id' => '2']))->first(); - $this->channelConnectionManager->shouldReceive('find') - ->andReturn($connectionOne); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn([$connectionOne, $connectionTwo]); + $this->channelConnectionManager->allows('find') + ->returns($connectionOne); + $this->channelConnectionManager->allows('all') + ->returns([$connectionOne, $connectionTwo]); ClientEvent::handle( $connectionOne->connection(), @@ -71,10 +74,10 @@ public function testClientMessagePreservesZeroUserIdInBroadcastAndWebhook(): voi $connectionOne = collect(static::factory(data: ['user_info' => ['name' => 'Zero'], 'user_id' => 0]))->first(); $connectionTwo = collect(static::factory(data: ['user_info' => ['name' => 'Two'], 'user_id' => '2']))->first(); - $this->channelConnectionManager->shouldReceive('find') - ->andReturn($connectionOne); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn([$connectionOne, $connectionTwo]); + $this->channelConnectionManager->allows('find') + ->returns($connectionOne); + $this->channelConnectionManager->allows('all') + ->returns([$connectionOne, $connectionTwo]); ClientEvent::handle( $connectionOne->connection(), @@ -138,9 +141,8 @@ public function testAllowsClientEventOnPublicChannelInAllMode(): void config()->set('reverb.apps.apps.0.accept_client_events_from', 'all'); $this->channels()->findOrCreate('test-channel'); - $this->channelConnectionManager->shouldReceive('all') - ->once() - ->andReturn($connections = static::factory(3)); + $this->channelConnectionManager->expects('all') + ->returns($connections = static::factory(3)); ClientEvent::handle( $connections[0]->connection(), @@ -191,10 +193,10 @@ public function testDoesNotForwardUnauthenticatedClientMessageWhenInMembersMode( $connectionOne = collect(static::factory(data: ['user_info' => ['name' => 'Joe'], 'user_id' => '1']))->first(); $connectionTwo = collect(static::factory(data: ['user_info' => ['name' => 'Joe'], 'user_id' => '2']))->first(); - $this->channelConnectionManager->shouldReceive('find') - ->andReturn(null); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn([$connectionTwo]); + $this->channelConnectionManager->allows('find') + ->returns(null); + $this->channelConnectionManager->allows('all') + ->returns([$connectionTwo]); ClientEvent::handle( $connectionOne->connection(), @@ -223,10 +225,10 @@ public function testDoesNotForwardClientMessageWhenSetToNone(): void $connectionOne = collect(static::factory(data: ['user_info' => ['name' => 'Joe'], 'user_id' => '1']))->first(); $connectionTwo = collect(static::factory(data: ['user_info' => ['name' => 'Joe'], 'user_id' => '2']))->first(); - $this->channelConnectionManager->shouldReceive('find') - ->andReturn($connectionOne); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn([$connectionOne, $connectionTwo]); + $this->channelConnectionManager->allows('find') + ->returns($connectionOne); + $this->channelConnectionManager->allows('all') + ->returns([$connectionOne, $connectionTwo]); ClientEvent::handle( $connectionOne->connection(), @@ -253,9 +255,8 @@ public function testForwardsAClientMessageForUnauthenticatedClientWhenSetToAll() $connection = new FakeConnection; $this->channels()->findOrCreate('test-channel'); - $this->channelConnectionManager->shouldReceive('all') - ->once() - ->andReturn($connections = static::factory()); + $this->channelConnectionManager->expects('all') + ->returns($connections = static::factory()); ClientEvent::handle( $connection, @@ -278,11 +279,10 @@ public function testDoesNotForwardAMessageToItself(): void $connection = new ChannelConnection(new FakeConnection); $this->channels()->findOrCreate('private-test-channel'); - $this->channelConnectionManager->shouldReceive('all') - ->once() - ->andReturn([$connection]); - $this->channelConnectionManager->shouldReceive('find') - ->andReturn($connection); + $this->channelConnectionManager->expects('all') + ->returns([$connection]); + $this->channelConnectionManager->allows('find') + ->returns($connection); ClientEvent::handle( $connection->connection(), @@ -311,10 +311,10 @@ public function testWebhookIncludesUserIdForPresenceChannelInAllMode(): void $this->channels()->findOrCreate('presence-test-channel'); - $this->channelConnectionManager->shouldReceive('find') - ->andReturn($channelConnection); - $this->channelConnectionManager->shouldReceive('all') - ->andReturn([$channelConnection]); + $this->channelConnectionManager->allows('find') + ->returns($channelConnection); + $this->channelConnectionManager->allows('all') + ->returns([$channelConnection]); ClientEvent::handle( $channelConnection->connection(), @@ -340,7 +340,7 @@ public function testFailsOnUnsupportedMessage(): void $connection = new FakeConnection; - $this->channelConnectionManager->shouldNotReceive('all'); + $this->channelConnectionManager->expects('all')->never(); ClientEvent::handle( $connection, diff --git a/tests/Reverb/Protocols/Pusher/EventHandlerTest.php b/tests/Reverb/Protocols/Pusher/EventHandlerTest.php index 981092e68f..907afdf464 100644 --- a/tests/Reverb/Protocols/Pusher/EventHandlerTest.php +++ b/tests/Reverb/Protocols/Pusher/EventHandlerTest.php @@ -20,8 +20,9 @@ use Hypervel\Support\Facades\Queue; use Hypervel\Tests\Reverb\Fixtures\FakeConnection; use Hypervel\Tests\Reverb\ReverbTestCase; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use JsonException; -use Mockery as m; use RuntimeException; use Swoole\Coroutine\CanceledException; use Swoole\Server; @@ -32,6 +33,9 @@ class EventHandlerTest extends ReverbTestCase protected EventHandler $pusher; + /** + * Set up the test environment. + */ protected function setUp(): void { parent::setUp(); @@ -80,10 +84,10 @@ public function testSubscriptionSucceedsWhenWebhookHandoffFails(): void config()->set('reverb.apps.apps.0.webhooks', $webhooks); $failure = new RuntimeException('The delivery queue is unavailable.'); - $sender = m::mock(WebhookSender::class); - $sender->expects('send')->andThrow($failure); + $sender = Double::for(WebhookSender::class)->strict(); + $sender->expects('send')->throws($failure); $this->app->instance(WebhookSender::class, $sender); - $exceptionHandler = m::mock(ExceptionHandler::class); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); $exceptionHandler->expects('report')->with($failure); $this->app->instance(ExceptionHandler::class, $exceptionHandler); @@ -104,12 +108,12 @@ public function testPresenceSubscriptionSurvivesSiblingPublicationFailure(): voi { $failure = new RuntimeException('Unable to reach a sibling worker.'); $metrics = null; - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $server->setting = ['worker_num' => 2]; $server->worker_id = 0; $server->expects('sendMessage') - ->twice() - ->andReturnUsing(function (object $message, int $workerId) use ($failure, &$metrics): bool { + ->times(2) + ->resolves(function (object $message, int $workerId) use ($failure, &$metrics): bool { $this->assertSame(1, $workerId); if ($message instanceof ChannelBroadcastPipeMessage) { @@ -127,7 +131,7 @@ public function testPresenceSubscriptionSurvivesSiblingPublicationFailure(): voi $this->app->instance(Server::class, $server); $metrics = $this->app->make(MetricsHandler::class); - $exceptionHandler = m::mock(ExceptionHandler::class); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); $exceptionHandler->expects('report')->with($failure); $this->app->instance(ExceptionHandler::class, $exceptionHandler); @@ -163,16 +167,16 @@ public function testPresenceSubscriptionSurvivesRedisPublicationFailure(): void $failure = new RuntimeException('Redis publication failed.'); $listener = null; $metricKey = null; - $pubSub = m::mock(PubSubProvider::class); + $pubSub = Double::for(PubSubProvider::class)->strict(); $pubSub->expects('on') - ->with(m::type('string'), m::type('callable')) - ->andReturnUsing(function (string $key, callable $callback) use (&$listener, &$metricKey): void { + ->with(Argument::type('string'), Argument::type('callable')) + ->resolves(function (string $key, callable $callback) use (&$listener, &$metricKey): void { $metricKey = $key; $listener = $callback; }); $pubSub->expects('publish') - ->twice() - ->andReturnUsing(function (array $payload) use ($failure, &$listener): int { + ->times(2) + ->resolves(function (array $payload) use ($failure, &$listener): int { if ($payload['type'] === 'message') { throw $failure; } @@ -191,13 +195,13 @@ public function testPresenceSubscriptionSurvivesRedisPublicationFailure(): void return 1; }); $pubSub->expects('stopListening') - ->with(m::on(function (string $key) use (&$metricKey): bool { + ->with(Argument::satisfies(function (string $key) use (&$metricKey): bool { return $key === $metricKey; })); $this->app->instance(PubSubProvider::class, $pubSub); $this->app->make(ServerProviderManager::class)->withPublishing(); - $exceptionHandler = m::mock(ExceptionHandler::class); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); $exceptionHandler->expects('report')->with($failure); $this->app->instance(ExceptionHandler::class, $exceptionHandler); @@ -266,11 +270,11 @@ public function testCanSubscribeToAnEmptyChannel(): void public function testFallsBackToLocalMembersWhenTheGatherFails(): void { $failure = new RuntimeException('Unable to gather metrics.'); - $metrics = m::mock(MetricsHandler::class); - $metrics->expects('gather')->andThrow($failure); + $metrics = Double::for(MetricsHandler::class)->strict(); + $metrics->expects('gather')->throws($failure); $this->app->instance(MetricsHandler::class, $metrics); - $exceptionHandler = m::mock(ExceptionHandler::class); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); $exceptionHandler->expects('report')->with($failure); $this->app->instance(ExceptionHandler::class, $exceptionHandler); @@ -296,12 +300,12 @@ public function testFallsBackToLocalMembersWhenTheGatherFails(): void public function testGatherCancellationIsNotAnsweredWithLocalMembers(): void { $cancellation = new CanceledException; - $metrics = m::mock(MetricsHandler::class); - $metrics->expects('gather')->andThrow($cancellation); + $metrics = Double::for(MetricsHandler::class)->strict(); + $metrics->expects('gather')->throws($cancellation); $this->app->instance(MetricsHandler::class, $metrics); - $exceptionHandler = m::mock(ExceptionHandler::class); - $exceptionHandler->shouldNotReceive('report'); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); + $exceptionHandler->expects('report')->never(); $this->app->instance(ExceptionHandler::class, $exceptionHandler); $data = json_encode(['user_id' => 1, 'user_info' => ['name' => 'Joe']]); diff --git a/tests/Reverb/Protocols/Pusher/Http/Controllers/ChannelUsersControllerTest.php b/tests/Reverb/Protocols/Pusher/Http/Controllers/ChannelUsersControllerTest.php index aaf3c70992..0f439acde5 100644 --- a/tests/Reverb/Protocols/Pusher/Http/Controllers/ChannelUsersControllerTest.php +++ b/tests/Reverb/Protocols/Pusher/Http/Controllers/ChannelUsersControllerTest.php @@ -8,7 +8,8 @@ use Hypervel\Reverb\Protocols\Pusher\MetricsHandler; use Hypervel\Tests\Reverb\Fixtures\FakeConnection; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; class ChannelUsersControllerTest extends ReverbTestCase { @@ -79,14 +80,14 @@ public function testReturnsUniqueUserData(): void public function testReturnsUsersWhenThePresenceChannelExistsOnlyOnAnotherWorker(): void { - $metrics = m::mock(MetricsHandler::class); + $metrics = Double::for(MetricsHandler::class)->strict(); $metrics->expects('gather') ->with( - m::type(Application::class), + Argument::type(Application::class), 'presence', ['channel' => 'presence-remote-channel'], ) - ->andReturn([ + ->returns([ 'exists' => true, 'presence' => true, 'users' => [ diff --git a/tests/Reverb/Protocols/Pusher/Http/Controllers/EventsBatchControllerTest.php b/tests/Reverb/Protocols/Pusher/Http/Controllers/EventsBatchControllerTest.php index c86109648e..0970d03324 100644 --- a/tests/Reverb/Protocols/Pusher/Http/Controllers/EventsBatchControllerTest.php +++ b/tests/Reverb/Protocols/Pusher/Http/Controllers/EventsBatchControllerTest.php @@ -7,7 +7,7 @@ use Hypervel\Reverb\ServerProviderManager; use Hypervel\Reverb\Servers\Hypervel\Contracts\PubSubProvider; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; class EventsBatchControllerTest extends ReverbTestCase { @@ -65,7 +65,7 @@ public function testDoesNotFailWhenIgnoringALocalSubscriberInABatchEvent(): void public function testPublishesTheOriginatingSocketIdForABatchEventOverRedisEvenWhenTheConnectionIsNotLocal(): void { app(ServerProviderManager::class)->withPublishing(); - $pubSub = m::mock(PubSubProvider::class); + $pubSub = Double::for(PubSubProvider::class)->strict(); $pubSub->expects('publish')->with([ 'type' => 'message', 'app_id' => '123456', @@ -75,7 +75,7 @@ public function testPublishesTheOriginatingSocketIdForABatchEventOverRedisEvenWh 'data' => '{"some":"data"}', ], 'socket_id' => 'remote-socket', - ])->andReturn(1); + ])->returns(1); $this->app->instance(PubSubProvider::class, $pubSub); $response = $this->signedPostRequest('batch_events', ['batch' => [ diff --git a/tests/Reverb/Protocols/Pusher/Http/Controllers/EventsControllerTest.php b/tests/Reverb/Protocols/Pusher/Http/Controllers/EventsControllerTest.php index 4ca64d8767..15375ea805 100644 --- a/tests/Reverb/Protocols/Pusher/Http/Controllers/EventsControllerTest.php +++ b/tests/Reverb/Protocols/Pusher/Http/Controllers/EventsControllerTest.php @@ -9,7 +9,7 @@ use Hypervel\Reverb\Servers\Hypervel\Contracts\PubSubProvider; use Hypervel\Testbench\Attributes\DefineEnvironment; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; class EventsControllerTest extends ReverbTestCase { @@ -120,7 +120,7 @@ public function testDoesNotFailWhenIgnoringAnInvalidSubscriber(): void public function testPublishesTheOriginatingSocketIdOverRedisEvenWhenTheConnectionIsNotLocal(): void { app(ServerProviderManager::class)->withPublishing(); - $pubSub = m::mock(PubSubProvider::class); + $pubSub = Double::for(PubSubProvider::class)->strict(); $pubSub->expects('publish')->with([ 'type' => 'message', 'app_id' => '123456', @@ -130,7 +130,7 @@ public function testPublishesTheOriginatingSocketIdOverRedisEvenWhenTheConnectio 'data' => '{"some":"data"}', ], 'socket_id' => 'remote-socket', - ])->andReturn(1); + ])->returns(1); $this->app->instance(PubSubProvider::class, $pubSub); $response = $this->signedPostRequest('events', [ diff --git a/tests/Reverb/Protocols/Pusher/Http/Controllers/UsersTerminateControllerTest.php b/tests/Reverb/Protocols/Pusher/Http/Controllers/UsersTerminateControllerTest.php index 4b1264c758..c294659513 100644 --- a/tests/Reverb/Protocols/Pusher/Http/Controllers/UsersTerminateControllerTest.php +++ b/tests/Reverb/Protocols/Pusher/Http/Controllers/UsersTerminateControllerTest.php @@ -9,7 +9,8 @@ use Hypervel\Reverb\Servers\Hypervel\TerminateUserPipeMessage; use Hypervel\Tests\Reverb\Fixtures\FakeConnection; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use Swoole\Server; class UsersTerminateControllerTest extends ReverbTestCase @@ -63,16 +64,16 @@ public function testReturns200WhenUserHasNoConnections(): void public function testTerminatesMatchingUserConnectionsOnEverySiblingWorker(): void { - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $server->setting = ['worker_num' => 3]; $server->worker_id = 1; $server->expects('sendMessage') - ->with(m::on(fn (TerminateUserPipeMessage $message): bool => $message->appId === '123456' + ->with(Argument::satisfies(fn (TerminateUserPipeMessage $message): bool => $message->appId === '123456' && $message->userId === '456'), 0) - ->andReturnTrue(); + ->returns(true); $server->expects('sendMessage') - ->with(m::type(TerminateUserPipeMessage::class), 2) - ->andReturnTrue(); + ->with(Argument::type(TerminateUserPipeMessage::class), 2) + ->returns(true); $this->app->instance(Server::class, $server); $response = $this->signedPostRequest('users/456/terminate_connections'); @@ -83,15 +84,15 @@ public function testTerminatesMatchingUserConnectionsOnEverySiblingWorker(): voi public function testRejectedSiblingTerminationAttemptsEveryWorkerAndReturnsAnError(): void { - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $server->setting = ['worker_num' => 3]; $server->worker_id = 0; $server->expects('sendMessage') - ->with(m::type(TerminateUserPipeMessage::class), 1) - ->andReturnFalse(); + ->with(Argument::type(TerminateUserPipeMessage::class), 1) + ->returns(false); $server->expects('sendMessage') - ->with(m::type(TerminateUserPipeMessage::class), 2) - ->andReturnTrue(); + ->with(Argument::type(TerminateUserPipeMessage::class), 2) + ->returns(true); $this->app->instance(Server::class, $server); $response = $this->signedPostRequest('users/456/terminate_connections'); @@ -101,19 +102,17 @@ public function testRejectedSiblingTerminationAttemptsEveryWorkerAndReturnsAnErr public function testPublishesTerminateViaPubsubWhenScalingEnabled(): void { - $serverManager = m::mock(ServerProviderManager::class); - $serverManager->shouldReceive('subscribesToEvents')->andReturn(true); - $this->app->instance(ServerProviderManager::class, $serverManager); + $this->app->make(ServerProviderManager::class)->withPublishing(); - $pubSub = m::mock(PubSubProvider::class); - $pubSub->shouldReceive('publish')->once()->with(m::on(function (array $payload) { + $pubSub = Double::for(PubSubProvider::class)->strict(); + $pubSub->expects('publish')->with(Argument::satisfies(function (array $payload) { return $payload['type'] === 'terminate' && $payload['app_id'] === '123456' && $payload['user_id'] === '456'; })); $this->app->instance(PubSubProvider::class, $pubSub); - $server = m::mock(Server::class); - $server->shouldNotReceive('sendMessage'); + $server = Double::for(Server::class)->strict(); + $server->expects('sendMessage')->never(); $this->app->instance(Server::class, $server); $response = $this->signedPostRequest('users/456/terminate_connections'); diff --git a/tests/Reverb/Protocols/Pusher/MetricsHandlerTest.php b/tests/Reverb/Protocols/Pusher/MetricsHandlerTest.php index 8ecbd73efe..c01de32243 100644 --- a/tests/Reverb/Protocols/Pusher/MetricsHandlerTest.php +++ b/tests/Reverb/Protocols/Pusher/MetricsHandlerTest.php @@ -15,7 +15,8 @@ use Hypervel\Reverb\Servers\Hypervel\MetricsResponsePipeMessage; use Hypervel\Support\Facades\Log; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use RuntimeException; use Swoole\Coroutine\Channel as CoroutineChannel; use Swoole\Server; @@ -24,14 +25,16 @@ class MetricsHandlerTest extends ReverbTestCase { protected MetricsHandler $metrics; + /** + * Set up the test environment. + */ protected function setUp(): void { parent::setUp(); - $serverManager = m::mock(ServerProviderManager::class); - $serverManager->shouldReceive('subscribesToEvents')->andReturn(false); + $serverManager = new ServerProviderManager($this->app); - $pubSub = m::mock(PubSubProvider::class); + $pubSub = Double::for(PubSubProvider::class)->strict(); $this->metrics = new MetricsHandler( $serverManager, @@ -80,12 +83,11 @@ public function testGatherConnectionsReturnsEmptyWhenNoConnections(): void public function testSingleWorkerGatherRetainsNoPendingState(): void { $app = $this->app->make(ApplicationProvider::class)->all()->first(); - $serverManager = m::mock(ServerProviderManager::class); - $serverManager->expects('subscribesToEvents')->andReturnFalse(); + $serverManager = new ServerProviderManager($this->app); $handler = new MetricsHandlerProbe( $serverManager, $this->app->make(ChannelManager::class), - m::mock(PubSubProvider::class), + Double::for(PubSubProvider::class)->strict(), $this->app->make(Server::class), ); @@ -264,16 +266,16 @@ public function testLocalMetricPayloadsContainOnlyTransportSafeValues(): void */ private function scalingMetricsHandler(array $subscriberResponses): MetricsHandler { - $serverManager = m::mock(ServerProviderManager::class); - $serverManager->shouldReceive('subscribesToEvents')->andReturn(true); + $serverManager = new ServerProviderManager($this->app); + $serverManager->withPublishing(); $capturedCallback = null; - $pubSub = m::mock(PubSubProvider::class); - $pubSub->shouldReceive('on')->once()->andReturnUsing(function (string $event, callable $callback) use (&$capturedCallback) { + $pubSub = Double::for(PubSubProvider::class)->strict(); + $pubSub->expects('on')->resolves(function (string $event, callable $callback) use (&$capturedCallback) { $capturedCallback = $callback; }); - $pubSub->shouldReceive('publish')->once()->andReturnUsing(function () use (&$capturedCallback, $subscriberResponses) { + $pubSub->expects('publish')->resolves(function () use (&$capturedCallback, $subscriberResponses) { // Simulate each subscriber responding immediately foreach ($subscriberResponses as $response) { $capturedCallback(['payload' => $response]); @@ -281,7 +283,7 @@ private function scalingMetricsHandler(array $subscriberResponses): MetricsHandl return count($subscriberResponses); }); - $pubSub->shouldReceive('stopListening')->once(); + $pubSub->expects('stopListening'); return new MetricsHandler( $serverManager, @@ -419,16 +421,15 @@ public function testScalingGatherPresenceForAChannelNoServerHas(): void public function testUnscaledMultiWorkerGatherIncludesLocalAndSiblingResponses(): void { $app = $this->app->make(ApplicationProvider::class)->all()->first(); - $serverManager = m::mock(ServerProviderManager::class); - $serverManager->expects('subscribesToEvents')->andReturnFalse(); - $server = m::mock(Server::class); + $serverManager = new ServerProviderManager($this->app); + $server = Double::for(Server::class)->strict(); $server->setting = ['worker_num' => 3]; $server->worker_id = 1; $handler = null; $server->expects('sendMessage') - ->twice() - ->with(m::type(MetricsRequestPipeMessage::class), m::type('int')) - ->andReturnUsing(function (MetricsRequestPipeMessage $message, int $workerId) use (&$handler): bool { + ->times(2) + ->with(Argument::type(MetricsRequestPipeMessage::class), Argument::type('int')) + ->resolves(function (MetricsRequestPipeMessage $message, int $workerId) use (&$handler): bool { $handler->receive(new MetricsResponsePipeMessage( $message->requestId, ['count' => $workerId + 1], @@ -439,7 +440,7 @@ public function testUnscaledMultiWorkerGatherIncludesLocalAndSiblingResponses(): $handler = new MetricsHandlerProbe( $serverManager, $this->app->make(ChannelManager::class), - m::mock(PubSubProvider::class), + Double::for(PubSubProvider::class)->strict(), $server, ); @@ -453,9 +454,8 @@ public function testUnscaledMultiWorkerGatherIncludesLocalAndSiblingResponses(): public function testUnscaledMultiWorkerTimeoutKeepsEveryReceivedSlice(): void { $app = $this->app->make(ApplicationProvider::class)->all()->first(); - $serverManager = m::mock(ServerProviderManager::class); - $serverManager->expects('subscribesToEvents')->andReturnFalse(); - $server = m::mock(Server::class); + $serverManager = new ServerProviderManager($this->app); + $server = Double::for(Server::class)->strict(); $server->setting = ['worker_num' => 3]; $server->worker_id = 0; $handler = null; @@ -467,8 +467,8 @@ public function testUnscaledMultiWorkerTimeoutKeepsEveryReceivedSlice(): void 'expected' => 3, ]); $server->expects('sendMessage') - ->twice() - ->andReturnUsing(function (MetricsRequestPipeMessage $message, int $workerId) use (&$handler): bool { + ->times(2) + ->resolves(function (MetricsRequestPipeMessage $message, int $workerId) use (&$handler): bool { if ($workerId === 1) { $handler->receive(new MetricsResponsePipeMessage( $message->requestId, @@ -481,7 +481,7 @@ public function testUnscaledMultiWorkerTimeoutKeepsEveryReceivedSlice(): void $handler = new MetricsHandlerProbe( $serverManager, $this->app->make(ChannelManager::class), - m::mock(PubSubProvider::class), + Double::for(PubSubProvider::class)->strict(), $server, ); $handler->timeoutImmediately = true; @@ -497,15 +497,14 @@ public function testUnscaledMultiWorkerTimeoutKeepsEveryReceivedSlice(): void public function testUnscaledMultiWorkerSendFailureRemovesPendingState(): void { $app = $this->app->make(ApplicationProvider::class)->all()->first(); - $serverManager = m::mock(ServerProviderManager::class); - $serverManager->expects('subscribesToEvents')->andReturnFalse(); - $server = m::mock(Server::class); + $serverManager = new ServerProviderManager($this->app); + $server = Double::for(Server::class)->strict(); $server->setting = ['worker_num' => 4]; $server->worker_id = 1; $workerIds = []; $server->expects('sendMessage') ->times(3) - ->andReturnUsing(function (MetricsRequestPipeMessage $message, int $workerId) use (&$workerIds): bool { + ->resolves(function (MetricsRequestPipeMessage $message, int $workerId) use (&$workerIds): bool { $workerIds[] = $workerId; return match ($workerId) { @@ -517,7 +516,7 @@ public function testUnscaledMultiWorkerSendFailureRemovesPendingState(): void $handler = new MetricsHandlerProbe( $serverManager, $this->app->make(ChannelManager::class), - m::mock(PubSubProvider::class), + Double::for(PubSubProvider::class)->strict(), $server, ); @@ -537,18 +536,17 @@ public function testUnscaledMultiWorkerLocalMetricFailureRemovesPendingState(): { $app = $this->app->make(ApplicationProvider::class)->all()->first(); $failure = new RuntimeException('Unable to read local channels.'); - $serverManager = m::mock(ServerProviderManager::class); - $serverManager->expects('subscribesToEvents')->andReturnFalse(); - $channels = m::mock(ChannelManager::class); - $channels->expects('for')->with($app)->andThrow($failure); - $server = m::mock(Server::class); + $serverManager = new ServerProviderManager($this->app); + $channels = Double::for(ChannelManager::class)->strict(); + $channels->expects('for')->with($app)->throws($failure); + $server = Double::for(Server::class)->strict(); $server->setting = ['worker_num' => 2]; $server->worker_id = 0; $server->expects('sendMessage')->never(); $handler = new MetricsHandlerProbe( $serverManager, $channels, - m::mock(PubSubProvider::class), + Double::for(PubSubProvider::class)->strict(), $server, ); @@ -588,17 +586,17 @@ public function testScalingResolvesImmediatelyWhenResponsesArriveBeforePop(): vo public function testRemovesTheListenerAfterMetricsAreGatheredSuccessfully(): void { $app = $this->app->make(ApplicationProvider::class)->all()->first(); - $serverManager = m::mock(ServerProviderManager::class); - $serverManager->expects('subscribesToEvents')->andReturnTrue(); + $serverManager = new ServerProviderManager($this->app); + $serverManager->withPublishing(); $registeredEvent = null; $registeredListener = null; - $pubSub = m::mock(PubSubProvider::class); - $pubSub->expects('on')->andReturnUsing(function (string $event, callable $listener) use (&$registeredEvent, &$registeredListener): void { + $pubSub = Double::for(PubSubProvider::class)->strict(); + $pubSub->expects('on')->resolves(function (string $event, callable $listener) use (&$registeredEvent, &$registeredListener): void { $registeredEvent = $event; $registeredListener = $listener; }); $responderId = null; - $pubSub->expects('publish')->andReturnUsing(function () use (&$registeredListener, &$responderId): int { + $pubSub->expects('publish')->resolves(function () use (&$registeredListener, &$responderId): int { $responderId = Coroutine::create(function () use (&$registeredListener): void { usleep(1000); $registeredListener(['payload' => ['count' => 1]]); @@ -606,7 +604,7 @@ public function testRemovesTheListenerAfterMetricsAreGatheredSuccessfully(): voi return 1; }); - $pubSub->expects('stopListening')->with(m::on(function (string $key) use (&$registeredEvent): bool { + $pubSub->expects('stopListening')->with(Argument::satisfies(function (string $key) use (&$registeredEvent): bool { return $key === $registeredEvent; })); $handler = new MetricsHandlerProbe( @@ -631,11 +629,11 @@ public function testScalingPublishFailureRemovesPendingMetricAndListener(): void { $app = $this->app->make(ApplicationProvider::class)->all()->first(); $failure = new RuntimeException('Redis publish failed.'); - $serverManager = m::mock(ServerProviderManager::class); - $serverManager->expects('subscribesToEvents')->andReturnTrue(); - $pubSub = m::mock(PubSubProvider::class); + $serverManager = new ServerProviderManager($this->app); + $serverManager->withPublishing(); + $pubSub = Double::for(PubSubProvider::class)->strict(); $pubSub->expects('on'); - $pubSub->expects('publish')->andThrow($failure); + $pubSub->expects('publish')->throws($failure); $pubSub->expects('stopListening'); $handler = new MetricsHandlerProbe( $serverManager, @@ -658,12 +656,12 @@ public function testScalingPublishFailureRemainsPrimaryWhenListenerCleanupFails( { $app = $this->app->make(ApplicationProvider::class)->all()->first(); $failure = new RuntimeException('Redis publish failed.'); - $serverManager = m::mock(ServerProviderManager::class); - $serverManager->expects('subscribesToEvents')->andReturnTrue(); - $pubSub = m::mock(PubSubProvider::class); + $serverManager = new ServerProviderManager($this->app); + $serverManager->withPublishing(); + $pubSub = Double::for(PubSubProvider::class)->strict(); $pubSub->expects('on'); - $pubSub->expects('publish')->andThrow($failure); - $pubSub->expects('stopListening')->andThrow(new RuntimeException('Listener cleanup failed.')); + $pubSub->expects('publish')->throws($failure); + $pubSub->expects('stopListening')->throws(new RuntimeException('Listener cleanup failed.')); $handler = new MetricsHandlerProbe( $serverManager, $this->app->make(ChannelManager::class), @@ -681,6 +679,9 @@ public function testScalingPublishFailureRemainsPrimaryWhenListenerCleanupFails( $this->assertSame([], $handler->metricsForTest()); } + /** + * Assert that a metric payload can cross worker and Redis transports. + */ private function assertTransportSafe(mixed $value): void { if (is_array($value)) { @@ -702,16 +703,25 @@ class MetricsHandlerProbe extends MetricsHandler { public bool $timeoutImmediately = false; + /** + * Return the pending metrics. + */ public function metricsForTest(): array { return $this->metrics; } + /** + * Return the pending metric waiters. + */ public function waitersForTest(): array { return $this->waiters; } + /** + * Allow tests to trigger the metric timeout immediately. + */ protected function waitForMetric(PendingMetric $metric, CoroutineChannel $waiter): array { if ($this->timeoutImmediately) { diff --git a/tests/Reverb/Protocols/Pusher/ServerTest.php b/tests/Reverb/Protocols/Pusher/ServerTest.php index 9b023cea18..55e89d3306 100644 --- a/tests/Reverb/Protocols/Pusher/ServerTest.php +++ b/tests/Reverb/Protocols/Pusher/ServerTest.php @@ -25,7 +25,7 @@ use Hypervel\Testbench\Attributes\DefineEnvironment; use Hypervel\Tests\Reverb\Fixtures\FakeConnection; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -34,6 +34,9 @@ class ServerTest extends ReverbTestCase { protected Server $server; + /** + * Set up the test environment. + */ protected function setUp(): void { parent::setUp(); @@ -60,12 +63,12 @@ public function testCanHandleAConnection(): void public function testCanceledOpenReleasesItsSlotWithoutSendingAProtocolError(): void { config()->set('reverb.apps.apps.0.max_connections', 1); - $state = m::mock(SharedState::class); - $state->expects('acquireConnectionSlot')->with('123456', 1)->andReturnTrue(); + $state = Double::for(SharedState::class)->strict(); + $state->expects('acquireConnectionSlot')->with('123456', 1)->returns(true); $state->expects('releaseConnectionSlot')->with('123456'); $this->app->instance(SharedState::class, $state); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); $this->app->instance(ExceptionHandler::class, $handler); $cancellation = new CanceledException; Event::listen(ConnectionEstablished::class, static fn () => throw $cancellation); @@ -87,8 +90,8 @@ public function testCanceledOpenReleasesItsSlotWithoutSendingAProtocolError(): v public function testTimedOutMessageDoesNotSendOrReportAProtocolError(): void { - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); $this->app->instance(ExceptionHandler::class, $handler); Event::listen(MessageReceived::class, static function (): void { Coroutine::sleep(1); @@ -108,10 +111,11 @@ public function testTimedOutMessageDoesNotSendOrReportAProtocolError(): void public function testCanHandleADisconnection(): void { - $scopedManager = m::spy(ScopedChannelManager::class); + $scopedManager = Double::for(ScopedChannelManager::class)->strict(); + $scopedManager->allows('unsubscribeFromAll'); - $channelManager = m::mock(ChannelManager::class); - $channelManager->shouldReceive('for')->andReturn($scopedManager); + $channelManager = Double::for(ChannelManager::class)->strict(); + $channelManager->allows('for')->returns($scopedManager); $this->app->singleton(ChannelManager::class, fn () => $channelManager); $this->app->forgetInstance(Server::class); @@ -120,7 +124,7 @@ public function testCanHandleADisconnection(): void $server->open($connection = new FakeConnection); $server->close($connection); - $scopedManager->shouldHaveReceived('unsubscribeFromAll'); + $scopedManager->received('unsubscribeFromAll')->with($connection)->times(1); } public function testCanHandleANewMessage(): void @@ -222,8 +226,8 @@ public function testSendsAnErrorIfSomethingFails(): void public function testRejectsScalarSubscriptionDataBeforePublishingSharedMembership(): void { - $exceptionHandler = m::mock(ExceptionHandler::class); - $exceptionHandler->shouldNotReceive('report'); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); + $exceptionHandler->expects('report')->never(); $this->app->instance(ExceptionHandler::class, $exceptionHandler); $this->server->message( @@ -255,11 +259,11 @@ public function testRejectsScalarSubscriptionDataBeforePublishingSharedMembershi public function testReportsUnexpectedMessageFailuresWithoutChangingTheClientPayload(): void { $exception = new RuntimeException('Internal handler failure'); - $handler = m::mock(EventHandler::class); - $handler->shouldReceive('handle')->once()->andThrow($exception); + $handler = Double::for(EventHandler::class)->strict(); + $handler->expects('handle')->throws($exception); - $exceptionHandler = m::mock(ExceptionHandler::class); - $exceptionHandler->shouldReceive('report')->once()->with($exception); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); + $exceptionHandler->expects('report')->with($exception); $this->app->instance(ExceptionHandler::class, $exceptionHandler); $server = $this->app->makeWith(Server::class, ['handler' => $handler]); @@ -486,6 +490,9 @@ public function testRejectsAConnectionFromAnInvalidOrigin(string $origin, array ]); } + /** + * Provide disallowed connection origins. + */ public static function invalidOriginProvider(): array { return [ @@ -499,8 +506,8 @@ public function testRejectsAConnectionWithoutAnOrigin(): void { config()->set('reverb.apps.apps.0.allowed_origins', ['localhost']); - $webSocket = m::mock(WebSocketConnection::class); - $webSocket->shouldReceive('send')->once(); + $webSocket = Double::for(WebSocketConnection::class)->strict(); + $webSocket->expects('send'); $application = $this->app->make(ApplicationProvider::class) ->findByKey('reverb-key'); $connection = new Connection($webSocket, $application, null); @@ -526,6 +533,9 @@ public function testAcceptsAConnectionFromAValidOrigin(string $origin, array $al ]); } + /** + * Provide allowed connection origins. + */ public static function validOriginProvider(): array { return [ @@ -837,6 +847,9 @@ public function testMessageRateLimiterIsIndependentOfRateLimiterConfiguration(): $this->assertFalse($connection->wasTerminated); } + /** + * Remove the configured rate limiter store. + */ protected function withInvalidRateLimiterConfiguration(ApplicationContract $app): void { $config = $app->make('config'); @@ -1031,10 +1044,11 @@ public function testAllowReceivingClientEventWithEmptyData(): void public function testCloseDoesNotTerminateTheConnection(): void { - $scopedManager = m::spy(ScopedChannelManager::class); + $scopedManager = Double::for(ScopedChannelManager::class)->strict(); + $scopedManager->allows('unsubscribeFromAll'); - $channelManager = m::mock(ChannelManager::class); - $channelManager->shouldReceive('for')->andReturn($scopedManager); + $channelManager = Double::for(ChannelManager::class)->strict(); + $channelManager->allows('for')->returns($scopedManager); $this->app->singleton(ChannelManager::class, fn () => $channelManager); $this->app->forgetInstance(Server::class); @@ -1052,10 +1066,11 @@ public function testCloseDoesNotTerminateTheConnection(): void public function testCloseSetsDisconnectingFlag(): void { - $scopedManager = m::spy(ScopedChannelManager::class); + $scopedManager = Double::for(ScopedChannelManager::class)->strict(); + $scopedManager->allows('unsubscribeFromAll'); - $channelManager = m::mock(ChannelManager::class); - $channelManager->shouldReceive('for')->andReturn($scopedManager); + $channelManager = Double::for(ChannelManager::class)->strict(); + $channelManager->allows('for')->returns($scopedManager); $this->app->singleton(ChannelManager::class, fn () => $channelManager); $this->app->forgetInstance(Server::class); diff --git a/tests/Reverb/ReverbServiceProviderTest.php b/tests/Reverb/ReverbServiceProviderTest.php index 901c47d392..c843b8e4ce 100644 --- a/tests/Reverb/ReverbServiceProviderTest.php +++ b/tests/Reverb/ReverbServiceProviderTest.php @@ -15,7 +15,7 @@ use Hypervel\Reverb\Servers\Hypervel\Contracts\PubSubIncomingMessageHandler; use Hypervel\Reverb\Webhooks\WebhookBatchBuffer; use Hypervel\Support\Facades\Log; -use Mockery as m; +use JMac\Testing\Double; use ReflectionMethod; use ReflectionProperty; use Swoole\Table; @@ -108,9 +108,9 @@ public function testWebhookBatchBufferUsesConfiguredScalingRedisConnection(): vo public function testPreservesCustomPusherBindings(): void { - $channelManager = m::mock(ChannelManager::class); - $channelConnectionManager = m::mock(ChannelConnectionManager::class); - $messageHandler = m::mock(PubSubIncomingMessageHandler::class); + $channelManager = Double::for(ChannelManager::class)->strict(); + $channelConnectionManager = Double::for(ChannelConnectionManager::class)->strict(); + $messageHandler = Double::for(PubSubIncomingMessageHandler::class)->strict(); $this->app->instance(ChannelManager::class, $channelManager); $this->app->instance(ChannelConnectionManager::class, $channelConnectionManager); $this->app->instance(PubSubIncomingMessageHandler::class, $messageHandler); @@ -134,7 +134,7 @@ public function testConcreteAndContractChannelManagersShareOneRepository(): void public function testChannelManagerBindingAfterRegistrationReplacesTheDefaultAlias(): void { - $channelManager = m::mock(ChannelManager::class); + $channelManager = Double::for(ChannelManager::class)->strict(); $this->app->instance(ChannelManager::class, $channelManager); @@ -145,7 +145,7 @@ public function testRegistersTheDefaultLoggerOnlyWhenUnbound(): void { $this->assertInstanceOf(NullLogger::class, $this->app->make(Logger::class)); - $logger = m::mock(Logger::class); + $logger = Double::for(Logger::class)->strict(); $this->app->instance(Logger::class, $logger); (new ReverbServiceProvider($this->app))->register(); @@ -175,6 +175,9 @@ public function testTableCapacityWarningsUseTheFrameworkLogger(): void $method->invoke(new ReverbServiceProvider($this->app), $table, 'Increase reverb.servers.reverb.swoole_shared_state.rows.'); } + /** + * Return the batch buffer Redis connection. + */ protected function bufferRedisConnection(WebhookBatchBuffer $buffer): RedisProxy { $property = new ReflectionProperty($buffer, 'redis'); @@ -182,6 +185,9 @@ protected function bufferRedisConnection(WebhookBatchBuffer $buffer): RedisProxy return $property->getValue($buffer); } + /** + * Register the WebSocket server with the given configuration. + */ protected function registerReverbServer(array $serverConfig): array { $config = $this->app->make('config'); diff --git a/tests/Reverb/ReverbTestCase.php b/tests/Reverb/ReverbTestCase.php index 74a4680589..9851aa330e 100644 --- a/tests/Reverb/ReverbTestCase.php +++ b/tests/Reverb/ReverbTestCase.php @@ -24,7 +24,8 @@ use Hypervel\Testbench\TestCase; use Hypervel\Testing\TestResponse; use Hypervel\Tests\Reverb\Fixtures\FakeConnection; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Swoole\Server; use Throwable; @@ -33,7 +34,11 @@ class ReverbTestCase extends TestCase { use InteractsWithSwooleTables; + use VerifiesDoubles; + /** + * Set up the test environment. + */ protected function setUp(): void { parent::setUp(); @@ -96,8 +101,8 @@ protected function defineEnvironment(ApplicationContract $app): void $config->set('database.redis.queue', $redisConnection); $config->set('database.redis.reverb', $redisConnection); - $server = m::mock(Server::class); - $server->shouldReceive('sendMessage')->zeroOrMoreTimes(); + $server = Double::for(Server::class)->strict(); + $server->allows('sendMessage')->returns(true); $server->setting = ['worker_num' => 1]; $server->worker_id = 0; $app->instance(Server::class, $server); diff --git a/tests/Reverb/Servers/Hypervel/ChannelBroadcastPipeMessageTest.php b/tests/Reverb/Servers/Hypervel/ChannelBroadcastPipeMessageTest.php index 410741a667..6e6427e2c8 100644 --- a/tests/Reverb/Servers/Hypervel/ChannelBroadcastPipeMessageTest.php +++ b/tests/Reverb/Servers/Hypervel/ChannelBroadcastPipeMessageTest.php @@ -13,7 +13,8 @@ use Hypervel\Reverb\Servers\Hypervel\MetricsResponsePipeMessage; use Hypervel\Reverb\Servers\Hypervel\TerminateUserPipeMessage; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use RuntimeException; use Swoole\Server; @@ -31,7 +32,7 @@ public function testPipeMessageBroadcastsToLocalConnections(): void exceptSocketId: null, ); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); event(new OnPipeMessage($server, 0, $message)); @@ -59,7 +60,7 @@ public function testPipeMessageExcludesExceptSocketId(): void exceptSocketId: $connectionOne->id(), ); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); event(new OnPipeMessage($server, 0, $message)); @@ -82,7 +83,7 @@ public function testPipeMessageIgnoresChannelsNotOnThisWorker(): void exceptSocketId: null, ); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); event(new OnPipeMessage($server, 0, $message)); @@ -95,7 +96,7 @@ public function testPipeMessageIgnoresNonChannelBroadcastMessages(): void $connection = $this->subscribeConnection('test-channel'); // Send a non-ChannelBroadcastPipeMessage — the listener should ignore it - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); event(new OnPipeMessage($server, 0, 'some-other-data')); @@ -114,7 +115,7 @@ public function testPipeMessageBroadcastsToMultipleChannels(): void exceptSocketId: null, ); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); event(new OnPipeMessage($server, 0, $message)); @@ -134,7 +135,7 @@ public function testPipeMessageSendsCorrectChannelNamePerChannel(): void exceptSocketId: null, ); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); event(new OnPipeMessage($server, 0, $message)); @@ -170,7 +171,7 @@ public function testPipeMessageClearsCacheMissLockForCacheChannel(): void exceptSocketId: null, ); - event(new OnPipeMessage(m::mock(Server::class), 0, $message)); + event(new OnPipeMessage(Double::for(Server::class)->strict(), 0, $message)); // Lock should be cleared — re-acquire should succeed $this->assertTrue($sharedState->tryCacheMissLock('123456', 'cache-test-channel')); @@ -183,10 +184,10 @@ public function testPipeMessageAttemptsEveryChannelBeforePropagatingTheFirstFail $cacheConnection->resetReceived(); $laterConnection->resetReceived(); $failure = new RuntimeException('cache lock failed'); - $sharedState = m::mock(SharedState::class); + $sharedState = Double::for(SharedState::class)->strict(); $sharedState->expects('clearCacheMissLock') ->with('123456', 'cache-first') - ->andThrow($failure); + ->throws($failure); $this->app->instance(SharedState::class, $sharedState); $message = new ChannelBroadcastPipeMessage( appId: '123456', @@ -196,7 +197,7 @@ public function testPipeMessageAttemptsEveryChannelBeforePropagatingTheFirstFail ); try { - event(new OnPipeMessage(m::mock(Server::class), 0, $message)); + event(new OnPipeMessage(Double::for(Server::class)->strict(), 0, $message)); $this->fail('Expected the first pipe delivery failure to propagate.'); } catch (RuntimeException $exception) { $this->assertSame($failure, $exception); @@ -216,18 +217,18 @@ public function testPipeMessageAttemptsEveryChannelBeforePropagatingTheFirstFail public function testMetricsRequestReturnsTheLocalWorkerSlice(): void { - $metrics = m::mock(MetricsHandler::class); + $metrics = Double::for(MetricsHandler::class)->strict(); $metrics->expects('get') - ->with(m::on(fn (PendingMetric $metric): bool => $metric->key() === 'request' + ->with(Argument::satisfies(fn (PendingMetric $metric): bool => $metric->key() === 'request' && $metric->application()->id() === '123456' && $metric->type()->value === 'connections')) - ->andReturn(['count' => 1]); + ->returns(['count' => 1]); $this->app->instance(MetricsHandler::class, $metrics); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $server->expects('sendMessage') - ->with(m::on(fn (MetricsResponsePipeMessage $message): bool => $message->requestId === 'request' + ->with(Argument::satisfies(fn (MetricsResponsePipeMessage $message): bool => $message->requestId === 'request' && $message->payload === ['count' => 1]), 2) - ->andReturnTrue(); + ->returns(true); event(new OnPipeMessage($server, 2, new MetricsRequestPipeMessage( 'request', @@ -240,11 +241,11 @@ public function testMetricsRequestReturnsTheLocalWorkerSlice(): void public function testMetricsResponseIsDeliveredToThePendingGather(): void { $message = new MetricsResponsePipeMessage('request', ['count' => 1]); - $metrics = m::mock(MetricsHandler::class); + $metrics = Double::for(MetricsHandler::class)->strict(); $metrics->expects('receive')->with($message); $this->app->instance(MetricsHandler::class, $metrics); - event(new OnPipeMessage(m::mock(Server::class), 2, $message)); + event(new OnPipeMessage(Double::for(Server::class)->strict(), 2, $message)); } public function testTerminateUserMessageDisconnectsMatchingLocalConnections(): void @@ -259,7 +260,7 @@ public function testTerminateUserMessageDisconnectsMatchingLocalConnections(): v ]); event(new OnPipeMessage( - m::mock(Server::class), + Double::for(Server::class)->strict(), 2, new TerminateUserPipeMessage('123456', 'matching'), )); diff --git a/tests/Reverb/Servers/Hypervel/ConnectionLifecycleTest.php b/tests/Reverb/Servers/Hypervel/ConnectionLifecycleTest.php index ff03ba20fc..e6a813ba83 100644 --- a/tests/Reverb/Servers/Hypervel/ConnectionLifecycleTest.php +++ b/tests/Reverb/Servers/Hypervel/ConnectionLifecycleTest.php @@ -7,18 +7,21 @@ use Hypervel\Reverb\Contracts\Connection; use Hypervel\Reverb\Servers\Hypervel\ConnectionLifecycle; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use Swoole\Coroutine\Channel; use function Hypervel\Coroutine\go; class ConnectionLifecycleTest extends TestCase { + use VerifiesDoubles; + public function testItAttachesOneConnection(): void { $lifecycle = new ConnectionLifecycle(123); - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class)->strict(); $lifecycle->attach($connection); @@ -27,7 +30,7 @@ public function testItAttachesOneConnection(): void $this->expectException(LogicException::class); - $lifecycle->attach(m::mock(Connection::class)); + $lifecycle->attach(Double::for(Connection::class)->strict()); } public function testTerminalCloseWaitsForCurrentWorkAndRejectsCapturedWaiters(): void diff --git a/tests/Reverb/Servers/Hypervel/ConnectionTest.php b/tests/Reverb/Servers/Hypervel/ConnectionTest.php index 07f222e0ed..1fcef43ecd 100644 --- a/tests/Reverb/Servers/Hypervel/ConnectionTest.php +++ b/tests/Reverb/Servers/Hypervel/ConnectionTest.php @@ -7,52 +7,66 @@ use Hypervel\Reverb\Servers\Hypervel\Connection; use Hypervel\Tests\Reverb\ReverbTestCase; use Hypervel\WebSocketServer\Sender; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use Swoole\Server; +use Swoole\WebSocket\Server as WebSocketServer; class ConnectionTest extends ReverbTestCase { public function testIdReturnsFd(): void { - $sender = m::mock(Sender::class); - $connection = new Connection($sender, 42); + $connection = new Connection(new Sender($this->app), 42); $this->assertSame(42, $connection->id()); } public function testSendDelegatesToSender(): void { - $sender = m::mock(Sender::class); - $sender->shouldReceive('push')->once()->with(42, 'hello')->andReturn(true); + $server = $this->server(); + $server->expects('push')->with(42, 'hello')->returns(true); - $connection = new Connection($sender, 42); + $connection = new Connection(new Sender($this->app), 42); $connection->send('hello'); } public function testControlSendsOpcodeViaSender(): void { - $sender = m::mock(Sender::class); - $sender->shouldReceive('push')->once()->with(42, '', WEBSOCKET_OPCODE_PING)->andReturn(true); + $server = $this->server(); + $server->expects('push')->with(42, '', WEBSOCKET_OPCODE_PING)->returns(true); - $connection = new Connection($sender, 42); + $connection = new Connection(new Sender($this->app), 42); $connection->control(WEBSOCKET_OPCODE_PING); } public function testCloseDisconnectsFd(): void { - $sender = m::mock(Sender::class); - $sender->shouldReceive('disconnect')->once()->with(42)->andReturn(true); + $server = $this->server(); + $server->expects('disconnect')->with(42)->returns(true); - $connection = new Connection($sender, 42); + $connection = new Connection(new Sender($this->app), 42); $connection->close(); } public function testCloseWithMessageSendsThenDisconnects(): void { - $sender = m::mock(Sender::class); - $sender->shouldReceive('push')->once()->with(42, 'goodbye')->andReturn(true); - $sender->shouldReceive('disconnect')->once()->with(42)->andReturn(true); + $server = $this->server(); + $server->expects('push')->with(42, 'goodbye')->returns(true); + $server->expects('disconnect')->with(42)->returns(true); - $connection = new Connection($sender, 42); + $connection = new Connection(new Sender($this->app), 42); $connection->close('goodbye'); } + + /** + * Bind a native server with an active WebSocket connection. + */ + protected function server(): WebSocketServer&DoubleInterface + { + $server = Double::for(WebSocketServer::class)->strict(); + $server->allows('connection_info')->with(42)->returns(['websocket_status' => WEBSOCKET_STATUS_ACTIVE]); + $this->app->instance(Server::class, $server); + + return $server; + } } diff --git a/tests/Reverb/Servers/Hypervel/GracefulShutdownTest.php b/tests/Reverb/Servers/Hypervel/GracefulShutdownTest.php index 7cc81acdee..a3f2f06470 100644 --- a/tests/Reverb/Servers/Hypervel/GracefulShutdownTest.php +++ b/tests/Reverb/Servers/Hypervel/GracefulShutdownTest.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\Reverb\Servers\Hypervel; +use Hypervel\Container\Container; use Hypervel\Contracts\Debug\ExceptionHandler; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Core\Events\OnWorkerExit; @@ -28,23 +29,18 @@ use Hypervel\Tests\Reverb\Fixtures\FakeConnection; use Hypervel\Tests\Reverb\ReverbTestCase; use Hypervel\WebSocketServer\Sender; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use ReflectionMethod; use ReflectionProperty; use RuntimeException; use Swoole\Coroutine\CanceledException; use Swoole\Server; +use Swoole\WebSocket\Server as WebSocketServer; use Throwable; class GracefulShutdownTest extends ReverbTestCase { - protected function tearDown(): void - { - WebSocketHandler::flushState(); - - parent::tearDown(); - } - // ── Drain connections ───────────────────────────────────────────── public function testDrainConnectionsCallsCloseForEachConnection(): void @@ -102,13 +98,13 @@ public function testDrainConnectionsHandlesEmptyConnectionList(): void public function testDrainConnectionsAttemptsEveryConnectionAndPreservesTheFirstFailure(): void { $firstFailure = new RuntimeException('First disconnect failed.'); - $firstSender = m::mock(Sender::class); - $firstSender->expects('disconnect')->andThrow($firstFailure); - $secondSender = m::mock(Sender::class); - $secondSender->expects('disconnect')->with(2, 1001, 'Server restarting')->andReturnTrue(); + $firstServer = Double::for(WebSocketServer::class)->strict(); + $firstServer->expects('disconnect')->throws($firstFailure); + $secondServer = Double::for(WebSocketServer::class)->strict(); + $secondServer->expects('disconnect')->with(2, 1001, 'Server restarting')->returns(true); - $this->addToWebSocketHandler(1, $this->createReverbConnection($firstSender, 1)); - $this->addToWebSocketHandler(2, $this->createReverbConnection($secondSender, 2)); + $this->addToWebSocketHandler(1, $this->createReverbConnection($this->createSender($firstServer), 1)); + $this->addToWebSocketHandler(2, $this->createReverbConnection($this->createSender($secondServer), 2)); $provider = $this->app->getProvider(ReverbServiceProvider::class); @@ -129,16 +125,12 @@ public function testShutdownAttemptsEveryPhaseAndReportsEachFailure(): void 'subscriber' => new RuntimeException('Subscriber disconnect failed.'), 'webhooks' => new RuntimeException('Webhook flush failed.'), ]; - $events = m::mock(Dispatcher::class); + $events = Double::for(Dispatcher::class)->strict(); $listener = null; $events->expects('listen') - ->with(OnWorkerExit::class, m::on(function (callable $callback) use (&$listener): bool { - $listener = $callback; - - return true; - })); + ->with(OnWorkerExit::class, Argument::capture($listener)); $this->app->instance('events', $events); - $exceptionHandler = m::mock(ExceptionHandler::class); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); $exceptionHandler->expects('report')->with($failures['drain']); $exceptionHandler->expects('report')->with($failures['subscriber']); $exceptionHandler->expects('report')->with($failures['webhooks']); @@ -146,7 +138,7 @@ public function testShutdownAttemptsEveryPhaseAndReportsEachFailure(): void $provider = new GracefulShutdownServiceProviderProbe($this->app); $provider->failures = $failures; $provider->registerShutdownHandlerForTest(); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $server->taskworker = false; $listener(new OnWorkerExit($server, 0)); @@ -161,10 +153,10 @@ public function testShutdownReportingFallsBackToThePhpErrorLog(): void $errorLog = $directory . '/php-error.log'; $previousErrorLog = ini_set('error_log', $errorLog); $failure = new RuntimeException('Connection drain failed.'); - $exceptionHandler = m::mock(ExceptionHandler::class); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); $exceptionHandler->expects('report') ->with($failure) - ->andThrow(new RuntimeException('Reporting failed.')); + ->throws(new RuntimeException('Reporting failed.')); $this->app->instance(ExceptionHandler::class, $exceptionHandler); $provider = new GracefulShutdownServiceProviderProbe($this->app); @@ -186,8 +178,8 @@ public function testShutdownReportingFallsBackToThePhpErrorLog(): void public function testShutdownReportingSkipsADirectCancellation(): void { - $exceptionHandler = m::mock(ExceptionHandler::class); - $exceptionHandler->shouldNotReceive('report'); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); + $exceptionHandler->expects('report')->never(); $this->app->instance(ExceptionHandler::class, $exceptionHandler); $provider = new GracefulShutdownServiceProviderProbe($this->app); @@ -222,8 +214,8 @@ public function testScheduleWebhookFlushesDispatchesWhenTheBufferGrantsIt(): voi $webhooks['batching']['enabled'] = true; config()->set('reverb.apps.apps.0.webhooks', $webhooks); - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->shouldReceive('shouldScheduleFlush')->once()->andReturnTrue(); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->expects('shouldScheduleFlush')->returns(true); $this->app->instance(WebhookBatchBuffer::class, $buffer); $provider = $this->app->getProvider(ReverbServiceProvider::class); @@ -246,12 +238,12 @@ public function testScheduleWebhookFlushesContinuesAfterOneApplicationsBufferFai ]); $failure = new RuntimeException('Redis Cluster slot unavailable.'); - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->expects('shouldScheduleFlush')->with('unavailable')->andThrow($failure); - $buffer->expects('shouldScheduleFlush')->with('healthy')->andReturnTrue(); - $buffer->shouldNotReceive('clearFlushLock'); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->expects('shouldScheduleFlush')->with('unavailable')->throws($failure); + $buffer->expects('shouldScheduleFlush')->with('healthy')->returns(true); + $buffer->expects('clearFlushLock')->never(); $this->app->instance(WebhookBatchBuffer::class, $buffer); - $exceptionHandler = m::mock(ExceptionHandler::class); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); $exceptionHandler->expects('report')->with($failure); $this->app->instance(ExceptionHandler::class, $exceptionHandler); @@ -284,8 +276,8 @@ public function testScheduleWebhookFlushesSkipsWhenTheBufferRefuses(): void $webhooks['batching']['enabled'] = true; config()->set('reverb.apps.apps.0.webhooks', $webhooks); - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->shouldReceive('shouldScheduleFlush')->once()->andReturnFalse(); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->expects('shouldScheduleFlush')->returns(false); $this->app->instance(WebhookBatchBuffer::class, $buffer); $provider = $this->app->getProvider(ReverbServiceProvider::class); @@ -325,10 +317,10 @@ public function testShutdownDoesNotLosePreExistingDeferredWebhooks(): void { Queue::fake(); - $sharedState = m::mock(SharedState::class); - $sharedState->shouldReceive('getSubscriptionCount') + $sharedState = Double::for(SharedState::class)->strict(); + $sharedState->allows('getSubscriptionCount') ->with('test-app', 'test-channel') - ->andReturn(0); + ->returns(0); $this->app->instance(SharedState::class, $sharedState); $webhooks = array_replace($this->webhookConfig(), [ @@ -370,8 +362,8 @@ public function testShutdownDoesNotLosePreExistingDeferredWebhooks(): void #[WithEnv('REVERB_SCALING_ENABLED', 'true')] public function testDisconnectScalingSubscriberCallsDisconnect(): void { - $pubSub = m::mock(PubSubProvider::class); - $pubSub->shouldReceive('disconnect')->once(); + $pubSub = Double::for(PubSubProvider::class)->strict(); + $pubSub->expects('disconnect'); $this->app->instance(PubSubProvider::class, $pubSub); $reverbProvider = $this->app->getProvider(ReverbServiceProvider::class); @@ -381,8 +373,8 @@ public function testDisconnectScalingSubscriberCallsDisconnect(): void public function testDisconnectScalingSubscriberSkipsWhenNotScaling(): void { - $pubSub = m::mock(PubSubProvider::class); - $pubSub->shouldNotReceive('disconnect'); + $pubSub = Double::for(PubSubProvider::class)->strict(); + $pubSub->expects('disconnect')->never(); $this->app->instance(PubSubProvider::class, $pubSub); $provider = $this->app->getProvider(ReverbServiceProvider::class); @@ -394,30 +386,34 @@ public function testDisconnectScalingSubscriberSkipsWhenNotScaling(): void public function testDisconnectWithNoCodeUsesPlainPath(): void { - $sender = m::mock(Sender::class); - $sender->shouldReceive('disconnect')->once()->with(99)->andReturn(true); + $server = Double::for(WebSocketServer::class)->strict(); + $server->expects('disconnect')->with(99)->returns(true); - $wsConnection = new WebSocketConnection($sender, 99); + $wsConnection = new WebSocketConnection($this->createSender($server), 99); $wsConnection->close(); } public function testDisconnectWithCodeForwardsCodeAndReason(): void { - $sender = m::mock(Sender::class); - $sender->shouldReceive('disconnect')->once()->with(99, 1001, 'Server restarting')->andReturn(true); + $server = Double::for(WebSocketServer::class)->strict(); + $server->expects('disconnect')->with(99, 1001, 'Server restarting')->returns(true); - $wsConnection = new WebSocketConnection($sender, 99); + $wsConnection = new WebSocketConnection($this->createSender($server), 99); $wsConnection->close(code: 1001, reason: 'Server restarting'); } // ── Helpers ─────────────────────────────────────────────────────── + /** + * Create a Reverb connection with a controlled native transport. + */ protected function createReverbConnection(?Sender $sender = null, ?int $fd = null): ReverbConnection { if ($sender === null) { - $sender = m::mock(Sender::class); - $sender->shouldReceive('push')->zeroOrMoreTimes(); - $sender->shouldReceive('disconnect')->zeroOrMoreTimes()->andReturn(true); + $server = Double::for(WebSocketServer::class)->strict(); + $server->allows('push')->returns(true); + $server->allows('disconnect')->returns(true); + $sender = $this->createSender($server); } $wsConnection = new WebSocketConnection($sender, $fd ?? rand(1, 99999)); @@ -426,6 +422,21 @@ protected function createReverbConnection(?Sender $sender = null, ?int $fd = nul return new ReverbConnection($wsConnection, $app, null); } + /** + * Create a real sender backed by an isolated native server. + */ + protected function createSender(WebSocketServer $server): Sender + { + $server->allows('connection_info')->returns(['websocket_status' => WEBSOCKET_STATUS_ACTIVE]); + $container = new Container; + $container->instance(Server::class, $server); + + return new Sender($container); + } + + /** + * Register an established connection lifecycle. + */ protected function addToWebSocketHandler(int $fd, ReverbConnection $connection): void { $connection->markEstablished(); @@ -451,31 +462,49 @@ class GracefulShutdownServiceProviderProbe extends ReverbServiceProvider */ public array $operations = []; + /** + * Register the shutdown listener for the test. + */ public function registerShutdownHandlerForTest(): void { $this->registerShutdownHandler(); } + /** + * Report a shutdown failure for the test. + */ public function reportShutdownFailureForTest(Throwable $throwable): void { $this->reportShutdownFailure($throwable); } + /** + * Record and exercise the connection drain. + */ public function drainConnections(): void { $this->fail('drain'); } + /** + * Record and exercise the subscriber disconnect. + */ protected function disconnectScalingSubscriber(): void { $this->fail('subscriber'); } + /** + * Record and exercise webhook scheduling. + */ protected function scheduleWebhookFlushes(): void { $this->fail('webhooks'); } + /** + * Record the operation and throw its configured failure. + */ private function fail(string $operation): void { $this->operations[] = $operation; diff --git a/tests/Reverb/Servers/Hypervel/HttpServerTest.php b/tests/Reverb/Servers/Hypervel/HttpServerTest.php index 4c6a82ee4a..85dae6b06e 100644 --- a/tests/Reverb/Servers/Hypervel/HttpServerTest.php +++ b/tests/Reverb/Servers/Hypervel/HttpServerTest.php @@ -16,7 +16,8 @@ use Hypervel\Reverb\Servers\Hypervel\HttpServer; use Hypervel\Reverb\Servers\Hypervel\ReverbRouter; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -27,6 +28,9 @@ class HttpServerTest extends ReverbTestCase { + /** + * Clean up the worker-start coordinator. + */ protected function tearDown(): void { parent::tearDown(); @@ -139,13 +143,13 @@ public function testCancellationSkipsFallbackAndCompletionEventsButPublishesTheC { CoordinatorManager::until(Constants::WORKER_START)->resume(); $cancellation = new CanceledException; - $router = m::mock(ReverbRouter::class); - $router->shouldReceive('compileAndWarm')->once(); - $router->shouldReceive('dispatch')->once()->andThrow($cancellation); + $router = Double::for(ReverbRouter::class)->strict(); + $router->expects('compileAndWarm'); + $router->expects('dispatch')->throws($cancellation); $this->app->instance(ReverbRouter::class, $router); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); - $handler->shouldNotReceive('render'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); + $handler->expects('render')->never(); $this->app->instance(ExceptionHandler::class, $handler); $dispatchedEvents = []; @@ -156,8 +160,7 @@ public function testCancellationSkipsFallbackAndCompletionEventsButPublishesTheC }); } - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status', 'header', 'end')->never(); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); try { $this->makeHttpServer()->onRequest( @@ -169,6 +172,8 @@ public function testCancellationSkipsFallbackAndCompletionEventsButPublishesTheC $this->assertSame($cancellation, $exception); } + $swooleResponse->unused(); + $this->assertSame([RequestReceived::class, RequestCanceled::class], array_keys($dispatchedEvents)); $this->assertSame($cancellation, $dispatchedEvents[RequestCanceled::class]->cancellation); $this->assertNull($dispatchedEvents[RequestCanceled::class]->response); @@ -181,11 +186,11 @@ public function testCancellationAfterAHeldFailurePublishesItAndReportsTheFailure $heldFailure = new RuntimeException('Handled listener failed.'); $listenerFailure = new RuntimeException('Canceled listener failed.'); $cancellation = new CanceledException; - $router = m::mock(ReverbRouter::class); - $router->shouldReceive('compileAndWarm')->once(); - $router->shouldReceive('dispatch')->once()->andReturn(new Response('OK')); + $router = Double::for(ReverbRouter::class)->strict(); + $router->expects('compileAndWarm'); + $router->expects('dispatch')->returns(new Response('OK')); $this->app->instance(ReverbRouter::class, $router); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $handler->expects('report')->with($heldFailure)->ordered(); $handler->expects('report')->with($listenerFailure)->ordered(); $this->app->instance(ExceptionHandler::class, $handler); @@ -250,6 +255,9 @@ public function testFallsBackToBodySizeForInvalidContentLength(string $contentLe $server->onRequest($swooleRequest, $swooleResponse); } + /** + * Provide invalid content-length headers. + */ public static function invalidContentLengthProvider(): array { return [ @@ -265,9 +273,9 @@ public function testEmitsFallbackResponseWhenRequestIsUnavailable(): void CoordinatorManager::until(Constants::WORKER_START)->resume(); $original = new RuntimeException('Request body failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($original); - $handler->shouldNotReceive('render'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($original); + $handler->expects('render')->never(); $this->app->instance(ExceptionHandler::class, $handler); $this->makeHttpServer()->onRequest( @@ -282,15 +290,15 @@ public function testRetainsRequestFailureWhenExceptionReportingFails(): void $original = new RuntimeException('Request failed'); $reportingFailure = new RuntimeException('Reporting failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($original)->andThrow($reportingFailure); - $handler->shouldNotReceive('render'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($original)->throws($reportingFailure); + $handler->expects('render')->never(); $this->app->instance(ExceptionHandler::class, $handler); try { $this->makeFailingHttpServer($original)->onRequest( $this->makeSwooleRequest('/up'), - m::mock(SwooleResponse::class), + Double::for(SwooleResponse::class)->strict(), ); $this->fail('Expected exception reporting to fail.'); } catch (RuntimeException $exception) { @@ -304,12 +312,11 @@ public function testReportsRendersAndEmitsRequestFailure(): void CoordinatorManager::until(Constants::WORKER_START)->resume(); $original = new RuntimeException('Request failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($original); - $handler->shouldReceive('render') - ->once() - ->with(m::type(Request::class), $original) - ->andReturn(new Response('Internal Server Error', 500)); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($original); + $handler->expects('render') + ->with(Argument::type(Request::class), $original) + ->returns(new Response('Internal Server Error', 500)); $this->app->instance(ExceptionHandler::class, $handler); $observedEvents = []; @@ -335,12 +342,12 @@ public function testPreservesCancellationWithoutReportingRenderingOrEmittingResp CoordinatorManager::until(Constants::WORKER_START)->resume(); $cancellation = new CanceledException; - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report', 'render'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); + $handler->expects('render')->never(); $this->app->instance(ExceptionHandler::class, $handler); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldNotReceive('status', 'header', 'cookie', 'rawcookie', 'write', 'sendfile', 'end'); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); try { $this->makeFailingHttpServer($cancellation)->onRequest( @@ -351,6 +358,8 @@ public function testPreservesCancellationWithoutReportingRenderingOrEmittingResp } catch (CanceledException $exception) { $this->assertSame($cancellation, $exception); } + + $swooleResponse->unused(); } public function testRetainsRequestFailureWhenResponseEmissionFails(): void @@ -359,16 +368,15 @@ public function testRetainsRequestFailureWhenResponseEmissionFails(): void $original = new RuntimeException('Request failed'); $emissionFailure = new RuntimeException('Response emission failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($original); - $handler->shouldReceive('render') - ->once() - ->with(m::type(Request::class), $original) - ->andReturn(new Response('Internal Server Error', 500)); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($original); + $handler->expects('render') + ->with(Argument::type(Request::class), $original) + ->returns(new Response('Internal Server Error', 500)); $this->app->instance(ExceptionHandler::class, $handler); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->once()->with(500)->andThrow($emissionFailure); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->with(500)->throws($emissionFailure); try { $this->makeFailingHttpServer($original)->onRequest( @@ -394,8 +402,8 @@ function (ResponseSent $event) use (&$sentEvent): void { $sentEvent = $event; }, ); - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->once()->with(200)->andThrow($emissionFailure); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->with(200)->throws($emissionFailure); try { $this->makeHttpServer()->onRequest( @@ -411,6 +419,9 @@ function (ResponseSent $event) use (&$sentEvent): void { $this->assertSame($emissionFailure, $sentEvent->exception); } + /** + * Create a bootstrapped Reverb HTTP server. + */ protected function makeHttpServer(): HttpServer { $server = new HttpServer($this->app); @@ -419,23 +430,29 @@ protected function makeHttpServer(): HttpServer return $server; } + /** + * Create a Reverb HTTP server whose router throws. + */ protected function makeFailingHttpServer(Throwable $exception): HttpServer { - $router = m::mock(ReverbRouter::class); - $router->shouldReceive('compileAndWarm')->once(); - $router->shouldReceive('dispatch')->once()->andThrow($exception); + $router = Double::for(ReverbRouter::class)->strict(); + $router->expects('compileAndWarm'); + $router->expects('dispatch')->throws($exception); $this->app->instance(ReverbRouter::class, $router); return $this->makeHttpServer(); } + /** + * Create a native request with the given body and headers. + */ protected function makeSwooleRequest( string $uri, string $method = 'get', array $headers = [], string|false|Throwable $rawContent = false, ): SwooleRequest { - $swooleRequest = m::mock(SwooleRequest::class); + $swooleRequest = Double::for(SwooleRequest::class)->strict(); $swooleRequest->server = [ 'request_method' => $method, 'request_uri' => $uri, @@ -446,25 +463,28 @@ protected function makeSwooleRequest( $swooleRequest->cookie = []; $swooleRequest->files = []; if ($rawContent instanceof Throwable) { - $swooleRequest->shouldReceive('rawContent')->andThrow($rawContent); + $swooleRequest->allows('rawContent')->throws($rawContent); } else { - $swooleRequest->shouldReceive('rawContent')->andReturn($rawContent); + $swooleRequest->allows('rawContent')->returns($rawContent); } return $swooleRequest; } + /** + * Expect the response status and body to be sent. + */ protected function makeSwooleResponse(int $status, string $body, ?Closure $onEnd = null): SwooleResponse { - $swooleResponse = m::mock(SwooleResponse::class); - $swooleResponse->shouldReceive('status')->once()->with($status)->andReturnTrue(); - $swooleResponse->shouldReceive('header')->withAnyArgs()->andReturnTrue(); - $expectation = $swooleResponse->shouldReceive('end')->once()->with($body); + $swooleResponse = Double::for(SwooleResponse::class)->strict(); + $swooleResponse->expects('status')->with($status)->returns(true); + $swooleResponse->allows('header')->returns(true); + $expectation = $swooleResponse->expects('end')->with($body); if ($onEnd === null) { - $expectation->andReturnTrue(); + $expectation->returns(true); } else { - $expectation->andReturnUsing(function () use ($onEnd): bool { + $expectation->resolves(function () use ($onEnd): bool { $onEnd(); return true; diff --git a/tests/Reverb/Servers/Hypervel/HypervelServerProviderTest.php b/tests/Reverb/Servers/Hypervel/HypervelServerProviderTest.php index fee23f0e74..7f98e3e369 100644 --- a/tests/Reverb/Servers/Hypervel/HypervelServerProviderTest.php +++ b/tests/Reverb/Servers/Hypervel/HypervelServerProviderTest.php @@ -16,7 +16,7 @@ use Hypervel\Testbench\Attributes\WithEnv; use Hypervel\Tests\Reverb\ReverbTestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; use ReflectionProperty; class HypervelServerProviderTest extends ReverbTestCase @@ -98,8 +98,8 @@ public function testRedisClusterScalingIsRejectedWithoutCreatingAPool(): void 'enabled' => true, 'seeds' => ['127.0.0.1:6379'], ]); - $this->app->instance(PoolManager::class, $poolManager = m::mock(PoolManager::class)); - $poolManager->shouldNotReceive('pool'); + $this->app->instance(PoolManager::class, $poolManager = Double::for(PoolManager::class)->strict()); + $poolManager->expects('pool')->never(); $provider = new HypervelServerProvider( $this->app, [ @@ -121,8 +121,8 @@ public function testRedisClusterScalingIsRejectedWithoutCreatingAPool(): void public function testRedisClusterIsNotValidatedWhenScalingIsDisabled(): void { - $redisConfig = m::mock(RedisConfig::class); - $redisConfig->shouldNotReceive('connectionConfig'); + $redisConfig = Double::for(RedisConfig::class)->strict(); + $redisConfig->expects('connectionConfig')->never(); $this->app->instance(RedisConfig::class, $redisConfig); $provider = new HypervelServerProvider( $this->app, @@ -163,6 +163,9 @@ protected function bootServerProvider(): Dispatcher return $events; } + /** + * Return the shared-state Redis connection. + */ protected function sharedStateRedisConnection(RedisSharedState $sharedState): RedisProxy { $property = new ReflectionProperty($sharedState, 'redis'); diff --git a/tests/Reverb/Servers/Hypervel/Scaling/RedisPubSubProviderTest.php b/tests/Reverb/Servers/Hypervel/Scaling/RedisPubSubProviderTest.php index f54273ddb8..6e82ab508d 100644 --- a/tests/Reverb/Servers/Hypervel/Scaling/RedisPubSubProviderTest.php +++ b/tests/Reverb/Servers/Hypervel/Scaling/RedisPubSubProviderTest.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\Reverb\Servers\Hypervel\Scaling; +use Hypervel\Container\Container; use Hypervel\Contracts\Debug\ExceptionHandler; use Hypervel\Coordinator\Constants; use Hypervel\Coordinator\CoordinatorManager; @@ -11,17 +12,23 @@ use Hypervel\Engine\Channel; use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Engine\Exceptions\CoroutineCreateException; +use Hypervel\Redis\Pool\PoolManager; +use Hypervel\Redis\Pool\RedisPool; use Hypervel\Redis\RedisProxy; +use Hypervel\Redis\RedisSentinelFactory; use Hypervel\Redis\Subscriber\Message; use Hypervel\Redis\Subscriber\Subscriber; use Hypervel\Reverb\Contracts\Logger; use Hypervel\Reverb\Loggers\Log; use Hypervel\Reverb\Servers\Hypervel\Contracts\PubSubIncomingMessageHandler; use Hypervel\Reverb\Servers\Hypervel\Scaling\RedisPubSubProvider; +use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; use Hypervel\Tests\Reverb\ReverbTestCase; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; use JsonException; -use Mockery as m; use PHPUnit\Framework\Attributes\RunInSeparateProcess; +use Redis; use RuntimeException; use Swoole\Coroutine as SwooleCoroutine; use Swoole\Coroutine\CanceledException; @@ -32,11 +39,16 @@ class RedisPubSubProviderTest extends ReverbTestCase { protected Logger $logger; + /** + * Set up the test logger. + */ protected function setUp(): void { parent::setUp(); - $this->logger = m::spy(Logger::class); + $this->logger = Double::for(Logger::class)->strict(); + $this->logger->allows('info'); + $this->logger->allows('error'); $this->app->instance(Logger::class, $this->logger); Log::flushState(); } @@ -46,8 +58,8 @@ public function testSpawnFailureRollsBackTheLifecycleOwner(): void { SwooleCoroutine::set(['max_coroutine' => 1]); - $redis = m::mock(RedisProxy::class); - $redis->shouldNotReceive('subscriber'); + $redis = Double::for(RedisProxy::class)->strict(); + $redis->expects('subscriber')->never(); $provider = $this->provider($redis); try { @@ -60,7 +72,7 @@ public function testSpawnFailureRollsBackTheLifecycleOwner(): void public function testCallerCancellationDuringStartupReportingLeavesTheLifecycleChildInControl(): void { - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $this->app->instance(ExceptionHandler::class, $handler); $hookFailure = new RuntimeException('The startup hook failed.'); $reportStarted = new Channel(1); @@ -69,13 +81,12 @@ public function testCallerCancellationDuringStartupReportingLeavesTheLifecycleCh $parentCancellation = null; $childCoroutineId = null; $subscriber = $this->subscriber(); - $redis = m::mock(RedisProxy::class); + $redis = Double::for(RedisProxy::class)->strict(); $provider = $this->provider($redis); - $handler->shouldReceive('report') - ->once() + $handler->expects('report') ->with($hookFailure) - ->andReturnUsing(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { + ->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { $childCoroutineId = EngineCoroutine::id(); $reportStarted->push(true); $releaseReport->pop(); @@ -83,11 +94,11 @@ public function testCallerCancellationDuringStartupReportingLeavesTheLifecycleCh Coroutine::afterCreated(static function () use ($hookFailure): void { throw $hookFailure; }); - $subscriber->expects('subscribe')->with('reverb')->andReturnUsing(function () use ($provider): void { + $subscriber->expects('subscribe')->with('reverb')->resolves(function () use ($provider): void { $provider->disconnect(); }); $this->expectSubscriberClose($subscriber); - $redis->expects('subscriber')->andReturn($subscriber); + $redis->expects('subscriber')->returns($subscriber); $canceller = EngineCoroutine::create(static function () use ($reportStarted, &$parentCoroutineId): void { $reportStarted->pop(); @@ -132,8 +143,8 @@ public function testDuplicateConnectCallsRetainOneLifecycleOwner(): void $subscriber = $this->subscriber($messages); $subscriber->expects('subscribe')->with('reverb'); $this->expectSubscriberClose($subscriber, $messages); - $redis = m::mock(RedisProxy::class); - $redis->expects('subscriber')->andReturn($subscriber); + $redis = Double::for(RedisProxy::class)->strict(); + $redis->expects('subscriber')->returns($subscriber); $provider = $this->provider($redis); $provider->connect(); @@ -147,10 +158,10 @@ public function testDuplicateConnectCallsRetainOneLifecycleOwner(): void public function testConnectionFailuresContinuePastTheOldRetryLimitAndAreLoggedAtABoundedRate(): void { - $redis = m::mock(RedisProxy::class); + $redis = Double::for(RedisProxy::class)->strict(); $provider = $this->provider($redis); $attempts = 0; - $redis->expects('subscriber')->times(61)->andReturnUsing( + $redis->expects('subscriber')->times(61)->resolves( function () use (&$attempts, $provider): never { ++$attempts; @@ -166,23 +177,23 @@ function () use (&$attempts, $provider): never { $this->waitUntilStopped($provider); $this->assertSame(61, $attempts); - $this->logger->shouldHaveReceived('error') + $this->logger->received('error') ->with('Redis connection failed: redis unavailable') - ->twice(); + ->times(2); } public function testDisconnectDuringSubscriptionDoesNotCommitOrRetry(): void { $subscriber = $this->subscriber(); - $redis = m::mock(RedisProxy::class); + $redis = Double::for(RedisProxy::class)->strict(); $provider = $this->provider($redis); - $subscriber->shouldReceive('subscribe')->once()->with('reverb')->andReturnUsing( + $subscriber->expects('subscribe')->with('reverb')->resolves( function () use ($provider): void { $provider->disconnect(); }, ); $this->expectSubscriberClose($subscriber); - $redis->expects('subscriber')->andReturn($subscriber); + $redis->expects('subscriber')->returns($subscriber); $provider->connect(); $this->waitUntilStopped($provider); @@ -193,31 +204,31 @@ function () use ($provider): void { public function testTransportFailureClosesTheCommittedSubscriberAndRecovers(): void { - $failedMessages = m::mock(Channel::class); - $failedMessages->expects('pop')->andThrow(new RuntimeException('connection lost')); + $failedMessages = Double::for(Channel::class)->strict(); + $failedMessages->expects('pop')->throws(new RuntimeException('connection lost')); $failedSubscriber = $this->subscriber($failedMessages); $failedSubscriber->expects('subscribe')->with('reverb'); $this->expectSubscriberClose($failedSubscriber); $recoveredSubscriber = $this->subscriber(); - $redis = m::mock(RedisProxy::class); + $redis = Double::for(RedisProxy::class)->strict(); $provider = $this->provider($redis); - $recoveredSubscriber->expects('subscribe')->with('reverb')->andReturnUsing( + $recoveredSubscriber->expects('subscribe')->with('reverb')->resolves( function () use ($provider): void { $provider->disconnect(); }, ); $this->expectSubscriberClose($recoveredSubscriber); - $redis->expects('subscriber')->twice()->andReturn($failedSubscriber, $recoveredSubscriber); + $redis->expects('subscriber')->times(2)->returns($failedSubscriber, $recoveredSubscriber); $provider->connect(); $this->waitUntilStopped($provider); $this->assertTrue($failedSubscriber->closed); $this->assertTrue($recoveredSubscriber->closed); - $this->logger->shouldHaveReceived('error') + $this->logger->received('error') ->with('Redis connection failed: connection lost') - ->once(); + ->times(1); } public function testMessageHandlerFailureDoesNotReplaceTheSubscriber(): void @@ -226,32 +237,32 @@ public function testMessageHandlerFailureDoesNotReplaceTheSubscriber(): void $messages->push(new Message('prefix:reverb', 'payload')); $subscriber = $this->subscriber($messages); $subscriber->expects('subscribe')->with('reverb'); - $redis = m::mock(RedisProxy::class); - $redis->expects('subscriber')->andReturn($subscriber); + $redis = Double::for(RedisProxy::class)->strict(); + $redis->expects('subscriber')->returns($subscriber); $provider = $this->provider($redis); $this->expectSubscriberClose($subscriber, $messages); $handlerFailure = new RuntimeException('handler failed'); $provider->messageHandlerForTest() ->expects('handle') ->with('payload') - ->andReturnUsing(function () use ($provider, $handlerFailure): never { + ->resolves(function () use ($provider, $handlerFailure): never { $provider->disconnect(); throw $handlerFailure; }); - $exceptionHandler = m::mock(ExceptionHandler::class); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); $exceptionHandler->expects('report')->with($handlerFailure); $this->app->instance(ExceptionHandler::class, $exceptionHandler); $provider->connect(); $this->waitUntilStopped($provider); - $this->logger->shouldNotHaveReceived('error', ['Redis connection failed: handler failed']); + $this->logger->received('error')->with('Redis connection failed: handler failed')->never(); } public function testRetryWaitWakesWhenTheWorkerExits(): void { - $provider = $this->provider(m::mock(RedisProxy::class)); + $provider = $this->provider(Double::for(RedisProxy::class)->strict()); $provider->useRealRetryWait = true; $result = new Channel(1); @@ -264,8 +275,8 @@ public function testRetryWaitWakesWhenTheWorkerExits(): void public function testPublishUsesIndependentRedisConnectionWithoutSubscriber(): void { - $redis = m::mock(RedisProxy::class); - $redis->expects('publish')->with('reverb', '{"id":1}')->andReturn(3); + [$redis, $client] = $this->publishingConnection(); + $client->expects('publish')->with('reverb', '{"id":1}')->returns(3); $provider = $this->provider($redis); $this->assertSame(3, $provider->publish(['id' => 1])); @@ -275,13 +286,13 @@ public function testPublishUsesIndependentRedisConnectionWithoutSubscriber(): vo public function testPublishFailureDoesNotRetainThePayload(): void { $failure = new RuntimeException('redis unavailable'); - $redis = m::mock(RedisProxy::class); - $redis->expects('publish') + [$redis, $client] = $this->publishingConnection(); + $client->expects('publish') ->with('reverb', '{"id":1}') - ->andThrow($failure); - $redis->expects('publish') + ->throws($failure); + $client->expects('publish') ->with('reverb', '{"id":2}') - ->andReturn(1); + ->returns(1); $provider = $this->provider($redis); try { @@ -296,8 +307,8 @@ public function testPublishFailureDoesNotRetainThePayload(): void public function testPublishPropagatesEncodingFailureWithoutCallingRedis(): void { - $redis = m::mock(RedisProxy::class); - $redis->shouldNotReceive('publish'); + [$redis, $client] = $this->publishingConnection(); + $client->expects('publish')->never(); $provider = $this->provider($redis); $this->expectException(JsonException::class); @@ -305,36 +316,67 @@ public function testPublishPropagatesEncodingFailureWithoutCallingRedis(): void $provider->publish(['invalid' => NAN]); } + /** + * Create a publishing connection through the real native forwarding path. + * + * @return array{RedisProxy, DoubleInterface&Redis} + */ + protected function publishingConnection(): array + { + $client = Double::for(Redis::class)->strict(); + $client->allows('getMode')->returns(Redis::ATOMIC); + $connection = Double::for((new PhpRedisConnectionStub)->setActiveConnection($client))->passthru(); + $connection->allows('release'); + $pool = Double::for(RedisPool::class)->strict(); + $pool->allows('borrow')->returns($connection); + $manager = Double::for(new PoolManager(new Container))->passthru(); + $manager->allows('pool')->with('reverb')->returns($pool); + + return [new RedisProxy($manager, 'reverb', new RedisSentinelFactory), $client]; + } + + /** + * Create a subscriber lifecycle probe. + */ protected function provider(RedisProxy $redis): RedisPubSubProviderProbe { return new RedisPubSubProviderProbe( - m::mock(PubSubIncomingMessageHandler::class), + Double::for(PubSubIncomingMessageHandler::class)->strict(), $redis, 'reverb', ); } + /** + * Create a subscriber with controlled lifecycle state. + */ protected function subscriber(?Channel $messages = null): Subscriber { - $subscriber = m::mock(Subscriber::class); + $subscriber = Double::for(Subscriber::class)->strict(); $subscriber->prefix = 'prefix:'; $subscriber->closed = false; if ($messages !== null) { - $subscriber->allows('channel')->andReturn($messages); + $subscriber->allows('channel')->returns($messages); } return $subscriber; } + /** + * Expect subscriber cleanup and close its message channel. + */ protected function expectSubscriberClose(Subscriber $subscriber, ?Channel $messages = null): void { - $subscriber->expects('close')->andReturnUsing(function () use ($subscriber, $messages): void { + $subscriber->expects('close')->resolves(function () use ($subscriber, $messages): void { $subscriber->closed = true; $messages?->close(); }); } + /** + * Wait for the subscriber lifecycle to finish. + */ protected function waitUntilStopped(RedisPubSubProviderProbe $provider): void { for ($attempt = 0; $attempt < 1000 && $provider->runningForTest(); ++$attempt) { @@ -349,26 +391,41 @@ class RedisPubSubProviderProbe extends RedisPubSubProvider { public bool $useRealRetryWait = false; + /** + * Return the committed subscriber. + */ public function subscriberForTest(): ?Subscriber { return $this->subscriber; } + /** + * Determine whether the lifecycle is running. + */ public function runningForTest(): bool { return $this->running; } + /** + * Return the incoming message handler. + */ public function messageHandlerForTest(): PubSubIncomingMessageHandler { return $this->messageHandler; } + /** + * Wait for the next retry. + */ public function waitBeforeRetryForTest(): bool { return $this->waitBeforeRetry(); } + /** + * Skip retry delays unless the test exercises the real wait. + */ protected function waitBeforeRetry(): bool { return $this->useRealRetryWait diff --git a/tests/Reverb/Servers/Hypervel/Scaling/RedisSharedStateTest.php b/tests/Reverb/Servers/Hypervel/Scaling/RedisSharedStateTest.php index 0e77cd355c..6d530874e0 100644 --- a/tests/Reverb/Servers/Hypervel/Scaling/RedisSharedStateTest.php +++ b/tests/Reverb/Servers/Hypervel/Scaling/RedisSharedStateTest.php @@ -4,16 +4,26 @@ namespace Hypervel\Tests\Reverb\Servers\Hypervel\Scaling; +use Hypervel\Container\Container; +use Hypervel\Redis\Pool\PoolManager; +use Hypervel\Redis\Pool\RedisPool; +use Hypervel\Redis\RedisConnection; use Hypervel\Redis\RedisProxy; +use Hypervel\Redis\RedisSentinelFactory; use Hypervel\Reverb\Servers\Hypervel\Scaling\RedisSharedState; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class RedisSharedStateTest extends TestCase { + use VerifiesDoubles; + public function testRecoveryPatternMatchesGeneratedSharedStateKeysOnly(): void { - $state = new class(m::mock(RedisProxy::class)) extends RedisSharedState { + $state = new class(Double::for(RedisProxy::class)->strict()) extends RedisSharedState { /** * Get the generated shared-state keys. * @@ -50,18 +60,17 @@ public function keysForTest(string $appId, string $channel, string $userId): arr public function testPresenceSubscribeUsesOneAtomicScript(): void { - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function (string $script, array $keys, array $arguments): bool { + [$redis, $connection] = $this->redisConnection(); + $connection->expects('evalWithShaCache') + ->with(Argument::all(function (string $script, array $keys, array $arguments): bool { $this->assertStringContainsString("redis.call('INCR', KEYS[1])", $script); $this->assertStringContainsString("redis.call('INCR', KEYS[2])", $script); $this->assertCount(2, $keys); $this->assertSame([], $arguments); return true; - }) - ->andReturn([1, 1]); + })) + ->returns([1, 1]); $result = (new RedisSharedState($redis))->subscribe('app', 'presence-channel', 'user'); @@ -72,18 +81,17 @@ public function testPresenceSubscribeUsesOneAtomicScript(): void public function testPresenceUnsubscribeUsesOneAtomicScript(): void { - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function (string $script, array $keys, array $arguments): bool { + [$redis, $connection] = $this->redisConnection(); + $connection->expects('evalWithShaCache') + ->with(Argument::all(function (string $script, array $keys, array $arguments): bool { $this->assertStringContainsString("redis.call('DECR', KEYS[1])", $script); $this->assertStringContainsString("redis.call('DECR', KEYS[2])", $script); $this->assertCount(2, $keys); $this->assertSame([], $arguments); return true; - }) - ->andReturn([0, 0]); + })) + ->returns([0, 0]); $result = (new RedisSharedState($redis))->unsubscribe('app', 'presence-channel', 'user'); @@ -92,13 +100,23 @@ public function testPresenceUnsubscribeUsesOneAtomicScript(): void $this->assertSame(0, $result->subscriptionCount); } - public function testLockAcquisitionRequiresTheExactTransformedBoolean(): void + /** + * Create a proxy that forwards script calls to a borrowed connection. + * + * @return array{RedisProxy, DoubleInterface&RedisConnection} + */ + protected function redisConnection(): array { - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('set')->twice()->andReturn(1, true); - $state = new RedisSharedState($redis); - - $this->assertFalse($state->tryCacheMissLock('app', 'channel')); - $this->assertTrue($state->tryCacheMissLock('app', 'channel')); + $connection = Double::for(RedisConnection::class)->strict(); + $connection->allows('getConnection')->returns($connection); + $connection->allows('shouldTransform'); + $connection->allows('getEventDispatcher')->returns(null); + $connection->allows('release'); + $pool = Double::for(RedisPool::class)->strict(); + $pool->allows('borrow')->returns($connection); + $manager = Double::for(new PoolManager(new Container))->passthru(); + $manager->allows('pool')->with('reverb')->returns($pool); + + return [new RedisProxy($manager, 'reverb', new RedisSentinelFactory), $connection]; } } diff --git a/tests/Reverb/Servers/Hypervel/WebSocketHandlerTest.php b/tests/Reverb/Servers/Hypervel/WebSocketHandlerTest.php index e103f18bdf..7bfb838490 100644 --- a/tests/Reverb/Servers/Hypervel/WebSocketHandlerTest.php +++ b/tests/Reverb/Servers/Hypervel/WebSocketHandlerTest.php @@ -7,6 +7,7 @@ use Hypervel\Context\RequestContext; use Hypervel\Http\Request as HttpRequest; use Hypervel\Reverb\Application; +use Hypervel\Reverb\Connection as ReverbConnection; use Hypervel\Reverb\Contracts\ApplicationProvider; use Hypervel\Reverb\Exceptions\InvalidApplication; use Hypervel\Reverb\Protocols\Pusher\Server as PusherServer; @@ -16,10 +17,12 @@ use Hypervel\Routing\Route; use Hypervel\Tests\Reverb\ReverbTestCase; use Hypervel\WebSocketServer\Sender; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use ReflectionClass; use Swoole\Coroutine\Channel; use Swoole\Http\Request as SwooleRequest; +use Swoole\Server; use Swoole\WebSocket\Frame; use Swoole\WebSocket\Server as WebSocketServer; @@ -33,11 +36,14 @@ class WebSocketHandlerTest extends ReverbTestCase protected WebSocketHandler $handler; + /** + * Set up the protocol server and connection handler. + */ protected function setUp(): void { parent::setUp(); - $this->pusherServer = m::mock(PusherServer::class); + $this->pusherServer = Double::for(PusherServer::class)->strict(); $this->applicationProvider = $this->app->make(ApplicationProvider::class); $this->handler = new WebSocketHandler( @@ -49,7 +55,7 @@ protected function setUp(): void public function testInvokeReturns426ForNonWebsocketRequest(): void { - $request = m::mock(HttpRequest::class); + $request = new HttpRequest; $response = ($this->handler)($request, 'reverb-key'); @@ -62,16 +68,16 @@ public function testOnOpenCreatesConnectionAndDelegatesToServer(): void { $this->setupRequestContext('reverb-key'); - $sender = m::mock(Sender::class); + $sender = Double::for(Sender::class)->strict(); $this->app->instance(Sender::class, $sender); - $this->pusherServer->shouldReceive('open')->once() - ->with(m::type(\Hypervel\Reverb\Connection::class)) - ->andReturnUsing(static function (\Hypervel\Reverb\Connection $connection): void { + $this->pusherServer->expects('open') + ->with(Argument::type(ReverbConnection::class)) + ->resolves(static function (ReverbConnection $connection): void { $connection->markEstablished(); }); - $swooleServer = m::mock(WebSocketServer::class); + $swooleServer = Double::for(WebSocketServer::class)->strict(); $swooleRequest = new SwooleRequest; $swooleRequest->fd = 1; @@ -81,7 +87,7 @@ public function testOnOpenCreatesConnectionAndDelegatesToServer(): void $this->assertCount(1, $connections); $this->assertArrayHasKey(1, $connections); $this->assertInstanceOf(ConnectionLifecycle::class, $connections[1]); - $this->assertInstanceOf(\Hypervel\Reverb\Connection::class, $connections[1]->connection()); + $this->assertInstanceOf(ReverbConnection::class, $connections[1]->connection()); } public function testOnOpenRejectsInvalidAppKey(): void @@ -89,18 +95,18 @@ public function testOnOpenRejectsInvalidAppKey(): void $this->setupRequestContext('invalid-key'); // Replace application provider with one that throws - $appProvider = m::mock(ApplicationProvider::class); - $appProvider->shouldReceive('findByKey')->with('invalid-key') - ->andThrow(new InvalidApplication('invalid-key')); + $appProvider = Double::for(ApplicationProvider::class)->strict(); + $appProvider->allows('findByKey')->with('invalid-key') + ->throws(new InvalidApplication('invalid-key')); $handler = new WebSocketHandler($this->app, $this->pusherServer, $appProvider); - $swooleServer = m::mock(WebSocketServer::class); - $swooleServer->shouldReceive('push')->once()->with( + $swooleServer = Double::for(WebSocketServer::class)->strict(); + $swooleServer->expects('push')->with( 1, '{"event":"pusher:error","data":"{\"code\":4001,\"message\":\"Application does not exist\"}"}' ); - $swooleServer->shouldReceive('disconnect')->once()->with(1); + $swooleServer->expects('disconnect')->with(1); $swooleRequest = new SwooleRequest; $swooleRequest->fd = 1; @@ -115,13 +121,13 @@ public function testOnOpenClosesAConnectionRejectedByTheProtocolServer(): void { $this->setupRequestContext('reverb-key'); - $this->app->instance(Sender::class, m::mock(Sender::class)); + $this->app->instance(Sender::class, Double::for(Sender::class)->strict()); - $this->pusherServer->shouldReceive('open')->once(); - $this->pusherServer->shouldReceive('close')->once(); + $this->pusherServer->expects('open'); + $this->pusherServer->expects('close'); - $swooleServer = m::mock(WebSocketServer::class); - $swooleServer->shouldReceive('disconnect')->once()->with(1)->andReturnTrue(); + $swooleServer = Double::for(WebSocketServer::class)->strict(); + $swooleServer->expects('disconnect')->with(1)->returns(true); $swooleRequest = new SwooleRequest; $swooleRequest->fd = 1; @@ -137,12 +143,12 @@ public function testOnCloseWaitsForYieldingOpenAndCleansUpTheAttachedConnection( $application = $this->applicationProvider->findByKey('reverb-key'); $closeStarted = new Channel(1); $closeFinished = new Channel(1); - $swooleServer = m::mock(WebSocketServer::class); - $server = m::mock(\Swoole\Server::class); + $swooleServer = Double::for(WebSocketServer::class)->strict(); + $server = Double::for(Server::class)->strict(); - $provider = m::mock(ApplicationProvider::class); - $provider->shouldReceive('findByKey')->once()->with('reverb-key') - ->andReturnUsing(function () use ($application, $closeStarted, $closeFinished, $server): Application { + $provider = Double::for(ApplicationProvider::class)->strict(); + $provider->expects('findByKey')->with('reverb-key') + ->resolves(function () use ($application, $closeStarted, $closeFinished, $server): Application { go(function () use ($closeStarted, $closeFinished, $server): void { $closeStarted->push(true); $this->handler->onClose($server, 1, 0); @@ -159,13 +165,13 @@ public function testOnCloseWaitsForYieldingOpenAndCleansUpTheAttachedConnection( }); $handler = new WebSocketHandler($this->app, $this->pusherServer, $provider); - $this->app->instance(Sender::class, m::mock(Sender::class)); - $this->pusherServer->shouldReceive('open')->once() - ->andReturnUsing(static function (\Hypervel\Reverb\Connection $connection): void { + $this->app->instance(Sender::class, Double::for(Sender::class)->strict()); + $this->pusherServer->expects('open') + ->resolves(static function (ReverbConnection $connection): void { $connection->markEstablished(); }); - $this->pusherServer->shouldReceive('close')->once() - ->with(m::type(\Hypervel\Reverb\Connection::class)); + $this->pusherServer->expects('close') + ->with(Argument::type(ReverbConnection::class)); $swooleRequest = new SwooleRequest; $swooleRequest->fd = 1; @@ -180,10 +186,10 @@ public function testOnMessageDelegatesTextFrameToServer(): void { $connection = $this->createStoredConnection(1); - $this->pusherServer->shouldReceive('message')->once() + $this->pusherServer->expects('message') ->with($connection, '{"event":"pusher:ping"}'); - $swooleServer = m::mock(WebSocketServer::class); + $swooleServer = Double::for(WebSocketServer::class)->strict(); $frame = new Frame; $frame->fd = 1; @@ -198,10 +204,10 @@ public function testOnMessageRejectsOversizedMessage(): void $connection = $this->createStoredConnection(1); // The message should NOT reach PusherServer - $this->pusherServer->shouldNotReceive('message'); + $this->pusherServer->expects('message')->never(); - $swooleServer = m::mock(WebSocketServer::class); - $swooleServer->shouldReceive('push')->once() + $swooleServer = Double::for(WebSocketServer::class)->strict(); + $swooleServer->expects('push') ->with(1, 'Maximum message size exceeded'); $frame = new Frame; @@ -217,11 +223,11 @@ public function testOnMessageHandlesPingControlFrame(): void { $connection = $this->createStoredConnection(1); - $this->pusherServer->shouldReceive('control')->once() + $this->pusherServer->expects('control') ->with($connection, WEBSOCKET_OPCODE_PING); - $swooleServer = m::mock(WebSocketServer::class); - $swooleServer->shouldReceive('push')->once() + $swooleServer = Double::for(WebSocketServer::class)->strict(); + $swooleServer->expects('push') ->with(1, '', WEBSOCKET_OPCODE_PONG); $frame = new Frame; @@ -235,12 +241,12 @@ public function testOnMessageHandlesPongControlFrame(): void { $connection = $this->createStoredConnection(1); - $this->pusherServer->shouldReceive('control')->once() + $this->pusherServer->expects('control') ->with($connection, WEBSOCKET_OPCODE_PONG); - $swooleServer = m::mock(WebSocketServer::class); + $swooleServer = Double::for(WebSocketServer::class)->strict(); // No pong response should be sent for pong frames - $swooleServer->shouldNotReceive('push'); + $swooleServer->expects('push')->never(); $frame = new Frame; $frame->fd = 1; @@ -251,10 +257,10 @@ public function testOnMessageHandlesPongControlFrame(): void public function testOnMessageIgnoresUnknownFd(): void { - $this->pusherServer->shouldNotReceive('message'); - $this->pusherServer->shouldNotReceive('control'); + $this->pusherServer->expects('message')->never(); + $this->pusherServer->expects('control')->never(); - $swooleServer = m::mock(WebSocketServer::class); + $swooleServer = Double::for(WebSocketServer::class)->strict(); $frame = new Frame; $frame->fd = 999; @@ -268,9 +274,9 @@ public function testOnCloseDelegatesToServerAndCleansUp(): void { $connection = $this->createStoredConnection(1); - $this->pusherServer->shouldReceive('close')->once()->with($connection); + $this->pusherServer->expects('close')->with($connection); - $swooleServer = m::mock(\Swoole\Server::class); + $swooleServer = Double::for(Server::class)->strict(); $this->handler->onClose($swooleServer, 1, 0); @@ -279,9 +285,9 @@ public function testOnCloseDelegatesToServerAndCleansUp(): void public function testOnCloseIgnoresUnknownFd(): void { - $this->pusherServer->shouldNotReceive('close'); + $this->pusherServer->expects('close')->never(); - $swooleServer = m::mock(\Swoole\Server::class); + $swooleServer = Double::for(Server::class)->strict(); // Should not throw — just a no-op $this->handler->onClose($swooleServer, 999, 0); @@ -300,16 +306,16 @@ public function testFlushStateClearsConnections(): void } /** - * Set up RequestContext with a mocked HttpRequest that has route parameters. + * Set up RequestContext with the application route parameter. */ private function setupRequestContext(string $appKey): void { - $route = m::mock(Route::class); - $route->shouldReceive('parameter')->with('appKey')->andReturn($appKey); + $route = Double::for(Route::class)->strict(); + $route->allows('parameter')->with('appKey')->returns($appKey); - $request = m::mock(HttpRequest::class); - $request->shouldReceive('route')->andReturn($route); - $request->headers = new \Symfony\Component\HttpFoundation\HeaderBag(['Origin' => 'http://localhost']); + $request = new HttpRequest; + $request->setRouteResolver(fn (): Route => $route); + $request->headers->set('Origin', 'http://localhost'); RequestContext::set($request); } @@ -317,16 +323,16 @@ private function setupRequestContext(string $appKey): void /** * Create a Reverb Connection and store it in the handler's static map. */ - private function createStoredConnection(int $fd): \Hypervel\Reverb\Connection + private function createStoredConnection(int $fd): ReverbConnection { $app = $this->app->make(ApplicationProvider::class)->all()->first(); $wsConnection = new Connection( - m::mock(Sender::class)->shouldIgnoreMissing(), + Double::for(Sender::class)->strict(), $fd, ); - $connection = new \Hypervel\Reverb\Connection($wsConnection, $app, 'http://localhost'); + $connection = new ReverbConnection($wsConnection, $app, 'http://localhost'); $connection->markEstablished(); $lifecycle = new ConnectionLifecycle($fd); diff --git a/tests/Reverb/Webhooks/DeferredWebhookManagerTest.php b/tests/Reverb/Webhooks/DeferredWebhookManagerTest.php index 8f3180982e..7c7d63be99 100644 --- a/tests/Reverb/Webhooks/DeferredWebhookManagerTest.php +++ b/tests/Reverb/Webhooks/DeferredWebhookManagerTest.php @@ -12,7 +12,7 @@ use Hypervel\Reverb\Webhooks\Jobs\WebhookDeliveryJob; use Hypervel\Support\Facades\Queue; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; use ReflectionProperty; class DeferredWebhookManagerTest extends ReverbTestCase @@ -21,6 +21,9 @@ class DeferredWebhookManagerTest extends ReverbTestCase protected Application $testApp; + /** + * Set up the deferred webhook manager. + */ protected function setUp(): void { parent::setUp(); @@ -50,13 +53,12 @@ public function testChannelVacatedFiresAfterDelay(): void $callback = null; $this->captureDeferredCallback(10, $callback); - $sharedState = m::mock(SharedState::class); - $sharedState->shouldReceive('getSubscriptionCount') + $sharedState = Double::for(SharedState::class)->strict(); + $sharedState->allows('getSubscriptionCount') ->with('test-app', 'test-channel') - ->andReturn(0); - $sharedState->shouldReceive('clearSmoothingPending') - ->with('test-app', 'test-channel', 5000) - ->once(); + ->returns(0); + $sharedState->expects('clearSmoothingPending') + ->with('test-app', 'test-channel', 5000); $this->app->instance(SharedState::class, $sharedState); $this->manager->deferChannelVacated($this->testApp, 'test-channel', 0.05, 5000); @@ -73,8 +75,8 @@ public function testChannelVacatedFiresAfterDelay(): void public function testChannelVacatedSuppressedOnCancel(): void { $timer = $this->replaceTimer(); - $timer->shouldReceive('after')->once()->andReturn(11); - $timer->shouldReceive('clear')->with(11)->once(); + $timer->expects('after')->returns(11); + $timer->expects('clear')->with(11); $this->manager->deferChannelVacated($this->testApp, 'test-channel', 0.05, 5000); @@ -88,13 +90,12 @@ public function testChannelVacatedSuppressedWhenReOccupied(): void $callback = null; $this->captureDeferredCallback(13, $callback); - $sharedState = m::mock(SharedState::class); - $sharedState->shouldReceive('getSubscriptionCount') + $sharedState = Double::for(SharedState::class)->strict(); + $sharedState->allows('getSubscriptionCount') ->with('test-app', 'test-channel') - ->andReturn(1); // Client reconnected - $sharedState->shouldReceive('clearSmoothingPending') - ->with('test-app', 'test-channel', 5000) - ->once(); + ->returns(1); // Client reconnected + $sharedState->expects('clearSmoothingPending') + ->with('test-app', 'test-channel', 5000); $this->app->instance(SharedState::class, $sharedState); $this->manager->deferChannelVacated($this->testApp, 'test-channel', 0.05, 5000); @@ -114,13 +115,12 @@ public function testMemberRemovedFiresAfterDelay(): void $callback = null; $this->captureDeferredCallback(14, $callback); - $sharedState = m::mock(SharedState::class); - $sharedState->shouldReceive('getUserSubscriptionCount') + $sharedState = Double::for(SharedState::class)->strict(); + $sharedState->allows('getUserSubscriptionCount') ->with('test-app', 'presence-test', 'user-1') - ->andReturn(0); - $sharedState->shouldReceive('clearMemberSmoothingPending') - ->with('test-app', 'presence-test', 'user-1', 5000) - ->once(); + ->returns(0); + $sharedState->expects('clearMemberSmoothingPending') + ->with('test-app', 'presence-test', 'user-1', 5000); $this->app->instance(SharedState::class, $sharedState); $this->manager->deferMemberRemoved($this->testApp, 'presence-test', 'user-1', 0.05, 5000); @@ -140,8 +140,8 @@ public function testMemberRemovedFiresAfterDelay(): void public function testMemberRemovedSuppressedOnCancel(): void { $timer = $this->replaceTimer(); - $timer->shouldReceive('after')->once()->andReturn(12); - $timer->shouldReceive('clear')->with(12)->once(); + $timer->expects('after')->returns(12); + $timer->expects('clear')->with(12); $this->manager->deferMemberRemoved($this->testApp, 'presence-test', 'user-1', 0.05, 5000); @@ -155,13 +155,12 @@ public function testMemberRemovedSuppressedWhenUserReturned(): void $callback = null; $this->captureDeferredCallback(15, $callback); - $sharedState = m::mock(SharedState::class); - $sharedState->shouldReceive('getUserSubscriptionCount') + $sharedState = Double::for(SharedState::class)->strict(); + $sharedState->allows('getUserSubscriptionCount') ->with('test-app', 'presence-test', 'user-1') - ->andReturn(1); // User reconnected - $sharedState->shouldReceive('clearMemberSmoothingPending') - ->with('test-app', 'presence-test', 'user-1', 5000) - ->once(); + ->returns(1); // User reconnected + $sharedState->expects('clearMemberSmoothingPending') + ->with('test-app', 'presence-test', 'user-1', 5000); $this->app->instance(SharedState::class, $sharedState); $this->manager->deferMemberRemoved($this->testApp, 'presence-test', 'user-1', 0.05, 5000); @@ -178,10 +177,10 @@ public function testMemberRemovedSuppressedWhenUserReturned(): void public function testCancelAllClearsAllPendingTimers(): void { $timer = $this->replaceTimer(); - $timer->shouldReceive('after')->times(3)->andReturn(1, 2, 3); - $timer->shouldReceive('clear')->with(1)->once(); - $timer->shouldReceive('clear')->with(2)->once(); - $timer->shouldReceive('clear')->with(3)->once(); + $timer->expects('after')->times(3)->returns(1, 2, 3); + $timer->expects('clear')->with(1); + $timer->expects('clear')->with(2); + $timer->expects('clear')->with(3); $this->manager->deferChannelVacated($this->testApp, 'channel-a', 0.05, 5000); $this->manager->deferChannelVacated($this->testApp, 'channel-b', 0.05, 5000); @@ -199,7 +198,7 @@ public function testCancelAllClearsAllPendingTimers(): void */ protected function replaceTimer(): Timer { - $timer = m::mock(Timer::class); + $timer = Double::for(Timer::class)->strict(); (new ReflectionProperty($this->manager, 'timer'))->setValue($this->manager, $timer); @@ -212,9 +211,8 @@ protected function replaceTimer(): Timer protected function captureDeferredCallback(int $timerId, ?Closure &$callback): void { $timer = $this->replaceTimer(); - $timer->shouldReceive('after') - ->once() - ->andReturnUsing(function (float $timeout, Closure $deferredCallback) use ($timerId, &$callback): int { + $timer->expects('after') + ->resolves(function (float $timeout, Closure $deferredCallback) use ($timerId, &$callback): int { $callback = $deferredCallback; return $timerId; diff --git a/tests/Reverb/Webhooks/HttpWebhookDispatcherTest.php b/tests/Reverb/Webhooks/HttpWebhookDispatcherTest.php index 2340e52c1d..9502fb57cd 100644 --- a/tests/Reverb/Webhooks/HttpWebhookDispatcherTest.php +++ b/tests/Reverb/Webhooks/HttpWebhookDispatcherTest.php @@ -14,8 +14,10 @@ use Hypervel\Reverb\Webhooks\WebhookBatchBuffer; use Hypervel\Reverb\Webhooks\WebhookPayload; use Hypervel\Support\Facades\Queue; +use Hypervel\Tests\Reverb\Fixtures\FakeConnection; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -116,7 +118,7 @@ public function testClientEventIncludesSocketIdAndStringifiedData(): void 'url' => 'https://example.com/webhook', 'events' => ['client_event'], ])); - $connection = new \Hypervel\Tests\Reverb\Fixtures\FakeConnection; + $connection = new FakeConnection; $dispatcher = new HttpWebhookDispatcher; $dispatcher->dispatch($app, 'client_event', [ @@ -324,11 +326,10 @@ public function testBatchingAppendsToBufferAndSchedulesFlush(): void { Queue::fake([FlushWebhookBatchJob::class]); - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->shouldReceive('appendAndCheckSchedule') - ->once() - ->with('app-1', m::type('array')) - ->andReturn(true); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->expects('appendAndCheckSchedule') + ->with('app-1', Argument::type('array')) + ->returns(true); $this->app->instance(WebhookBatchBuffer::class, $buffer); $app = $this->makeApp(webhooks: array_replace($this->webhookConfig(), [ @@ -357,10 +358,9 @@ public function testBatchingDoesNotScheduleFlushWhenLockAlreadyHeld(): void { Queue::fake([FlushWebhookBatchJob::class]); - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->shouldReceive('appendAndCheckSchedule') - ->once() - ->andReturn(false); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->expects('appendAndCheckSchedule') + ->returns(false); $this->app->instance(WebhookBatchBuffer::class, $buffer); $app = $this->makeApp(webhooks: array_replace($this->webhookConfig(), [ @@ -380,17 +380,17 @@ public function testBatchingDoesNotScheduleFlushWhenLockAlreadyHeld(): void public function testBatchingClearsANewlyOwnedLockWhenQueueDispatchFails(): void { - $buffer = m::mock(WebhookBatchBuffer::class); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); $buffer->expects('appendAndCheckSchedule') - ->with('app-1', m::type('array')) - ->andReturnTrue(); + ->with('app-1', Argument::type('array')) + ->returns(true); $buffer->expects('clearFlushLock')->with('app-1'); $this->app->instance(WebhookBatchBuffer::class, $buffer); $failure = new RuntimeException('Queue dispatch failed.'); - $bus = m::mock(BusDispatcher::class); + $bus = Double::for(BusDispatcher::class)->strict(); $bus->expects('dispatch') - ->with(m::type(FlushWebhookBatchJob::class)) - ->andThrow($failure); + ->with(Argument::type(FlushWebhookBatchJob::class)) + ->throws($failure); $this->app->instance(BusDispatcher::class, $bus); $app = $this->makeApp(webhooks: array_replace($this->webhookConfig(), [ 'url' => 'https://example.com/webhook', @@ -401,7 +401,7 @@ public function testBatchingClearsANewlyOwnedLockWhenQueueDispatchFails(): void ])); $dispatcher = new HttpWebhookDispatcher; - $exceptionHandler = m::mock(ExceptionHandler::class); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); $exceptionHandler->expects('report')->with($failure); $this->app->instance(ExceptionHandler::class, $exceptionHandler); @@ -413,14 +413,14 @@ public function testBatchingClearsANewlyOwnedLockWhenQueueDispatchFails(): void public function testBufferFailuresAreReportedAndCancellationPropagates(bool $cancel): void { $failure = $cancel ? new CanceledException : new RuntimeException('Buffer unavailable.'); - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->expects('appendAndCheckSchedule')->andThrow($failure); - $buffer->shouldNotReceive('clearFlushLock'); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->expects('appendAndCheckSchedule')->throws($failure); + $buffer->expects('clearFlushLock')->never(); $this->app->instance(WebhookBatchBuffer::class, $buffer); - $exceptionHandler = m::mock(ExceptionHandler::class); + $exceptionHandler = Double::for(ExceptionHandler::class)->strict(); if ($cancel) { - $exceptionHandler->shouldNotReceive('report'); + $exceptionHandler->expects('report')->never(); $this->expectExceptionObject($failure); } else { $exceptionHandler->expects('report')->with($failure); @@ -437,12 +437,12 @@ public function testBufferFailuresAreReportedAndCancellationPropagates(bool $can public function testBatchingDoesNotClearALockOwnedByAnotherDispatch(): void { - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->expects('appendAndCheckSchedule')->andReturnFalse(); - $buffer->shouldNotReceive('clearFlushLock'); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->expects('appendAndCheckSchedule')->returns(false); + $buffer->expects('clearFlushLock')->never(); $this->app->instance(WebhookBatchBuffer::class, $buffer); - $bus = m::mock(BusDispatcher::class); - $bus->shouldNotReceive('dispatch'); + $bus = Double::for(BusDispatcher::class)->strict(); + $bus->expects('dispatch')->never(); $this->app->instance(BusDispatcher::class, $bus); $app = $this->makeApp(webhooks: array_replace($this->webhookConfig(), [ 'url' => 'https://example.com/webhook', @@ -457,8 +457,6 @@ public function testBatchingDoesNotClearALockOwnedByAnotherDispatch(): void 'channel_occupied', ['channel' => 'test-channel'], ); - - $this->addToAssertionCount(1); } public function testImmediateDispatchWhenBatchingDisabled(): void @@ -487,11 +485,11 @@ public function testImmediateWebhooksAreHandedToTheBoundSender(): void 'url' => 'https://example.com/webhook', 'events' => ['channel_occupied'], ])); - $sender = m::mock(WebhookSender::class); + $sender = Double::for(WebhookSender::class)->strict(); $sender->expects('send')->with( $app, $app->webhooks(), - m::on(static fn (WebhookPayload $payload): bool => $payload->events === [ + Argument::satisfies(static fn (WebhookPayload $payload): bool => $payload->events === [ ['name' => 'channel_occupied', 'channel' => 'test-channel'], ]), ); diff --git a/tests/Reverb/Webhooks/Jobs/FlushWebhookBatchJobTest.php b/tests/Reverb/Webhooks/Jobs/FlushWebhookBatchJobTest.php index ed2854ab99..640d3cb4f0 100644 --- a/tests/Reverb/Webhooks/Jobs/FlushWebhookBatchJobTest.php +++ b/tests/Reverb/Webhooks/Jobs/FlushWebhookBatchJobTest.php @@ -12,11 +12,15 @@ use Hypervel\Reverb\Webhooks\WebhookPayload; use Hypervel\Support\Facades\Queue; use Hypervel\Tests\Reverb\ReverbTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use RuntimeException; class FlushWebhookBatchJobTest extends ReverbTestCase { + /** + * Fake webhook delivery and flush jobs. + */ protected function setUp(): void { parent::setUp(); @@ -26,9 +30,9 @@ protected function setUp(): void public function testClearsDebounceBeforeClaiming(): void { - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->shouldReceive('clearFlushLock')->with('123456')->once()->ordered(); - $buffer->shouldReceive('claim')->once()->ordered()->andReturnNull(); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->expects('clearFlushLock')->with('123456')->ordered(); + $buffer->expects('claim')->ordered()->returns(null); $this->app->instance(WebhookBatchBuffer::class, $buffer); $job = new FlushWebhookBatchJob('123456', $this->defaultWebhookConfig()); @@ -38,11 +42,11 @@ public function testClearsDebounceBeforeClaiming(): void public function testDeliversTheClaimedBatchAndAcknowledgesItsClaim(): void { $batch = $this->claimedBatch(); - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->shouldReceive('clearFlushLock'); - $buffer->shouldReceive('claim')->andReturn($batch); - $buffer->shouldReceive('acknowledge')->with('123456', 'claim-token')->once(); - $buffer->shouldReceive('hasRemaining')->andReturn(false); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->allows('clearFlushLock'); + $buffer->allows('claim')->returns($batch); + $buffer->expects('acknowledge')->with('123456', 'claim-token'); + $buffer->allows('hasRemaining')->returns(false); $this->app->instance(WebhookBatchBuffer::class, $buffer); $job = new FlushWebhookBatchJob('123456', $this->defaultWebhookConfig()); @@ -57,14 +61,14 @@ public function testHandsTheClaimedBatchToTheBoundSender(): void { $batch = $this->claimedBatch(); $config = $this->defaultWebhookConfig(); - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->shouldReceive('clearFlushLock'); - $buffer->shouldReceive('claim')->andReturn($batch); - $buffer->shouldReceive('acknowledge')->with('123456', 'claim-token')->once(); - $buffer->shouldReceive('hasRemaining')->andReturn(false); - $sender = m::mock(WebhookSender::class); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->allows('clearFlushLock'); + $buffer->allows('claim')->returns($batch); + $buffer->expects('acknowledge')->with('123456', 'claim-token'); + $buffer->allows('hasRemaining')->returns(false); + $sender = Double::for(WebhookSender::class)->strict(); $sender->expects('send')->with( - m::on(static fn (Application $application): bool => $application->id() === '123456'), + Argument::satisfies(static fn (Application $application): bool => $application->id() === '123456'), $config, $batch['payload'], ); @@ -78,13 +82,13 @@ public function testHandsTheClaimedBatchToTheBoundSender(): void public function testFailedSendKeepsTheClaimForRecovery(): void { $failure = new RuntimeException('The sender could not accept the batch.'); - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->shouldReceive('clearFlushLock'); - $buffer->shouldReceive('claim')->andReturn($this->claimedBatch()); - $buffer->shouldNotReceive('acknowledge'); - $buffer->shouldNotReceive('hasRemaining'); - $sender = m::mock(WebhookSender::class); - $sender->expects('send')->andThrow($failure); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->allows('clearFlushLock'); + $buffer->allows('claim')->returns($this->claimedBatch()); + $buffer->expects('acknowledge')->never(); + $buffer->expects('hasRemaining')->never(); + $sender = Double::for(WebhookSender::class)->strict(); + $sender->expects('send')->throws($failure); $job = new FlushWebhookBatchJob('123456', $this->defaultWebhookConfig()); @@ -100,10 +104,10 @@ public function testFailedSendKeepsTheClaimForRecovery(): void public function testBailsWhenClaimReturnsEmpty(): void { - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->shouldReceive('clearFlushLock'); - $buffer->shouldReceive('claim')->andReturnNull(); - $buffer->shouldNotReceive('acknowledge'); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->allows('clearFlushLock'); + $buffer->allows('claim')->returns(null); + $buffer->expects('acknowledge')->never(); $this->app->instance(WebhookBatchBuffer::class, $buffer); $job = new FlushWebhookBatchJob('123456', $this->defaultWebhookConfig()); @@ -114,11 +118,11 @@ public function testBailsWhenClaimReturnsEmpty(): void public function testReschedulesWhenItemsRemain(): void { - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->shouldReceive('clearFlushLock'); - $buffer->shouldReceive('claim')->andReturn($this->claimedBatch()); - $buffer->shouldReceive('acknowledge'); - $buffer->shouldReceive('hasRemaining')->andReturn(true); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->allows('clearFlushLock'); + $buffer->allows('claim')->returns($this->claimedBatch()); + $buffer->allows('acknowledge'); + $buffer->allows('hasRemaining')->returns(true); $this->app->instance(WebhookBatchBuffer::class, $buffer); $job = new FlushWebhookBatchJob('123456', $this->defaultWebhookConfig()); @@ -129,11 +133,11 @@ public function testReschedulesWhenItemsRemain(): void public function testDoesNotRescheduleWhenBufferEmpty(): void { - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->shouldReceive('clearFlushLock'); - $buffer->shouldReceive('claim')->andReturn($this->claimedBatch()); - $buffer->shouldReceive('acknowledge'); - $buffer->shouldReceive('hasRemaining')->andReturn(false); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->allows('clearFlushLock'); + $buffer->allows('claim')->returns($this->claimedBatch()); + $buffer->allows('acknowledge'); + $buffer->allows('hasRemaining')->returns(false); $this->app->instance(WebhookBatchBuffer::class, $buffer); $job = new FlushWebhookBatchJob('123456', $this->defaultWebhookConfig()); @@ -144,11 +148,11 @@ public function testDoesNotRescheduleWhenBufferEmpty(): void public function testUsesAppKeyAndSecretForSigning(): void { - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->shouldReceive('clearFlushLock'); - $buffer->shouldReceive('claim')->andReturn($this->claimedBatch()); - $buffer->shouldReceive('acknowledge'); - $buffer->shouldReceive('hasRemaining')->andReturn(false); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->allows('clearFlushLock'); + $buffer->allows('claim')->returns($this->claimedBatch()); + $buffer->allows('acknowledge'); + $buffer->allows('hasRemaining')->returns(false); $this->app->instance(WebhookBatchBuffer::class, $buffer); $job = new FlushWebhookBatchJob('123456', $this->defaultWebhookConfig()); @@ -162,11 +166,11 @@ public function testUsesAppKeyAndSecretForSigning(): void public function testPassesCustomHeadersToDeliveryJob(): void { - $buffer = m::mock(WebhookBatchBuffer::class); - $buffer->shouldReceive('clearFlushLock'); - $buffer->shouldReceive('claim')->andReturn($this->claimedBatch()); - $buffer->shouldReceive('acknowledge'); - $buffer->shouldReceive('hasRemaining')->andReturn(false); + $buffer = Double::for(WebhookBatchBuffer::class)->strict(); + $buffer->allows('clearFlushLock'); + $buffer->allows('claim')->returns($this->claimedBatch()); + $buffer->allows('acknowledge'); + $buffer->allows('hasRemaining')->returns(false); $this->app->instance(WebhookBatchBuffer::class, $buffer); $config = $this->defaultWebhookConfig(); diff --git a/tests/Routing/ImplicitRouteBindingTest.php b/tests/Routing/ImplicitRouteBindingTest.php index 3899db3af5..ddbc0ccb47 100644 --- a/tests/Routing/ImplicitRouteBindingTest.php +++ b/tests/Routing/ImplicitRouteBindingTest.php @@ -21,14 +21,18 @@ use Hypervel\Tests\Routing\Fixtures\CategoryBackedEnum; use Hypervel\Tests\Routing\Fixtures\CategoryEnum; use Hypervel\Tests\Routing\RoutingTestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionProperty; use WeakMap; class ImplicitRouteBindingTest extends RoutingTestCase { + use VerifiesDoubles; + public function testItDoesNotInspectTheActionWhenTheRouteHasNoParameters(): void { $route = new EmptyParameterRoute('GET', '/test', fn () => 'ok'); @@ -154,12 +158,12 @@ public function testItThrowsModelNotFoundExceptionOnInvalidValueException(bool $ { Model::reportRouteModelBindingExceptions($shouldReport); - $mock = m::mock(ExceptionHandler::class); + $mock = Double::for(ExceptionHandler::class)->strict(); if ($shouldReport) { - $mock->shouldReceive('report')->once()->with(m::type(InvalidValueException::class), []); + $mock->expects('report')->with(Argument::type(InvalidValueException::class), []); } else { - $mock->shouldReceive('report')->never(); + $mock->expects('report')->never(); } $container = Container::getInstance(); @@ -187,8 +191,8 @@ public static function shouldReportProvider(): array public function testItDoesNotConvertUnrelatedQueryExceptions(): void { - $mock = m::mock(ExceptionHandler::class); - $mock->shouldReceive('report')->never(); + $mock = Double::for(ExceptionHandler::class)->strict(); + $mock->expects('report')->never(); $container = Container::getInstance(); $container->instance(ExceptionHandler::class, $mock); @@ -206,8 +210,8 @@ public function testItDoesNotConvertUnrelatedQueryExceptions(): void public function testItConvertsInvalidValueExceptionsFromNonModelBindings(): void { - $mock = m::mock(ExceptionHandler::class); - $mock->shouldReceive('report')->once()->with(m::type(InvalidValueException::class), []); + $mock = Double::for(ExceptionHandler::class)->strict(); + $mock->expects('report')->with(Argument::type(InvalidValueException::class), []); $container = Container::getInstance(); $container->instance(ExceptionHandler::class, $mock); diff --git a/tests/Routing/RoutingPipelineTest.php b/tests/Routing/RoutingPipelineTest.php index 41708fd2f9..b60987245e 100644 --- a/tests/Routing/RoutingPipelineTest.php +++ b/tests/Routing/RoutingPipelineTest.php @@ -11,20 +11,24 @@ use Hypervel\Http\Response; use Hypervel\Routing\Pipeline; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use RuntimeException; use Throwable; class RoutingPipelineTest extends TestCase { + use VerifiesDoubles; + public function testReportingFailureRetainsTheOriginalException(): void { $original = new RuntimeException('original'); $failure = new LogicException('reporting failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->expects('report')->with($original)->andThrow($failure); - $handler->shouldNotReceive('render'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($original)->throws($failure); + $handler->expects('render')->never(); $caught = $this->handleAndCatch($handler, $original); @@ -36,9 +40,9 @@ public function testRenderingFailureRetainsTheOriginalException(): void { $original = new RuntimeException('original'); $failure = new LogicException('rendering failed'); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $handler->expects('report')->with($original); - $handler->expects('render')->with(m::type(Request::class), $original)->andThrow($failure); + $handler->expects('render')->with(Argument::type(Request::class), $original)->throws($failure); $caught = $this->handleAndCatch($handler, $original); @@ -51,8 +55,8 @@ public function testHandlingFailureRetainsItsExistingChainBeforeTheOriginalExcep $original = new RuntimeException('original'); $existing = new DomainException('existing'); $failure = new LogicException('reporting failed', previous: $existing); - $handler = m::mock(ExceptionHandler::class); - $handler->expects('report')->with($original)->andThrow($failure); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($original)->throws($failure); $caught = $this->handleAndCatch($handler, $original); @@ -64,8 +68,8 @@ public function testHandlingFailureRetainsItsExistingChainBeforeTheOriginalExcep public function testRethrowingTheOriginalExceptionDoesNotCreateASelfReferentialChain(): void { $original = new RuntimeException('original'); - $handler = m::mock(ExceptionHandler::class); - $handler->expects('report')->with($original)->andThrow($original); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($original)->throws($original); $caught = $this->handleAndCatch($handler, $original); @@ -77,9 +81,9 @@ public function testSuccessfulHandlingReturnsTheRenderedResponse(): void { $original = new RuntimeException('original'); $response = new Response('handled', 500); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $handler->expects('report')->with($original); - $handler->expects('render')->with(m::type(Request::class), $original)->andReturn($response); + $handler->expects('render')->with(Argument::type(Request::class), $original)->returns($response); $this->assertSame($response, $this->pipeline($handler)->handleThrowable(new Request, $original)); } diff --git a/tests/Saloon/Cache/Feature/CacheTest.php b/tests/Saloon/Cache/Feature/CacheTest.php index cc3a84f9c3..b84083a69f 100644 --- a/tests/Saloon/Cache/Feature/CacheTest.php +++ b/tests/Saloon/Cache/Feature/CacheTest.php @@ -11,8 +11,8 @@ use GuzzleHttp\Psr7\Utils; use Hypervel\Cache\ArrayStore; use Hypervel\Cache\Repository; +use Hypervel\Config\Repository as ConfigRepository; use Hypervel\Contracts\Cache\Factory as CacheFactory; -use Hypervel\Contracts\Config\Repository as ConfigRepository; use Hypervel\Contracts\Foundation\Application as ApplicationContract; use Hypervel\Events\Dispatcher; use Hypervel\Http\Client\Factory; @@ -49,7 +49,8 @@ use Hypervel\Tests\Saloon\Cache\Fixtures\Requests\CustomKeyCachedUserRequest; use Hypervel\Tests\Saloon\Cache\Fixtures\Requests\ShortLivedCachedUserRequest; use Hypervel\Tests\Saloon\Fixtures\Connectors\TestConnector; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Psr\Http\Message\StreamInterface; use stdClass; @@ -59,6 +60,8 @@ // testARequestWithTheHasCachingTraitWillCacheTheResponse. class CacheTest extends TestCase { + use VerifiesDoubles; + /** * Get the package providers. */ @@ -594,8 +597,7 @@ public function testCacheMissResolvesTransportConfigurationOnce(): void $http = new Factory; $http->registerConnection('saloon'); $http->fake(['*' => Factory::response(['ok' => true])]); - $senderConfig = m::mock(ConfigRepository::class); - $senderConfig->shouldReceive('string')->with('saloon.connection.name')->andReturn('saloon'); + $senderConfig = new ConfigRepository(['saloon' => ['connection' => ['name' => 'saloon']]]); $sender = new CountingCacheSender($http, $senderConfig); $this->manager($http, sender: $sender)->send(new CacheConnectorStub, new CacheRequestStub); @@ -756,8 +758,8 @@ public function testDefaultBodyIdentityRestoresSeekableStreamsAndRejectsUnsafeIn $this->assertSame(2, $pendingRequest->preparedBody()?->tell()); - $nonSeekable = m::mock(StreamInterface::class); - $nonSeekable->shouldReceive('isSeekable')->andReturn(false); + $nonSeekable = Double::for(StreamInterface::class)->strict(); + $nonSeekable->allows('isSeekable')->returns(false); $unsafe = $this->pending(new CacheConnectorStub, new CacheStreamRequestStub($nonSeekable)); try { @@ -810,16 +812,17 @@ protected function http(): Factory */ protected function manager(Factory $http, ?Dispatcher $events = null, ?Sender $sender = null): SaloonManager { - $cache = m::mock(CacheFactory::class); - $cache->shouldReceive('store')->with(null)->andReturn(new Repository(new ArrayStore)); - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('string')->with('saloon.connection.name')->andReturn('saloon'); - $config->shouldReceive('get')->with('saloon.cache.store')->andReturn(null); + $cache = Double::for(CacheFactory::class)->strict(); + $cache->allows('store')->with(null)->returns(new Repository(new ArrayStore)); + $config = new ConfigRepository(['saloon' => [ + 'connection' => ['name' => 'saloon'], + 'cache' => ['store' => null], + ]]); return new SaloonManager( $sender ?? new Sender($http, $config), $cache, - m::mock(RateLimiter::class), + Double::for(RateLimiter::class, override: true)->strict()->instance(), $config, $events ?? new Dispatcher, ); diff --git a/tests/Saloon/CoroutineIsolationTest.php b/tests/Saloon/CoroutineIsolationTest.php index ca821fb656..550bbaa6a7 100644 --- a/tests/Saloon/CoroutineIsolationTest.php +++ b/tests/Saloon/CoroutineIsolationTest.php @@ -4,8 +4,8 @@ namespace Hypervel\Tests\Saloon; +use Hypervel\Config\Repository as ConfigRepository; use Hypervel\Contracts\Cache\Factory as CacheFactory; -use Hypervel\Contracts\Config\Repository as ConfigRepository; use Hypervel\Events\Dispatcher; use Hypervel\Http\Client\Factory; use Hypervel\RateLimiter\RateLimiter; @@ -18,23 +18,25 @@ use Hypervel\Saloon\Http\Sender; use Hypervel\Saloon\SaloonManager; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use function Hypervel\Coroutine\parallel; class CoroutineIsolationTest extends TestCase { + use VerifiesDoubles; + public function testSharedConnectorKeepsConcurrentOperationStateIsolated(): void { $http = new Factory; $http->registerConnection('saloon'); $http->preventStrayRequests(); - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('string')->with('saloon.connection.name')->andReturn('saloon'); + $config = new ConfigRepository(['saloon' => ['connection' => ['name' => 'saloon']]]); $manager = new SaloonManager( new Sender($http, $config), - m::mock(CacheFactory::class), - m::mock(RateLimiter::class), + Double::for(CacheFactory::class)->strict(), + Double::for(RateLimiter::class, override: true)->strict()->instance(), $config, new Dispatcher, ); diff --git a/tests/Saloon/Pagination/PaginatorTest.php b/tests/Saloon/Pagination/PaginatorTest.php index 031be5bbd8..5f644edfe6 100644 --- a/tests/Saloon/Pagination/PaginatorTest.php +++ b/tests/Saloon/Pagination/PaginatorTest.php @@ -7,8 +7,8 @@ use Closure; use GuzzleHttp\Psr7\Query; use GuzzleHttp\Psr7\Response as PsrResponse; +use Hypervel\Config\Repository as ConfigRepository; use Hypervel\Contracts\Cache\Factory as CacheFactory; -use Hypervel\Contracts\Config\Repository as ConfigRepository; use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Events\Dispatcher; use Hypervel\Http\Client\Factory; @@ -34,8 +34,9 @@ use Hypervel\Saloon\Pagination\PagedPaginator; use Hypervel\Saloon\SaloonManager; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use Psr\Http\Message\UriInterface; @@ -47,6 +48,8 @@ class PaginatorTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('currentPageLoads')] public function testCurrentLoadsEachPageOnceAndRetriesFailedMapping(string $class, array $queries, int $mappingFailures): void { @@ -1210,13 +1213,12 @@ protected function manager(): SaloonManager { $http = new Factory; $http->registerConnection('saloon'); - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('string')->with('saloon.connection.name')->andReturn('saloon'); + $config = new ConfigRepository(['saloon' => ['connection' => ['name' => 'saloon']]]); return new SaloonManager( new Sender($http, $config), - m::mock(CacheFactory::class), - m::mock(RateLimiter::class), + Double::for(CacheFactory::class)->strict(), + Double::for(RateLimiter::class, override: true)->strict()->instance(), $config, new Dispatcher, ); diff --git a/tests/Saloon/RateLimit/RateLimitTest.php b/tests/Saloon/RateLimit/RateLimitTest.php index b75773df4a..6c8483b46a 100644 --- a/tests/Saloon/RateLimit/RateLimitTest.php +++ b/tests/Saloon/RateLimit/RateLimitTest.php @@ -8,8 +8,8 @@ use DateTimeInterface; use Hypervel\Cache\ArrayStore; use Hypervel\Cache\Repository; +use Hypervel\Config\Repository as ConfigRepository; use Hypervel\Contracts\Cache\Factory as CacheFactory; -use Hypervel\Contracts\Config\Repository as ConfigRepository; use Hypervel\Events\Dispatcher; use Hypervel\Http\Client\Factory; use Hypervel\RateLimiter\AdmissionPolicy; @@ -37,12 +37,16 @@ use Hypervel\Support\Sleep; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; // Feature/HasRateLimitsTest covers consuming connector and request policies, denials before transport, cooldowns // recorded before response middleware and waiting, and Unit/HelperTest covers Retry-After parsing. class RateLimitTest extends TestCase { + use VerifiesDoubles; + public function testFakesAndCacheHitsDoNotConsumeAdmissionCapacity(): void { [$manager, $limiter, $http] = $this->manager(); @@ -70,7 +74,7 @@ public function testPoliciesCanUseOperationStateAndSelectAStore(): void { [$manager, $limiter, $http, $rateLimiter] = $this->manager(); $http->fake(['*' => Factory::response(['ok' => true])]); - $rateLimiter->shouldReceive('store')->twice()->with('secondary')->andReturn($limiter); + $rateLimiter->expects('store')->times(2)->with('secondary')->returns($limiter); $connector = new PlainRateLimitConnectorStub($manager); $tenantA = (new OperationRateLimitRequestStub)->withHeader('X-Tenant', 'tenant-a'); $tenantB = (new OperationRateLimitRequestStub)->withHeader('X-Tenant', 'tenant-b'); @@ -162,29 +166,30 @@ public function testServerOnlyPolicyCallbacksAreRejected(): void /** * Create a manager and isolated worker-array limiter. * - * @return array{SaloonManager, Limiter, Factory, RateLimiter} + * @return array{SaloonManager, Limiter, Factory, DoubleInterface} */ protected function manager(): array { $http = new Factory; $http->registerConnection('saloon'); $cacheRepository = new Repository(new ArrayStore); - $cache = m::mock(CacheFactory::class); - $cache->shouldReceive('store')->with(null)->andReturn($cacheRepository)->byDefault(); - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('string')->with('saloon.connection.name')->andReturn('saloon'); - $config->shouldReceive('get')->with('saloon.cache.store')->andReturn(null)->byDefault(); - $config->shouldReceive('get')->with('saloon.rate_limiter.store')->andReturn(null)->byDefault(); + $cache = Double::for(CacheFactory::class)->strict(); + $cache->allows('store')->with(null)->returns($cacheRepository); + $config = new ConfigRepository(['saloon' => [ + 'connection' => ['name' => 'saloon'], + 'cache' => ['store' => null], + 'rate_limiter' => ['store' => null], + ]]); $limiter = new Limiter( new WorkerArrayStore, new KeyResolver('saloon-tests', static fn (): ?string => null), ); - $rateLimiter = m::mock(RateLimiter::class); - $rateLimiter->shouldReceive('store')->with(null)->andReturn($limiter)->byDefault(); + $rateLimiter = Double::for(RateLimiter::class, override: true)->strict(); + $rateLimiter->allows('store')->with(null)->returns($limiter); $manager = new SaloonManager( new Sender($http, $config), $cache, - $rateLimiter, + $rateLimiter->instance(), $config, new Dispatcher, ); diff --git a/tests/Saloon/SaloonManagerTest.php b/tests/Saloon/SaloonManagerTest.php index 218af91495..0f7082eaca 100644 --- a/tests/Saloon/SaloonManagerTest.php +++ b/tests/Saloon/SaloonManagerTest.php @@ -6,8 +6,8 @@ use Carbon\CarbonInterval; use GuzzleHttp\Promise\PromiseInterface; +use Hypervel\Config\Repository as ConfigRepository; use Hypervel\Contracts\Cache\Factory as CacheFactory; -use Hypervel\Contracts\Config\Repository as ConfigRepository; use Hypervel\Events\Dispatcher; use Hypervel\Http\Client\Factory; use Hypervel\Http\Client\Request as HttpRequest; @@ -31,11 +31,14 @@ use Hypervel\Saloon\Traits\Plugins\AlwaysThrowOnErrors; use Hypervel\Support\Sleep; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Psr\Http\Message\RequestInterface; class SaloonManagerTest extends TestCase { + use VerifiesDoubles; + public function testEachRetryUsesFreshOperationStateAndRunsTheCompleteLifecycle(): void { Sleep::fake(); @@ -391,15 +394,12 @@ protected function http(): Factory */ protected function manager(Factory $http, ?Dispatcher $events = null): SaloonManager { - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('string') - ->with('saloon.connection.name') - ->andReturn('saloon'); + $config = new ConfigRepository(['saloon' => ['connection' => ['name' => 'saloon']]]); return new SaloonManager( new Sender($http, $config), - m::mock(CacheFactory::class), - m::mock(RateLimiter::class), + Double::for(CacheFactory::class)->strict(), + Double::for(RateLimiter::class, override: true)->strict()->instance(), $config, $events ?? new Dispatcher, ); diff --git a/tests/Saloon/Unit/FixtureTest.php b/tests/Saloon/Unit/FixtureTest.php index 421edbe807..42a5d021fd 100644 --- a/tests/Saloon/Unit/FixtureTest.php +++ b/tests/Saloon/Unit/FixtureTest.php @@ -13,11 +13,14 @@ use Hypervel\Saloon\SaloonManager; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class FixtureTest extends TestCase { + use VerifiesDoubles; + protected Filesystem $files; protected string $fixturePath; @@ -247,9 +250,9 @@ protected function tearDown(): void */ protected function bindManager(bool $throwOnMissing): void { - $manager = m::mock(SaloonManager::class); - $manager->shouldReceive('getFixturePath')->andReturn($this->fixturePath); - $manager->shouldReceive('throwsOnMissingFixtures')->andReturn($throwOnMissing); + $manager = Double::for(SaloonManager::class)->strict(); + $manager->allows('getFixturePath')->returns($this->fixturePath); + $manager->allows('throwsOnMissingFixtures')->returns($throwOnMissing); $container = new Container; $container->instance('saloon', $manager); diff --git a/tests/Saloon/Unit/MockResponseTest.php b/tests/Saloon/Unit/MockResponseTest.php index 6f0daa24d0..59fa1f0e1f 100644 --- a/tests/Saloon/Unit/MockResponseTest.php +++ b/tests/Saloon/Unit/MockResponseTest.php @@ -18,7 +18,6 @@ use Hypervel\Tests\Saloon\Fixtures\Requests\UserRequestWithCustomResponse; use Hypervel\Tests\Saloon\Fixtures\Responses\UserData; use Hypervel\Tests\Saloon\Fixtures\Responses\UserResponse; -use Mockery as m; use RuntimeException; class MockResponseTest extends TestCase @@ -83,7 +82,7 @@ public function testItCreatesJsonAndStringResponses(): void public function testItResolvesConfiguredExceptionsAgainstThePendingRequest(): void { - $pendingRequest = m::mock(PendingRequest::class); + $pendingRequest = new PendingRequest(new TestConnector, new UserRequest); $exception = new RuntimeException('Failed.'); $response = (new FakeResponse)->throw( fn (PendingRequest $request): RuntimeException => $request === $pendingRequest diff --git a/tests/Saloon/Unit/PoolNonCoroutineTest.php b/tests/Saloon/Unit/PoolNonCoroutineTest.php index 483f8a8cce..e73b822fb8 100644 --- a/tests/Saloon/Unit/PoolNonCoroutineTest.php +++ b/tests/Saloon/Unit/PoolNonCoroutineTest.php @@ -4,8 +4,8 @@ namespace Hypervel\Tests\Saloon\Unit; +use Hypervel\Config\Repository as ConfigRepository; use Hypervel\Contracts\Cache\Factory as CacheFactory; -use Hypervel\Contracts\Config\Repository as ConfigRepository; use Hypervel\Events\Dispatcher; use Hypervel\Http\Client\Factory; use Hypervel\RateLimiter\RateLimiter; @@ -18,10 +18,13 @@ use Hypervel\Saloon\Http\Sender; use Hypervel\Saloon\SaloonManager; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class PoolNonCoroutineTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; public function testPoolEntersOneRootCoroutineWhenCalledFromCliCode(): void @@ -47,15 +50,12 @@ protected function manager(): SaloonManager { $http = new Factory; $http->registerConnection('saloon'); - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('string') - ->with('saloon.connection.name') - ->andReturn('saloon'); + $config = new ConfigRepository(['saloon' => ['connection' => ['name' => 'saloon']]]); return new SaloonManager( new Sender($http, $config), - m::mock(CacheFactory::class), - m::mock(RateLimiter::class), + Double::for(CacheFactory::class)->strict(), + Double::for(RateLimiter::class, override: true)->strict()->instance(), $config, new Dispatcher, ); diff --git a/tests/Saloon/Unit/PoolTest.php b/tests/Saloon/Unit/PoolTest.php index cc83c88753..ad19f0150e 100644 --- a/tests/Saloon/Unit/PoolTest.php +++ b/tests/Saloon/Unit/PoolTest.php @@ -10,9 +10,9 @@ use GuzzleHttp\Promise\PromiseInterface; use Hypervel\Cache\ArrayStore; use Hypervel\Cache\Repository; +use Hypervel\Config\Repository as ConfigRepository; use Hypervel\Context\CoroutineContext; use Hypervel\Contracts\Cache\Factory as CacheFactory; -use Hypervel\Contracts\Config\Repository as ConfigRepository; use Hypervel\Contracts\Foundation\Application as ApplicationContract; use Hypervel\Coroutine\Coroutine; use Hypervel\Coroutine\Exceptions\ChildCancellationException; @@ -47,7 +47,8 @@ use Hypervel\Tests\Saloon\Fixtures\Connectors\TestConnector; use Hypervel\Tests\Saloon\Fixtures\Requests\UserRequest; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -62,6 +63,8 @@ // map to Feature/PoolTest, and its then() chaining cases only test promises. class PoolTest extends TestCase { + use VerifiesDoubles; + /** * Get the package providers. */ @@ -783,8 +786,8 @@ public function testConcurrentPoolParentsKeepCacheAndRateScopesInTheirChildren() return Factory::response(['ok' => true]); }); $cacheRepository = new Repository(new ArrayStore); - $cache = m::mock(CacheFactory::class); - $cache->shouldReceive('store')->with(null)->andReturn($cacheRepository); + $cache = Double::for(CacheFactory::class)->strict(); + $cache->allows('store')->with(null)->returns($cacheRepository); $cacheScopes = []; $rateScopes = []; $limiter = new Limiter( @@ -796,16 +799,17 @@ public function testConcurrentPoolParentsKeepCacheAndRateScopesInTheirChildren() return $scope; }), ); - $rateLimiter = m::mock(RateLimiter::class); - $rateLimiter->shouldReceive('store')->with(null)->andReturn($limiter); - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('string')->with('saloon.connection.name')->andReturn('saloon'); - $config->shouldReceive('get')->with('saloon.cache.store')->andReturn(null); - $config->shouldReceive('get')->with('saloon.rate_limiter.store')->andReturn(null); + $rateLimiter = Double::for(RateLimiter::class, override: true)->strict(); + $rateLimiter->allows('store')->with(null)->returns($limiter); + $config = new ConfigRepository(['saloon' => [ + 'connection' => ['name' => 'saloon'], + 'cache' => ['store' => null], + 'rate_limiter' => ['store' => null], + ]]); $manager = new SaloonManager( new Sender($http, $config), $cache, - $rateLimiter, + $rateLimiter->instance(), $config, new Dispatcher, ); @@ -858,15 +862,12 @@ protected function manager(): SaloonManager { $http = new Factory; $http->registerConnection('saloon'); - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('string') - ->with('saloon.connection.name') - ->andReturn('saloon'); + $config = new ConfigRepository(['saloon' => ['connection' => ['name' => 'saloon']]]); return new SaloonManager( new Sender($http, $config), - m::mock(CacheFactory::class), - m::mock(RateLimiter::class), + Double::for(CacheFactory::class)->strict(), + Double::for(RateLimiter::class, override: true)->strict()->instance(), $config, new Dispatcher, ); diff --git a/tests/Saloon/Unit/ResponseTest.php b/tests/Saloon/Unit/ResponseTest.php index 2855690fb1..b1fff31eca 100644 --- a/tests/Saloon/Unit/ResponseTest.php +++ b/tests/Saloon/Unit/ResponseTest.php @@ -27,7 +27,8 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Saloon\Fixtures\Connectors\TestConnector; use Hypervel\Tests\Saloon\Fixtures\Requests\UserRequest; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\StreamInterface; @@ -37,6 +38,8 @@ class ResponseTest extends TestCase { + use VerifiesDoubles; + /** * The scratch directory for saved response bodies. */ @@ -690,10 +693,10 @@ public function testBodyExportsPreservePositionsAndCallerOwnedResources(): void public function testFailedBodyExportDoesNotCloseACallerOwnedResource(): void { - $source = m::mock(StreamInterface::class); - $source->shouldReceive('isSeekable')->once()->andReturn(false); - $source->shouldReceive('eof')->once()->andReturn(false); - $source->shouldReceive('read')->once()->andThrow(new RuntimeException('read failed')); + $source = Double::for(StreamInterface::class)->strict(); + $source->expects('isSeekable')->returns(false); + $source->expects('eof')->returns(false); + $source->expects('read')->throws(new RuntimeException('read failed')); $response = $this->response(200, body: $source); $resource = fopen('php://temp', 'wb+'); $this->assertIsResource($resource); diff --git a/tests/Saloon/Unit/SenderTest.php b/tests/Saloon/Unit/SenderTest.php index 75ede1fb94..8ab5e6c3b9 100644 --- a/tests/Saloon/Unit/SenderTest.php +++ b/tests/Saloon/Unit/SenderTest.php @@ -8,7 +8,7 @@ use GuzzleHttp\Promise\Create; use GuzzleHttp\Promise\PromiseInterface; use GuzzleHttp\Psr7\Response as PsrResponse; -use Hypervel\Contracts\Config\Repository as ConfigRepository; +use Hypervel\Config\Repository as ConfigRepository; use Hypervel\Contracts\Foundation\Application as ApplicationContract; use Hypervel\Contracts\Telescope\TelescopeTag; use Hypervel\Http\Client\Factory; @@ -29,7 +29,6 @@ use Hypervel\Testbench\TestCase; use Hypervel\Tests\Saloon\Fixtures\Connectors\TestConnector; use Hypervel\Tests\Saloon\Fixtures\Requests\UserRequest; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use Psr\Http\Message\RequestInterface; @@ -350,12 +349,7 @@ protected function setUp(): void */ protected function config(): ConfigRepository { - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('string') - ->with('saloon.connection.name') - ->andReturn('saloon'); - - return $config; + return new ConfigRepository(['saloon' => ['connection' => ['name' => 'saloon']]]); } } diff --git a/tests/Sanctum/CheckAbilitiesTest.php b/tests/Sanctum/CheckAbilitiesTest.php index 03e024c2c0..8b6b3090b3 100644 --- a/tests/Sanctum/CheckAbilitiesTest.php +++ b/tests/Sanctum/CheckAbilitiesTest.php @@ -11,20 +11,23 @@ use Hypervel\Sanctum\Exceptions\MissingAbilityException; use Hypervel\Sanctum\Http\Middleware\CheckAbilities; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpFoundation\Response; class CheckAbilitiesTest extends TestCase { + use VerifiesDoubles; + public function testRequestIsPassedAlongIfAbilitiesArePresentOnToken(): void { $middleware = new CheckAbilities; $request = new Request; - $user = m::mock(HasApiTokens::class); + $user = Double::for(HasApiTokens::class)->strict(); $request->setUserResolver(fn (): HasApiTokens => $user); - $user->expects('currentAccessToken')->andReturn(m::mock(HasAbilities::class)); - $user->expects('tokenCan')->with('foo')->andReturn(true); - $user->expects('tokenCan')->with('bar')->andReturn(true); + $user->expects('currentAccessToken')->returns(Double::for(HasAbilities::class)->strict()); + $user->expects('tokenCan')->with('foo')->returns(true); + $user->expects('tokenCan')->with('bar')->returns(true); $expected = new Response('response'); $response = $middleware->handle($request, function () use ($expected): Response { @@ -40,10 +43,10 @@ public function testExceptionIsThrownIfTokenDoesntHaveAbility(): void $middleware = new CheckAbilities; $request = new Request; - $user = m::mock(HasApiTokens::class); + $user = Double::for(HasApiTokens::class)->strict(); $request->setUserResolver(fn (): HasApiTokens => $user); - $user->expects('currentAccessToken')->andReturn(m::mock(HasAbilities::class)); - $user->expects('tokenCan')->with('foo')->andReturn(false); + $user->expects('currentAccessToken')->returns(Double::for(HasAbilities::class)->strict()); + $user->expects('tokenCan')->with('foo')->returns(false); $middleware->handle($request, function (): Response { return new Response('response'); @@ -69,9 +72,9 @@ public function testExceptionIsThrownIfNoToken(): void $middleware = new CheckAbilities; $request = new Request; - $user = m::mock(HasApiTokens::class); + $user = Double::for(HasApiTokens::class)->strict(); $request->setUserResolver(fn (): HasApiTokens => $user); - $user->expects('currentAccessToken')->andReturn(null); + $user->expects('currentAccessToken')->returns(null); $middleware->handle($request, function (): Response { return new Response('response'); diff --git a/tests/Sanctum/CheckForAnyAbilityTest.php b/tests/Sanctum/CheckForAnyAbilityTest.php index 051b01739a..0a99b5f3a5 100644 --- a/tests/Sanctum/CheckForAnyAbilityTest.php +++ b/tests/Sanctum/CheckForAnyAbilityTest.php @@ -11,20 +11,23 @@ use Hypervel\Sanctum\Exceptions\MissingAbilityException; use Hypervel\Sanctum\Http\Middleware\CheckForAnyAbility; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpFoundation\Response; class CheckForAnyAbilityTest extends TestCase { + use VerifiesDoubles; + public function testRequestIsPassedAlongIfAbilitiesArePresentOnToken(): void { $middleware = new CheckForAnyAbility; $request = new Request; - $user = m::mock(HasApiTokens::class); + $user = Double::for(HasApiTokens::class)->strict(); $request->setUserResolver(fn (): HasApiTokens => $user); - $user->expects('currentAccessToken')->andReturn(m::mock(HasAbilities::class)); - $user->expects('tokenCan')->with('foo')->andReturn(true); - $user->allows('tokenCan')->with('bar')->andReturn(false); + $user->expects('currentAccessToken')->returns(Double::for(HasAbilities::class)->strict()); + $user->expects('tokenCan')->with('foo')->returns(true); + $user->allows('tokenCan')->with('bar')->returns(false); $expected = new Response('response'); $response = $middleware->handle($request, function () use ($expected): Response { @@ -40,11 +43,11 @@ public function testExceptionIsThrownIfTokenDoesntHaveAbility(): void $middleware = new CheckForAnyAbility; $request = new Request; - $user = m::mock(HasApiTokens::class); + $user = Double::for(HasApiTokens::class)->strict(); $request->setUserResolver(fn (): HasApiTokens => $user); - $user->expects('currentAccessToken')->andReturn(m::mock(HasAbilities::class)); - $user->expects('tokenCan')->with('foo')->andReturn(false); - $user->expects('tokenCan')->with('bar')->andReturn(false); + $user->expects('currentAccessToken')->returns(Double::for(HasAbilities::class)->strict()); + $user->expects('tokenCan')->with('foo')->returns(false); + $user->expects('tokenCan')->with('bar')->returns(false); $middleware->handle($request, function (): Response { return new Response('response'); @@ -70,9 +73,9 @@ public function testExceptionIsThrownIfNoToken(): void $middleware = new CheckForAnyAbility; $request = new Request; - $user = m::mock(HasApiTokens::class); + $user = Double::for(HasApiTokens::class)->strict(); $request->setUserResolver(fn (): HasApiTokens => $user); - $user->expects('currentAccessToken')->andReturn(null); + $user->expects('currentAccessToken')->returns(null); $middleware->handle($request, function (): Response { return new Response('response'); diff --git a/tests/Sanctum/CoroutineIsolationTest.php b/tests/Sanctum/CoroutineIsolationTest.php index 45ce9b404e..32f86cbf47 100644 --- a/tests/Sanctum/CoroutineIsolationTest.php +++ b/tests/Sanctum/CoroutineIsolationTest.php @@ -14,19 +14,22 @@ use Hypervel\Http\Request; use Hypervel\Sanctum\SanctumGuard; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use function Hypervel\Coroutine\parallel; class CoroutineIsolationTest extends TestCase { + use VerifiesDoubles; + public function testSharedRequestDoesNotShareResolvedSessionUsers(): void { $container = new Container; - $provider = m::mock(UserProvider::class); - $sessionGuard = new SessionGuard('web', $provider, m::mock(Session::class), $container); - $auth = m::mock(Factory::class); - $auth->shouldReceive('guard')->with('web')->andReturn($sessionGuard); + $provider = Double::for(UserProvider::class)->strict(); + $sessionGuard = new SessionGuard('web', $provider, Double::for(Session::class)->strict(), $container); + $auth = Double::for(Factory::class)->strict(); + $auth->allows('guard')->with('web')->returns($sessionGuard); $container->instance('auth', $auth); $container->bind('request', static fn (): Request => RequestContext::get()); $guard = new SanctumGuard('sanctum', $provider, $container, ['web']); diff --git a/tests/Sanctum/PersonalAccessTokenCacheTest.php b/tests/Sanctum/PersonalAccessTokenCacheTest.php index 82295c7009..6874d125f8 100644 --- a/tests/Sanctum/PersonalAccessTokenCacheTest.php +++ b/tests/Sanctum/PersonalAccessTokenCacheTest.php @@ -20,7 +20,8 @@ use Hypervel\Testbench\Attributes\DefineEnvironment; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Sanctum\Fixtures\TestUser; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; @@ -32,6 +33,7 @@ class PersonalAccessTokenCacheTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; protected bool $migrateRefresh = true; @@ -494,8 +496,8 @@ public function testLastUsedAtIsWrittenEveryTimeWhenCachingIsDisabled(): void $token = $this->createToken(); $cacheManager = $this->app->make(CacheManager::class); - $cacheDouble = m::mock(CacheManager::class); - $cacheDouble->shouldNotReceive('store'); + $cacheDouble = Double::for(CacheManager::class)->strict(); + $cacheDouble->expects('store')->never(); $this->app->instance('cache', $cacheDouble); try { diff --git a/tests/Sanctum/SanctumServiceProviderTest.php b/tests/Sanctum/SanctumServiceProviderTest.php index 1666131f6b..5721a66e42 100644 --- a/tests/Sanctum/SanctumServiceProviderTest.php +++ b/tests/Sanctum/SanctumServiceProviderTest.php @@ -26,12 +26,17 @@ use Hypervel\Sanctum\SanctumServiceProvider; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use Swoole\Server as SwooleServer; class SanctumServiceProviderTest extends TestCase { + use VerifiesDoubles; + public function testBootContributesLateTokenModelConfiguredGuardModelsAndFrameworkContainers(): void { $config = new ConfigRepository([ @@ -70,7 +75,7 @@ public function testBootContributesLateTokenModelConfiguredGuardModelsAndFramewo ], ], ]); - $manager = m::mock(CacheManager::class); + $manager = Double::for(CacheManager::class)->strict(); $resolver = $this->bootAndCaptureResolver($manager, $config); Sanctum::usePersonalAccessTokenModel(SanctumProviderToken::class); @@ -96,29 +101,22 @@ public function testConsoleStartupUsesDefaultsForOmittedCacheMembers(): void 'guards' => [], ], ]); - $repository = m::mock(CacheRepository::class); - $manager = m::mock(CacheManager::class); - $manager->shouldReceive('allowSerializableClassesUsing')->once()->andReturnSelf(); - $manager->shouldReceive('store')->once()->with(null)->andReturn($repository); - $validator = m::mock(ModelCacheStoreValidator::class); - $validator->shouldReceive('validate') - ->once() + $repository = Double::for(CacheRepository::class)->strict(); + $manager = Double::for(CacheManager::class)->strict(); + $manager->expects('allowSerializableClassesUsing'); + $manager->expects('store')->with(null)->returns($repository); + $validator = Double::for(ModelCacheStoreValidator::class)->strict(); + $validator->expects('validate') ->with($repository, 'Sanctum token cache'); $bootedCallback = null; $application = $this->consoleApplication($manager, $config); - $application->shouldReceive('make') - ->once() + $application->expects('make') ->with(ModelCacheStoreValidator::class) - ->andReturn($validator); - $application->shouldReceive('booted') - ->once() - ->with(m::on(function (mixed $callback) use (&$bootedCallback): bool { - $bootedCallback = $callback; - - return $callback instanceof Closure; - })); + ->returns($validator); + $application->expects('booted') + ->with(Argument::capture($bootedCallback)); - $provider = new SanctumServiceProviderFixture($application); + $provider = new SanctumServiceProviderFixture($application->instance()); $provider->boot(); $this->assertTrue($provider->bootCalled); @@ -142,23 +140,21 @@ public function testDisabledCachingResolvesNeitherAStoreNorTheValidator(): void 'guards' => [], ], ]); - $manager = m::mock(CacheManager::class); - $manager->shouldReceive('allowSerializableClassesUsing')->once()->andReturnSelf(); - $manager->shouldNotReceive('store'); + $manager = Double::for(CacheManager::class)->strict(); + $resolver = null; + $manager->expects('allowSerializableClassesUsing') + ->with(Argument::capture($resolver)); + $manager->expects('store')->never(); $bootedCallback = null; $application = $this->consoleApplication($manager, $config); - $application->shouldNotReceive('make')->with(ModelCacheStoreValidator::class); - $application->shouldReceive('booted') - ->once() - ->with(m::on(function (mixed $callback) use (&$bootedCallback): bool { - $bootedCallback = $callback; + $application->expects('make')->never()->with(ModelCacheStoreValidator::class); + $application->expects('booted') + ->with(Argument::capture($bootedCallback)); - return $callback instanceof Closure; - })); + (new SanctumServiceProviderFixture($application->instance()))->boot(); - (new SanctumServiceProviderFixture($application))->boot(); - - $this->assertSame([], $this->capturedResolver($manager)()); + $this->assertInstanceOf(Closure::class, $resolver); + $this->assertSame([], $resolver()); $this->assertInstanceOf(Closure::class, $bootedCallback); $bootedCallback(); @@ -187,43 +183,36 @@ public function testServerValidationUsesWorkerDependenciesAndRunsForTaskworkers( 'guards' => [], ], ]); - $masterManager = m::mock(CacheManager::class); - $masterManager->shouldReceive('allowSerializableClassesUsing')->once()->andReturnSelf(); - $masterManager->shouldNotReceive('store'); - $workerRepository = m::mock(CacheRepository::class); - $workerManager = m::mock(CacheManager::class); - $workerManager->shouldReceive('store')->once()->with('worker')->andReturn($workerRepository); - $validator = m::mock(ModelCacheStoreValidator::class); - $validator->shouldReceive('validate') - ->once() + $masterManager = Double::for(CacheManager::class)->strict(); + $masterManager->expects('allowSerializableClassesUsing'); + $masterManager->expects('store')->never(); + $workerRepository = Double::for(CacheRepository::class)->strict(); + $workerManager = Double::for(CacheManager::class)->strict(); + $workerManager->expects('store')->with('worker')->returns($workerRepository); + $validator = Double::for(ModelCacheStoreValidator::class)->strict(); + $validator->expects('validate') ->with($workerRepository, 'Sanctum token cache'); $listener = null; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('listen') - ->once() - ->with(AfterWorkerStart::class, m::on(function (mixed $callback) use (&$listener): bool { - $listener = $callback; - - return $callback instanceof Closure; - })); - $application = m::mock(Application::class); - $application->shouldReceive('make') - ->twice() + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('listen') + ->with(AfterWorkerStart::class, Argument::capture($listener)); + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('make') + ->times(2) ->with(CacheManager::class) - ->andReturn($masterManager, $workerManager); - $application->shouldReceive('make') - ->twice() + ->returns($masterManager, $workerManager); + $application->expects('make') + ->times(2) ->with(ConfigRepositoryContract::class) - ->andReturn($masterConfig, $workerConfig); - $application->shouldReceive('make')->once()->with('events')->andReturn($events); - $application->shouldReceive('make') - ->once() + ->returns($masterConfig, $workerConfig); + $application->expects('make')->with('events')->returns($events); + $application->expects('make') ->with(ModelCacheStoreValidator::class) - ->andReturn($validator); - $application->shouldReceive('runningInConsole')->twice()->andReturnFalse(); - $application->shouldNotReceive('booted'); + ->returns($validator); + $application->expects('runningInConsole')->times(2)->returns(false); + $application->expects('booted')->never(); - $provider = new SanctumServiceProviderFixture($application); + $provider = new SanctumServiceProviderFixture($application->instance()); $provider->boot(); $this->assertTrue($provider->bootCalled); @@ -231,7 +220,7 @@ public function testServerValidationUsesWorkerDependenciesAndRunsForTaskworkers( $this->assertFalse($provider->commandsRegistered); $this->assertInstanceOf(Closure::class, $listener); - $server = m::mock(SwooleServer::class); + $server = Double::for(SwooleServer::class)->strict(); // Store validation runs in request workers and taskworkers, unlike Swoole timer registration. $server->taskworker = true; $listener(new AfterWorkerStart($server, 8)); @@ -258,7 +247,7 @@ public function testSelectedProviderRequiresAnEloquentAuthenticatableModel(): vo ], ], ]); - $manager = m::mock(CacheManager::class); + $manager = Double::for(CacheManager::class)->strict(); $resolver = $this->bootAndCaptureResolver($manager, $config); $this->expectException(InvalidArgumentException::class); @@ -271,12 +260,10 @@ public function testSelectedProviderRequiresAnEloquentAuthenticatableModel(): vo public function testDefineRoutesSkipsRegistrationWhenRoutesAreCached(): void { - $application = m::mock(Application::class); - $application->shouldReceive('routesAreCached')->once()->andReturnTrue(); + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('routesAreCached')->returns(true); - (new SanctumServiceProviderFixture($application))->defineRoutesUsingParent(); - - $this->addToAssertionCount(1); + (new SanctumServiceProviderFixture($application->instance()))->defineRoutesUsingParent(); } #[DataProvider('invalidRouteConfigurationProvider')] @@ -293,17 +280,16 @@ public function testDefineRoutesRequiresExactConfigurationTypes( ]); $config->set($key, $value); - $application = m::mock(Application::class); - $application->shouldReceive('routesAreCached')->once()->andReturnFalse(); - $application->shouldReceive('make') - ->once() + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('routesAreCached')->returns(false); + $application->expects('make') ->with(ConfigRepositoryContract::class) - ->andReturn($config); + ->returns($config); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs($message); - (new SanctumServiceProviderFixture($application))->defineRoutesUsingParent(); + (new SanctumServiceProviderFixture($application->instance()))->defineRoutesUsingParent(); } /** @@ -332,19 +318,18 @@ public function testDefineRoutesRequiresRoutesSetting(): void 'prefix' => 'sanctum', ], ]); - $application = m::mock(Application::class); - $application->shouldReceive('routesAreCached')->once()->andReturnFalse(); - $application->shouldReceive('make') - ->once() + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('routesAreCached')->returns(false); + $application->expects('make') ->with(ConfigRepositoryContract::class) - ->andReturn($config); + ->returns($config); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs( 'Configuration value for key [sanctum.routes] must be a boolean, NULL given.' ); - (new SanctumServiceProviderFixture($application))->defineRoutesUsingParent(); + (new SanctumServiceProviderFixture($application->instance()))->defineRoutesUsingParent(); } public function testDefineRoutesRequiresPrefixWhenRoutesAreEnabled(): void @@ -354,42 +339,41 @@ public function testDefineRoutesRequiresPrefixWhenRoutesAreEnabled(): void 'routes' => true, ], ]); - $application = m::mock(Application::class); - $application->shouldReceive('routesAreCached')->once()->andReturnFalse(); - $application->shouldReceive('make') - ->once() + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('routesAreCached')->returns(false); + $application->expects('make') ->with(ConfigRepositoryContract::class) - ->andReturn($config); + ->returns($config); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs( 'Configuration value for key [sanctum.prefix] must be a string, NULL given.' ); - (new SanctumServiceProviderFixture($application))->defineRoutesUsingParent(); + (new SanctumServiceProviderFixture($application->instance()))->defineRoutesUsingParent(); } // REMOVED: Hypervel's Middleware::statefulApi() owns middleware priority before kernel construction. public function testCreateGuardRemainsAProtectedExtensionPoint(): void { - $application = m::mock(Application::class); - $container = m::mock(Container::class); + $application = Double::for(Application::class, override: true)->strict(); + $container = Double::for(Container::class, override: true)->strict(); $config = new ConfigRepository([ 'sanctum' => [ 'expiration' => null, 'last_used_at' => true, ], ]); - $container->shouldReceive('bound')->once()->with('events')->andReturnFalse(); - $container->shouldReceive('make')->twice()->with('config')->andReturn($config); - $userProvider = m::mock(UserProvider::class); - $authManager = m::mock(AuthManager::class); - $authManager->shouldReceive('createUserProvider')->once()->with('users')->andReturn($userProvider); + $container->expects('bound')->with('events')->returns(false); + $container->expects('make')->times(2)->with('config')->returns($config); + $userProvider = Double::for(UserProvider::class)->strict(); + $authManager = Double::for(AuthManager::class)->strict(); + $authManager->expects('createUserProvider')->with('users')->returns($userProvider); - $guard = (new SanctumServiceProviderFixture($application))->createGuardUsingParent( + $guard = (new SanctumServiceProviderFixture($application->instance()))->createGuardUsingParent( $authManager, - $container, + $container->instance(), 'sanctum', [ 'provider' => 'users', @@ -403,31 +387,26 @@ public function testCreateGuardRemainsAProtectedExtensionPoint(): void public function testConfiguredGuardResolutionUsesTheProtectedFactoryExtensionPoint(): void { $afterResolving = null; - $application = m::mock(Application::class); - $application->shouldReceive('afterResolving') - ->once() - ->with(AuthManager::class, m::on(function (mixed $callback) use (&$afterResolving): bool { - $afterResolving = $callback; - - return $callback instanceof Closure; - })); - $application->shouldReceive('resolved')->once()->with(AuthManager::class)->andReturnFalse(); - - $provider = new ResolvingSanctumServiceProviderFixture($application); - $provider->guard = m::mock(SanctumGuard::class); + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('afterResolving') + ->with(AuthManager::class, Argument::capture($afterResolving)); + $application->expects('resolved')->with(AuthManager::class)->returns(false); + + $provider = new ResolvingSanctumServiceProviderFixture($application->instance()); + $provider->guard = Double::for(SanctumGuard::class)->strict(); $provider->configureGuardUsingParent(); $this->assertInstanceOf(Closure::class, $afterResolving); - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with('config')->andReturn(new ConfigRepository([ + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with('config')->returns(new ConfigRepository([ 'auth' => [ 'guards' => [ 'sanctum' => ['driver' => 'sanctum'], ], ], ])); - $authManager = new AuthManager($container); + $authManager = new AuthManager($container->instance()); $afterResolving($authManager); @@ -448,20 +427,15 @@ public function testConfiguredStoreMustBeAStringOrNull(): void 'guards' => [], ], ]); - $manager = m::mock(CacheManager::class); - $manager->shouldReceive('allowSerializableClassesUsing')->once()->andReturnSelf(); - $manager->shouldNotReceive('store'); + $manager = Double::for(CacheManager::class)->strict(); + $manager->expects('allowSerializableClassesUsing'); + $manager->expects('store')->never(); $bootedCallback = null; $application = $this->consoleApplication($manager, $config); - $application->shouldReceive('booted') - ->once() - ->with(m::on(function (mixed $callback) use (&$bootedCallback): bool { - $bootedCallback = $callback; - - return $callback instanceof Closure; - })); + $application->expects('booted') + ->with(Argument::capture($bootedCallback)); - (new SanctumServiceProviderFixture($application))->boot(); + (new SanctumServiceProviderFixture($application->instance()))->boot(); $this->assertInstanceOf(Closure::class, $bootedCallback); $this->expectException(InvalidArgumentException::class); @@ -484,8 +458,8 @@ public function testCachingRequiresPositiveIntegerTtl(array $cache, string $mess 'guards' => [], ], ]); - $manager = m::mock(CacheManager::class); - $manager->shouldNotReceive('store'); + $manager = Double::for(CacheManager::class)->strict(); + $manager->expects('store')->never(); $startup = $this->bootAndCaptureStartupValidation($manager, $config); $this->expectException(InvalidArgumentException::class); @@ -519,8 +493,8 @@ public function testCachingRequiresNonNegativeIntegerLastUsedUpdateInterval(arra 'guards' => [], ], ]); - $manager = m::mock(CacheManager::class); - $manager->shouldNotReceive('store'); + $manager = Double::for(CacheManager::class)->strict(); + $manager->expects('store')->never(); $startup = $this->bootAndCaptureStartupValidation($manager, $config); $this->expectException(InvalidArgumentException::class); @@ -544,17 +518,15 @@ public static function invalidLastUsedUpdateIntervalProvider(): iterable private function consoleApplication( CacheManager $manager, ConfigRepositoryContract $config, - ): Application|m\MockInterface { - $application = m::mock(Application::class); - $application->shouldReceive('make') - ->once() + ): DoubleInterface { + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('make') ->with(CacheManager::class) - ->andReturn($manager); - $application->shouldReceive('make') - ->once() + ->returns($manager); + $application->expects('make') ->with(ConfigRepositoryContract::class) - ->andReturn($config); - $application->shouldReceive('runningInConsole')->twice()->andReturnTrue(); + ->returns($config); + $application->expects('runningInConsole')->times(2)->returns(true); return $application; } @@ -563,23 +535,16 @@ private function consoleApplication( * Boot the provider and capture its console startup validation callback. */ private function bootAndCaptureStartupValidation( - CacheManager|m\MockInterface $manager, + CacheManager&DoubleInterface $manager, ConfigRepositoryContract $config, ): Closure { - $manager->shouldReceive('allowSerializableClassesUsing') - ->once() - ->andReturnSelf(); + $manager->expects('allowSerializableClassesUsing'); $startup = null; $application = $this->consoleApplication($manager, $config); - $application->shouldReceive('booted') - ->once() - ->with(m::on(function (mixed $callback) use (&$startup): bool { - $startup = $callback; + $application->expects('booted') + ->with(Argument::capture($startup)); - return $callback instanceof Closure; - })); - - (new SanctumServiceProviderFixture($application))->boot(); + (new SanctumServiceProviderFixture($application->instance()))->boot(); $this->assertInstanceOf(Closure::class, $startup); @@ -590,41 +555,16 @@ private function bootAndCaptureStartupValidation( * Boot the provider and capture its class resolver. */ private function bootAndCaptureResolver( - CacheManager|m\MockInterface $manager, + CacheManager&DoubleInterface $manager, ConfigRepositoryContract $config, ): Closure { $resolver = null; - $manager->shouldReceive('allowSerializableClassesUsing') - ->once() - ->with(m::on(function (mixed $callback) use (&$resolver): bool { - $resolver = $callback; - - return $callback instanceof Closure; - })) - ->andReturnSelf(); + $manager->expects('allowSerializableClassesUsing') + ->with(Argument::capture($resolver)); $application = $this->consoleApplication($manager, $config); - $application->shouldReceive('booted')->once(); - - (new SanctumServiceProviderFixture($application))->boot(); - - $this->assertInstanceOf(Closure::class, $resolver); - - return $resolver; - } - - /** - * Capture the registered class resolver from a manager mock. - */ - private function capturedResolver(CacheManager|m\MockInterface $manager): Closure - { - $resolver = null; - $manager->shouldHaveReceived('allowSerializableClassesUsing') - ->with(m::on(function (mixed $callback) use (&$resolver): bool { - $resolver = $callback; + $application->expects('booted'); - return $callback instanceof Closure; - })) - ->once(); + (new SanctumServiceProviderFixture($application->instance()))->boot(); $this->assertInstanceOf(Closure::class, $resolver); diff --git a/tests/Scout/Feature/ConcurrentImportConnectionTest.php b/tests/Scout/Feature/ConcurrentImportConnectionTest.php index b77620dc75..da06e09da0 100644 --- a/tests/Scout/Feature/ConcurrentImportConnectionTest.php +++ b/tests/Scout/Feature/ConcurrentImportConnectionTest.php @@ -16,12 +16,15 @@ use Hypervel\Support\Facades\DB; use Hypervel\Support\Facades\Event; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Swoole\Coroutine\CanceledException; class ConcurrentImportConnectionTest extends TestCase { + use VerifiesDoubles; + /** * Share one physical slot between the chunk reader and import operations. */ @@ -192,8 +195,8 @@ public function testOrdinaryParentReleaseFailureWaitsForChildrenBeforeRethrowing $failure = new RuntimeException('Session cleanup failed.'); $childCompleted = false; $observed = null; - $lease = m::mock(ConnectionLease::class); - $lease->expects('releaseIfIdle')->andReturnUsing(static function () use ($releaseAttempted, $failure): void { + $lease = Double::for(ConnectionLease::class)->strict(); + $lease->expects('releaseIfIdle')->resolves(static function () use ($releaseAttempted, $failure): void { $releaseAttempted->push(true); throw $failure; }); diff --git a/tests/Scout/Feature/SearchableModelTest.php b/tests/Scout/Feature/SearchableModelTest.php index dc61fa7e9c..6a4d424203 100644 --- a/tests/Scout/Feature/SearchableModelTest.php +++ b/tests/Scout/Feature/SearchableModelTest.php @@ -13,12 +13,16 @@ use Hypervel\Tests\Scout\Fixtures\Models\SearchableModel; use Hypervel\Tests\Scout\Fixtures\Models\SoftDeletableSearchableModel; use Hypervel\Tests\Scout\ScoutTestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use RuntimeException; class SearchableModelTest extends ScoutTestCase { + use VerifiesDoubles; + public function testSearchableBootDefersModelInstanceWorkUntilAfterPublication(): void { $model = new SearchableModel; @@ -225,12 +229,11 @@ public function testMakeAllSearchableQueryReturnsBuilder(): void public function testRemoveAllFromSearchGuardsTheResolvedEngineBeforeFlushing(): void { - $engine = m::mock(Engine::class); - $engine->shouldReceive('runFlush') - ->once() - ->with(m::type(SearchableModel::class)); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine')->once()->andReturn($engine); + $engine = Double::for(Engine::class)->strict(); + $engine->expects('runFlush') + ->with(Argument::type(SearchableModel::class)); + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine')->returns($engine); $this->app->instance(EngineManager::class, $manager); $guarded = false; Scout::guardModelFlushUsing(function (Model $model, Engine $givenEngine, bool $force) use ( diff --git a/tests/Scout/Fixtures/SettingsEngine.php b/tests/Scout/Fixtures/SettingsEngine.php new file mode 100644 index 0000000000..d5d0fa9ae5 --- /dev/null +++ b/tests/Scout/Fixtures/SettingsEngine.php @@ -0,0 +1,12 @@ +strict(); $builder = new Builder($model, 'test query'); $this->assertSame($model, $builder->model); @@ -40,7 +48,7 @@ public function testBuilderStoresQueryAndModel(): void public function testBuilderIsNotPreparedUntilTerminalExecution(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $calls = 0; Scout::prepareBuilderUsing(function () use (&$calls): void { @@ -54,7 +62,7 @@ public function testBuilderIsNotPreparedUntilTerminalExecution(): void public function testWhereAddsConstraint(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $result = $builder->where('status', 'active'); @@ -69,7 +77,7 @@ public function testWhereAddsConstraint(): void public function testWhereAddsComparisonConstraintWithoutOverwritingTheSameField(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $result = $builder @@ -85,21 +93,9 @@ public function testWhereAddsComparisonConstraintWithoutOverwritingTheSameField( public function testWhereInAddsConstraint(): void { - $model = m::mock(Model::class); - $builder = new Builder($model, 'query'); - - $result = $builder->whereIn('id', [1, 2, 3]); - - $this->assertSame($builder, $result); - $this->assertSame(['id' => [1, 2, 3]], $builder->whereIns); - } - - public function testWhereInAcceptsArrayable(): void - { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); - // Use an array directly as Collection may not implement Arrayable $result = $builder->whereIn('id', [1, 2, 3]); $this->assertSame($builder, $result); @@ -108,7 +104,7 @@ public function testWhereInAcceptsArrayable(): void public function testWhereNotInAddsConstraint(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $result = $builder->whereNotIn('id', [4, 5, 6]); @@ -119,7 +115,7 @@ public function testWhereNotInAddsConstraint(): void public function testWithinSetsCustomIndex(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $result = $builder->within('custom_index'); @@ -130,7 +126,7 @@ public function testWithinSetsCustomIndex(): void public function testTakeSetsLimit(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $result = $builder->take(100); @@ -141,7 +137,7 @@ public function testTakeSetsLimit(): void public function testOrderByAddsOrder(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $result = $builder->orderBy('name', 'asc'); @@ -152,7 +148,7 @@ public function testOrderByAddsOrder(): void public function testOrderByNormalizesDirection(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $builder->orderBy('name', 'ASC'); @@ -162,7 +158,7 @@ public function testOrderByNormalizesDirection(): void public function testOrderByDescAddsDescendingOrder(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $result = $builder->orderByDesc('name'); @@ -173,8 +169,8 @@ public function testOrderByDescAddsDescendingOrder(): void public function testLatestOrdersByCreatedAtDesc(): void { - $model = m::mock(Model::class); - $model->shouldReceive('getCreatedAtColumn')->andReturn('created_at'); + $model = Double::for(Model::class)->strict(); + $model->allows('getCreatedAtColumn')->returns('created_at'); $builder = new Builder($model, 'query'); $result = $builder->latest(); @@ -185,7 +181,7 @@ public function testLatestOrdersByCreatedAtDesc(): void public function testLatestWithCustomColumn(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $result = $builder->latest('updated_at'); @@ -196,8 +192,8 @@ public function testLatestWithCustomColumn(): void public function testOldestOrdersByCreatedAtAsc(): void { - $model = m::mock(Model::class); - $model->shouldReceive('getCreatedAtColumn')->andReturn('created_at'); + $model = Double::for(Model::class)->strict(); + $model->allows('getCreatedAtColumn')->returns('created_at'); $builder = new Builder($model, 'query'); $result = $builder->oldest(); @@ -208,7 +204,7 @@ public function testOldestOrdersByCreatedAtAsc(): void public function testOptionsSetsOptions(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $result = $builder->options(['highlight' => true]); @@ -219,7 +215,7 @@ public function testOptionsSetsOptions(): void public function testQuerySetsQueryCallback(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $callback = fn () => 'test'; @@ -231,7 +227,7 @@ public function testQuerySetsQueryCallback(): void public function testWithRawResultsSetsCallback(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $callback = fn ($results) => $results; @@ -243,7 +239,7 @@ public function testWithRawResultsSetsCallback(): void public function testSoftDeleteSetsSoftDeleteWhere(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query', null, softDelete: true); $this->assertSame([[ @@ -255,7 +251,7 @@ public function testSoftDeleteSetsSoftDeleteWhere(): void public function testHardDeleteDoesNotSetSoftDeleteWhere(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query', null, softDelete: false); $this->assertSame([], $builder->wheres); @@ -263,7 +259,7 @@ public function testHardDeleteDoesNotSetSoftDeleteWhere(): void public function testWithTrashedRemovesSoftDeleteWhere(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query', null, softDelete: true); $this->assertSame('__soft_deleted', $builder->wheres[0]['field']); @@ -276,7 +272,7 @@ public function testWithTrashedRemovesSoftDeleteWhere(): void public function testOnlyTrashedSetsSoftDeleteWhereToOne(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query', null, softDelete: true); $result = $builder->onlyTrashed(); @@ -291,7 +287,7 @@ public function testOnlyTrashedSetsSoftDeleteWhereToOne(): void public function testSemanticSearchCanBeEnabled(): void { - $builder = (new Builder(m::mock(Model::class), 'conceptual query'))->semantic(minSimilarity: 0.7); + $builder = (new Builder(Double::for(Model::class)->strict(), 'conceptual query'))->semantic(minSimilarity: 0.7); $this->assertTrue($builder->semanticSearch); $this->assertNull($builder->hybridSearch); @@ -300,7 +296,7 @@ public function testSemanticSearchCanBeEnabled(): void public function testHybridSearchCanBeEnabledWithWeights(): void { - $builder = (new Builder(m::mock(Model::class), 'combined query'))->hybrid(2, 3, minSimilarity: 0.8); + $builder = (new Builder(Double::for(Model::class)->strict(), 'combined query'))->hybrid(2, 3, minSimilarity: 0.8); $this->assertFalse($builder->semanticSearch); $this->assertSame([ @@ -314,7 +310,7 @@ public function testSemanticAndHybridSearchRequireAQuery(): void { foreach (['semantic', 'hybrid'] as $method) { try { - (new Builder(m::mock(Model::class), ''))->{$method}(); + (new Builder(Double::for(Model::class)->strict(), ''))->{$method}(); $this->fail("Expected [{$method}] to reject an empty query."); } catch (ScoutException $e) { @@ -328,13 +324,13 @@ public function testHybridSearchRequiresPositiveWeights(): void $this->expectException(ScoutException::class); $this->expectExceptionMessageIsOrContains('positive numbers'); - (new Builder(m::mock(Model::class), 'query'))->hybrid(1, 0); + (new Builder(Double::for(Model::class)->strict(), 'query'))->hybrid(1, 0); } public function testUnsupportedEnginesRejectSemanticSearch(): void { - $model = m::mock(Model::class); - $model->shouldReceive('searchableUsing')->andReturn(m::mock(Engine::class)); + $model = Double::for(SearchableModel::class)->strict(); + $model->allows('searchableUsing')->returns(Double::for(Engine::class)->strict()); $this->expectException(NotSupportedException::class); $this->expectExceptionMessageIsOrContains('does not support semantic search'); @@ -344,10 +340,10 @@ public function testUnsupportedEnginesRejectSemanticSearch(): void public function testUnsupportedEnginesRejectSemanticSearchEnabledDuringPreparation(): void { - $model = m::mock(Model::class); - $engine = m::mock(Engine::class); - $model->shouldReceive('searchableUsing')->andReturn($engine); - $engine->shouldNotReceive('runSearch'); + $model = Double::for(SearchableModel::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $model->allows('searchableUsing')->returns($engine); + $engine->expects('runSearch')->never(); Scout::prepareBuilderUsing(function (Builder $builder): void { $builder->semantic(); @@ -361,10 +357,10 @@ public function testUnsupportedEnginesRejectSemanticSearchEnabledDuringPreparati public function testUnsupportedEnginesTreatHybridSearchAsNormalTextSearch(): void { - $model = m::mock(Model::class); - $engine = m::mock(Engine::class); - $model->shouldReceive('searchableUsing')->andReturn($engine); - $engine->shouldReceive('runSearch')->once()->andReturn(['results']); + $model = Double::for(SearchableModel::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $model->allows('searchableUsing')->returns($engine); + $engine->expects('runSearch')->returns(['results']); $results = (new Builder($model, 'query'))->hybrid()->raw(); @@ -373,13 +369,12 @@ public function testUnsupportedEnginesTreatHybridSearchAsNormalTextSearch(): voi public function testRawCallsEngineSearchEntryPoint(): void { - $model = m::mock(Model::class); - $engine = m::mock(Engine::class); - $model->shouldReceive('searchableUsing')->andReturn($engine); + $model = Double::for(SearchableModel::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $model->allows('searchableUsing')->returns($engine); - $engine->shouldReceive('runSearch') - ->once() - ->andReturn(['hits' => [], 'totalHits' => 0]); + $engine->expects('runSearch') + ->returns(['hits' => [], 'totalHits' => 0]); $builder = new Builder($model, 'query'); @@ -390,13 +385,12 @@ public function testRawCallsEngineSearchEntryPoint(): void public function testKeysCallsEngineKeys(): void { - $model = m::mock(Model::class); - $engine = m::mock(Engine::class); - $model->shouldReceive('searchableUsing')->andReturn($engine); + $model = Double::for(SearchableModel::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $model->allows('searchableUsing')->returns($engine); - $engine->shouldReceive('keys') - ->once() - ->andReturn(new Collection([1, 2, 3])); + $engine->expects('keys') + ->returns(new Collection([1, 2, 3])); $builder = new Builder($model, 'query'); @@ -407,13 +401,12 @@ public function testKeysCallsEngineKeys(): void public function testGetCallsEngineGet(): void { - $model = m::mock(Model::class); - $engine = m::mock(Engine::class); - $model->shouldReceive('searchableUsing')->andReturn($engine); + $model = Double::for(SearchableModel::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $model->allows('searchableUsing')->returns($engine); - $engine->shouldReceive('get') - ->once() - ->andReturn(new EloquentCollection([m::mock(Model::class)])); + $engine->expects('get') + ->returns(new EloquentCollection([Double::for(Model::class)->strict()])); $builder = new Builder($model, 'query'); @@ -425,15 +418,14 @@ public function testGetCallsEngineGet(): void public function testFirstReturnsFirstResult(): void { - $model = m::mock(Model::class); - $engine = m::mock(Engine::class); - $model->shouldReceive('searchableUsing')->andReturn($engine); + $model = Double::for(SearchableModel::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $model->allows('searchableUsing')->returns($engine); - $firstModel = m::mock(Model::class); + $firstModel = Double::for(Model::class)->strict(); - $engine->shouldReceive('get') - ->once() - ->andReturn(new EloquentCollection([$firstModel])); + $engine->expects('get') + ->returns(new EloquentCollection([$firstModel])); $builder = new Builder($model, 'query'); @@ -444,13 +436,12 @@ public function testFirstReturnsFirstResult(): void public function testFirstReturnsNullWhenNoResults(): void { - $model = m::mock(Model::class); - $engine = m::mock(Engine::class); - $model->shouldReceive('searchableUsing')->andReturn($engine); + $model = Double::for(SearchableModel::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $model->allows('searchableUsing')->returns($engine); - $engine->shouldReceive('get') - ->once() - ->andReturn(new EloquentCollection([])); + $engine->expects('get') + ->returns(new EloquentCollection([])); $builder = new Builder($model, 'query'); @@ -461,13 +452,13 @@ public function testFirstReturnsNullWhenNoResults(): void public function testResultTerminalsPrepareBuilderExactlyOnce(): void { - $model = m::mock(Model::class); - $engine = m::mock(Engine::class); - $model->shouldReceive('searchableUsing')->times(5)->andReturn($engine); - $engine->shouldReceive('runSearch')->once()->andReturn([]); - $engine->shouldReceive('keys')->once()->andReturn(new Collection); - $engine->shouldReceive('get')->twice()->andReturn(new EloquentCollection); - $engine->shouldReceive('cursor')->once()->andReturn(new LazyCollection([])); + $model = Double::for(SearchableModel::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $model->expects('searchableUsing')->times(5)->returns($engine); + $engine->expects('runSearch')->returns([]); + $engine->expects('keys')->returns(new Collection); + $engine->expects('get')->times(2)->returns(new EloquentCollection); + $engine->expects('cursor')->returns(new LazyCollection([])); $builder = new Builder($model, 'query'); $prepared = []; @@ -495,14 +486,14 @@ public function testPaginationTerminalsPrepareBeforeEngineExecution(): void Paginator::currentPageResolver(fn () => 1); Paginator::currentPathResolver(fn () => 'http://localhost/foo'); - $model = m::mock(Model::class); - $model->shouldReceive('getPerPage')->times(4)->andReturn(15); - $model->shouldNotReceive('searchableAs'); - $engine = m::mock(Engine::class . ', ' . PaginatesEloquentModels::class); - $model->shouldReceive('searchableUsing')->times(4)->andReturn($engine); + $model = Double::for(SearchableModel::class)->strict(); + $model->expects('getPerPage')->times(4)->returns(15); + $model->expects('searchableAs')->never(); + $engine = Double::for(BuilderTestPaginatingEngine::class)->strict(); + $model->expects('searchableUsing')->times(4)->returns($engine); $this->passThroughEngineOperations($engine, 4); - $engine->shouldReceive('paginate')->twice()->andReturn(new LengthAwarePaginator([], 0, 15, 1)); - $engine->shouldReceive('simplePaginate')->twice()->andReturn(new Paginator([], 15, 1)); + $engine->expects('paginate')->times(2)->returns(new LengthAwarePaginator([], 0, 15, 1)); + $engine->expects('simplePaginate')->times(2)->returns(new Paginator([], 15, 1)); $builder = new Builder($model, 'query'); $prepared = 0; @@ -533,25 +524,25 @@ public function testPaginationCorrectlyHandlesPaginatedResults(): void return 'http://localhost/foo'; }); - $model = m::mock(Model::class); - $model->shouldReceive('getPerPage')->andReturn(15); - $model->shouldReceive('searchableUsing')->andReturn($engine = m::mock(Engine::class)); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); + $model = Double::for(SearchableModel::class)->strict(); + $model->allows('getPerPage')->returns(15); + $model->allows('searchableUsing')->returns($engine = Double::for(Engine::class)->strict()); + $model->allows('getScoutKeyName')->returns('id'); // Create collection manually instead of using times() $items = []; for ($i = 0; $i < 15; ++$i) { - $items[] = m::mock(Model::class); + $items[] = Double::for(Model::class)->strict(); } $results = new EloquentCollection($items); - $engine->shouldReceive('runPaginate')->once(); - $engine->shouldReceive('map')->andReturn($results); - $engine->shouldReceive('getTotalCount')->andReturn(16); + $engine->expects('runPaginate'); + $engine->allows('map')->returns($results); + $engine->allows('getTotalCount')->returns(16); - $model->shouldReceive('newCollection') - ->with(m::type('array')) - ->andReturn($results); + $model->allows('newCollection') + ->with(Argument::type('array')) + ->returns($results); $builder = new Builder($model, 'zonda'); $paginated = $builder->paginate(); @@ -571,24 +562,24 @@ public function testSimplePaginationCorrectlyHandlesPaginatedResults(): void return 'http://localhost/foo'; }); - $model = m::mock(Model::class); - $model->shouldReceive('getPerPage')->andReturn(15); - $model->shouldReceive('searchableUsing')->andReturn($engine = m::mock(Engine::class)); + $model = Double::for(SearchableModel::class)->strict(); + $model->allows('getPerPage')->returns(15); + $model->allows('searchableUsing')->returns($engine = Double::for(Engine::class)->strict()); // Create collection manually instead of using times() $items = []; for ($i = 0; $i < 15; ++$i) { - $items[] = m::mock(Model::class); + $items[] = Double::for(Model::class)->strict(); } $results = new EloquentCollection($items); - $engine->shouldReceive('runPaginate')->once(); - $engine->shouldReceive('map')->andReturn($results); - $engine->shouldReceive('getTotalCount')->andReturn(16); + $engine->expects('runPaginate'); + $engine->allows('map')->returns($results); + $engine->allows('getTotalCount')->returns(16); - $model->shouldReceive('newCollection') - ->with(m::type('array')) - ->andReturn($results); + $model->allows('newCollection') + ->with(Argument::type('array')) + ->returns($results); $builder = new Builder($model, 'zonda'); $paginated = $builder->simplePaginate(); @@ -603,26 +594,26 @@ public function testGenericPaginatorsShareTheTransformedPayloadWithMappingAndMet { Paginator::currentPathResolver(fn () => 'http://localhost/foo'); - $model = m::mock(Model::class); - $engine = m::mock(Engine::class); - $model->shouldReceive('getPerPage')->times(4)->andReturn(15); - $model->shouldReceive('searchableUsing')->times(8)->andReturn($engine); - $model->shouldReceive('newCollection')->twice()->andReturnUsing( + $model = Double::for(SearchableModel::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $model->expects('getPerPage')->times(4)->returns(15); + $model->expects('searchableUsing')->times(8)->returns($engine); + $model->expects('newCollection')->times(2)->resolves( fn (array $models) => new EloquentCollection($models) ); $rawResults = ['hits' => ['raw'], 'estimatedTotalHits' => 30]; $transformedResults = ['hits' => ['transformed'], 'estimatedTotalHits' => 16]; - $engine->shouldReceive('runPaginate')->times(4)->andReturn($rawResults); - $engine->shouldReceive('map') - ->twice() - ->withArgs(fn (Builder $builder, array $results, Model $givenModel): bool => $results === $transformedResults - && $givenModel === $model) - ->andReturn(new EloquentCollection); - $engine->shouldReceive('getTotalCount') + $engine->expects('runPaginate')->times(4)->returns($rawResults); + $engine->expects('map') + ->times(2) + ->with(Argument::all(fn (Builder $builder, array $results, Model $givenModel): bool => $results === $transformedResults + && $givenModel === $model)) + ->returns(new EloquentCollection); + $engine->expects('getTotalCount') ->times(4) ->with($transformedResults) - ->andReturn(16); + ->returns(16); $callbackInvocations = 0; $builder = (new Builder($model, 'zonda'))->withRawResults( @@ -644,26 +635,26 @@ public function testSimplePaginatorsApplyTheEloquentQueryCallbackToTheirTotals() { Paginator::currentPathResolver(fn () => 'http://localhost/foo'); - $model = m::mock(Model::class . ', ' . SearchableInterface::class); - $engine = m::mock(Engine::class); - $eloquentQuery = m::mock(\Hypervel\Database\Eloquent\Builder::class); - $baseQuery = m::mock(\Hypervel\Database\Query\Builder::class); + $model = Double::for(SearchableModel::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $eloquentQuery = Double::for(EloquentBuilder::class)->strict(); + $baseQuery = Double::for(QueryBuilder::class)->strict(); $rawResults = ['hits' => [], 'estimatedTotalHits' => 16]; - $model->shouldReceive('getPerPage')->twice()->andReturn(15); - $model->shouldReceive('searchableUsing')->times(4)->andReturn($engine); - $model->shouldReceive('newCollection')->once()->andReturn(new EloquentCollection); - $model->shouldReceive('getScoutKeyName')->twice()->andReturn('id'); - $model->shouldReceive('queryScoutModelsByIds') - ->twice() - ->withArgs(fn (Builder $builder, array $ids): bool => count($ids) === 16) - ->andReturn($eloquentQuery); - $eloquentQuery->shouldReceive('toBase')->twice()->andReturn($baseQuery); - $baseQuery->shouldReceive('getCountForPagination')->twice()->andReturn(15); - $engine->shouldReceive('runPaginate')->twice()->andReturn($rawResults); - $engine->shouldReceive('map')->once()->andReturn(new EloquentCollection); - $engine->shouldReceive('getTotalCount')->twice()->andReturn(16); - $engine->shouldReceive('mapIdsFrom')->twice()->andReturn(new Collection(range(1, 16))); + $model->expects('getPerPage')->times(2)->returns(15); + $model->expects('searchableUsing')->times(4)->returns($engine); + $model->expects('newCollection')->returns(new EloquentCollection); + $model->expects('getScoutKeyName')->times(2)->returns('id'); + $model->expects('queryScoutModelsByIds') + ->times(2) + ->with(Argument::all(fn (Builder $builder, array $ids): bool => count($ids) === 16)) + ->returns($eloquentQuery); + $eloquentQuery->expects('toBase')->times(2)->returns($baseQuery); + $baseQuery->expects('getCountForPagination')->times(2)->returns(15); + $engine->expects('runPaginate')->times(2)->returns($rawResults); + $engine->expects('map')->returns(new EloquentCollection); + $engine->expects('getTotalCount')->times(2)->returns(16); + $engine->expects('mapIdsFrom')->times(2)->returns(new Collection(range(1, 16))); $builder = (new Builder($model, 'zonda'))->query(static function (): void { }); @@ -676,36 +667,32 @@ public function testQueryCallbackTotalSearchIsObservedAfterPagination(): void { Paginator::currentPathResolver(fn () => 'http://localhost/foo'); - $model = m::mock(Model::class . ', ' . SearchableInterface::class); - $engine = m::mock(Engine::class)->makePartial(); - $eloquentQuery = m::mock(\Hypervel\Database\Eloquent\Builder::class); - $baseQuery = m::mock(\Hypervel\Database\Query\Builder::class); + $model = Double::for(SearchableModel::class)->strict(); + $engine = Double::for(Engine::class)->passthru(); + $eloquentQuery = Double::for(EloquentBuilder::class)->strict(); + $baseQuery = Double::for(QueryBuilder::class)->strict(); $rawResults = ['hits' => [], 'estimatedTotalHits' => 2]; $runner = new EngineOperationRunner; - $observer = m::mock(EngineOperationObserver::class); + $observer = Double::for(EngineOperationObserver::class)->strict(); - $observer->shouldReceive('starting') - ->once() - ->with(m::on(fn (EngineOperation $operation): bool => $operation->operation === 'paginate')) + $observer->expects('starting') + ->with(Argument::satisfies(fn (EngineOperation $operation): bool => $operation->operation === 'paginate')) ->ordered() - ->andReturn('paginate'); - $observer->shouldReceive('finished') - ->once() + ->returns('paginate'); + $observer->expects('finished') ->with( - m::on(fn (EngineOperation $operation): bool => $operation->operation === 'paginate'), + Argument::satisfies(fn (EngineOperation $operation): bool => $operation->operation === 'paginate'), 'paginate', null, ) ->ordered(); - $observer->shouldReceive('starting') - ->once() - ->with(m::on(fn (EngineOperation $operation): bool => $operation->operation === 'search')) + $observer->expects('starting') + ->with(Argument::satisfies(fn (EngineOperation $operation): bool => $operation->operation === 'search')) ->ordered() - ->andReturn('search'); - $observer->shouldReceive('finished') - ->once() + ->returns('search'); + $observer->expects('finished') ->with( - m::on(fn (EngineOperation $operation): bool => $operation->operation === 'search'), + Argument::satisfies(fn (EngineOperation $operation): bool => $operation->operation === 'search'), 'search', null, ) @@ -714,23 +701,22 @@ public function testQueryCallbackTotalSearchIsObservedAfterPagination(): void $runner->observe($observer); $engine->setOperationRunner($runner, 'fixture'); - $model->shouldReceive('getPerPage')->once()->andReturn(15); - $model->shouldReceive('searchableUsing')->twice()->andReturn($engine); - $model->shouldReceive('searchableAs')->twice()->andReturn('read_index'); - $model->shouldReceive('newCollection')->once()->andReturn(new EloquentCollection); - $model->shouldReceive('getScoutKeyName')->once()->andReturn('id'); - $model->shouldReceive('queryScoutModelsByIds') - ->once() - ->withArgs(fn (Builder $builder, array $ids): bool => $ids === [1, 2]) - ->andReturn($eloquentQuery); - $eloquentQuery->shouldReceive('toBase')->once()->andReturn($baseQuery); - $baseQuery->shouldReceive('getCountForPagination')->once()->andReturn(2); - $engine->shouldReceive('paginate')->once()->andReturn($rawResults); - $engine->shouldReceive('map')->once()->andReturn(new EloquentCollection); - $engine->shouldReceive('getTotalCount')->once()->andReturn(2); - $engine->shouldReceive('mapIdsFrom')->once()->andReturn(new Collection([1])); - $engine->shouldReceive('search')->once()->andReturn(['hits' => [1, 2]]); - $engine->shouldReceive('mapIds')->once()->andReturn(new Collection([1, 2])); + $model->expects('getPerPage')->returns(15); + $model->expects('searchableUsing')->times(2)->returns($engine); + $model->expects('searchableAs')->times(2)->returns('read_index'); + $model->expects('newCollection')->returns(new EloquentCollection); + $model->expects('getScoutKeyName')->returns('id'); + $model->expects('queryScoutModelsByIds') + ->with(Argument::all(fn (Builder $builder, array $ids): bool => $ids === [1, 2])) + ->returns($eloquentQuery); + $eloquentQuery->expects('toBase')->returns($baseQuery); + $baseQuery->expects('getCountForPagination')->returns(2); + $engine->expects('paginate')->returns($rawResults); + $engine->expects('map')->returns(new EloquentCollection); + $engine->expects('getTotalCount')->returns(2); + $engine->expects('mapIdsFrom')->returns(new Collection([1])); + $engine->expects('search')->returns(['hits' => [1, 2]]); + $engine->expects('mapIds')->returns(new Collection([1, 2])); $builder = (new Builder($model, 'zonda'))->query(static function (): void { }); @@ -743,22 +729,21 @@ public function testPaginateDelegatesToEngineWhenImplementsPaginatesEloquentMode Paginator::currentPageResolver(fn () => 1); Paginator::currentPathResolver(fn () => 'http://localhost/foo'); - $model = m::mock(Model::class); - $model->shouldReceive('getPerPage')->andReturn(15); - $model->shouldNotReceive('searchableAs'); + $model = Double::for(SearchableModel::class)->strict(); + $model->allows('getPerPage')->returns(15); + $model->expects('searchableAs')->never(); // Create a mock engine that implements PaginatesEloquentModels - $engine = m::mock(Engine::class . ', ' . PaginatesEloquentModels::class); - $model->shouldReceive('searchableUsing')->andReturn($engine); + $engine = Double::for(BuilderTestPaginatingEngine::class)->strict(); + $model->allows('searchableUsing')->returns($engine); $this->passThroughEngineOperations($engine, 1); $expectedPaginator = new LengthAwarePaginator([], 0, 15, 1); // The engine's paginate method should be called directly - $engine->shouldReceive('paginate') - ->once() - ->with(m::type(Builder::class), 15, 1) - ->andReturn($expectedPaginator); + $engine->expects('paginate') + ->with(Argument::type(Builder::class), 15, 1) + ->returns($expectedPaginator); $builder = new Builder($model, 'test query'); $result = $builder->paginate(); @@ -771,22 +756,21 @@ public function testSimplePaginateDelegatesToEngineWhenImplementsPaginatesEloque Paginator::currentPageResolver(fn () => 1); Paginator::currentPathResolver(fn () => 'http://localhost/foo'); - $model = m::mock(Model::class); - $model->shouldReceive('getPerPage')->andReturn(15); - $model->shouldNotReceive('searchableAs'); + $model = Double::for(SearchableModel::class)->strict(); + $model->allows('getPerPage')->returns(15); + $model->expects('searchableAs')->never(); // Create a mock engine that implements PaginatesEloquentModels - $engine = m::mock(Engine::class . ', ' . PaginatesEloquentModels::class); - $model->shouldReceive('searchableUsing')->andReturn($engine); + $engine = Double::for(BuilderTestPaginatingEngine::class)->strict(); + $model->allows('searchableUsing')->returns($engine); $this->passThroughEngineOperations($engine, 1); $expectedPaginator = new Paginator([], 15, 1); // The engine's simplePaginate method should be called directly - $engine->shouldReceive('simplePaginate') - ->once() - ->with(m::type(Builder::class), 15, 1) - ->andReturn($expectedPaginator); + $engine->expects('simplePaginate') + ->with(Argument::type(Builder::class), 15, 1) + ->returns($expectedPaginator); $builder = new Builder($model, 'test query'); $result = $builder->simplePaginate(); @@ -799,22 +783,21 @@ public function testPaginateDelegatesToEngineWhenImplementsPaginatesEloquentMode Paginator::currentPageResolver(fn () => 1); Paginator::currentPathResolver(fn () => 'http://localhost/foo'); - $model = m::mock(Model::class); - $model->shouldReceive('getPerPage')->andReturn(15); - $model->shouldNotReceive('searchableAs'); + $model = Double::for(SearchableModel::class)->strict(); + $model->allows('getPerPage')->returns(15); + $model->expects('searchableAs')->never(); // Create a mock engine that implements PaginatesEloquentModelsUsingDatabase - $engine = m::mock(Engine::class . ', ' . PaginatesEloquentModelsUsingDatabase::class); - $model->shouldReceive('searchableUsing')->andReturn($engine); + $engine = Double::for(BuilderTestDatabasePaginatingEngine::class)->strict(); + $model->allows('searchableUsing')->returns($engine); $this->passThroughEngineOperations($engine, 1); $expectedPaginator = new LengthAwarePaginator([], 0, 15, 1); // The engine's paginateUsingDatabase method should be called - $engine->shouldReceive('paginateUsingDatabase') - ->once() - ->with(m::type(Builder::class), 15, 'page', 1) - ->andReturn($expectedPaginator); + $engine->expects('paginateUsingDatabase') + ->with(Argument::type(Builder::class), 15, 'page', 1) + ->returns($expectedPaginator); $builder = new Builder($model, 'test query'); $result = $builder->paginate(); @@ -827,22 +810,21 @@ public function testSimplePaginateDelegatesToEngineWhenImplementsPaginatesEloque Paginator::currentPageResolver(fn () => 1); Paginator::currentPathResolver(fn () => 'http://localhost/foo'); - $model = m::mock(Model::class); - $model->shouldReceive('getPerPage')->andReturn(15); - $model->shouldNotReceive('searchableAs'); + $model = Double::for(SearchableModel::class)->strict(); + $model->allows('getPerPage')->returns(15); + $model->expects('searchableAs')->never(); // Create a mock engine that implements PaginatesEloquentModelsUsingDatabase - $engine = m::mock(Engine::class . ', ' . PaginatesEloquentModelsUsingDatabase::class); - $model->shouldReceive('searchableUsing')->andReturn($engine); + $engine = Double::for(BuilderTestDatabasePaginatingEngine::class)->strict(); + $model->allows('searchableUsing')->returns($engine); $this->passThroughEngineOperations($engine, 1); $expectedPaginator = new Paginator([], 15, 1); // The engine's simplePaginateUsingDatabase method should be called - $engine->shouldReceive('simplePaginateUsingDatabase') - ->once() - ->with(m::type(Builder::class), 15, 'page', 1) - ->andReturn($expectedPaginator); + $engine->expects('simplePaginateUsingDatabase') + ->with(Argument::type(Builder::class), 15, 'page', 1) + ->returns($expectedPaginator); $builder = new Builder($model, 'test query'); $result = $builder->simplePaginate(); @@ -852,25 +834,23 @@ public function testSimplePaginateDelegatesToEngineWhenImplementsPaginatesEloque public function testRawPaginationDelegatesToEngineWhenItPaginatesEloquentModels(): void { - $model = m::mock(Model::class); - $model->shouldReceive('getPerPage')->twice()->andReturn(15); - $model->shouldNotReceive('searchableAs'); + $model = Double::for(SearchableModel::class)->strict(); + $model->expects('getPerPage')->times(2)->returns(15); + $model->expects('searchableAs')->never(); - $engine = m::mock(Engine::class . ', ' . PaginatesEloquentModels::class); - $model->shouldReceive('searchableUsing')->twice()->andReturn($engine); + $engine = Double::for(BuilderTestPaginatingEngine::class)->strict(); + $model->expects('searchableUsing')->times(2)->returns($engine); $this->passThroughEngineOperations($engine, 2); $expectedPaginator = new LengthAwarePaginator([], 0, 15, 1); $expectedSimplePaginator = new Paginator([], 15, 1); - $engine->shouldReceive('paginate') - ->once() - ->with(m::type(Builder::class), 15, 1) - ->andReturn($expectedPaginator); - $engine->shouldReceive('simplePaginate') - ->once() - ->with(m::type(Builder::class), 15, 1) - ->andReturn($expectedSimplePaginator); + $engine->expects('paginate') + ->with(Argument::type(Builder::class), 15, 1) + ->returns($expectedPaginator); + $engine->expects('simplePaginate') + ->with(Argument::type(Builder::class), 15, 1) + ->returns($expectedSimplePaginator); $builder = new Builder($model, 'test query'); @@ -880,25 +860,23 @@ public function testRawPaginationDelegatesToEngineWhenItPaginatesEloquentModels( public function testRawPaginationDelegatesToEngineWhenItPaginatesUsingDatabase(): void { - $model = m::mock(Model::class); - $model->shouldReceive('getPerPage')->twice()->andReturn(15); - $model->shouldNotReceive('searchableAs'); + $model = Double::for(SearchableModel::class)->strict(); + $model->expects('getPerPage')->times(2)->returns(15); + $model->expects('searchableAs')->never(); - $engine = m::mock(Engine::class . ', ' . PaginatesEloquentModelsUsingDatabase::class); - $model->shouldReceive('searchableUsing')->twice()->andReturn($engine); + $engine = Double::for(BuilderTestDatabasePaginatingEngine::class)->strict(); + $model->expects('searchableUsing')->times(2)->returns($engine); $this->passThroughEngineOperations($engine, 2); $expectedPaginator = new LengthAwarePaginator([], 0, 15, 1); $expectedSimplePaginator = new Paginator([], 15, 1); - $engine->shouldReceive('paginateUsingDatabase') - ->once() - ->with(m::type(Builder::class), 15, 'results', 1) - ->andReturn($expectedPaginator); - $engine->shouldReceive('simplePaginateUsingDatabase') - ->once() - ->with(m::type(Builder::class), 15, 'results', 1) - ->andReturn($expectedSimplePaginator); + $engine->expects('paginateUsingDatabase') + ->with(Argument::type(Builder::class), 15, 'results', 1) + ->returns($expectedPaginator); + $engine->expects('simplePaginateUsingDatabase') + ->with(Argument::type(Builder::class), 15, 'results', 1) + ->returns($expectedSimplePaginator); $builder = new Builder($model, 'test query'); @@ -911,19 +889,18 @@ public function testOptionalPaginationDoesNotResolveSearchIndexWithoutObservers( Paginator::currentPageResolver(fn () => 1); Paginator::currentPathResolver(fn () => 'http://localhost/foo'); - $model = m::mock(Model::class); - $model->shouldReceive('getPerPage')->once()->andReturn(15); - $model->shouldNotReceive('searchableAs'); + $model = Double::for(SearchableModel::class)->strict(); + $model->expects('getPerPage')->returns(15); + $model->expects('searchableAs')->never(); - $engine = m::mock(DatabaseEngine::class)->makePartial(); + $engine = Double::for(DatabaseEngine::class)->passthru(); $engine->setOperationRunner(new EngineOperationRunner, 'database'); - $model->shouldReceive('searchableUsing')->once()->andReturn($engine); + $model->expects('searchableUsing')->returns($engine); $expectedPaginator = new LengthAwarePaginator([], 0, 15, 1); - $engine->shouldReceive('paginateUsingDatabase') - ->once() - ->with(m::type(Builder::class), 15, 'page', 1) - ->andReturn($expectedPaginator); + $engine->expects('paginateUsingDatabase') + ->with(Argument::type(Builder::class), 15, 'page', 1) + ->returns($expectedPaginator); $this->assertSame($expectedPaginator, (new Builder($model, 'query'))->paginate()); } @@ -936,18 +913,18 @@ public function testGenericPaginationUsesFreshContainerSubstitutionsAndDefaultPe Container::getInstance()->bind(Paginator::class, ScoutBuilderPaginator::class); Container::getInstance()->bind(LengthAwarePaginator::class, ScoutBuilderLengthAwarePaginator::class); - $model = m::mock(Model::class); - $model->shouldReceive('getPerPage')->times(4)->andReturn(15); - $model->shouldReceive('searchableUsing')->times(8)->andReturn($engine = m::mock(Engine::class)); - $model->shouldReceive('newCollection')->twice()->andReturnUsing( + $model = Double::for(SearchableModel::class)->strict(); + $model->expects('getPerPage')->times(4)->returns(15); + $model->expects('searchableUsing')->times(8)->returns($engine = Double::for(Engine::class)->strict()); + $model->expects('newCollection')->times(2)->resolves( fn (array $models) => new EloquentCollection($models) ); $rawResults = ['hits' => [], 'estimatedTotalHits' => 0]; - $engine->shouldReceive('runPaginate')->times(4)->andReturn($rawResults); - $engine->shouldReceive('map')->twice()->andReturn(new EloquentCollection); - $engine->shouldReceive('getTotalCount')->times(4)->andReturn(0); + $engine->expects('runPaginate')->times(4)->returns($rawResults); + $engine->expects('map')->times(2)->returns(new EloquentCollection); + $engine->expects('getTotalCount')->times(4)->returns(0); $builder = new Builder($model, 'zonda'); @@ -974,15 +951,15 @@ public function testPublicPaginationBoundariesClampInvalidPagesBeforeEngineDispa Paginator::currentPageResolver(fn () => 3); Paginator::currentPathResolver(fn () => 'http://localhost/foo'); - $model = m::mock(Model::class); - $engine = m::mock(Engine::class); - $model->shouldReceive('getPerPage')->times(5)->andReturn(15); - $model->shouldReceive('searchableUsing')->times(10)->andReturn($engine); - $model->shouldReceive('newCollection')->twice()->andReturn(new EloquentCollection); + $model = Double::for(SearchableModel::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $model->expects('getPerPage')->times(5)->returns(15); + $model->expects('searchableUsing')->times(10)->returns($engine); + $model->expects('newCollection')->times(2)->returns(new EloquentCollection); $pages = []; $rawResults = ['hits' => [], 'estimatedTotalHits' => 0]; - $engine->shouldReceive('runPaginate')->times(5)->andReturnUsing( + $engine->expects('runPaginate')->times(5)->resolves( function (Builder $_, int $perPage, int $page) use (&$pages, $rawResults): array { $this->assertSame(15, $perPage); $pages[] = $page; @@ -990,8 +967,8 @@ function (Builder $_, int $perPage, int $page) use (&$pages, $rawResults): array return $rawResults; } ); - $engine->shouldReceive('map')->twice()->andReturn(new EloquentCollection); - $engine->shouldReceive('getTotalCount')->times(5)->andReturn(0); + $engine->expects('map')->times(2)->returns(new EloquentCollection); + $engine->expects('getTotalCount')->times(5)->returns(0); $builder = new Builder($model, 'query'); @@ -1009,7 +986,7 @@ public function testMacroable(): void return 'macro result'; }); - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $this->assertSame('macro result', $builder->testMacro()); @@ -1017,7 +994,7 @@ public function testMacroable(): void public function testApplyAfterRawSearchCallbackInvokesCallback(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $builder->withRawResults(function ($results) { @@ -1032,7 +1009,7 @@ public function testApplyAfterRawSearchCallbackInvokesCallback(): void public function testApplyAfterRawSearchCallbackReturnsOriginalWhenNoCallback(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); $original = ['hits' => []]; @@ -1050,14 +1027,14 @@ public function testSimplePaginateRawCorrectlyHandlesPaginatedResults(): void return 'http://localhost/foo'; }); - $model = m::mock(Model::class); - $model->shouldReceive('getPerPage')->andReturn(15); - $model->shouldReceive('searchableUsing')->andReturn($engine = m::mock(Engine::class)); + $model = Double::for(SearchableModel::class)->strict(); + $model->allows('getPerPage')->returns(15); + $model->allows('searchableUsing')->returns($engine = Double::for(Engine::class)->strict()); $rawResults = ['hits' => [], 'estimatedTotalHits' => 16]; - $engine->shouldReceive('runPaginate')->once()->andReturn($rawResults); - $engine->shouldReceive('getTotalCount')->andReturn(16); + $engine->expects('runPaginate')->returns($rawResults); + $engine->allows('getTotalCount')->returns(16); $builder = new Builder($model, 'zonda'); $paginated = $builder->simplePaginateRaw(); @@ -1070,7 +1047,7 @@ public function testSimplePaginateRawCorrectlyHandlesPaginatedResults(): void public function testWhereInAcceptsArrayableInterface(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); // Create a Collection (which implements Arrayable) @@ -1084,7 +1061,7 @@ public function testWhereInAcceptsArrayableInterface(): void public function testWhereNotInAcceptsArrayableInterface(): void { - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); $builder = new Builder($model, 'query'); // Create a Collection (which implements Arrayable) @@ -1097,18 +1074,18 @@ public function testWhereNotInAcceptsArrayableInterface(): void } /** - * Let mocked optional engine operations execute their narrowed callback. + * Let doubled optional engine operations execute their narrowed callback. */ - protected function passThroughEngineOperations(m\MockInterface&Engine $engine, int $times): void + protected function passThroughEngineOperations(Engine&DoubleInterface $engine, int $times): void { - $engine->shouldReceive('runOperation') + $engine->expects('runOperation') ->times($times) ->with( 'paginate', - m::type(Builder::class), - m::type(Closure::class), + Argument::type(Builder::class), + Argument::type(Closure::class), ) - ->andReturnUsing( + ->resolves( fn (string $operation, Builder $builder, Closure $callback): mixed => $callback() ); } @@ -1121,3 +1098,15 @@ class ScoutBuilderPaginator extends Paginator class ScoutBuilderLengthAwarePaginator extends LengthAwarePaginator { } + +abstract class BuilderTestPaginatingEngine extends Engine implements PaginatesEloquentModels +{ + /** + * Paginate the given search on the engine. + */ + abstract public function paginate(Builder $builder, int $perPage, int $page): LengthAwarePaginatorContract; +} + +abstract class BuilderTestDatabasePaginatingEngine extends Engine implements PaginatesEloquentModelsUsingDatabase +{ +} diff --git a/tests/Scout/Unit/Console/ConcurrentImportRunnerTest.php b/tests/Scout/Unit/Console/ConcurrentImportRunnerTest.php index f4a80e3c6e..f64dc498f1 100644 --- a/tests/Scout/Unit/Console/ConcurrentImportRunnerTest.php +++ b/tests/Scout/Unit/Console/ConcurrentImportRunnerTest.php @@ -16,7 +16,8 @@ use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Scout\Console\ConcurrentImportRunner; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -24,6 +25,8 @@ class ConcurrentImportRunnerTest extends TestCase { + use VerifiesDoubles; + public function testChildrenPreserveTheScopedDefaultDatabaseConnection(): void { $container = new Container; @@ -124,8 +127,8 @@ public function testWaitDrainsActiveChildrenBeforeRethrowingTheFirstFailure(): v public function testCancellationWhileReleasingTheParentConnectionCancelsActiveImports(bool $cleanupThrows): void { $failure = $cleanupThrows ? new RuntimeException('Release cleanup failed.', previous: new CanceledException) : new CanceledException; - $lease = m::mock(ConnectionLease::class); - $lease->shouldReceive('releaseIfIdle')->once()->andThrow($failure); + $lease = Double::for(ConnectionLease::class)->strict(); + $lease->expects('releaseIfIdle')->throws($failure); $runner = new ConcurrentImportRunner(1); $blocker = new Channel(1); $childCanceled = false; diff --git a/tests/Scout/Unit/Console/DeleteAllIndexesCommandTest.php b/tests/Scout/Unit/Console/DeleteAllIndexesCommandTest.php index 97f7873a98..5220ce1e01 100644 --- a/tests/Scout/Unit/Console/DeleteAllIndexesCommandTest.php +++ b/tests/Scout/Unit/Console/DeleteAllIndexesCommandTest.php @@ -11,29 +11,30 @@ use Hypervel\Scout\Engines\CollectionEngine; use Hypervel\Scout\Engines\MeilisearchEngine; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class DeleteAllIndexesCommandTest extends TestCase { + use VerifiesDoubles; + public function testDeletesAllIndexesSuccessfully(): void { - $engine = m::mock(MeilisearchEngine::class); - $engine->shouldReceive('deleteAllIndexes') - ->once() + $engine = Double::for(MeilisearchEngine::class)->strict(); + $engine->expects('deleteAllIndexes') ->with('test_') - ->andReturn([]); + ->returns([]); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine') - ->once() - ->andReturn($engine); + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine') + ->returns($engine); $config = $this->configWithPrefix('test_'); - $command = m::mock(DeleteAllIndexesCommand::class)->makePartial(); - $command->shouldReceive('option')->with('force')->andReturn(false); - $command->shouldReceive('info') - ->once() + $command = Double::for(new DeleteAllIndexesCommand)->passthru(); + $command->allows('option')->with('force')->returns(false); + $command->expects('info') ->with('All indexes deleted successfully.'); $result = $command->handle($manager, $config); @@ -45,23 +46,20 @@ public function testFailsWhenEngineDoesNotSupportDeleteAllIndexes(): void { $engine = new CollectionEngine; - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine') - ->once() - ->andReturn($engine); - $manager->shouldReceive('getDefaultDriver') - ->once() - ->andReturn('collection'); + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine') + ->returns($engine); + $manager->expects('getDefaultDriver') + ->returns('collection'); // Must set a non-empty prefix: the safety gate runs before engine // resolution, and with an empty prefix we'd hit the refusal message // rather than the "does not support" path. $config = $this->configWithPrefix('test_'); - $command = m::mock(DeleteAllIndexesCommand::class)->makePartial(); - $command->shouldReceive('option')->with('force')->andReturn(false); - $command->shouldReceive('error') - ->once() + $command = Double::for(new DeleteAllIndexesCommand)->passthru(); + $command->allows('option')->with('force')->returns(false); + $command->expects('error') ->with('The [collection] engine does not support deleting all indexes.'); $result = $command->handle($manager, $config); @@ -71,23 +69,20 @@ public function testFailsWhenEngineDoesNotSupportDeleteAllIndexes(): void public function testHandlesExceptionFromEngine(): void { - $engine = m::mock(MeilisearchEngine::class); - $engine->shouldReceive('deleteAllIndexes') - ->once() + $engine = Double::for(MeilisearchEngine::class)->strict(); + $engine->expects('deleteAllIndexes') ->with('test_') - ->andThrow(new Exception('Connection failed')); + ->throws(new Exception('Connection failed')); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine') - ->once() - ->andReturn($engine); + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine') + ->returns($engine); $config = $this->configWithPrefix('test_'); - $command = m::mock(DeleteAllIndexesCommand::class)->makePartial(); - $command->shouldReceive('option')->with('force')->andReturn(false); - $command->shouldReceive('error') - ->once() + $command = Double::for(new DeleteAllIndexesCommand)->passthru(); + $command->allows('option')->with('force')->returns(false); + $command->expects('error') ->with('Connection failed'); $result = $command->handle($manager, $config); @@ -97,22 +92,17 @@ public function testHandlesExceptionFromEngine(): void public function testRefusesWhenPrefixEmptyAndNotForced(): void { - $manager = m::mock(EngineManager::class); + $manager = Double::for(EngineManager::class)->strict(); // Safety gate runs first; engine is never resolved. - $manager->shouldNotReceive('engine'); + $manager->expects('engine')->never(); $config = $this->configWithPrefix(''); $capturedMessage = null; - $command = m::mock(DeleteAllIndexesCommand::class)->makePartial(); - $command->shouldReceive('option')->with('force')->andReturn(false); - $command->shouldReceive('error') - ->once() - ->with(m::on(function (string $message) use (&$capturedMessage) { - $capturedMessage = $message; - - return true; - })); + $command = Double::for(new DeleteAllIndexesCommand)->passthru(); + $command->allows('option')->with('force')->returns(false); + $command->expects('error') + ->with(Argument::capture($capturedMessage)); $result = $command->handle($manager, $config); @@ -123,22 +113,20 @@ public function testRefusesWhenPrefixEmptyAndNotForced(): void public function testRunsUnscopedWhenForcedWithEmptyPrefix(): void { - $engine = m::mock(MeilisearchEngine::class); - $engine->shouldReceive('deleteAllIndexes') - ->once() + $engine = Double::for(MeilisearchEngine::class)->strict(); + $engine->expects('deleteAllIndexes') ->with(null) - ->andReturn([]); + ->returns([]); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine') - ->once() - ->andReturn($engine); + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine') + ->returns($engine); $config = $this->configWithPrefix(''); - $command = m::mock(DeleteAllIndexesCommand::class)->makePartial(); - $command->shouldReceive('option')->with('force')->andReturn(true); - $command->shouldReceive('info')->once(); + $command = Double::for(new DeleteAllIndexesCommand)->passthru(); + $command->allows('option')->with('force')->returns(true); + $command->expects('info'); $result = $command->handle($manager, $config); @@ -147,22 +135,20 @@ public function testRunsUnscopedWhenForcedWithEmptyPrefix(): void public function testRunsScopedWhenPrefixSet(): void { - $engine = m::mock(MeilisearchEngine::class); - $engine->shouldReceive('deleteAllIndexes') - ->once() + $engine = Double::for(MeilisearchEngine::class)->strict(); + $engine->expects('deleteAllIndexes') ->with('app_') - ->andReturn([]); + ->returns([]); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine') - ->once() - ->andReturn($engine); + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine') + ->returns($engine); $config = $this->configWithPrefix('app_'); - $command = m::mock(DeleteAllIndexesCommand::class)->makePartial(); - $command->shouldReceive('option')->with('force')->andReturn(false); - $command->shouldReceive('info')->once(); + $command = Double::for(new DeleteAllIndexesCommand)->passthru(); + $command->allows('option')->with('force')->returns(false); + $command->expects('info'); $result = $command->handle($manager, $config); @@ -171,36 +157,32 @@ public function testRunsScopedWhenPrefixSet(): void public function testForceDoesNotOverrideScopingWhenPrefixSet(): void { - $engine = m::mock(MeilisearchEngine::class); + $engine = Double::for(MeilisearchEngine::class)->strict(); // Even with --force, the configured prefix still scopes the deletion. - $engine->shouldReceive('deleteAllIndexes') - ->once() + $engine->expects('deleteAllIndexes') ->with('app_') - ->andReturn([]); + ->returns([]); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine') - ->once() - ->andReturn($engine); + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine') + ->returns($engine); $config = $this->configWithPrefix('app_'); - $command = m::mock(DeleteAllIndexesCommand::class)->makePartial(); - $command->shouldReceive('option')->with('force')->andReturn(true); - $command->shouldReceive('info')->once(); + $command = Double::for(new DeleteAllIndexesCommand)->passthru(); + $command->allows('option')->with('force')->returns(true); + $command->expects('info'); $result = $command->handle($manager, $config); $this->assertSame(0, $result); } + /** + * Create configuration with the given search index prefix. + */ protected function configWithPrefix(string $prefix): Repository { - $config = m::mock(Repository::class); - $config->shouldReceive('string') - ->with('scout.prefix') - ->andReturn($prefix); - - return $config; + return new Repository(['scout' => ['prefix' => $prefix]]); } } diff --git a/tests/Scout/Unit/Console/ImportCommandTest.php b/tests/Scout/Unit/Console/ImportCommandTest.php index 9ffe8d09bb..cee882b2ff 100644 --- a/tests/Scout/Unit/Console/ImportCommandTest.php +++ b/tests/Scout/Unit/Console/ImportCommandTest.php @@ -19,12 +19,15 @@ use Hypervel\Support\Facades\Event; use Hypervel\Tests\Scout\Fixtures\Models\SearchableModel; use Hypervel\Tests\Scout\ScoutTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\Console\Tester\CommandTester; class ImportCommandTest extends ScoutTestCase { + use VerifiesDoubles; + public function testItThrowsScoutExceptionForNonExistentModelClass(): void { $this->expectException(ScoutException::class); @@ -111,12 +114,11 @@ public function testChildFailureAbortsImportDrainsTheRunnerAndDoesNotContaminate }); $failure = new RuntimeException('Search transport failed.'); - $failingEngine = m::mock(Engine::class); - $failingEngine->shouldReceive('importConcurrency')->once()->passthru(); - $failingEngine->shouldReceive('runUpdate')->once()->andThrow($failure); + $failingEngine = Double::for(Engine::class)->passthru(); + $failingEngine->expects('runUpdate')->throws($failure); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine')->andReturn($failingEngine); + $manager = Double::for(EngineManager::class)->strict(); + $manager->allows('engine')->returns($failingEngine); $this->app->instance(EngineManager::class, $manager); $command = $this->app->make(Kernel::class)->getArtisan()->find('scout:import'); @@ -135,12 +137,12 @@ public function testChildFailureAbortsImportDrainsTheRunnerAndDoesNotContaminate $this->assertStringNotContainsString('records have been imported', $tester->getDisplay()); $this->assertFalse(CoroutineContext::has(SearchableModel::SCOUT_RUNNER_CONTEXT_KEY)); - $successfulEngine = m::mock(Engine::class); - $successfulEngine->shouldReceive('importConcurrency')->once()->passthru(); - $successfulEngine->shouldReceive('runUpdate')->times(3); + $failingEngine->received('importConcurrency')->times(1); + $successfulEngine = Double::for(Engine::class)->passthru(); + $successfulEngine->expects('runUpdate')->times(3); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine')->andReturn($successfulEngine); + $manager = Double::for(EngineManager::class)->strict(); + $manager->allows('engine')->returns($successfulEngine); $this->app->instance(EngineManager::class, $manager); $tester = new CommandTester(clone $command); @@ -151,6 +153,7 @@ public function testChildFailureAbortsImportDrainsTheRunnerAndDoesNotContaminate ]); $this->assertSame(0, $status, $tester->getDisplay()); + $successfulEngine->received('importConcurrency')->times(1); $this->assertStringContainsString('records have been imported', $tester->getDisplay()); $this->assertFalse(CoroutineContext::has(SearchableModel::SCOUT_RUNNER_CONTEXT_KEY)); } diff --git a/tests/Scout/Unit/Console/IndexCommandTest.php b/tests/Scout/Unit/Console/IndexCommandTest.php index f7d961206f..f87f0af8ff 100644 --- a/tests/Scout/Unit/Console/IndexCommandTest.php +++ b/tests/Scout/Unit/Console/IndexCommandTest.php @@ -7,102 +7,100 @@ use Hypervel\Config\Repository; use Hypervel\Database\Eloquent\Model; use Hypervel\Scout\Console\IndexCommand; -use Hypervel\Scout\Contracts\UpdatesIndexSettings; use Hypervel\Scout\EngineManager; use Hypervel\Scout\Engines\Engine; use Hypervel\Scout\Exceptions\NotSupportedException; use Hypervel\Scout\Scout; +use Hypervel\Tests\Scout\Fixtures\SettingsEngine; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class IndexCommandTest extends TestCase { + use VerifiesDoubles; + public function testZeroPrimaryKeyReachesTheEngine(): void { - $engine = m::mock(Engine::class); - $engine->shouldReceive('createIndex') - ->once() + $engine = Double::for(Engine::class)->strict(); + $engine->expects('createIndex') ->with('prod_posts', ['primaryKey' => '0']); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine')->once()->andReturn($engine); + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine')->returns($engine); - $config = m::mock(Repository::class); - $config->shouldReceive('string')->with('scout.prefix')->andReturn('prod_'); + $config = new Repository(['scout' => ['prefix' => 'prod_']]); $command = $this->command('posts', '0'); - $command->shouldReceive('info')->once()->with('Synchronized index ["prod_posts"] successfully.'); + $command->expects('info')->with('Synchronized index ["prod_posts"] successfully.'); $this->assertSame(0, $command->handle($manager, $config)); } public function testUnsupportedCreationStillAppliesLogicalIndexSettings(): void { - $engine = m::mock(Engine::class . ', ' . UpdatesIndexSettings::class); - $engine->shouldReceive('createIndex') - ->once() + $engine = Double::for(SettingsEngine::class)->strict(); + $engine->expects('createIndex') ->with('prod_posts', []) - ->andThrow(new NotSupportedException); - $engine->shouldReceive('updateIndexSettings') - ->once() + ->throws(new NotSupportedException); + $engine->expects('updateIndexSettings') ->with('prod_posts', ['filterableAttributes' => ['status']]); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine')->once()->andReturn($engine); + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine')->returns($engine); - $config = m::mock(Repository::class); - $config->shouldReceive('string')->with('scout.prefix')->andReturn('prod_'); - $config->shouldReceive('string')->with('scout.driver')->andReturn('meilisearch'); - $config->shouldReceive('get') - ->with('scout.meilisearch.index-settings.posts') - ->andReturn(['filterableAttributes' => ['status']]); + $config = new Repository(['scout' => [ + 'prefix' => 'prod_', + 'driver' => 'meilisearch', + 'meilisearch' => ['index-settings' => [ + 'posts' => ['filterableAttributes' => ['status']], + ]], + ]]); $command = $this->command('posts'); - $command->shouldReceive('info')->once()->with('Synchronized index ["prod_posts"] successfully.'); + $command->expects('info')->with('Synchronized index ["prod_posts"] successfully.'); $this->assertSame(0, $command->handle($manager, $config)); } public function testPhysicalIndexSettingsAreUsedAsFallback(): void { - $engine = m::mock(Engine::class . ', ' . UpdatesIndexSettings::class); - $engine->shouldReceive('createIndex')->once()->with('prod_posts', []); - $engine->shouldReceive('updateIndexSettings') - ->once() + $engine = Double::for(SettingsEngine::class)->strict(); + $engine->expects('createIndex')->with('prod_posts', []); + $engine->expects('updateIndexSettings') ->with('prod_posts', ['sortableAttributes' => ['created_at']]); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine')->once()->andReturn($engine); + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine')->returns($engine); - $config = m::mock(Repository::class); - $config->shouldReceive('string')->with('scout.prefix')->andReturn('prod_'); - $config->shouldReceive('string')->with('scout.driver')->andReturn('meilisearch'); - $config->shouldReceive('get')->with('scout.meilisearch.index-settings.posts')->andReturn(null); - $config->shouldReceive('get') - ->with('scout.meilisearch.index-settings.prod_posts') - ->andReturn(['sortableAttributes' => ['created_at']]); + $config = new Repository(['scout' => [ + 'prefix' => 'prod_', + 'driver' => 'meilisearch', + 'meilisearch' => ['index-settings' => [ + 'prod_posts' => ['sortableAttributes' => ['created_at']], + ]], + ]]); $command = $this->command('posts'); - $command->shouldReceive('info')->once()->with('Synchronized index ["prod_posts"] successfully.'); + $command->expects('info')->with('Synchronized index ["prod_posts"] successfully.'); $this->assertSame(0, $command->handle($manager, $config)); } public function testLifecycleCallbackCanPrepareAnEmptyNamedIndexEntry(): void { - $engine = m::mock(Engine::class . ', ' . UpdatesIndexSettings::class); - $engine->shouldReceive('createIndex')->once()->with('prod_posts', []); - $engine->shouldReceive('updateIndexSettings') - ->once() + $engine = Double::for(SettingsEngine::class)->strict(); + $engine->expects('createIndex')->with('prod_posts', []); + $engine->expects('updateIndexSettings') ->with('prod_posts', ['filterableAttributes' => ['tenant_id']]); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine')->once()->andReturn($engine); - $config = m::mock(Repository::class); - $config->shouldReceive('string')->with('scout.prefix')->andReturn('prod_'); - $config->shouldReceive('string')->with('scout.driver')->andReturn('meilisearch'); - $config->shouldReceive('get')->with('scout.meilisearch.index-settings.posts')->andReturn(null); - $config->shouldReceive('get')->with('scout.meilisearch.index-settings.prod_posts')->andReturn(null); + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine')->returns($engine); + $config = new Repository(['scout' => [ + 'prefix' => 'prod_', + 'driver' => 'meilisearch', + ]]); Scout::prepareIndexSettingsUsing(function ( array $settings, @@ -119,7 +117,7 @@ public function testLifecycleCallbackCanPrepareAnEmptyNamedIndexEntry(): void }); $command = $this->command('posts'); - $command->shouldReceive('info')->once(); + $command->expects('info'); $this->assertSame(0, $command->handle($manager, $config)); } @@ -127,17 +125,16 @@ public function testLifecycleCallbackCanPrepareAnEmptyNamedIndexEntry(): void public function testOperationalCreationFailuresPropagate(): void { $failure = new RuntimeException('Search service unavailable.'); - $engine = m::mock(Engine::class); - $engine->shouldReceive('createIndex')->once()->andThrow($failure); + $engine = Double::for(Engine::class)->strict(); + $engine->expects('createIndex')->throws($failure); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine')->once()->andReturn($engine); + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine')->returns($engine); - $config = m::mock(Repository::class); - $config->shouldReceive('string')->with('scout.prefix')->andReturn(''); + $config = new Repository(['scout' => ['prefix' => '']]); $command = $this->command('posts'); - $command->shouldNotReceive('info'); + $command->expects('info')->never(); try { $command->handle($manager, $config); @@ -147,11 +144,14 @@ public function testOperationalCreationFailuresPropagate(): void } } - protected function command(string $name, ?string $key = null): IndexCommand + /** + * Create a command double with the given index arguments. + */ + protected function command(string $name, ?string $key = null): IndexCommand&DoubleInterface { - $command = m::mock(IndexCommand::class)->makePartial(); - $command->shouldReceive('argument')->with('name')->andReturn($name); - $command->shouldReceive('option')->with('key')->andReturn($key); + $command = Double::for(new IndexCommand)->passthru(); + $command->allows('argument')->with('name')->returns($name); + $command->allows('option')->with('key')->returns($key); return $command; } diff --git a/tests/Scout/Unit/Console/SyncIndexSettingsCommandTest.php b/tests/Scout/Unit/Console/SyncIndexSettingsCommandTest.php index c21f1bcc71..7a25227a62 100644 --- a/tests/Scout/Unit/Console/SyncIndexSettingsCommandTest.php +++ b/tests/Scout/Unit/Console/SyncIndexSettingsCommandTest.php @@ -9,39 +9,39 @@ use Hypervel\Database\Eloquent\Model; use Hypervel\Database\Eloquent\SoftDeletes; use Hypervel\Scout\Console\SyncIndexSettingsCommand; -use Hypervel\Scout\Contracts\UpdatesIndexSettings; use Hypervel\Scout\EngineManager; use Hypervel\Scout\EngineOperationRunner; use Hypervel\Scout\Engines\CollectionEngine; use Hypervel\Scout\Engines\Engine; use Hypervel\Scout\Scout; +use Hypervel\Tests\Scout\Fixtures\SettingsEngine; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionMethod; class SyncIndexSettingsCommandTest extends TestCase { + use VerifiesDoubles; + public function testFailsWhenEngineDoesNotSupportUpdatingIndexSettings(): void { $engine = new CollectionEngine; - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('getDefaultDriver') - ->once() - ->andReturn('collection'); - $manager->shouldReceive('engine') + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('getDefaultDriver') + ->returns('collection'); + $manager->expects('engine') ->with('collection') - ->once() - ->andReturn($engine); + ->returns($engine); - $config = m::mock(Repository::class); + $config = new Repository; - $command = m::mock(SyncIndexSettingsCommand::class)->makePartial(); - $command->shouldReceive('option') + $command = Double::for(new SyncIndexSettingsCommand)->passthru(); + $command->allows('option') ->with('driver') - ->andReturn(null); - $command->shouldReceive('error') - ->once() + ->returns(null); + $command->expects('error') ->with('The "collection" engine does not support updating index settings.'); $result = $command->handle($manager, $config); @@ -52,14 +52,13 @@ public function testFailsWhenEngineDoesNotSupportUpdatingIndexSettings(): void public function testNullConfiguredDriverResolvesThroughTheManager(): void { $config = new Repository(['scout' => ['driver' => null]]); - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with('config')->andReturn($config); - $manager = new EngineManager($container, new EngineOperationRunner); - - $command = m::mock(SyncIndexSettingsCommand::class)->makePartial(); - $command->shouldReceive('option')->with('driver')->andReturn(null); - $command->shouldReceive('error') - ->once() + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with('config')->returns($config); + $manager = new EngineManager($container->instance(), new EngineOperationRunner); + + $command = Double::for(new SyncIndexSettingsCommand)->passthru(); + $command->allows('option')->with('driver')->returns(null); + $command->expects('error') ->with('The "null" engine does not support updating index settings.'); $this->assertSame(1, $command->handle($manager, $config)); @@ -67,28 +66,22 @@ public function testNullConfiguredDriverResolvesThroughTheManager(): void public function testSucceedsWithInfoMessageWhenNoIndexSettingsConfigured(): void { - $engine = m::mock(Engine::class . ', ' . UpdatesIndexSettings::class); + $engine = Double::for(SettingsEngine::class)->strict(); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('getDefaultDriver') - ->once() - ->andReturn('meilisearch'); - $manager->shouldReceive('engine') + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('getDefaultDriver') + ->returns('meilisearch'); + $manager->expects('engine') ->with('meilisearch') - ->once() - ->andReturn($engine); + ->returns($engine); - $config = m::mock(Repository::class); - $config->shouldReceive('array') - ->with('scout.meilisearch.index-settings', []) - ->andReturn([]); + $config = new Repository(['scout' => ['meilisearch' => ['index-settings' => []]]]); - $command = m::mock(SyncIndexSettingsCommand::class)->makePartial(); - $command->shouldReceive('option') + $command = Double::for(new SyncIndexSettingsCommand)->passthru(); + $command->allows('option') ->with('driver') - ->andReturn(null); - $command->shouldReceive('info') - ->once() + ->returns(null); + $command->expects('info') ->with('No index settings found for the "meilisearch" engine.'); $result = $command->handle($manager, $config); @@ -98,36 +91,29 @@ public function testSucceedsWithInfoMessageWhenNoIndexSettingsConfigured(): void public function testSyncsIndexSettingsSuccessfully(): void { - $engine = m::mock(Engine::class . ', ' . UpdatesIndexSettings::class); - $engine->shouldReceive('updateIndexSettings') - ->once() + $engine = Double::for(SettingsEngine::class)->strict(); + $engine->expects('updateIndexSettings') ->with('test_posts', ['filterableAttributes' => ['status']]); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('getDefaultDriver') - ->once() - ->andReturn('meilisearch'); - $manager->shouldReceive('engine') + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('getDefaultDriver') + ->returns('meilisearch'); + $manager->expects('engine') ->with('meilisearch') - ->once() - ->andReturn($engine); + ->returns($engine); - $config = m::mock(Repository::class); - $config->shouldReceive('array') - ->with('scout.meilisearch.index-settings', []) - ->andReturn([ + $config = new Repository(['scout' => [ + 'prefix' => '', + 'meilisearch' => ['index-settings' => [ 'test_posts' => ['filterableAttributes' => ['status']], - ]); - $config->shouldReceive('string') - ->with('scout.prefix') - ->andReturn(''); + ]], + ]]); - $command = m::mock(SyncIndexSettingsCommand::class)->makePartial(); - $command->shouldReceive('option') + $command = Double::for(new SyncIndexSettingsCommand)->passthru(); + $command->allows('option') ->with('driver') - ->andReturn(null); - $command->shouldReceive('info') - ->once() + ->returns(null); + $command->expects('info') ->with('Settings for the [test_posts] index synced successfully.'); $result = $command->handle($manager, $config); @@ -137,30 +123,27 @@ public function testSyncsIndexSettingsSuccessfully(): void public function testLifecycleCallbackReceivesModelSettingsAfterSoftDeleteContribution(): void { - $engine = m::mock(Engine::class . ', ' . UpdatesIndexSettings::class); - $engine->shouldReceive('configureSoftDeleteFilter') - ->once() + $engine = Double::for(SettingsEngine::class)->strict(); + $engine->expects('configureSoftDeleteFilter') ->with(['searchableAttributes' => ['title']]) - ->andReturn([ + ->returns([ 'searchableAttributes' => ['title'], 'filterableAttributes' => ['__soft_deleted'], ]); - $engine->shouldReceive('updateIndexSettings') - ->once() + $engine->expects('updateIndexSettings') ->with('soft_deletable_searchable_models', [ 'searchableAttributes' => ['title'], 'filterableAttributes' => ['__soft_deleted', 'tenant_id'], ]); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('getDefaultDriver')->once()->andReturn('meilisearch'); - $manager->shouldReceive('engine')->with('meilisearch')->once()->andReturn($engine); - $config = m::mock(Repository::class); - $config->shouldReceive('array') - ->with('scout.meilisearch.index-settings', []) - ->andReturn([ + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('getDefaultDriver')->returns('meilisearch'); + $manager->expects('engine')->with('meilisearch')->returns($engine); + $config = new Repository(['scout' => [ + 'soft_delete' => true, + 'meilisearch' => ['index-settings' => [ SyncIndexSettingsSoftDeleteModel::class => ['searchableAttributes' => ['title']], - ]); - $config->shouldReceive('boolean')->with('scout.soft_delete')->andReturn(true); + ]], + ]]); Scout::prepareIndexSettingsUsing(function ( array $settings, @@ -181,35 +164,29 @@ public function testLifecycleCallbackReceivesModelSettingsAfterSoftDeleteContrib return $settings; }); - $command = m::mock(SyncIndexSettingsCommand::class)->makePartial(); - $command->shouldReceive('option')->with('driver')->andReturn(null); - $command->shouldReceive('info')->once(); + $command = Double::for(new SyncIndexSettingsCommand)->passthru(); + $command->allows('option')->with('driver')->returns(null); + $command->expects('info'); $this->assertSame(0, $command->handle($manager, $config)); } public function testUsesDriverOptionWhenProvided(): void { - $engine = m::mock(Engine::class . ', ' . UpdatesIndexSettings::class); + $engine = Double::for(SettingsEngine::class)->strict(); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine') + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine') ->with('typesense') - ->once() - ->andReturn($engine); + ->returns($engine); - $config = m::mock(Repository::class); - // Note: scout.driver should not be called when driver option is provided - $config->shouldReceive('array') - ->with('scout.typesense.index-settings', []) - ->andReturn([]); + $config = new Repository(['scout' => ['typesense' => ['index-settings' => []]]]); - $command = m::mock(SyncIndexSettingsCommand::class)->makePartial(); - $command->shouldReceive('option') + $command = Double::for(new SyncIndexSettingsCommand)->passthru(); + $command->allows('option') ->with('driver') - ->andReturn('typesense'); - $command->shouldReceive('info') - ->once() + ->returns('typesense'); + $command->expects('info') ->with('No index settings found for the "typesense" engine.'); $result = $command->handle($manager, $config); @@ -219,25 +196,20 @@ public function testUsesDriverOptionWhenProvided(): void public function testZeroDriverOptionIsNotReplacedByConfiguredDriver(): void { - $engine = m::mock(Engine::class . ', ' . UpdatesIndexSettings::class); + $engine = Double::for(SettingsEngine::class)->strict(); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine') + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine') ->with('0') - ->once() - ->andReturn($engine); + ->returns($engine); - $config = m::mock(Repository::class); - $config->shouldReceive('array') - ->with('scout.0.index-settings', []) - ->andReturn([]); + $config = new Repository(['scout' => ['0' => ['index-settings' => []]]]); - $command = m::mock(SyncIndexSettingsCommand::class)->makePartial(); - $command->shouldReceive('option') + $command = Double::for(new SyncIndexSettingsCommand)->passthru(); + $command->allows('option') ->with('driver') - ->andReturn('0'); - $command->shouldReceive('info') - ->once() + ->returns('0'); + $command->expects('info') ->with('No index settings found for the "0" engine.'); $this->assertSame(0, $command->handle($manager, $config)); @@ -245,28 +217,22 @@ public function testZeroDriverOptionIsNotReplacedByConfiguredDriver(): void public function testEmptyDriverOptionUsesConfiguredDriver(): void { - $engine = m::mock(Engine::class . ', ' . UpdatesIndexSettings::class); + $engine = Double::for(SettingsEngine::class)->strict(); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('getDefaultDriver') - ->once() - ->andReturn('meilisearch'); - $manager->shouldReceive('engine') + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('getDefaultDriver') + ->returns('meilisearch'); + $manager->expects('engine') ->with('meilisearch') - ->once() - ->andReturn($engine); + ->returns($engine); - $config = m::mock(Repository::class); - $config->shouldReceive('array') - ->with('scout.meilisearch.index-settings', []) - ->andReturn([]); + $config = new Repository(['scout' => ['meilisearch' => ['index-settings' => []]]]); - $command = m::mock(SyncIndexSettingsCommand::class)->makePartial(); - $command->shouldReceive('option') + $command = Double::for(new SyncIndexSettingsCommand)->passthru(); + $command->allows('option') ->with('driver') - ->andReturn(''); - $command->shouldReceive('info') - ->once() + ->returns(''); + $command->expects('info') ->with('No index settings found for the "meilisearch" engine.'); $this->assertSame(0, $command->handle($manager, $config)); @@ -274,14 +240,11 @@ public function testEmptyDriverOptionUsesConfiguredDriver(): void public function testIndexNameResolutionPrependsPrefix(): void { - $command = m::mock(SyncIndexSettingsCommand::class)->makePartial(); + $command = new SyncIndexSettingsCommand; $method = new ReflectionMethod(SyncIndexSettingsCommand::class, 'indexName'); - $config = m::mock(Repository::class); - $config->shouldReceive('string') - ->with('scout.prefix') - ->andReturn('prod_'); + $config = new Repository(['scout' => ['prefix' => 'prod_']]); // Test that prefix is prepended when not already present $result = $method->invoke($command, 'posts', $config); @@ -290,14 +253,11 @@ public function testIndexNameResolutionPrependsPrefix(): void public function testIndexNameResolutionDoesNotDuplicatePrefix(): void { - $command = m::mock(SyncIndexSettingsCommand::class)->makePartial(); + $command = new SyncIndexSettingsCommand; $method = new ReflectionMethod(SyncIndexSettingsCommand::class, 'indexName'); - $config = m::mock(Repository::class); - $config->shouldReceive('string') - ->with('scout.prefix') - ->andReturn('prod_'); + $config = new Repository(['scout' => ['prefix' => 'prod_']]); // Test that prefix is not duplicated when already present $result = $method->invoke($command, 'prod_posts', $config); diff --git a/tests/Scout/Unit/DatabaseEngineSemanticTest.php b/tests/Scout/Unit/DatabaseEngineSemanticTest.php index 00f0ac7aa0..edb6e0865c 100644 --- a/tests/Scout/Unit/DatabaseEngineSemanticTest.php +++ b/tests/Scout/Unit/DatabaseEngineSemanticTest.php @@ -20,12 +20,16 @@ use Hypervel\Scout\Engines\DatabaseEngine; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PDO; #[WithConfig('ai.caching.embeddings.store', 'array')] class DatabaseEngineSemanticTest extends TestCase { + use VerifiesDoubles; + /** * Register the embedding provider used by semantic searches. */ @@ -166,14 +170,14 @@ public function testItGeneratesAndPersistsADatabaseEmbedding(): void $model->forceFill(['id' => 1, 'name' => 'Generate this']); $model->exists = true; - $observer = m::mock(EngineOperationObserver::class); - $observer->shouldReceive('starting')->once()->with(m::on( + $observer = Double::for(EngineOperationObserver::class)->strict(); + $observer->expects('starting')->with(Argument::satisfies( fn (EngineOperation $operation): bool => $operation->operation === 'update' && $operation->engineName === 'database' && $operation->modelCount === 1 && $operation->index === 'documents' - ))->andReturn(null); - $observer->shouldReceive('finished')->once()->with(m::type(EngineOperation::class), null, null); + ))->returns(null); + $observer->expects('finished')->with(Argument::type(EngineOperation::class), null, null); $runner = new EngineOperationRunner; $runner->observe($observer); @@ -192,7 +196,8 @@ public function testItGeneratesAndPersistsADatabaseEmbedding(): void protected function model(): DatabaseSemanticModel { $connection = new PostgresConnection(new PDO('sqlite::memory:'), '', '', ['driver' => 'pgsql']); - $resolver = m::mock(ConnectionResolverInterface::class, ['connection' => $connection]); + $resolver = Double::for(ConnectionResolverInterface::class)->strict(); + $resolver->allows('connection')->returns($connection); Model::setConnectionResolver($resolver); return new DatabaseSemanticModel; diff --git a/tests/Scout/Unit/EngineManagerTest.php b/tests/Scout/Unit/EngineManagerTest.php index 218d2a4665..98e10bfeea 100644 --- a/tests/Scout/Unit/EngineManagerTest.php +++ b/tests/Scout/Unit/EngineManagerTest.php @@ -6,7 +6,7 @@ use Algolia\AlgoliaSearch\Api\SearchClient as AlgoliaSearchClient; use Hypervel\Config\Repository; -use Hypervel\Contracts\Container\Container; +use Hypervel\Container\Container; use Hypervel\Database\Eloquent\Model; use Hypervel\Scout\Builder; use Hypervel\Scout\Contracts\EngineOperationObserver; @@ -24,15 +24,19 @@ use Hypervel\Support\ClassInvoker; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Meilisearch\Client as MeilisearchClient; -use Mockery as m; use Typesense\Client as TypesenseClient; class EngineManagerTest extends TestCase { + use VerifiesDoubles; + public function testResolveNullEngine(): void { - $container = $this->createMockContainer(['driver' => 'null']); + $container = $this->createContainer(['driver' => 'null']); $manager = $this->createManager($container); $engine = $manager->engine('null'); @@ -42,7 +46,7 @@ public function testResolveNullEngine(): void public function testResolveCollectionEngine(): void { - $container = $this->createMockContainer(['driver' => 'collection']); + $container = $this->createContainer(['driver' => 'collection']); $manager = $this->createManager($container); $engine = $manager->engine('collection'); @@ -52,16 +56,14 @@ public function testResolveCollectionEngine(): void public function testResolveAlgoliaEngine(): void { - $container = $this->createMockContainerWithAlgolia([ + $container = $this->createContainer([ 'driver' => 'algolia', 'soft_delete' => false, 'identify' => false, ]); - $algoliaClient = m::mock(AlgoliaSearchClient::class); - $container->shouldReceive('make') - ->with(AlgoliaSearchClient::class) - ->andReturn($algoliaClient); + $algoliaClient = Double::for(AlgoliaSearchClient::class)->strict(); + $container->instance(AlgoliaSearchClient::class, $algoliaClient); $manager = $this->createManager($container); $engine = $manager->engine('algolia'); @@ -71,16 +73,14 @@ public function testResolveAlgoliaEngine(): void public function testResolveAlgoliaEngineWithSoftDelete(): void { - $container = $this->createMockContainerWithAlgolia([ + $container = $this->createContainer([ 'driver' => 'algolia', 'soft_delete' => true, 'identify' => false, ]); - $algoliaClient = m::mock(AlgoliaSearchClient::class); - $container->shouldReceive('make') - ->with(AlgoliaSearchClient::class) - ->andReturn($algoliaClient); + $algoliaClient = Double::for(AlgoliaSearchClient::class)->strict(); + $container->instance(AlgoliaSearchClient::class, $algoliaClient); $manager = $this->createManager($container); $engine = $manager->engine('algolia'); @@ -91,16 +91,14 @@ public function testResolveAlgoliaEngineWithSoftDelete(): void public function testResolveAlgoliaEngineWithIdentify(): void { - $container = $this->createMockContainerWithAlgolia([ + $container = $this->createContainer([ 'driver' => 'algolia', 'soft_delete' => false, 'identify' => true, ]); - $algoliaClient = m::mock(AlgoliaSearchClient::class); - $container->shouldReceive('make') - ->with(AlgoliaSearchClient::class) - ->andReturn($algoliaClient); + $algoliaClient = Double::for(AlgoliaSearchClient::class)->strict(); + $container->instance(AlgoliaSearchClient::class, $algoliaClient); $manager = $this->createManager($container); $engine = $manager->engine('algolia'); @@ -117,16 +115,14 @@ public function testResolveMeilisearchEngine(): void ], ]; - $container = $this->createMockContainer([ + $container = $this->createContainer([ 'driver' => 'meilisearch', 'soft_delete' => false, 'meilisearch' => $meilisearchConfig, ]); - $meilisearchClient = m::mock(MeilisearchClient::class); - $container->shouldReceive('make') - ->with(MeilisearchClient::class) - ->andReturn($meilisearchClient); + $meilisearchClient = Double::for(MeilisearchClient::class)->strict(); + $container->instance(MeilisearchClient::class, $meilisearchClient); $manager = $this->createManager($container); $engine = $manager->engine('meilisearch'); @@ -137,15 +133,13 @@ public function testResolveMeilisearchEngine(): void public function testResolveMeilisearchEngineWithSoftDelete(): void { - $container = $this->createMockContainer([ + $container = $this->createContainer([ 'driver' => 'meilisearch', 'soft_delete' => true, ]); - $meilisearchClient = m::mock(MeilisearchClient::class); - $container->shouldReceive('make') - ->with(MeilisearchClient::class) - ->andReturn($meilisearchClient); + $meilisearchClient = Double::for(MeilisearchClient::class)->strict(); + $container->instance(MeilisearchClient::class, $meilisearchClient); $manager = $this->createManager($container); $engine = $manager->engine('meilisearch'); @@ -156,7 +150,7 @@ public function testResolveMeilisearchEngineWithSoftDelete(): void public function testResolveDatabaseEngine(): void { - $container = $this->createMockContainer(['driver' => 'database']); + $container = $this->createContainer(['driver' => 'database']); $manager = $this->createManager($container); $engine = $manager->engine('database'); @@ -172,16 +166,14 @@ public function testResolveTypesenseEngine(): void ], ]; - $container = $this->createMockContainerWithTypesense([ + $container = $this->createContainer([ 'driver' => 'typesense', 'soft_delete' => false, 'typesense' => $typesenseConfig, ]); - $typesenseClient = m::mock(TypesenseClient::class); - $container->shouldReceive('make') - ->with(TypesenseClient::class) - ->andReturn($typesenseClient); + $typesenseClient = Double::for(TypesenseClient::class)->strict(); + $container->instance(TypesenseClient::class, $typesenseClient); $manager = $this->createManager($container); $engine = $manager->engine('typesense'); @@ -198,16 +190,14 @@ public function testResolveTurbopufferEngine(): void ], ]; - $container = $this->createMockContainer([ + $container = $this->createContainer([ 'driver' => 'turbopuffer', 'soft_delete' => true, 'turbopuffer' => $turbopufferConfig, ]); - $turbopufferClient = m::mock(TurbopufferClient::class); - $container->shouldReceive('make') - ->with(TurbopufferClient::class) - ->andReturn($turbopufferClient); + $turbopufferClient = Double::for(TurbopufferClient::class)->strict(); + $container->instance(TurbopufferClient::class, $turbopufferClient); $manager = $this->createManager($container); $engine = $manager->engine('turbopuffer'); @@ -220,7 +210,7 @@ public function testResolveTurbopufferEngine(): void public function testEngineUsesDefaultDriver(): void { - $container = $this->createMockContainer(['driver' => 'collection']); + $container = $this->createContainer(['driver' => 'collection']); $manager = $this->createManager($container); $engine = $manager->engine(); // No name specified @@ -230,7 +220,7 @@ public function testEngineUsesDefaultDriver(): void public function testEngineDefaultsToNullWhenNoDriverConfigured(): void { - $container = $this->createMockContainer(['driver' => null]); + $container = $this->createContainer(['driver' => null]); $manager = $this->createManager($container); $engine = $manager->engine(); @@ -240,7 +230,7 @@ public function testEngineDefaultsToNullWhenNoDriverConfigured(): void public function testEngineCachesInstances(): void { - $container = $this->createMockContainer(['driver' => 'collection']); + $container = $this->createContainer(['driver' => 'collection']); $manager = $this->createManager($container); @@ -252,7 +242,7 @@ public function testEngineCachesInstances(): void public function testForgetEnginesClearsCache(): void { - $container = $this->createMockContainer(['driver' => 'collection']); + $container = $this->createContainer(['driver' => 'collection']); $manager = $this->createManager($container); @@ -265,7 +255,7 @@ public function testForgetEnginesClearsCache(): void public function testForgetEngineClearsSpecificEngine(): void { - $container = $this->createMockContainer(['driver' => 'collection']); + $container = $this->createContainer(['driver' => 'collection']); $manager = $this->createManager($container); @@ -283,13 +273,11 @@ public function testForgetEngineClearsSpecificEngine(): void public function testExtendRegisterCustomDriver(): void { - $container = $this->createMockContainer(['driver' => 'custom']); + $container = $this->createContainer(['driver' => 'custom']); - $customEngine = m::mock(Engine::class); - $customEngine->shouldReceive('setOperationRunner') - ->once() - ->with(m::type(EngineOperationRunner::class), 'custom') - ->andReturnSelf(); + $customEngine = Double::for(Engine::class)->strict(); + $customEngine->expects('setOperationRunner') + ->with(Argument::type(EngineOperationRunner::class), 'custom'); $manager = $this->createManager($container); $manager->extend('custom', function ($container) use ($customEngine) { @@ -303,14 +291,12 @@ public function testExtendRegisterCustomDriver(): void public function testExtendCustomDriverReceivesContainer(): void { - $container = $this->createMockContainer(['driver' => 'custom']); + $container = $this->createContainer(['driver' => 'custom']); $receivedContainer = null; - $customEngine = m::mock(Engine::class); - $customEngine->shouldReceive('setOperationRunner') - ->once() - ->with(m::type(EngineOperationRunner::class), 'custom') - ->andReturnSelf(); + $customEngine = Double::for(Engine::class)->strict(); + $customEngine->expects('setOperationRunner') + ->with(Argument::type(EngineOperationRunner::class), 'custom'); $manager = $this->createManager($container); $manager->extend('custom', function ($passedContainer) use (&$receivedContainer, $customEngine) { @@ -325,13 +311,11 @@ public function testExtendCustomDriverReceivesContainer(): void public function testCustomDriverOverridesBuiltIn(): void { - $container = $this->createMockContainer(['driver' => 'collection']); + $container = $this->createContainer(['driver' => 'collection']); - $customEngine = m::mock(Engine::class); - $customEngine->shouldReceive('setOperationRunner') - ->once() - ->with(m::type(EngineOperationRunner::class), 'collection') - ->andReturnSelf(); + $customEngine = Double::for(Engine::class)->strict(); + $customEngine->expects('setOperationRunner') + ->with(Argument::type(EngineOperationRunner::class), 'collection'); $manager = $this->createManager($container); $manager->extend('collection', function () use ($customEngine) { @@ -345,7 +329,7 @@ public function testCustomDriverOverridesBuiltIn(): void public function testThrowsExceptionForUnsupportedDriver(): void { - $container = $this->createMockContainer(['driver' => 'unsupported']); + $container = $this->createContainer(['driver' => 'unsupported']); $manager = $this->createManager($container); @@ -357,7 +341,7 @@ public function testThrowsExceptionForUnsupportedDriver(): void public function testGetDefaultDriverReturnsConfiguredDriver(): void { - $container = $this->createMockContainer(['driver' => 'meilisearch']); + $container = $this->createContainer(['driver' => 'meilisearch']); $manager = $this->createManager($container); @@ -366,7 +350,7 @@ public function testGetDefaultDriverReturnsConfiguredDriver(): void public function testGetDefaultDriverReturnsNullWhenNotConfigured(): void { - $container = $this->createMockContainer([]); + $container = $this->createContainer([]); $manager = $this->createManager($container); @@ -375,7 +359,7 @@ public function testGetDefaultDriverReturnsNullWhenNotConfigured(): void public function testGetDefaultDriverReturnsNullWhenConfiguredAsPhpNull(): void { - $container = $this->createMockContainer(['driver' => null]); + $container = $this->createContainer(['driver' => null]); $manager = $this->createManager($container); @@ -384,7 +368,7 @@ public function testGetDefaultDriverReturnsNullWhenConfiguredAsPhpNull(): void public function testSeparateManagerInstancesDoNotShareEngineCache(): void { - $container = $this->createMockContainer(['driver' => 'collection']); + $container = $this->createContainer(['driver' => 'collection']); $manager1 = $this->createManager($container); $engine1 = $manager1->engine('collection'); @@ -397,92 +381,36 @@ public function testSeparateManagerInstancesDoNotShareEngineCache(): void public function testDefaultNullEngineDoesNotNotifyOperationObservers(): void { - $container = $this->createMockContainer([]); + $container = $this->createContainer([]); $runner = new EngineOperationRunner; - $observer = m::mock(EngineOperationObserver::class); - $observer->shouldNotReceive('starting'); - $observer->shouldNotReceive('finished'); + $observer = Double::for(EngineOperationObserver::class)->strict(); + $observer->expects('starting')->never(); + $observer->expects('finished')->never(); $runner->observe($observer); $manager = new EngineManager($container, $runner); - $result = $manager->engine()->runSearch(new Builder(m::mock(Model::class), 'query')); + $result = $manager->engine()->runSearch(new Builder(Double::for(Model::class)->strict(), 'query')); $this->assertSame([], $result); } + /** + * Create a manager with an independent operation runner. + */ protected function createManager(Container $container): EngineManager { return new EngineManager($container, new EngineOperationRunner); } - protected function createMockContainer(array $config): m\MockInterface&Container - { - $container = m::mock(Container::class); - - $configService = m::mock(Repository::class); - $configService->shouldReceive('get') - ->with('scout.driver', m::any()) - ->andReturn($config['driver'] ?? null); - $configService->shouldReceive('boolean') - ->with('scout.soft_delete') - ->andReturn($config['soft_delete'] ?? false); - $configService->shouldReceive('array') - ->with('scout.meilisearch', []) - ->andReturn($config['meilisearch'] ?? []); - $configService->shouldReceive('array') - ->with('scout.turbopuffer', []) - ->andReturn($config['turbopuffer'] ?? []); - - $container->shouldReceive('make') - ->with('config') - ->andReturn($configService); - - return $container; - } - - protected function createMockContainerWithTypesense(array $config): m\MockInterface&Container - { - $container = m::mock(Container::class); - - $configService = m::mock(Repository::class); - $configService->shouldReceive('get') - ->with('scout.driver', m::any()) - ->andReturn($config['driver'] ?? null); - $configService->shouldReceive('boolean') - ->with('scout.soft_delete') - ->andReturn($config['soft_delete'] ?? false); - $configService->shouldReceive('integer') - ->with('scout.typesense.max_total_results', m::any()) - ->andReturn($config['max_total_results'] ?? 1000); - $configService->shouldReceive('array') - ->with('scout.typesense', []) - ->andReturn($config['typesense'] ?? []); - - $container->shouldReceive('make') - ->with('config') - ->andReturn($configService); - - return $container; - } - - protected function createMockContainerWithAlgolia(array $config): m\MockInterface&Container + /** + * Create a container with the given Scout configuration. + */ + protected function createContainer(array $config): Container { - $container = m::mock(Container::class); - - $configService = m::mock(Repository::class); - $configService->shouldReceive('get') - ->with('scout.driver', m::any()) - ->andReturn($config['driver'] ?? null); - $configService->shouldReceive('boolean') - ->with('scout.soft_delete') - ->andReturn($config['soft_delete'] ?? false); - $configService->shouldReceive('boolean') - ->with('scout.identify') - ->andReturn($config['identify'] ?? false); - - $container->shouldReceive('make') - ->with('config') - ->andReturn($configService); + $container = new Container; + $container->instance('config', new Repository([ + 'scout' => ['soft_delete' => false, 'identify' => false, ...$config], + ])); return $container; } diff --git a/tests/Scout/Unit/EngineOperationRunnerTest.php b/tests/Scout/Unit/EngineOperationRunnerTest.php index a91c1d08a0..db391ef3f0 100644 --- a/tests/Scout/Unit/EngineOperationRunnerTest.php +++ b/tests/Scout/Unit/EngineOperationRunnerTest.php @@ -12,8 +12,9 @@ use Hypervel\Scout\EngineOperation; use Hypervel\Scout\EngineOperationRunner; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -21,6 +22,8 @@ class EngineOperationRunnerTest extends TestCase { + use VerifiesDoubles; + public function testRunsCallbackDirectlyWithoutObservers(): void { $runner = new EngineOperationRunner; @@ -107,7 +110,7 @@ function () use ($startingFailure): never { fn (): null => null, )); - $this->bindReportingHandler()->shouldReceive('report')->once()->with($completionFailure); + $this->bindReportingHandler()->expects('report')->with($completionFailure); $caught = null; try { @@ -155,7 +158,7 @@ function (EngineOperation $operation, mixed $token, ?Throwable $exception) use ( )); $reported = []; - $this->bindReportingHandler()->shouldReceive('report')->andReturnUsing(function (Throwable $throwable) use (&$reported): void { + $this->bindReportingHandler()->allows('report')->resolves(function (Throwable $throwable) use (&$reported): void { $reported[] = $throwable; }); $caught = null; @@ -200,7 +203,7 @@ function () use (&$finished, $secondFailure): never { }, )); - $this->bindReportingHandler()->shouldReceive('report')->once()->with($secondFailure); + $this->bindReportingHandler()->expects('report')->with($secondFailure); $caught = null; try { @@ -302,7 +305,7 @@ function () use (&$secondFinished): void { $secondFinished = true; }, )); - $this->bindReportingHandler()->shouldReceive('report')->once()->with($operationFailure); + $this->bindReportingHandler()->expects('report')->with($operationFailure); $caught = null; @@ -334,13 +337,13 @@ protected function observer(Closure $starting, Closure $finished): EngineOperati } /** - * Bind a mocked exception handler for displaced failure reports. + * Bind an exception handler double for displaced failure reports. */ - private function bindReportingHandler(): MockInterface + private function bindReportingHandler(): ExceptionHandler&DoubleInterface { $container = new Container; Container::setInstance($container); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $container->instance(ExceptionHandler::class, $handler); return $handler; diff --git a/tests/Scout/Unit/Engines/AlgoliaEngineTest.php b/tests/Scout/Unit/Engines/AlgoliaEngineTest.php index 6f6b61ef09..ed551c71ef 100644 --- a/tests/Scout/Unit/Engines/AlgoliaEngineTest.php +++ b/tests/Scout/Unit/Engines/AlgoliaEngineTest.php @@ -8,6 +8,7 @@ use Algolia\AlgoliaSearch\Exceptions\NotFoundException; use Hypervel\Context\RequestContext; use Hypervel\Coroutine\WaitGroup; +use Hypervel\Database\Eloquent\Builder as EloquentBuilder; use Hypervel\Database\Eloquent\Collection as EloquentCollection; use Hypervel\Database\Eloquent\Model; use Hypervel\Database\Eloquent\SoftDeletes; @@ -15,7 +16,6 @@ use Hypervel\Scout\Builder; use Hypervel\Scout\Contracts\DeletesByFilter; use Hypervel\Scout\Contracts\EngineOperationObserver; -use Hypervel\Scout\Contracts\SearchableInterface; use Hypervel\Scout\EngineOperation; use Hypervel\Scout\EngineOperationRunner; use Hypervel\Scout\Engines\AlgoliaEngine; @@ -28,7 +28,9 @@ use Hypervel\Support\LazyCollection; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use Throwable; @@ -36,78 +38,75 @@ class AlgoliaEngineTest extends TestCase { + use VerifiesDoubles; + public function testUpdateSavesObjects(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('saveObjects') - ->once() + $client->expects('saveObjects') ->with('users', [ ['id' => 1, 'name' => 'Taylor', 'objectID' => 1], ]); $engine = new AlgoliaEngine($client); - $model = $this->createSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('users'); - $model->shouldReceive('toSearchableArray')->andReturn(['id' => 1, 'name' => 'Taylor']); - $model->shouldReceive('scoutMetadata')->andReturn([]); - $model->shouldReceive('getScoutKey')->andReturn(1); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('indexableAs')->returns('users'); + $model->allows('toSearchableArray')->returns(['id' => 1, 'name' => 'Taylor']); + $model->allows('scoutMetadata')->returns([]); + $model->allows('getScoutKey')->returns(1); $engine->update(new EloquentCollection([$model])); } public function testUpdateEmptyCollectionDoesNothing(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldNotReceive('saveObjects'); + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('saveObjects')->never(); $engine = new AlgoliaEngine($client); $engine->update(new EloquentCollection); - - $this->assertTrue(true); } public function testUpdateFiltersOutEmptySearchableArrays(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldNotReceive('saveObjects'); + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('saveObjects')->never(); $engine = new AlgoliaEngine($client); - $model = $this->createSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('users'); - $model->shouldReceive('toSearchableArray')->andReturn([]); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('indexableAs')->returns('users'); + $model->allows('toSearchableArray')->returns([]); $engine->update(new EloquentCollection([$model])); } public function testUpdateIncludesScoutMetadata(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('saveObjects') - ->once() + $client->expects('saveObjects') ->with('users', [ ['id' => 1, 'name' => 'Taylor', 'foo' => 'bar', 'objectID' => 1], ]); $engine = new AlgoliaEngine($client); - $model = $this->createSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('users'); - $model->shouldReceive('toSearchableArray')->andReturn(['id' => 1, 'name' => 'Taylor']); - $model->shouldReceive('scoutMetadata')->andReturn(['foo' => 'bar']); - $model->shouldReceive('getScoutKey')->andReturn(1); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('indexableAs')->returns('users'); + $model->allows('toSearchableArray')->returns(['id' => 1, 'name' => 'Taylor']); + $model->allows('scoutMetadata')->returns(['foo' => 'bar']); + $model->allows('getScoutKey')->returns(1); $engine->update(new EloquentCollection([$model])); } public function testUpdatePreparesTheFinalSearchableDocument(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldReceive('saveObjects') - ->once() + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('saveObjects') ->with('users', [[ 'name' => 'Taylor', '__soft_deleted' => 0, @@ -116,11 +115,11 @@ public function testUpdatePreparesTheFinalSearchableDocument(): void ]]); $engine = new AlgoliaEngine($client); - $model = $this->createSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('users'); - $model->shouldReceive('toSearchableArray')->andReturn(['name' => 'Taylor']); - $model->shouldReceive('scoutMetadata')->andReturn(['__soft_deleted' => 0]); - $model->shouldReceive('getScoutKey')->andReturn(1); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('indexableAs')->returns('users'); + $model->allows('toSearchableArray')->returns(['name' => 'Taylor']); + $model->allows('scoutMetadata')->returns(['__soft_deleted' => 0]); + $model->allows('getScoutKey')->returns(1); Scout::prepareSearchableDocumentUsing(function ( array $document, @@ -143,77 +142,69 @@ public function testUpdatePreparesTheFinalSearchableDocument(): void public function testUpdateWithSoftDeletesAddsSoftDeleteMetadata(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('saveObjects') - ->once() - ->with('users', m::on(function ($objects) { + $client->expects('saveObjects') + ->with('users', Argument::satisfies(function ($objects) { return isset($objects[0]['__soft_deleted']); })); $engine = new AlgoliaEngine($client, softDelete: true); - $model = $this->createSoftDeleteSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('users'); - $model->shouldReceive('toSearchableArray')->andReturn(['id' => 1, 'name' => 'Taylor']); - $model->shouldReceive('scoutMetadata')->andReturn(['__soft_deleted' => 0]); - $model->shouldReceive('getScoutKey')->andReturn(1); - $model->shouldReceive('pushSoftDeleteMetadata')->once()->andReturnSelf(); + $model = Double::for(AlgoliaTestSoftDeleteModel::class)->strict(); + $model->allows('indexableAs')->returns('users'); + $model->allows('toSearchableArray')->returns(['id' => 1, 'name' => 'Taylor']); + $model->allows('scoutMetadata')->returns(['__soft_deleted' => 0]); + $model->allows('getScoutKey')->returns(1); + $model->expects('pushSoftDeleteMetadata'); $engine->update(new EloquentCollection([$model])); } public function testDeleteRemovesObjects(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('deleteObjects') - ->once() + $client->expects('deleteObjects') ->with('users', [1]); $engine = new AlgoliaEngine($client); - $model = $this->createSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('users'); - $model->shouldReceive('getScoutKey')->andReturn(1); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('indexableAs')->returns('users'); + $model->allows('getScoutKey')->returns(1); + $model->allows('getScoutKeyName')->returns('id'); $engine->delete(new EloquentCollection([$model])); } public function testDeleteWithCustomScoutKey(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('deleteObjects') - ->once() + $client->expects('deleteObjects') ->with('chirps', ['my-key']); $engine = new AlgoliaEngine($client); - $model = $this->createSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('chirps'); - $model->shouldReceive('getScoutKey')->andReturn('my-key'); - $model->shouldReceive('getScoutKeyName')->andReturn('scout_id'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('indexableAs')->returns('chirps'); + $model->allows('getScoutKey')->returns('my-key'); + $model->allows('getScoutKeyName')->returns('scout_id'); $engine->delete(new EloquentCollection([$model])); } public function testDeleteWithRemoveableScoutCollection(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('deleteObjects') - ->once() + $client->expects('deleteObjects') ->with('chirps', ['my-key']); $engine = new AlgoliaEngine($client); - // RemoveableScoutCollection's delete path uses pluck($keyName) which - // reads attributes directly via data_get. A Mockery mock can't satisfy - // that because Model::__set routes through setAttribute (intercepted). - // A real fixture model with setRawAttributes works cleanly — no DB - // needed because delete() never hits the database. + // RemoveableScoutCollection reads attributes through pluck(), so use a real model. $model = new AlgoliaTestChirpModel; $model->setRawAttributes(['scout_id' => 'my-key']); @@ -224,23 +215,20 @@ public function testDeleteWithRemoveableScoutCollection(): void public function testDeleteEmptyCollection(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldNotReceive('deleteObjects'); + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('deleteObjects')->never(); $engine = new AlgoliaEngine($client); $engine->delete(new EloquentCollection); - - $this->assertTrue(true); } public function testDeleteIndex(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('deleteIndex') - ->once() + $client->expects('deleteIndex') ->with('users') - ->andReturn(['taskID' => 123]); + ->returns(['taskID' => 123]); $engine = new AlgoliaEngine($client); @@ -251,33 +239,30 @@ public function testDeleteIndex(): void public function testFlush(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('clearObjects') - ->once() + $client->expects('clearObjects') ->with('users'); $engine = new AlgoliaEngine($client); - $model = $this->createSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('indexableAs')->returns('users'); $engine->flush($model); } public function testDeleteByFilterPreparesTheBuilderAndUsesTheDefaultWriteIndex(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldReceive('deleteBy') - ->once() + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('deleteBy') ->with('users_write', [ 'filters' => "(visibility:public) AND (status:'active' AND tenant_id = 42)", ]) - ->andReturn(['taskID' => 123]); - $client->shouldReceive('waitForTask') - ->once() + ->returns(['taskID' => 123]); + $client->expects('waitForTask') ->with('users_write', 123) - ->andReturn(['status' => 'published']); + ->returns(['status' => 'published']); $runner = new EngineOperationRunner; $observer = new AlgoliaEngineOperationObserver; @@ -285,9 +270,9 @@ public function testDeleteByFilterPreparesTheBuilderAndUsesTheDefaultWriteIndex( $engine = (new AlgoliaEngine($client))->setOperationRunner($runner, 'algolia'); $this->assertInstanceOf(DeletesByFilter::class, $engine); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('indexableAs')->once()->andReturn('users_write'); - $model->shouldNotReceive('searchableAs'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->expects('indexableAs')->returns('users_write'); + $model->expects('searchableAs')->never(); $builder = (new Builder($model, '')) ->options(['filters' => 'visibility:public']) ->where('status', 'active'); @@ -307,19 +292,17 @@ public function testDeleteByFilterPreparesTheBuilderAndUsesTheDefaultWriteIndex( public function testDeleteByFilterUsesAnExplicitIndex(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldReceive('deleteBy') - ->once() + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('deleteBy') ->with('users_v2', ['filters' => 'tenant_id = 42']) - ->andReturn(['taskID' => 123]); - $client->shouldReceive('waitForTask') - ->once() + ->returns(['taskID' => 123]); + $client->expects('waitForTask') ->with('users_v2', 123) - ->andReturn(['status' => 'published']); + ->returns(['status' => 'published']); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldNotReceive('indexableAs'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->expects('indexableAs')->never(); $builder = (new Builder($model, ''))->within('users_v2')->where('tenant_id', 42); $engine->deleteByFilter($builder); @@ -327,30 +310,27 @@ public function testDeleteByFilterUsesAnExplicitIndex(): void public function testDeleteByFilterTreatsAMissingIndexAsAlreadyDeleted(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldReceive('deleteBy') - ->once() + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('deleteBy') ->with('users', ['filters' => 'tenant_id = 42']) - ->andThrow(new NotFoundException('Index not found', 404)); - $client->shouldNotReceive('waitForTask'); + ->throws(new NotFoundException('Index not found', 404)); + $client->expects('waitForTask')->never(); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('indexableAs')->once()->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->expects('indexableAs')->returns('users'); $builder = (new Builder($model, ''))->where('tenant_id', 42); (new AlgoliaEngine($client))->deleteByFilter($builder); - - $this->assertTrue(true); } public function testDeleteByFilterRejectsAnEmptyFilterBeforeIo(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldNotReceive('deleteBy'); - $client->shouldNotReceive('waitForTask'); + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('deleteBy')->never(); + $client->expects('waitForTask')->never(); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldNotReceive('indexableAs'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->expects('indexableAs')->never(); $builder = new Builder($model, ''); $prepared = false; @@ -370,17 +350,17 @@ public function testDeleteByFilterRejectsAnEmptyFilterBeforeIo(): void public function testDeleteByFilterDoesNotNotifyObserversForAnEmptyFilter(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldNotReceive('deleteBy'); - $client->shouldNotReceive('waitForTask'); - $observer = m::mock(EngineOperationObserver::class); - $observer->shouldNotReceive('starting'); - $observer->shouldNotReceive('finished'); + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('deleteBy')->never(); + $client->expects('waitForTask')->never(); + $observer = Double::for(EngineOperationObserver::class)->strict(); + $observer->expects('starting')->never(); + $observer->expects('finished')->never(); $runner = new EngineOperationRunner; $runner->observe($observer); $engine = (new AlgoliaEngine($client))->setOperationRunner($runner, 'algolia'); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldNotReceive('indexableAs'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->expects('indexableAs')->never(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('Algolia filter deletion requires a non-empty filter.'); @@ -391,19 +371,17 @@ public function testDeleteByFilterDoesNotNotifyObserversForAnEmptyFilter(): void #[DataProvider('incompleteFilterDeletionTasks')] public function testDeleteByFilterRejectsAnIncompleteTask(?array $task): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldReceive('deleteBy') - ->once() + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('deleteBy') ->with('users', ['filters' => 'tenant_id = 42']) - ->andReturn(['taskID' => 123]); - $client->shouldReceive('waitForTask') - ->once() + ->returns(['taskID' => 123]); + $client->expects('waitForTask') ->with('users', 123) - ->andReturn($task); + ->returns($task); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('indexableAs')->once()->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->expects('indexableAs')->returns('users'); $builder = (new Builder($model, ''))->where('tenant_id', 42); $this->expectException(ScoutException::class); @@ -427,10 +405,9 @@ public static function incompleteFilterDeletionTasks(): array public function testUpdateIndexSettings(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('setSettings') - ->once() + $client->expects('setSettings') ->with('users', ['searchableAttributes' => ['name', 'email']]); $engine = new AlgoliaEngine($client); @@ -439,7 +416,7 @@ public function testUpdateIndexSettings(): void public function testCreateIndexThrows(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); $engine = new AlgoliaEngine($client); $this->expectException(NotSupportedException::class); @@ -449,16 +426,15 @@ public function testCreateIndexThrows(): void public function testSearchSendsCorrectParameters(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() + $client->expects('searchSingleIndex') ->with('users', ['query' => 'zonda', 'filters' => 'foo = 1'], []); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'zonda'); $builder->where('foo', 1); @@ -472,20 +448,19 @@ public function testSearchComposesApplicationAndBuilderFilters( bool $hasBuilderFilter, ?string $expectedFilters ): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); $expected = ['query' => 'zonda']; if ($expectedFilters !== null) { $expected['filters'] = $expectedFilters; } - $client->shouldReceive('searchSingleIndex') - ->once() + $client->expects('searchSingleIndex') ->with('users', $expected, []); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'zonda'); if ($applicationFilters !== null) { @@ -520,9 +495,8 @@ public static function filterCombinations(): array public function testPaginateComposesApplicationAndBuilderFilters(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldReceive('searchSingleIndex') - ->once() + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('searchSingleIndex') ->with('users', [ 'query' => 'zonda', 'filters' => '(status:active OR status:trial) AND (tenant_id = 42)', @@ -531,8 +505,8 @@ public function testPaginateComposesApplicationAndBuilderFilters(): void ], []); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = (new Builder($model, 'zonda')) ->options(['filters' => 'status:active OR status:trial']) ->where('tenant_id', 42); @@ -542,11 +516,11 @@ public function testPaginateComposesApplicationAndBuilderFilters(): void public function testSearchCallbackReceivesFinalComposedOptions(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldNotReceive('searchSingleIndex'); + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('searchSingleIndex')->never(); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'zonda', function ($givenClient, $query, $options) use ($client) { $this->assertSame($client, $givenClient); $this->assertSame('zonda', $query); @@ -563,10 +537,9 @@ public function testSearchCallbackReceivesFinalComposedOptions(): void public function testSearchSendsBooleanInequalityAndEscapedFilters(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() + $client->expects('searchSingleIndex') ->with('users', [ 'query' => 'zonda', 'filters' => "is_live:true AND is_archived:false AND NOT status:'draft' AND NOT label:'manager\\'s draft\\\\review' AND NOT is_deleted:true AND is_featured>1 AND is_disabled<=0 AND rank>=10 AND score>=9223372036854775808 AND ratio<1.25 AND precise_ratio<1.2345678901234567 AND (is_featured:true OR is_featured:false) AND NOT is_hidden:true AND NOT is_hidden:false", @@ -574,8 +547,8 @@ public function testSearchSendsBooleanInequalityAndEscapedFilters(): void $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'zonda'); $builder->where('is_live', true) @@ -597,18 +570,17 @@ public function testSearchSendsBooleanInequalityAndEscapedFilters(): void public function testSearchPreservesNumericAndStringValueCategories(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() + $client->expects('searchSingleIndex') ->with('users', [ 'query' => 'zonda', 'filters' => "integer = -10 AND decimal = 1.25 AND precise = 1.2345678901234567 AND large = 1234567890123456 AND small = 1.0e-5 AND NOT excluded = 42 AND numeric_string:'42' AND (numbers = 1 OR numbers = 2.5) AND NOT blocked = 3 AND NOT blocked = 4", ], []); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'zonda'); $builder->where('integer', -10) @@ -626,17 +598,16 @@ public function testSearchPreservesNumericAndStringValueCategories(): void public function testCustomFilterFormattingAppliesToNumericFilters(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() + $client->expects('searchSingleIndex') ->with('users', [ 'query' => 'zonda', 'filters' => 'number = custom AND ordered>custom AND (numbers = custom OR numbers = custom)', ], []); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'zonda'); $builder->where('number', 1) @@ -649,11 +620,11 @@ public function testCustomFilterFormattingAppliesToNumericFilters(): void #[DataProvider('invalidFilterValues')] public function testSearchRejectsInvalidFilters(string $operator, mixed $value, string $message): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldNotReceive('searchSingleIndex'); + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('searchSingleIndex')->never(); $engine = new AlgoliaEngine($client); - $builder = new Builder(m::mock(AlgoliaTestSearchableModel::class), 'zonda'); + $builder = new Builder(Double::for(AlgoliaTestSearchableModel::class)->strict(), 'zonda'); $builder->where('value', $operator, $value); $this->expectException(InvalidArgumentException::class); @@ -686,10 +657,9 @@ public static function invalidFilterValues(): array public function testSearchSendsBackedEnumFilters(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() + $client->expects('searchSingleIndex') ->with('users', [ 'query' => 'zonda', 'filters' => "status:'published' AND priority = 1 AND (statuses:'draft' OR statuses:'published') AND NOT priorities = 1 AND NOT priorities = 2", @@ -697,8 +667,8 @@ public function testSearchSendsBackedEnumFilters(): void $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'zonda'); $builder->where('status', AlgoliaStringStatus::Published) @@ -711,16 +681,15 @@ public function testSearchSendsBackedEnumFilters(): void public function testSearchPreservesStringZeroIndex(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() + $client->expects('searchSingleIndex') ->with('0', ['query' => 'zonda'], []); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldNotReceive('searchableAs'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->expects('searchableAs')->never(); $builder = new Builder($model, 'zonda'); $builder->within('0'); @@ -730,16 +699,15 @@ public function testSearchPreservesStringZeroIndex(): void public function testSearchSendsCorrectParametersForWhereInSearch(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() + $client->expects('searchSingleIndex') ->with('users', ['query' => 'zonda', 'filters' => 'foo = 1 AND (bar = 1 OR bar = 2)'], []); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'zonda'); $builder->where('foo', 1)->whereIn('bar', [1, 2]); @@ -749,16 +717,15 @@ public function testSearchSendsCorrectParametersForWhereInSearch(): void public function testSearchSendsCorrectParametersForEmptyWhereInSearch(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() + $client->expects('searchSingleIndex') ->with('users', ['query' => 'zonda', 'filters' => 'foo = 1 AND 0:1'], []); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'zonda'); $builder->where('foo', 1)->whereIn('bar', []); @@ -768,16 +735,15 @@ public function testSearchSendsCorrectParametersForEmptyWhereInSearch(): void public function testSearchSendsCorrectParametersForWhereNotInSearch(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() + $client->expects('searchSingleIndex') ->with('users', ['query' => 'zonda', 'filters' => 'NOT foo = 1 AND NOT foo = 2'], []); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'zonda'); $builder->whereNotIn('foo', [1, 2]); @@ -787,16 +753,15 @@ public function testSearchSendsCorrectParametersForWhereNotInSearch(): void public function testSearchIgnoresEmptyWhereNotIn(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() + $client->expects('searchSingleIndex') ->with('users', ['query' => 'zonda'], []); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'zonda'); $builder->whereNotIn('foo', []); @@ -806,10 +771,9 @@ public function testSearchIgnoresEmptyWhereNotIn(): void public function testSearchSendsCorrectParametersForMixedSearch(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() + $client->expects('searchSingleIndex') ->with( 'users', ['query' => 'zonda', 'filters' => 'foo = 1 AND (bar = 1 OR bar = 2) AND NOT baz = 1 AND NOT baz = 2'], @@ -818,8 +782,8 @@ public function testSearchSendsCorrectParametersForMixedSearch(): void $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'zonda'); $builder->where('foo', 1) @@ -831,13 +795,13 @@ public function testSearchSendsCorrectParametersForMixedSearch(): void public function testSearchWithCallbackUsesCallback(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldNotReceive('searchSingleIndex'); + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('searchSingleIndex')->never(); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $called = false; $builder = new Builder($model, 'zonda', function ($c, $query, $options) use ($client, &$called) { @@ -856,18 +820,17 @@ public function testSearchWithCallbackUsesCallback(): void public function testPaginateComputesCorrectPage(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() - ->with('users', m::on(function ($params) { + $client->expects('searchSingleIndex') + ->with('users', Argument::satisfies(function ($params) { return $params['hitsPerPage'] === 15 && $params['page'] === 1; }), []); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'query'); @@ -876,13 +839,13 @@ public function testPaginateComputesCorrectPage(): void public function testMapReturnsEmptyWhenNoHits(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); $engine = new AlgoliaEngine($client); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('newCollection')->andReturn(new EloquentCollection); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('newCollection')->returns(new EloquentCollection); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $results = $engine->map($builder, ['hits' => []], $model); @@ -891,22 +854,20 @@ public function testMapReturnsEmptyWhenNoHits(): void public function testMapPopulatesScoutMetadataFromUnderscoreKeys(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); $engine = new AlgoliaEngine($client); - $searchableModel = m::mock(Model::class . ', ' . SearchableInterface::class); - $searchableModel->shouldReceive('getScoutKey')->andReturn(1); - $searchableModel->shouldReceive('withScoutMetadata') - ->with('_rankingInfo', ['nbTypos' => 0]) - ->once() - ->andReturnSelf(); + $searchableModel = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $searchableModel->allows('getScoutKey')->returns(1); + $searchableModel->expects('withScoutMetadata') + ->with('_rankingInfo', ['nbTypos' => 0]); - $model = m::mock(Model::class . ', ' . SearchableInterface::class); - $model->shouldReceive('getScoutModelsByIds')->andReturn(new EloquentCollection([$searchableModel])); - $model->shouldReceive('newCollection') - ->andReturnUsing(fn ($models) => new EloquentCollection($models)); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('getScoutModelsByIds')->returns(new EloquentCollection([$searchableModel])); + $model->allows('newCollection') + ->resolves(fn ($models) => new EloquentCollection($models)); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $results = $engine->map($builder, [ 'nbHits' => 1, @@ -920,24 +881,24 @@ public function testMapPopulatesScoutMetadataFromUnderscoreKeys(): void public function testMapRespectsOrder(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); $engine = new AlgoliaEngine($client); $mockModels = []; foreach ([1, 2, 3, 4] as $id) { - $mock = m::mock(Model::class . ', ' . SearchableInterface::class); - $mock->shouldReceive('getScoutKey')->andReturn($id); + $mock = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $mock->allows('getScoutKey')->returns($id); $mockModels[] = $mock; } $models = new EloquentCollection($mockModels); - $model = m::mock(Model::class . ', ' . SearchableInterface::class); - $model->shouldReceive('getScoutModelsByIds')->andReturn($models); - $model->shouldReceive('newCollection') - ->andReturnUsing(fn ($models) => new EloquentCollection($models)); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('getScoutModelsByIds')->returns($models); + $model->allows('newCollection') + ->resolves(fn ($models) => new EloquentCollection($models)); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $results = $engine->map($builder, [ 'nbHits' => 4, @@ -956,25 +917,25 @@ public function testMapRespectsOrder(): void public function testLazyMapRespectsOrder(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); $engine = new AlgoliaEngine($client); $mockModels = []; foreach ([1, 2, 3, 4] as $id) { - $mock = m::mock(Model::class . ', ' . SearchableInterface::class); - $mock->shouldReceive('getScoutKey')->andReturn($id); + $mock = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $mock->allows('getScoutKey')->returns($id); $mockModels[] = $mock; } $lazy = LazyCollection::make($mockModels); - $queryBuilder = m::mock(\Hypervel\Database\Eloquent\Builder::class); - $queryBuilder->shouldReceive('cursor')->andReturn($lazy); + $queryBuilder = Double::for(EloquentBuilder::class)->strict(); + $queryBuilder->allows('cursor')->returns($lazy); - $model = m::mock(Model::class . ', ' . SearchableInterface::class); - $model->shouldReceive('queryScoutModelsByIds')->andReturn($queryBuilder); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('queryScoutModelsByIds')->returns($queryBuilder); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $results = $engine->lazyMap($builder, [ 'nbHits' => 4, @@ -993,7 +954,7 @@ public function testLazyMapRespectsOrder(): void public function testGetTotalCount(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); $engine = new AlgoliaEngine($client); $this->assertEquals(42, $engine->getTotalCount(['nbHits' => 42])); @@ -1001,7 +962,7 @@ public function testGetTotalCount(): void public function testMapIdsReturnsObjectIDs(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); $engine = new AlgoliaEngine($client); $results = $engine->mapIds([ @@ -1018,7 +979,7 @@ public function testMapIdsReturnsObjectIDs(): void public function testConfigureSoftDeleteFilter(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); $engine = new AlgoliaEngine($client); $result = $engine->configureSoftDeleteFilter([ @@ -1033,16 +994,15 @@ public function testConfigureSoftDeleteFilter(): void public function testIdentifyDisabledSendsEmptyRequestOptions(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() - ->with('users', m::any(), []); + $client->expects('searchSingleIndex') + ->with('users', Argument::any(), []); $engine = new AlgoliaEngine($client, identify: false); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'query'); @@ -1051,19 +1011,18 @@ public function testIdentifyDisabledSendsEmptyRequestOptions(): void public function testIdentifyEnabledSendsHeadersFromRequest(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() - ->with('users', m::any(), ['headers' => ['X-Forwarded-For' => '203.0.113.10']]); + $client->expects('searchSingleIndex') + ->with('users', Argument::any(), ['headers' => ['X-Forwarded-For' => '203.0.113.10']]); $engine = new AlgoliaEngine($client, identify: true); $request = Request::create('/', 'GET', [], [], [], ['REMOTE_ADDR' => '203.0.113.10']); RequestContext::set($request); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'query'); @@ -1072,28 +1031,24 @@ public function testIdentifyEnabledSendsHeadersFromRequest(): void public function testIdentifyEnabledWithAuthenticatedUserAddsUserToken(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() - ->with('users', m::any(), m::on(function ($requestOptions) { + $client->expects('searchSingleIndex') + ->with('users', Argument::any(), Argument::satisfies(function ($requestOptions) { return isset($requestOptions['headers']['X-Algolia-UserToken']) && $requestOptions['headers']['X-Algolia-UserToken'] === '42'; })); $engine = new AlgoliaEngine($client, identify: true); - // Using a real fixture class (not a Mockery mock) because the engine - // calls method_exists($user, 'getKey') — Mockery's __call-based method - // stubs are not detected by method_exists, so a mock would be rejected. $user = new AlgoliaTestUser(42); $request = Request::create('/', 'GET', [], [], [], ['REMOTE_ADDR' => '203.0.113.10']); $request->setUserResolver(fn () => $user); RequestContext::set($request); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'query'); @@ -1102,19 +1057,18 @@ public function testIdentifyEnabledWithAuthenticatedUserAddsUserToken(): void public function testIdentifyIgnoresPrivateIPs(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('searchSingleIndex') - ->once() - ->with('users', m::any(), []); + $client->expects('searchSingleIndex') + ->with('users', Argument::any(), []); $engine = new AlgoliaEngine($client, identify: true); $request = Request::create('/', 'GET', [], [], [], ['REMOTE_ADDR' => '127.0.0.1']); RequestContext::set($request); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'query'); @@ -1128,12 +1082,12 @@ public function testIdentifyHeadersReflectTheCurrentRequestNotTheCachedOne(): vo // ONCE (as it would be in a Swoole worker) and must pick up the // current request's IP on every search — not the IP of whichever // request happened to trigger engine construction. - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); $capturedHeaders = []; - $client->shouldReceive('searchSingleIndex') - ->twice() - ->with('users', m::any(), m::on(function ($opts) use (&$capturedHeaders) { + $client->expects('searchSingleIndex') + ->times(2) + ->with('users', Argument::any(), Argument::satisfies(function ($opts) use (&$capturedHeaders) { $capturedHeaders[] = $opts['headers']['X-Forwarded-For'] ?? null; return true; @@ -1141,8 +1095,8 @@ public function testIdentifyHeadersReflectTheCurrentRequestNotTheCachedOne(): vo $engine = new AlgoliaEngine($client, identify: true); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'query'); @@ -1169,12 +1123,12 @@ public function testIdentifyHeadersDoNotLeakAcrossCoroutines(): void // two concurrent coroutines each seeding their own request must each // see their own headers in the resulting search call — never the // other coroutine's. - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); $capturedHeaders = []; - $client->shouldReceive('searchSingleIndex') - ->twice() - ->with('users', m::any(), m::on(function ($opts) use (&$capturedHeaders) { + $client->expects('searchSingleIndex') + ->times(2) + ->with('users', Argument::any(), Argument::satisfies(function ($opts) use (&$capturedHeaders) { $capturedHeaders[] = $opts['headers']['X-Forwarded-For'] ?? null; return true; @@ -1182,8 +1136,8 @@ public function testIdentifyHeadersDoNotLeakAcrossCoroutines(): void $engine = new AlgoliaEngine($client, identify: true); - $model = m::mock(AlgoliaTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('users'); + $model = Double::for(AlgoliaTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('users'); $builder = new Builder($model, 'query'); @@ -1191,15 +1145,23 @@ public function testIdentifyHeadersDoNotLeakAcrossCoroutines(): void $waiter->add(2); go(function () use ($engine, $builder, $waiter) { - RequestContext::set(Request::create('/', 'GET', [], [], [], ['REMOTE_ADDR' => '203.0.113.10'])); - $engine->search($builder); - $waiter->done(); + try { + RequestContext::set(Request::create('/', 'GET', [], [], [], ['REMOTE_ADDR' => '203.0.113.10'])); + usleep(5000); + $engine->search($builder); + } finally { + $waiter->done(); + } }); go(function () use ($engine, $builder, $waiter) { - RequestContext::set(Request::create('/', 'GET', [], [], [], ['REMOTE_ADDR' => '198.51.100.20'])); - $engine->search($builder); - $waiter->done(); + try { + RequestContext::set(Request::create('/', 'GET', [], [], [], ['REMOTE_ADDR' => '198.51.100.20'])); + usleep(5000); + $engine->search($builder); + } finally { + $waiter->done(); + } }); $waiter->wait(); @@ -1215,40 +1177,38 @@ public function testUpdateSoftDeletedWithEmptySearchableArrayDoesNotSave(): void // softDelete enabled and an empty toSearchableArray(), the engine // still calls pushSoftDeleteMetadata (runs before the empty check) // but does not call saveObjects. - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldNotReceive('saveObjects'); + $client = Double::for(AlgoliaSearchClient::class)->strict(); + $client->expects('saveObjects')->never(); $engine = new AlgoliaEngine($client, softDelete: true); - $model = $this->createSoftDeleteSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('chirps'); - $model->shouldReceive('toSearchableArray')->andReturn([]); - $model->shouldReceive('pushSoftDeleteMetadata')->once()->andReturnSelf(); + $model = Double::for(AlgoliaTestSoftDeleteModel::class)->strict(); + $model->allows('indexableAs')->returns('chirps'); + $model->allows('toSearchableArray')->returns([]); + $model->expects('pushSoftDeleteMetadata'); $engine->update(new EloquentCollection([$model])); } public function testCallForwardsUnknownMethodsToClient(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('customMethod') - ->once() - ->with('arg') - ->andReturn('result'); + $client->expects('getSettings') + ->with('users') + ->returns(['searchableAttributes' => ['name']]); $engine = new AlgoliaEngine($client); - $this->assertEquals('result', $engine->customMethod('arg')); + $this->assertSame(['searchableAttributes' => ['name']], $engine->getSettings('users')); } public function testDeleteAllIndexesWithPrefixScopesToPrefixedIndexes(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('listIndices') - ->once() - ->andReturn([ + $client->expects('listIndices') + ->returns([ 'items' => [ ['name' => 'test_users'], ['name' => 'test_posts'], @@ -1256,9 +1216,9 @@ public function testDeleteAllIndexesWithPrefixScopesToPrefixedIndexes(): void ], ]); - $client->shouldReceive('deleteIndex')->once()->with('test_users'); - $client->shouldReceive('deleteIndex')->once()->with('test_posts'); - $client->shouldNotReceive('deleteIndex')->with('other_data'); + $client->expects('deleteIndex')->with('test_users'); + $client->expects('deleteIndex')->with('test_posts'); + $client->expects('deleteIndex')->never()->with('other_data'); $engine = new AlgoliaEngine($client); $engine->deleteAllIndexes('test_'); @@ -1266,11 +1226,10 @@ public function testDeleteAllIndexesWithPrefixScopesToPrefixedIndexes(): void public function testDeleteAllIndexesWithNullPrefixDeletesEverything(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('listIndices') - ->once() - ->andReturn([ + $client->expects('listIndices') + ->returns([ 'items' => [ ['name' => 'test_users'], ['name' => 'test_posts'], @@ -1278,9 +1237,9 @@ public function testDeleteAllIndexesWithNullPrefixDeletesEverything(): void ], ]); - $client->shouldReceive('deleteIndex')->once()->with('test_users'); - $client->shouldReceive('deleteIndex')->once()->with('test_posts'); - $client->shouldReceive('deleteIndex')->once()->with('other_data'); + $client->expects('deleteIndex')->with('test_users'); + $client->expects('deleteIndex')->with('test_posts'); + $client->expects('deleteIndex')->with('other_data'); $engine = new AlgoliaEngine($client); $engine->deleteAllIndexes(null); @@ -1288,11 +1247,10 @@ public function testDeleteAllIndexesWithNullPrefixDeletesEverything(): void public function testDeleteAllIndexesWithEmptyStringPrefixDeletesEverything(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('listIndices') - ->once() - ->andReturn([ + $client->expects('listIndices') + ->returns([ 'items' => [ ['name' => 'test_users'], ['name' => 'test_posts'], @@ -1300,9 +1258,9 @@ public function testDeleteAllIndexesWithEmptyStringPrefixDeletesEverything(): vo ], ]); - $client->shouldReceive('deleteIndex')->once()->with('test_users'); - $client->shouldReceive('deleteIndex')->once()->with('test_posts'); - $client->shouldReceive('deleteIndex')->once()->with('other_data'); + $client->expects('deleteIndex')->with('test_users'); + $client->expects('deleteIndex')->with('test_posts'); + $client->expects('deleteIndex')->with('other_data'); $engine = new AlgoliaEngine($client); $engine->deleteAllIndexes(''); @@ -1310,19 +1268,18 @@ public function testDeleteAllIndexesWithEmptyStringPrefixDeletesEverything(): vo public function testDeleteAllIndexesReturnsResponses(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('listIndices') - ->once() - ->andReturn([ + $client->expects('listIndices') + ->returns([ 'items' => [ ['name' => 'test_users'], ['name' => 'test_posts'], ], ]); - $client->shouldReceive('deleteIndex')->with('test_users')->andReturn(['taskID' => 1]); - $client->shouldReceive('deleteIndex')->with('test_posts')->andReturn(['taskID' => 2]); + $client->allows('deleteIndex')->with('test_users')->returns(['taskID' => 1]); + $client->allows('deleteIndex')->with('test_posts')->returns(['taskID' => 2]); $engine = new AlgoliaEngine($client); $responses = $engine->deleteAllIndexes('test_'); @@ -1332,13 +1289,12 @@ public function testDeleteAllIndexesReturnsResponses(): void public function testDeleteAllIndexesWithNoIndexesReturnsEmptyArray(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('listIndices') - ->once() - ->andReturn(['items' => []]); + $client->expects('listIndices') + ->returns(['items' => []]); - $client->shouldNotReceive('deleteIndex'); + $client->expects('deleteIndex')->never(); $engine = new AlgoliaEngine($client); $result = $engine->deleteAllIndexes('test_'); @@ -1348,11 +1304,10 @@ public function testDeleteAllIndexesWithNoIndexesReturnsEmptyArray(): void public function testDeleteAllIndexesSkipsEntriesWithoutStringNames(): void { - $client = m::mock(AlgoliaSearchClient::class); + $client = Double::for(AlgoliaSearchClient::class)->strict(); - $client->shouldReceive('listIndices') - ->once() - ->andReturn([ + $client->expects('listIndices') + ->returns([ 'items' => [ ['name' => 'test_users'], ['name' => 42], // non-string, should skip @@ -1361,26 +1316,15 @@ public function testDeleteAllIndexesSkipsEntriesWithoutStringNames(): void ], ]); - $client->shouldReceive('deleteIndex')->once()->with('test_users'); - $client->shouldReceive('deleteIndex')->once()->with('test_posts'); - $client->shouldNotReceive('deleteIndex')->with(42); + $client->expects('deleteIndex')->with('test_users'); + $client->expects('deleteIndex')->with('test_posts'); + $client->expects('deleteIndex')->never()->with(42); $engine = new AlgoliaEngine($client); $responses = $engine->deleteAllIndexes('test_'); $this->assertCount(2, $responses); } - - protected function createSearchableModelMock(): m\MockInterface - { - return m::mock(Model::class . ', ' . SearchableInterface::class); - } - - protected function createSoftDeleteSearchableModelMock(): m\MockInterface - { - // Must mock a class that uses SoftDeletes for usesSoftDelete() to return true - return m::mock(AlgoliaTestSoftDeleteModel::class . ', ' . SearchableInterface::class); - } } class AlgoliaEngineOperationObserver implements EngineOperationObserver @@ -1470,13 +1414,6 @@ public function indexableAs(): string } } -/** - * Minimal user stub for identifyHeaders() tests. - * - * Needs a real class (not a Mockery mock) because the engine uses - * method_exists($user, 'getKey') to detect the presence of the method. - * Mockery stubs methods via __call which are invisible to method_exists. - */ class AlgoliaTestUser { public function __construct(private mixed $key) diff --git a/tests/Scout/Unit/Engines/EngineTest.php b/tests/Scout/Unit/Engines/EngineTest.php index b99ce24772..5e5d2532e1 100644 --- a/tests/Scout/Unit/Engines/EngineTest.php +++ b/tests/Scout/Unit/Engines/EngineTest.php @@ -8,7 +8,6 @@ use Hypervel\Database\Eloquent\Model; use Hypervel\Scout\Builder; use Hypervel\Scout\Contracts\EngineOperationObserver; -use Hypervel\Scout\Contracts\SearchableInterface; use Hypervel\Scout\EngineOperation; use Hypervel\Scout\EngineOperationRunner; use Hypervel\Scout\Engines\CollectionEngine; @@ -16,12 +15,16 @@ use Hypervel\Scout\Engines\Engine; use Hypervel\Support\Collection; use Hypervel\Support\LazyCollection; +use Hypervel\Tests\Scout\Fixtures\Models\SearchableModel; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Throwable; class EngineTest extends TestCase { + use VerifiesDoubles; + public function testOperationEntryPointsDescribeTheirExactTargets(): void { $model = $this->model(); @@ -181,14 +184,12 @@ public function testLocalEnginesBypassNoOpWritesWhileObservingReads(): void /** * Create a searchable model test double with different read and write indices. - * - * @return Model&SearchableInterface */ - protected function model(): Model + protected function model(): SearchableModel { - $model = m::mock(Model::class . ', ' . SearchableInterface::class); - $model->shouldReceive('searchableAs')->andReturn('read_index'); - $model->shouldReceive('indexableAs')->andReturn('write_index'); + $model = Double::for(SearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('read_index'); + $model->allows('indexableAs')->returns('write_index'); return $model; } diff --git a/tests/Scout/Unit/Engines/MeilisearchEngineTest.php b/tests/Scout/Unit/Engines/MeilisearchEngineTest.php index 5d4f9502a0..72d5af5ef7 100644 --- a/tests/Scout/Unit/Engines/MeilisearchEngineTest.php +++ b/tests/Scout/Unit/Engines/MeilisearchEngineTest.php @@ -16,7 +16,6 @@ use Hypervel\Scout\Builder; use Hypervel\Scout\Contracts\DeletesByFilter; use Hypervel\Scout\Contracts\EngineOperationObserver; -use Hypervel\Scout\Contracts\SearchableInterface; use Hypervel\Scout\EngineOperation; use Hypervel\Scout\EngineOperationRunner; use Hypervel\Scout\Engines\Engine; @@ -31,18 +30,22 @@ use Hypervel\Tests\Scout\Fixtures\Models\SearchableModelWithNativeEmbedding; use Hypervel\Tests\Scout\Fixtures\Models\SearchableModelWithPrecomputedEmbedding; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Meilisearch\Client; use Meilisearch\Contracts\IndexesResults; use Meilisearch\Endpoints\Indexes; use Meilisearch\Exceptions\ApiException; use Meilisearch\Exceptions\TimeOutException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use Throwable; #[WithConfig('ai.caching.embeddings.store', 'array')] class MeilisearchEngineTest extends TestCase { + use VerifiesDoubles; + /** * Register the embedding provider used by semantic searches. */ @@ -53,79 +56,72 @@ protected function getPackageProviders(ApplicationContract $app): array public function testUpdateAddsDocumentsToIndex(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); - $client->shouldReceive('index') + $client->expects('index') ->with('test_index') - ->once() - ->andReturn($index); + ->returns($index); - $index->shouldReceive('addDocuments') - ->once() + $index->expects('addDocuments') ->with([ ['id' => 1, 'title' => 'Test'], ], 'id'); $engine = new MeilisearchEngine($client); - $model = $this->createSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('test_index'); - $model->shouldReceive('toSearchableArray')->andReturn(['id' => 1, 'title' => 'Test']); - $model->shouldReceive('scoutMetadata')->andReturn([]); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); - $model->shouldReceive('getScoutKey')->andReturn(1); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('indexableAs')->returns('test_index'); + $model->allows('toSearchableArray')->returns(['id' => 1, 'title' => 'Test']); + $model->allows('scoutMetadata')->returns([]); + $model->allows('getScoutKeyName')->returns('id'); + $model->allows('getScoutKey')->returns(1); $engine->update(new EloquentCollection([$model])); } public function testUpdateEmptyCollectionDoesNothing(): void { - $client = m::mock(Client::class); - $client->shouldNotReceive('index'); + $client = Double::for(Client::class)->strict(); + $client->expects('index')->never(); $engine = new MeilisearchEngine($client); $engine->update(new EloquentCollection); - - $this->assertTrue(true); } public function testUpdateWithSoftDeletesAddsSoftDeleteMetadata(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); - $client->shouldReceive('index') + $client->expects('index') ->with('test_index') - ->once() - ->andReturn($index); + ->returns($index); - $index->shouldReceive('addDocuments') - ->once() - ->with(m::on(function ($documents) { + $index->expects('addDocuments') + ->with(Argument::satisfies(function ($documents) { return isset($documents[0]['__soft_deleted']); }), 'id'); $engine = new MeilisearchEngine($client, softDelete: true); - $model = $this->createSoftDeleteSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('test_index'); - $model->shouldReceive('toSearchableArray')->andReturn(['id' => 1, 'title' => 'Test']); - $model->shouldReceive('scoutMetadata')->andReturn(['__soft_deleted' => 0]); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); - $model->shouldReceive('getScoutKey')->andReturn(1); - $model->shouldReceive('pushSoftDeleteMetadata')->once()->andReturnSelf(); + $model = Double::for(MeilisearchTestSoftDeleteModel::class)->strict(); + $model->allows('indexableAs')->returns('test_index'); + $model->allows('toSearchableArray')->returns(['id' => 1, 'title' => 'Test']); + $model->allows('scoutMetadata')->returns(['__soft_deleted' => 0]); + $model->allows('getScoutKeyName')->returns('id'); + $model->allows('getScoutKey')->returns(1); + $model->expects('pushSoftDeleteMetadata'); $engine->update(new EloquentCollection([$model])); } public function testUpdatePreparesTheFinalSearchableDocument(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); - $client->shouldReceive('index')->once()->with('test_index')->andReturn($index); - $index->shouldReceive('addDocuments') - ->once() + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); + $client->expects('index')->with('test_index')->returns($index); + $index->expects('addDocuments') ->with([[ 'title' => 'Test', '__soft_deleted' => 0, @@ -134,12 +130,12 @@ public function testUpdatePreparesTheFinalSearchableDocument(): void ]], 'id'); $engine = new MeilisearchEngine($client); - $model = $this->createSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('test_index'); - $model->shouldReceive('toSearchableArray')->andReturn(['title' => 'Test']); - $model->shouldReceive('scoutMetadata')->andReturn(['__soft_deleted' => 0]); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); - $model->shouldReceive('getScoutKey')->andReturn(1); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('indexableAs')->returns('test_index'); + $model->allows('toSearchableArray')->returns(['title' => 'Test']); + $model->allows('scoutMetadata')->returns(['__soft_deleted' => 0]); + $model->allows('getScoutKeyName')->returns('id'); + $model->allows('getScoutKey')->returns(1); Scout::prepareSearchableDocumentUsing(function ( array $document, @@ -164,7 +160,7 @@ public function testUpdateAddsPrecomputedEmbeddingsToVectorsBeforePreparingDocum { Embeddings::fake()->preventStrayEmbeddings(); - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = $this->engineWithEmbedding($client, ['embedder' => 'default', 'dimensions' => 2]); $first = new SearchableModelWithPrecomputedEmbedding(['id' => 10, 'name' => 'First']); @@ -182,8 +178,8 @@ public function testUpdateAddsPrecomputedEmbeddingsToVectorsBeforePreparingDocum return $document; }); - $client->shouldReceive('index')->once()->with('table')->andReturn($index = m::mock(Indexes::class)); - $index->shouldReceive('addDocuments')->once()->with([ + $client->expects('index')->with('table')->returns($index = Double::for(Indexes::class)->strict()); + $index->expects('addDocuments')->with([ [ 'id' => 10, 'name' => 'First', @@ -210,7 +206,7 @@ public function testUpdateAddsPrecomputedAndGeneratedEmbeddingsToVectors(): void { Embeddings::fake([[[0.3, 0.4]]])->preventStrayEmbeddings(); - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = $this->engineWithEmbedding($client, [ 'embedder' => 'default', 'dimensions' => 2, @@ -223,8 +219,8 @@ public function testUpdateAddsPrecomputedAndGeneratedEmbeddingsToVectors(): void $precomputed->setAttribute('_vectors', ['other' => [0.9, 0.8]]); $generated = new SearchableModelWithPrecomputedEmbedding(['id' => 20, 'name' => 'Generate this']); - $client->shouldReceive('index')->once()->with('table')->andReturn($index = m::mock(Indexes::class)); - $index->shouldReceive('addDocuments')->once()->with(m::on(fn (array $objects): bool => $objects[0]['_vectors'] === [ + $client->expects('index')->with('table')->returns($index = Double::for(Indexes::class)->strict()); + $index->expects('addDocuments')->with(Argument::satisfies(fn (array $objects): bool => $objects[0]['_vectors'] === [ 'other' => [0.9, 0.8], 'default' => [0.1, 0.2], ] && $objects[1]['_vectors'] === ['default' => [0.3, 0.4]]), 'id'); @@ -241,7 +237,7 @@ public function testUpdateDoesNotAddVectorsWhenUsingNativeEmbeddings(): void { Embeddings::fake()->preventStrayEmbeddings(); - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = $this->engineWithEmbedding( $client, ['embedder' => 'default', 'driver' => 'meilisearch'], @@ -250,8 +246,8 @@ public function testUpdateDoesNotAddVectorsWhenUsingNativeEmbeddings(): void $model = new SearchableModelWithNativeEmbedding(['id' => 1, 'name' => 'Model 1']); - $client->shouldReceive('index')->once()->with('table')->andReturn($index = m::mock(Indexes::class)); - $index->shouldReceive('addDocuments')->once()->with([ + $client->expects('index')->with('table')->returns($index = Double::for(Indexes::class)->strict()); + $index->expects('addDocuments')->with([ ['id' => 1, 'name' => 'Model 1'], ], 'id'); @@ -262,7 +258,7 @@ public function testUpdatePreservesUserProvidedVectorsWhenUsingNativeEmbeddings( { Embeddings::fake()->preventStrayEmbeddings(); - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = $this->engineWithEmbedding( $client, ['embedder' => 'default', 'driver' => 'meilisearch'], @@ -277,8 +273,8 @@ public function testUpdatePreservesUserProvidedVectorsWhenUsingNativeEmbeddings( ], ]); - $client->shouldReceive('index')->once()->with('table')->andReturn($index = m::mock(Indexes::class)); - $index->shouldReceive('addDocuments')->once()->with([ + $client->expects('index')->with('table')->returns($index = Double::for(Indexes::class)->strict()); + $index->expects('addDocuments')->with([ [ 'id' => 1, 'name' => 'Model 1', @@ -296,42 +292,38 @@ public function testUpdatePreservesUserProvidedVectorsWhenUsingNativeEmbeddings( public function testDeleteRemovesDocumentsFromIndex(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); - $client->shouldReceive('index') + $client->expects('index') ->with('test_index') - ->once() - ->andReturn($index); + ->returns($index); - $index->shouldReceive('deleteDocuments') - ->once() + $index->expects('deleteDocuments') ->with([1, 2]); $engine = new MeilisearchEngine($client); - $model1 = $this->createSearchableModelMock(); - $model1->shouldReceive('indexableAs')->andReturn('test_index'); - $model1->shouldReceive('getScoutKey')->andReturn(1); + $model1 = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model1->allows('indexableAs')->returns('test_index'); + $model1->allows('getScoutKey')->returns(1); - $model2 = $this->createSearchableModelMock(); - $model2->shouldReceive('getScoutKey')->andReturn(2); + $model2 = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model2->allows('getScoutKey')->returns(2); $engine->delete(new EloquentCollection([$model1, $model2])); } public function testDeleteWithRemoveableScoutCollectionUsesStoredScoutKey(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); - $client->shouldReceive('index') + $client->expects('index') ->with('chirps') - ->once() - ->andReturn($index); + ->returns($index); - $index->shouldReceive('deleteDocuments') - ->once() + $index->expects('deleteDocuments') ->with(['stored-scout-key']); $engine = new MeilisearchEngine($client); @@ -344,35 +336,31 @@ public function testDeleteWithRemoveableScoutCollectionUsesStoredScoutKey(): voi public function testDeleteEmptyCollectionDoesNothing(): void { - $client = m::mock(Client::class); - $client->shouldNotReceive('index'); + $client = Double::for(Client::class)->strict(); + $client->expects('index')->never(); $engine = new MeilisearchEngine($client); $engine->delete(new EloquentCollection); - - $this->assertTrue(true); } public function testSearchPerformsSearchOnMeilisearch(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); - $client->shouldReceive('index') + $client->expects('index') ->with('test_index') - ->once() - ->andReturn($index); + ->returns($index); - $index->shouldReceive('rawSearch') - ->once() - ->with('test query', m::any()) - ->andReturn(['hits' => [], 'totalHits' => 0]); + $index->expects('rawSearch') + ->with('test query', Argument::any()) + ->returns(['hits' => [], 'totalHits' => 0]); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('test_index'); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('test_index'); + $model->allows('getScoutKeyName')->returns('id'); $builder = new Builder($model, 'test query'); @@ -383,26 +371,24 @@ public function testSearchPerformsSearchOnMeilisearch(): void public function testSearchWithFilters(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); - $client->shouldReceive('index') + $client->expects('index') ->with('test_index') - ->once() - ->andReturn($index); + ->returns($index); - $index->shouldReceive('rawSearch') - ->once() - ->with('query', m::on(function ($params) { + $index->expects('rawSearch') + ->with('query', Argument::satisfies(function ($params) { return $params['filter'] === 'status="active" AND score>=10 AND label!="draft\"review\\\copy" AND archived_at IS NOT NULL AND tags IN ["a\"b\\\c", true] AND hidden NOT IN ["draft", false]'; })) - ->andReturn(['hits' => [], 'totalHits' => 0]); + ->returns(['hits' => [], 'totalHits' => 0]); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('test_index'); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('test_index'); + $model->allows('getScoutKeyName')->returns('id'); $builder = new Builder($model, 'query'); $builder->where('status', 'active') @@ -417,18 +403,18 @@ public function testSearchWithFilters(): void public function testWhereInAndWhereNotInValuesAreEscaped(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); - $client->shouldReceive('index')->once()->with('test_index')->andReturn($index); - $index->shouldReceive('rawSearch')->once()->with('', [ + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); + $client->expects('index')->with('test_index')->returns($index); + $index->expects('rawSearch')->with('', [ 'filter' => 'category IN ["12\" pipe", "back\\\slash"] AND tag NOT IN ["a\"] OR team_id = 2 OR tag IN [\"b"]', - ])->andReturn(['hits' => [], 'totalHits' => 0]); + ])->returns(['hits' => [], 'totalHits' => 0]); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('test_index'); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('test_index'); + $model->allows('getScoutKeyName')->returns('id'); $builder = new Builder($model, ''); $builder->whereIn('category', ['12" pipe', 'back\slash']); @@ -443,16 +429,16 @@ public function testSearchComposesApplicationAndBuilderFilters( bool $hasBuilderFilter, string|array|null $expectedFilter ): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); - $client->shouldReceive('index')->once()->with('test_index')->andReturn($index); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); + $client->expects('index')->with('test_index')->returns($index); $expected = $expectedFilter === null ? [] : ['filter' => $expectedFilter]; - $index->shouldReceive('rawSearch')->once()->with('query', $expected); + $index->expects('rawSearch')->with('query', $expected); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('test_index'); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('test_index'); + $model->allows('getScoutKeyName')->returns('id'); $builder = new Builder($model, 'query'); if ($applicationFilter !== null) { @@ -498,19 +484,19 @@ public static function filterCombinations(): array public function testPaginateComposesApplicationAndBuilderFilters(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); - $client->shouldReceive('index')->once()->with('test_index')->andReturn($index); - $index->shouldReceive('rawSearch')->once()->with('query', [ + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); + $client->expects('index')->with('test_index')->returns($index); + $index->expects('rawSearch')->with('query', [ 'filter' => '(status="active" OR status="trial") AND (tenant_id=42)', 'hitsPerPage' => 15, 'page' => 2, ]); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('test_index'); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('test_index'); + $model->allows('getScoutKeyName')->returns('id'); $builder = (new Builder($model, 'query')) ->options(['filter' => 'status="active" OR status="trial"']) ->where('tenant_id', 42); @@ -520,14 +506,14 @@ public function testPaginateComposesApplicationAndBuilderFilters(): void public function testSearchCallbackReceivesFinalComposedOptions(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); - $client->shouldReceive('index')->once()->with('test_index')->andReturn($index); - $index->shouldNotReceive('rawSearch'); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); + $client->expects('index')->with('test_index')->returns($index); + $index->expects('rawSearch')->never(); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('test_index'); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('test_index'); + $model->allows('getScoutKeyName')->returns('id'); $builder = new Builder($model, 'query', function ($givenIndex, $query, $options) use ($index) { $this->assertSame($index, $givenIndex); $this->assertSame('query', $query); @@ -544,26 +530,24 @@ public function testSearchCallbackReceivesFinalComposedOptions(): void public function testSearchWithBackedEnumFilters(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); - $client->shouldReceive('index') + $client->expects('index') ->with('test_index') - ->once() - ->andReturn($index); + ->returns($index); - $index->shouldReceive('rawSearch') - ->once() - ->with('query', m::on(function ($params) { + $index->expects('rawSearch') + ->with('query', Argument::satisfies(function ($params) { return $params['filter'] === 'status="published" AND priority=1 AND statuses IN ["draft", "published"] AND priorities NOT IN [1, 2]'; })) - ->andReturn(['hits' => [], 'totalHits' => 0]); + ->returns(['hits' => [], 'totalHits' => 0]); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('test_index'); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('test_index'); + $model->allows('getScoutKeyName')->returns('id'); $builder = new Builder($model, 'query'); $builder->where('status', MeilisearchStringStatus::Published) @@ -576,26 +560,24 @@ public function testSearchWithBackedEnumFilters(): void public function testPaginatePerformsPaginatedSearch(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); - $client->shouldReceive('index') + $client->expects('index') ->with('test_index') - ->once() - ->andReturn($index); + ->returns($index); - $index->shouldReceive('rawSearch') - ->once() - ->with('query', m::on(function ($params) { + $index->expects('rawSearch') + ->with('query', Argument::satisfies(function ($params) { return $params['hitsPerPage'] === 15 && $params['page'] === 2; })) - ->andReturn(['hits' => [], 'totalHits' => 0]); + ->returns(['hits' => [], 'totalHits' => 0]); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('searchableAs')->andReturn('test_index'); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('test_index'); + $model->allows('getScoutKeyName')->returns('id'); $builder = new Builder($model, 'query'); @@ -606,15 +588,15 @@ public function testSemanticSearchWithNativeEmbeddingsOmitsTheQueryVector(): voi { Embeddings::fake()->preventStrayEmbeddings(); - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = $this->engineWithEmbedding( $client, ['embedder' => 'default', 'driver' => 'meilisearch'], SearchableModelWithNativeEmbedding::class, ); - $client->shouldReceive('index')->once()->with('table')->andReturn($index = m::mock(Indexes::class)); - $index->shouldReceive('rawSearch')->once()->with('conceptual query', m::on(fn (array $parameters): bool => $parameters === [ + $client->expects('index')->with('table')->returns($index = Double::for(Indexes::class)->strict()); + $index->expects('rawSearch')->with('conceptual query', Argument::satisfies(fn (array $parameters): bool => $parameters === [ 'hitsPerPage' => 10, 'hybrid' => [ 'embedder' => 'default', @@ -622,7 +604,7 @@ public function testSemanticSearchWithNativeEmbeddingsOmitsTheQueryVector(): voi ], 'rankingScoreThreshold' => 0, 'filter' => 'status="published"', - ]))->andReturn(['hits' => []]); + ]))->returns(['hits' => []]); $builder = (new Builder(new SearchableModelWithNativeEmbedding, 'conceptual query')) ->semantic(minSimilarity: 0) @@ -636,15 +618,15 @@ public function testHybridSearchWithNativeEmbeddingsAcceptsAPrecomputedQueryVect { Embeddings::fake()->preventStrayEmbeddings(); - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = $this->engineWithEmbedding( $client, ['embedder' => 'default', 'driver' => 'meilisearch'], SearchableModelWithNativeEmbedding::class, ); - $client->shouldReceive('index')->once()->with('table')->andReturn($index = m::mock(Indexes::class)); - $index->shouldReceive('rawSearch')->once()->with('combined query', [ + $client->expects('index')->with('table')->returns($index = Double::for(Indexes::class)->strict()); + $index->expects('rawSearch')->with('combined query', [ 'vector' => [0.4, 0.6], 'hitsPerPage' => 5, 'page' => 2, @@ -652,7 +634,7 @@ public function testHybridSearchWithNativeEmbeddingsAcceptsAPrecomputedQueryVect 'embedder' => 'default', 'semanticRatio' => 2 / 3, ], - ])->andReturn(['hits' => []]); + ])->returns(['hits' => []]); $builder = (new Builder(new SearchableModelWithNativeEmbedding, 'combined query')) ->options(['vector' => [0.4, 0.6]]) @@ -663,8 +645,8 @@ public function testHybridSearchWithNativeEmbeddingsAcceptsAPrecomputedQueryVect public function testSemanticSearchRejectsAnUnsupportedEmbeddingDriver(): void { - $client = m::mock(Client::class); - $client->shouldNotReceive('index'); + $client = Double::for(Client::class)->strict(); + $client->expects('index')->never(); $engine = $this->engineWithEmbedding($client, ['embedder' => 'default', 'dimensions' => 2, 'driver' => 'foo']); $builder = (new Builder(new SearchableModelWithPrecomputedEmbedding, 'conceptual query'))->semantic(); @@ -679,11 +661,11 @@ public function testHybridSearchAcceptsAPrecomputedQueryVectorAndNormalizesWeigh { Embeddings::fake()->preventStrayEmbeddings(); - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = $this->engineWithEmbedding($client, ['embedder' => 'default', 'dimensions' => 2]); - $client->shouldReceive('index')->once()->with('table')->andReturn($index = m::mock(Indexes::class)); - $index->shouldReceive('rawSearch')->once()->with('combined query', [ + $client->expects('index')->with('table')->returns($index = Double::for(Indexes::class)->strict()); + $index->expects('rawSearch')->with('combined query', [ 'vector' => [0.4, 0.6], 'hitsPerPage' => 5, 'page' => 2, @@ -692,7 +674,7 @@ public function testHybridSearchAcceptsAPrecomputedQueryVectorAndNormalizesWeigh 'semanticRatio' => 2 / 3, ], 'rankingScoreThreshold' => 0.5, - ])->andReturn(['hits' => []]); + ])->returns(['hits' => []]); $builder = (new Builder(new SearchableModelWithPrecomputedEmbedding, 'combined query')) ->options(['vector' => [0.4, 0.6]]) @@ -705,17 +687,17 @@ public function testSemanticSearchGeneratesAQueryVector(): void { Embeddings::fake([[[0.25, 0.75]]])->preventStrayEmbeddings(); - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = $this->engineWithEmbedding($client, ['embedder' => 'default', 'dimensions' => 2]); - $client->shouldReceive('index')->twice()->with('table')->andReturn($index = m::mock(Indexes::class)); - $index->shouldReceive('rawSearch')->twice()->with('conceptual query', [ + $client->expects('index')->times(2)->with('table')->returns($index = Double::for(Indexes::class)->strict()); + $index->expects('rawSearch')->times(2)->with('conceptual query', [ 'hitsPerPage' => 10, 'vector' => [0.25, 0.75], 'hybrid' => ['embedder' => 'default', 'semanticRatio' => 1.0], 'rankingScoreThreshold' => 0, 'filter' => 'status="published"', - ])->andReturn(['hits' => []]); + ])->returns(['hits' => []]); $builder = (new Builder(new SearchableModelWithPrecomputedEmbedding, 'conceptual query')) ->semantic(minSimilarity: 0) @@ -735,8 +717,8 @@ public function testSemanticSearchGeneratesAQueryVector(): void #[DataProvider('invalidSemanticSearchOptions')] public function testSemanticSearchRejectsInvalidOptions(array $options, string $message): void { - $client = m::mock(Client::class); - $client->shouldNotReceive('index'); + $client = Double::for(Client::class)->strict(); + $client->expects('index')->never(); $engine = $this->engineWithEmbedding($client, ['embedder' => 'default', 'dimensions' => 2]); $this->expectException(ScoutException::class); @@ -770,7 +752,7 @@ public static function invalidSemanticSearchOptions(): array public function testMapIdsReturnsEmptyCollectionIfNoHits(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = new MeilisearchEngine($client); $results = $engine->mapIdsFrom([ @@ -783,7 +765,7 @@ public function testMapIdsReturnsEmptyCollectionIfNoHits(): void public function testMapIdsReturnsCorrectPrimaryKeys(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = new MeilisearchEngine($client); $results = $engine->mapIdsFrom([ @@ -801,24 +783,22 @@ public function testMapIdsReturnsCorrectPrimaryKeys(): void public function testMapCorrectlyMapsResultsToModels(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = new MeilisearchEngine($client); // Create a mock searchable model that tracks scout metadata - $searchableModel = m::mock(Model::class . ', ' . SearchableInterface::class); - $searchableModel->shouldReceive('getScoutKey')->andReturn(1); - $searchableModel->shouldReceive('withScoutMetadata') - ->with('_rankingScore', 0.86) - ->once() - ->andReturnSelf(); + $searchableModel = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $searchableModel->allows('getScoutKey')->returns(1); + $searchableModel->expects('withScoutMetadata') + ->with('_rankingScore', 0.86); - $model = m::mock(Model::class . ', ' . SearchableInterface::class); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); - $model->shouldReceive('getScoutModelsByIds')->andReturn(new EloquentCollection([$searchableModel])); - $model->shouldReceive('newCollection') - ->andReturnUsing(fn ($models) => new EloquentCollection($models)); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('getScoutKeyName')->returns('id'); + $model->allows('getScoutModelsByIds')->returns(new EloquentCollection([$searchableModel])); + $model->allows('newCollection') + ->resolves(fn ($models) => new EloquentCollection($models)); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $results = $engine->map($builder, [ 'totalHits' => 1, @@ -832,13 +812,13 @@ public function testMapCorrectlyMapsResultsToModels(): void public function testMapReturnsEmptyCollectionWhenNoHits(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('newCollection')->andReturn(new EloquentCollection); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('newCollection')->returns(new EloquentCollection); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $results = $engine->map($builder, ['hits' => []], $model); @@ -847,26 +827,26 @@ public function testMapReturnsEmptyCollectionWhenNoHits(): void public function testMapRespectsOrder(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = new MeilisearchEngine($client); // Create mock models $mockModels = []; foreach ([1, 2, 3, 4] as $id) { - $mock = m::mock(Model::class . ', ' . SearchableInterface::class); - $mock->shouldReceive('getScoutKey')->andReturn($id); + $mock = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $mock->allows('getScoutKey')->returns($id); $mockModels[] = $mock; } $models = new EloquentCollection($mockModels); - $model = m::mock(Model::class . ', ' . SearchableInterface::class); - $model->shouldReceive('getScoutKeyName')->andReturn('id'); - $model->shouldReceive('getScoutModelsByIds')->andReturn($models); - $model->shouldReceive('newCollection') - ->andReturnUsing(fn ($models) => new EloquentCollection($models)); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('getScoutKeyName')->returns('id'); + $model->allows('getScoutModelsByIds')->returns($models); + $model->allows('newCollection') + ->resolves(fn ($models) => new EloquentCollection($models)); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $results = $engine->map($builder, [ 'totalHits' => 4, @@ -886,13 +866,13 @@ public function testMapRespectsOrder(): void public function testLazyMapReturnsEmptyCollectionWhenNoHits(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('newCollection')->andReturn(new EloquentCollection); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('newCollection')->returns(new EloquentCollection); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $results = $engine->lazyMap($builder, ['hits' => []], $model); @@ -902,7 +882,7 @@ public function testLazyMapReturnsEmptyCollectionWhenNoHits(): void public function testGetTotalCountReturnsTotalHits(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = new MeilisearchEngine($client); $this->assertSame(3, $engine->getTotalCount(['totalHits' => 3])); @@ -910,7 +890,7 @@ public function testGetTotalCountReturnsTotalHits(): void public function testGetTotalCountReturnsEstimatedTotalHits(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = new MeilisearchEngine($client); $this->assertSame(5, $engine->getTotalCount(['estimatedTotalHits' => 5])); @@ -918,7 +898,7 @@ public function testGetTotalCountReturnsEstimatedTotalHits(): void public function testGetTotalCountReturnsZeroWhenNoCountAvailable(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = new MeilisearchEngine($client); $this->assertSame(0, $engine->getTotalCount([])); @@ -926,37 +906,34 @@ public function testGetTotalCountReturnsZeroWhenNoCountAvailable(): void public function testFlushDeletesAllDocuments(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); - $client->shouldReceive('index') + $client->expects('index') ->with('test_index') - ->once() - ->andReturn($index); + ->returns($index); - $index->shouldReceive('deleteAllDocuments')->once(); + $index->expects('deleteAllDocuments'); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('indexableAs')->andReturn('test_index'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('indexableAs')->returns('test_index'); $engine->flush($model); } public function testDeleteByFilterPreparesTheBuilderAndWaitsForTheDefaultWriteIndex(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); - $client->shouldReceive('index')->once()->with('users_write')->andReturn($index); - $index->shouldReceive('deleteDocuments') - ->once() + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); + $client->expects('index')->with('users_write')->returns($index); + $index->expects('deleteDocuments') ->with(['filter' => [['visibility=true', 'visibility=false'], 'status="active" AND tenant_id=42']]) - ->andReturn(['taskUid' => 123]); - $client->shouldReceive('waitForTask') - ->once() + ->returns(['taskUid' => 123]); + $client->expects('waitForTask') ->with(123, 500_000, 5_000) - ->andReturn(['status' => 'succeeded']); + ->returns(['status' => 'succeeded']); $runner = new EngineOperationRunner; $observer = new MeilisearchEngineOperationObserver; @@ -964,9 +941,9 @@ public function testDeleteByFilterPreparesTheBuilderAndWaitsForTheDefaultWriteIn $engine = (new MeilisearchEngine($client))->setOperationRunner($runner, 'meilisearch'); $this->assertInstanceOf(DeletesByFilter::class, $engine); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('indexableAs')->once()->andReturn('users_write'); - $model->shouldNotReceive('searchableAs'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->expects('indexableAs')->returns('users_write'); + $model->expects('searchableAs')->never(); $builder = (new Builder($model, '')) ->options(['filter' => [['visibility=true', 'visibility=false']]]) ->where('status', 'active'); @@ -986,21 +963,19 @@ public function testDeleteByFilterPreparesTheBuilderAndWaitsForTheDefaultWriteIn public function testDeleteByFilterUsesAnExplicitIndex(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); - $client->shouldReceive('index')->once()->with('users_v2')->andReturn($index); - $index->shouldReceive('deleteDocuments') - ->once() + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); + $client->expects('index')->with('users_v2')->returns($index); + $index->expects('deleteDocuments') ->with(['filter' => 'tenant_id=42']) - ->andReturn(['taskUid' => 123]); - $client->shouldReceive('waitForTask') - ->once() + ->returns(['taskUid' => 123]); + $client->expects('waitForTask') ->with(123, 500_000, 5_000) - ->andReturn(['status' => 'succeeded']); + ->returns(['status' => 'succeeded']); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldNotReceive('indexableAs'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->expects('indexableAs')->never(); $builder = (new Builder($model, ''))->within('users_v2')->where('tenant_id', 42); $engine->deleteByFilter($builder); @@ -1008,38 +983,34 @@ public function testDeleteByFilterUsesAnExplicitIndex(): void public function testDeleteByFilterTreatsAMissingIndexAsAlreadyDeleted(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); - $client->shouldReceive('index')->once()->with('users')->andReturn($index); - $index->shouldReceive('deleteDocuments') - ->once() + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); + $client->expects('index')->with('users')->returns($index); + $index->expects('deleteDocuments') ->with(['filter' => 'tenant_id=42']) - ->andReturn(['taskUid' => 123]); - $client->shouldReceive('waitForTask') - ->once() + ->returns(['taskUid' => 123]); + $client->expects('waitForTask') ->with(123, 500_000, 5_000) - ->andReturn([ + ->returns([ 'status' => 'failed', 'error' => ['code' => 'index_not_found'], ]); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('indexableAs')->once()->andReturn('users'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->expects('indexableAs')->returns('users'); $builder = (new Builder($model, ''))->where('tenant_id', 42); (new MeilisearchEngine($client))->deleteByFilter($builder); - - $this->assertTrue(true); } public function testDeleteByFilterRejectsAnEmptyFilterBeforeIo(): void { - $client = m::mock(Client::class); - $client->shouldNotReceive('index'); - $client->shouldNotReceive('waitForTask'); + $client = Double::for(Client::class)->strict(); + $client->expects('index')->never(); + $client->expects('waitForTask')->never(); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldNotReceive('indexableAs'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->expects('indexableAs')->never(); $builder = new Builder($model, ''); $prepared = false; Scout::prepareBuilderUsing(function () use (&$prepared): void { @@ -1058,17 +1029,17 @@ public function testDeleteByFilterRejectsAnEmptyFilterBeforeIo(): void public function testDeleteByFilterDoesNotNotifyObserversForAnEmptyFilter(): void { - $client = m::mock(Client::class); - $client->shouldNotReceive('index'); - $client->shouldNotReceive('waitForTask'); - $observer = m::mock(EngineOperationObserver::class); - $observer->shouldNotReceive('starting'); - $observer->shouldNotReceive('finished'); + $client = Double::for(Client::class)->strict(); + $client->expects('index')->never(); + $client->expects('waitForTask')->never(); + $observer = Double::for(EngineOperationObserver::class)->strict(); + $observer->expects('starting')->never(); + $observer->expects('finished')->never(); $runner = new EngineOperationRunner; $runner->observe($observer); $engine = (new MeilisearchEngine($client))->setOperationRunner($runner, 'meilisearch'); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldNotReceive('indexableAs'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->expects('indexableAs')->never(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('Meilisearch filter deletion requires a non-empty filter.'); @@ -1078,18 +1049,17 @@ public function testDeleteByFilterDoesNotNotifyObserversForAnEmptyFilter(): void public function testDeleteByFilterRejectsAnUnsuccessfulTask(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); - $client->shouldReceive('index')->once()->with('users')->andReturn($index); - $index->shouldReceive('deleteDocuments')->once()->andReturn(['taskUid' => 123]); - $client->shouldReceive('waitForTask') - ->once() + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); + $client->expects('index')->with('users')->returns($index); + $index->expects('deleteDocuments')->returns(['taskUid' => 123]); + $client->expects('waitForTask') ->with(123, 500_000, 5_000) - ->andReturn(['status' => 'failed']); + ->returns(['status' => 'failed']); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('indexableAs')->andReturn('users'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('indexableAs')->returns('users'); $builder = (new Builder($model, ''))->where('tenant_id', 42); $this->expectException(ScoutException::class); @@ -1100,19 +1070,18 @@ public function testDeleteByFilterRejectsAnUnsuccessfulTask(): void public function testDeleteByFilterPreservesSdkTimeouts(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); $timeout = new TimeOutException('Timed out waiting for deletion.'); - $client->shouldReceive('index')->once()->with('users')->andReturn($index); - $index->shouldReceive('deleteDocuments')->once()->andReturn(['taskUid' => 123]); - $client->shouldReceive('waitForTask') - ->once() + $client->expects('index')->with('users')->returns($index); + $index->expects('deleteDocuments')->returns(['taskUid' => 123]); + $client->expects('waitForTask') ->with(123, 500_000, 5_000) - ->andThrow($timeout); + ->throws($timeout); $engine = new MeilisearchEngine($client); - $model = m::mock(MeilisearchTestSearchableModel::class); - $model->shouldReceive('indexableAs')->andReturn('users'); + $model = Double::for(MeilisearchTestSearchableModel::class)->strict(); + $model->allows('indexableAs')->returns('users'); $builder = (new Builder($model, ''))->where('tenant_id', 42); $this->expectExceptionObject($timeout); @@ -1122,18 +1091,16 @@ public function testDeleteByFilterPreservesSdkTimeouts(): void public function testCreateIndexCreatesNewIndex(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); - $client->shouldReceive('getIndex') + $client->expects('getIndex') ->with('test_index') - ->once() - ->andThrow($this->apiException(404, 'index_not_found')); + ->throws($this->apiException(404, 'index_not_found')); $taskInfo = ['taskUid' => 1, 'indexUid' => 'test_index', 'status' => 'enqueued']; - $client->shouldReceive('createIndex') + $client->expects('createIndex') ->with('test_index', ['primaryKey' => 'id']) - ->once() - ->andReturn($taskInfo); + ->returns($taskInfo); $engine = new MeilisearchEngine($client); @@ -1144,17 +1111,16 @@ public function testCreateIndexCreatesNewIndex(): void public function testCreateIndexReturnsExistingIndex(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); - $index->shouldReceive('getUid')->andReturn('test_index'); + $index->allows('getUid')->returns('test_index'); - $client->shouldReceive('getIndex') + $client->expects('getIndex') ->with('test_index') - ->once() - ->andReturn($index); + ->returns($index); - $client->shouldNotReceive('createIndex'); + $client->expects('createIndex')->never(); $engine = new MeilisearchEngine($client); @@ -1165,15 +1131,14 @@ public function testCreateIndexReturnsExistingIndex(): void public function testCreateIndexPropagatesNonNotFoundLookupFailure(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $exception = $this->apiException(401, 'invalid_api_key'); - $client->shouldReceive('getIndex') + $client->expects('getIndex') ->with('test_index') - ->once() - ->andThrow($exception); + ->throws($exception); - $client->shouldNotReceive('createIndex'); + $client->expects('createIndex')->never(); $engine = new MeilisearchEngine($client); @@ -1184,23 +1149,20 @@ public function testCreateIndexPropagatesNonNotFoundLookupFailure(): void public function testCreateIndexReturnsIndexWhenCreationLosesRace(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); - $client->shouldReceive('getIndex') + $client->expects('getIndex') ->with('test_index') - ->once() - ->andThrow($this->apiException(404, 'index_not_found')); + ->throws($this->apiException(404, 'index_not_found')); - $client->shouldReceive('createIndex') + $client->expects('createIndex') ->with('test_index', []) - ->once() - ->andThrow($this->apiException(409, 'index_already_exists')); + ->throws($this->apiException(409, 'index_already_exists')); - $client->shouldReceive('index') + $client->expects('index') ->with('test_index') - ->once() - ->andReturn($index); + ->returns($index); $engine = new MeilisearchEngine($client); @@ -1209,20 +1171,18 @@ public function testCreateIndexReturnsIndexWhenCreationLosesRace(): void public function testCreateIndexPropagatesOtherCreateConflict(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $exception = $this->apiException(409, 'invalid_index_uid'); - $client->shouldReceive('getIndex') + $client->expects('getIndex') ->with('test_index') - ->once() - ->andThrow($this->apiException(404, 'index_not_found')); + ->throws($this->apiException(404, 'index_not_found')); - $client->shouldReceive('createIndex') + $client->expects('createIndex') ->with('test_index', []) - ->once() - ->andThrow($exception); + ->throws($exception); - $client->shouldNotReceive('index'); + $client->expects('index')->never(); $engine = new MeilisearchEngine($client); @@ -1233,12 +1193,11 @@ public function testCreateIndexPropagatesOtherCreateConflict(): void public function testDeleteIndexDeletesIndex(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); - $client->shouldReceive('deleteIndex') + $client->expects('deleteIndex') ->with('test_index') - ->once() - ->andReturn(['taskUid' => 1]); + ->returns(['taskUid' => 1]); $engine = new MeilisearchEngine($client); @@ -1249,24 +1208,24 @@ public function testDeleteIndexDeletesIndex(): void public function testDeleteAllIndexesWithPrefixScopesToPrefixedUids(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); - $testUsers = m::mock(Indexes::class); - $testUsers->shouldReceive('getUid')->andReturn('test_users'); - $testUsers->shouldReceive('delete')->once()->andReturn(['taskUid' => 1]); + $testUsers = Double::for(Indexes::class)->strict(); + $testUsers->allows('getUid')->returns('test_users'); + $testUsers->expects('delete')->returns(['taskUid' => 1]); - $testPosts = m::mock(Indexes::class); - $testPosts->shouldReceive('getUid')->andReturn('test_posts'); - $testPosts->shouldReceive('delete')->once()->andReturn(['taskUid' => 2]); + $testPosts = Double::for(Indexes::class)->strict(); + $testPosts->allows('getUid')->returns('test_posts'); + $testPosts->expects('delete')->returns(['taskUid' => 2]); - $otherData = m::mock(Indexes::class); - $otherData->shouldReceive('getUid')->andReturn('other_data'); - $otherData->shouldNotReceive('delete'); + $otherData = Double::for(Indexes::class)->strict(); + $otherData->allows('getUid')->returns('other_data'); + $otherData->expects('delete')->never(); - $results = m::mock(IndexesResults::class); - $results->shouldReceive('getResults')->andReturn([$testUsers, $testPosts, $otherData]); + $results = Double::for(IndexesResults::class)->strict(); + $results->allows('getResults')->returns([$testUsers, $testPosts, $otherData]); - $client->shouldReceive('getIndexes')->once()->andReturn($results); + $client->expects('getIndexes')->returns($results); $engine = new MeilisearchEngine($client); $engine->deleteAllIndexes('test_'); @@ -1274,24 +1233,24 @@ public function testDeleteAllIndexesWithPrefixScopesToPrefixedUids(): void public function testDeleteAllIndexesWithNullPrefixDeletesEverything(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); - $testUsers = m::mock(Indexes::class); - $testUsers->shouldReceive('getUid')->andReturn('test_users'); - $testUsers->shouldReceive('delete')->once(); + $testUsers = Double::for(Indexes::class)->strict(); + $testUsers->allows('getUid')->returns('test_users'); + $testUsers->expects('delete'); - $testPosts = m::mock(Indexes::class); - $testPosts->shouldReceive('getUid')->andReturn('test_posts'); - $testPosts->shouldReceive('delete')->once(); + $testPosts = Double::for(Indexes::class)->strict(); + $testPosts->allows('getUid')->returns('test_posts'); + $testPosts->expects('delete'); - $otherData = m::mock(Indexes::class); - $otherData->shouldReceive('getUid')->andReturn('other_data'); - $otherData->shouldReceive('delete')->once(); + $otherData = Double::for(Indexes::class)->strict(); + $otherData->allows('getUid')->returns('other_data'); + $otherData->expects('delete'); - $results = m::mock(IndexesResults::class); - $results->shouldReceive('getResults')->andReturn([$testUsers, $testPosts, $otherData]); + $results = Double::for(IndexesResults::class)->strict(); + $results->allows('getResults')->returns([$testUsers, $testPosts, $otherData]); - $client->shouldReceive('getIndexes')->once()->andReturn($results); + $client->expects('getIndexes')->returns($results); $engine = new MeilisearchEngine($client); $engine->deleteAllIndexes(null); @@ -1299,24 +1258,24 @@ public function testDeleteAllIndexesWithNullPrefixDeletesEverything(): void public function testDeleteAllIndexesWithEmptyStringPrefixDeletesEverything(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); - $testUsers = m::mock(Indexes::class); - $testUsers->shouldReceive('getUid')->andReturn('test_users'); - $testUsers->shouldReceive('delete')->once(); + $testUsers = Double::for(Indexes::class)->strict(); + $testUsers->allows('getUid')->returns('test_users'); + $testUsers->expects('delete'); - $testPosts = m::mock(Indexes::class); - $testPosts->shouldReceive('getUid')->andReturn('test_posts'); - $testPosts->shouldReceive('delete')->once(); + $testPosts = Double::for(Indexes::class)->strict(); + $testPosts->allows('getUid')->returns('test_posts'); + $testPosts->expects('delete'); - $otherData = m::mock(Indexes::class); - $otherData->shouldReceive('getUid')->andReturn('other_data'); - $otherData->shouldReceive('delete')->once(); + $otherData = Double::for(Indexes::class)->strict(); + $otherData->allows('getUid')->returns('other_data'); + $otherData->expects('delete'); - $results = m::mock(IndexesResults::class); - $results->shouldReceive('getResults')->andReturn([$testUsers, $testPosts, $otherData]); + $results = Double::for(IndexesResults::class)->strict(); + $results->allows('getResults')->returns([$testUsers, $testPosts, $otherData]); - $client->shouldReceive('getIndexes')->once()->andReturn($results); + $client->expects('getIndexes')->returns($results); $engine = new MeilisearchEngine($client); $engine->deleteAllIndexes(''); @@ -1324,20 +1283,20 @@ public function testDeleteAllIndexesWithEmptyStringPrefixDeletesEverything(): vo public function testDeleteAllIndexesReturnsTasks(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); - $testUsers = m::mock(Indexes::class); - $testUsers->shouldReceive('getUid')->andReturn('test_users'); - $testUsers->shouldReceive('delete')->andReturn(['taskUid' => 1]); + $testUsers = Double::for(Indexes::class)->strict(); + $testUsers->allows('getUid')->returns('test_users'); + $testUsers->allows('delete')->returns(['taskUid' => 1]); - $testPosts = m::mock(Indexes::class); - $testPosts->shouldReceive('getUid')->andReturn('test_posts'); - $testPosts->shouldReceive('delete')->andReturn(['taskUid' => 2]); + $testPosts = Double::for(Indexes::class)->strict(); + $testPosts->allows('getUid')->returns('test_posts'); + $testPosts->allows('delete')->returns(['taskUid' => 2]); - $results = m::mock(IndexesResults::class); - $results->shouldReceive('getResults')->andReturn([$testUsers, $testPosts]); + $results = Double::for(IndexesResults::class)->strict(); + $results->allows('getResults')->returns([$testUsers, $testPosts]); - $client->shouldReceive('getIndexes')->andReturn($results); + $client->allows('getIndexes')->returns($results); $engine = new MeilisearchEngine($client); $tasks = $engine->deleteAllIndexes('test_'); @@ -1347,58 +1306,49 @@ public function testDeleteAllIndexesReturnsTasks(): void public function testUpdateIndexSettingsWithEmbedders(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); - $client->shouldReceive('index') + $client->expects('index') ->with('test_index') - ->once() - ->andReturn($index); + ->returns($index); - $index->shouldReceive('updateSettings') - ->with(['searchableAttributes' => ['title']]) - ->once(); + $index->expects('updateSettings') + ->with(['searchableAttributes' => ['title']]); - $index->shouldReceive('updateEmbedders') - ->with(['default' => ['source' => 'openAi']]) - ->once(); + $index->expects('updateEmbedders') + ->with(['default' => ['source' => 'openAi']]); $engine = new MeilisearchEngine($client); $engine->updateIndexSettings('test_index', [ 'searchableAttributes' => ['title'], 'embedders' => ['default' => ['source' => 'openAi']], ]); - - $this->assertTrue(true); } public function testUpdateIndexSettingsWithoutEmbedders(): void { - $client = m::mock(Client::class); - $index = m::mock(Indexes::class); + $client = Double::for(Client::class)->strict(); + $index = Double::for(Indexes::class)->strict(); - $client->shouldReceive('index') + $client->expects('index') ->with('test_index') - ->once() - ->andReturn($index); + ->returns($index); - $index->shouldReceive('updateSettings') - ->with(['searchableAttributes' => ['title', 'body']]) - ->once(); + $index->expects('updateSettings') + ->with(['searchableAttributes' => ['title', 'body']]); - $index->shouldNotReceive('updateEmbedders'); + $index->expects('updateEmbedders')->never(); $engine = new MeilisearchEngine($client); $engine->updateIndexSettings('test_index', [ 'searchableAttributes' => ['title', 'body'], ]); - - $this->assertTrue(true); } public function testConfigureSoftDeleteFilterAddsFilterableAttribute(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = new MeilisearchEngine($client); $settings = $engine->configureSoftDeleteFilter([ @@ -1411,10 +1361,9 @@ public function testConfigureSoftDeleteFilterAddsFilterableAttribute(): void public function testEngineForwardsCallsToMeilisearchClient(): void { - $client = m::mock(Client::class); - $client->shouldReceive('health') - ->once() - ->andReturn(['status' => 'available']); + $client = Double::for(Client::class)->strict(); + $client->expects('health') + ->returns(['status' => 'available']); $engine = new MeilisearchEngine($client); @@ -1425,7 +1374,7 @@ public function testEngineForwardsCallsToMeilisearchClient(): void public function testGetMeilisearchClientReturnsClient(): void { - $client = m::mock(Client::class); + $client = Double::for(Client::class)->strict(); $engine = new MeilisearchEngine($client); $this->assertSame($client, $engine->getMeilisearchClient()); @@ -1467,9 +1416,9 @@ public function testGenerateTenantTokenRejectsEmptyCredentials( string $apiKey, string $message ): void { - $client = m::mock(Client::class); - $client->shouldNotReceive('generateTenantToken'); - $client->shouldNotReceive('getKeys'); + $client = Double::for(Client::class)->strict(); + $client->expects('generateTenantToken')->never(); + $client->expects('getKeys')->never(); $engine = new MeilisearchEngine($client); $this->expectException(InvalidArgumentException::class); @@ -1516,17 +1465,6 @@ protected function engineWithEmbedding( ], ]); } - - protected function createSearchableModelMock(): m\MockInterface - { - return m::mock(Model::class . ', ' . SearchableInterface::class); - } - - protected function createSoftDeleteSearchableModelMock(): m\MockInterface - { - // Must mock a class that uses SoftDeletes for usesSoftDelete() to return true - return m::mock(MeilisearchTestSoftDeleteModel::class . ', ' . SearchableInterface::class); - } } class MeilisearchEngineOperationObserver implements EngineOperationObserver diff --git a/tests/Scout/Unit/Engines/NullEngineTest.php b/tests/Scout/Unit/Engines/NullEngineTest.php index 08fc246811..302ca3cb52 100644 --- a/tests/Scout/Unit/Engines/NullEngineTest.php +++ b/tests/Scout/Unit/Engines/NullEngineTest.php @@ -8,42 +8,45 @@ use Hypervel\Database\Eloquent\Model; use Hypervel\Scout\Builder; use Hypervel\Scout\Contracts\EngineOperationObserver; -use Hypervel\Scout\Contracts\SearchableInterface; use Hypervel\Scout\EngineOperation; use Hypervel\Scout\EngineOperationRunner; use Hypervel\Scout\Engines\NullEngine; use Hypervel\Support\Collection; use Hypervel\Support\LazyCollection; +use Hypervel\Tests\Scout\Fixtures\Models\SearchableModel; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Throwable; class NullEngineTest extends TestCase { + use VerifiesDoubles; + public function testUpdateDoesNothing(): void { $engine = new NullEngine; - $models = new EloquentCollection([m::mock(Model::class)]); + $model = Double::for(Model::class)->strict(); + $models = new EloquentCollection([$model]); - // Should not throw any exception $engine->update($models); - $this->assertTrue(true); + $model->unused(); } public function testDeleteDoesNothing(): void { $engine = new NullEngine; - $models = new EloquentCollection([m::mock(Model::class)]); + $model = Double::for(Model::class)->strict(); + $models = new EloquentCollection([$model]); - // Should not throw any exception $engine->delete($models); - $this->assertTrue(true); + $model->unused(); } public function testSearchReturnsEmptyArray(): void { $engine = new NullEngine; - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $result = $engine->search($builder); @@ -54,7 +57,7 @@ public function testSearchReturnsEmptyArray(): void public function testPaginateReturnsEmptyArray(): void { $engine = new NullEngine; - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $result = $engine->paginate($builder, 15, 1); @@ -75,8 +78,8 @@ public function testMapIdsReturnsEmptyCollection(): void public function testMapReturnsEmptyEloquentCollection(): void { $engine = new NullEngine; - $builder = m::mock(Builder::class); - $model = m::mock(Model::class); + $builder = Double::for(Builder::class)->strict(); + $model = Double::for(Model::class)->strict(); $result = $engine->map($builder, [], $model); @@ -87,8 +90,8 @@ public function testMapReturnsEmptyEloquentCollection(): void public function testLazyMapReturnsEmptyLazyCollection(): void { $engine = new NullEngine; - $builder = m::mock(Builder::class); - $model = m::mock(Model::class); + $builder = Double::for(Builder::class)->strict(); + $model = Double::for(Model::class)->strict(); $result = $engine->lazyMap($builder, [], $model); @@ -113,11 +116,10 @@ public function testGetTotalCountReturnsCountForCountableResults(): void public function testFlushDoesNothing(): void { $engine = new NullEngine; - $model = m::mock(Model::class); + $model = Double::for(Model::class)->strict(); - // Should not throw any exception $engine->flush($model); - $this->assertTrue(true); + $model->unused(); } public function testCreateIndexReturnsEmptyArray(): void @@ -143,13 +145,13 @@ public function testDeleteIndexReturnsEmptyArray(): void public function testDeclinesObservationForEveryOperationEntryPoint(): void { $runner = new EngineOperationRunner; - $observer = m::mock(EngineOperationObserver::class); - $observer->shouldNotReceive('starting'); - $observer->shouldNotReceive('finished'); + $observer = Double::for(EngineOperationObserver::class)->strict(); + $observer->expects('starting')->never(); + $observer->expects('finished')->never(); $runner->observe($observer); $engine = (new NullEngine)->setOperationRunner($runner, 'null'); - $builder = m::mock(Builder::class); - $model = m::mock(Model::class); + $builder = Double::for(Builder::class)->strict(); + $model = Double::for(Model::class)->strict(); $models = new EloquentCollection([$model]); $this->assertSame([], $engine->runSearch($builder)); @@ -165,8 +167,8 @@ public function testDeclinesObservationForEveryOperationEntryPoint(): void public function testSubclassWithRealOperationsCanOptIntoObservation(): void { - $model = m::mock(Model::class . ', ' . SearchableInterface::class); - $model->shouldReceive('searchableAs')->andReturn('models'); + $model = Double::for(SearchableModel::class)->strict(); + $model->allows('searchableAs')->returns('models'); $builder = new Builder($model, 'query'); $runner = new EngineOperationRunner; $observer = new NullEngineOperationObserver; diff --git a/tests/Scout/Unit/Engines/TypesenseEngineTest.php b/tests/Scout/Unit/Engines/TypesenseEngineTest.php index a49139d3bd..7112ce93d5 100644 --- a/tests/Scout/Unit/Engines/TypesenseEngineTest.php +++ b/tests/Scout/Unit/Engines/TypesenseEngineTest.php @@ -13,7 +13,6 @@ use Hypervel\Scout\Builder; use Hypervel\Scout\Contracts\DeletesByFilter; use Hypervel\Scout\Contracts\EngineOperationObserver; -use Hypervel\Scout\Contracts\SearchableInterface; use Hypervel\Scout\EngineOperation; use Hypervel\Scout\EngineOperationRunner; use Hypervel\Scout\Engines\Engine; @@ -24,11 +23,14 @@ use Hypervel\Scout\Scout; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; +use Hypervel\Tests\Scout\Fixtures\Models\SearchableModel; use Hypervel\Tests\Scout\Fixtures\Models\SearchableModelWithNativeEmbedding; use Hypervel\Tests\Scout\Fixtures\Models\SearchableModelWithPrecomputedEmbedding; use InvalidArgumentException; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionMethod; use Throwable; @@ -47,6 +49,8 @@ #[WithConfig('ai.caching.embeddings.store', 'array')] class TypesenseEngineTest extends TestCase { + use VerifiesDoubles; + /** * Register the embedding provider used by semantic searches. */ @@ -55,16 +59,22 @@ protected function getPackageProviders(ApplicationContract $app): array return [AiServiceProvider::class]; } - protected function createEngine(?MockInterface $client = null): TypesenseEngine + /** + * Create an engine with the given client. + */ + protected function createEngine(?TypesenseClient $client = null): TypesenseEngine { - $client = $client ?? m::mock(TypesenseClient::class); + $client = $client ?? Double::for(TypesenseClient::class)->strict(); return new TypesenseEngine($client, 1000); } - protected function createSearchableModelMock(): MockInterface + /** + * Create a double with the declared searchable model methods. + */ + protected function createSearchableModelDouble(): SearchableModel&DoubleInterface { - return m::mock(Model::class . ', ' . SearchableInterface::class); + return Double::for(SearchableModel::class)->strict(); } protected function invokeMethod(object $object, string $methodName, array $parameters = []): mixed @@ -78,7 +88,7 @@ public function testFiltersMethod(): void { $engine = $this->createEngine(); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $builder->wheres = [ ['field' => 'status', 'operator' => '=', 'value' => 'active'], ['field' => 'age', 'operator' => '>=', 'value' => 25], @@ -222,20 +232,18 @@ public function testCreateIndexThrowsNotSupportedException(): void public function testUpdateWithEmptyCollectionDoesNothing(): void { - $client = m::mock(TypesenseClient::class); - $client->shouldNotReceive('getCollections'); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->never(); $engine = $this->createEngine($client); $engine->update(new EloquentCollection([])); - - $this->assertTrue(true); // No exception means success } public function testUpdateTransformsBeforeTouchingTypesense(): void { - $client = m::mock(TypesenseClient::class); - $client->shouldNotReceive('getCollections'); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->never(); $model = new TypesenseLifecycleModel; $model->searchableData = []; @@ -245,20 +253,19 @@ public function testUpdateTransformsBeforeTouchingTypesense(): void public function testUpdateImportsIntoIndexableCollection(): void { - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); - - $client->shouldReceive('getCollections')->once()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); - $collections->shouldNotReceive('create'); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $documents->shouldReceive('import') - ->once() + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); + + $client->expects('getCollections')->returns($collections); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); + $collections->expects('create')->never(); + $collection->expects('getDocuments')->returns($documents); + $documents->expects('import') ->with([['id' => 1, 'title' => 'Scout']], ['action' => 'upsert']) - ->andReturn([['success' => true, 'document' => '{"id":1}']]); + ->returns([['success' => true, 'document' => '{"id":1}']]); $model = new TypesenseLifecycleModel; @@ -267,19 +274,18 @@ public function testUpdateImportsIntoIndexableCollection(): void public function testUpdateMethodWithEmplaceAction(): void { - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); - - $client->shouldReceive('getCollections')->once()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $documents->shouldReceive('import') - ->once() + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); + + $client->expects('getCollections')->returns($collections); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); + $collection->expects('getDocuments')->returns($documents); + $documents->expects('import') ->with([['id' => 1, 'title' => 'Scout']], ['action' => 'emplace']) - ->andReturn([['success' => true, 'document' => '{"id":1}']]); + ->returns([['success' => true, 'document' => '{"id":1}']]); $engine = $this->createPartialEngineWithConfig($client, config: ['typesense.import_action' => 'emplace']); @@ -288,18 +294,17 @@ public function testUpdateMethodWithEmplaceAction(): void public function testUpdatePreparesTheFinalSearchableDocument(): void { - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $documents->shouldReceive('import') - ->once() + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); + $client->expects('getCollections')->returns($collections); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); + $collection->expects('getDocuments')->returns($documents); + $documents->expects('import') ->with([['id' => 1, 'title' => 'Scout', 'tenant_id' => 42]], ['action' => 'upsert']) - ->andReturn([['success' => true, 'document' => '{"id":1}']]); + ->returns([['success' => true, 'document' => '{"id":1}']]); $model = new TypesenseLifecycleModel; $engine = $this->createPartialEngineWithConfig($client); @@ -322,21 +327,20 @@ public function testUpdateAddsPrecomputedEmbeddingsToDocumentsBeforePreparingThe { Embeddings::fake()->preventStrayEmbeddings(); - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('table')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('table')->once(); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $documents->shouldReceive('import') - ->once() + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); + $client->expects('getCollections')->returns($collections); + $collections->expects('offsetGet')->with('table')->returns($collection); + $collections->expects('offsetUnset')->with('table'); + $collection->expects('getDocuments')->returns($documents); + $documents->expects('import') ->with([ ['id' => 10, 'name' => 'First', 'embedding' => [0.1, 0.2], 'embedding_vector' => [0.1, 0.2]], ['id' => 20, 'name' => 'Second', 'embedding' => [0.3, 0.4], 'embedding_vector' => [0.3, 0.4]], ], ['action' => 'upsert']) - ->andReturn([['success' => true], ['success' => true]]); + ->returns([['success' => true], ['success' => true]]); $engine = $this->createSemanticEngine(['attribute' => 'embedding_vector', 'dimensions' => 2], client: $client); @@ -363,18 +367,18 @@ public function testUpdateAddsPrecomputedAndGeneratedEmbeddingsToDocuments(): vo { Embeddings::fake([[[0.3, 0.4]]])->preventStrayEmbeddings(); - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('table')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('table')->once(); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $documents->shouldReceive('import')->once()->with([ + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); + $client->expects('getCollections')->returns($collections); + $collections->expects('offsetGet')->with('table')->returns($collection); + $collections->expects('offsetUnset')->with('table'); + $collection->expects('getDocuments')->returns($documents); + $documents->expects('import')->with([ ['id' => 10, 'name' => 'Precomputed', 'embedding' => [0.1, 0.2]], ['id' => 20, 'name' => 'Generate this', 'embedding' => [0.3, 0.4]], - ], ['action' => 'upsert'])->andReturn([['success' => true], ['success' => true]]); + ], ['action' => 'upsert'])->returns([['success' => true], ['success' => true]]); $engine = $this->createSemanticEngine([ 'attribute' => 'embedding', @@ -399,18 +403,17 @@ public function testUpdateDoesNotGenerateEmbeddingsWhenUsingNativeEmbeddings(): { Embeddings::fake()->preventStrayEmbeddings(); - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('table')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('table')->once(); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $documents->shouldReceive('import') - ->once() + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); + $client->expects('getCollections')->returns($collections); + $collections->expects('offsetGet')->with('table')->returns($collection); + $collections->expects('offsetUnset')->with('table'); + $collection->expects('getDocuments')->returns($documents); + $documents->expects('import') ->with([['id' => 1, 'name' => 'Model 1']], ['action' => 'upsert']) - ->andReturn([['success' => true]]); + ->returns([['success' => true]]); $engine = $this->createSemanticEngine( ['attribute' => 'embedding', 'driver' => 'typesense'], @@ -425,30 +428,29 @@ public function testUpdateDoesNotGenerateEmbeddingsWhenUsingNativeEmbeddings(): public function testMissingCollectionIsCreatedUsingTheIndexableName(): void { - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); - $client->shouldReceive('getCollections')->twice()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); - $collections->shouldReceive('create') - ->once() + $client->expects('getCollections')->times(2)->returns($collections); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); + $collections->expects('create') ->with([ 'fields' => [['name' => 'title', 'type' => 'string']], 'name' => 'write_index', ]) - ->andReturn(['name' => 'write_index']); - $collection->shouldReceive('getDocuments')->twice()->andReturn($documents); - $documents->shouldReceive('import') - ->once() - ->ordered() - ->andThrow(new ObjectNotFound('Collection not found')); - $documents->shouldReceive('import') - ->once() - ->ordered() - ->andReturn([['success' => true, 'document' => '{"id":1}']]); + ->returns(['name' => 'write_index']); + $collection->expects('getDocuments')->times(2)->returns($documents); + $attempts = 0; + $documents->expects('import')->times(2)->resolves(function () use (&$attempts): array { + if (++$attempts === 1) { + throw new ObjectNotFound('Collection not found'); + } + + return [['success' => true, 'document' => '{"id":1}']]; + }); $model = new TypesenseLifecycleModel; @@ -457,15 +459,14 @@ public function testMissingCollectionIsCreatedUsingTheIndexableName(): void public function testMissingCollectionPreparesSettingsBeforeTheAuthoritativeName(): void { - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); - $client->shouldReceive('getCollections')->twice()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); - $collections->shouldReceive('create') - ->once() + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); + $client->expects('getCollections')->times(2)->returns($collections); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); + $collections->expects('create') ->with([ 'fields' => [ ['name' => 'title', 'type' => 'string'], @@ -473,12 +474,15 @@ public function testMissingCollectionPreparesSettingsBeforeTheAuthoritativeName( ], 'name' => 'write_index', ]); - $collection->shouldReceive('getDocuments')->twice()->andReturn($documents); - $documents->shouldReceive('import')->once()->ordered()->andThrow(new ObjectNotFound('Collection not found')); - $documents->shouldReceive('import') - ->once() - ->ordered() - ->andReturn([['success' => true, 'document' => '{"id":1}']]); + $collection->expects('getDocuments')->times(2)->returns($documents); + $attempts = 0; + $documents->expects('import')->times(2)->resolves(function () use (&$attempts): array { + if (++$attempts === 1) { + throw new ObjectNotFound('Collection not found'); + } + + return [['success' => true, 'document' => '{"id":1}']]; + }); $model = new TypesenseLifecycleModel; $engine = $this->createPartialEngineWithConfig($client); @@ -507,24 +511,24 @@ public function testMissingCollectionPreparesSettingsBeforeTheAuthoritativeName( public function testUpdateAcceptsOnlyCollectionAlreadyExistsCreateRace(): void { - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); - - $client->shouldReceive('getCollections')->twice()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); - $collections->shouldReceive('create')->once()->andThrow(new ObjectAlreadyExists('Collection exists')); - $collection->shouldReceive('getDocuments')->twice()->andReturn($documents); - $documents->shouldReceive('import') - ->once() - ->ordered() - ->andThrow(new ObjectNotFound('Collection not found')); - $documents->shouldReceive('import') - ->once() - ->ordered() - ->andReturn([['success' => true, 'document' => '{"id":1}']]); + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); + + $client->expects('getCollections')->times(2)->returns($collections); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); + $collections->expects('create')->throws(new ObjectAlreadyExists('Collection exists')); + $collection->expects('getDocuments')->times(2)->returns($documents); + $attempts = 0; + $documents->expects('import')->times(2)->resolves(function () use (&$attempts): array { + if (++$attempts === 1) { + throw new ObjectNotFound('Collection not found'); + } + + return [['success' => true, 'document' => '{"id":1}']]; + }); $model = new TypesenseLifecycleModel; @@ -533,18 +537,18 @@ public function testUpdateAcceptsOnlyCollectionAlreadyExistsCreateRace(): void public function testUpdatePropagatesOtherCollectionCreateFailures(): void { - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); $exception = new TypesenseClientError('Invalid schema'); - $client->shouldReceive('getCollections')->twice()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); - $collections->shouldReceive('create')->once()->andThrow($exception); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $documents->shouldReceive('import')->once()->andThrow(new ObjectNotFound('Collection not found')); + $client->expects('getCollections')->times(2)->returns($collections); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); + $collections->expects('create')->throws($exception); + $collection->expects('getDocuments')->returns($documents); + $documents->expects('import')->throws(new ObjectNotFound('Collection not found')); $model = new TypesenseLifecycleModel; @@ -555,18 +559,18 @@ public function testUpdatePropagatesOtherCollectionCreateFailures(): void public function testUpdatePropagatesNonMissingImportFailure(): void { - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); $exception = new TypesenseClientError('Authentication failed'); - $client->shouldReceive('getCollections')->once()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); - $collections->shouldNotReceive('create'); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $documents->shouldReceive('import')->once()->andThrow($exception); + $client->expects('getCollections')->returns($collections); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); + $collections->expects('create')->never(); + $collection->expects('getDocuments')->returns($documents); + $documents->expects('import')->throws($exception); $model = new TypesenseLifecycleModel; @@ -577,123 +581,119 @@ public function testUpdatePropagatesNonMissingImportFailure(): void public function testDeleteRemovesDocumentsFromIndex(): void { - $model = $this->createSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('write_index'); - $model->shouldReceive('getScoutKey')->andReturn(123); + $model = $this->createSearchableModelDouble(); + $model->allows('indexableAs')->returns('write_index'); + $model->allows('getScoutKey')->returns(123); - $document = m::mock(Document::class); - $document->shouldReceive('delete')->once()->andReturn([]); + $document = Double::for(Document::class)->strict(); + $document->expects('delete')->returns([]); - $documents = m::mock(Documents::class); - $documents->shouldReceive('offsetGet') + $documents = Double::for(Documents::class)->strict(); + $documents->allows('offsetGet') ->with('123') - ->andReturn($document); + ->returns($document); - $collection = m::mock(TypesenseCollection::class); - $collection->shouldReceive('getDocuments')->andReturn($documents); + $collection = Double::for(TypesenseCollection::class)->strict(); + $collection->allows('getDocuments')->returns($documents); - $collections = m::mock(Collections::class); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); + $collections = Double::for(Collections::class)->strict(); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); - $client = m::mock(TypesenseClient::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->returns($collections); $this->createEngine($client)->delete(new EloquentCollection([$model])); } public function testDeleteUsesStoredScoutKeyFromRemoveableCollection(): void { - $document = m::mock(Document::class); - $document->shouldReceive('delete')->once()->andReturn([]); + $document = Double::for(Document::class)->strict(); + $document->expects('delete')->returns([]); - $documents = m::mock(Documents::class); - $documents->shouldReceive('offsetGet')->with('stored-scout-key')->once()->andReturn($document); + $documents = Double::for(Documents::class)->strict(); + $documents->expects('offsetGet')->with('stored-scout-key')->returns($document); - $collection = m::mock(TypesenseCollection::class); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); + $collection = Double::for(TypesenseCollection::class)->strict(); + $collection->expects('getDocuments')->returns($documents); - $collections = m::mock(Collections::class); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); + $collections = Double::for(Collections::class)->strict(); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); - $client = m::mock(TypesenseClient::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->returns($collections); - $model = $this->createSearchableModelMock(); - $model->shouldReceive('getScoutKeyName')->andReturn('scout_id'); - $model->shouldReceive('getAttribute')->with('scout_id')->andReturn('stored-scout-key'); - $model->shouldReceive('indexableAs')->andReturn('write_index'); + $model = $this->createSearchableModelDouble(); + $model->allows('getScoutKeyName')->returns('scout_id'); + $model->allows('getAttribute')->with('scout_id')->returns('stored-scout-key'); + $model->allows('indexableAs')->returns('write_index'); $this->createEngine($client)->delete(new RemoveableScoutCollection([$model])); } public function testDeleteWithEmptyCollectionDoesNothing(): void { - $client = m::mock(TypesenseClient::class); - $client->shouldNotReceive('getCollections'); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->never(); $engine = $this->createEngine($client); $engine->delete(new EloquentCollection([])); - - $this->assertTrue(true); } public function testDeleteDocumentReturnsEmptyArrayWhenDocumentNotFound(): void { - $model = $this->createSearchableModelMock(); - $model->shouldReceive('getScoutKey')->andReturn(123); + $model = $this->createSearchableModelDouble(); + $model->allows('getScoutKey')->returns(123); - $document = m::mock(Document::class); - $document->shouldReceive('delete')->once()->andThrow(new ObjectNotFound('Document not found')); + $document = Double::for(Document::class)->strict(); + $document->expects('delete')->throws(new ObjectNotFound('Document not found')); - $documents = m::mock(Documents::class); - $documents->shouldReceive('offsetGet') + $documents = Double::for(Documents::class)->strict(); + $documents->allows('offsetGet') ->with('123') - ->andReturn($document); + ->returns($document); - $collection = m::mock(TypesenseCollection::class); - $collection->shouldReceive('getDocuments')->andReturn($documents); + $collection = Double::for(TypesenseCollection::class)->strict(); + $collection->allows('getDocuments')->returns($documents); - $model->shouldReceive('indexableAs')->andReturn('write_index'); + $model->allows('indexableAs')->returns('write_index'); - $collections = m::mock(Collections::class); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); + $collections = Double::for(Collections::class)->strict(); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); - $client = m::mock(TypesenseClient::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->returns($collections); $this->createEngine($client)->delete(new EloquentCollection([$model])); - - $this->assertTrue(true); } public function testDeleteDocumentThrowsOnNonNotFoundErrors(): void { - $model = $this->createSearchableModelMock(); - $model->shouldReceive('getScoutKey')->andReturn(123); + $model = $this->createSearchableModelDouble(); + $model->allows('getScoutKey')->returns(123); - $document = m::mock(Document::class); - $document->shouldReceive('delete')->once()->andThrow(new TypesenseClientError('Connection failed')); + $document = Double::for(Document::class)->strict(); + $document->expects('delete')->throws(new TypesenseClientError('Connection failed')); - $documents = m::mock(Documents::class); - $documents->shouldReceive('offsetGet') + $documents = Double::for(Documents::class)->strict(); + $documents->allows('offsetGet') ->with('123') - ->andReturn($document); + ->returns($document); - $collection = m::mock(TypesenseCollection::class); - $collection->shouldReceive('getDocuments')->andReturn($documents); + $collection = Double::for(TypesenseCollection::class)->strict(); + $collection->allows('getDocuments')->returns($documents); - $model->shouldReceive('indexableAs')->andReturn('write_index'); + $model->allows('indexableAs')->returns('write_index'); - $collections = m::mock(Collections::class); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); + $collections = Double::for(Collections::class)->strict(); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); - $client = m::mock(TypesenseClient::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->returns($collections); $this->expectException(TypesenseClientError::class); $this->expectExceptionMessageIs('Connection failed'); @@ -703,55 +703,54 @@ public function testDeleteDocumentThrowsOnNonNotFoundErrors(): void public function testFlushDeletesCollection(): void { - $model = $this->createSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('write_index'); + $model = $this->createSearchableModelDouble(); + $model->allows('indexableAs')->returns('write_index'); - $collection = m::mock(TypesenseCollection::class); - $collection->shouldReceive('delete')->once(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $collection->expects('delete'); - $collections = m::mock(Collections::class); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); + $collections = Double::for(Collections::class)->strict(); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); - $client = m::mock(TypesenseClient::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->returns($collections); $this->createEngine($client)->flush($model); } public function testFlushTreatsMissingCollectionAsAlreadyFlushed(): void { - $model = $this->createSearchableModelMock(); - $model->shouldReceive('indexableAs')->andReturn('write_index'); + $model = $this->createSearchableModelDouble(); + $model->allows('indexableAs')->returns('write_index'); - $collection = m::mock(TypesenseCollection::class); - $collection->shouldReceive('delete')->once()->andThrow(new ObjectNotFound('Collection not found')); + $collection = Double::for(TypesenseCollection::class)->strict(); + $collection->expects('delete')->throws(new ObjectNotFound('Collection not found')); - $collections = m::mock(Collections::class); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); - $collections->shouldNotReceive('create'); + $collections = Double::for(Collections::class)->strict(); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); + $collections->expects('create')->never(); - $client = m::mock(TypesenseClient::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->returns($collections); $this->createEngine($client)->flush($model); } public function testDeleteByFilterPreparesTheBuilderAndUsesTheDefaultWriteCollection(): void { - $documents = m::mock(Documents::class); - $documents->shouldReceive('delete') - ->once() + $documents = Double::for(Documents::class)->strict(); + $documents->expects('delete') ->with(['filter_by' => '(status:=active || status:=trial) && (tenant_id:=42)']) - ->andReturn(['num_deleted' => 2]); - $collection = m::mock(TypesenseCollection::class); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $collections = m::mock(Collections::class); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); - $client = m::mock(TypesenseClient::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); + ->returns(['num_deleted' => 2]); + $collection = Double::for(TypesenseCollection::class)->strict(); + $collection->expects('getDocuments')->returns($documents); + $collections = Double::for(Collections::class)->strict(); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->returns($collections); $model = new TypesenseLifecycleModel; $model->searchParameters = ['filter_by' => 'from_model:=true']; @@ -778,18 +777,17 @@ public function testDeleteByFilterPreparesTheBuilderAndUsesTheDefaultWriteCollec public function testDeleteByFilterUsesAnExplicitCollection(): void { - $documents = m::mock(Documents::class); - $documents->shouldReceive('delete') - ->once() + $documents = Double::for(Documents::class)->strict(); + $documents->expects('delete') ->with(['filter_by' => 'tenant_id:=42']) - ->andReturn(['num_deleted' => 1]); - $collection = m::mock(TypesenseCollection::class); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $collections = m::mock(Collections::class); - $collections->shouldReceive('offsetGet')->with('users_v2')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('users_v2')->once(); - $client = m::mock(TypesenseClient::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); + ->returns(['num_deleted' => 1]); + $collection = Double::for(TypesenseCollection::class)->strict(); + $collection->expects('getDocuments')->returns($documents); + $collections = Double::for(Collections::class)->strict(); + $collections->expects('offsetGet')->with('users_v2')->returns($collection); + $collections->expects('offsetUnset')->with('users_v2'); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->returns($collections); $model = new TypesenseLifecycleModel; $builder = (new Builder($model, ''))->within('users_v2')->where('tenant_id', 42); @@ -799,31 +797,28 @@ public function testDeleteByFilterUsesAnExplicitCollection(): void public function testDeleteByFilterTreatsAMissingCollectionAsAlreadyDeleted(): void { - $documents = m::mock(Documents::class); - $documents->shouldReceive('delete') - ->once() + $documents = Double::for(Documents::class)->strict(); + $documents->expects('delete') ->with(['filter_by' => 'tenant_id:=42']) - ->andThrow(new ObjectNotFound('Collection not found')); - $collection = m::mock(TypesenseCollection::class); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $collections = m::mock(Collections::class); - $collections->shouldReceive('offsetGet')->with('write_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('write_index')->once(); - $client = m::mock(TypesenseClient::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); + ->throws(new ObjectNotFound('Collection not found')); + $collection = Double::for(TypesenseCollection::class)->strict(); + $collection->expects('getDocuments')->returns($documents); + $collections = Double::for(Collections::class)->strict(); + $collections->expects('offsetGet')->with('write_index')->returns($collection); + $collections->expects('offsetUnset')->with('write_index'); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->returns($collections); $model = new TypesenseLifecycleModel; $builder = (new Builder($model, ''))->where('tenant_id', 42); $this->createPartialEngineWithConfig($client)->deleteByFilter($builder); - - $this->assertTrue(true); } public function testDeleteByFilterRejectsAnEmptyFilterBeforeIo(): void { - $client = m::mock(TypesenseClient::class); - $client->shouldNotReceive('getCollections'); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->never(); $model = new TypesenseLifecycleModel; $builder = new Builder($model, ''); $engine = $this->createPartialEngineWithConfig($client); @@ -844,17 +839,17 @@ public function testDeleteByFilterRejectsAnEmptyFilterBeforeIo(): void public function testDeleteByFilterDoesNotNotifyObserversForAnEmptyFilter(): void { - $client = m::mock(TypesenseClient::class); - $client->shouldNotReceive('getCollections'); - $observer = m::mock(EngineOperationObserver::class); - $observer->shouldNotReceive('starting'); - $observer->shouldNotReceive('finished'); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->never(); + $observer = Double::for(EngineOperationObserver::class)->strict(); + $observer->expects('starting')->never(); + $observer->expects('finished')->never(); $runner = new EngineOperationRunner; $runner->observe($observer); $engine = $this->createPartialEngineWithConfig($client) ->setOperationRunner($runner, 'typesense'); - $model = m::mock(TypesenseLifecycleModel::class)->makePartial(); - $model->shouldNotReceive('indexableAs'); + $model = Double::for(new TypesenseLifecycleModel)->passthru(); + $model->expects('indexableAs')->never(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('Typesense filter deletion requires a non-empty filter.'); @@ -864,17 +859,16 @@ public function testDeleteByFilterDoesNotNotifyObserversForAnEmptyFilter(): void public function testDeleteIndexCallsTypesenseDelete(): void { - $collection = m::mock(TypesenseCollection::class); - $collection->shouldReceive('delete') - ->once() - ->andReturn(['name' => 'test_index']); + $collection = Double::for(TypesenseCollection::class)->strict(); + $collection->expects('delete') + ->returns(['name' => 'test_index']); - $collections = m::mock(Collections::class); - $collections->shouldReceive('offsetGet')->with('test_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('test_index')->once(); + $collections = Double::for(Collections::class)->strict(); + $collections->expects('offsetGet')->with('test_index')->returns($collection); + $collections->expects('offsetUnset')->with('test_index'); - $client = m::mock(TypesenseClient::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->returns($collections); $engine = $this->createEngine($client); @@ -885,10 +879,10 @@ public function testDeleteIndexCallsTypesenseDelete(): void public function testCollectionHandlesAreDetachedAndMagicNamesRemainUsable(): void { - $collections = new Collections(m::mock(ApiCall::class)); + $collections = new Collections(Double::for(ApiCall::class)->strict()); - $client = m::mock(TypesenseClient::class); - $client->shouldReceive('getCollections')->twice()->andReturn($collections); + $client = Double::for(TypesenseClient::class)->strict(); + $client->expects('getCollections')->times(2)->returns($collections); $engine = $this->createEngine($client); @@ -904,7 +898,7 @@ public function testCollectionHandlesAreDetachedAndMagicNamesRemainUsable(): voi public function testGetTypesenseClientReturnsClient(): void { - $client = m::mock(TypesenseClient::class); + $client = Double::for(TypesenseClient::class)->strict(); $engine = $this->createEngine($client); $this->assertSame($client, $engine->getTypesenseClient()); @@ -912,20 +906,19 @@ public function testGetTypesenseClientReturnsClient(): void public function testSearchUsesExplicitWithinCollection(): void { - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); - - $client->shouldReceive('getCollections')->once()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('custom_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('custom_index')->once(); - $collections->shouldNotReceive('create'); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $documents->shouldReceive('search') - ->once() - ->with(m::on(fn (array $parameters): bool => $parameters['q'] === 'scout')) - ->andReturn(['found' => 0, 'hits' => []]); + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); + + $client->expects('getCollections')->returns($collections); + $collections->expects('offsetGet')->with('custom_index')->returns($collection); + $collections->expects('offsetUnset')->with('custom_index'); + $collections->expects('create')->never(); + $collection->expects('getDocuments')->returns($documents); + $documents->expects('search') + ->with(Argument::satisfies(fn (array $parameters): bool => $parameters['q'] === 'scout')) + ->returns(['found' => 0, 'hits' => []]); $model = new TypesenseLifecycleModel; $builder = (new Builder($model, 'scout'))->within('custom_index'); @@ -938,30 +931,29 @@ public function testSearchUsesExplicitWithinCollection(): void public function testSearchCreatesMissingSearchableCollectionAndRetriesOnce(): void { - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); - $client->shouldReceive('getCollections')->twice()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('read_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('read_index')->once(); - $collections->shouldReceive('create') - ->once() + $client->expects('getCollections')->times(2)->returns($collections); + $collections->expects('offsetGet')->with('read_index')->returns($collection); + $collections->expects('offsetUnset')->with('read_index'); + $collections->expects('create') ->with([ 'fields' => [['name' => 'title', 'type' => 'string']], 'name' => 'read_index', ]) - ->andReturn(['name' => 'read_index']); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $documents->shouldReceive('search') - ->once() - ->ordered() - ->andThrow(new ObjectNotFound('Collection not found')); - $documents->shouldReceive('search') - ->once() - ->ordered() - ->andReturn(['found' => 0, 'hits' => []]); + ->returns(['name' => 'read_index']); + $collection->expects('getDocuments')->returns($documents); + $attempts = 0; + $documents->expects('search')->times(2)->resolves(function () use (&$attempts): array { + if (++$attempts === 1) { + throw new ObjectNotFound('Collection not found'); + } + + return ['found' => 0, 'hits' => []]; + }); $model = new TypesenseLifecycleModel; $builder = new Builder($model, 'scout'); @@ -971,18 +963,18 @@ public function testSearchCreatesMissingSearchableCollectionAndRetriesOnce(): vo public function testSearchPropagatesNonMissingFailure(): void { - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); $exception = new TypesenseClientError('Authentication failed'); - $client->shouldReceive('getCollections')->once()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('read_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('read_index')->once(); - $collections->shouldNotReceive('create'); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $documents->shouldReceive('search')->once()->andThrow($exception); + $client->expects('getCollections')->returns($collections); + $collections->expects('offsetGet')->with('read_index')->returns($collection); + $collections->expects('offsetUnset')->with('read_index'); + $collections->expects('create')->never(); + $collection->expects('getDocuments')->returns($documents); + $documents->expects('search')->throws($exception); $model = new TypesenseLifecycleModel; $builder = new Builder($model, 'scout'); @@ -994,17 +986,16 @@ public function testSearchPropagatesNonMissingFailure(): void public function testSearchesWithVectorQueriesUseTheMultiSearchEndpoint(): void { - $multiSearch = m::mock(MultiSearch::class); + $multiSearch = Double::for(MultiSearch::class)->strict(); $engine = $this->createMultiSearchEngine($multiSearch); - $engine->shouldReceive('buildSearchParameters')->once()->andReturn([ + $engine->expects('buildSearchParameters')->returns([ 'q' => '*', 'query_by' => 'name', 'vector_query' => 'embedding:([0.1, 0.2])', ]); - $multiSearch->shouldReceive('perform') - ->once() + $multiSearch->expects('perform') ->with([ 'searches' => [ [ @@ -1015,7 +1006,7 @@ public function testSearchesWithVectorQueriesUseTheMultiSearchEndpoint(): void ], ], ]) - ->andReturn(['results' => [['found' => 1, 'hits' => [['document' => ['id' => '1']]]]]]); + ->returns(['results' => [['found' => 1, 'hits' => [['document' => ['id' => '1']]]]]]); $results = $engine->search(new Builder(new SearchableModelWithPrecomputedEmbedding, 'conceptual query')); @@ -1025,16 +1016,16 @@ public function testSearchesWithVectorQueriesUseTheMultiSearchEndpoint(): void public function testMultiSearchErrorsAreConvertedToTypesenseExceptions(): void { - $multiSearch = m::mock(MultiSearch::class); + $multiSearch = Double::for(MultiSearch::class)->strict(); $engine = $this->createMultiSearchEngine($multiSearch); - $engine->shouldReceive('buildSearchParameters')->andReturn([ + $engine->allows('buildSearchParameters')->returns([ 'q' => '*', 'query_by' => 'name', 'vector_query' => 'embedding:([0.1, 0.2])', ]); - $multiSearch->shouldReceive('perform')->andReturn([ + $multiSearch->allows('perform')->returns([ 'results' => [['code' => 400, 'error' => 'Query string exceeds max allowed length.']], ]); @@ -1046,23 +1037,22 @@ public function testMultiSearchErrorsAreConvertedToTypesenseExceptions(): void public function testMultiSearchCreatesMissingCollectionsAndRetries(): void { - $multiSearch = m::mock(MultiSearch::class); + $multiSearch = Double::for(MultiSearch::class)->strict(); $engine = $this->createMultiSearchEngine($multiSearch); $collections = $engine->getTypesenseClient()->getCollections(); - $collections->shouldReceive('create') - ->once() + $collections->expects('create') ->with(['name' => 'table']) - ->andReturn(['name' => 'table']); + ->returns(['name' => 'table']); - $engine->shouldReceive('buildSearchParameters')->andReturn([ + $engine->allows('buildSearchParameters')->returns([ 'q' => '*', 'query_by' => 'name', 'vector_query' => 'embedding:([0.1, 0.2])', ]); - $multiSearch->shouldReceive('perform') - ->twice() - ->andReturn( + $multiSearch->expects('perform') + ->times(2) + ->returns( ['results' => [['code' => 404, 'error' => 'Not found.']]], ['results' => [['found' => 0, 'hits' => []]]], ); @@ -1080,9 +1070,9 @@ public function testLargeTakeUsesFixedPageSizesAndTruthfulMetadata(): void ['hits' => range(1, 250), 'found' => 600, 'out_of' => 900], ['hits' => range(251, 350), 'found' => 600, 'out_of' => 900], ]; - $engine->shouldReceive('performSearch') - ->twice() - ->andReturnUsing(function (Builder $builder, array $options) use (&$parameters, &$responses): array { + $engine->expects('performSearch') + ->times(2) + ->resolves(function (Builder $builder, array $options) use (&$parameters, &$responses): array { $parameters[] = $options; return array_shift($responses); @@ -1114,9 +1104,9 @@ public function testLargeTakeStopsWhenTheKnownMatchCountIsExhausted(): void ['hits' => range(1, 250), 'found' => 500, 'out_of' => 800], ['hits' => range(251, 500), 'found' => 500, 'out_of' => 800], ]; - $engine->shouldReceive('performSearch') - ->twice() - ->andReturnUsing(function () use (&$responses): array { + $engine->expects('performSearch') + ->times(2) + ->resolves(function () use (&$responses): array { return array_shift($responses); }); @@ -1133,9 +1123,9 @@ public function testLargeTakeStopsWhenTypesenseReturnsAShortPage(): void ['hits' => range(1, 250), 'found' => 600, 'out_of' => 800], ['hits' => range(251, 275), 'found' => 600, 'out_of' => 800], ]; - $engine->shouldReceive('performSearch') - ->twice() - ->andReturnUsing(function () use (&$responses): array { + $engine->expects('performSearch') + ->times(2) + ->resolves(function () use (&$responses): array { return array_shift($responses); }); @@ -1152,9 +1142,9 @@ public function testLargeTakeHonorsTheConfiguredResultLimit(): void ['hits' => range(1, 250), 'found' => 600, 'out_of' => 800], ['hits' => range(251, 500), 'found' => 600, 'out_of' => 800], ]; - $engine->shouldReceive('performSearch') - ->twice() - ->andReturnUsing(function () use (&$responses): array { + $engine->expects('performSearch') + ->times(2) + ->resolves(function () use (&$responses): array { return array_shift($responses); }); @@ -1167,7 +1157,7 @@ public function testLargeTakeHonorsTheConfiguredResultLimit(): void public function testPaginateRejectsInvalidPageSizesBeforeIo(): void { $engine = $this->createPartialEngineWithConfig(); - $engine->shouldNotReceive('performSearch'); + $engine->expects('performSearch')->never(); $builder = new Builder(new TypesenseLifecycleModel, 'scout'); foreach ([0, -1, 251] as $perPage) { @@ -1186,15 +1176,14 @@ public function testPaginateRejectsInvalidPageSizesBeforeIo(): void public function testPaginatePreservesValidatedPageSizeAndLargePage(): void { $engine = $this->createPartialEngineWithConfig(maxTotalResults: 10); - $engine->shouldReceive('performSearch') - ->once() - ->withArgs(function (Builder $builder, array $options): bool { + $engine->expects('performSearch') + ->with(Argument::all(function (Builder $builder, array $options): bool { $this->assertSame(500_000_000, $options['page']); $this->assertSame(250, $options['per_page']); return true; - }) - ->andReturn(['hits' => [], 'found' => 0]); + })) + ->returns(['hits' => [], 'found' => 0]); $engine->paginate(new Builder(new TypesenseLifecycleModel, 'scout'), 250, 500_000_000); } @@ -1203,10 +1192,10 @@ public function testMapReturnsEmptyCollectionWhenNoResults(): void { $engine = $this->createEngine(); - $model = $this->createSearchableModelMock(); - $model->shouldReceive('newCollection')->andReturn(new EloquentCollection); + $model = $this->createSearchableModelDouble(); + $model->allows('newCollection')->returns(new EloquentCollection); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $results = ['found' => 0, 'hits' => []]; $mapped = $engine->map($builder, $results, $model); @@ -1218,10 +1207,10 @@ public function testLazyMapReturnsLazyCollectionWhenNoResults(): void { $engine = $this->createEngine(); - $model = $this->createSearchableModelMock(); - $model->shouldReceive('newCollection')->andReturn(new EloquentCollection); + $model = $this->createSearchableModelDouble(); + $model->allows('newCollection')->returns(new EloquentCollection); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $results = ['found' => 0, 'hits' => []]; $lazyMapped = $engine->lazyMap($builder, $results, $model); @@ -1233,9 +1222,9 @@ public function testBuildSearchParametersIncludesBasicParameters(): void { $engine = $this->createPartialEngineWithConfig(); - $model = $this->createSearchableModelMock(); + $model = $this->createSearchableModelDouble(); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $builder->model = $model; $builder->query = 'search term'; $builder->wheres = []; @@ -1259,9 +1248,9 @@ public function testBuildSearchParametersIncludesFilters(): void { $engine = $this->createPartialEngineWithConfig(); - $model = $this->createSearchableModelMock(); + $model = $this->createSearchableModelDouble(); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $builder->model = $model; $builder->query = 'test'; $builder->wheres = [ @@ -1295,15 +1284,15 @@ public function testBuildSearchParametersComposesTheWinningApplicationFilterWith public function testSearchCallbackReceivesFinalComposedOptions(): void { - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); - $client->shouldReceive('getCollections')->once()->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('read_index')->once()->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('read_index')->once(); - $collection->shouldReceive('getDocuments')->once()->andReturn($documents); - $documents->shouldNotReceive('search'); + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); + $client->expects('getCollections')->returns($collections); + $collections->expects('offsetGet')->with('read_index')->returns($collection); + $collections->expects('offsetUnset')->with('read_index'); + $collection->expects('getDocuments')->returns($documents); + $documents->expects('search')->never(); $model = new TypesenseLifecycleModel; $builder = new Builder($model, 'scout', function ($givenDocuments, $query, $options) use ($documents) { @@ -1322,9 +1311,9 @@ public function testBuildSearchParametersMergesBuilderOptions(): void { $engine = $this->createPartialEngineWithConfig(); - $model = $this->createSearchableModelMock(); + $model = $this->createSearchableModelDouble(); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $builder->model = $model; $builder->query = 'test'; $builder->wheres = []; @@ -1364,9 +1353,9 @@ public function testBuildSearchParametersIncludesSortBy(): void { $engine = $this->createPartialEngineWithConfig(); - $model = $this->createSearchableModelMock(); + $model = $this->createSearchableModelDouble(); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $builder->model = $model; $builder->query = 'test'; $builder->wheres = []; @@ -1387,9 +1376,9 @@ public function testBuildSearchParametersAppendsToExistingSortBy(): void { $engine = $this->createPartialEngineWithConfig(); - $model = $this->createSearchableModelMock(); + $model = $this->createSearchableModelDouble(); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $builder->model = $model; $builder->query = 'test'; $builder->wheres = []; @@ -1411,9 +1400,9 @@ public function testBuildSearchParametersWithDifferentPageAndPerPage(): void { $engine = $this->createPartialEngineWithConfig(); - $model = $this->createSearchableModelMock(); + $model = $this->createSearchableModelDouble(); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $builder->model = $model; $builder->query = 'query'; $builder->wheres = []; @@ -1432,9 +1421,9 @@ public function testBuildSearchParametersWithEmptyQuery(): void { $engine = $this->createPartialEngineWithConfig(); - $model = $this->createSearchableModelMock(); + $model = $this->createSearchableModelDouble(); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class)->strict(); $builder->model = $model; $builder->query = ''; $builder->wheres = []; @@ -1685,26 +1674,23 @@ public function testSemanticSearchRequiresEmbeddingSettings(): void } /** - * Create a partial engine mock that stubs getConfig to avoid container dependency. + * Create an initialized engine double with isolated configuration. * * @param array $config * @param array $engineConfig */ protected function createPartialEngineWithConfig( - ?MockInterface $client = null, + ?TypesenseClient $client = null, int $maxTotalResults = 1000, array $config = [], array $engineConfig = [], - ): MockInterface&TypesenseEngine { - $client = $client ?? m::mock(TypesenseClient::class); + ): TypesenseEngine&DoubleInterface { + $client = $client ?? Double::for(TypesenseClient::class)->strict(); - /** @var MockInterface&TypesenseEngine */ - $engine = m::mock(TypesenseEngine::class, [$client, $maxTotalResults, $engineConfig]) - ->shouldAllowMockingProtectedMethods() - ->makePartial(); + $engine = Double::for(new TypesenseEngine($client, $maxTotalResults, $engineConfig))->passthru(); - $engine->shouldReceive('getConfig') - ->andReturnUsing(fn (string $key, mixed $default = null): mixed => $config[$key] ?? $default); + $engine->allows('getConfig') + ->resolves(fn (string $key, mixed $default = null): mixed => $config[$key] ?? $default); return $engine; } @@ -1718,9 +1704,9 @@ protected function createPartialEngineWithConfig( protected function createSemanticEngine( array $embedding, string $queryBy = 'name', - ?MockInterface $client = null, + ?TypesenseClient $client = null, string $model = SearchableModelWithPrecomputedEmbedding::class, - ): MockInterface&TypesenseEngine { + ): TypesenseEngine&DoubleInterface { return $this->createPartialEngineWithConfig( $client, config: ["typesense.model-settings.{$model}.search-parameters" => ['query_by' => $queryBy]], @@ -1731,19 +1717,19 @@ protected function createSemanticEngine( /** * Create a partial engine whose client performs multi-searches against the "table" collection. */ - protected function createMultiSearchEngine(MultiSearch $multiSearch): MockInterface&TypesenseEngine - { - $client = m::mock(TypesenseClient::class); - $collections = m::mock(Collections::class); - $collection = m::mock(TypesenseCollection::class); - $documents = m::mock(Documents::class); - - $client->shouldReceive('getMultiSearch')->andReturn($multiSearch); - $client->shouldReceive('getCollections')->andReturn($collections); - $collections->shouldReceive('offsetGet')->with('table')->andReturn($collection); - $collections->shouldReceive('offsetUnset')->with('table'); - $collection->shouldReceive('getDocuments')->andReturn($documents); - $documents->shouldNotReceive('search'); + protected function createMultiSearchEngine(MultiSearch $multiSearch): TypesenseEngine&DoubleInterface + { + $client = Double::for(TypesenseClient::class)->strict(); + $collections = Double::for(Collections::class)->strict(); + $collection = Double::for(TypesenseCollection::class)->strict(); + $documents = Double::for(Documents::class)->strict(); + + $client->allows('getMultiSearch')->returns($multiSearch); + $client->allows('getCollections')->returns($collections); + $collections->allows('offsetGet')->with('table')->returns($collection); + $collections->allows('offsetUnset')->with('table'); + $collection->allows('getDocuments')->returns($documents); + $documents->expects('search')->never(); return $this->createPartialEngineWithConfig($client); } diff --git a/tests/Scout/Unit/Jobs/RemoveFromSearchTest.php b/tests/Scout/Unit/Jobs/RemoveFromSearchTest.php index c66952ee1c..9eba0e236b 100644 --- a/tests/Scout/Unit/Jobs/RemoveFromSearchTest.php +++ b/tests/Scout/Unit/Jobs/RemoveFromSearchTest.php @@ -17,13 +17,17 @@ use Hypervel\Tests\Scout\Fixtures\Models\CustomScoutKeyModel; use Hypervel\Tests\Scout\Fixtures\Models\SearchableModel; use Hypervel\Tests\Scout\ScoutTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; /** * Tests for RemoveFromSearch job. */ class RemoveFromSearchTest extends ScoutTestCase { + use VerifiesDoubles; + public function testHandleCallsEngineDelete(): void { $model1 = new SearchableModel(['title' => 'First', 'body' => 'Content']); @@ -34,24 +38,16 @@ public function testHandleCallsEngineDelete(): void $collection = new Collection([$model1, $model2]); - $engine = m::mock(Engine::class); - $engine->shouldReceive('runDelete') - ->once() - ->with(m::on(function ($models) { + $engine = Double::for(Engine::class)->strict(); + $engine->expects('runDelete') + ->with(Argument::satisfies(function ($models) { return $models instanceof RemoveableScoutCollection && $models->count() === 2; })); - $this->app->instance(EngineManager::class, new class($engine) { - public function __construct(private Engine $engine) - { - } - - public function engine(): Engine - { - return $this->engine; - } - }); + $manager = Double::for(EngineManager::class)->strict(); + $manager->allows('engine')->returns($engine); + $this->app->instance(EngineManager::class, $manager); $job = new RemoveFromSearch($collection); $job->handle(); @@ -61,25 +57,15 @@ public function testHandleDoesNothingForEmptyCollection(): void { $collection = new Collection([]); - $engine = m::mock(Engine::class); - $engine->shouldNotReceive('runDelete'); + $engine = Double::for(Engine::class)->strict(); + $engine->expects('runDelete')->never(); - $this->app->instance(EngineManager::class, new class($engine) { - public function __construct(private Engine $engine) - { - } - - public function engine(): Engine - { - return $this->engine; - } - }); + $manager = Double::for(EngineManager::class)->strict(); + $manager->allows('engine')->returns($engine); + $this->app->instance(EngineManager::class, $manager); $job = new RemoveFromSearch($collection); $job->handle(); - - // If we get here without exception, the test passes - $this->assertTrue(true); } public function testConstructorWrapsCollectionInRemoveableScoutCollection(): void diff --git a/tests/Scout/Unit/MakeSearchableUsingTest.php b/tests/Scout/Unit/MakeSearchableUsingTest.php index 223e447df5..9de3ad06e5 100644 --- a/tests/Scout/Unit/MakeSearchableUsingTest.php +++ b/tests/Scout/Unit/MakeSearchableUsingTest.php @@ -11,13 +11,17 @@ use Hypervel\Tests\Scout\Fixtures\Models\FilteringSearchableModel; use Hypervel\Tests\Scout\Fixtures\Models\SearchableModel; use Hypervel\Tests\Scout\ScoutTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; /** * Tests for makeSearchableUsing() behavior. */ class MakeSearchableUsingTest extends ScoutTestCase { + use VerifiesDoubles; + public function testSyncMakeSearchablePassesFilteredCollectionToEngine(): void { // Create models - one published, one draft @@ -30,10 +34,9 @@ public function testSyncMakeSearchablePassesFilteredCollectionToEngine(): void $collection = new Collection([$published, $draft]); // Mock the engine to verify what gets passed to update() - $engine = m::mock(Engine::class); - $engine->shouldReceive('runUpdate') - ->once() - ->with(m::on(function ($models) { + $engine = Double::for(Engine::class)->strict(); + $engine->expects('runUpdate') + ->with(Argument::satisfies(function ($models) { // Should only contain the published model, not the draft return $models->count() === 1 && $models->first()->id === 1 @@ -41,16 +44,9 @@ public function testSyncMakeSearchablePassesFilteredCollectionToEngine(): void })); // Replace the engine - $this->app->instance(EngineManager::class, new class($engine) { - public function __construct(private Engine $engine) - { - } - - public function engine(): Engine - { - return $this->engine; - } - }); + $manager = Double::for(EngineManager::class)->strict(); + $manager->allows('engine')->returns($engine); + $this->app->instance(EngineManager::class, $manager); $published->syncMakeSearchable($collection); } @@ -67,25 +63,15 @@ public function testSyncMakeSearchableHandlesEmptyFilteredCollection(): void $collection = new Collection([$draft1, $draft2]); // Mock the engine - update should NOT be called - $engine = m::mock(Engine::class); - $engine->shouldNotReceive('runUpdate'); + $engine = Double::for(Engine::class)->strict(); + $engine->expects('runUpdate')->never(); - $this->app->instance(EngineManager::class, new class($engine) { - public function __construct(private Engine $engine) - { - } - - public function engine(): Engine - { - return $this->engine; - } - }); + $manager = Double::for(EngineManager::class)->strict(); + $manager->allows('engine')->returns($engine); + $this->app->instance(EngineManager::class, $manager); // This should not throw, even though all models are filtered out $draft1->syncMakeSearchable($collection); - - // If we get here without exception, the test passes - $this->assertTrue(true); } public function testMakeSearchableJobPassesFilteredCollectionToEngine(): void @@ -100,26 +86,18 @@ public function testMakeSearchableJobPassesFilteredCollectionToEngine(): void $collection = new Collection([$published, $draft]); // Mock the engine to verify what gets passed to update() - $engine = m::mock(Engine::class); - $engine->shouldReceive('runUpdate') - ->once() - ->with(m::on(function ($models) { + $engine = Double::for(Engine::class)->strict(); + $engine->expects('runUpdate') + ->with(Argument::satisfies(function ($models) { // Should only contain the published model, not the draft return $models->count() === 1 && $models->first()->id === 1 && $models->first()->title === 'Published Post'; })); - $this->app->instance(EngineManager::class, new class($engine) { - public function __construct(private Engine $engine) - { - } - - public function engine(): Engine - { - return $this->engine; - } - }); + $manager = Double::for(EngineManager::class)->strict(); + $manager->allows('engine')->returns($engine); + $this->app->instance(EngineManager::class, $manager); $job = new MakeSearchable($collection); $job->handle(); @@ -137,27 +115,17 @@ public function testMakeSearchableJobHandlesEmptyFilteredCollection(): void $collection = new Collection([$draft1, $draft2]); // Mock the engine - update should NOT be called - $engine = m::mock(Engine::class); - $engine->shouldNotReceive('runUpdate'); - - $this->app->instance(EngineManager::class, new class($engine) { - public function __construct(private Engine $engine) - { - } + $engine = Double::for(Engine::class)->strict(); + $engine->expects('runUpdate')->never(); - public function engine(): Engine - { - return $this->engine; - } - }); + $manager = Double::for(EngineManager::class)->strict(); + $manager->allows('engine')->returns($engine); + $this->app->instance(EngineManager::class, $manager); $job = new MakeSearchable($collection); // This should not throw, even though all models are filtered out $job->handle(); - - // If we get here without exception, the test passes - $this->assertTrue(true); } public function testMakeSearchableUsingDefaultBehaviorPassesThroughUnchanged(): void @@ -172,23 +140,15 @@ public function testMakeSearchableUsingDefaultBehaviorPassesThroughUnchanged(): $collection = new Collection([$model1, $model2]); // Mock the engine to verify all models are passed - $engine = m::mock(Engine::class); - $engine->shouldReceive('runUpdate') - ->once() - ->with(m::on(function ($models) { + $engine = Double::for(Engine::class)->strict(); + $engine->expects('runUpdate') + ->with(Argument::satisfies(function ($models) { return $models->count() === 2; })); - $this->app->instance(EngineManager::class, new class($engine) { - public function __construct(private Engine $engine) - { - } - - public function engine(): Engine - { - return $this->engine; - } - }); + $manager = Double::for(EngineManager::class)->strict(); + $manager->allows('engine')->returns($engine); + $this->app->instance(EngineManager::class, $manager); $model1->syncMakeSearchable($collection); } diff --git a/tests/Scout/Unit/ModelObserverTest.php b/tests/Scout/Unit/ModelObserverTest.php index c591859cae..20e05cb7b7 100644 --- a/tests/Scout/Unit/ModelObserverTest.php +++ b/tests/Scout/Unit/ModelObserverTest.php @@ -6,20 +6,23 @@ use Hypervel\Database\Eloquent\Model; use Hypervel\Database\Eloquent\SoftDeletes; -use Hypervel\Scout\Contracts\SearchableInterface; use Hypervel\Scout\ModelObserver; +use Hypervel\Scout\Searchable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionClass; class ModelObserverTest extends TestCase { + use VerifiesDoubles; + public function testForceDeletingSoftDeleteModelIsRemovedOnce(): void { - $model = m::mock(ModelObserverSoftDeleteModel::class . ', ' . SearchableInterface::class); - $model->shouldReceive('wasSearchableBeforeDelete')->once()->andReturnTrue(); - $model->shouldReceive('isForceDeleting')->once()->andReturnTrue(); - $model->shouldReceive('unsearchable')->once(); + $model = Double::for(ModelObserverSoftDeleteModel::class)->strict(); + $model->expects('wasSearchableBeforeDelete')->returns(true); + $model->expects('isForceDeleting')->returns(true); + $model->expects('unsearchable'); $observer = (new ReflectionClass(ModelObserver::class))->newInstanceWithoutConstructor(); @@ -30,5 +33,6 @@ public function testForceDeletingSoftDeleteModelIsRemovedOnce(): void class ModelObserverSoftDeleteModel extends Model { + use Searchable; use SoftDeletes; } diff --git a/tests/Scout/Unit/ScoutTest.php b/tests/Scout/Unit/ScoutTest.php index b3a4fd567a..a908df18cf 100644 --- a/tests/Scout/Unit/ScoutTest.php +++ b/tests/Scout/Unit/ScoutTest.php @@ -12,7 +12,8 @@ use Hypervel\Scout\Jobs\RemoveFromSearch; use Hypervel\Scout\Scout; use Hypervel\Tests\Scout\ScoutTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; /** @@ -20,6 +21,8 @@ */ class ScoutTest extends ScoutTestCase { + use VerifiesDoubles; + public function testDefaultMakeSearchableJobClass(): void { $this->assertSame(MakeSearchable::class, Scout::$makeSearchableJob); @@ -46,9 +49,9 @@ public function testRemoveFromSearchUsingChangesJobClass(): void public function testLifecycleCallbacksPreserveValuesWhenUnset(): void { - $builder = m::mock(Builder::class); - $engine = m::mock(Engine::class); - $model = m::mock(Model::class); + $builder = Double::for(Builder::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $model = Double::for(Model::class)->strict(); Scout::prepareBuilder($builder, $engine); @@ -69,9 +72,9 @@ public function testLifecycleCallbacksPreserveValuesWhenUnset(): void public function testLifecycleCallbacksReceiveTheirCompleteBoundaries(): void { - $builder = m::mock(Builder::class); - $engine = m::mock(Engine::class); - $model = m::mock(Model::class); + $builder = Double::for(Builder::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $model = Double::for(Model::class)->strict(); $preparedBuilder = false; $guardedFlush = false; @@ -130,8 +133,8 @@ public function testLifecycleCallbacksReceiveTheirCompleteBoundaries(): void public function testRegisteringLifecycleCallbackAgainReplacesPreviousCallback(): void { - $builder = m::mock(Builder::class); - $engine = m::mock(Engine::class); + $builder = Double::for(Builder::class)->strict(); + $engine = Double::for(Engine::class)->strict(); $calls = []; Scout::prepareBuilderUsing(function () use (&$calls): void { @@ -160,9 +163,9 @@ public function testFlushStateRestoresDefaults(): void $this->assertSame(MakeSearchable::class, Scout::$makeSearchableJob); $this->assertSame(RemoveFromSearch::class, Scout::$removeFromSearchJob); - $builder = m::mock(Builder::class); - $engine = m::mock(Engine::class); - $model = m::mock(Model::class); + $builder = Double::for(Builder::class)->strict(); + $engine = Double::for(Engine::class)->strict(); + $model = Double::for(Model::class)->strict(); Scout::prepareBuilder($builder, $engine); $this->assertSame([], Scout::prepareSearchableDocument([], $model, $engine)); @@ -172,13 +175,12 @@ public function testFlushStateRestoresDefaults(): void public function testEngineMethodReturnsEngineFromManager(): void { - $engine = m::mock(Engine::class); + $engine = Double::for(Engine::class)->strict(); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine') + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine') ->with('meilisearch') - ->once() - ->andReturn($engine); + ->returns($engine); $this->app->instance(EngineManager::class, $manager); @@ -189,13 +191,12 @@ public function testEngineMethodReturnsEngineFromManager(): void public function testEngineMethodWithNullUsesDefaultEngine(): void { - $engine = m::mock(Engine::class); + $engine = Double::for(Engine::class)->strict(); - $manager = m::mock(EngineManager::class); - $manager->shouldReceive('engine') + $manager = Double::for(EngineManager::class)->strict(); + $manager->expects('engine') ->with(null) - ->once() - ->andReturn($engine); + ->returns($engine); $this->app->instance(EngineManager::class, $manager); diff --git a/tests/Scout/Unit/SearchableDispatchTest.php b/tests/Scout/Unit/SearchableDispatchTest.php index 1915a7a049..96d83f54f3 100644 --- a/tests/Scout/Unit/SearchableDispatchTest.php +++ b/tests/Scout/Unit/SearchableDispatchTest.php @@ -11,11 +11,14 @@ use Hypervel\Http\Request; use Hypervel\Scout\Searchable; use Hypervel\Tests\Scout\ScoutTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class SearchableDispatchTest extends ScoutTestCase { + use VerifiesDoubles; + protected bool $migrateRefresh = false; public function testDispatchRunsImmediatelyOutsideARequest(): void @@ -126,8 +129,8 @@ public function testDeferredOwnerDrainsJobsEnqueuedWhileItIsRunning(): void public function testAReportedFailureDoesNotStopLaterJobs(): void { $exception = new RuntimeException('indexing failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($exception, []); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($exception, []); $this->app->instance(ExceptionHandler::class, $handler); $events = []; diff --git a/tests/Sentry/CoroutineSafetyTest.php b/tests/Sentry/CoroutineSafetyTest.php index ab8d453251..c80a124af4 100644 --- a/tests/Sentry/CoroutineSafetyTest.php +++ b/tests/Sentry/CoroutineSafetyTest.php @@ -23,7 +23,8 @@ use Hypervel\Sentry\Tracing\EventHandler as TracingEventHandler; use Hypervel\Tests\Ai\Fixtures\Agents\RememberingAssistantAgent; use Hypervel\Tests\Ai\Fixtures\FakeConversationStore; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Sentry\SentrySdk; use Sentry\Tracing\SpanStatus; use Sentry\Tracing\TransactionContext; @@ -33,6 +34,8 @@ class CoroutineSafetyTest extends TestCase { + use VerifiesDoubles; + protected array $defaultSetupConfig = ['sentry.traces_sample_rate' => 1.0]; /** @@ -80,8 +83,8 @@ public function testTracingEventHandlerSpanStacksAreIsolatedPerCoroutine(): void $transaction->setSampled(true); $hub->setSpan($transaction); - $connection = m::mock(Connection::class); - $connection->shouldReceive('getName')->once()->andReturn('parent'); + $connection = Double::for(Connection::class)->strict(); + $connection->expects('getName')->returns('parent'); $handler->transactionBeginning(new TransactionBeginning($connection)); // Verify parent has a span on its stack diff --git a/tests/Sentry/EventHandler/DatabaseEventsTest.php b/tests/Sentry/EventHandler/DatabaseEventsTest.php index fa9ba246c1..d41f1c79e9 100644 --- a/tests/Sentry/EventHandler/DatabaseEventsTest.php +++ b/tests/Sentry/EventHandler/DatabaseEventsTest.php @@ -10,12 +10,15 @@ use Hypervel\Database\Events\TransactionCommitted; use Hypervel\Database\Events\TransactionRolledBack; use Hypervel\Tests\Sentry\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Sentry\Breadcrumb; class DatabaseEventsTest extends TestCase { + use VerifiesDoubles; + public function testSqlQueriesAreRecordedWhenEnabled(): void { $this->resetApplicationWithConfig([ @@ -189,8 +192,8 @@ public function testSqlTransactionsAreNotRecordedWhenDisabled(): void */ private function getMockedConnection(): Connection { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getName')->andReturn('test'); + $connection = Double::for(Connection::class)->strict(); + $connection->allows('getName')->returns('test'); return $connection; } diff --git a/tests/Sentry/EventHandlerTest.php b/tests/Sentry/EventHandlerTest.php index 528e75e61d..d7bb38fc19 100644 --- a/tests/Sentry/EventHandlerTest.php +++ b/tests/Sentry/EventHandlerTest.php @@ -10,7 +10,9 @@ use Hypervel\Core\Events\OnWorkerExit; use Hypervel\Sentry\EventHandler; use Hypervel\Sentry\Transport\HttpPoolTransport; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionClass; use RuntimeException; use Sentry\Client; @@ -24,6 +26,8 @@ class EventHandlerTest extends TestCase { + use VerifiesDoubles; + public function testMissingEventHandlerThrowsException(): void { $handler = new EventHandler($this->app, config()->array('sentry')); @@ -54,23 +58,21 @@ public function testAllMappedAuthEventHandlersExist(): void public function testWorkerExitListenerReturnsBeforeCoordinatorReleaseThenDrainsAndCloses(): void { $closed = new Channel(1); - $transport = m::mock(HttpPoolTransport::class); - $transport->shouldReceive('shutdown')->once()->andReturnUsing(function () use ($closed): void { + $transport = Double::for(HttpPoolTransport::class)->strict(); + $transport->expects('shutdown')->resolves(function () use ($closed): void { $closed->push(true); }); - $client = m::mock(Client::class); - $client->shouldReceive('getOptions')->once()->andReturn(new Options(['http_timeout' => 0.1])); - $client->shouldReceive('flush') - ->once() - ->withNoArgs() + $client = Double::for(Client::class)->strict(); + $client->expects('getOptions')->returns(new Options(['http_timeout' => 0.1])); + $client->expects('flush') + ->with(Argument::none()) ->ordered() - ->andReturn(new Result(ResultStatus::success())); - $client->shouldReceive('flush') - ->once() + ->returns(new Result(ResultStatus::success())); + $client->expects('flush') ->with(1) ->ordered() - ->andReturn(new Result(ResultStatus::success())); - $client->shouldReceive('getTransport')->once()->andReturn($transport); + ->returns(new Result(ResultStatus::success())); + $client->expects('getTransport')->returns($transport); $previousHub = SentrySdk::getCurrentHub(); SentrySdk::setCurrentHub(new Hub($client)); CoordinatorManager::initialize(Constants::WORKER_EXIT); @@ -80,7 +82,7 @@ public function testWorkerExitListenerReturnsBeforeCoordinatorReleaseThenDrainsA }); try { - $this->dispatchHypervelEvent(new OnWorkerExit(m::mock(Server::class), 1)); + $this->dispatchHypervelEvent(new OnWorkerExit(Double::for(Server::class)->strict(), 1)); $this->assertTrue($laterListenerRan); $this->assertTrue($closed->isEmpty()); @@ -98,35 +100,32 @@ public function testWorkerExitClosesTheTransportPoolWhenFlushFails(): void { $closed = new Channel(1); $flushException = new RuntimeException('Unable to flush.'); - $transport = m::mock(HttpPoolTransport::class); - $transport->shouldReceive('shutdown')->once()->andReturnUsing(function () use ($closed): void { + $transport = Double::for(HttpPoolTransport::class)->strict(); + $transport->expects('shutdown')->resolves(function () use ($closed): void { $closed->push(true); }); - $client = m::mock(Client::class); - $client->shouldReceive('getOptions')->once()->andReturn(new Options(['http_timeout' => 0.1])); - $client->shouldReceive('flush') - ->once() - ->withNoArgs() + $client = Double::for(Client::class)->strict(); + $client->expects('getOptions')->returns(new Options(['http_timeout' => 0.1])); + $client->expects('flush') + ->with(Argument::none()) ->ordered() - ->andReturn(new Result(ResultStatus::success())); - $client->shouldReceive('flush') - ->once() + ->returns(new Result(ResultStatus::success())); + $client->expects('flush') ->with(1) ->ordered() - ->andThrow($flushException); - $client->shouldReceive('getTransport') - ->once() - ->andReturn($transport); + ->throws($flushException); + $client->expects('getTransport') + ->returns($transport); $previousHub = SentrySdk::getCurrentHub(); SentrySdk::setCurrentHub(new Hub($client)); CoordinatorManager::initialize(Constants::WORKER_EXIT); - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $exceptionHandler->shouldReceive('report')->once()->with($flushException); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $exceptionHandler->expects('report')->with($flushException); $this->app->instance(ExceptionHandlerContract::class, $exceptionHandler); try { $handler = new EventHandler($this->app, config()->array('sentry')); - $handler->workerExit(new OnWorkerExit(m::mock(Server::class), 1)); + $handler->workerExit(new OnWorkerExit(Double::for(Server::class)->strict(), 1)); CoordinatorManager::until(Constants::WORKER_EXIT)->resume(); diff --git a/tests/Sentry/Features/AiFailedInvocationTest.php b/tests/Sentry/Features/AiFailedInvocationTest.php index c7ca5b0eee..723a5acb15 100644 --- a/tests/Sentry/Features/AiFailedInvocationTest.php +++ b/tests/Sentry/Features/AiFailedInvocationTest.php @@ -23,7 +23,8 @@ use Hypervel\Support\Facades\Http; use Hypervel\Tests\Ai\Fixtures\FakeConversationStore; use Hypervel\Tests\Sentry\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Sentry\SentrySdk; @@ -38,6 +39,8 @@ class AiFailedInvocationTest extends TestCase { + use VerifiesDoubles; + protected array $defaultSetupConfig = [ 'sentry.traces_sample_rate' => 1.0, 'sentry.tracing.http_client_requests' => false, @@ -261,8 +264,8 @@ public function testPersistenceFailureClosesTheInvocationAfterItsModelStep(): vo config(['ai.conversations.generate_title' => false]); SentryInnerRememberingAgent::fake(['Hello']); $failure = new RuntimeException('Storage failed.'); - $store = m::mock(FakeConversationStore::class)->makePartial(); - $store->shouldReceive('storeConversation')->once()->andThrow($failure); + $store = Double::for(new FakeConversationStore)->passthru(); + $store->expects('storeConversation')->throws($failure); $this->app->instance(ConversationStore::class, $store); $transaction = $this->startTransaction(); diff --git a/tests/Sentry/Features/AiIntegrationTest.php b/tests/Sentry/Features/AiIntegrationTest.php index 196da889b1..4708d6c372 100644 --- a/tests/Sentry/Features/AiIntegrationTest.php +++ b/tests/Sentry/Features/AiIntegrationTest.php @@ -152,8 +152,9 @@ public function handle(Request $request): string use Hypervel\Tests\Sentry\Features\AiStubs\TestAgentWithConfig; use Hypervel\Tests\Sentry\Features\AiStubs\WeatherLookup; use Hypervel\Tests\Sentry\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonSerializable; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -167,6 +168,8 @@ public function handle(Request $request): string class AiIntegrationTest extends TestCase { + use VerifiesDoubles; + private const string PROVIDER_URL = 'https://api.openai.com/v1'; protected array $defaultSetupConfig = [ @@ -677,8 +680,8 @@ public function testToolSchemaCancellationEscapesTracing(bool $canceled): void $this->startTransaction(); [$prompt] = $this->makePromptAndResponse(); $failure = new RuntimeException('Schema failed.', previous: $canceled ? new CanceledException : null); - $tool = m::mock(WeatherLookup::class)->makePartial(); - $tool->shouldReceive('schema')->once()->andThrow($failure); + $tool = Double::for(new WeatherLookup)->passthru(); + $tool->expects('schema')->throws($failure); $this->dispatchHypervelEvent(new PromptingAgent('schema', $prompt)); $caught = null; @@ -864,7 +867,7 @@ public function testAChangedResponseConversationDoesNotRenameTheCapturedAssociat private function makeProvider(): OpenAiProvider { return new OpenAiProvider( - m::mock(Gateway::class), + Double::for(Gateway::class)->strict(), ['name' => 'openai', 'driver' => 'openai', 'key' => 'test-key'], $this->app->make('events') ); diff --git a/tests/Sentry/Features/CacheIntegrationTest.php b/tests/Sentry/Features/CacheIntegrationTest.php index a629c3c0bc..86ae25a78e 100644 --- a/tests/Sentry/Features/CacheIntegrationTest.php +++ b/tests/Sentry/Features/CacheIntegrationTest.php @@ -30,7 +30,8 @@ use Hypervel\Session\Store as SessionStore; use Hypervel\Support\Facades\Cache; use Hypervel\Tests\Sentry\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Override; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -44,6 +45,8 @@ class CacheIntegrationTest extends TestCase { + use VerifiesDoubles; + protected array $defaultSetupConfig = [ 'sentry.traces_sample_rate' => 1.0, 'sentry.features' => [ @@ -286,8 +289,8 @@ public function testCacheRemoveSpanIsRecorded(): void public function testCacheGetFailureFinishesItsSpanAndRethrows(): void { $exception = new RuntimeException('The cache read failed.'); - $store = m::mock(Store::class); - $store->shouldReceive('get')->once()->with('foo')->andThrow($exception); + $store = Double::for(Store::class)->strict(); + $store->expects('get')->with('foo')->throws($exception); $span = $this->executeFailureAndReturnMostRecentSpan( fn (): mixed => $this->repository($store)->get('foo'), @@ -300,8 +303,8 @@ public function testCacheGetFailureFinishesItsSpanAndRethrows(): void public function testCacheManyFailureFinishesItsSpanAndRethrows(): void { $exception = new RuntimeException('The cache batch read failed.'); - $store = m::mock(Store::class); - $store->shouldReceive('many')->once()->with(['foo', 'bar'])->andThrow($exception); + $store = Double::for(Store::class)->strict(); + $store->expects('many')->with(['foo', 'bar'])->throws($exception); $span = $this->executeFailureAndReturnMostRecentSpan( fn (): array => $this->repository($store)->many(['foo', 'bar']), @@ -314,8 +317,8 @@ public function testCacheManyFailureFinishesItsSpanAndRethrows(): void public function testCachePutFailureFinishesItsSpanAndRethrows(): void { $exception = new RuntimeException('The cache write failed.'); - $store = m::mock(Store::class); - $store->shouldReceive('put')->once()->with('foo', 'bar', 60)->andThrow($exception); + $store = Double::for(Store::class)->strict(); + $store->expects('put')->with('foo', 'bar', 60)->throws($exception); $span = $this->executeFailureAndReturnMostRecentSpan( fn (): bool => $this->repository($store)->put('foo', 'bar', 60), @@ -329,8 +332,8 @@ public function testCachePutFailureFinishesItsSpanAndRethrows(): void public function testCachePutManyFailureFinishesItsSpanAndRethrows(): void { $exception = new RuntimeException('The cache batch write failed.'); - $store = m::mock(Store::class); - $store->shouldReceive('putMany')->once()->with(['foo' => 'bar', 'baz' => 'qux'], 60)->andThrow($exception); + $store = Double::for(Store::class)->strict(); + $store->expects('putMany')->with(['foo' => 'bar', 'baz' => 'qux'], 60)->throws($exception); $span = $this->executeFailureAndReturnMostRecentSpan( fn (): bool => $this->repository($store)->putMany(['foo' => 'bar', 'baz' => 'qux'], 60), @@ -344,8 +347,8 @@ public function testCachePutManyFailureFinishesItsSpanAndRethrows(): void public function testCacheForgetFailureFinishesItsSpanAndRethrows(): void { $exception = new RuntimeException('The cache forget failed.'); - $store = m::mock(Store::class); - $store->shouldReceive('forget')->once()->with('foo')->andThrow($exception); + $store = Double::for(Store::class)->strict(); + $store->expects('forget')->with('foo')->throws($exception); $span = $this->executeFailureAndReturnMostRecentSpan( fn (): bool => $this->repository($store)->forget('foo'), @@ -357,8 +360,8 @@ public function testCacheForgetFailureFinishesItsSpanAndRethrows(): void public function testCacheForgetFalseResultFinishesItsSpanWithoutErrorStatus(): void { - $store = m::mock(Store::class); - $store->shouldReceive('forget')->once()->with('foo')->andReturnFalse(); + $store = Double::for(Store::class)->strict(); + $store->expects('forget')->with('foo')->returns(false); $span = $this->executeAndReturnMostRecentSpan( fn (): bool => $this->repository($store)->forget('foo'), @@ -655,8 +658,8 @@ public function testRedisSessionKeyFallbackIsReentrySafe(): void { $this->registerObservedRedisPool(); $connection = $this->createRedisConnection('default'); - $session = m::mock(Session::class); - $session->shouldReceive('getId')->once()->andReturn('outer-key'); + $session = Double::for(Session::class)->strict(); + $session->expects('getId')->returns('outer-key'); $this->app->bind('session.store', function () use ($connection, $session): Session { $this->dispatchHypervelEvent(new CommandExecuted('GET', ['inner-key'], 0.005, $connection)); @@ -939,16 +942,16 @@ private function repository(Store $store): Repository */ private function registerObservedRedisPool(string $connectionName = 'default', int $database = 0, ?float $maxIdleTime = 60.0): void { - $pool = m::mock(RedisPool::class); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray(['max_idle_time' => $maxIdleTime])); - $pool->shouldReceive('getManagedCount')->andReturn(7); - $pool->shouldReceive('getBorrowedCount')->andReturn(2); - $pool->shouldReceive('getIdleCount')->andReturn(5); - $pool->shouldReceive('getWaitingCount')->andReturn(1); + $pool = Double::for(RedisPool::class)->strict(); + $pool->allows('getOptions')->returns(PoolOptions::fromArray(['max_idle_time' => $maxIdleTime])); + $pool->allows('getManagedCount')->returns(7); + $pool->allows('getBorrowedCount')->returns(2); + $pool->allows('getIdleCount')->returns(5); + $pool->allows('getWaitingCount')->returns(1); - $poolManager = m::mock(PoolManager::class); - $poolManager->shouldReceive('getPools')->andReturn([$connectionName => $pool]); - $poolManager->shouldNotReceive('pool'); + $poolManager = Double::for(new PoolManager($this->app))->passthru(); + $poolManager->allows('getPools')->returns([$connectionName => $pool]); + $poolManager->expects('pool')->never(); $this->app->instance(PoolManager::class, $poolManager); @@ -960,8 +963,8 @@ private function registerObservedRedisPool(string $connectionName = 'default', i */ private function createRedisConnection(string $name): RedisConnection { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getName')->andReturn($name); + $connection = Double::for(PhpRedisConnection::class)->strict(); + $connection->allows('getName')->returns($name); return $connection; } diff --git a/tests/Sentry/Features/NotificationsIntegrationTest.php b/tests/Sentry/Features/NotificationsIntegrationTest.php index 3d42c5ff11..23544fc200 100644 --- a/tests/Sentry/Features/NotificationsIntegrationTest.php +++ b/tests/Sentry/Features/NotificationsIntegrationTest.php @@ -6,7 +6,6 @@ use Closure; use Hypervel\Contracts\Foundation\Application as ApplicationContract; -use Hypervel\Contracts\View\Factory as ViewFactory; use Hypervel\Notifications\Events\NotificationFailed; use Hypervel\Notifications\Events\NotificationSending; use Hypervel\Notifications\Events\NotificationSent; @@ -17,7 +16,6 @@ use Hypervel\Support\Facades\Mail; use Hypervel\Support\Facades\Notification; use Hypervel\Tests\Sentry\TestCase; -use Mockery as m; use RuntimeException; use Sentry\SentrySdk; use Sentry\Tracing\Span; @@ -41,7 +39,6 @@ protected function defineEnvironment(ApplicationContract $app): void { parent::defineEnvironment($app); $app->make('config')->set('sentry.tracing.views', false); - $app->instance(ViewFactory::class, m::mock(ViewFactory::class)->shouldIgnoreMissing()); } public function testSpanIsRecorded(): void diff --git a/tests/Sentry/FlushLifecycleTest.php b/tests/Sentry/FlushLifecycleTest.php index 2b7b5cc59d..00cde80b5c 100644 --- a/tests/Sentry/FlushLifecycleTest.php +++ b/tests/Sentry/FlushLifecycleTest.php @@ -22,7 +22,9 @@ use Hypervel\Sentry\SentryConfig; use Hypervel\Sentry\State\CoroutineRuntimeContextStorage; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Sentry\ClientInterface; use Sentry\Event; use Sentry\EventType; @@ -39,40 +41,38 @@ class FlushLifecycleTest extends TestCase { + use VerifiesDoubles; + public function testDrainPublishesBufferedTelemetryBeforeTheBoundedWait(): void { - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions') + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('getOptions') ->times(3) - ->andReturn(new Options); - $client->shouldReceive('captureEvent') - ->once() + ->returns(new Options); + $client->expects('captureEvent') ->with( - m::on(static fn (Event $event): bool => $event->getType() === EventType::logs()), + Argument::satisfies(static fn (Event $event): bool => $event->getType() === EventType::logs()), null, - m::type(Scope::class), + Argument::type(Scope::class), ) ->ordered() - ->andReturn(null); - $client->shouldReceive('captureEvent') - ->once() + ->returns(null); + $client->expects('captureEvent') ->with( - m::on(static fn (Event $event): bool => $event->getType() === EventType::metrics()), + Argument::satisfies(static fn (Event $event): bool => $event->getType() === EventType::metrics()), null, - m::type(Scope::class), + Argument::type(Scope::class), ) ->ordered() - ->andReturn(null); - $client->shouldReceive('flush') - ->once() - ->withNoArgs() + ->returns(null); + $client->expects('flush') + ->with(Argument::none()) ->ordered() - ->andReturn(new Result(ResultStatus::success())); - $client->shouldReceive('flush') - ->once() + ->returns(new Result(ResultStatus::success())); + $client->expects('flush') ->with(1) ->ordered() - ->andReturn(new Result(ResultStatus::success())); + ->returns(new Result(ResultStatus::success())); $this->withHub(new Hub($client), static function (): void { Logs::getInstance()->info('Buffered log'); @@ -84,20 +84,17 @@ public function testDrainPublishesBufferedTelemetryBeforeTheBoundedWait(): void public function testDrainDerivesAPositiveTimeoutFromTheClient(): void { - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions') - ->once() - ->andReturn(new Options(['http_timeout' => 2.2])); - $client->shouldReceive('flush') - ->once() - ->withNoArgs() + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('getOptions') + ->returns(new Options(['http_timeout' => 2.2])); + $client->expects('flush') + ->with(Argument::none()) ->ordered() - ->andReturn(new Result(ResultStatus::success())); - $client->shouldReceive('flush') - ->once() + ->returns(new Result(ResultStatus::success())); + $client->expects('flush') ->with(3) ->ordered() - ->andReturn(new Result(ResultStatus::success())); + ->returns(new Result(ResultStatus::success())); $result = $this->withHub( new Hub($client), @@ -109,19 +106,17 @@ public function testDrainDerivesAPositiveTimeoutFromTheClient(): void public function testDrainNormalizesAnExplicitNonPositiveTimeout(): void { - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions') + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('getOptions') ->never(); - $client->shouldReceive('flush') - ->once() - ->withNoArgs() + $client->expects('flush') + ->with(Argument::none()) ->ordered() - ->andReturn(new Result(ResultStatus::success())); - $client->shouldReceive('flush') - ->once() + ->returns(new Result(ResultStatus::success())); + $client->expects('flush') ->with(1) ->ordered() - ->andReturn(new Result(ResultStatus::success())); + ->returns(new Result(ResultStatus::success())); $result = $this->withHub( new Hub($client), @@ -143,21 +138,18 @@ public function testDrainWithoutAClientIsAlreadyComplete(): void public function testGracefulQueueWorkerStoppingPerformsABoundedDrain(): void { - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions') - ->once() - ->andReturn(new Options(['http_timeout' => 1.2])); - $client->shouldReceive('flush') - ->once() - ->withNoArgs() + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('getOptions') + ->returns(new Options(['http_timeout' => 1.2])); + $client->expects('flush') + ->with(Argument::none()) ->ordered() - ->andReturn(new Result(ResultStatus::success())); - $client->shouldReceive('flush') - ->once() + ->returns(new Result(ResultStatus::success())); + $client->expects('flush') ->with(2) ->ordered() - ->andReturn(new Result(ResultStatus::success())); - $feature = new QueueIntegration(m::mock(Container::class)); + ->returns(new Result(ResultStatus::success())); + $feature = new QueueIntegration(Double::for(Container::class, override: true)->strict()->instance()); $this->withHub( new Hub($client), @@ -169,10 +161,10 @@ public function testGracefulQueueWorkerStoppingPerformsABoundedDrain(): void public function testImmediateAndMemoryLimitQueueStopsDoNotDrain(): void { - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions')->never(); - $client->shouldReceive('flush')->never(); - $feature = new QueueIntegration(m::mock(Container::class)); + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('getOptions')->never(); + $client->expects('flush')->never(); + $feature = new QueueIntegration(Double::for(Container::class, override: true)->strict()->instance()); $this->withHub(new Hub($client), static function () use ($feature): void { $feature->handleWorkerStoppingQueueEvent(new WorkerStopping(terminatesImmediately: true)); @@ -184,12 +176,11 @@ public function testImmediateAndMemoryLimitQueueStopsDoNotDrain(): void public function testConsoleCompletionLeavesGlobalTelemetryForApplicationTermination(): void { - $client = m::mock(ClientInterface::class); - $client->shouldNotReceive('flush'); - $client->shouldReceive('getIntegration') - ->once() + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('flush')->never(); + $client->expects('getIntegration') ->with(Integration::class) - ->andReturn(null); + ->returns(null); $config = new Repository([ 'sentry' => [ 'dsn' => 'https://public@example.com/1', @@ -199,12 +190,12 @@ public function testConsoleCompletionLeavesGlobalTelemetryForApplicationTerminat ], ]); $sentryConfig = new SentryConfig($config, 'sentry'); - $container = m::mock(Container::class); - $container->shouldReceive('make') - ->twice() + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make') + ->times(2) ->with(SentryConfig::class) - ->andReturn($sentryConfig); - $feature = new ConsoleFeature($container); + ->returns($sentryConfig); + $feature = new ConsoleFeature($container->instance()); $this->withHub(new Hub($client), static function () use ($feature): void { $command = new FlushLifecycleCommand; @@ -264,20 +255,19 @@ public function testScheduledTaskCompletionFollowedByFailureFlushesOnce(): void private function assertScheduledTaskFlushesAtExecutionEnd(callable $terminal): void { $flushed = false; - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions')->andReturn(new Options); - $client->shouldReceive('captureEvent')->never(); - $client->shouldReceive('flush') - ->once() + $client = Double::for(ClientInterface::class)->strict(); + $client->allows('getOptions')->returns(new Options); + $client->expects('captureEvent')->never(); + $client->expects('flush') ->with(null) - ->andReturnUsing(static function () use (&$flushed): Result { + ->resolves(static function () use (&$flushed): Result { $flushed = true; return new Result(ResultStatus::success()); }); - $feature = new ConsoleSchedulingIntegration(m::mock(Container::class)); - $event = (new ScheduledEvent(m::mock(EventMutex::class)))->description('Scheduled task'); + $feature = new ConsoleSchedulingIntegration(Double::for(Container::class, override: true)->strict()->instance()); + $event = (new ScheduledEvent(Double::for(EventMutex::class)->strict()))->description('Scheduled task'); $hub = new Hub($client); $storage = new CoroutineRuntimeContextStorage; $previousHub = SentrySdk::getCurrentHub(); diff --git a/tests/Sentry/Http/FlushEventsMiddlewareTest.php b/tests/Sentry/Http/FlushEventsMiddlewareTest.php index 8de942941c..8263481bf1 100644 --- a/tests/Sentry/Http/FlushEventsMiddlewareTest.php +++ b/tests/Sentry/Http/FlushEventsMiddlewareTest.php @@ -10,7 +10,8 @@ use Hypervel\Sentry\State\CoroutineRuntimeContextStorage; use Hypervel\Sentry\State\RuntimeContextBoundary; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Sentry\ClientInterface; use Sentry\Options; use Sentry\SentrySdk; @@ -22,17 +23,18 @@ class FlushEventsMiddlewareTest extends TestCase { + use VerifiesDoubles; + public function testFlushIsDeferredUntilTheRequestCoroutineExits(): void { $handled = new Channel(1); $flushed = new Channel(1); $storage = new CoroutineRuntimeContextStorage; - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions')->once()->andReturn(new Options); - $client->shouldReceive('flush') - ->once() + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('getOptions')->returns(new Options); + $client->expects('flush') ->with(null) - ->andReturnUsing(static function () use ($flushed): Result { + ->resolves(static function () use ($flushed): Result { $flushed->push(true); return new Result(ResultStatus::success()); diff --git a/tests/Sentry/HttpPoolTransportNonCoroutineTest.php b/tests/Sentry/HttpPoolTransportNonCoroutineTest.php index 2138842dbb..e2e3244980 100644 --- a/tests/Sentry/HttpPoolTransportNonCoroutineTest.php +++ b/tests/Sentry/HttpPoolTransportNonCoroutineTest.php @@ -7,7 +7,8 @@ use Hypervel\Sentry\Transport\HttpPoolTransport; use Hypervel\Sentry\Transport\HttpTransportPool; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Sentry\Event; use Sentry\Options; use Sentry\Transport\HttpTransport; @@ -16,17 +17,18 @@ class HttpPoolTransportNonCoroutineTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; public function testRootCoroutineOwnsAndReleasesTheTransport(): void { - $httpTransport = m::mock(HttpTransport::class); - $httpTransport->shouldReceive('send') - ->once() - ->andReturn(new Result(ResultStatus::success())); - $pool = m::mock(HttpTransportPool::class); - $pool->shouldReceive('borrow')->once()->andReturn($httpTransport); - $pool->shouldReceive('release')->once()->with($httpTransport); + $httpTransport = Double::for(HttpTransport::class)->strict(); + $httpTransport->expects('send') + ->returns(new Result(ResultStatus::success())); + $pool = Double::for(HttpTransportPool::class)->strict(); + $pool->expects('borrow')->returns($httpTransport); + $pool->expects('release')->with($httpTransport); $transport = new HttpPoolTransport($pool, new Options(['dsn' => 'https://public@example.com/1'])); $event = Event::createEvent(); diff --git a/tests/Sentry/HttpPoolTransportTest.php b/tests/Sentry/HttpPoolTransportTest.php index 5ab811eb72..7d193b545f 100644 --- a/tests/Sentry/HttpPoolTransportTest.php +++ b/tests/Sentry/HttpPoolTransportTest.php @@ -14,7 +14,9 @@ use Hypervel\Sentry\Transport\HttpPoolTransport; use Hypervel\Sentry\Transport\HttpTransportPool; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use Sentry\ClientBuilder; use Sentry\Event; @@ -26,13 +28,15 @@ class HttpPoolTransportTest extends TestCase { + use VerifiesDoubles; + public function testAcquisitionTimeoutReturnsSkippedWithoutReleasingTheBorrowedTransport(): void { - $pool = m::mock(HttpTransportPool::class, [ + $pool = Double::for(new HttpTransportPool( new ClientBuilder, PoolOptions::fromArray(['max_objects' => 1, 'wait_timeout' => 0.001]), - ])->makePartial()->shouldAllowMockingProtectedMethods(); - $pool->shouldReceive('createObject')->once()->andReturn(m::mock(HttpTransport::class)); + ))->passthru(); + $pool->expects('createObject')->returns(Double::for(HttpTransport::class)->strict()); $borrowed = $pool->borrow(); $transport = new HttpPoolTransport($pool, $this->optionsWithDsn()); @@ -49,17 +53,14 @@ public function testAcquisitionTimeoutReturnsSkippedWithoutReleasingTheBorrowedT public function testAcceptedSendReturnsItsEventAndReleasesTransportAfterCompletion(): void { - $httpTransport = m::mock(HttpTransport::class); - $httpTransport->shouldReceive('send') - ->once() - ->andReturn(new Result(ResultStatus::success())); - - $pool = m::mock(HttpTransportPool::class); - $pool->shouldReceive('borrow') - ->once() - ->andReturn($httpTransport); - $pool->shouldReceive('release') - ->once() + $httpTransport = Double::for(HttpTransport::class)->strict(); + $httpTransport->expects('send') + ->returns(new Result(ResultStatus::success())); + + $pool = Double::for(HttpTransportPool::class)->strict(); + $pool->expects('borrow') + ->returns($httpTransport); + $pool->expects('release') ->with($httpTransport); $transport = new HttpPoolTransport($pool, $this->optionsWithDsn()); @@ -88,8 +89,8 @@ public function testSendWithoutAnEndpointSkipsWithoutBorrowingOrStartingACorouti Coroutine::afterCreated(static function () use (&$createdCoroutines): void { ++$createdCoroutines; }); - $pool = m::mock(HttpTransportPool::class); - $pool->shouldNotReceive('borrow'); + $pool = Double::for(HttpTransportPool::class)->strict(); + $pool->expects('borrow')->never(); $transport = new HttpPoolTransport($pool, new Options); $event = Event::createEvent(); @@ -105,8 +106,8 @@ public function testSpotlightOnlySendIsDeliveredAsynchronously(): void { $started = new Channel(1); $finish = new Channel(1); - $httpTransport = m::mock(HttpTransport::class); - $httpTransport->shouldReceive('send')->once()->andReturnUsing( + $httpTransport = Double::for(HttpTransport::class)->strict(); + $httpTransport->expects('send')->resolves( static function () use ($started, $finish): Result { $started->push(true); $finish->pop(1.0); @@ -114,9 +115,9 @@ static function () use ($started, $finish): Result { return new Result(ResultStatus::success()); } ); - $pool = m::mock(HttpTransportPool::class); - $pool->shouldReceive('borrow')->once()->andReturn($httpTransport); - $pool->shouldReceive('release')->once()->with($httpTransport); + $pool = Double::for(HttpTransportPool::class)->strict(); + $pool->expects('borrow')->returns($httpTransport); + $pool->expects('release')->with($httpTransport); $transport = new HttpPoolTransport($pool, new Options(['spotlight' => true])); $result = $transport->send(Event::createEvent()); @@ -136,10 +137,8 @@ static function () use ($started, $finish): Result { public function testTransportCreationFailurePropagatesUnchanged(): void { $failure = new RuntimeException('Transport creation failed.'); - $pool = m::mock(HttpTransportPool::class, [new ClientBuilder, PoolOptions::fromArray([])]) - ->makePartial() - ->shouldAllowMockingProtectedMethods(); - $pool->shouldReceive('createObject')->once()->andThrow($failure); + $pool = Double::for(new HttpTransportPool(new ClientBuilder, PoolOptions::fromArray([])))->passthru(); + $pool->expects('createObject')->throws($failure); $transport = new HttpPoolTransport($pool, $this->optionsWithDsn()); $caught = null; @@ -161,13 +160,12 @@ public function testDeliveryMarkerIsAvailableToChildStartupHooks(): void Coroutine::afterCreated(static function () use ($marker): void { $marker->push(CoroutineContext::get(HttpPoolTransport::DELIVERY_CONTEXT_KEY)); }); - $httpTransport = m::mock(HttpTransport::class); - $httpTransport->shouldReceive('send') - ->once() - ->andReturn(new Result(ResultStatus::success())); - $pool = m::mock(HttpTransportPool::class); - $pool->shouldReceive('borrow')->once()->andReturn($httpTransport); - $pool->shouldReceive('release')->once()->with($httpTransport); + $httpTransport = Double::for(HttpTransport::class)->strict(); + $httpTransport->expects('send') + ->returns(new Result(ResultStatus::success())); + $pool = Double::for(HttpTransportPool::class)->strict(); + $pool->expects('borrow')->returns($httpTransport); + $pool->expects('release')->with($httpTransport); $transport = new HttpPoolTransport($pool, $this->optionsWithDsn()); $transport->send(Event::createEvent()); @@ -178,17 +176,14 @@ public function testDeliveryMarkerIsAvailableToChildStartupHooks(): void public function testUnexpectedChildFailureDiscardsTransport(): void { - $httpTransport = m::mock(HttpTransport::class); - $httpTransport->shouldReceive('send') - ->once() - ->andThrow(new RuntimeException('Send failed')); - - $pool = m::mock(HttpTransportPool::class); - $pool->shouldReceive('borrow') - ->once() - ->andReturn($httpTransport); - $pool->shouldReceive('discard') - ->once() + $httpTransport = Double::for(HttpTransport::class)->strict(); + $httpTransport->expects('send') + ->throws(new RuntimeException('Send failed')); + + $pool = Double::for(HttpTransportPool::class)->strict(); + $pool->expects('borrow') + ->returns($httpTransport); + $pool->expects('discard') ->with($httpTransport); $transport = new HttpPoolTransport($pool, $this->optionsWithDsn()); @@ -204,35 +199,29 @@ public function testUnexpectedChildFailureDiscardsTransport(): void public function testMixedSuccessAndFailureFinalizesCorrectly(): void { - $httpTransport1 = m::mock(HttpTransport::class); - $httpTransport1->shouldReceive('send') - ->once() - ->andReturn(new Result(ResultStatus::success())); - - $httpTransport2 = m::mock(HttpTransport::class); - $httpTransport2->shouldReceive('send') - ->once() - ->andThrow(new RuntimeException('Send failed')); - - $httpTransport3 = m::mock(HttpTransport::class); - $httpTransport3->shouldReceive('send') - ->once() - ->andReturn(new Result(ResultStatus::success())); - - $pool = m::mock(HttpTransportPool::class); - $pool->shouldReceive('borrow') + $httpTransport1 = Double::for(HttpTransport::class)->strict(); + $httpTransport1->expects('send') + ->returns(new Result(ResultStatus::success())); + + $httpTransport2 = Double::for(HttpTransport::class)->strict(); + $httpTransport2->expects('send') + ->throws(new RuntimeException('Send failed')); + + $httpTransport3 = Double::for(HttpTransport::class)->strict(); + $httpTransport3->expects('send') + ->returns(new Result(ResultStatus::success())); + + $pool = Double::for(HttpTransportPool::class)->strict(); + $pool->expects('borrow') ->times(3) - ->andReturn($httpTransport1, $httpTransport2, $httpTransport3); + ->returns($httpTransport1, $httpTransport2, $httpTransport3); // transport2 is discarded immediately on exception. - $pool->shouldReceive('discard') - ->once() - ->with($httpTransport2); - $pool->shouldReceive('release') - ->once() - ->with($httpTransport1); - $pool->shouldReceive('release') - ->once() - ->with($httpTransport3); + $pool->expects('discard') + ->with(Argument::same($httpTransport2)); + $pool->expects('release') + ->with(Argument::same($httpTransport1)); + $pool->expects('release') + ->with(Argument::same($httpTransport3)); $transport = new HttpPoolTransport($pool, $this->optionsWithDsn()); @@ -250,8 +239,8 @@ public function testPositiveCloseWaitsOnlyForItsCapturedGeneration(): void $releaseSecond = new Channel(1); $drainResult = new Channel(1); - $first = m::mock(HttpTransport::class); - $first->shouldReceive('send')->once()->andReturnUsing( + $first = Double::for(HttpTransport::class)->strict(); + $first->expects('send')->resolves( static function () use ($firstStarted, $releaseFirst): Result { $firstStarted->push(true); $releaseFirst->pop(); @@ -259,8 +248,8 @@ static function () use ($firstStarted, $releaseFirst): Result { return new Result(ResultStatus::success()); } ); - $second = m::mock(HttpTransport::class); - $second->shouldReceive('send')->once()->andReturnUsing( + $second = Double::for(HttpTransport::class)->strict(); + $second->expects('send')->resolves( static function () use ($secondStarted, $releaseSecond): Result { $secondStarted->push(true); $releaseSecond->pop(); @@ -269,10 +258,10 @@ static function () use ($secondStarted, $releaseSecond): Result { } ); - $pool = m::mock(HttpTransportPool::class); - $pool->shouldReceive('borrow')->twice()->andReturn($first, $second); - $pool->shouldReceive('release')->once()->with($first); - $pool->shouldReceive('release')->once()->with($second); + $pool = Double::for(HttpTransportPool::class)->strict(); + $pool->expects('borrow')->times(2)->returns($first, $second); + $pool->expects('release')->with(Argument::same($first)); + $pool->expects('release')->with(Argument::same($second)); $transport = new HttpPoolTransport($pool, $this->optionsWithDsn()); @@ -305,12 +294,12 @@ static function () use ($secondStarted, $releaseSecond): Result { public function testCoroutineCreationFailureBalancesTheGenerationAndReleasesTheTransport(): void { - $httpTransport = m::mock(HttpTransport::class); - $httpTransport->shouldNotReceive('send'); + $httpTransport = Double::for(HttpTransport::class)->strict(); + $httpTransport->expects('send')->never(); - $pool = m::mock(HttpTransportPool::class); - $pool->shouldReceive('borrow')->once()->andReturn($httpTransport); - $pool->shouldReceive('release')->once()->with($httpTransport); + $pool = Double::for(HttpTransportPool::class)->strict(); + $pool->expects('borrow')->returns($httpTransport); + $pool->expects('release')->with($httpTransport); $transport = new FailingCoroutineHttpPoolTransport($pool, $this->optionsWithDsn()); $result = $transport->send(Event::createEvent()); @@ -321,24 +310,23 @@ public function testCoroutineCreationFailureBalancesTheGenerationAndReleasesTheT public function testStartupCancellationReleasesAnUntouchedTransport(): void { - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); Container::getInstance()->instance(ExceptionHandlerContract::class, $handler); - $httpTransport = m::mock(HttpTransport::class); - $httpTransport->shouldNotReceive('send'); - $pool = m::mock(HttpTransportPool::class); - $pool->shouldReceive('borrow')->once()->andReturn($httpTransport); - $pool->shouldReceive('release')->once()->with($httpTransport); - $pool->shouldNotReceive('discard'); + $httpTransport = Double::for(HttpTransport::class)->strict(); + $httpTransport->expects('send')->never(); + $pool = Double::for(HttpTransportPool::class)->strict(); + $pool->expects('borrow')->returns($httpTransport); + $pool->expects('release')->with($httpTransport); + $pool->expects('discard')->never(); $transport = new HttpPoolTransport($pool, $this->optionsWithDsn()); $hookFailure = new RuntimeException('The startup hook failed.'); $reportStarted = new Channel(1); $releaseReport = new Channel(1); $childCoroutineId = null; - $handler->shouldReceive('report') - ->once() + $handler->expects('report') ->with($hookFailure) - ->andReturnUsing(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { + ->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { $childCoroutineId = EngineCoroutine::id(); $reportStarted->push(true); $releaseReport->pop(); @@ -370,8 +358,8 @@ public function testStartupCancellationReleasesAnUntouchedTransport(): void public function testShutdownClosesThePool(): void { - $pool = m::mock(HttpTransportPool::class); - $pool->shouldReceive('close')->once(); + $pool = Double::for(HttpTransportPool::class)->strict(); + $pool->expects('close'); (new HttpPoolTransport($pool, $this->optionsWithDsn()))->shutdown(); } diff --git a/tests/Sentry/HttpTransportPoolTest.php b/tests/Sentry/HttpTransportPoolTest.php index 010cb7ef94..2378887cd6 100644 --- a/tests/Sentry/HttpTransportPoolTest.php +++ b/tests/Sentry/HttpTransportPoolTest.php @@ -7,7 +7,8 @@ use Hypervel\ObjectPool\PoolOptions; use Hypervel\Sentry\Transport\HttpTransportPool; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Psr\Log\AbstractLogger; use ReflectionProperty; use Sentry\ClientBuilder; @@ -20,6 +21,8 @@ class HttpTransportPoolTest extends TestCase { + use VerifiesDoubles; + public function testEachTransportGetsItsOwnDefaultClientIdentifiedByTheBuilder(): void { $builder = new ClientBuilder; @@ -43,10 +46,10 @@ public function testEachTransportGetsItsOwnDefaultClientIdentifiedByTheBuilder() public function testTransportsShareTheBuilderClientAndLogThroughTheBuilderLogger(): void { - $httpClient = m::mock(HttpClientInterface::class); - $httpClient->shouldReceive('sendRequest') - ->twice() - ->andReturn(new Response(200, [], '')); + $httpClient = Double::for(HttpClientInterface::class)->strict(); + $httpClient->expects('sendRequest') + ->times(2) + ->returns(new Response(200, [], '')); $logger = new class extends AbstractLogger { /** @var list */ public array $messages = []; @@ -79,10 +82,9 @@ public function log(mixed $level, string|Stringable $message, array $context = [ public function testPooledTransportRetainsRateLimitsFromRealResponses(): void { - $httpClient = m::mock(HttpClientInterface::class); - $httpClient->shouldReceive('sendRequest') - ->once() - ->andReturn(new Response(429, [ + $httpClient = Double::for(HttpClientInterface::class)->strict(); + $httpClient->expects('sendRequest') + ->returns(new Response(429, [ 'X-Sentry-Rate-Limits' => ['60:error'], ], '')); diff --git a/tests/Sentry/HubTest.php b/tests/Sentry/HubTest.php index 49550f2f89..f91a72c32c 100644 --- a/tests/Sentry/HubTest.php +++ b/tests/Sentry/HubTest.php @@ -10,7 +10,8 @@ use Hypervel\Foundation\Application; use Hypervel\Sentry\Hub; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Psr\Log\LoggerInterface; use RuntimeException; @@ -28,6 +29,8 @@ class HubTest extends TestCase { + use VerifiesDoubles; + /** * Set up the test environment. */ @@ -55,7 +58,7 @@ public function testConfiguredBaselineScopeIsClonedAndPreservedWhenClientIsBound $this->assertSame($baseline, $root); - $client = m::mock(ClientInterface::class); + $client = Double::for(ClientInterface::class)->strict(); $hub->bindClient($client); $application->boot(); @@ -125,12 +128,11 @@ public function testFinalRootLayerCannotBePoppedBeforeOrAfterNestedScopes(): voi public function testFailingBeforeBreadcrumbCallbackDropsTheBreadcrumb(): void { - $logger = m::mock(LoggerInterface::class); - $logger->shouldReceive('error') - ->once() + $logger = Double::for(LoggerInterface::class)->strict(); + $logger->expects('error') ->with('The "before_breadcrumb" callback failed with exception: "Callback failed.".'); - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions')->once()->andReturn(new Options([ + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('getOptions')->returns(new Options([ 'logger' => $logger, 'before_breadcrumb' => static fn (): ?Breadcrumb => throw new RuntimeException('Callback failed.'), ])); @@ -146,7 +148,7 @@ public function testAttachmentsAreAddedToTheCurrentScopeOnlyWithAClient(): void $this->assertFalse((new Hub)->addAttachment($attachment)); - $hub = new Hub(m::mock(ClientInterface::class)); + $hub = new Hub(Double::for(ClientInterface::class)->strict()); $this->assertTrue($hub->addAttachment($attachment)); $this->assertSame([$attachment], $this->scopedEvent($hub)->getAttachments()); @@ -163,8 +165,8 @@ public function testProfilesSamplerControlsProfileSampling(): void return 0.0; }, ]); - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions')->once()->andReturn($options); + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('getOptions')->returns($options); $transaction = (new Hub($client))->startTransaction(new TransactionContext('test')); $this->assertTrue($called); @@ -174,15 +176,15 @@ public function testProfilesSamplerControlsProfileSampling(): void public function testFailingSamplersFallBackToTheConfiguredRates(): void { - $logger = m::mock(LoggerInterface::class)->shouldIgnoreMissing(); - $logger->shouldReceive('error') - ->once() + $logger = Double::for(LoggerInterface::class)->strict(); + $logger->allows('info'); + $logger->allows('warning')->with('The profiler was started but is not available because the "excimer" extension is not loaded.'); + $logger->expects('error') ->with('The "traces_sampler" callback failed with exception: "Traces sampler failed.".'); - $logger->shouldReceive('error') - ->once() + $logger->expects('error') ->with('The "profiles_sampler" callback failed with exception: "Profiles sampler failed.".'); - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions')->andReturn(new Options([ + $client = Double::for(ClientInterface::class)->strict(); + $client->allows('getOptions')->returns(new Options([ 'logger' => $logger, 'traces_sample_rate' => 1.0, 'traces_sampler' => static fn (): float => throw new RuntimeException('Traces sampler failed.'), @@ -206,8 +208,8 @@ public function testCallbackCancellationPropagatesUnchanged(string $option, Clos $cancellation = new RuntimeException('Callback cleanup failed.', previous: $cancellation); } - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions')->andReturn(new Options([ + $client = Double::for(ClientInterface::class)->strict(); + $client->allows('getOptions')->returns(new Options([ 'traces_sample_rate' => 1.0, $option => static fn (): never => throw $cancellation, ])); diff --git a/tests/Sentry/IntegrationMetaTagTest.php b/tests/Sentry/IntegrationMetaTagTest.php index fc00286e9e..781df88679 100644 --- a/tests/Sentry/IntegrationMetaTagTest.php +++ b/tests/Sentry/IntegrationMetaTagTest.php @@ -5,7 +5,8 @@ namespace Hypervel\Tests\Sentry; use Hypervel\Sentry\Integration; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Sentry\State\Scope; use Sentry\Tracing\Span; @@ -13,6 +14,8 @@ class IntegrationMetaTagTest extends TestCase { + use VerifiesDoubles; + private const string DANGEROUS_PAYLOAD = ''; /** @@ -90,9 +93,9 @@ public function testSentryBaggageMetaReturnsAWellFormedMetaTag(): void */ private function setDangerousSpanValues(string $traceparent, string $baggage): void { - $span = m::mock(Span::class); - $span->shouldReceive('toTraceparent')->andReturn($traceparent)->zeroOrMoreTimes(); - $span->shouldReceive('toBaggage')->andReturn($baggage)->zeroOrMoreTimes(); + $span = Double::for(Span::class)->strict(); + $span->allows('toTraceparent')->returns($traceparent); + $span->allows('toBaggage')->returns($baggage); configureScope(static function (Scope $scope) use ($span): void { $scope->setSpan($span); diff --git a/tests/Sentry/IntegrationTest.php b/tests/Sentry/IntegrationTest.php index 879497e759..5eccbc54e1 100644 --- a/tests/Sentry/IntegrationTest.php +++ b/tests/Sentry/IntegrationTest.php @@ -8,7 +8,9 @@ use Hypervel\Routing\Events\RouteMatched; use Hypervel\Routing\Route; use Hypervel\Sentry\Integration; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Psr\Log\LoggerInterface; use RuntimeException; use Sentry\Event; @@ -19,6 +21,8 @@ class IntegrationTest extends TestCase { + use VerifiesDoubles; + public function testIntegrationIsRegistered(): void { $integration = $this->getSentryHubFromContainer()->getIntegration(Integration::class); @@ -32,7 +36,7 @@ public function testTransactionIsSetWhenRouteMatchedEventIsFired(): void $event = new RouteMatched( new Route('GET', $routeUrl = '/sentry-route-matched-event', []), - m::mock(Request::class)->makePartial() + new Request ); $this->dispatchHypervelEvent($event); @@ -121,8 +125,10 @@ public function testExtractingNameForRouteWithIncompleteGroupName(): void public function testExceptionReportedUsingReportHelperIsNotMarkedAsUnhandled(): void { $testException = new RuntimeException('This was handled'); - $logger = m::mock(LoggerInterface::class); - $logger->expects('error')->with('This was handled', m::subset(['order_id' => 42])); + $logger = Double::for(LoggerInterface::class)->strict(); + $logger->expects('error')->with('This was handled', Argument::satisfies( + static fn (array $context): bool => ($context['order_id'] ?? null) === 42, + )); $this->app->instance(LoggerInterface::class, $logger); report($testException, ['order_id' => 42]); diff --git a/tests/Sentry/LogChannelTest.php b/tests/Sentry/LogChannelTest.php index 6ff0e04f4d..b0d50727fe 100644 --- a/tests/Sentry/LogChannelTest.php +++ b/tests/Sentry/LogChannelTest.php @@ -10,7 +10,6 @@ use Hypervel\Sentry\Logs\LogChannel as LogsLogChannel; use Hypervel\Sentry\Logs\LogsHandler; use Hypervel\Sentry\SentryHandler; -use Mockery as m; use Monolog\Formatter\LineFormatter; use Monolog\Level; use Monolog\LogRecord; @@ -18,7 +17,7 @@ use ReflectionProperty; use RuntimeException; use Sentry\Event; -use Sentry\State\HubInterface; +use Sentry\State\Hub; class LogChannelTest extends TestCase { @@ -47,9 +46,7 @@ public function testCreatingHandlerWithActionLevelConfig(): void $this->assertSame(FingersCrossedHandler::class, get_class($currentHandler)); $this->assertFalse((new ReflectionProperty($currentHandler, 'stopBuffering'))->getValue($currentHandler)); - if (method_exists($currentHandler, 'getHandler')) { - $this->assertInstanceOf(SentryHandler::class, $currentHandler->getHandler()); - } + $this->assertInstanceOf(SentryHandler::class, $currentHandler->getHandler()); $loggerWithoutActionLevel = $logChannel(['action_level' => null]); @@ -101,7 +98,7 @@ public function testNativeBatchHandlingFiltersAndEnrichesImmutableRecords(Record */ public static function nativeBatchHandlerDataProvider(): iterable { - yield 'events handler' => [new RecordingSentryHandler(m::mock(HubInterface::class), Level::Warning)]; + yield 'events handler' => [new RecordingSentryHandler(new Hub, Level::Warning)]; yield 'logs handler' => [new RecordingLogsHandler(Level::Warning)]; } diff --git a/tests/Sentry/ServerForkTest.php b/tests/Sentry/ServerForkTest.php index 1683cf2b53..b26c926418 100644 --- a/tests/Sentry/ServerForkTest.php +++ b/tests/Sentry/ServerForkTest.php @@ -12,7 +12,8 @@ use Hypervel\Sentry\Logs\LogsHandler; use Hypervel\ServerProcess\AbstractProcess; use Hypervel\ServerProcess\Events\BeforeProcessHandle; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Monolog\Handler\BufferHandler; use PHPUnit\Framework\Attributes\DataProvider; use Sentry\ClientBuilder; @@ -27,6 +28,8 @@ class ServerForkTest extends TestCase { + use VerifiesDoubles; + private ServerForkRecordingHttpClient $httpClient; /** @@ -72,7 +75,7 @@ public function testRecordsBufferedByLogChannelsAreSentBeforeTheServerForks(): v $this->assertSame([], $this->getCapturedSentryEventsOfType(EventType::logs())); - $this->dispatchHypervelEvent(new BeforeServerFork(m::mock(Server::class))); + $this->dispatchHypervelEvent(new BeforeServerFork(Double::for(Server::class)->strict())); $logs = $this->getCapturedSentryEventsOfType(EventType::logs()); @@ -108,11 +111,13 @@ public function testServerSendsWithoutConnectionSharingUntilAForkedProcessStarts */ public static function forkedProcessStarts(): iterable { - yield 'worker' => ['start' => static fn (): BeforeWorkerStart => new BeforeWorkerStart(m::mock(Server::class), 0)]; + yield 'worker' => ['start' => static fn (): BeforeWorkerStart => new BeforeWorkerStart(Double::for(Server::class)->strict(), 0)]; yield 'custom process' => ['start' => static function (ApplicationContract $app): BeforeProcessHandle { // Keep the process start log line out of the test output. - $app->instance(StdoutLoggerInterface::class, m::mock(StdoutLoggerInterface::class)->shouldIgnoreMissing()); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->allows('info'); + $app->instance(StdoutLoggerInterface::class, $logger); return new BeforeProcessHandle(new ServerForkProcess($app), 0); }]; @@ -125,7 +130,7 @@ public function testForkedProcessesRestoreOnlyTheChosenSetting(Closure $customiz $this->assertFalse($options->isShareHandleEnabled()); - $this->dispatchHypervelEvent(new BeforeWorkerStart(m::mock(Server::class), 0)); + $this->dispatchHypervelEvent(new BeforeWorkerStart(Double::for(Server::class)->strict(), 0)); $this->assertSame($sharesAfterStart, $options->isShareHandleEnabled()); } diff --git a/tests/Sentry/ServiceProviderListenerRegistrationTest.php b/tests/Sentry/ServiceProviderListenerRegistrationTest.php index 3d0b530245..503af0f459 100644 --- a/tests/Sentry/ServiceProviderListenerRegistrationTest.php +++ b/tests/Sentry/ServiceProviderListenerRegistrationTest.php @@ -16,11 +16,14 @@ use Hypervel\WebSocketServer\Events\ConnectionClosing; use Hypervel\WebSocketServer\Events\ConnectionOpening; use Hypervel\WebSocketServer\Events\MessageReceived; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionFunction; class ServiceProviderListenerRegistrationTest extends TestCase { + use VerifiesDoubles; + protected array $defaultSetupConfig = [ 'sentry.traces_sample_rate' => 1.0, ]; @@ -80,8 +83,8 @@ public function testMessageLoggedIsRegisteredWhenLogBreadcrumbsAreEnabled(): voi public function testRuntimeContextBoundariesPrecedeFeatureListenersAndResolveAtDispatchTime(): void { - $boundary = m::mock(RuntimeContextBoundary::class); - $boundary->shouldReceive('start')->times(5); + $boundary = Double::for(RuntimeContextBoundary::class)->strict(); + $boundary->expects('start')->times(5); $this->app->instance(RuntimeContextBoundary::class, $boundary); foreach ([ diff --git a/tests/Sentry/ServiceProviderTest.php b/tests/Sentry/ServiceProviderTest.php index 63d8d7ab66..d1dfafed02 100644 --- a/tests/Sentry/ServiceProviderTest.php +++ b/tests/Sentry/ServiceProviderTest.php @@ -26,8 +26,10 @@ use Hypervel\Support\Facades\Artisan; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Di\Fixtures\ProxySources; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Depends; use Psr\Log\LoggerInterface; @@ -46,6 +48,8 @@ class ServiceProviderTest extends TestCase { + use VerifiesDoubles; + private ?string $proxyFile = null; protected array $setupConfig = [ @@ -141,11 +145,10 @@ public function testArtisanCommandsAreRegistered(): void public function testRootTelemetryFlushesAtApplicationTermination(): void { - $client = m::mock(ClientInterface::class); - $client->shouldReceive('flush') - ->once() - ->withNoArgs() - ->andReturn(new Result(ResultStatus::success())); + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('flush') + ->with(Argument::none()) + ->returns(new Result(ResultStatus::success())); $previousHub = SentrySdk::getCurrentHub(); try { @@ -160,14 +163,12 @@ public function testRootTelemetryFlushesAtApplicationTermination(): void public function testApplicationTerminationDoesNotFlushAnActiveExecutionContext(): void { $flushed = false; - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions') - ->once() - ->andReturn(new Options); - $client->shouldReceive('flush') - ->once() + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('getOptions') + ->returns(new Options); + $client->expects('flush') ->with(null) - ->andReturnUsing(static function () use (&$flushed): Result { + ->resolves(static function () use (&$flushed): Result { $flushed = true; return new Result(ResultStatus::success()); @@ -194,18 +195,14 @@ public function testApplicationTerminationDoesNotFlushAnActiveExecutionContext() public function testMiddlewareRegistersThroughTheKernelContract(): void { - $kernel = m::mock(Kernel::class); - $kernel->shouldReceive('prependMiddleware') - ->once() + $kernel = Double::for(Kernel::class)->strict(); + $kernel->expects('prependMiddleware') ->with(TracingMiddleware::class) - ->ordered() - ->andReturnSelf(); - $kernel->shouldReceive('prependMiddleware') - ->once() + ->ordered(); + $kernel->expects('prependMiddleware') ->with(FlushEventsMiddleware::class) - ->ordered() - ->andReturnSelf(); - $kernel->shouldNotReceive('pushMiddleware'); + ->ordered(); + $kernel->expects('pushMiddleware')->never(); $this->app->instance(Kernel::class, $kernel); (new InspectableSentryServiceProvider($this->app)) @@ -216,26 +213,20 @@ public function testMiddlewareRegistersThroughTheKernelContract(): void public function testRequestIpMiddlewareIsRegisteredOnlyWhenUserInfoIsCollected(array $config, bool $registered): void { $this->resetApplicationWithConfig($config); - $kernel = m::mock(Kernel::class); - $kernel->shouldReceive('prependMiddleware') - ->once() + $kernel = Double::for(Kernel::class)->strict(); + $kernel->expects('prependMiddleware') ->with(TracingMiddleware::class) - ->ordered() - ->andReturnSelf(); - $kernel->shouldReceive('prependMiddleware') - ->once() + ->ordered(); + $kernel->expects('prependMiddleware') ->with(FlushEventsMiddleware::class) - ->ordered() - ->andReturnSelf(); + ->ordered(); if ($registered) { - $kernel->shouldReceive('pushMiddleware') - ->once() + $kernel->expects('pushMiddleware') ->with(SetRequestIpMiddleware::class) - ->ordered() - ->andReturnSelf(); + ->ordered(); } else { - $kernel->shouldNotReceive('pushMiddleware'); + $kernel->expects('pushMiddleware')->never(); } $this->app->instance(Kernel::class, $kernel); @@ -408,10 +399,9 @@ public function testFeatureFailureIsLoggedWithoutOverwritingItsInstanceOrSkippin $exception = new RuntimeException('Feature registration failed.'); $feature = new FailingRegistrationSentryFeature($this->app); $feature->exception = $exception; - $logger = m::mock(LoggerInterface::class); - $logger->shouldReceive('warning') - ->once() - ->withArgs(static function (string $message, array $context) use ($exception): bool { + $logger = Double::for(LoggerInterface::class)->strict(); + $logger->expects('warning') + ->with(Argument::all(static function (string $message, array $context) use ($exception): bool { return str_contains($message, 'failed during [register]') && str_contains($message, 'effects applied before the failure remain in place') && str_contains($message, 'will not be retried for this worker lifetime') @@ -420,7 +410,7 @@ public function testFeatureFailureIsLoggedWithoutOverwritingItsInstanceOrSkippin 'phase' => 'register', 'exception' => $exception, ]; - }); + })); $this->app->instance('log', $logger); $this->app->instance(FailingRegistrationSentryFeature::class, $feature); config()->set('sentry.features', [FailingRegistrationSentryFeature::class]); @@ -442,12 +432,12 @@ public function testLogChannelsAreComputedAgainAgainstTheRebuiltConfiguration(): ]); $tracker = new ConfigMutationTracker; $tracker->observe($masterConfig); - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturnFalse(); - $app->shouldReceive('make')->with('config')->andReturn($masterConfig); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->andReturn($tracker); + $app = Double::for(Application::class, override: true)->strict(); + $app->allows('configurationIsCached')->returns(false); + $app->allows('make')->with('config')->returns($masterConfig); + $app->allows('make')->with(ConfigMutationTracker::class)->returns($tracker); - (new CustomRootInspectableSentryServiceProvider($app))->registerLogChannelsForTest(); + (new CustomRootInspectableSentryServiceProvider($app->instance()))->registerLogChannelsForTest(); $this->assertSame($explicitChannel, $masterConfig->get('logging.channels.sentry')); $this->assertSame(['driver' => 'sentry_logs', 'level' => 'debug'], $masterConfig->get('logging.channels.sentry_logs')); diff --git a/tests/Sentry/State/RuntimeContextBoundaryTest.php b/tests/Sentry/State/RuntimeContextBoundaryTest.php index ecf83c9ca1..9223d5d7db 100644 --- a/tests/Sentry/State/RuntimeContextBoundaryTest.php +++ b/tests/Sentry/State/RuntimeContextBoundaryTest.php @@ -8,7 +8,8 @@ use Hypervel\Sentry\State\CoroutineRuntimeContextStorage; use Hypervel\Sentry\State\RuntimeContextBoundary; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Sentry\ClientInterface; use Sentry\Options; use Sentry\SentrySdk; @@ -19,17 +20,18 @@ class RuntimeContextBoundaryTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; public function testStartsContextWithHypervelHubAndFlushesAtCoroutineExit(): void { $storage = new CoroutineRuntimeContextStorage; - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions')->once()->andReturn(new Options); - $client->shouldReceive('flush') - ->once() + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('getOptions')->returns(new Options); + $client->expects('flush') ->with(null) - ->andReturn(new Result(ResultStatus::success())); + ->returns(new Result(ResultStatus::success())); $hub = new Hub($client); $boundary = new RuntimeContextBoundary($hub, $storage); @@ -49,12 +51,11 @@ public function testStartsContextWithHypervelHubAndFlushesAtCoroutineExit(): voi public function testReusesActiveContextWithoutRegisteringAnotherEnd(): void { $storage = new CoroutineRuntimeContextStorage; - $client = m::mock(ClientInterface::class); - $client->shouldReceive('getOptions')->once()->andReturn(new Options); - $client->shouldReceive('flush') - ->once() + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('getOptions')->returns(new Options); + $client->expects('flush') ->with(null) - ->andReturn(new Result(ResultStatus::success())); + ->returns(new Result(ResultStatus::success())); $boundary = new RuntimeContextBoundary(new Hub($client), $storage); SentrySdk::init(); @@ -73,8 +74,8 @@ public function testReusesActiveContextWithoutRegisteringAnotherEnd(): void public function testDoesNothingOutsideACoroutine(): void { $storage = new CoroutineRuntimeContextStorage; - $client = m::mock(ClientInterface::class); - $client->shouldNotReceive('flush'); + $client = Double::for(ClientInterface::class)->strict(); + $client->expects('flush')->never(); $boundary = new RuntimeContextBoundary(new Hub($client), $storage); SentrySdk::init(); diff --git a/tests/Sentry/Tracing/EventHandlerTest.php b/tests/Sentry/Tracing/EventHandlerTest.php index 11c1cf6067..39306d688b 100644 --- a/tests/Sentry/Tracing/EventHandlerTest.php +++ b/tests/Sentry/Tracing/EventHandlerTest.php @@ -18,7 +18,8 @@ use Hypervel\Routing\Events\ResponsePrepared; use Hypervel\Sentry\Tracing\EventHandler; use Hypervel\Tests\Sentry\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\TestWith; use ReflectionClass; @@ -33,6 +34,8 @@ class EventHandlerTest extends TestCase { + use VerifiesDoubles; + protected array $defaultSetupConfig = [ 'sentry.traces_sample_rate' => 1.0, ]; @@ -139,14 +142,12 @@ public function testNullQueryTimeCreatesAnInstantaneousSpanWithoutOriginResoluti public function testThrowableFromInstrumentationDoesNotReachApplicationCode(): void { $this->startTransaction(); - $connection = m::mock(Connection::class); - $connection->shouldReceive('getName')->once()->andReturn('throwing'); - $connection->shouldReceive('getDatabaseName')->once()->andThrow(new Error('broken instrumentation')); + $connection = Double::for(Connection::class)->strict(); + $connection->expects('getName')->returns('throwing'); + $connection->expects('getDatabaseName')->throws(new Error('broken instrumentation')); $handler = new EventHandler(config()->array('sentry.tracing')); $handler->queryExecuted(new QueryExecuted('select 1', [], 1.0, $connection)); - - $this->addToAssertionCount(1); } #[TestWith([false], 'direct cancellation')] @@ -160,9 +161,9 @@ public function testCancellationFromInstrumentationReachesApplicationCode(bool $ $cancellation = new RuntimeException('Instrumentation cleanup failed.', previous: $cancellation); } - $connection = m::mock(Connection::class); - $connection->shouldReceive('getName')->once()->andReturn('canceled'); - $connection->shouldReceive('getDatabaseName')->once()->andThrow($cancellation); + $connection = Double::for(Connection::class)->strict(); + $connection->expects('getName')->returns('canceled'); + $connection->expects('getDatabaseName')->throws($cancellation); $handler = new EventHandler(config()->array('sentry.tracing')); $caught = null; diff --git a/tests/Sentry/VersionTest.php b/tests/Sentry/VersionTest.php index 181f15c530..b8a5babc36 100644 --- a/tests/Sentry/VersionTest.php +++ b/tests/Sentry/VersionTest.php @@ -9,17 +9,19 @@ use Hypervel\Foundation\PackageManifest; use Hypervel\Sentry\Version; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class VersionTest extends TestCase { + use VerifiesDoubles; + public function testSdkVersionIsTheInstalledPackageVersion(): void { - $manifest = m::mock(PackageManifest::class); - $manifest->shouldReceive('version') - ->once() + $manifest = Double::for(PackageManifest::class)->strict(); + $manifest->expects('version') ->with('hypervel/sentry') - ->andReturn('1.2.3'); + ->returns('1.2.3'); Container::getInstance()->singleton(PackageManifest::class, fn () => $manifest); @@ -28,11 +30,10 @@ public function testSdkVersionIsTheInstalledPackageVersion(): void public function testSdkVersionFallsBackToTheFrameworkVersion(): void { - $manifest = m::mock(PackageManifest::class); - $manifest->shouldReceive('version') - ->once() + $manifest = Double::for(PackageManifest::class)->strict(); + $manifest->expects('version') ->with('hypervel/sentry') - ->andReturn(null); + ->returns(null); Container::getInstance()->singleton(PackageManifest::class, fn () => $manifest); diff --git a/tests/Sentry/WebSocketRuntimeContextTest.php b/tests/Sentry/WebSocketRuntimeContextTest.php index 629d7481d7..64e065473c 100644 --- a/tests/Sentry/WebSocketRuntimeContextTest.php +++ b/tests/Sentry/WebSocketRuntimeContextTest.php @@ -17,12 +17,12 @@ use Hypervel\Routing\Route; use Hypervel\Routing\Router; use Hypervel\WebSocketServer\Collector\FdCollector; -use Hypervel\WebSocketServer\Context as WebSocketContext; use Hypervel\WebSocketServer\Events\ConnectionClosed; use Hypervel\WebSocketServer\Events\ConnectionOpening; use Hypervel\WebSocketServer\Security; use Hypervel\WebSocketServer\Server; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Sentry\EventType; use Sentry\Logs\Log; use Sentry\Metrics\Types\Metric; @@ -39,6 +39,8 @@ class WebSocketRuntimeContextTest extends TestCase { + use VerifiesDoubles; + public function testRejectedHandshakeFlushesTelemetryRecordedBeforeValidation(): void { $this->app->make('events')->listen(ConnectionOpening::class, static function (): void { @@ -47,8 +49,8 @@ public function testRejectedHandshakeFlushesTelemetryRecordedBeforeValidation(): $server = new SentryWebSocketServer( $this->app, - m::mock(Router::class)->shouldIgnoreMissing(), - m::mock(SwooleWebSocketServer::class), + Double::for(Router::class)->strict(), + Double::for(SwooleWebSocketServer::class)->strict(), ); $request = $this->handshakeRequest(validSecurityKey: false); $response = $this->handshakeResponse(Response::HTTP_INTERNAL_SERVER_ERROR, 'Handshake failed.'); @@ -73,17 +75,17 @@ public function testOpeningContextIncludesDeferredOnOpenTelemetry(): void }; $this->app->instance(SentryWebSocketRuntimeHandler::class, $handler); - $route = m::mock(Route::class); - $route->shouldReceive('getControllerClass')->andReturn(SentryWebSocketRuntimeHandler::class); - $router = m::mock(Router::class); - $router->shouldReceive('dispatchToCallback')->once() - ->andReturnUsing(static function (HttpRequest $request) use ($route): Response { + $route = Double::for(Route::class)->strict(); + $route->allows('getControllerClass')->returns(SentryWebSocketRuntimeHandler::class); + $router = Double::for(Router::class)->strict(); + $router->expects('dispatchToCallback') + ->resolves(static function (HttpRequest $request) use ($route): Response { $request->setRouteResolver(static fn (): Route => $route); return new Response('', Response::HTTP_SWITCHING_PROTOCOLS); }); - $nativeServer = m::mock(SwooleWebSocketServer::class); - $nativeServer->shouldReceive('isEstablished')->once()->with(42)->andReturnTrue(); + $nativeServer = Double::for(SwooleWebSocketServer::class)->strict(); + $nativeServer->expects('isEstablished')->with(42)->returns(true); $server = new SentryWebSocketServer($this->app, $router, $nativeServer); $request = $this->handshakeRequest(); $response = $this->handshakeResponse(Response::HTTP_SWITCHING_PROTOCOLS); @@ -129,7 +131,7 @@ public function testConcurrentMessagesFlushIsolatedTelemetry(): void FdCollector::set(2, SentryWebSocketRuntimeHandler::class); $server = new Server($this->app); - $nativeServer = m::mock(SwooleWebSocketServer::class); + $nativeServer = Double::for(SwooleWebSocketServer::class)->strict(); $firstCoroutineId = Coroutine::create(static function () use ($server, $nativeServer): void { $server->onMessage($nativeServer, self::frame(1, 'first')); }); @@ -170,7 +172,7 @@ public function testClosingContextFlushesAfterHandlerAndCompletionEvent(): void FdCollector::set(42, SentryWebSocketRuntimeHandler::class); $server = new Server($this->app); - $nativeServer = m::mock(SwooleServer::class); + $nativeServer = Double::for(SwooleServer::class)->strict(); $coroutineId = Coroutine::create(static function () use ($server, $nativeServer): void { $server->onClose($nativeServer, 42, 0); }); @@ -186,7 +188,7 @@ public function testClosingContextFlushesAfterHandlerAndCompletionEvent(): void */ private function handshakeRequest(bool $validSecurityKey = true): SwooleRequest { - $request = m::mock(SwooleRequest::class); + $request = Double::for(SwooleRequest::class)->strict(); $request->fd = 42; $request->server = [ 'request_method' => 'get', @@ -201,7 +203,7 @@ private function handshakeRequest(bool $validSecurityKey = true): SwooleRequest $request->post = []; $request->cookie = []; $request->files = []; - $request->shouldReceive('rawContent')->once()->andReturnFalse(); + $request->expects('rawContent')->returns(false); return $request; } @@ -211,10 +213,10 @@ private function handshakeRequest(bool $validSecurityKey = true): SwooleRequest */ private function handshakeResponse(int $status, string $content = ''): SwooleResponse { - $response = m::mock(SwooleResponse::class); - $response->shouldReceive('status')->once()->with($status)->andReturnTrue(); - $response->shouldReceive('header')->zeroOrMoreTimes()->andReturnTrue(); - $response->shouldReceive('end')->once()->with($content)->andReturnTrue(); + $response = Double::for(SwooleResponse::class)->strict(); + $response->expects('status')->with($status)->returns(true); + $response->allows('header')->returns(true); + $response->expects('end')->with($content)->returns(true); return $response; } @@ -273,24 +275,22 @@ private function capturedMetricBatches(): array ); } + /** + * Release the worker-start coordinator before handling connections. + */ protected function setUp(): void { parent::setUp(); CoordinatorManager::until(Constants::WORKER_START)->resume(); } - - protected function tearDown(): void - { - FdCollector::flushState(); - WebSocketContext::flushState(); - - parent::tearDown(); - } } class SentryWebSocketServer extends Server { + /** + * Create a server with the test router and native transport. + */ public function __construct( Container $container, private readonly Router $router, diff --git a/tests/Server/Listeners/InitProcessTitleListenerTest.php b/tests/Server/Listeners/InitProcessTitleListenerTest.php index 3ff5236382..6b683d6fbe 100644 --- a/tests/Server/Listeners/InitProcessTitleListenerTest.php +++ b/tests/Server/Listeners/InitProcessTitleListenerTest.php @@ -5,14 +5,13 @@ namespace Hypervel\Tests\Server\Listeners; use Hypervel\Config\Repository as ConfigRepository; +use Hypervel\Container\Container; use Hypervel\Context\CoroutineContext; -use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\ServerProcess\Events\BeforeProcessHandle; use Hypervel\Tests\Server\Fixtures\DemoProcess; use Hypervel\Tests\Server\Fixtures\InitProcessTitleListenerStub; use Hypervel\Tests\Server\Fixtures\InitProcessTitleListenerStub2; use Hypervel\Tests\TestCase; -use Mockery as m; class InitProcessTitleListenerTest extends TestCase { @@ -85,11 +84,11 @@ public function testProcessNameUsesTheReloadedConfigRepository(): void } } + /** + * Create the process without an event dispatcher. + */ private function process(): DemoProcess { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturnFalse(); - - return new DemoProcess($container); + return new DemoProcess(new Container); } } diff --git a/tests/Server/ServerFactoryTest.php b/tests/Server/ServerFactoryTest.php index 52bd842cbe..e7f1c4cfca 100644 --- a/tests/Server/ServerFactoryTest.php +++ b/tests/Server/ServerFactoryTest.php @@ -4,20 +4,23 @@ namespace Hypervel\Tests\Server; -use Hypervel\Contracts\Container\Container; +use Hypervel\Container\Container; use Hypervel\Server\ServerConfig; use Hypervel\Server\ServerFactory; use Hypervel\Server\ServerInterface; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Swoole\Server as SwooleServer; class ServerFactoryTest extends TestCase { + use VerifiesDoubles; + public function testExplicitServerInjectionAcceptsAnyInterfaceImplementation(): void { - $server = new ServerFactoryTestServer(m::mock(SwooleServer::class)); - $factory = new ServerFactory(m::mock(Container::class)); + $server = new ServerFactoryTestServer(Double::for(SwooleServer::class)->strict()); + $factory = new ServerFactory(new Container); $this->assertSame($factory, $factory->setServer($server)); @@ -40,10 +43,16 @@ class ServerFactoryTestServer implements ServerInterface public bool $started = false; + /** + * Create a server wrapper with the supplied native server. + */ public function __construct(private SwooleServer $server) { } + /** + * Record the server configuration. + */ public function init(ServerConfig $config): ServerInterface { $this->config = $config; @@ -51,11 +60,17 @@ public function init(ServerConfig $config): ServerInterface return $this; } + /** + * Record that the server was started. + */ public function start(): void { $this->started = true; } + /** + * Return the supplied native server. + */ public function getServer(): SwooleServer { return $this->server; diff --git a/tests/Server/ServerNativeTest.php b/tests/Server/ServerNativeTest.php index b5f5ec3589..ce39dc9e21 100644 --- a/tests/Server/ServerNativeTest.php +++ b/tests/Server/ServerNativeTest.php @@ -14,13 +14,16 @@ use Hypervel\Server\ServerInterface; use Hypervel\Server\ServerManager; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use Psr\Log\LoggerInterface; use Swoole\Exception as SwooleException; class ServerNativeTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; // A real Swoole\Server owns process-global native lifecycle state that a reusable @@ -34,21 +37,21 @@ public function testSecondarySettingsFailureStopsConfigurationBeforePublication( } $events = []; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(BeforeMainServerStart::class)->andReturnTrue(); - $dispatcher->shouldReceive('hasListeners')->once()->with(BeforeServerStart::class)->andReturnTrue(); - $dispatcher->expects('dispatch')->twice()->andReturnUsing( + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('hasListeners')->with(BeforeMainServerStart::class)->returns(true); + $dispatcher->expects('hasListeners')->with(BeforeServerStart::class)->returns(true); + $dispatcher->expects('dispatch')->times(2)->resolves( static function (object $event) use (&$events): null { $events[] = $event; return null; }, ); - $container = m::mock(Container::class); - $container->shouldNotReceive('has'); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('has')->never(); $server = new ServerNativeTestServer( - $container, - m::mock(LoggerInterface::class), + $container->instance(), + Double::for(LoggerInterface::class)->strict(), $dispatcher, ); @@ -95,6 +98,9 @@ static function (object $event) use (&$events): null { class ServerNativeTestServer extends Server { + /** + * Keep unrelated native callbacks out of the configuration test. + */ protected function defaultCallbacks(): array { return []; @@ -103,6 +109,9 @@ protected function defaultCallbacks(): array class ServerNativeBeforeStartCallback { + /** + * Accept the secondary server startup callback. + */ public function handle(): void { } diff --git a/tests/Server/ServerReloadCommandTest.php b/tests/Server/ServerReloadCommandTest.php index 17304af265..6401864ec7 100644 --- a/tests/Server/ServerReloadCommandTest.php +++ b/tests/Server/ServerReloadCommandTest.php @@ -10,7 +10,8 @@ use Hypervel\Server\Commands\ServerReloadCommand; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Swoole\Constant; use Symfony\Component\Console\Command\Command; @@ -18,10 +19,12 @@ class ServerReloadCommandTest extends TestCase { + use VerifiesDoubles; + public function testReloadCommandThrowsCommandExceptionWhenPidFileConfigIsMissing(): void { - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldNotReceive('get'); + $filesystem = Double::for(Filesystem::class)->strict(); + $filesystem->expects('get')->never(); $command = $this->reloadCommand([], $filesystem); $this->expectException(InvalidArgumentException::class); @@ -32,8 +35,8 @@ public function testReloadCommandThrowsCommandExceptionWhenPidFileConfigIsMissin public function testReloadCommandFailsWhenPidFileCannotBeRead(): void { - $filesystem = m::mock(Filesystem::class); - $filesystem->expects('get')->with('/tmp/hypervel.pid')->andThrow( + $filesystem = Double::for(Filesystem::class)->strict(); + $filesystem->expects('get')->with('/tmp/hypervel.pid')->throws( new FileNotFoundException('File does not exist.') ); $command = $this->reloadCommand($this->settings(), $filesystem); @@ -50,8 +53,8 @@ public function testReloadCommandFailsWhenPidFileCannotBeRead(): void #[DataProvider('invalidProcessIds')] public function testReloadCommandRejectsInvalidProcessIds(string $contents): void { - $filesystem = m::mock(Filesystem::class); - $filesystem->expects('get')->with('/tmp/hypervel.pid')->andReturn($contents); + $filesystem = Double::for(Filesystem::class)->strict(); + $filesystem->expects('get')->with('/tmp/hypervel.pid')->returns($contents); $command = $this->reloadCommand($this->settings(), $filesystem); $tester = new CommandTester($command); @@ -63,6 +66,9 @@ public function testReloadCommandRejectsInvalidProcessIds(string $contents): voi $this->assertSame([], $command->signals); } + /** + * Provide invalid PID-file contents. + */ public static function invalidProcessIds(): array { return [ @@ -77,8 +83,8 @@ public static function invalidProcessIds(): array public function testReloadCommandSignalsEventWorkers(): void { - $filesystem = m::mock(Filesystem::class); - $filesystem->expects('get')->with('/tmp/hypervel.pid')->andReturn("123\n"); + $filesystem = Double::for(Filesystem::class)->strict(); + $filesystem->expects('get')->with('/tmp/hypervel.pid')->returns("123\n"); $command = $this->reloadCommand($this->settings(), $filesystem); $command->returnSignalResults(true); $tester = new CommandTester($command); @@ -92,8 +98,8 @@ public function testReloadCommandSignalsEventWorkers(): void public function testReloadCommandSignalsEventAndTaskWorkers(): void { - $filesystem = m::mock(Filesystem::class); - $filesystem->expects('get')->with('/tmp/hypervel.pid')->andReturn('123'); + $filesystem = Double::for(Filesystem::class)->strict(); + $filesystem->expects('get')->with('/tmp/hypervel.pid')->returns('123'); $command = $this->reloadCommand($this->settings(taskWorkers: 2), $filesystem); $command->returnSignalResults(true, true); $tester = new CommandTester($command); @@ -106,8 +112,8 @@ public function testReloadCommandSignalsEventAndTaskWorkers(): void public function testReloadCommandFailsWhenEventWorkersCannotBeSignaled(): void { - $filesystem = m::mock(Filesystem::class); - $filesystem->expects('get')->with('/tmp/hypervel.pid')->andReturn('123'); + $filesystem = Double::for(Filesystem::class)->strict(); + $filesystem->expects('get')->with('/tmp/hypervel.pid')->returns('123'); $command = $this->reloadCommand($this->settings(taskWorkers: 2), $filesystem); $command->returnSignalResults(false); $tester = new CommandTester($command); @@ -121,8 +127,8 @@ public function testReloadCommandFailsWhenEventWorkersCannotBeSignaled(): void public function testReloadCommandFailsWhenTaskWorkersCannotBeSignaled(): void { - $filesystem = m::mock(Filesystem::class); - $filesystem->expects('get')->with('/tmp/hypervel.pid')->andReturn('123'); + $filesystem = Double::for(Filesystem::class)->strict(); + $filesystem->expects('get')->with('/tmp/hypervel.pid')->returns('123'); $command = $this->reloadCommand($this->settings(taskWorkers: 2), $filesystem); $command->returnSignalResults(true, false); $tester = new CommandTester($command); @@ -133,6 +139,9 @@ public function testReloadCommandFailsWhenTaskWorkersCannotBeSignaled(): void $this->assertStringNotContainsString('Done.', $tester->getDisplay()); } + /** + * Create a reload command with the supplied configuration and filesystem. + */ private function reloadCommand(array $config, Filesystem $filesystem): ServerReloadCommandTestCommand { $command = new ServerReloadCommandTestCommand(new Repository($config), $filesystem); @@ -141,6 +150,9 @@ private function reloadCommand(array $config, Filesystem $filesystem): ServerRel return $command; } + /** + * Provide server PID and worker settings. + */ private function settings(int $taskWorkers = 0): array { return [ @@ -162,11 +174,17 @@ class ServerReloadCommandTestCommand extends ServerReloadCommand /** @var list */ private array $signalResults = []; + /** + * Set the results returned by successive signal attempts. + */ public function returnSignalResults(bool ...$results): void { $this->signalResults = $results; } + /** + * Record the signal and return its configured result. + */ protected function signalProcess(int $pid, int $signal): bool { $this->signals[] = [$pid, $signal]; diff --git a/tests/Server/ServerStartCommandTest.php b/tests/Server/ServerStartCommandTest.php index d5bf9a6b65..bf28af3379 100644 --- a/tests/Server/ServerStartCommandTest.php +++ b/tests/Server/ServerStartCommandTest.php @@ -4,8 +4,8 @@ namespace Hypervel\Tests\Server; +use Hypervel\Config\Repository; use Hypervel\Console\Command as ConsoleCommand; -use Hypervel\Contracts\Config\Repository; use Hypervel\Contracts\Events\Dispatcher as DispatcherContract; use Hypervel\Contracts\Log\StdoutLoggerInterface; use Hypervel\Foundation\Application; @@ -14,7 +14,8 @@ use Hypervel\Server\ServerInterface; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Symfony\Component\Console\Command\Command as SymfonyCommand; @@ -23,6 +24,8 @@ class ServerStartCommandTest extends TestCase { + use VerifiesDoubles; + // REMOVED: ServeCommandLogParserTest; Swoole does not emit PHP's built-in-server request logs. public function testServeCommandFailsFastWhenRunningInConsoleIsTrue(): void @@ -58,17 +61,16 @@ public function testServeCommandStartsServerWhenRunningInConsoleIsFalse(): void ], ]; - $serverFactory = m::mock(ServerFactory::class); - $serverFactory->shouldReceive('setEventDispatcher')->once()->andReturnSelf(); - $serverFactory->shouldReceive('setLogger')->once()->andReturnSelf(); - $serverFactory->shouldReceive('configure')->once()->with($serverConfig); - $serverFactory->shouldReceive('start')->once(); + $serverFactory = Double::for(ServerFactory::class)->strict(); + $serverFactory->expects('setEventDispatcher'); + $serverFactory->expects('setLogger'); + $serverFactory->expects('configure')->with($serverConfig); + $serverFactory->expects('start'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->once()->with('server')->andReturn($serverConfig); + $config = new Repository(['server' => $serverConfig]); - $dispatcher = m::mock(DispatcherContract::class); - $logger = m::mock(StdoutLoggerInterface::class); + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); $this->app->instance(ServerFactory::class, $serverFactory); $this->app->instance('events', $dispatcher); @@ -118,18 +120,16 @@ public function testServeCommandOverridesHttpServerHostAndPort(): void ], ]; - $serverFactory = m::mock(ServerFactory::class); - $serverFactory->shouldReceive('setEventDispatcher')->once()->andReturnSelf(); - $serverFactory->shouldReceive('setLogger')->once()->andReturnSelf(); - $serverFactory->shouldReceive('configure')->once()->with(['servers' => $expectedServers]); - $serverFactory->shouldReceive('start')->once(); + $serverFactory = Double::for(ServerFactory::class)->strict(); + $serverFactory->expects('setEventDispatcher'); + $serverFactory->expects('setLogger'); + $serverFactory->expects('configure')->with(['servers' => $expectedServers]); + $serverFactory->expects('start'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->once()->with('server')->andReturn($serverConfig); - $config->shouldReceive('set')->once()->with('server.servers', $expectedServers); + $config = new Repository(['server' => $serverConfig]); - $dispatcher = m::mock(DispatcherContract::class); - $logger = m::mock(StdoutLoggerInterface::class); + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); $this->app->instance(ServerFactory::class, $serverFactory); $this->app->instance('events', $dispatcher); @@ -146,6 +146,7 @@ public function testServeCommandOverridesHttpServerHostAndPort(): void ]), new NullOutput); $this->assertSame(0, $result); + $this->assertSame($expectedServers, $config->array('server.servers')); } public function testServeCommandOverridesHostAndPortForTheDefaultHttpServerType(): void @@ -168,18 +169,16 @@ public function testServeCommandOverridesHostAndPortForTheDefaultHttpServerType( ], ]; - $serverFactory = m::mock(ServerFactory::class); - $serverFactory->shouldReceive('setEventDispatcher')->once()->andReturnSelf(); - $serverFactory->shouldReceive('setLogger')->once()->andReturnSelf(); - $serverFactory->shouldReceive('configure')->once()->with(['servers' => $expectedServers]); - $serverFactory->shouldReceive('start')->once(); + $serverFactory = Double::for(ServerFactory::class)->strict(); + $serverFactory->expects('setEventDispatcher'); + $serverFactory->expects('setLogger'); + $serverFactory->expects('configure')->with(['servers' => $expectedServers]); + $serverFactory->expects('start'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->once()->with('server')->andReturn($serverConfig); - $config->shouldReceive('set')->once()->with('server.servers', $expectedServers); + $config = new Repository(['server' => $serverConfig]); - $dispatcher = m::mock(DispatcherContract::class); - $logger = m::mock(StdoutLoggerInterface::class); + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); $this->app->instance(ServerFactory::class, $serverFactory); $this->app->instance('events', $dispatcher); @@ -196,6 +195,7 @@ public function testServeCommandOverridesHostAndPortForTheDefaultHttpServerType( ]), new NullOutput); $this->assertSame(0, $result); + $this->assertSame($expectedServers, $config->array('server.servers')); } #[DataProvider('hostAndPortProvider')] @@ -221,9 +221,9 @@ public function testHostAndPortParsing( 'sock_type' => $expectedSocketType, ]); - $serverFactory = m::mock(ServerFactory::class); - $serverFactory->shouldReceive('setEventDispatcher')->once()->andReturnSelf(); - $serverFactory->shouldReceive('setLogger')->once()->andReturnSelf(); + $serverFactory = Double::for(ServerFactory::class)->strict(); + $serverFactory->expects('setEventDispatcher'); + $serverFactory->expects('setLogger'); $serverFactory->expects('configure')->with(['servers' => [$expectedServer]]); $serverFactory->expects('start'); $this->app->instance(ServerFactory::class, $serverFactory); @@ -265,12 +265,11 @@ public static function hostAndPortProvider(): array #[DataProvider('invalidServePorts')] public function testServeCommandRejectsInvalidPortOption(array $options): void { - $serverFactory = m::mock(ServerFactory::class); - $serverFactory->shouldReceive('setEventDispatcher')->once()->andReturnSelf(); - $serverFactory->shouldReceive('setLogger')->once()->andReturnSelf(); + $serverFactory = Double::for(ServerFactory::class)->strict(); + $serverFactory->expects('setEventDispatcher'); + $serverFactory->expects('setLogger'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->once()->with('server')->andReturn([ + $config = new Repository(['server' => [ 'servers' => [ [ 'name' => 'http', @@ -279,10 +278,10 @@ public function testServeCommandRejectsInvalidPortOption(array $options): void 'port' => 8000, ], ], - ]); + ]]); - $dispatcher = m::mock(DispatcherContract::class); - $logger = m::mock(StdoutLoggerInterface::class); + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); $this->app->instance(ServerFactory::class, $serverFactory); $this->app->instance('events', $dispatcher); @@ -318,12 +317,11 @@ public static function invalidServePorts(): array public function testServeCommandRejectsAddressOptionsWithoutHttpServer(): void { - $serverFactory = m::mock(ServerFactory::class); - $serverFactory->shouldReceive('setEventDispatcher')->once()->andReturnSelf(); - $serverFactory->shouldReceive('setLogger')->once()->andReturnSelf(); + $serverFactory = Double::for(ServerFactory::class)->strict(); + $serverFactory->expects('setEventDispatcher'); + $serverFactory->expects('setLogger'); - $config = m::mock(Repository::class); - $config->shouldReceive('array')->once()->with('server')->andReturn([ + $config = new Repository(['server' => [ 'servers' => [ [ 'name' => 'reverb', @@ -332,10 +330,10 @@ public function testServeCommandRejectsAddressOptionsWithoutHttpServer(): void 'port' => 8080, ], ], - ]); + ]]); - $dispatcher = m::mock(DispatcherContract::class); - $logger = m::mock(StdoutLoggerInterface::class); + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); $this->app->instance(ServerFactory::class, $serverFactory); $this->app->instance('events', $dispatcher); diff --git a/tests/Server/ServerTest.php b/tests/Server/ServerTest.php index e5da0dc485..77fa78cf34 100644 --- a/tests/Server/ServerTest.php +++ b/tests/Server/ServerTest.php @@ -25,7 +25,9 @@ use Hypervel\Server\ServerManager; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use Psr\Log\LoggerInterface; use RuntimeException; @@ -37,58 +39,60 @@ class ServerTest extends TestCase { + use VerifiesDoubles; + public function testResponseCallbackReportsAnEscapedExceptionAndCompletesTheResponse(): void { $exception = new RuntimeException('request callback failed'); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $handler->expects('report')->with($exception); - $container = m::mock(Container::class); - $container->expects('make')->with(ExceptionHandler::class)->andReturn($handler); - $response = m::mock(SwooleResponse::class); - $response->expects('isWritable')->andReturnTrue(); - $response->expects('end')->andReturnTrue(); - $callback = $this->server($container)->guardedResponseCallback( + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(ExceptionHandler::class)->returns($handler); + $response = Double::for(SwooleResponse::class)->strict(); + $response->expects('isWritable')->returns(true); + $response->expects('end')->returns(true); + $callback = $this->server($container->instance())->guardedResponseCallback( static function (SwooleRequest $request, SwooleResponse $response) use ($exception): never { throw $exception; }, ); - $callback(m::mock(SwooleRequest::class), $response); + $callback(Double::for(SwooleRequest::class)->strict(), $response); } public function testResponseCallbackDoesNotReportCancellation(): void { - $container = m::mock(Container::class); - $container->shouldNotReceive('make'); - $response = m::mock(SwooleResponse::class); - $response->expects('isWritable')->andReturnTrue(); - $response->expects('end')->andReturnTrue(); - $callback = $this->server($container)->guardedResponseCallback( + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->never(); + $response = Double::for(SwooleResponse::class)->strict(); + $response->expects('isWritable')->returns(true); + $response->expects('end')->returns(true); + $callback = $this->server($container->instance())->guardedResponseCallback( static function (SwooleRequest $request, SwooleResponse $response): never { throw new CanceledException; }, ); - $callback(m::mock(SwooleRequest::class), $response); + $callback(Double::for(SwooleRequest::class)->strict(), $response); } public function testResponseCallbackDoesNotCompleteAnUnwritableResponse(): void { $exception = new RuntimeException('request callback failed'); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $handler->expects('report')->with($exception); - $container = m::mock(Container::class); - $container->expects('make')->with(ExceptionHandler::class)->andReturn($handler); - $response = m::mock(SwooleResponse::class); - $response->expects('isWritable')->andReturnFalse(); - $response->shouldNotReceive('end'); - $callback = $this->server($container)->guardedResponseCallback( + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(ExceptionHandler::class)->returns($handler); + $response = Double::for(SwooleResponse::class)->strict(); + $response->expects('isWritable')->returns(false); + $response->expects('end')->never(); + $callback = $this->server($container->instance())->guardedResponseCallback( static function (SwooleRequest $request, SwooleResponse $response) use ($exception): never { throw $exception; }, ); - $callback(m::mock(SwooleRequest::class), $response); + $callback(Double::for(SwooleRequest::class)->strict(), $response); } public function testResponseCallbackFallsBackToThePhpErrorLogAndContainsCompletionFailures(): void @@ -99,21 +103,21 @@ public function testResponseCallbackFallsBackToThePhpErrorLogAndContainsCompleti $errorLog = $directory . '/php-error.log'; $previousErrorLog = ini_set('error_log', $errorLog); $exception = new RuntimeException('request callback failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->expects('report')->with($exception)->andThrow(new RuntimeException('reporting failed')); - $container = m::mock(Container::class); - $container->expects('make')->with(ExceptionHandler::class)->andReturn($handler); - $response = m::mock(SwooleResponse::class); - $response->expects('isWritable')->andReturnTrue(); - $response->expects('end')->andThrow(new RuntimeException('completion failed')); - $callback = $this->server($container)->guardedResponseCallback( + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($exception)->throws(new RuntimeException('reporting failed')); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(ExceptionHandler::class)->returns($handler); + $response = Double::for(SwooleResponse::class)->strict(); + $response->expects('isWritable')->returns(true); + $response->expects('end')->throws(new RuntimeException('completion failed')); + $callback = $this->server($container->instance())->guardedResponseCallback( static function (SwooleRequest $request, SwooleResponse $response) use ($exception): never { throw $exception; }, ); try { - $callback(m::mock(SwooleRequest::class), $response); + $callback(Double::for(SwooleRequest::class)->strict(), $response); $contents = file_get_contents($errorLog); $this->assertIsString($contents); @@ -145,8 +149,8 @@ public function testResponseAndWorkerDeliveryEventsReceiveTheirCallbackGuards(): $workerCallback = static function (): void { }; $registered = []; - $nativeServer = m::mock(SwooleServer::class); - $nativeServer->expects('on')->times(7)->andReturnUsing( + $nativeServer = Double::for(SwooleServer::class)->strict(); + $nativeServer->expects('on')->times(7)->resolves( static function (string $event, callable $callback) use (&$registered): bool { $registered[$event] = $callback; @@ -154,7 +158,7 @@ static function (string $event, callable $callback) use (&$registered): bool { }, ); - $this->server(m::mock(Container::class))->registerEvents($nativeServer, [ + $this->server(Double::for(Container::class, override: true)->strict()->instance())->registerEvents($nativeServer, [ Event::ON_REQUEST => $requestCallback, Event::ON_HANDSHAKE => $handshakeCallback, Event::ON_PIPE_MESSAGE => $pipeCallback, @@ -176,30 +180,30 @@ static function (string $event, callable $callback) use (&$registered): bool { public function testWorkerDeliveryCallbackReportsAnEscapedException(): void { $exception = new RuntimeException('worker delivery callback failed'); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $handler->expects('report')->with($exception); - $container = m::mock(Container::class); - $container->expects('make')->with(ExceptionHandler::class)->andReturn($handler); - $callback = $this->server($container)->guardedWorkerDeliveryCallback( + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(ExceptionHandler::class)->returns($handler); + $callback = $this->server($container->instance())->guardedWorkerDeliveryCallback( static function (SwooleServer $server, int $sourceId, mixed $data) use ($exception): never { throw $exception; }, ); - $callback(m::mock(SwooleServer::class), 1, ['message' => true]); + $callback(Double::for(SwooleServer::class)->strict(), 1, ['message' => true]); } public function testWorkerDeliveryCallbackDoesNotReportCancellation(): void { - $container = m::mock(Container::class); - $container->shouldNotReceive('make'); - $callback = $this->server($container)->guardedWorkerDeliveryCallback( + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->never(); + $callback = $this->server($container->instance())->guardedWorkerDeliveryCallback( static function (SwooleServer $server, int $sourceId, mixed $data): never { throw new CanceledException; }, ); - $callback(m::mock(SwooleServer::class), 1, ['message' => true]); + $callback(Double::for(SwooleServer::class)->strict(), 1, ['message' => true]); } public function testWorkerDeliveryCallbackFallsBackToThePhpErrorLog(): void @@ -210,18 +214,18 @@ public function testWorkerDeliveryCallbackFallsBackToThePhpErrorLog(): void $errorLog = $directory . '/php-error.log'; $previousErrorLog = ini_set('error_log', $errorLog); $exception = new RuntimeException('worker delivery callback failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->expects('report')->with($exception)->andThrow(new RuntimeException('reporting failed')); - $container = m::mock(Container::class); - $container->expects('make')->with(ExceptionHandler::class)->andReturn($handler); - $callback = $this->server($container)->guardedWorkerDeliveryCallback( + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($exception)->throws(new RuntimeException('reporting failed')); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(ExceptionHandler::class)->returns($handler); + $callback = $this->server($container->instance())->guardedWorkerDeliveryCallback( static function (SwooleServer $server, int $sourceId, mixed $data) use ($exception): never { throw $exception; }, ); try { - $callback(m::mock(SwooleServer::class), 1, ['message' => true]); + $callback(Double::for(SwooleServer::class)->strict(), 1, ['message' => true]); $contents = file_get_contents($errorLog); $this->assertIsString($contents); @@ -238,13 +242,13 @@ static function (SwooleServer $server, int $sourceId, mixed $data) use ($excepti public function testServerEventRegistrationFailureStopsConfiguration(): void { - $nativeServer = m::mock(SwooleServer::class); - $nativeServer->expects('on')->with(Event::ON_WORKER_START, m::type('callable'))->andReturnFalse(); + $nativeServer = Double::for(SwooleServer::class)->strict(); + $nativeServer->expects('on')->with(Event::ON_WORKER_START, Argument::type('callable'))->returns(false); $this->expectException(ServerException::class); $this->expectExceptionMessageIs('Failed to register event [workerStart] on server [test].'); - $this->server(m::mock(Container::class))->registerEvents($nativeServer, [ + $this->server(Double::for(Container::class, override: true)->strict()->instance())->registerEvents($nativeServer, [ Event::ON_WORKER_START => static function (): void { }, ]); @@ -252,10 +256,10 @@ public function testServerEventRegistrationFailureStopsConfiguration(): void public function testPortEventRegistrationFailureStopsConfiguration(): void { - $nativePort = m::mock(SwoolePort::class); - $nativePort->expects('on')->with(Event::ON_REQUEST, m::type('callable'))->andReturnFalse(); - $server = $this->server(m::mock(Container::class)); - $server->useNativeServer(m::mock(SwooleServer::class)); + $nativePort = Double::for(SwoolePort::class)->strict(); + $nativePort->expects('on')->with(Event::ON_REQUEST, Argument::type('callable'))->returns(false); + $server = $this->server(Double::for(Container::class, override: true)->strict()->instance()); + $server->useNativeServer(Double::for(SwooleServer::class)->strict()); $this->expectException(ServerException::class); $this->expectExceptionMessageIs('Failed to register event [request] on server [test].'); @@ -274,10 +278,10 @@ public function testDisconnectHandlingPreservesApplicationCallbacksAndRespectsSe $applicationCallback = static function (SwooleServer $server, int $connection, int $reactor) use (&$received): void { $received = [$server, $connection, $reactor]; }; - $nativeServer = m::mock(SwooleServer::class); + $nativeServer = Double::for(SwooleServer::class)->strict(); $nativeServer->mode = $mode; $nativeServer->setting = $settings; - $nativeServer->expects('on')->twice()->andReturnUsing( + $nativeServer->expects('on')->times(2)->resolves( static function (string $event, callable $callback) use (&$registered): bool { $registered[$event] = $callback; @@ -285,7 +289,7 @@ static function (string $event, callable $callback) use (&$registered): bool { }, ); - $this->server(m::mock(Container::class))->registerEvents($nativeServer, [ + $this->server(Double::for(Container::class, override: true)->strict()->instance())->registerEvents($nativeServer, [ Event::ON_REQUEST => static function (): void { }, Event::ON_CLOSE => $applicationCallback, @@ -315,9 +319,9 @@ public static function responseCancellationModes(): array public function testResponseDisconnectCallbackIsInstalledWithoutAnApplicationCallback(): void { $registered = []; - $nativeServer = m::mock(SwooleServer::class); + $nativeServer = Double::for(SwooleServer::class)->strict(); $nativeServer->mode = SWOOLE_PROCESS; - $nativeServer->expects('on')->twice()->andReturnUsing( + $nativeServer->expects('on')->times(2)->resolves( static function (string $event, callable $callback) use (&$registered): bool { $registered[$event] = $callback; @@ -325,7 +329,7 @@ static function (string $event, callable $callback) use (&$registered): bool { }, ); - $this->server(m::mock(Container::class))->registerEvents($nativeServer, [ + $this->server(Double::for(Container::class, override: true)->strict()->instance())->registerEvents($nativeServer, [ Event::ON_REQUEST => static function (): void { }, ]); @@ -336,9 +340,9 @@ static function (string $event, callable $callback) use (&$registered): bool { public function testMainServerSettingsFailureStopsConfiguration(): void { - $nativeServer = m::mock(SwooleServer::class); - $nativeServer->expects('set')->with([])->andReturnFalse(); - $server = $this->server(m::mock(Container::class)); + $nativeServer = Double::for(SwooleServer::class)->strict(); + $nativeServer->expects('set')->with([])->returns(false); + $server = $this->server(Double::for(Container::class, override: true)->strict()->instance()); $server->createWith($nativeServer); $this->expectException(ServerException::class); @@ -353,14 +357,14 @@ public function testMainServerSettingsFailureStopsConfiguration(): void public function testSecondaryServerSettingsFailureStopsConfigurationBeforeRegistration(): void { - $secondary = m::mock(SwoolePort::class); - $secondary->expects('set')->with([])->andReturnFalse(); - $secondary->shouldNotReceive('on'); - $nativeServer = m::mock(SwooleServer::class); - $nativeServer->ports = [m::mock(SwoolePort::class)]; - $nativeServer->expects('set')->with([])->andReturnTrue(); - $nativeServer->expects('addlistener')->with('127.0.0.1', 8001, SWOOLE_SOCK_TCP)->andReturn($secondary); - $server = $this->server(m::mock(Container::class)); + $secondary = Double::for(SwoolePort::class)->strict(); + $secondary->expects('set')->with([])->returns(false); + $secondary->expects('on')->never(); + $nativeServer = Double::for(SwooleServer::class)->strict(); + $nativeServer->ports = [Double::for(SwoolePort::class)->strict()]; + $nativeServer->expects('set')->with([])->returns(true); + $nativeServer->expects('addlistener')->with('127.0.0.1', 8001, SWOOLE_SOCK_TCP)->returns($secondary); + $server = $this->server(Double::for(Container::class, override: true)->strict()->instance()); $server->createWith($nativeServer); try { @@ -384,32 +388,32 @@ public function testSecondaryServerSettingsFailureStopsConfigurationBeforeRegist public function testEverySecondaryServerReceivesGlobalAndOnlyItsOwnSettings(): void { - $mainPort = m::mock(SwoolePort::class); - $firstSecondary = m::mock(SwoolePort::class); - $secondSecondary = m::mock(SwoolePort::class); - $nativeServer = m::mock(SwooleServer::class); + $mainPort = Double::for(SwoolePort::class)->strict(); + $firstSecondary = Double::for(SwoolePort::class)->strict(); + $secondSecondary = Double::for(SwoolePort::class)->strict(); + $nativeServer = Double::for(SwooleServer::class)->strict(); $nativeServer->ports = [$mainPort]; $nativeServer->expects('set')->with([ 'socket_buffer_size' => 2048, 'http_compression' => false, 'open_http2_protocol' => true, - ])->andReturnTrue(); + ])->returns(true); $nativeServer->expects('addlistener') ->with('127.0.0.1', 8001, SWOOLE_SOCK_TCP) - ->andReturn($firstSecondary); + ->returns($firstSecondary); $firstSecondary->expects('set')->with([ 'socket_buffer_size' => 4096, 'http_compression' => false, 'open_http_protocol' => false, - ])->andReturnTrue(); + ])->returns(true); $nativeServer->expects('addlistener') ->with('127.0.0.1', 8002, SWOOLE_SOCK_TCP) - ->andReturn($secondSecondary); + ->returns($secondSecondary); $secondSecondary->expects('set')->with([ 'socket_buffer_size' => 2048, 'http_compression' => false, - ])->andReturnTrue(); - $server = $this->server(m::mock(Container::class)); + ])->returns(true); + $server = $this->server(Double::for(Container::class, override: true)->strict()->instance()); $server->createWith($nativeServer); $server->init(new ServerConfig([ @@ -453,18 +457,18 @@ public function testInheritedResponseCallbacksUseTheirReceivingListenerAndPreser $closeCallback = static function (SwooleServer $server, int $connection) use (&$closed): void { $closed[] = $connection; }; - $nativeServer = m::mock(SwooleServer::class); + $nativeServer = Double::for(SwooleServer::class)->strict(); $nativeServer->mode = SWOOLE_BASE; $nativeServer->ssl = false; - $nativeServer->ports = [m::mock(SwoolePort::class)]; - $inherited = m::mock(SwoolePort::class); + $nativeServer->ports = [Double::for(SwoolePort::class)->strict()]; + $inherited = Double::for(SwoolePort::class)->strict(); $inherited->ssl = true; - $overridden = m::mock(SwoolePort::class); + $overridden = Double::for(SwoolePort::class)->strict(); $overridden->ssl = false; foreach ([$nativeServer, $inherited, $overridden] as $index => $listener) { - $listener->expects('set')->with([])->andReturnTrue(); - $listener->expects('on')->times(3)->andReturnUsing( + $listener->expects('set')->with([])->returns(true); + $listener->expects('on')->times(3)->resolves( static function (string $event, callable $callback) use (&$registered, $index): bool { $registered[$index][$event] = $callback; @@ -473,9 +477,9 @@ static function (string $event, callable $callback) use (&$registered, $index): ); } - $nativeServer->expects('addlistener')->with('127.0.0.2', 8443, SWOOLE_SOCK_TCP | SWOOLE_SSL)->andReturn($inherited); - $nativeServer->expects('addlistener')->with('127.0.0.1', 8080, SWOOLE_SOCK_TCP)->andReturn($overridden); - $server = $this->server(m::mock(Container::class)); + $nativeServer->expects('addlistener')->with('127.0.0.2', 8443, SWOOLE_SOCK_TCP | SWOOLE_SSL)->returns($inherited); + $nativeServer->expects('addlistener')->with('127.0.0.1', 8080, SWOOLE_SOCK_TCP)->returns($overridden); + $server = $this->server(Double::for(Container::class, override: true)->strict()->instance()); $server->createWith($nativeServer); $server->init(new ServerConfig(['servers' => [ ['name' => 'http', 'host' => '127.0.0.1', 'port' => 8443, 'callbacks' => [ @@ -493,9 +497,9 @@ static function (string $event, callable $callback) use (&$registered, $index): foreach ([0, 1, 2] as $index) { foreach ([Event::ON_REQUEST, Event::ON_HANDSHAKE] as $event) { - $request = m::mock(SwooleRequest::class); + $request = Double::for(SwooleRequest::class)->strict(); $request->server = []; - $registered[$index][$event]($request, m::mock(SwooleResponse::class)); + $registered[$index][$event]($request, Double::for(SwooleResponse::class)->strict()); } } @@ -528,33 +532,27 @@ static function (string $event, callable $callback) use (&$registered, $index): public function testServerInitializationDispatchesLifecycleEventsWhenListenedFor(): void { - $mainPort = m::mock(SwoolePort::class); - $nativeServer = m::mock(SwooleServer::class); + $mainPort = Double::for(SwoolePort::class)->strict(); + $nativeServer = Double::for(SwooleServer::class)->strict(); $nativeServer->ports = [$mainPort]; - $nativeServer->expects('set')->with([])->andReturnTrue(); + $nativeServer->expects('set')->with([])->returns(true); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->expects('hasListeners')->with(BeforeMainServerStart::class)->andReturnTrue(); + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('hasListeners')->with(BeforeMainServerStart::class)->returns(true); $dispatcher->expects('dispatch') - ->with(m::on(function (BeforeMainServerStart $event) use ($nativeServer): bool { - $this->assertSame($nativeServer, $event->server); - $this->assertSame('http', $event->serverConfig['servers'][0]->getName()); - - return true; - })) - ->andReturnNull(); - $dispatcher->expects('hasListeners')->with(BeforeServerStart::class)->andReturnTrue(); + ->with(Argument::satisfies(static fn (mixed $event): bool => $event instanceof BeforeMainServerStart + && $event->server === $nativeServer + && $event->serverConfig['servers'][0]->getName() === 'http')) + ->returns(null); + $dispatcher->expects('hasListeners')->with(BeforeServerStart::class)->returns(true); $dispatcher->expects('dispatch') - ->with(m::on(function (BeforeServerStart $event): bool { - $this->assertSame('http', $event->serverName); - - return true; - })) - ->andReturnNull(); + ->with(Argument::satisfies(static fn (mixed $event): bool => $event instanceof BeforeServerStart + && $event->serverName === 'http')) + ->returns(null); $server = new ServerTestServer( - m::mock(Container::class), - m::mock(LoggerInterface::class), + Double::for(Container::class, override: true)->strict()->instance(), + Double::for(LoggerInterface::class)->strict(), $dispatcher, ); $server->createWith($nativeServer); @@ -568,12 +566,12 @@ public function testServerInitializationDispatchesLifecycleEventsWhenListenedFor public function testListenerCreationFailureStopsConfiguration(): void { - $mainPort = m::mock(SwoolePort::class); - $nativeServer = m::mock(SwooleServer::class); + $mainPort = Double::for(SwoolePort::class)->strict(); + $nativeServer = Double::for(SwooleServer::class)->strict(); $nativeServer->ports = [$mainPort]; - $nativeServer->expects('set')->with([])->andReturnTrue(); - $nativeServer->expects('addlistener')->with('127.0.0.1', 8001, SWOOLE_SOCK_TCP)->andReturnFalse(); - $server = $this->server(m::mock(Container::class)); + $nativeServer->expects('set')->with([])->returns(true); + $nativeServer->expects('addlistener')->with('127.0.0.1', 8001, SWOOLE_SOCK_TCP)->returns(false); + $server = $this->server(Double::for(Container::class, override: true)->strict()->instance()); $server->createWith($nativeServer); $this->expectException(ServerException::class); @@ -592,7 +590,7 @@ public function testUnsupportedServerTypeUsesThePackageInvalidArgumentException( $this->expectException(ServerInvalidArgumentException::class); $this->expectExceptionMessageIs('Server type is invalid.'); - $this->server(m::mock(Container::class))->init(new ServerConfig([ + $this->server(Double::for(Container::class, override: true)->strict()->instance())->init(new ServerConfig([ 'servers' => [ ['name' => 'invalid', 'type' => 999], ], @@ -601,9 +599,9 @@ public function testUnsupportedServerTypeUsesThePackageInvalidArgumentException( public function testStartFailureIsReported(): void { - $nativeServer = m::mock(SwooleServer::class); - $nativeServer->expects('start')->andReturnFalse(); - $server = $this->server(m::mock(Container::class)); + $nativeServer = Double::for(SwooleServer::class)->strict(); + $nativeServer->expects('start')->returns(false); + $server = $this->server(Double::for(Container::class, override: true)->strict()->instance()); $server->useNativeServer($nativeServer); $this->expectException(ServerException::class); @@ -615,26 +613,25 @@ public function testStartFailureIsReported(): void public function testBeforeServerForkIsDispatchedBeforeNativeStart(): void { $order = []; - $nativeServer = m::mock(SwooleServer::class); - $nativeServer->expects('start')->andReturnUsing(function () use (&$order): bool { + $nativeServer = Double::for(SwooleServer::class)->strict(); + $nativeServer->expects('start')->resolves(function () use (&$order): bool { $order[] = 'start'; return true; }); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->expects('hasListeners')->with(BeforeServerFork::class)->andReturnTrue(); + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('hasListeners')->with(BeforeServerFork::class)->returns(true); $dispatcher->expects('dispatch') - ->with(m::on(function (BeforeServerFork $event) use ($nativeServer, &$order): bool { + ->with(Argument::type(BeforeServerFork::class)) + ->resolves(function (BeforeServerFork $event) use ($nativeServer, &$order): void { $this->assertSame($nativeServer, $event->server); $order[] = 'before-fork'; - - return true; - })); + }); $server = new ServerTestServer( - m::mock(Container::class), - m::mock(LoggerInterface::class), + Double::for(Container::class, override: true)->strict()->instance(), + Double::for(LoggerInterface::class)->strict(), $dispatcher, ); $server->useNativeServer($nativeServer); @@ -646,18 +643,18 @@ public function testBeforeServerForkIsDispatchedBeforeNativeStart(): void public function testBeforeServerForkFailurePreventsNativeStart(): void { $exception = new RuntimeException('Pre-fork cleanup failed.'); - $nativeServer = m::mock(SwooleServer::class); - $nativeServer->shouldNotReceive('start'); + $nativeServer = Double::for(SwooleServer::class)->strict(); + $nativeServer->expects('start')->never(); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->expects('hasListeners')->with(BeforeServerFork::class)->andReturnTrue(); + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('hasListeners')->with(BeforeServerFork::class)->returns(true); $dispatcher->expects('dispatch') - ->with(m::type(BeforeServerFork::class)) - ->andThrow($exception); + ->with(Argument::type(BeforeServerFork::class)) + ->throws($exception); $server = new ServerTestServer( - m::mock(Container::class), - m::mock(LoggerInterface::class), + Double::for(Container::class, override: true)->strict()->instance(), + Double::for(LoggerInterface::class)->strict(), $dispatcher, ); $server->useNativeServer($nativeServer); @@ -673,20 +670,20 @@ public function testBeforeServerForkFailurePreventsNativeStart(): void public function testStartSkipsLifecycleEventWithoutListeners(): void { $started = false; - $nativeServer = m::mock(SwooleServer::class); - $nativeServer->expects('start')->andReturnUsing(function () use (&$started): bool { + $nativeServer = Double::for(SwooleServer::class)->strict(); + $nativeServer->expects('start')->resolves(function () use (&$started): bool { $started = true; return true; }); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->expects('hasListeners')->with(BeforeServerFork::class)->andReturnFalse(); - $dispatcher->shouldNotReceive('dispatch'); + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->expects('hasListeners')->with(BeforeServerFork::class)->returns(false); + $dispatcher->expects('dispatch')->never(); $server = new ServerTestServer( - m::mock(Container::class), - m::mock(LoggerInterface::class), + Double::for(Container::class, override: true)->strict()->instance(), + Double::for(LoggerInterface::class)->strict(), $dispatcher, ); $server->useNativeServer($nativeServer); @@ -699,9 +696,9 @@ public function testStartSkipsLifecycleEventWithoutListeners(): void public function testServerTypesArePrioritizedWithoutReorderingEqualTypes(): void { $server = new ServerTestServer( - m::mock(Container::class), - m::mock(LoggerInterface::class), - m::mock(Dispatcher::class), + Double::for(Container::class, override: true)->strict()->instance(), + Double::for(LoggerInterface::class)->strict(), + Double::for(Dispatcher::class)->strict(), ); $ports = [ @@ -725,9 +722,9 @@ public function testServerTypesArePrioritizedWithoutReorderingEqualTypes(): void public function testAppendedHttpServerCannotReplaceTheConfiguredMainHttpServer(): void { $server = new ServerTestServer( - m::mock(Container::class), - m::mock(LoggerInterface::class), - m::mock(Dispatcher::class), + Double::for(Container::class, override: true)->strict()->instance(), + Double::for(LoggerInterface::class)->strict(), + Double::for(Dispatcher::class)->strict(), ); $ports = [ @@ -744,6 +741,9 @@ public function testAppendedHttpServerCannotReplaceTheConfiguredMainHttpServer() ); } + /** + * Create a named server port. + */ private function port(string $name, int $type): Port { return Port::build([ @@ -752,15 +752,18 @@ private function port(string $name, int $type): Port ]); } + /** + * Create a server with inactive lifecycle listeners. + */ private function server(Container $container): ServerTestServer { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->allows('hasListeners')->andReturnFalse(); - $dispatcher->allows('dispatch')->andReturnNull(); + $dispatcher = Double::for(Dispatcher::class)->strict(); + $dispatcher->allows('hasListeners')->returns(false); + $dispatcher->allows('dispatch')->returns(null); return new ServerTestServer( $container, - m::mock(LoggerInterface::class), + Double::for(LoggerInterface::class)->strict(), $dispatcher, ); } @@ -770,32 +773,49 @@ class ServerTestServer extends Server { private ?SwooleServer $serverToCreate = null; + /** + * Choose the native server returned during initialization. + */ public function createWith(SwooleServer $server): void { $this->serverToCreate = $server; } + /** + * Set the native server without initialization. + */ public function useNativeServer(SwooleServer $server): void { $this->server = $server; } + /** + * Expose the guarded response callback. + */ public function guardedResponseCallback(callable $callback): Closure { return $this->guardResponseCallback($callback, false); } + /** + * Expose the guarded worker delivery callback. + */ public function guardedWorkerDeliveryCallback(callable $callback): Closure { return $this->guardWorkerDeliveryCallback($callback); } + /** + * Register callbacks on the test listener. + */ public function registerEvents(SwoolePort|SwooleServer $server, array $events): void { $this->registerSwooleEvents($server, $events, 'test'); } /** + * Expose server sorting without starting any listeners. + * * @param list $servers * @return list */ @@ -804,11 +824,17 @@ public function sortedServers(array $servers): array return $this->sortServers($servers); } + /** + * Return the supplied server or create the requested native server. + */ protected function makeServer(int $type, string $host, int $port, int $mode, int $sockType): SwooleServer { return $this->serverToCreate ?? parent::makeServer($type, $host, $port, $mode, $sockType); } + /** + * Keep default native callbacks out of these tests. + */ protected function defaultCallbacks(): array { return []; diff --git a/tests/ServerProcess/AbstractProcessTest.php b/tests/ServerProcess/AbstractProcessTest.php index c89ce0171b..f028472af2 100644 --- a/tests/ServerProcess/AbstractProcessTest.php +++ b/tests/ServerProcess/AbstractProcessTest.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\ServerProcess; +use Hypervel\Container\Container; use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\Contracts\Debug\ExceptionHandler as ExceptionHandlerContract; use Hypervel\Contracts\Events\Dispatcher as DispatcherContract; @@ -16,7 +17,9 @@ use Hypervel\Support\Sleep; use Hypervel\Tests\ServerProcess\Fixtures\FooProcess; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionClass; use RuntimeException; use Swoole\Event as SwooleEvent; @@ -27,6 +30,8 @@ class AbstractProcessTest extends TestCase { + use VerifiesDoubles; + /** @var SwooleProcess[] */ private array $nativeProcesses = []; @@ -36,6 +41,9 @@ class AbstractProcessTest extends TestCase // not coroutine behavior, so opting out is safe. protected bool $runTestsInCoroutine = false; + /** + * Close native process pipes and drain their reactor cleanup. + */ protected function tearDown(): void { foreach ($this->nativeProcesses as $process) { @@ -52,21 +60,17 @@ protected function tearDown(): void public function testIsEnabledReturnsTrueByDefault(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->andReturn(false); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = new Container; $process = new FooProcess($container); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $this->assertTrue($process->isEnabled($server)); } public function testDefaultPropertyValues(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->andReturn(false); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = new Container; $process = new FooProcess($container); @@ -78,13 +82,12 @@ public function testDefaultPropertyValues(): void public function testBindCreatesProcessAndAddsToServer(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = new Container; $process = new FooProcess($container); - $server = m::mock(Server::class); - $server->shouldReceive('addProcess')->once()->andReturnUsing(function (SwooleProcess $swooleProcess) { + $server = Double::for(Server::class)->strict(); + $server->expects('addProcess')->resolves(function (SwooleProcess $swooleProcess) { $this->nativeProcesses[] = $swooleProcess; $reflection = new ReflectionClass($swooleProcess); $property = $reflection->getProperty('callback'); @@ -100,15 +103,14 @@ public function testBindCreatesProcessAndAddsToServer(): void public function testBindCreatesMultipleProcessesWhenProcessCountGreaterThanOne(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = new Container; $process = new FooProcess($container); $process->processCount = 3; $addCount = 0; - $server = m::mock(Server::class); - $server->shouldReceive('addProcess')->times(3)->andReturnUsing(function (SwooleProcess $swooleProcess) use (&$addCount) { + $server = Double::for(Server::class)->strict(); + $server->expects('addProcess')->times(3)->resolves(function (SwooleProcess $swooleProcess) use (&$addCount) { $this->nativeProcesses[] = $swooleProcess; return ++$addCount; }); @@ -121,21 +123,20 @@ public function testBindCreatesMultipleProcessesWhenProcessCountGreaterThanOne() public function testBindDispatchesBeforeAndAfterEvents(): void { $dispatched = []; - $dispatcher = m::mock(DispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(BeforeProcessHandle::class)->andReturnTrue(); - $dispatcher->shouldReceive('hasListeners')->once()->with(AfterProcessHandle::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->times(2)->andReturnUsing(function ($event) use (&$dispatched) { + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(BeforeProcessHandle::class)->returns(true); + $dispatcher->expects('hasListeners')->with(AfterProcessHandle::class)->returns(true); + $dispatcher->expects('dispatch')->times(2)->resolves(function ($event) use (&$dispatched) { $dispatched[] = $event; }); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher); + $container = new Container; + $container->instance('events', $dispatcher); $process = new FooProcess($container); - $server = m::mock(Server::class); - $server->shouldReceive('addProcess')->andReturnUsing(function (SwooleProcess $swooleProcess) { + $server = Double::for(Server::class)->strict(); + $server->allows('addProcess')->resolves(function (SwooleProcess $swooleProcess) { $this->nativeProcesses[] = $swooleProcess; $reflection = new ReflectionClass($swooleProcess); $callback = $reflection->getProperty('callback')->getValue($swooleProcess); @@ -154,18 +155,17 @@ public function testBindDispatchesBeforeAndAfterEvents(): void public function testBindHandlesProcessWithoutLifecycleListeners(): void { - $dispatcher = m::mock(DispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(BeforeProcessHandle::class)->andReturnFalse(); - $dispatcher->shouldReceive('hasListeners')->once()->with(AfterProcessHandle::class)->andReturnFalse(); - $dispatcher->shouldNotReceive('dispatch'); + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(BeforeProcessHandle::class)->returns(false); + $dispatcher->expects('hasListeners')->with(AfterProcessHandle::class)->returns(false); + $dispatcher->expects('dispatch')->never(); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturnTrue(); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher); + $container = new Container; + $container->instance('events', $dispatcher); $process = new FooProcess($container); - $server = m::mock(Server::class); - $server->shouldReceive('addProcess')->once()->andReturnUsing(function (SwooleProcess $swooleProcess): int { + $server = Double::for(Server::class)->strict(); + $server->expects('addProcess')->resolves(function (SwooleProcess $swooleProcess): int { $this->nativeProcesses[] = $swooleProcess; $reflection = new ReflectionClass($swooleProcess); $callback = $reflection->getProperty('callback')->getValue($swooleProcess); @@ -182,22 +182,21 @@ public function testBindHandlesProcessWithoutLifecycleListeners(): void public function testBindDispatchesEventsWithCorrectIndices(): void { $dispatched = []; - $dispatcher = m::mock(DispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->twice()->with(BeforeProcessHandle::class)->andReturnTrue(); - $dispatcher->shouldReceive('hasListeners')->twice()->with(AfterProcessHandle::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->times(4)->andReturnUsing(function ($event) use (&$dispatched) { + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->times(2)->with(BeforeProcessHandle::class)->returns(true); + $dispatcher->expects('hasListeners')->times(2)->with(AfterProcessHandle::class)->returns(true); + $dispatcher->expects('dispatch')->times(4)->resolves(function ($event) use (&$dispatched) { $dispatched[] = $event; }); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher); + $container = new Container; + $container->instance('events', $dispatcher); $process = new FooProcess($container); $process->processCount = 2; - $server = m::mock(Server::class); - $server->shouldReceive('addProcess')->andReturnUsing(function (SwooleProcess $swooleProcess) { + $server = Double::for(Server::class)->strict(); + $server->allows('addProcess')->resolves(function (SwooleProcess $swooleProcess) { $this->nativeProcesses[] = $swooleProcess; $reflection = new ReflectionClass($swooleProcess); $callback = $reflection->getProperty('callback')->getValue($swooleProcess); @@ -217,27 +216,28 @@ public function testBindDispatchesEventsWithCorrectIndices(): void public function testLogThrowableReportsViaExceptionHandler(): void { - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->once(); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report'); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); - $container->shouldReceive('has')->with(ExceptionHandlerContract::class)->andReturn(true); - $container->shouldReceive('make')->with(ExceptionHandlerContract::class)->andReturn($handler); + $container = new Container; + $container->instance(ExceptionHandlerContract::class, $handler); $process = new class($container) extends AbstractProcess { public bool $enableCoroutine = false; public int $restartInterval = 0; + /** + * Throw the process failure under test. + */ public function handle(): void { throw new RuntimeException('test error'); } }; - $server = m::mock(Server::class); - $server->shouldReceive('addProcess')->andReturnUsing(function (SwooleProcess $swooleProcess) { + $server = Double::for(Server::class)->strict(); + $server->allows('addProcess')->resolves(function (SwooleProcess $swooleProcess) { $this->nativeProcesses[] = $swooleProcess; $reflection = new ReflectionClass($swooleProcess); $callback = $reflection->getProperty('callback')->getValue($swooleProcess); @@ -250,23 +250,24 @@ public function handle(): void public function testLogThrowableSilentlyIgnoresWhenNoExceptionHandler(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); - $container->shouldReceive('has')->with(ExceptionHandlerContract::class)->andReturn(false); + $container = new Container; $process = new class($container) extends AbstractProcess { public bool $enableCoroutine = false; public int $restartInterval = 0; + /** + * Throw the process failure under test. + */ public function handle(): void { throw new RuntimeException('test error'); } }; - $server = m::mock(Server::class); - $server->shouldReceive('addProcess')->andReturnUsing(function (SwooleProcess $swooleProcess) { + $server = Double::for(Server::class)->strict(); + $server->expects('addProcess')->resolves(function (SwooleProcess $swooleProcess) { $this->nativeProcesses[] = $swooleProcess; $reflection = new ReflectionClass($swooleProcess); $callback = $reflection->getProperty('callback')->getValue($swooleProcess); @@ -276,15 +277,13 @@ public function handle(): void // Should not throw — the exception is caught and silently ignored $process->bind($server); - $this->assertTrue(true); } public function testConstructorResolvesEventDispatcherIfAvailable(): void { - $dispatcher = m::mock(DispatcherContract::class); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher); + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $container = new Container; + $container->instance('events', $dispatcher); $process = new FooProcess($container); @@ -295,8 +294,7 @@ public function testConstructorResolvesEventDispatcherIfAvailable(): void public function testConstructorSetsEventToNullWhenNotAvailable(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = new Container; $process = new FooProcess($container); @@ -307,13 +305,12 @@ public function testConstructorSetsEventToNullWhenNotAvailable(): void public function testBindRejectsFailedNativeProcessRegistration(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = new Container; $process = new FooProcess($container); $process->enableCoroutine = true; - $server = m::mock(Server::class); - $server->shouldReceive('addProcess')->once()->andReturnUsing(function (SwooleProcess $swooleProcess): false { + $server = Double::for(Server::class)->strict(); + $server->expects('addProcess')->resolves(function (SwooleProcess $swooleProcess): false { $this->nativeProcesses[] = $swooleProcess; return false; @@ -337,19 +334,18 @@ public function testTeardownContinuesAfterAfterProcessEventFailure(): void $timerId = Timer::after(60_000, static fn (): null => null); $afterFailure = new RuntimeException('after event failed'); - $dispatcher = m::mock(DispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(BeforeProcessHandle::class)->andReturnTrue(); - $dispatcher->shouldReceive('hasListeners')->once()->with(AfterProcessHandle::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->with(m::type(BeforeProcessHandle::class))->once(); - $dispatcher->shouldReceive('dispatch')->with(m::type(AfterProcessHandle::class))->once()->andThrow($afterFailure); + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(BeforeProcessHandle::class)->returns(true); + $dispatcher->expects('hasListeners')->with(AfterProcessHandle::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(BeforeProcessHandle::class)); + $dispatcher->expects('dispatch')->with(Argument::type(AfterProcessHandle::class))->throws($afterFailure); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher); + $container = new Container; + $container->instance('events', $dispatcher); $process = new FooProcess($container); - $server = m::mock(Server::class); - $server->shouldReceive('addProcess')->once()->andReturnUsing(function (SwooleProcess $swooleProcess): int { + $server = Double::for(Server::class)->strict(); + $server->expects('addProcess')->resolves(function (SwooleProcess $swooleProcess): int { $this->nativeProcesses[] = $swooleProcess; $reflection = new ReflectionClass($swooleProcess); $callback = $reflection->getProperty('callback')->getValue($swooleProcess); @@ -384,39 +380,43 @@ public function testTeardownPreservesReporterFailureAfterLaterCleanupFailure(): $operationFailure = new RuntimeException('operation failed'); $reporterFailure = new RuntimeException('reporter failed'); - $dispatcher = m::mock(DispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(BeforeProcessHandle::class)->andReturnTrue(); - $dispatcher->shouldReceive('hasListeners')->once()->with(AfterProcessHandle::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->with(m::type(BeforeProcessHandle::class))->once(); - $dispatcher->shouldReceive('dispatch')->with(m::type(AfterProcessHandle::class))->once(); + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(BeforeProcessHandle::class)->returns(true); + $dispatcher->expects('hasListeners')->with(AfterProcessHandle::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(BeforeProcessHandle::class)); + $dispatcher->expects('dispatch')->with(Argument::type(AfterProcessHandle::class)); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->with($operationFailure)->once()->andThrow($reporterFailure); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report')->with($operationFailure)->throws($reporterFailure); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn(true); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher); - $container->shouldReceive('has')->with(ExceptionHandlerContract::class)->andReturn(true); - $container->shouldReceive('make')->with(ExceptionHandlerContract::class)->andReturn($handler); + $container = new Container; + $container->instance('events', $dispatcher); + $container->instance(ExceptionHandlerContract::class, $handler); $process = new class($container, $operationFailure) extends AbstractProcess { public bool $enableCoroutine = false; public int $restartInterval = 1; + /** + * Create a process with the configured operation failure. + */ public function __construct(ContainerContract $container, private Throwable $failure) { parent::__construct($container); } + /** + * Throw the process failure under test. + */ public function handle(): void { throw $this->failure; } }; - $server = m::mock(Server::class); - $server->shouldReceive('addProcess')->once()->andReturnUsing(function (SwooleProcess $swooleProcess): int { + $server = Double::for(Server::class)->strict(); + $server->expects('addProcess')->resolves(function (SwooleProcess $swooleProcess): int { $this->nativeProcesses[] = $swooleProcess; $reflection = new ReflectionClass($swooleProcess); $callback = $reflection->getProperty('callback')->getValue($swooleProcess); diff --git a/tests/ServerProcess/BootProcessListenerTest.php b/tests/ServerProcess/BootProcessListenerTest.php index 3649276cc1..1a097b03bf 100644 --- a/tests/ServerProcess/BootProcessListenerTest.php +++ b/tests/ServerProcess/BootProcessListenerTest.php @@ -10,23 +10,25 @@ use Hypervel\ServerProcess\Listeners\BootProcessListener; use Hypervel\ServerProcess\ProcessManager; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Swoole\Server; class BootProcessListenerTest extends TestCase { + use VerifiesDoubles; + public function testBootsProcessesFromServerConfig(): void { - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $process = new BootProcessListenerFakeProcess; - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make') - ->once() + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->expects('make') ->with(BootProcessListenerFakeProcess::class) - ->andReturn($process); + ->returns($process); - $listener = new BootProcessListener($container); + $listener = new BootProcessListener($container->instance()); $event = new BeforeMainServerStart($server, ['processes' => [BootProcessListenerFakeProcess::class]]); $listener->handle($event); @@ -38,15 +40,15 @@ public function testBootsProcessesFromServerConfig(): void public function testBootsProcessesFromProcessManager(): void { - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $process = new BootProcessListenerFakeProcess; ProcessManager::register($process); - $container = m::mock(ContainerContract::class); - $container->shouldNotReceive('make'); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->expects('make')->never(); - $listener = new BootProcessListener($container); + $listener = new BootProcessListener($container->instance()); $event = new BeforeMainServerStart($server, []); $listener->handle($event); @@ -58,16 +60,15 @@ public function testBootsProcessesFromProcessManager(): void public function testSkipsProcessWhereIsEnabledReturnsFalse(): void { - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $process = new BootProcessListenerFakeProcess(enabled: false); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make') - ->once() + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->expects('make') ->with(BootProcessListenerFakeProcess::class) - ->andReturn($process); + ->returns($process); - $listener = new BootProcessListener($container); + $listener = new BootProcessListener($container->instance()); $event = new BeforeMainServerStart($server, ['processes' => [BootProcessListenerFakeProcess::class]]); $listener->handle($event); @@ -78,12 +79,12 @@ public function testSkipsProcessWhereIsEnabledReturnsFalse(): void public function testHandlesMissingProcessesKeyInServerConfig(): void { - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); - $container = m::mock(ContainerContract::class); - $container->shouldNotReceive('make'); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->expects('make')->never(); - $listener = new BootProcessListener($container); + $listener = new BootProcessListener($container->instance()); $event = new BeforeMainServerStart($server, []); $listener->handle($event); @@ -93,16 +94,15 @@ public function testHandlesMissingProcessesKeyInServerConfig(): void public function testDedupesDuplicateClassStringRegistration(): void { - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $process = new BootProcessListenerFakeProcess; - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make') - ->once() + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->expects('make') ->with(BootProcessListenerFakeProcess::class) - ->andReturn($process); + ->returns($process); - $listener = new BootProcessListener($container); + $listener = new BootProcessListener($container->instance()); $event = new BeforeMainServerStart($server, [ 'processes' => [BootProcessListenerFakeProcess::class, BootProcessListenerFakeProcess::class], ]); @@ -115,17 +115,17 @@ public function testDedupesDuplicateClassStringRegistration(): void public function testDoesNotDedupDistinctInstancesOfSameClass(): void { - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $process1 = new BootProcessListenerFakeProcess; $process2 = new BootProcessListenerFakeProcess; ProcessManager::register($process1); ProcessManager::register($process2); - $container = m::mock(ContainerContract::class); - $container->shouldNotReceive('make'); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->expects('make')->never(); - $listener = new BootProcessListener($container); + $listener = new BootProcessListener($container->instance()); $event = new BeforeMainServerStart($server, []); $listener->handle($event); @@ -143,6 +143,9 @@ class BootProcessListenerFakeProcess implements ProcessInterface public int $enableChecks = 0; + /** + * Create a process with the selected enabled state. + */ public function __construct(private bool $enabled = true) { } diff --git a/tests/ServerProcess/EventTest.php b/tests/ServerProcess/EventTest.php index 161015bccb..288f9febdb 100644 --- a/tests/ServerProcess/EventTest.php +++ b/tests/ServerProcess/EventTest.php @@ -4,23 +4,23 @@ namespace Hypervel\Tests\ServerProcess; -use Hypervel\Contracts\Container\Container as ContainerContract; +use Hypervel\Container\Container; use Hypervel\ServerProcess\AbstractProcess; use Hypervel\ServerProcess\Events\AfterProcessHandle; use Hypervel\ServerProcess\Events\BeforeProcessHandle; use Hypervel\ServerProcess\Events\PipeMessage; use Hypervel\Tests\TestCase; -use Mockery as m; class EventTest extends TestCase { public function testBeforeProcessHandleHoldsProcessAndIndex(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->andReturn(false); - $process = new class($container) extends AbstractProcess { + $process = new class(new Container) extends AbstractProcess { public string $name = 'test-process'; + /** + * Leave process execution outside this event test. + */ public function handle(): void { } @@ -35,9 +35,10 @@ public function handle(): void public function testAfterProcessHandleHoldsProcessAndIndex(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->andReturn(false); - $process = new class($container) extends AbstractProcess { + $process = new class(new Container) extends AbstractProcess { + /** + * Leave process execution outside this event test. + */ public function handle(): void { } diff --git a/tests/ServerProcess/ListenCreationFailureTest.php b/tests/ServerProcess/ListenCreationFailureTest.php index f71ba958f9..70688505de 100644 --- a/tests/ServerProcess/ListenCreationFailureTest.php +++ b/tests/ServerProcess/ListenCreationFailureTest.php @@ -4,12 +4,11 @@ namespace Hypervel\Tests\ServerProcess; -use Hypervel\Contracts\Container\Container as ContainerContract; +use Hypervel\Container\Container; use Hypervel\Engine\Channel; use Hypervel\Engine\Exceptions\CoroutineCreateException; use Hypervel\Tests\ServerProcess\Fixtures\ListenableProcess; use Hypervel\Tests\TestCase; -use Mockery as m; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use Swoole\Coroutine as SwooleCoroutine; @@ -23,10 +22,7 @@ public function testCreationFailureClosesTheUntransferredQuitChannel(): void SwooleCoroutine::set(['max_coroutine' => 1]); SwooleCoroutine\run(function (): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn(false); - - $process = new ListenableProcess($container); + $process = new ListenableProcess(new Container); $quit = new Channel(1); try { diff --git a/tests/ServerProcess/ListenMethodTest.php b/tests/ServerProcess/ListenMethodTest.php index ac6501f888..31af42287e 100644 --- a/tests/ServerProcess/ListenMethodTest.php +++ b/tests/ServerProcess/ListenMethodTest.php @@ -5,7 +5,7 @@ namespace Hypervel\Tests\ServerProcess; use Closure; -use Hypervel\Contracts\Container\Container as ContainerContract; +use Hypervel\Container\Container; use Hypervel\Contracts\Debug\ExceptionHandler as ExceptionHandlerContract; use Hypervel\Contracts\Events\Dispatcher as DispatcherContract; use Hypervel\Coroutine\Coroutine; @@ -15,22 +15,26 @@ use Hypervel\Tests\ServerProcess\Fixtures\FakeSocket; use Hypervel\Tests\ServerProcess\Fixtures\ListenableProcess; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; class ListenMethodTest extends TestCase { + use VerifiesDoubles; + public function testListenerContinuesAfterSignalInterruption(): void { $dispatched = []; - $dispatcher = m::mock(DispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(PipeMessage::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->andReturnUsing(function (object $event) use (&$dispatched): void { + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(PipeMessage::class)->returns(true); + $dispatcher->expects('dispatch')->resolves(function (object $event) use (&$dispatched): void { $dispatched[] = $event; }); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->with(m::type(SocketAcceptException::class))->once(); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report')->with(Argument::type(SocketAcceptException::class)); $process = new ListenableProcess($this->makeContainer($dispatcher, $handler)); $socket = new FakeSocket([ @@ -60,9 +64,9 @@ public function testListenerContinuesAfterSignalInterruption(): void public function testListenerSkipsPipeMessageEventWithoutListeners(): void { - $dispatcher = m::mock(DispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(PipeMessage::class)->andReturnFalse(); - $dispatcher->shouldNotReceive('dispatch'); + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(PipeMessage::class)->returns(false); + $dispatcher->expects('dispatch')->never(); $process = new ListenableProcess($this->makeContainer($dispatcher)); $socket = new FakeSocket([[serialize(['hello' => 'world']), 0]]); @@ -83,14 +87,14 @@ public function testListenerSkipsPipeMessageEventWithoutListeners(): void public function testListenerContinuesAfterEagain(): void { $dispatched = []; - $dispatcher = m::mock(DispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(PipeMessage::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->andReturnUsing(function (object $event) use (&$dispatched): void { + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(PipeMessage::class)->returns(true); + $dispatcher->expects('dispatch')->resolves(function (object $event) use (&$dispatched): void { $dispatched[] = $event; }); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->with(m::type(SocketAcceptException::class))->once(); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report')->with(Argument::type(SocketAcceptException::class)); $process = new ListenableProcess($this->makeContainer($dispatcher, $handler)); $socket = new FakeSocket([ @@ -118,11 +122,11 @@ public function testListenerContinuesAfterEagain(): void public function testListenerStopsOnPermanentSocketClosure(): void { - $dispatcher = m::mock(DispatcherContract::class); - $dispatcher->shouldNotReceive('dispatch'); + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $dispatcher->expects('dispatch')->never(); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->with(m::type(SocketAcceptException::class))->once(); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report')->with(Argument::type(SocketAcceptException::class)); $process = new ListenableProcess($this->makeContainer($dispatcher, $handler)); $socket = new FakeSocket([ @@ -146,8 +150,8 @@ public function testListenerStopsOnPermanentSocketClosure(): void public function testListenerStopsOnConnectionReset(): void { - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->with(m::type(SocketAcceptException::class))->once(); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report')->with(Argument::type(SocketAcceptException::class)); $process = new ListenableProcess($this->makeContainer(handler: $handler)); $socket = new FakeSocket([ @@ -171,8 +175,8 @@ public function testListenerStopsOnConnectionReset(): void public function testListenerStopsOnBadFileDescriptor(): void { - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->with(m::type(SocketAcceptException::class))->once(); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report')->with(Argument::type(SocketAcceptException::class)); $process = new ListenableProcess($this->makeContainer(handler: $handler)); $socket = new FakeSocket([ @@ -196,11 +200,10 @@ public function testListenerStopsOnBadFileDescriptor(): void public function testListenerStopsWhenTheProcessSocketCannotBeExported(): void { - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report') - ->with(m::on(fn (SocketAcceptException $exception): bool => $exception->isPermanent() - && $exception->getMessage() === 'Unable to export process IPC socket')) - ->once(); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report') + ->with(Argument::satisfies(fn (SocketAcceptException $exception): bool => $exception->isPermanent() + && $exception->getMessage() === 'Unable to export process IPC socket')); $process = new ListenableProcess($this->makeContainer(handler: $handler)); $process->fakeSocket = false; @@ -220,11 +223,10 @@ public function testListenerClosesItsChannelWhenTheExceptionReporterThrows(): vo { Coroutine::reportExceptions(false); $reporterFailure = new RuntimeException('reporter failed'); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report') - ->with(m::type(SocketAcceptException::class)) - ->once() - ->andThrow($reporterFailure); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report') + ->with(Argument::type(SocketAcceptException::class)) + ->throws($reporterFailure); $process = new ListenableProcess($this->makeContainer(handler: $handler)); $socket = new FakeSocket([['', 0]]); @@ -246,9 +248,9 @@ public function testListenerDispatchesEverySerializableFalsyPayload(): void { $payloads = [false, null, 0, '', []]; $dispatched = []; - $dispatcher = m::mock(DispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->times(count($payloads))->with(PipeMessage::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->times(count($payloads))->andReturnUsing(function (PipeMessage $event) use (&$dispatched): void { + $dispatcher = Double::for(DispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->times(count($payloads))->with(PipeMessage::class)->returns(true); + $dispatcher->expects('dispatch')->times(count($payloads))->resolves(function (PipeMessage $event) use (&$dispatched): void { $dispatched[] = $event->data; }); @@ -279,17 +281,15 @@ public function testListenerDispatchesEverySerializableFalsyPayload(): void private function makeContainer( ?DispatcherContract $dispatcher = null, ?ExceptionHandlerContract $handler = null, - ): ContainerContract { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->with('events')->andReturn($dispatcher !== null); + ): Container { + $container = new Container; if ($dispatcher !== null) { - $container->shouldReceive('make')->with('events')->andReturn($dispatcher); + $container->instance('events', $dispatcher); } if ($handler !== null) { - $container->shouldReceive('has')->with(ExceptionHandlerContract::class)->andReturn(true); - $container->shouldReceive('make')->with(ExceptionHandlerContract::class)->andReturn($handler); + $container->instance(ExceptionHandlerContract::class, $handler); } return $container; diff --git a/tests/ServerProcess/LoggingListenerTest.php b/tests/ServerProcess/LoggingListenerTest.php index a40c1bdc47..0696b81ef3 100644 --- a/tests/ServerProcess/LoggingListenerTest.php +++ b/tests/ServerProcess/LoggingListenerTest.php @@ -4,7 +4,7 @@ namespace Hypervel\Tests\ServerProcess; -use Hypervel\Contracts\Container\Container as ContainerContract; +use Hypervel\Container\Container; use Hypervel\Contracts\Log\StdoutLoggerInterface; use Hypervel\ServerProcess\AbstractProcess; use Hypervel\ServerProcess\Events\AfterProcessHandle; @@ -12,18 +12,20 @@ use Hypervel\ServerProcess\Listeners\LogAfterProcessStoppedListener; use Hypervel\ServerProcess\Listeners\LogBeforeProcessStartListener; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class LoggingListenerTest extends TestCase { + use VerifiesDoubles; + public function testLogBeforeProcessStartLogsViaStdoutLogger(): void { - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('info')->once()->with('Process[my-worker.2] start.'); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('info')->with('Process[my-worker.2] start.'); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->andReturn(true); - $container->shouldReceive('make')->with(StdoutLoggerInterface::class)->andReturn($logger); + $container = new Container; + $container->instance(StdoutLoggerInterface::class, $logger); $listener = new LogBeforeProcessStartListener($container); $event = new BeforeProcessHandle($this->createProcess('my-worker'), 2); @@ -33,12 +35,11 @@ public function testLogBeforeProcessStartLogsViaStdoutLogger(): void public function testLogAfterProcessStoppedLogsViaStdoutLogger(): void { - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('info')->once()->with('Process[scheduler.0] stopped.'); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('info')->with('Process[scheduler.0] stopped.'); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->andReturn(true); - $container->shouldReceive('make')->with(StdoutLoggerInterface::class)->andReturn($logger); + $container = new Container; + $container->instance(StdoutLoggerInterface::class, $logger); $listener = new LogAfterProcessStoppedListener($container); $event = new AfterProcessHandle($this->createProcess('scheduler'), 0); @@ -48,8 +49,7 @@ public function testLogAfterProcessStoppedLogsViaStdoutLogger(): void public function testLogBeforeProcessStartFallsBackToEchoWhenNoLogger(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->andReturn(false); + $container = new Container; $listener = new LogBeforeProcessStartListener($container); $event = new BeforeProcessHandle($this->createProcess('queue'), 1); @@ -63,8 +63,7 @@ public function testLogBeforeProcessStartFallsBackToEchoWhenNoLogger(): void public function testLogAfterProcessStoppedFallsBackToEchoWhenNoLogger(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->andReturn(false); + $container = new Container; $listener = new LogAfterProcessStoppedListener($container); $event = new AfterProcessHandle($this->createProcess('queue'), 1); @@ -76,12 +75,15 @@ public function testLogAfterProcessStoppedFallsBackToEchoWhenNoLogger(): void $this->assertSame("Process[queue.1] stopped.\n", $output); } + /** + * Create a named process without an event dispatcher. + */ private function createProcess(string $name): AbstractProcess { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('bound')->andReturn(false); - - $process = new class($container) extends AbstractProcess { + $process = new class(new Container) extends AbstractProcess { + /** + * Handle the test process. + */ public function handle(): void { } diff --git a/tests/ServerProcess/ProcessCollectorTest.php b/tests/ServerProcess/ProcessCollectorTest.php index 629cb78429..4a33474515 100644 --- a/tests/ServerProcess/ProcessCollectorTest.php +++ b/tests/ServerProcess/ProcessCollectorTest.php @@ -6,11 +6,14 @@ use Hypervel\ServerProcess\ProcessCollector; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Swoole\Process; class ProcessCollectorTest extends TestCase { + use VerifiesDoubles; + public function testIsEmptyInitially(): void { $this->assertTrue(ProcessCollector::isEmpty()); @@ -18,7 +21,7 @@ public function testIsEmptyInitially(): void public function testAddAndGetByName(): void { - $process = m::mock(Process::class); + $process = Double::for(Process::class)->strict(); ProcessCollector::add('worker', $process); @@ -33,8 +36,8 @@ public function testGetReturnsEmptyArrayForUnknownName(): void public function testAddMultipleProcessesUnderSameName(): void { - $process1 = m::mock(Process::class); - $process2 = m::mock(Process::class); + $process1 = Double::for(Process::class)->strict(); + $process2 = Double::for(Process::class)->strict(); ProcessCollector::add('worker', $process1); ProcessCollector::add('worker', $process2); @@ -46,8 +49,8 @@ public function testAddMultipleProcessesUnderSameName(): void public function testAddProcessesUnderDifferentNames(): void { - $process1 = m::mock(Process::class); - $process2 = m::mock(Process::class); + $process1 = Double::for(Process::class)->strict(); + $process2 = Double::for(Process::class)->strict(); ProcessCollector::add('queue', $process1); ProcessCollector::add('scheduler', $process2); @@ -58,9 +61,9 @@ public function testAddProcessesUnderDifferentNames(): void public function testAllReturnsFlattenedArray(): void { - $process1 = m::mock(Process::class); - $process2 = m::mock(Process::class); - $process3 = m::mock(Process::class); + $process1 = Double::for(Process::class)->strict(); + $process2 = Double::for(Process::class)->strict(); + $process3 = Double::for(Process::class)->strict(); ProcessCollector::add('queue', $process1); ProcessCollector::add('queue', $process2); diff --git a/tests/ServerProcess/ProcessManagerTest.php b/tests/ServerProcess/ProcessManagerTest.php index 48d73169d0..f6690f49de 100644 --- a/tests/ServerProcess/ProcessManagerTest.php +++ b/tests/ServerProcess/ProcessManagerTest.php @@ -7,11 +7,14 @@ use Hypervel\Contracts\ServerProcess\ProcessInterface; use Hypervel\ServerProcess\ProcessManager; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class ProcessManagerTest extends TestCase { + use VerifiesDoubles; + public function testIsNotRunningInitially(): void { $this->assertFalse(ProcessManager::isRunning()); @@ -33,7 +36,7 @@ public function testAllReturnsEmptyArrayInitially(): void public function testRegisterProcess(): void { - $process = m::mock(ProcessInterface::class); + $process = Double::for(ProcessInterface::class)->strict(); ProcessManager::register($process); @@ -43,8 +46,8 @@ public function testRegisterProcess(): void public function testRegisterMultipleProcesses(): void { - $process1 = m::mock(ProcessInterface::class); - $process2 = m::mock(ProcessInterface::class); + $process1 = Double::for(ProcessInterface::class)->strict(); + $process2 = Double::for(ProcessInterface::class)->strict(); ProcessManager::register($process1); ProcessManager::register($process2); @@ -56,7 +59,7 @@ public function testRegisterMultipleProcesses(): void public function testFlushState(): void { - ProcessManager::register(m::mock(ProcessInterface::class)); + ProcessManager::register(Double::for(ProcessInterface::class)->strict()); ProcessManager::setRunning(true); $this->assertCount(1, ProcessManager::all()); $this->assertTrue(ProcessManager::isRunning()); @@ -73,7 +76,7 @@ public function testRegisterThrowsWhenRunning(): void $this->expectException(RuntimeException::class); $this->expectExceptionMessageIsOrContains('Processes are running'); - ProcessManager::register(m::mock(ProcessInterface::class)); + ProcessManager::register(Double::for(ProcessInterface::class)->strict()); } public function testRegisterWorksAfterStoppingAndClearing(): void @@ -81,7 +84,7 @@ public function testRegisterWorksAfterStoppingAndClearing(): void ProcessManager::setRunning(true); ProcessManager::setRunning(false); - $process = m::mock(ProcessInterface::class); + $process = Double::for(ProcessInterface::class)->strict(); ProcessManager::register($process); $this->assertCount(1, ProcessManager::all()); diff --git a/tests/ServerProcess/ServerProcessServiceProviderTest.php b/tests/ServerProcess/ServerProcessServiceProviderTest.php index d1f6137d34..2ab3113d94 100644 --- a/tests/ServerProcess/ServerProcessServiceProviderTest.php +++ b/tests/ServerProcess/ServerProcessServiceProviderTest.php @@ -16,32 +16,33 @@ use Hypervel\ServerProcess\Events\BeforeProcessHandle; use Hypervel\ServerProcess\ServerProcessServiceProvider; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class ServerProcessServiceProviderTest extends TestCase { + use VerifiesDoubles; + public function testLifecycleLoggingIsRegisteredAsPassiveObservation(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('listen') - ->with(BeforeMainServerStart::class, m::type(Closure::class)) - ->once(); - $events->shouldReceive('observe') - ->with(AfterProcessHandle::class, m::type(Closure::class)) - ->once(); - $events->shouldReceive('observe') - ->with(BeforeProcessHandle::class, m::type(Closure::class)) - ->once(); + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('listen') + ->with(BeforeMainServerStart::class, Argument::type(Closure::class)); + $events->expects('observe') + ->with(AfterProcessHandle::class, Argument::type(Closure::class)); + $events->expects('observe') + ->with(BeforeProcessHandle::class, Argument::type(Closure::class)); - $application = m::mock(Application::class); - $application->shouldReceive('make')->with('events')->once()->andReturn($events); + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('make')->with('events')->returns($events); - (new ServerProcessServiceProvider($application))->boot(); + (new ServerProcessServiceProvider($application->instance()))->boot(); } public function testLifecycleObserversLogDispatchedProcessEvents(): void { - $logger = m::mock(StdoutLoggerInterface::class); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); $logger->expects('info')->with('Process[observed.0] start.'); $logger->expects('info')->with('Process[observed.0] stopped.'); diff --git a/tests/Session/CookieSessionHandlerCoroutineSafetyTest.php b/tests/Session/CookieSessionHandlerCoroutineSafetyTest.php index 6f2f2fa464..68a996eb5b 100644 --- a/tests/Session/CookieSessionHandlerCoroutineSafetyTest.php +++ b/tests/Session/CookieSessionHandlerCoroutineSafetyTest.php @@ -4,11 +4,10 @@ namespace Hypervel\Tests\Session; -use Hypervel\Contracts\Cookie\QueueingFactory; +use Hypervel\Cookie\CookieJar; use Hypervel\Http\Request; use Hypervel\Session\CookieSessionHandler; use Hypervel\Tests\TestCase; -use Mockery as m; use function Hypervel\Coroutine\parallel; @@ -17,7 +16,7 @@ class CookieSessionHandlerCoroutineSafetyTest extends TestCase public function testCookieSessionHandlerRequestIsCoroutineIsolated(): void { $handler = new CookieSessionHandler( - m::mock(QueueingFactory::class), + new CookieJar, 120 ); diff --git a/tests/Session/CookieSessionHandlerTest.php b/tests/Session/CookieSessionHandlerTest.php index 067960dc59..2850b84ebc 100644 --- a/tests/Session/CookieSessionHandlerTest.php +++ b/tests/Session/CookieSessionHandlerTest.php @@ -8,27 +8,24 @@ use Hypervel\Http\Request; use Hypervel\Session\CookieSessionHandler; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use stdClass; class CookieSessionHandlerTest extends TestCase { + use VerifiesDoubles; + public function testBinarySessionPayloadRoundTripsThroughCookieEnvelope(): void { - $cookie = m::mock(QueueingFactory::class); + $cookie = Double::for(QueueingFactory::class)->strict(); $handler = new CookieSessionHandler($cookie, 120); $payload = serialize(['binary' => "\x00\xff\x10"]); $cookieValue = null; - $cookie->shouldReceive('queue') - ->once() - ->withArgs(function (string $name, string $value, int $minutes) use (&$cookieValue): bool { - $this->assertSame('session-id', $name); - $this->assertSame(120, $minutes); - $cookieValue = $value; - - return true; - }); + $cookie->expects('queue') + ->with('session-id', Argument::capture($cookieValue), 120); $this->assertTrue($handler->write('session-id', $payload)); $this->assertIsString($cookieValue); @@ -40,7 +37,7 @@ public function testBinarySessionPayloadRoundTripsThroughCookieEnvelope(): void public function testInvalidCookieEnvelopesReturnEmptyString(): void { - $handler = new CookieSessionHandler(m::mock(QueueingFactory::class), 120); + $handler = new CookieSessionHandler(Double::for(QueueingFactory::class)->strict(), 120); foreach ([ 'garbage' => 'not serialized data', diff --git a/tests/Session/Middleware/StartSessionTest.php b/tests/Session/Middleware/StartSessionTest.php index 332333f252..26c36d800e 100644 --- a/tests/Session/Middleware/StartSessionTest.php +++ b/tests/Session/Middleware/StartSessionTest.php @@ -18,12 +18,16 @@ use Hypervel\Session\SessionManager; use Hypervel\Support\ClassInvoker; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use Symfony\Component\HttpFoundation\Response; class StartSessionTest extends TestCase { + use VerifiesDoubles; + public function testResolveCookieConfigReturnsDefaults(): void { $config = StartSession::resolveCookieConfig( @@ -143,15 +147,15 @@ public function testFailedSessionStartupDoesNotRegisterPersistenceRetry(): void { $request = Request::create('/'); $failure = new RuntimeException('read failure'); - $manager = m::mock(SessionManager::class); - $cache = m::mock(CacheFactoryContract::class); - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $session = m::mock(Session::class); + $manager = Double::for(SessionManager::class)->strict(); + $cache = Double::for(CacheFactoryContract::class)->strict(); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $session = Double::for(Session::class)->strict(); $middleware = new StartSession($manager, $cache, $exceptionHandler); - $session->shouldReceive('setRequestOnHandler')->once()->with($request); - $session->shouldReceive('start')->once()->andThrow($failure); - $exceptionHandler->shouldNotReceive('afterResponse'); + $session->expects('setRequestOnHandler')->with($request); + $session->expects('start')->throws($failure); + $exceptionHandler->expects('afterResponse')->never(); try { (new ClassInvoker($middleware))->handleStatefulRequest( @@ -172,26 +176,22 @@ public function testFailureAfterSuccessfulStartupRegistersPersistenceRetry(): vo { $request = Request::create('/'); $failure = new RuntimeException('route failure'); - $manager = m::mock(SessionManager::class); - $cache = m::mock(CacheFactoryContract::class); - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $session = m::mock(Session::class); + $manager = Double::for(SessionManager::class)->strict(); + $cache = Double::for(CacheFactoryContract::class)->strict(); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $session = Double::for(Session::class)->strict(); $middleware = new StartSession($manager, $cache, $exceptionHandler); $afterResponse = null; - $session->shouldReceive('setRequestOnHandler')->once()->with($request); - $session->shouldReceive('start')->once()->andReturnTrue(); - $session->shouldReceive('isReadOnly')->once()->andReturnFalse(); - $manager->shouldReceive('getSessionConfig')->once()->andReturn([ + $session->expects('setRequestOnHandler')->with($request); + $session->expects('start')->returns(true); + $session->expects('isReadOnly')->returns(false); + $manager->expects('getSessionConfig')->returns([ 'lottery' => [0, 1], ]); - $exceptionHandler->shouldReceive('afterResponse')->once()->andReturnUsing( - function (callable $callback) use (&$afterResponse): void { - $afterResponse = $callback; - } - ); - $manager->shouldReceive('driver')->once()->andReturn($session); - $session->shouldReceive('save')->once(); + $exceptionHandler->expects('afterResponse')->with(Argument::capture($afterResponse)); + $manager->expects('driver')->returns($session); + $session->expects('save'); try { (new ClassInvoker($middleware))->handleStatefulRequest( @@ -215,27 +215,23 @@ public function testPersistenceRetryFailureDoesNotReplacePrimaryFailure(): void { $request = Request::create('/'); $failure = new RuntimeException('write failure'); - $manager = m::mock(SessionManager::class); - $cache = m::mock(CacheFactoryContract::class); - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $session = m::mock(Session::class); + $manager = Double::for(SessionManager::class)->strict(); + $cache = Double::for(CacheFactoryContract::class)->strict(); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $session = Double::for(Session::class)->strict(); $middleware = new StartSession($manager, $cache, $exceptionHandler); $afterResponse = null; - $session->shouldReceive('setRequestOnHandler')->once()->with($request); - $session->shouldReceive('start')->once()->andReturnTrue(); - $session->shouldReceive('isReadOnly')->twice()->andReturnFalse(); - $manager->shouldReceive('getSessionConfig')->twice()->andReturn([ + $session->expects('setRequestOnHandler')->with($request); + $session->expects('start')->returns(true); + $session->expects('isReadOnly')->times(2)->returns(false); + $manager->expects('getSessionConfig')->times(2)->returns([ 'lottery' => [0, 1], 'driver' => null, ]); - $manager->shouldReceive('driver')->twice()->andReturn($session); - $session->shouldReceive('save')->twice()->andThrow($failure); - $exceptionHandler->shouldReceive('afterResponse')->once()->andReturnUsing( - function (callable $callback) use (&$afterResponse): void { - $afterResponse = $callback; - } - ); + $manager->expects('driver')->times(2)->returns($session); + $session->expects('save')->times(2)->throws($failure); + $exceptionHandler->expects('afterResponse')->with(Argument::capture($afterResponse)); try { (new ClassInvoker($middleware))->handleStatefulRequest( @@ -252,7 +248,6 @@ function (callable $callback) use (&$afterResponse): void { $this->assertIsCallable($afterResponse); $afterResponse(); - $this->addToAssertionCount(1); } public function testBlockingPreservesRequestFailureWhenReleaseAlsoFails(): void @@ -260,18 +255,18 @@ public function testBlockingPreservesRequestFailureWhenReleaseAlsoFails(): void $request = Request::create('/'); $route = (new Route('GET', '/', fn () => new Response))->block(10, 0); $request->setRouteResolver(fn (): Route => $route); - $manager = m::mock(SessionManager::class); - $cache = m::mock(CacheFactoryContract::class); - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $session = m::mock(Session::class); - $store = m::mock(Repository::class, LockProvider::class); + $manager = Double::for(SessionManager::class)->strict(); + $cache = Double::for(CacheFactoryContract::class)->strict(); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $session = Double::for(Session::class)->strict(); + $store = Double::for(Repository::class, LockProvider::class)->strict(); $lock = new StartSessionFailingReleaseLock; $middleware = new StartSessionThrowingMiddleware($manager, $cache, $exceptionHandler); - $manager->shouldReceive('blockDriver')->once()->andReturn('array'); - $cache->shouldReceive('store')->once()->with('array')->andReturn($store); - $session->shouldReceive('getId')->once()->andReturn('session-id'); - $store->shouldReceive('lock')->once()->with('session:session-id', 10)->andReturn($lock); + $manager->expects('blockDriver')->returns('array'); + $cache->expects('store')->with('array')->returns($store); + $session->expects('getId')->returns('session-id'); + $store->expects('lock')->with('session:session-id', 10)->returns($lock); try { (new ClassInvoker($middleware))->handleRequestWhileBlocking( @@ -292,26 +287,25 @@ public function testNullBlockStoreUsesTheDefaultCacheStore(): void { $request = Request::create('/'); $request->setRouteResolver(fn (): Route => (new Route('GET', '/', fn () => new Response))->block(10, 0)); - $manager = m::mock(SessionManager::class); - $cache = m::mock(CacheFactoryContract::class); - $session = m::mock(Session::class); - $store = m::mock(Repository::class, LockProvider::class); - $lock = m::mock(Lock::class); + $manager = Double::for(SessionManager::class)->strict(); + $cache = Double::for(CacheFactoryContract::class)->strict(); + $session = Double::for(Session::class)->strict(); + $store = Double::for(Repository::class, LockProvider::class)->strict(); + $lock = Double::for(Lock::class)->strict(); $middleware = new StartSessionRespondingMiddleware( $manager, $cache, - m::mock(ExceptionHandlerContract::class), + Double::for(ExceptionHandlerContract::class)->strict(), ); - $manager->shouldReceive('blockDriver')->once()->andReturnNull(); - $cache->shouldReceive('store')->once()->with(null)->andReturn($store); - $session->shouldReceive('getId')->once()->andReturn('session-id'); - $store->shouldReceive('lock')->once()->with('session:session-id', 10)->andReturn($lock); - $lock->shouldReceive('betweenBlockedAttemptsSleepFor')->once()->with(50)->andReturnSelf(); - $lock->shouldReceive('block') - ->once() - ->with(0, m::type(Closure::class)) - ->andReturnUsing(fn (int $seconds, Closure $callback): Response => $callback()); + $manager->expects('blockDriver')->returns(null); + $cache->expects('store')->with(null)->returns($store); + $session->expects('getId')->returns('session-id'); + $store->expects('lock')->with('session:session-id', 10)->returns($lock); + $lock->expects('betweenBlockedAttemptsSleepFor')->with(50); + $lock->expects('block') + ->with(0, Argument::type(Closure::class)) + ->resolves(fn (int $seconds, Closure $callback): Response => $callback()); $response = (new ClassInvoker($middleware))->handleRequestWhileBlocking( $request, @@ -327,18 +321,18 @@ public function testBlockingTimeoutDoesNotReleaseUnacquiredLock(): void $request = Request::create('/'); $route = (new Route('GET', '/', fn () => new Response))->block(10, 0); $request->setRouteResolver(fn (): Route => $route); - $manager = m::mock(SessionManager::class); - $cache = m::mock(CacheFactoryContract::class); - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $session = m::mock(Session::class); - $store = m::mock(Repository::class, LockProvider::class); + $manager = Double::for(SessionManager::class)->strict(); + $cache = Double::for(CacheFactoryContract::class)->strict(); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $session = Double::for(Session::class)->strict(); + $store = Double::for(Repository::class, LockProvider::class)->strict(); $lock = new StartSessionUnacquirableLock; $middleware = new StartSession($manager, $cache, $exceptionHandler); - $manager->shouldReceive('blockDriver')->once()->andReturn('array'); - $cache->shouldReceive('store')->once()->with('array')->andReturn($store); - $session->shouldReceive('getId')->once()->andReturn('session-id'); - $store->shouldReceive('lock')->once()->with('session:session-id', 10)->andReturn($lock); + $manager->expects('blockDriver')->returns('array'); + $cache->expects('store')->with('array')->returns($store); + $session->expects('getId')->returns('session-id'); + $store->expects('lock')->with('session:session-id', 10)->returns($lock); try { (new ClassInvoker($middleware))->handleRequestWhileBlocking( @@ -354,6 +348,8 @@ public function testBlockingTimeoutDoesNotReleaseUnacquiredLock(): void } /** + * Provide the default session cookie settings. + * * @return array{path: string, domain: ?string, secure: ?bool, http_only: bool, same_site: ?string, partitioned: bool} */ private function defaultCookieConfig(): array @@ -371,6 +367,9 @@ private function defaultCookieConfig(): array class StartSessionThrowingMiddleware extends StartSession { + /** + * Fail the request with the test exception. + */ protected function handleStatefulRequest(Request $request, Session $session, Closure $next): Response { throw new RuntimeException('request failure'); @@ -379,6 +378,9 @@ protected function handleStatefulRequest(Request $request, Session $session, Clo class StartSessionRespondingMiddleware extends StartSession { + /** + * Pass the request to the next handler. + */ protected function handleStatefulRequest(Request $request, Session $session, Closure $next): Response { return $next($request); @@ -389,16 +391,25 @@ class StartSessionFailingReleaseLock extends Lock { public bool $released = false; + /** + * Create the session lock fixture. + */ public function __construct() { parent::__construct('session', 10, 'owner'); } + /** + * Acquire the test lock. + */ public function acquire(): bool { return true; } + /** + * Record the release attempt and fail. + */ public function release(): bool { $this->released = true; @@ -406,10 +417,16 @@ public function release(): bool throw new RuntimeException('release failure'); } + /** + * Leave forced release inactive for this fixture. + */ public function forceRelease(): void { } + /** + * Return the test lock owner. + */ protected function getCurrentOwner(): ?string { return $this->owner; @@ -420,25 +437,40 @@ class StartSessionUnacquirableLock extends Lock { public bool $released = false; + /** + * Create the session lock fixture. + */ public function __construct() { parent::__construct('session', 10, 'owner'); } + /** + * Refuse to acquire the test lock. + */ public function acquire(): bool { return false; } + /** + * Record the release attempt. + */ public function release(): bool { return $this->released = true; } + /** + * Leave forced release inactive for this fixture. + */ public function forceRelease(): void { } + /** + * Return the test lock owner. + */ protected function getCurrentOwner(): ?string { return null; diff --git a/tests/Session/RedisSessionHandlerTest.php b/tests/Session/RedisSessionHandlerTest.php index aca6e756df..4b298ea58e 100644 --- a/tests/Session/RedisSessionHandlerTest.php +++ b/tests/Session/RedisSessionHandlerTest.php @@ -11,16 +11,22 @@ use Hypervel\Contracts\Auth\Guard; use Hypervel\Contracts\Redis\Factory as RedisFactory; use Hypervel\Http\Request; -use Hypervel\Redis\RedisConnection; use Hypervel\Redis\RedisProxy; use Hypervel\Session\RedisSessionHandler; use Hypervel\Session\UserSessionIdentity; use Hypervel\Support\CarbonImmutable; +use Hypervel\Tests\Redis\Fixtures\PhpRedisClusterConnectionStub; +use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; +use Redis; +use RedisCluster; use RuntimeException; use Swoole\Coroutine\CanceledException; use Throwable; @@ -30,22 +36,27 @@ class RedisSessionHandlerTest extends TestCase { + use VerifiesDoubles; + private const string SESSION_ID = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; private const string OTHER_SESSION_ID = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'; private RedisFactory $redis; + /** + * Set up the Redis factory. + */ protected function setUp(): void { parent::setUp(); - $this->redis = m::mock(RedisFactory::class); + $this->redis = Double::for(RedisFactory::class)->strict(); } public function testLifecycleAndCapabilityMethodsDoNotUseRedis(): void { - $this->redis->shouldReceive('connection')->never(); + $this->redis->expects('connection')->never(); $plain = $this->handler(); $tracked = $this->handler(tracked: true); @@ -69,7 +80,7 @@ public function testItCreatesSessionIds(): void public function testValidateIdChecksRedis(int $exists, bool $expected): void { $connection = $this->expectConnection(); - $connection->expects('exists')->with('sessions:' . self::SESSION_ID)->andReturn($exists); + $connection->expects('exists')->with('sessions:' . self::SESSION_ID)->returns($exists); $this->assertSame($expected, $this->handler()->validateId(self::SESSION_ID)); } @@ -86,14 +97,16 @@ public static function sessionExistenceProvider(): array public function testReadUnderstandsRawAndVersionedPayloads(string $stored, string $expected): void { $connection = $this->expectConnection(); - $connection->shouldReceive('get') - ->once() + $connection->expects('get') ->with('sessions:' . self::SESSION_ID) - ->andReturn($stored); + ->returns($stored); $this->assertSame($expected, $this->handler()->read(self::SESSION_ID)); } + /** + * Provide stored session payloads. + */ public static function storedPayloadProvider(): array { return [ @@ -112,7 +125,7 @@ public static function storedPayloadProvider(): array public function testMissingReadReturnsAnEmptyString(): void { $connection = $this->expectConnection(); - $connection->shouldReceive('get')->once()->andReturnFalse(); + $connection->expects('get')->returns(false); $this->assertSame('', $this->handler()->read(self::SESSION_ID)); } @@ -120,7 +133,7 @@ public function testMissingReadReturnsAnEmptyString(): void public function testInvalidReadResultFailsExplicitly(): void { $connection = $this->expectConnection(); - $connection->shouldReceive('get')->once()->andReturn(123); + $connection->expects('get')->returns(123); $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessageIs('Redis returned an invalid session payload.'); @@ -130,38 +143,36 @@ public function testInvalidReadResultFailsExplicitly(): void public function testTrackingDisabledWriteUsesOneRawSetex(): void { - $container = m::mock(Container::class); - $container->shouldReceive('has')->never(); - $container->shouldReceive('make')->never(); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('has')->never(); + $container->expects('make')->never(); $connection = $this->expectConnection(); - $connection->shouldReceive('setex') - ->once() + $connection->expects('setex') ->with('sessions:' . self::SESSION_ID, 600, 'payload') - ->andReturnTrue(); + ->returns(true); - $this->assertTrue($this->handler(container: $container)->write(self::SESSION_ID, 'payload')); + $this->assertTrue($this->handler(container: $container->instance())->write(self::SESSION_ID, 'payload')); } public function testTrackingDisabledWriteReturnsFalseWithoutPublishingSuccess(): void { $connection = $this->expectConnection(); - $connection->shouldReceive('setex')->once()->andReturnFalse(); + $connection->expects('setex')->returns(false); $this->assertFalse($this->handler()->write(self::SESSION_ID, 'payload')); } public function testTrackingDisabledDestroyUsesOneRawDelete(): void { - $container = m::mock(Container::class); - $container->shouldReceive('has')->never(); - $container->shouldReceive('make')->never(); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('has')->never(); + $container->expects('make')->never(); $connection = $this->expectConnection(); - $connection->shouldReceive('del') - ->once() + $connection->expects('del') ->with('sessions:' . self::SESSION_ID) - ->andReturn(1); + ->returns(1); - $this->assertTrue($this->handler(container: $container)->destroy(self::SESSION_ID)); + $this->assertTrue($this->handler(container: $container->instance())->destroy(self::SESSION_ID)); } public function testStandaloneTrackedWriteUsesOneScriptWithPhysicalPrefixAndFreshMetadata(): void @@ -171,11 +182,13 @@ public function testStandaloneTrackedWriteUsesOneScriptWithPhysicalPrefixAndFres $connection = $this->expectConnection(); $captured = []; - $connection->shouldReceive('getOption')->once()->andReturn('redis:'); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturnUsing(static function (string $script, array $keys, array $arguments) use (&$captured): int { - $captured = compact('script', 'keys', 'arguments'); + $connection->expects('getOption')->with(Redis::OPT_PREFIX)->returns('redis:'); + $connection->expects('evalSha') + ->resolves(static function (string $sha, array $parameters, int $keyCount) use (&$captured): int { + $captured = [ + 'keys' => array_slice($parameters, 0, $keyCount), + 'arguments' => array_slice($parameters, $keyCount), + ]; return 1; }); @@ -206,11 +219,13 @@ public function testStandaloneTrackedWritePassesUnresolvedIntentWithoutRequestMe $connection = $this->expectConnection(); $captured = []; - $connection->shouldReceive('getOption')->once()->andReturn(''); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturnUsing(static function (string $script, array $keys, array $arguments) use (&$captured): int { - $captured = compact('script', 'keys', 'arguments'); + $connection->expects('getOption')->with(Redis::OPT_PREFIX)->returns(''); + $connection->expects('evalSha') + ->resolves(static function (string $sha, array $parameters, int $keyCount) use (&$captured): int { + $captured = [ + 'keys' => array_slice($parameters, 0, $keyCount), + 'arguments' => array_slice($parameters, $keyCount), + ]; return 1; }); @@ -229,11 +244,13 @@ public function testStandaloneTrackedWritePassesUnownedIntentAndMapsNonSuccessTo $connection = $this->expectConnection(); $captured = []; - $connection->shouldReceive('getOption')->once()->andReturn(''); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturnUsing(static function (string $script, array $keys, array $arguments) use (&$captured): false { - $captured = compact('script', 'keys', 'arguments'); + $connection->expects('getOption')->with(Redis::OPT_PREFIX)->returns(''); + $connection->expects('evalSha') + ->resolves(static function (string $sha, array $parameters, int $keyCount) use (&$captured): false { + $captured = [ + 'keys' => array_slice($parameters, 0, $keyCount), + 'arguments' => array_slice($parameters, $keyCount), + ]; return false; }); @@ -248,11 +265,13 @@ public function testProviderlessAuthenticatedWriteUsesUnownedIntent(): void $connection = $this->expectConnection(); $captured = []; - $connection->shouldReceive('getOption')->once()->andReturn(''); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturnUsing(static function (string $script, array $keys, array $arguments) use (&$captured): int { - $captured = compact('script', 'keys', 'arguments'); + $connection->expects('getOption')->with(Redis::OPT_PREFIX)->returns(''); + $connection->expects('evalSha') + ->resolves(static function (string $sha, array $parameters, int $keyCount) use (&$captured): int { + $captured = [ + 'keys' => array_slice($parameters, 0, $keyCount), + 'arguments' => array_slice($parameters, $keyCount), + ]; return 1; }); @@ -270,15 +289,14 @@ public function testProviderQualifiedOwnerDigestIsolatesEqualUserIdentifiers(): $container = $this->authenticatedContainer('1', withRequest: false, authProvider: $authProvider); $connection = $this->expectConnection(); - $connection->shouldReceive('getOption')->once()->andReturn(''); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturnUsing(static function ( - string $script, - array $keys, - array $arguments, + $connection->expects('getOption')->with(Redis::OPT_PREFIX)->returns(''); + $connection->expects('evalSha') + ->resolves(static function ( + string $sha, + array $parameters, + int $keyCount, ) use (&$owners, $authProvider): int { - $owners[$authProvider] = $arguments[4]; + $owners[$authProvider] = $parameters[$keyCount + 4]; return 1; }); @@ -300,29 +318,26 @@ public function testClusterResolvedWriteUpdatesNewIndexBeforePayloadAndOldIndexC $container = $this->authenticatedContainer('new-user', withRequest: true); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('hsetex') - ->once() + $connection->expects('hsetex') ->ordered() ->with( 'sessions:_users:' . $newOwner . ':sessions', - m::on(static fn (array $fields): bool => array_key_exists(self::SESSION_ID, $fields)), + Argument::satisfies(static fn (array $fields): bool => array_key_exists(self::SESSION_ID, $fields)), ['EXAT' => $expiresAt], ) - ->andReturn(1); - $connection->shouldReceive('evalWithShaCache') - ->once() + ->returns(1); + $connection->expects('evalSha') ->ordered() ->with( - m::type('string'), - ['sessions:' . self::SESSION_ID], - [(string) $expiresAt, 'resolved', $newOwner, $newOwner, 'payload'], + Argument::type('string'), + ['sessions:' . self::SESSION_ID, (string) $expiresAt, 'resolved', $newOwner, $newOwner, 'payload'], + 1, ) - ->andReturn([1, $oldOwner, $newOwner]); - $connection->shouldReceive('hdel') - ->once() + ->returns([1, $oldOwner, $newOwner]); + $connection->expects('hdel') ->ordered() ->with('sessions:_users:' . $oldOwner . ':sessions', self::SESSION_ID) - ->andReturn(1); + ->returns(1); $this->assertTrue($this->handler(tracked: true, container: $container)->write(self::SESSION_ID, 'payload')); } @@ -334,34 +349,33 @@ public function testClusterWritePreservesSameOwnerMetadataWithOneIndexScript(): $expiresAt = CarbonImmutable::now()->getTimestamp() + 600; $handler = $this->handler(tracked: true); $readConnection = $this->expectConnection(cluster: true); - $readConnection->shouldReceive('get')->once()->andReturn("\0HVS1{$owner}old"); + $readConnection->expects('get')->returns("\0HVS1{$owner}old"); $this->assertSame('old', $handler->read(self::SESSION_ID)); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('evalWithShaCache') - ->once() + $connection->expects('evalSha') ->ordered() ->with( - m::type('string'), - ['sessions:_users:' . $owner . ':sessions'], - m::on(static fn (array $arguments): bool => $arguments[0] === self::SESSION_ID - && $arguments[1] === (string) $expiresAt - && count($arguments) === 4), + Argument::type('string'), + Argument::satisfies(static fn (array $parameters): bool => $parameters[0] === 'sessions:_users:' . $owner . ':sessions' + && $parameters[1] === self::SESSION_ID + && $parameters[2] === (string) $expiresAt + && count($parameters) === 5), + 1, ) - ->andReturn(1); - $connection->shouldReceive('evalWithShaCache') - ->once() + ->returns(1); + $connection->expects('evalSha') ->ordered() ->with( - m::type('string'), - ['sessions:' . self::SESSION_ID], - [(string) $expiresAt, 'unresolved', '', $owner, 'payload'], + Argument::type('string'), + ['sessions:' . self::SESSION_ID, (string) $expiresAt, 'unresolved', '', $owner, 'payload'], + 1, ) - ->andReturn([1, $owner, $owner]); - $connection->shouldReceive('hdel')->never(); - $connection->shouldReceive('get')->never(); + ->returns([1, $owner, $owner]); + $connection->expects('hdel')->never(); + $connection->expects('get')->never(); $this->assertTrue($handler->write(self::SESSION_ID, 'payload')); } @@ -374,16 +388,15 @@ public function testClusterWriteReturnsFalseWhenFreshIndexWriteFails(): void $container = $this->authenticatedContainer('user-1', withRequest: true); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('hsetex') - ->once() + $connection->expects('hsetex') ->with( 'sessions:_users:' . $owner . ':sessions', - m::type('array'), + Argument::type('array'), ['EXAT' => $expiresAt], ) - ->andReturn(0); - $connection->shouldReceive('evalWithShaCache')->never(); - $connection->shouldReceive('hdel')->never(); + ->returns(0); + $connection->expects('evalSha')->never(); + $connection->expects('hdel')->never(); $this->assertFalse( $this->handler(tracked: true, container: $container)->write(self::SESSION_ID, 'payload') @@ -395,17 +408,16 @@ public function testClusterUnresolvedWriteDoesNotRefreshPayloadWhenIndexRefreshF $owner = $this->ownerDigest('users', 'user-1'); $handler = $this->handler(tracked: true); $readConnection = $this->expectConnection(cluster: true); - $readConnection->shouldReceive('get')->once()->andReturn("\0HVS1{$owner}old"); + $readConnection->expects('get')->returns("\0HVS1{$owner}old"); $this->assertSame('old', $handler->read(self::SESSION_ID)); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->with(m::type('string'), ['sessions:_users:' . $owner . ':sessions'], m::type('array')) - ->andReturnFalse(); - $connection->shouldReceive('hdel')->never(); + $connection->expects('evalSha') + ->with(Argument::type('string'), Argument::satisfies(static fn (array $parameters): bool => $parameters[0] === 'sessions:_users:' . $owner . ':sessions'), 1) + ->returns(false); + $connection->expects('hdel')->never(); $this->assertFalse($handler->write(self::SESSION_ID, 'payload')); } @@ -425,9 +437,9 @@ public function testClusterWriteReturnsFalseWhenObsoleteIndexCleanupFails(): voi ); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('hsetex')->once()->ordered()->andReturn(1); - $connection->shouldReceive('evalWithShaCache')->once()->ordered()->andReturn([1, $oldOwner, $newOwner]); - $connection->shouldReceive('hdel')->once()->ordered()->andReturnFalse(); + $connection->expects('hsetex')->ordered()->returns(1); + $connection->expects('evalSha')->ordered()->returns([1, $oldOwner, $newOwner]); + $connection->expects('hdel')->ordered()->returns(false); $this->assertFalse($handler->write(self::SESSION_ID, 'payload')); $this->assertSame($newOwner, $handler->observedOwnerForTesting(self::SESSION_ID)); @@ -440,26 +452,23 @@ public function testClusterUnresolvedWriteProbesAnUnobservedOwnerBeforeUpdatingI $expiresAt = CarbonImmutable::now()->getTimestamp() + 600; $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('get') - ->once() + $connection->expects('get') ->ordered() ->with('sessions:' . self::SESSION_ID) - ->andReturn("\0HVS1{$owner}old"); - $connection->shouldReceive('evalWithShaCache') - ->once() + ->returns("\0HVS1{$owner}old"); + $connection->expects('evalSha') ->ordered() - ->with(m::type('string'), ['sessions:_users:' . $owner . ':sessions'], m::type('array')) - ->andReturn(1); - $connection->shouldReceive('evalWithShaCache') - ->once() + ->with(Argument::type('string'), Argument::satisfies(static fn (array $parameters): bool => $parameters[0] === 'sessions:_users:' . $owner . ':sessions'), 1) + ->returns(1); + $connection->expects('evalSha') ->ordered() ->with( - m::type('string'), - ['sessions:' . self::SESSION_ID], - [(string) $expiresAt, 'unresolved', '', $owner, 'payload'], + Argument::type('string'), + ['sessions:' . self::SESSION_ID, (string) $expiresAt, 'unresolved', '', $owner, 'payload'], + 1, ) - ->andReturn([1, $owner, $owner]); - $connection->shouldReceive('hdel')->never(); + ->returns([1, $owner, $owner]); + $connection->expects('hdel')->never(); $this->assertTrue($this->handler(tracked: true)->write(self::SESSION_ID, 'payload')); } @@ -471,42 +480,39 @@ public function testClusterUnresolvedWriteRejectsAnOwnerAppearingAfterAnOwnerles $expiresAt = CarbonImmutable::now()->getTimestamp() + 600; $handler = $this->handler(tracked: true); $readConnection = $this->expectConnection(cluster: true); - $readConnection->shouldReceive('get')->once()->andReturnFalse(); + $readConnection->expects('get')->returns(false); $this->assertSame('', $handler->read(self::SESSION_ID)); $racedConnection = $this->expectConnection(cluster: true); - $racedConnection->shouldReceive('get')->never(); - $racedConnection->shouldReceive('hsetex')->never(); - $racedConnection->shouldReceive('evalWithShaCache') - ->once() + $racedConnection->expects('get')->never(); + $racedConnection->expects('hsetex')->never(); + $racedConnection->expects('evalSha') ->with( - m::type('string'), - ['sessions:' . self::SESSION_ID], - [(string) $expiresAt, 'unresolved', '', '', 'first'], + Argument::type('string'), + ['sessions:' . self::SESSION_ID, (string) $expiresAt, 'unresolved', '', '', 'first'], + 1, ) - ->andReturn([0, $owner, '']); - $racedConnection->shouldReceive('hdel')->never(); + ->returns([0, $owner, '']); + $racedConnection->expects('hdel')->never(); $this->assertFalse($handler->write(self::SESSION_ID, 'first')); $retryConnection = $this->expectConnection(cluster: true); - $retryConnection->shouldReceive('get')->never(); - $retryConnection->shouldReceive('evalWithShaCache') - ->once() + $retryConnection->expects('get')->never(); + $retryConnection->expects('evalSha') ->ordered() - ->with(m::type('string'), ['sessions:_users:' . $owner . ':sessions'], m::type('array')) - ->andReturn(1); - $retryConnection->shouldReceive('evalWithShaCache') - ->once() + ->with(Argument::type('string'), Argument::satisfies(static fn (array $parameters): bool => $parameters[0] === 'sessions:_users:' . $owner . ':sessions'), 1) + ->returns(1); + $retryConnection->expects('evalSha') ->ordered() ->with( - m::type('string'), - ['sessions:' . self::SESSION_ID], - [(string) $expiresAt, 'unresolved', '', $owner, 'second'], + Argument::type('string'), + ['sessions:' . self::SESSION_ID, (string) $expiresAt, 'unresolved', '', $owner, 'second'], + 1, ) - ->andReturn([1, $owner, $owner]); - $retryConnection->shouldReceive('hdel')->never(); + ->returns([1, $owner, $owner]); + $retryConnection->expects('hdel')->never(); $this->assertTrue($handler->write(self::SESSION_ID, 'second')); } @@ -519,48 +525,44 @@ public function testClusterUnresolvedWriteRejectsAReassignmentAfterPreIndexingTh $expiresAt = CarbonImmutable::now()->getTimestamp() + 600; $handler = new ObservableRedisSessionHandler($this->redis, 'session', 'sessions:', 10, true); $readConnection = $this->expectConnection(cluster: true); - $readConnection->shouldReceive('get')->once()->andReturn("\0HVS1{$observedOwner}old"); + $readConnection->expects('get')->returns("\0HVS1{$observedOwner}old"); $this->assertSame('old', $handler->read(self::SESSION_ID)); $racedConnection = $this->expectConnection(cluster: true); - $racedConnection->shouldReceive('get')->never(); - $racedConnection->shouldReceive('evalWithShaCache') - ->once() + $racedConnection->expects('get')->never(); + $racedConnection->expects('evalSha') ->ordered() - ->with(m::type('string'), ['sessions:_users:' . $observedOwner . ':sessions'], m::type('array')) - ->andReturn(1); - $racedConnection->shouldReceive('evalWithShaCache') - ->once() + ->with(Argument::type('string'), Argument::satisfies(static fn (array $parameters): bool => $parameters[0] === 'sessions:_users:' . $observedOwner . ':sessions'), 1) + ->returns(1); + $racedConnection->expects('evalSha') ->ordered() ->with( - m::type('string'), - ['sessions:' . self::SESSION_ID], - [(string) $expiresAt, 'unresolved', '', $observedOwner, 'first'], + Argument::type('string'), + ['sessions:' . self::SESSION_ID, (string) $expiresAt, 'unresolved', '', $observedOwner, 'first'], + 1, ) - ->andReturn([0, $actualOwner, '']); - $racedConnection->shouldReceive('hdel')->never(); + ->returns([0, $actualOwner, '']); + $racedConnection->expects('hdel')->never(); $this->assertFalse($handler->write(self::SESSION_ID, 'first')); $this->assertSame($actualOwner, $handler->observedOwnerForTesting(self::SESSION_ID)); $retryConnection = $this->expectConnection(cluster: true); - $retryConnection->shouldReceive('get')->never(); - $retryConnection->shouldReceive('evalWithShaCache') - ->once() + $retryConnection->expects('get')->never(); + $retryConnection->expects('evalSha') ->ordered() - ->with(m::type('string'), ['sessions:_users:' . $actualOwner . ':sessions'], m::type('array')) - ->andReturn(1); - $retryConnection->shouldReceive('evalWithShaCache') - ->once() + ->with(Argument::type('string'), Argument::satisfies(static fn (array $parameters): bool => $parameters[0] === 'sessions:_users:' . $actualOwner . ':sessions'), 1) + ->returns(1); + $retryConnection->expects('evalSha') ->ordered() ->with( - m::type('string'), - ['sessions:' . self::SESSION_ID], - [(string) $expiresAt, 'unresolved', '', $actualOwner, 'second'], + Argument::type('string'), + ['sessions:' . self::SESSION_ID, (string) $expiresAt, 'unresolved', '', $actualOwner, 'second'], + 1, ) - ->andReturn([1, $actualOwner, $actualOwner]); - $retryConnection->shouldReceive('hdel')->never(); + ->returns([1, $actualOwner, $actualOwner]); + $retryConnection->expects('hdel')->never(); $this->assertTrue($handler->write(self::SESSION_ID, 'second')); $this->assertSame($actualOwner, $handler->observedOwnerForTesting(self::SESSION_ID)); @@ -574,22 +576,20 @@ public function testClusterUnownedWriteChangesThePayloadBeforeCleaningItsOldInde UserSessionIdentity::suppress(self::SESSION_ID); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('get')->never(); - $connection->shouldReceive('hsetex')->never(); - $connection->shouldReceive('evalWithShaCache') - ->once() + $connection->expects('get')->never(); + $connection->expects('hsetex')->never(); + $connection->expects('evalSha') ->ordered() ->with( - m::type('string'), - ['sessions:' . self::SESSION_ID], - [(string) $expiresAt, 'unowned', '', '', 'payload'], + Argument::type('string'), + ['sessions:' . self::SESSION_ID, (string) $expiresAt, 'unowned', '', '', 'payload'], + 1, ) - ->andReturn([1, $oldOwner, '']); - $connection->shouldReceive('hdel') - ->once() + ->returns([1, $oldOwner, '']); + $connection->expects('hdel') ->ordered() ->with('sessions:_users:' . $oldOwner . ':sessions', self::SESSION_ID) - ->andReturn(1); + ->returns(1); $this->assertTrue($this->handler(tracked: true)->write(self::SESSION_ID, 'payload')); } @@ -598,8 +598,8 @@ public function testClusterUnownedWriteChangesThePayloadBeforeCleaningItsOldInde public function testClusterWriteRejectsMalformedOwnershipResults(mixed $result): void { $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('get')->once()->andReturnFalse(); - $connection->shouldReceive('evalWithShaCache')->once()->andReturn($result); + $connection->expects('get')->returns(false); + $connection->expects('evalSha')->returns($result); $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessageIs('Redis returned an invalid session ownership transition.'); @@ -607,6 +607,9 @@ public function testClusterWriteRejectsMalformedOwnershipResults(mixed $result): $this->handler(tracked: true)->write(self::SESSION_ID, 'payload'); } + /** + * Provide malformed ownership transitions. + */ public static function invalidOwnershipTransitionProvider(): array { return [ @@ -650,11 +653,13 @@ public function testStandaloneTrackedDestroyUsesOneScript(): void $connection = $this->expectConnection(); $captured = []; - $connection->shouldReceive('getOption')->once()->andReturn('redis:'); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturnUsing(static function (string $script, array $keys, array $arguments) use (&$captured): int { - $captured = compact('script', 'keys', 'arguments'); + $connection->expects('getOption')->with(Redis::OPT_PREFIX)->returns('redis:'); + $connection->expects('evalSha') + ->resolves(static function (string $sha, array $parameters, int $keyCount) use (&$captured): int { + $captured = [ + 'keys' => array_slice($parameters, 0, $keyCount), + 'arguments' => array_slice($parameters, $keyCount), + ]; return 1; }); @@ -669,12 +674,11 @@ public function testClusterTrackedDestroyDeletesPayloadBeforeCleaningItsIndex(): $owner = $this->ownerDigest('users', 'user-1'); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('evalWithShaCache')->once()->ordered()->andReturn([1, $owner]); - $connection->shouldReceive('hdel') - ->once() + $connection->expects('evalSha')->ordered()->returns([1, $owner]); + $connection->expects('hdel') ->ordered() ->with('sessions:_users:' . $owner . ':sessions', self::SESSION_ID) - ->andReturn(1); + ->returns(1); $this->assertTrue($this->handler(tracked: true)->destroy(self::SESSION_ID)); } @@ -684,8 +688,8 @@ public function testClusterTrackedDestroyRejectsFailedIndexCleanup(): void $owner = $this->ownerDigest('users', 'user-1'); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('evalWithShaCache')->once()->ordered()->andReturn([1, $owner]); - $connection->shouldReceive('hdel')->once()->ordered()->andReturnFalse(); + $connection->expects('evalSha')->ordered()->returns([1, $owner]); + $connection->expects('hdel')->ordered()->returns(false); $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessageIs('Redis failed to clean the user session index.'); @@ -697,10 +701,9 @@ public function testUserSessionsUsesOneReadAndReturnsSortedValues(): void { $owner = $this->ownerDigest('users', 'user-1'); $connection = $this->expectConnection(); - $connection->shouldReceive('hGetAll') - ->once() + $connection->expects('hGetAll') ->with('sessions:_users:' . $owner . ':sessions') - ->andReturn([ + ->returns([ self::SESSION_ID => json_encode([ 'ip_address' => '203.0.113.1', 'user_agent' => 'First', @@ -712,8 +715,8 @@ public function testUserSessionsUsesOneReadAndReturnsSortedValues(): void 'last_activity' => 200, ]), ]); - $connection->shouldReceive('hdel')->never(); - $connection->shouldReceive('getRange')->never(); + $connection->expects('hdel')->never(); + $connection->expects('getRange')->never(); $sessions = $this->handler(tracked: true)->userSessions('users', 'user-1'); @@ -728,7 +731,7 @@ public function testUserSessionsUsesOneReadAndReturnsSortedValues(): void public function testUserSessionsIgnoresMalformedMetadataAndInvalidIdentifiers(): void { $connection = $this->expectConnection(); - $connection->shouldReceive('hGetAll')->once()->andReturn([ + $connection->expects('hGetAll')->returns([ self::SESSION_ID => '{', 'invalid' => json_encode([ 'ip_address' => null, @@ -741,8 +744,8 @@ public function testUserSessionsIgnoresMalformedMetadataAndInvalidIdentifiers(): 'last_activity' => 100, ]), ]); - $connection->shouldReceive('hdel')->never(); - $connection->shouldReceive('getRange')->never(); + $connection->expects('hdel')->never(); + $connection->expects('getRange')->never(); $sessions = $this->handler(tracked: true)->userSessions('users', 42); @@ -765,7 +768,7 @@ public function testClusterUserSessionsReturnsOnlyAuthoritativeOwnerMatches(): v 'last_activity' => 100, ]); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('hGetAll')->once()->andReturn([ + $connection->expects('hGetAll')->returns([ self::SESSION_ID => $metadata, self::OTHER_SESSION_ID => $metadata, $missingSessionId => $metadata, @@ -774,35 +777,28 @@ public function testClusterUserSessionsReturnsOnlyAuthoritativeOwnerMatches(): v $unknownVersionSessionId => $metadata, $unreadableSessionId => $metadata, ]); - $connection->shouldReceive('getRange') - ->once() + $connection->expects('getRange') ->with('sessions:' . self::SESSION_ID, 0, 36) - ->andReturn("\0HVS1" . $owner); - $connection->shouldReceive('getRange') - ->once() + ->returns("\0HVS1" . $owner); + $connection->expects('getRange') ->with('sessions:' . self::OTHER_SESSION_ID, 0, 36) - ->andReturn("\0HVS1" . $otherOwner); - $connection->shouldReceive('getRange') - ->once() + ->returns("\0HVS1" . $otherOwner); + $connection->expects('getRange') ->with('sessions:' . $missingSessionId, 0, 36) - ->andReturn(''); - $connection->shouldReceive('getRange') - ->once() + ->returns(''); + $connection->expects('getRange') ->with('sessions:' . $rawSessionId, 0, 36) - ->andReturn('raw payload'); - $connection->shouldReceive('getRange') - ->once() + ->returns('raw payload'); + $connection->expects('getRange') ->with('sessions:' . $corruptSessionId, 0, 36) - ->andReturn("\0HVS1" . str_repeat('A', 32)); - $connection->shouldReceive('getRange') - ->once() + ->returns("\0HVS1" . str_repeat('A', 32)); + $connection->expects('getRange') ->with('sessions:' . $unknownVersionSessionId, 0, 36) - ->andReturn("\0HVS2" . $owner); - $connection->shouldReceive('getRange') - ->once() + ->returns("\0HVS2" . $owner); + $connection->expects('getRange') ->with('sessions:' . $unreadableSessionId, 0, 36) - ->andReturnFalse(); - $connection->shouldReceive('hdel')->never(); + ->returns(false); + $connection->expects('hdel')->never(); $sessions = $this->handler(tracked: true)->userSessions('users', 'user-1'); @@ -812,7 +808,7 @@ public function testClusterUserSessionsReturnsOnlyAuthoritativeOwnerMatches(): v public function testClusterUserSessionsDoesNotReadPayloadsWhenIndexHasNoValidCandidates(): void { $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('hGetAll')->once()->andReturn([ + $connection->expects('hGetAll')->returns([ self::SESSION_ID => '{', 'invalid' => json_encode([ 'ip_address' => null, @@ -820,8 +816,8 @@ public function testClusterUserSessionsDoesNotReadPayloadsWhenIndexHasNoValidCan 'last_activity' => 100, ]), ]); - $connection->shouldReceive('getRange')->never(); - $connection->shouldReceive('hdel')->never(); + $connection->expects('getRange')->never(); + $connection->expects('hdel')->never(); $this->assertEmpty($this->handler(tracked: true)->userSessions('users', 'user-1')); } @@ -829,7 +825,7 @@ public function testClusterUserSessionsDoesNotReadPayloadsWhenIndexHasNoValidCan public function testUserSessionsRejectsInvalidIndexResponses(): void { $connection = $this->expectConnection(); - $connection->shouldReceive('hGetAll')->once()->andReturnFalse(); + $connection->expects('hGetAll')->returns(false); $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessageIs('Redis returned an invalid user session index.'); @@ -843,10 +839,12 @@ public function testStandaloneScopedDestroyUsesOneOwnershipScript(): void $connection = $this->expectConnection(); $captured = []; - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturnUsing(static function (string $script, array $keys, array $arguments) use (&$captured): int { - $captured = compact('script', 'keys', 'arguments'); + $connection->expects('evalSha') + ->resolves(static function (string $sha, array $parameters, int $keyCount) use (&$captured): int { + $captured = [ + 'keys' => array_slice($parameters, 0, $keyCount), + 'arguments' => array_slice($parameters, $keyCount), + ]; return 1; }); @@ -865,12 +863,11 @@ public function testClusterScopedDestroyAlwaysCleansTheRequestedIndexAfterOwners $otherOwner = $this->ownerDigest('users', 'other-user'); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('evalWithShaCache')->once()->ordered()->andReturn([0, $otherOwner]); - $connection->shouldReceive('hdel') - ->once() + $connection->expects('evalSha')->ordered()->returns([0, $otherOwner]); + $connection->expects('hdel') ->ordered() ->with('sessions:_users:' . $owner . ':sessions', self::SESSION_ID) - ->andReturn(1); + ->returns(1); $this->assertFalse($this->handler(tracked: true)->destroyUserSession('users', 'user-1', self::SESSION_ID)); } @@ -880,8 +877,8 @@ public function testClusterScopedDestroyRejectsFailedRequestedIndexCleanup(): vo $owner = $this->ownerDigest('users', 'user-1'); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('evalWithShaCache')->once()->ordered()->andReturn([1, $owner]); - $connection->shouldReceive('hdel')->once()->ordered()->andReturnFalse(); + $connection->expects('evalSha')->ordered()->returns([1, $owner]); + $connection->expects('hdel')->ordered()->returns(false); $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessageIs('Redis failed to clean the user session index.'); @@ -895,11 +892,13 @@ public function testStandaloneBulkDestroyUsesOneScriptAndDeduplicatesExceptions( $connection = $this->expectConnection(); $captured = []; - $connection->shouldReceive('getOption')->once()->andReturn('redis:'); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturnUsing(static function (string $script, array $keys, array $arguments) use (&$captured): int { - $captured = compact('script', 'keys', 'arguments'); + $connection->expects('getOption')->with(Redis::OPT_PREFIX)->returns('redis:'); + $connection->expects('evalSha') + ->resolves(static function (string $sha, array $parameters, int $keyCount) use (&$captured): int { + $captured = [ + 'keys' => array_slice($parameters, 0, $keyCount), + 'arguments' => array_slice($parameters, $keyCount), + ]; return 3; }); @@ -919,8 +918,8 @@ public function testStandaloneBulkDestroyUsesOneScriptAndDeduplicatesExceptions( public function testStandaloneBulkDestroyRejectsInvalidResults(mixed $result): void { $connection = $this->expectConnection(); - $connection->shouldReceive('getOption')->once()->andReturn('redis:'); - $connection->shouldReceive('evalWithShaCache')->once()->andReturn($result); + $connection->expects('getOption')->with(Redis::OPT_PREFIX)->returns('redis:'); + $connection->expects('evalSha')->returns($result); $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessageIs('Redis returned an invalid bulk session deletion result.'); @@ -928,6 +927,9 @@ public function testStandaloneBulkDestroyRejectsInvalidResults(mixed $result): v $this->handler(tracked: true)->destroyUserSessions('users', 'user-1'); } + /** + * Provide invalid bulk deletion results. + */ public static function invalidBulkDeletionResultProvider(): array { return [ @@ -940,20 +942,17 @@ public function testClusterBulkDestroyPreservesExceptionsAndCleansCandidatesOnce { $owner = $this->ownerDigest('users', 'user-1'); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('hKeys') - ->once() + $connection->expects('hKeys') ->ordered() - ->andReturn([self::SESSION_ID, self::OTHER_SESSION_ID, 'invalid']); - $connection->shouldReceive('evalWithShaCache') - ->once() + ->returns([self::SESSION_ID, self::OTHER_SESSION_ID, 'invalid']); + $connection->expects('evalSha') ->ordered() - ->with(m::type('string'), ['sessions:' . self::OTHER_SESSION_ID], [$owner]) - ->andReturn([1, $owner]); - $connection->shouldReceive('hdel') - ->once() + ->with(Argument::type('string'), ['sessions:' . self::OTHER_SESSION_ID, $owner], 1) + ->returns([1, $owner]); + $connection->expects('hdel') ->ordered() ->with('sessions:_users:' . $owner . ':sessions', self::OTHER_SESSION_ID, 'invalid') - ->andReturn(2); + ->returns(2); $deleted = $this->handler(tracked: true)->destroyUserSessions('users', 'user-1', [self::SESSION_ID]); @@ -966,7 +965,7 @@ public function testClusterBulkDestroyClearsObservedOwners(): void $handler = new ObservableRedisSessionHandler($this->redis, 'session', 'sessions:', 10, true); $handler->rememberOwnerForTesting(self::SESSION_ID, $owner); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('hKeys')->once()->andReturn([]); + $connection->expects('hKeys')->returns([]); $this->assertSame(0, $handler->destroyUserSessions('users', 'user-1')); $this->assertNull($handler->observedOwnerForTesting(self::SESSION_ID)); @@ -977,12 +976,11 @@ public function testClusterBulkDestroyRethrowsPayloadFailureAfterSuccessfulClean $owner = $this->ownerDigest('users', 'user-1'); $failure = new RuntimeException('payload failed'); $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('hKeys')->once()->andReturn(['invalid', self::SESSION_ID]); - $connection->shouldReceive('evalWithShaCache')->once()->andThrow($failure); - $connection->shouldReceive('hdel') - ->once() + $connection->expects('hKeys')->returns(['invalid', self::SESSION_ID]); + $connection->expects('evalSha')->throws($failure); + $connection->expects('hdel') ->with('sessions:_users:' . $owner . ':sessions', 'invalid') - ->andReturn(1); + ->returns(1); try { $this->handler(tracked: true)->destroyUserSessions('users', 'user-1'); @@ -1004,12 +1002,11 @@ public function testClusterBulkDestroyRetainsCleanupFailureWhenBothOperationsFai default => new UnexpectedValueException('payload failed'), }; $connection = $this->expectConnection(cluster: true); - $connection->shouldReceive('hKeys')->once()->andReturn(['invalid', self::SESSION_ID]); - $connection->shouldReceive('evalWithShaCache')->once()->andThrow($payloadFailure); - $connection->shouldReceive('hdel') - ->once() + $connection->expects('hKeys')->returns(['invalid', self::SESSION_ID]); + $connection->expects('evalSha')->throws($payloadFailure); + $connection->expects('hdel') ->with('sessions:_users:' . $owner . ':sessions', 'invalid') - ->andReturnFalse(); + ->returns(false); $caught = null; try { @@ -1032,13 +1029,13 @@ public function testClusterBulkDestroyRetainsCleanupFailureWhenBothOperationsFai #[DataProvider('invalidSessionIdProvider')] public function testManagedDeletesRejectInvalidSessionIdentifiers(string $sessionId): void { - $this->redis->shouldReceive('connection')->never(); + $this->redis->expects('connection')->never(); try { $this->handler(tracked: true)->destroyUserSession('users', 'user-1', $sessionId); $this->fail('Expected the scoped delete to reject the identifier.'); - } catch (InvalidArgumentException) { - $this->addToAssertionCount(1); + } catch (InvalidArgumentException $exception) { + $this->assertSame('The session identifier is invalid.', $exception->getMessage()); } $this->expectException(InvalidArgumentException::class); @@ -1046,6 +1043,9 @@ public function testManagedDeletesRejectInvalidSessionIdentifiers(string $sessio $this->handler(tracked: true)->destroyUserSessions('users', 'user-1', [$sessionId]); } + /** + * Provide invalid session identifiers. + */ public static function invalidSessionIdProvider(): array { return [ @@ -1058,7 +1058,7 @@ public static function invalidSessionIdProvider(): array public function testManagementRejectsAnEmptyAuthenticationProviderWithoutUsingRedis(): void { - $this->redis->shouldReceive('connection')->never(); + $this->redis->expects('connection')->never(); foreach ([ fn () => $this->handler(tracked: true)->userSessions('', 'user-1'), @@ -1082,7 +1082,7 @@ public function testRawConnectionExceptionsPropagateThroughTheHandler(): void { $connection = $this->expectConnection(); $failure = new RuntimeException('connection failed'); - $connection->shouldReceive('get')->once()->andThrow($failure); + $connection->expects('get')->throws($failure); try { $this->handler()->read(self::SESSION_ID); @@ -1092,6 +1092,9 @@ public function testRawConnectionExceptionsPropagateThroughTheHandler(): void } } + /** + * Create the session handler. + */ private function handler(bool $tracked = false, ?Container $container = null): RedisSessionHandler { return new RedisSessionHandler( @@ -1104,32 +1107,40 @@ private function handler(bool $tracked = false, ?Container $container = null): R ); } - private function expectConnection(bool $cluster = false): RedisConnection + /** + * Expect a raw connection lease and return its native client double. + */ + private function expectConnection(bool $cluster = false): (Redis&DoubleInterface)|(RedisCluster&DoubleInterface) { - $proxy = m::mock(RedisProxy::class); - $connection = m::mock(RedisConnection::class); - - $this->redis->shouldReceive('connection')->once()->with('session')->andReturn($proxy); - $proxy->shouldReceive('isCluster')->once()->andReturn($cluster); - $proxy->shouldReceive('withConnection') - ->once() - ->with(m::type('callable'), false) - ->andReturnUsing(static fn (callable $callback): mixed => $callback($connection)); - $connection->shouldReceive('withoutSerializationOrCompression') - ->once() - ->with(m::type('callable')) - ->andReturnUsing(static fn (callable $callback): mixed => $callback()); - - return $connection; + $client = Double::for($cluster ? RedisCluster::class : Redis::class)->strict(); + $client->expects('getOption')->with(Redis::OPT_SERIALIZER)->returns(Redis::SERIALIZER_NONE); + $client->expects('getOption')->with(Redis::OPT_COMPRESSION)->returns(Redis::COMPRESSION_NONE); + $client->allows('clearLastError'); + $client->allows('getLastError')->returns(null); + + $connection = ($cluster ? new PhpRedisClusterConnectionStub : new PhpRedisConnectionStub) + ->setActiveConnection($client); + $proxy = Double::for(RedisProxy::class)->strict(); + + $this->redis->allows('connection')->with('session')->returns($proxy); + $proxy->expects('isCluster')->returns($cluster); + $proxy->expects('withConnection') + ->with(Argument::type('callable'), false) + ->resolves(static fn (callable $callback): mixed => $callback($connection)); + + return $client; } + /** + * Create a container with an authenticated guard. + */ private function authenticatedContainer( string $userId, bool $withRequest, ?string $authProvider = 'users', ): Container { - $guard = m::mock(Guard::class); - $guard->shouldReceive('id')->once()->andReturn($userId); + $guard = Double::for(Guard::class)->strict(); + $guard->expects('id')->returns($userId); $guardConfig = ['driver' => 'custom']; @@ -1160,6 +1171,9 @@ private function authenticatedContainer( return $container; } + /** + * Calculate the provider-qualified owner digest. + */ private function ownerDigest(string $authProvider, string $userId): string { return substr( @@ -1172,11 +1186,17 @@ private function ownerDigest(string $authProvider, string $userId): string class ObservableRedisSessionHandler extends RedisSessionHandler { + /** + * Record an observed session owner. + */ public function rememberOwnerForTesting(string $sessionId, string $owner): void { $this->rememberOwner($sessionId, $owner); } + /** + * Get the observed session owner. + */ public function observedOwnerForTesting(string $sessionId): ?string { return $this->observedOwner($sessionId); diff --git a/tests/Session/SessionGarbageCollectCommandTest.php b/tests/Session/SessionGarbageCollectCommandTest.php index 3255675be5..4fccf278c1 100644 --- a/tests/Session/SessionGarbageCollectCommandTest.php +++ b/tests/Session/SessionGarbageCollectCommandTest.php @@ -7,7 +7,8 @@ use Hypervel\Session\SessionManager; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use SessionHandlerInterface; @@ -15,13 +16,15 @@ #[WithConfig('session.lifetime', 7)] class SessionGarbageCollectCommandTest extends TestCase { + use VerifiesDoubles; + #[TestWith([2, 0, 'ran successfully'], 'sessions removed')] #[TestWith([0, 0, 'ran successfully'], 'nothing expired')] #[TestWith([false, 1, 'failed'], 'handler failure')] public function testRegisteredCommandCollectsTheConfiguredSessionDriver(int|false $result, int $exitCode, string $message): void { - $handler = m::mock(SessionHandlerInterface::class); - $handler->expects('gc')->with(420)->andReturn($result); + $handler = Double::for(SessionHandlerInterface::class)->strict(); + $handler->expects('gc')->with(420)->returns($result); $this->app->make(SessionManager::class)->extend('custom', fn () => $handler); $this->artisan('session:garbage-collect') diff --git a/tests/Session/SessionStoreBackedEnumTest.php b/tests/Session/SessionStoreBackedEnumTest.php index 7933738b76..cde3ccac46 100644 --- a/tests/Session/SessionStoreBackedEnumTest.php +++ b/tests/Session/SessionStoreBackedEnumTest.php @@ -6,7 +6,8 @@ use Hypervel\Session\Store; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use SessionHandlerInterface; enum SessionKey: string @@ -33,6 +34,8 @@ enum SessionUnitKey class SessionStoreBackedEnumTest extends TestCase { + use VerifiesDoubles; + // ========================================================================= // get() tests // ========================================================================= @@ -466,7 +469,7 @@ public function testDecrementWithEnum(): void public function testFlashWithEnum(): void { $session = $this->getSession(); - $session->getHandler()->shouldReceive('read')->once()->andReturn(serialize([])); + $session->getHandler()->expects('read')->returns(serialize([])); $session->start(); $session->flash(SessionKey::User, 'flash-value'); @@ -482,7 +485,7 @@ public function testFlashWithEnum(): void public function testFlashWithEnumIsProperlyAged(): void { $session = $this->getSession(); - $session->getHandler()->shouldReceive('read')->once()->andReturn(serialize([])); + $session->getHandler()->expects('read')->returns(serialize([])); $session->start(); $session->flash(SessionKey::User, 'flash-value'); @@ -507,7 +510,7 @@ public function testFlashWithEnumIsProperlyAged(): void public function testNowWithEnum(): void { $session = $this->getSession(); - $session->getHandler()->shouldReceive('read')->once()->andReturn(serialize([])); + $session->getHandler()->expects('read')->returns(serialize([])); $session->start(); $session->now(SessionKey::User, 'now-value'); @@ -740,7 +743,7 @@ public function testDecrementWithUnitEnum(): void public function testFlashWithUnitEnum(): void { $session = $this->getSession(); - $session->getHandler()->shouldReceive('read')->once()->andReturn(serialize([])); + $session->getHandler()->expects('read')->returns(serialize([])); $session->start(); $session->flash(SessionUnitKey::User, 'flash-value'); @@ -756,7 +759,7 @@ public function testFlashWithUnitEnum(): void public function testNowWithUnitEnum(): void { $session = $this->getSession(); - $session->getHandler()->shouldReceive('read')->once()->andReturn(serialize([])); + $session->getHandler()->expects('read')->returns(serialize([])); $session->start(); $session->now(SessionUnitKey::User, 'now-value'); @@ -820,11 +823,14 @@ public function testMixedBackedAndUnitEnums(): void // Helper methods // ========================================================================= + /** + * Create a session store with an isolated handler. + */ protected function getSession(string $serialization = 'php'): Store { return new Store( 'test-session', - m::mock(SessionHandlerInterface::class), + Double::for(SessionHandlerInterface::class)->strict(), 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', $serialization ); diff --git a/tests/Session/UserSessionIdentityTest.php b/tests/Session/UserSessionIdentityTest.php index 4b5a8dbdf2..198b7b74d0 100644 --- a/tests/Session/UserSessionIdentityTest.php +++ b/tests/Session/UserSessionIdentityTest.php @@ -11,16 +11,19 @@ use Hypervel\Session\UserSessionIdentity; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use function Hypervel\Coroutine\parallel; class UserSessionIdentityTest extends TestCase { + use VerifiesDoubles; + public function testItResolvesTheSelectedGuardIdentity(): void { - $guard = m::mock(Guard::class); - $guard->shouldReceive('id')->once()->andReturn(42); + $guard = Double::for(Guard::class)->strict(); + $guard->expects('id')->returns(42); $container = $this->containerWithGuard($guard, 'users'); @@ -34,8 +37,8 @@ public function testItResolvesTheSelectedGuardIdentity(): void public function testItReturnsAnUnresolvedIdentityWithoutASelectedUser(): void { - $guard = m::mock(Guard::class); - $guard->shouldReceive('id')->once()->andReturnNull(); + $guard = Double::for(Guard::class)->strict(); + $guard->expects('id')->returns(null); $container = $this->containerWithGuard($guard, 'users'); @@ -54,8 +57,8 @@ public function testItReturnsAnUnresolvedIdentityWithoutASelectedUser(): void public function testAuthenticatedProviderlessGuardIsExplicitlyUnowned(): void { - $guard = m::mock(Guard::class); - $guard->shouldReceive('id')->once()->andReturn('custom-user'); + $guard = Double::for(Guard::class)->strict(); + $guard->expects('id')->returns('custom-user'); $identity = UserSessionIdentity::resolve( $this->containerWithGuard($guard), @@ -98,13 +101,13 @@ public function testSuppressionSurvivesRepeatedResolution(): void public function testSuppressionShortCircuitsGuardResolution(): void { $sessionId = str_repeat('a', 40); - $container = m::mock(Container::class); - $container->shouldReceive('has')->never(); - $container->shouldReceive('make')->never(); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('has')->never(); + $container->expects('make')->never(); UserSessionIdentity::suppress($sessionId); - $identity = UserSessionIdentity::resolve($container, $sessionId); + $identity = UserSessionIdentity::resolve($container->instance(), $sessionId); $this->assertFalse($identity->isResolved()); $this->assertTrue($identity->isUnowned()); @@ -117,8 +120,8 @@ public function testSuppressionIsScopedOnlyToTheSessionIdentifier(): void $markedSessionId = str_repeat('a', 40); $otherSessionId = str_repeat('b', 40); - $guard = m::mock(Guard::class); - $guard->shouldReceive('id')->once()->andReturn('user-1'); + $guard = Double::for(Guard::class)->strict(); + $guard->expects('id')->returns('user-1'); $container = $this->containerWithGuard($guard, 'users'); @@ -154,6 +157,9 @@ function () use ($sessionId): bool { $this->assertFalse($unresolved); } + /** + * Create a container with the selected authentication guard. + */ private function containerWithGuard(Guard $guard, ?string $provider = null): Container { $guardConfig = ['driver' => 'custom']; diff --git a/tests/Session/UserSessionsTest.php b/tests/Session/UserSessionsTest.php index 1779f0f3eb..362635cb38 100644 --- a/tests/Session/UserSessionsTest.php +++ b/tests/Session/UserSessionsTest.php @@ -17,12 +17,15 @@ use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use SessionHandlerInterface; class UserSessionsTest extends TestCase { + use VerifiesDoubles; + private const string AUTH_PROVIDER = 'users'; private const string CURRENT_SESSION_ID = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; @@ -261,12 +264,12 @@ public function testRepeatedSavesRetainReplacementSuppression(): void $store->save(); $store->save(); - $container = m::mock(Container::class); - $container->shouldReceive('has')->never(); - $container->shouldReceive('make')->never(); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('has')->never(); + $container->expects('make')->never(); - $this->assertTrue(UserSessionIdentity::resolve($container, $replacementSessionId)->isUnowned()); - $this->assertTrue(UserSessionIdentity::resolve($container, $replacementSessionId)->isUnowned()); + $this->assertTrue(UserSessionIdentity::resolve($container->instance(), $replacementSessionId)->isUnowned()); + $this->assertTrue(UserSessionIdentity::resolve($container->instance(), $replacementSessionId)->isUnowned()); $this->assertSame([$replacementSessionId, $replacementSessionId], $handler->writtenSessionIds); } @@ -283,8 +286,8 @@ public function testLaterLoginStyleRegenerationRotatesBeyondTheUnownedReplacemen $store->regenerate(true); - $guard = m::mock(Guard::class); - $guard->shouldReceive('id')->once()->andReturn($userId); + $guard = Double::for(Guard::class)->strict(); + $guard->expects('id')->returns($userId); $container = $this->identityContainer($guard); diff --git a/tests/Signal/SignalDeregisterListenerTest.php b/tests/Signal/SignalDeregisterListenerTest.php index eb0f938ed1..08445920e4 100644 --- a/tests/Signal/SignalDeregisterListenerTest.php +++ b/tests/Signal/SignalDeregisterListenerTest.php @@ -10,41 +10,42 @@ use Hypervel\Signal\SignalDeregisterListener; use Hypervel\Signal\SignalManager; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class SignalDeregisterListenerTest extends TestCase { + use VerifiesDoubles; + public function testHandleOnWorkerExitStopsSignalManager(): void { - $container = m::mock(ContainerContract::class); - $manager = m::mock(SignalManager::class); - $event = m::mock(OnWorkerExit::class); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $manager = Double::for(SignalManager::class)->strict(); + $event = Double::for(OnWorkerExit::class)->strict(); - $container->shouldReceive('make') + $container->expects('make') ->with(SignalManager::class) - ->once() - ->andReturn($manager); + ->returns($manager); - $manager->shouldReceive('stop')->once(); + $manager->expects('stop'); - $listener = new SignalDeregisterListener($container); + $listener = new SignalDeregisterListener($container->instance()); $listener->handle($event); } public function testHandleAfterProcessHandleStopsSignalManager(): void { - $container = m::mock(ContainerContract::class); - $manager = m::mock(SignalManager::class); - $event = m::mock(AfterProcessHandle::class); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $manager = Double::for(SignalManager::class)->strict(); + $event = Double::for(AfterProcessHandle::class)->strict(); - $container->shouldReceive('make') + $container->expects('make') ->with(SignalManager::class) - ->once() - ->andReturn($manager); + ->returns($manager); - $manager->shouldReceive('stop')->once(); + $manager->expects('stop'); - $listener = new SignalDeregisterListener($container); + $listener = new SignalDeregisterListener($container->instance()); $listener->handle($event); } } diff --git a/tests/Signal/SignalManagerListenRollbackTest.php b/tests/Signal/SignalManagerListenRollbackTest.php index 9e4835ddc1..e899fc3329 100644 --- a/tests/Signal/SignalManagerListenRollbackTest.php +++ b/tests/Signal/SignalManagerListenRollbackTest.php @@ -7,7 +7,6 @@ use Hypervel\Config\Repository; use Hypervel\Container\Container; use Hypervel\Contracts\Config\Repository as ConfigContract; -use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\Contracts\Debug\ExceptionHandler as ExceptionHandlerContract; use Hypervel\Contracts\Signal\SignalHandler; use Hypervel\Coroutine\Coroutine; @@ -18,7 +17,8 @@ use Hypervel\Signal\SignalManager; use Hypervel\Support\SafeCaller; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use RuntimeException; use Swoole\Coroutine as SwooleCoroutine; @@ -26,6 +26,8 @@ class SignalManagerListenRollbackTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; #[RunInSeparateProcess] @@ -34,8 +36,8 @@ public function testPartialListenerCreationCancelsEarlierWatchers(): void SwooleCoroutine::set(['max_coroutine' => 2]); SwooleCoroutine\run(function (): void { - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $exceptionHandler->shouldNotReceive('report'); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $exceptionHandler->expects('report')->never(); Container::getInstance()->instance( ExceptionHandlerContract::class, $exceptionHandler, @@ -51,13 +53,13 @@ public function handle(int $signal): void { } }; - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make')->with(ConfigContract::class)->andReturn(new Repository([ + $container = new Container; + $container->instance(ConfigContract::class, new Repository([ 'signal' => ['handlers' => [$handler::class]], ])); - $container->shouldReceive('make')->with(SafeCaller::class)->andReturn(new SafeCaller($container)); - $container->shouldReceive('make')->with(SignalRegistry::class)->andReturn(new SignalRegistry); - $container->shouldReceive('make')->with($handler::class)->andReturn($handler); + $container->instance(SafeCaller::class, new SafeCaller($container)); + $container->instance(SignalRegistry::class, new SignalRegistry); + $container->instance($handler::class, $handler); $manager = new SignalManager($container); try { @@ -75,7 +77,7 @@ public function handle(int $signal): void public function testOwnerCancellationAfterWatcherStartRollsBackTheWatcher(): void { SwooleCoroutine\run(function (): void { - $exceptionHandler = m::mock(ExceptionHandlerContract::class); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); Container::getInstance()->instance( ExceptionHandlerContract::class, $exceptionHandler, @@ -88,10 +90,9 @@ public function testOwnerCancellationAfterWatcherStartRollsBackTheWatcher(): voi $parentCancellation = null; $childCoroutineId = null; - $exceptionHandler->shouldReceive('report') - ->once() + $exceptionHandler->expects('report') ->with($hookFailure) - ->andReturnUsing(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { + ->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { $childCoroutineId = EngineCoroutine::id(); $reportStarted->push(true); $releaseReport->pop(); @@ -116,13 +117,13 @@ public function handle(int $signal): void { } }; - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make')->with(ConfigContract::class)->andReturn(new Repository([ + $container = new Container; + $container->instance(ConfigContract::class, new Repository([ 'signal' => ['handlers' => [$handler::class]], ])); - $container->shouldReceive('make')->with(SafeCaller::class)->andReturn(new SafeCaller($container)); - $container->shouldReceive('make')->with(SignalRegistry::class)->andReturn(new SignalRegistry); - $container->shouldReceive('make')->with($handler::class)->andReturn($handler); + $container->instance(SafeCaller::class, new SafeCaller($container)); + $container->instance(SignalRegistry::class, new SignalRegistry); + $container->instance($handler::class, $handler); $manager = new SignalManager($container); try { diff --git a/tests/Signal/SignalManagerNonCoroutineTest.php b/tests/Signal/SignalManagerNonCoroutineTest.php index 0f720ce4ca..3645a63f19 100644 --- a/tests/Signal/SignalManagerNonCoroutineTest.php +++ b/tests/Signal/SignalManagerNonCoroutineTest.php @@ -14,22 +14,25 @@ use Hypervel\Support\SafeCaller; use Hypervel\Tests\Signal\Fixtures\SignalHandlerStub; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class SignalManagerNonCoroutineTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; public function testListenDoesNotResolveHandlersOutsideACoroutine(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make')->with(ConfigContract::class)->andReturn(new Repository([ + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->allows('make')->with(ConfigContract::class)->returns(new Repository([ 'signal' => ['handlers' => [SignalHandlerStub::class]], ])); - $container->shouldReceive('make')->with(SafeCaller::class)->andReturn(new SafeCaller($container)); - $container->shouldReceive('make')->with(SignalRegistry::class)->andReturn(new SignalRegistry); - $container->shouldNotReceive('make')->with(SignalHandlerStub::class); - $manager = new SignalManager($container); + $container->allows('make')->with(SafeCaller::class)->returns(new SafeCaller($container->instance())); + $container->allows('make')->with(SignalRegistry::class)->returns(new SignalRegistry); + $container->expects('make')->with(SignalHandlerStub::class)->never(); + $manager = new SignalManager($container->instance()); $this->assertFalse(Coroutine::inCoroutine()); diff --git a/tests/Signal/SignalManagerTest.php b/tests/Signal/SignalManagerTest.php index 6791f78b76..483f3064d9 100644 --- a/tests/Signal/SignalManagerTest.php +++ b/tests/Signal/SignalManagerTest.php @@ -20,13 +20,17 @@ use Hypervel\Tests\Signal\Fixtures\SignalHandlerStub; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use RuntimeException; use Swoole\Coroutine as SwooleCoroutine; class SignalManagerTest extends TestCase { + use VerifiesDoubles; + #[RunInSeparateProcess] public function testCommandTrapsShareTheWorkerListenerAndUntrapOnlyTheirOwnHandlers(): void { @@ -132,10 +136,10 @@ public function handle(int $signal): void throw new RuntimeException('Signal handler failed.'); } }; - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $exceptionHandler->shouldReceive('report') - ->twice() - ->with(m::type(RuntimeException::class)); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $exceptionHandler->expects('report') + ->times(2) + ->with(Argument::type(RuntimeException::class)); $container = new Container; $container->instance(ContainerContract::class, $container); $container->instance(ConfigContract::class, new Repository([ @@ -493,14 +497,14 @@ public function handle(int $signal): void public function testListenAfterStopDoesNotResolveHandlersOrSpawnWatchers(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make')->with(ConfigContract::class)->andReturn(new Repository([ + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->allows('make')->with(ConfigContract::class)->returns(new Repository([ 'signal' => ['handlers' => [SignalHandlerStub::class]], ])); - $container->shouldReceive('make')->with(SafeCaller::class)->andReturn(new SafeCaller($container)); - $container->shouldReceive('make')->with(SignalRegistry::class)->andReturn(new SignalRegistry); - $container->shouldNotReceive('make')->with(SignalHandlerStub::class); - $manager = new SignalManager($container); + $container->allows('make')->with(SafeCaller::class)->returns(new SafeCaller($container->instance())); + $container->allows('make')->with(SignalRegistry::class)->returns(new SignalRegistry); + $container->expects('make')->with(SignalHandlerStub::class)->never(); + $manager = new SignalManager($container->instance()); $manager->stop(); $coroutinesBeforeListen = SwooleCoroutine::stats()['coroutine_num']; @@ -538,15 +542,15 @@ protected function createManager(SignalHandler $handler): SignalManager */ protected function createManagerFromConfig(array $handlers, array $instances = []): SignalManager { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make')->with(ConfigContract::class)->andReturn(new Repository([ + $container = new Container; + $container->instance(ConfigContract::class, new Repository([ 'signal' => ['handlers' => $handlers], ])); - $container->shouldReceive('make')->with(SafeCaller::class)->andReturn(new SafeCaller($container)); - $container->shouldReceive('make')->with(SignalRegistry::class)->andReturn(new SignalRegistry); + $container->instance(SafeCaller::class, new SafeCaller($container)); + $container->instance(SignalRegistry::class, new SignalRegistry); foreach ($instances as $class => $instance) { - $container->shouldReceive('make')->with($class)->andReturn($instance); + $container->instance($class, $instance); } return new SignalManager($container); diff --git a/tests/Signal/SignalRegisterListenerTest.php b/tests/Signal/SignalRegisterListenerTest.php index 175c9f5df8..4092eb66fa 100644 --- a/tests/Signal/SignalRegisterListenerTest.php +++ b/tests/Signal/SignalRegisterListenerTest.php @@ -11,45 +11,44 @@ use Hypervel\Signal\SignalManager; use Hypervel\Signal\SignalRegisterListener; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class SignalRegisterListenerTest extends TestCase { + use VerifiesDoubles; + public function testHandleBeforeWorkerStartListensForWorker(): void { - $container = m::mock(ContainerContract::class); - $manager = m::mock(SignalManager::class); - $event = m::mock(BeforeWorkerStart::class); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $manager = Double::for(SignalManager::class)->strict(); + $event = Double::for(BeforeWorkerStart::class)->strict(); - $container->shouldReceive('make') + $container->expects('make') ->with(SignalManager::class) - ->once() - ->andReturn($manager); + ->returns($manager); - $manager->shouldReceive('listen') - ->with(SignalHandler::WORKER) - ->once(); + $manager->expects('listen') + ->with(SignalHandler::WORKER); - $listener = new SignalRegisterListener($container); + $listener = new SignalRegisterListener($container->instance()); $listener->handle($event); } public function testHandleBeforeProcessHandleListensForServerProcess(): void { - $container = m::mock(ContainerContract::class); - $manager = m::mock(SignalManager::class); - $event = m::mock(BeforeProcessHandle::class); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $manager = Double::for(SignalManager::class)->strict(); + $event = Double::for(BeforeProcessHandle::class)->strict(); - $container->shouldReceive('make') + $container->expects('make') ->with(SignalManager::class) - ->once() - ->andReturn($manager); + ->returns($manager); - $manager->shouldReceive('listen') - ->with(SignalHandler::SERVER_PROCESS) - ->once(); + $manager->expects('listen') + ->with(SignalHandler::SERVER_PROCESS); - $listener = new SignalRegisterListener($container); + $listener = new SignalRegisterListener($container->instance()); $listener->handle($event); } } diff --git a/tests/SlackNotificationChannel/NotificationSlackChannelTest.php b/tests/SlackNotificationChannel/NotificationSlackChannelTest.php index ea39b202b1..7f036a57a1 100644 --- a/tests/SlackNotificationChannel/NotificationSlackChannelTest.php +++ b/tests/SlackNotificationChannel/NotificationSlackChannelTest.php @@ -15,19 +15,22 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\SlackNotificationChannel\Slack\Fixtures\SlackChannelTestNotifiable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class NotificationSlackChannelTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('payloadDataProvider')] public function testCorrectPayloadIsSentToSlack(Notification $notification, array $payload): void { - $guzzleHttp = m::mock(Client::class); + $guzzleHttp = Double::for(Client::class)->strict(); $slackChannel = new SlackWebhookChannel($guzzleHttp); - $guzzleHttp->shouldReceive('post')->andReturnUsing(function (string $argUrl, array $argPayload) use ($payload): Response { + $guzzleHttp->expects('post')->resolves(function (string $argUrl, array $argPayload) use ($payload): Response { $this->assertSame('url', $argUrl); $this->assertEquals($payload, $argPayload); @@ -52,7 +55,7 @@ public static function payloadDataProvider(): array public function testModernBlockKitPayloadIsSentToSlack(): void { - $guzzleHttp = m::mock(Client::class); + $guzzleHttp = Double::for(Client::class)->strict(); $notification = new class extends Notification { /** * Get the Slack representation of the notification. @@ -63,12 +66,12 @@ public function toSlack(mixed $notifiable): SlackMessage } }; - $guzzleHttp->shouldReceive('post')->once()->with('url', [ + $guzzleHttp->expects('post')->with('url', [ 'json' => [ 'channel' => null, 'text' => 'Modern content', ], - ])->andReturn(new Response); + ])->returns(new Response); $response = (new SlackWebhookChannel($guzzleHttp))->send( new SlackChannelTestNotifiable('url'), @@ -153,8 +156,8 @@ public function testAttachmentFieldTitlesThatNamePhpFunctionsAreNotCalled(): voi public function testDisabledWebhookDoesNotRequireASlackMessageMethod(): void { - $http = m::mock(Client::class); - $http->shouldNotReceive('post'); + $http = Double::for(Client::class)->strict(); + $http->expects('post')->never(); $this->assertNull((new SlackWebhookChannel($http))->send( new SlackChannelTestNotifiable, diff --git a/tests/SlackNotificationChannel/NotificationTransportQueueTest.php b/tests/SlackNotificationChannel/NotificationTransportQueueTest.php index ed216deac1..be289a9fc2 100644 --- a/tests/SlackNotificationChannel/NotificationTransportQueueTest.php +++ b/tests/SlackNotificationChannel/NotificationTransportQueueTest.php @@ -30,7 +30,8 @@ use Hypervel\Notifications\Slack\SlackRoute; use Hypervel\Notifications\SlackChannelServiceProvider; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Psr\Http\Message\ResponseInterface; use stdClass; @@ -41,6 +42,8 @@ class NotificationTransportQueueTest extends TestCase { + use VerifiesDoubles; + /** * Register the Slack channel package. */ @@ -195,7 +198,7 @@ public function testDecliningQueueingDoesNotInspectAnUnserializableBody(): void public function testExistingSymfonyMailFailureConversionRemainsUnchanged(): void { - $response = m::mock(SymfonyResponse::class); + $response = Double::for(SymfonyResponse::class)->strict(); $original = new HttpTransportException('Mailer HTTP failure', $response); $manager = $this->app->make(ChannelManager::class); $manager->extend('test-mail', fn (): NotificationTransportFailingChannel => new NotificationTransportFailingChannel($original)); diff --git a/tests/SlackNotificationChannel/SlackNotificationRouterChannelTest.php b/tests/SlackNotificationChannel/SlackNotificationRouterChannelTest.php index 75879332ad..cf0548140c 100644 --- a/tests/SlackNotificationChannel/SlackNotificationRouterChannelTest.php +++ b/tests/SlackNotificationChannel/SlackNotificationRouterChannelTest.php @@ -15,19 +15,23 @@ use Hypervel\Tests\SlackNotificationChannel\Slack\Fixtures\SlackChannelTestNotifiable; use Hypervel\Tests\SlackNotificationChannel\Slack\Fixtures\SlackChannelTestNotification; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class SlackNotificationRouterChannelTest extends TestCase { + use VerifiesDoubles; + public function testItRoutesTheNotificationToTheWebhookChannelWhenTheNotifiableRouteIsAStringUrl(): void { $app = new Container; - $webhook = m::mock(SlackWebhookChannel::class); - $webApi = m::mock(SlackWebApiChannel::class); - $webhook->shouldReceive('send')->once()->withArgs(function (SlackChannelTestNotifiable $notifiable, Notification $notification): bool { + $webhook = Double::for(SlackWebhookChannel::class)->strict(); + $webApi = Double::for(SlackWebApiChannel::class)->strict(); + $webhook->expects('send')->with(Argument::all(function (SlackChannelTestNotifiable $notifiable, Notification $notification): bool { return $notifiable->routeNotificationFor('slack', $notification) === 'http://example.com'; - })->andReturn(new Response); - $webApi->shouldNotReceive('send'); + }))->returns(new Response); + $webApi->expects('send')->never(); $app->instance(SlackWebhookChannel::class, $webhook); $app->instance(SlackWebApiChannel::class, $webApi); @@ -39,12 +43,12 @@ public function testItRoutesTheNotificationToTheWebhookChannelWhenTheNotifiableR public function testItRoutesTheNotificationToTheWebhookChannelWhenTheNotifiableRouteIsAPsrUrlInstance(): void { $app = new Container; - $webhook = m::mock(SlackWebhookChannel::class); - $webApi = m::mock(SlackWebApiChannel::class); - $webhook->shouldReceive('send')->once()->withArgs(function (SlackChannelTestNotifiable $notifiable, Notification $notification): bool { + $webhook = Double::for(SlackWebhookChannel::class)->strict(); + $webApi = Double::for(SlackWebApiChannel::class)->strict(); + $webhook->expects('send')->with(Argument::all(function (SlackChannelTestNotifiable $notifiable, Notification $notification): bool { return $notifiable->routeNotificationFor('slack', $notification) instanceof Uri; - })->andReturn(new Response); - $webApi->shouldNotReceive('send'); + }))->returns(new Response); + $webApi->expects('send')->never(); $app->instance(SlackWebhookChannel::class, $webhook); $app->instance(SlackWebApiChannel::class, $webApi); @@ -56,12 +60,12 @@ public function testItRoutesTheNotificationToTheWebhookChannelWhenTheNotifiableR public function testItRoutesTheNotificationToTheWebApiChannelWhenTheNotifiableRouteIsNotAnUrl(): void { $app = new Container; - $webhook = m::mock(SlackWebhookChannel::class); - $webApi = m::mock(SlackWebApiChannel::class); - $webhook->shouldNotReceive('send'); - $webApi->shouldReceive('send')->once()->withArgs(function (SlackChannelTestNotifiable $notifiable, Notification $notification): bool { + $webhook = Double::for(SlackWebhookChannel::class)->strict(); + $webApi = Double::for(SlackWebApiChannel::class)->strict(); + $webhook->expects('send')->never(); + $webApi->expects('send')->with(Argument::all(function (SlackChannelTestNotifiable $notifiable, Notification $notification): bool { return $notifiable->routeNotificationFor('slack', $notification) === '#general'; - })->andReturn($response = new HttpResponse(new Response)); + }))->returns($response = new HttpResponse(new Response)); $app->instance(SlackWebhookChannel::class, $webhook); $app->instance(SlackWebApiChannel::class, $webApi); @@ -76,10 +80,10 @@ public function testItRoutesTheNotificationToTheWebApiChannelWhenTheNotifiableRo public function testItStopsSendingWhenTheNotifiableRouteIsFalse(): void { $app = new Container; - $webhook = m::mock(SlackWebhookChannel::class); - $webApi = m::mock(SlackWebApiChannel::class); - $webhook->shouldNotReceive('send'); - $webApi->shouldNotReceive('send'); + $webhook = Double::for(SlackWebhookChannel::class)->strict(); + $webApi = Double::for(SlackWebApiChannel::class)->strict(); + $webhook->expects('send')->never(); + $webApi->expects('send')->never(); $app->instance(SlackWebhookChannel::class, $webhook); $app->instance(SlackWebApiChannel::class, $webApi); diff --git a/tests/Socialite/AbstractProviderTest.php b/tests/Socialite/AbstractProviderTest.php index 2a621255c4..c60e0fe87c 100644 --- a/tests/Socialite/AbstractProviderTest.php +++ b/tests/Socialite/AbstractProviderTest.php @@ -10,7 +10,6 @@ use Hypervel\Tests\Socialite\Fixtures\GenericTestProviderStub; use Hypervel\Tests\TestCase; use LogicException; -use Mockery as m; use Swoole\Coroutine\Channel; use Throwable; @@ -27,7 +26,7 @@ class AbstractProviderTest extends TestCase public function testWithConfigSeedsBaselineConfig(): void { $provider = new GenericTestProviderStub( - m::mock(Request::class), + new Request, ); $provider->withConfig([ 'base_url' => 'https://idp.example.com', @@ -41,7 +40,7 @@ public function testWithConfigSeedsBaselineConfig(): void public function testSetConfigOverridesPerRequest(): void { $provider = new GenericTestProviderStub( - m::mock(Request::class), + new Request, ); $provider->withConfig([ 'base_url' => 'https://idp.example.com', @@ -57,7 +56,7 @@ public function testSetConfigOverridesPerRequest(): void public function testGetConfigReturnsDefaultForMissingKeys(): void { $provider = new GenericTestProviderStub( - m::mock(Request::class), + new Request, ); $this->assertNull($provider->getProviderConfig('nonexistent')); @@ -66,7 +65,7 @@ public function testGetConfigReturnsDefaultForMissingKeys(): void public function testGetConfigDelegatesNullAndZeroKeysToArr(): void { - $provider = new GenericTestProviderStub(m::mock(Request::class)); + $provider = new GenericTestProviderStub(new Request); $provider->withConfig([ 0 => 'zero', 'realm' => 'default', @@ -79,10 +78,10 @@ public function testGetConfigDelegatesNullAndZeroKeysToArr(): void public function testSetHttpClient(): void { $provider = new GenericTestProviderStub( - m::mock(Request::class), + new Request, ); - $client = m::mock(Client::class); + $client = new Client; $provider->setHttpClient($client); $this->assertSame($client, $provider->getProviderHttpClient()); @@ -91,7 +90,7 @@ public function testSetHttpClient(): void public function testStatelessToggle(): void { $provider = new GenericTestProviderStub( - m::mock(Request::class), + new Request, ); $this->assertTrue($provider->providerUsesState()); @@ -103,8 +102,8 @@ public function testStatelessToggle(): void public function testSetRequest(): void { - $originalRequest = m::mock(Request::class); - $newRequest = m::mock(Request::class); + $originalRequest = new Request; + $newRequest = new Request; $provider = new GenericTestProviderStub($originalRequest); $provider->setRequest($newRequest); @@ -190,7 +189,7 @@ public function testRecycledObjectIdsCannotReuseProviderContext(): void public function testBaselineConfigSurvivesAcrossCoroutines(): void { $provider = new GenericTestProviderStub( - m::mock(Request::class), + new Request, ); $provider->withConfig([ 'base_url' => 'https://idp.example.com', @@ -212,7 +211,7 @@ public function testBaselineConfigSurvivesAcrossCoroutines(): void public function testSetConfigIsIsolatedPerCoroutine(): void { $provider = new GenericTestProviderStub( - m::mock(Request::class), + new Request, ); $provider->withConfig([ 'realm' => 'default', diff --git a/tests/Socialite/BitbucketProviderTest.php b/tests/Socialite/BitbucketProviderTest.php index 968a3ba449..53a20a2859 100644 --- a/tests/Socialite/BitbucketProviderTest.php +++ b/tests/Socialite/BitbucketProviderTest.php @@ -10,24 +10,27 @@ use Hypervel\Http\Request; use Hypervel\Socialite\Two\BitbucketProvider; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class BitbucketProviderTest extends TestCase { + use VerifiesDoubles; + public function testUserAndEmailRequestsUseBearerAuthorizationWithoutTokenQueries(): void { $provider = new BitbucketProvider( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect', ); - $httpClient = m::mock(Client::class); + $httpClient = Double::for(Client::class)->strict(); $provider->setHttpClient($httpClient); $httpClient->expects('get')->with('https://api.bitbucket.org/2.0/user', [ RequestOptions::HEADERS => ['Authorization' => 'Bearer access-token'], - ])->andReturn(new Response(body: json_encode([ + ])->returns(new Response(body: json_encode([ 'uuid' => 'user-id', 'username' => 'taylor', 'display_name' => 'Taylor Otwell', @@ -35,7 +38,7 @@ public function testUserAndEmailRequestsUseBearerAuthorizationWithoutTokenQuerie ]))); $httpClient->expects('get')->with('https://api.bitbucket.org/2.0/user/emails', [ RequestOptions::HEADERS => ['Authorization' => 'Bearer access-token'], - ])->andReturn(new Response(body: json_encode([ + ])->returns(new Response(body: json_encode([ 'values' => [[ 'type' => 'email', 'is_primary' => true, diff --git a/tests/Socialite/EmailLookupTest.php b/tests/Socialite/EmailLookupTest.php index 9233da4687..2ec130350a 100644 --- a/tests/Socialite/EmailLookupTest.php +++ b/tests/Socialite/EmailLookupTest.php @@ -10,7 +10,9 @@ use Hypervel\Socialite\Two\BitbucketProvider; use Hypervel\Socialite\Two\GithubProvider; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -18,6 +20,8 @@ class EmailLookupTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('emailFailures')] public function testOnlyOrdinaryEmailFailuresAllowAuthenticationToContinue(string $providerClass, string $kind): void { @@ -27,13 +31,18 @@ public function testOnlyOrdinaryEmailFailuresAllowAuthenticationToContinue(strin default => new RuntimeException('Email lookup failed.'), }; $provider = new $providerClass(Request::create('/'), 'client', 'secret', 'redirect'); - $http = m::mock(Client::class); + $http = Double::for(Client::class)->strict(); $provider->setHttpClient($http); $userData = $providerClass === GithubProvider::class ? ['id' => 'user-id', 'node_id' => 'node-id', 'login' => 'taylor', 'avatar_url' => 'https://example.com/avatar'] : ['uuid' => 'user-id', 'username' => 'taylor']; - $http->shouldReceive('get')->once()->ordered()->andReturn(new Response(body: json_encode($userData))); - $http->shouldReceive('get')->once()->ordered()->andThrow($failure); + $userUrl = $providerClass === GithubProvider::class + ? 'https://api.github.com/user' + : 'https://api.bitbucket.org/2.0/user'; + $http->expects('get')->with($userUrl, Argument::type('array'))->ordered() + ->returns(new Response(body: json_encode($userData))); + $http->expects('get')->with($userUrl . '/emails', Argument::type('array'))->ordered() + ->throws($failure); $caught = null; $user = null; diff --git a/tests/Socialite/FacebookProviderOIDCTokenTest.php b/tests/Socialite/FacebookProviderOIDCTokenTest.php index 315d8454d4..7a47079d6a 100644 --- a/tests/Socialite/FacebookProviderOIDCTokenTest.php +++ b/tests/Socialite/FacebookProviderOIDCTokenTest.php @@ -14,7 +14,8 @@ use Hypervel\Socialite\Two\User; use Hypervel\Tests\Socialite\Fixtures\CreatesJwksFixtures; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use UnexpectedValueException; use function Hypervel\Coroutine\parallel; @@ -22,6 +23,7 @@ class FacebookProviderOIDCTokenTest extends TestCase { use CreatesJwksFixtures; + use VerifiesDoubles; public function testItValidatesExpectedNonceForFacebookOidcTokens(): void { @@ -104,8 +106,8 @@ public function testExpectedNonceIsIsolatedBetweenCoroutines(): void [$nonceA, $nonceB] = parallel([ function () use ($provider, $key): string { - $httpClient = m::mock(Client::class); - $httpClient->expects('get')->andReturnUsing(function () use ($key): Response { + $httpClient = Double::for(Client::class)->strict(); + $httpClient->expects('get')->resolves(function () use ($key): Response { // Suspend this verification after its nonce is set. usleep(5000); @@ -186,7 +188,7 @@ public function testAnUnknownKidRaisesTheLibraryAuthenticationFailure(): void private function getProvider(): FacebookProvider { return new FacebookProvider( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect', @@ -198,13 +200,13 @@ private function getProvider(): FacebookProvider */ private function expectJwksResponses(FacebookProvider $provider, array $keys): void { - $httpClient = m::mock(Client::class); + $httpClient = Double::for(Client::class)->strict(); $provider->setHttpClient($httpClient); $httpClient->expects('get') ->with('https://limited.facebook.com/.well-known/oauth/openid/jwks/') ->times(count($keys)) - ->andReturn(...array_map( + ->returns(...array_map( fn (array $key): Response => new Response( headers: ['Cache-Control' => 'max-age=3600'], body: json_encode($this->jwks($key)), diff --git a/tests/Socialite/FacebookProviderTest.php b/tests/Socialite/FacebookProviderTest.php index 7f3193d6bc..4bdba5bdf8 100644 --- a/tests/Socialite/FacebookProviderTest.php +++ b/tests/Socialite/FacebookProviderTest.php @@ -11,11 +11,14 @@ use Hypervel\Socialite\Two\FacebookProvider; use Hypervel\Socialite\Two\User; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionMethod; class FacebookProviderTest extends TestCase { + use VerifiesDoubles; + public function testMapUserToObjectWithAccessTokenResponse(): void { $provider = $this->getProvider(); @@ -61,7 +64,7 @@ public function testMapUserToObjectWithOidcTokenResponse(): void public function testAccessTokenProfileRequestPreservesDocumentedQueryParameters(): void { $provider = $this->getProvider(); - $httpClient = m::mock(Client::class); + $httpClient = Double::for(Client::class)->strict(); $provider->setHttpClient($httpClient); $httpClient->expects('get')->with('https://graph.facebook.com/v23.0/me', [ @@ -73,7 +76,7 @@ public function testAccessTokenProfileRequestPreservesDocumentedQueryParameters( 'fields' => 'name,email,gender,verified,link,picture.width(1920)', 'appsecret_proof' => hash_hmac('sha256', 'access-token', 'client_secret'), ], - ])->andReturn(new Response(body: json_encode([ + ])->returns(new Response(body: json_encode([ 'id' => '123456', 'name' => 'Test User', ]))); @@ -81,10 +84,13 @@ public function testAccessTokenProfileRequestPreservesDocumentedQueryParameters( $this->assertSame('123456', $provider->userFromToken('access-token')->getId()); } + /** + * Create the Facebook provider. + */ private function getProvider(): FacebookProvider { return new FacebookProvider( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect', diff --git a/tests/Socialite/Fixtures/FacebookTestProviderStub.php b/tests/Socialite/Fixtures/FacebookTestProviderStub.php index 39ada9a2fb..72fb743054 100644 --- a/tests/Socialite/Fixtures/FacebookTestProviderStub.php +++ b/tests/Socialite/Fixtures/FacebookTestProviderStub.php @@ -6,15 +6,12 @@ use GuzzleHttp\Client; use Hypervel\Socialite\Two\FacebookProvider; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; class FacebookTestProviderStub extends FacebookProvider { - /** - * @var Client|MockInterface - */ - public $http; + public (Client&DoubleInterface)|null $http = null; protected function getUserByToken(string $token): array { @@ -22,7 +19,7 @@ protected function getUserByToken(string $token): array } /** - * Get a fresh instance of the Guzzle HTTP client. + * Return the test HTTP client. */ protected function getHttpClient(): Client { @@ -30,6 +27,6 @@ protected function getHttpClient(): Client return $this->http; } - return $this->http = m::mock(Client::class); + return $this->http = Double::for(Client::class)->strict(); } } diff --git a/tests/Socialite/Fixtures/GoogleTestProviderStub.php b/tests/Socialite/Fixtures/GoogleTestProviderStub.php index f538e42a2b..1d294d6494 100644 --- a/tests/Socialite/Fixtures/GoogleTestProviderStub.php +++ b/tests/Socialite/Fixtures/GoogleTestProviderStub.php @@ -7,15 +7,12 @@ use GuzzleHttp\Client; use Hypervel\Socialite\Two\GoogleProvider; use Hypervel\Socialite\Two\User; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; class GoogleTestProviderStub extends GoogleProvider { - /** - * @var Client|MockInterface - */ - public $http; + public (Client&DoubleInterface)|null $http = null; protected function getAuthUrl(?string $state): string { @@ -38,7 +35,7 @@ protected function mapUserToObject(array $user): User } /** - * Get a fresh instance of the Guzzle HTTP client. + * Return the test HTTP client. */ protected function getHttpClient(): Client { @@ -46,6 +43,6 @@ protected function getHttpClient(): Client return $this->http; } - return $this->http = m::mock(Client::class); + return $this->http = Double::for(Client::class)->strict(); } } diff --git a/tests/Socialite/Fixtures/OAuthTwoTestProviderStub.php b/tests/Socialite/Fixtures/OAuthTwoTestProviderStub.php index fb8e39b5cd..b203c7bde5 100644 --- a/tests/Socialite/Fixtures/OAuthTwoTestProviderStub.php +++ b/tests/Socialite/Fixtures/OAuthTwoTestProviderStub.php @@ -8,12 +8,13 @@ use Hypervel\Http\Request; use Hypervel\Socialite\Two\AbstractProvider; use Hypervel\Socialite\Two\User; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; use SensitiveParameter; class OAuthTwoTestProviderStub extends AbstractProvider { - public ?Client $http = null; + public (Client&DoubleInterface)|null $http = null; protected function getAuthUrl(?string $state): string { @@ -66,7 +67,7 @@ public function getProviderRequest(): Request } /** - * Get a fresh instance of the Guzzle HTTP client. + * Return the test HTTP client. */ protected function getHttpClient(): Client { @@ -74,6 +75,6 @@ protected function getHttpClient(): Client return $this->http; } - return $this->http = m::mock(Client::class); + return $this->http = Double::for(Client::class)->strict(); } } diff --git a/tests/Socialite/Fixtures/OpenIdTestProviderStub.php b/tests/Socialite/Fixtures/OpenIdTestProviderStub.php index f8279580c6..bcee7aafe3 100644 --- a/tests/Socialite/Fixtures/OpenIdTestProviderStub.php +++ b/tests/Socialite/Fixtures/OpenIdTestProviderStub.php @@ -7,12 +7,13 @@ use GuzzleHttp\Client; use Hypervel\Socialite\Two\OpenIdProvider; use Hypervel\Socialite\Two\User; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; use SensitiveParameter; class OpenIdTestProviderStub extends OpenIdProvider { - public ?Client $http = null; + public (Client&DoubleInterface)|null $http = null; protected function getBaseUrl(): string { @@ -72,7 +73,7 @@ public function getProviderUserByToken(#[SensitiveParameter] string $token): arr } /** - * Get a fresh instance of the Guzzle HTTP client. + * Return the test HTTP client. */ protected function getHttpClient(): Client { @@ -80,6 +81,6 @@ protected function getHttpClient(): Client return $this->http; } - return $this->http = m::mock(Client::class); + return $this->http = Double::for(Client::class)->strict(); } } diff --git a/tests/Socialite/Fixtures/VerifyingOpenIdTestProviderStub.php b/tests/Socialite/Fixtures/VerifyingOpenIdTestProviderStub.php index fe2cc1f8a6..0dedd0d620 100644 --- a/tests/Socialite/Fixtures/VerifyingOpenIdTestProviderStub.php +++ b/tests/Socialite/Fixtures/VerifyingOpenIdTestProviderStub.php @@ -7,14 +7,15 @@ use GuzzleHttp\Client; use Hypervel\Socialite\Two\OpenIdProvider; use Hypervel\Socialite\Two\User; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; use SensitiveParameter; class VerifyingOpenIdTestProviderStub extends OpenIdProvider { protected bool $usesNonce = false; - public ?Client $http = null; + public (Client&DoubleInterface)|null $http = null; public function verifyToken(#[SensitiveParameter] string $token): array { @@ -57,7 +58,7 @@ protected function mapUserToObject(array $user): User } /** - * Get a fresh instance of the Guzzle HTTP client. + * Return the test HTTP client. */ protected function getHttpClient(): Client { @@ -65,6 +66,6 @@ protected function getHttpClient(): Client return $this->http; } - return $this->http = m::mock(Client::class); + return $this->http = Double::for(Client::class)->strict(); } } diff --git a/tests/Socialite/GitlabProviderTest.php b/tests/Socialite/GitlabProviderTest.php index 6840138deb..17beb7f87f 100644 --- a/tests/Socialite/GitlabProviderTest.php +++ b/tests/Socialite/GitlabProviderTest.php @@ -10,24 +10,27 @@ use Hypervel\Http\Request; use Hypervel\Socialite\Two\GitlabProvider; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class GitlabProviderTest extends TestCase { + use VerifiesDoubles; + public function testUserRequestUsesTheVersionedApiAndBearerAuthorization(): void { $provider = new GitlabProvider( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect', ); - $httpClient = m::mock(Client::class); + $httpClient = Double::for(Client::class)->strict(); $provider->setHttpClient($httpClient); $httpClient->expects('get')->with('https://gitlab.com/api/v4/user', [ RequestOptions::HEADERS => ['Authorization' => 'Bearer access-token'], - ])->andReturn(new Response(body: json_encode([ + ])->returns(new Response(body: json_encode([ 'id' => 1, 'username' => 'taylor', 'name' => 'Taylor Otwell', diff --git a/tests/Socialite/GoogleProviderIdTokenTest.php b/tests/Socialite/GoogleProviderIdTokenTest.php index ddc365b347..b6cd4d6bdd 100644 --- a/tests/Socialite/GoogleProviderIdTokenTest.php +++ b/tests/Socialite/GoogleProviderIdTokenTest.php @@ -17,16 +17,16 @@ use Hypervel\Socialite\Two\User; use Hypervel\Tests\Socialite\Fixtures\CreatesJwksFixtures; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; -use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\StreamInterface; use ReflectionMethod; use UnexpectedValueException; class GoogleProviderIdTokenTest extends TestCase { use CreatesJwksFixtures; + use VerifiesDoubles; public function testItCanDetectJwtTokens(): void { @@ -65,6 +65,9 @@ public function testItAcceptsTheDocumentedIssuers(string $issuer): void $this->assertSame('123456789012345678901', $user->getId()); } + /** + * Provide the documented Google token issuers. + */ public static function validIssuerProvider(): array { return [ @@ -112,12 +115,9 @@ public function testItFallsBackToApiCallForAccessTokens(): void $provider = $this->getProvider(); $accessToken = 'ya29.a0AfH6SMCxyz123456789'; - $httpClient = m::mock(Client::class); + $httpClient = Double::for(Client::class)->strict(); $provider->setHttpClient($httpClient); - $response = m::mock(ResponseInterface::class); - $stream = m::mock(StreamInterface::class); - $mockUserData = [ 'sub' => '123456789', 'email' => 'test@example.com', @@ -126,7 +126,7 @@ public function testItFallsBackToApiCallForAccessTokens(): void ]; $httpClient - ->shouldReceive('get') + ->expects('get') ->with('https://www.googleapis.com/oauth2/v3/userinfo', [ RequestOptions::QUERY => [ 'prettyPrint' => 'false', @@ -136,15 +136,7 @@ public function testItFallsBackToApiCallForAccessTokens(): void 'Authorization' => 'Bearer ' . $accessToken, ], ]) - ->once() - ->andReturn($response); - - $response->shouldReceive('getBody')->once()->andReturn($stream); - - $stream - ->shouldReceive('__toString') - ->once() - ->andReturn(json_encode($mockUserData)); + ->returns(new Response(body: json_encode($mockUserData))); $user = $provider->userFromToken($accessToken); @@ -218,22 +210,25 @@ public function testUserMappingWorksWithIdTokenFormat(): void protected function getProvider(): GoogleProvider { return new GoogleProvider( - m::mock(Request::class), + new Request, 'test-client-id', 'test-client-secret', 'http://localhost/callback' ); } + /** + * Expect key-set responses in order. + */ private function expectJwksResponses(GoogleProvider $provider, array $keys): void { - $httpClient = m::mock(Client::class); + $httpClient = Double::for(Client::class)->strict(); $provider->setHttpClient($httpClient); $httpClient->expects('get') ->with('https://www.googleapis.com/oauth2/v3/certs') ->times(count($keys)) - ->andReturn(...array_map( + ->returns(...array_map( fn (array $key): Response => new Response( headers: ['Cache-Control' => 'max-age=3600'], body: json_encode($this->jwks($key)), diff --git a/tests/Socialite/GoogleProviderTest.php b/tests/Socialite/GoogleProviderTest.php index 4d792d0cb0..721b380449 100644 --- a/tests/Socialite/GoogleProviderTest.php +++ b/tests/Socialite/GoogleProviderTest.php @@ -5,29 +5,33 @@ namespace Hypervel\Tests\Socialite; use GuzzleHttp\Client; +use GuzzleHttp\Psr7\Response; use GuzzleHttp\RequestOptions; use Hypervel\Http\Request; +use Hypervel\Socialite\Two\GoogleProvider; use Hypervel\Socialite\Two\User; -use Hypervel\Tests\Socialite\Fixtures\GoogleTestProviderStub; use Hypervel\Tests\TestCase; -use Mockery as m; -use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\StreamInterface; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class GoogleProviderTest extends TestCase { + use VerifiesDoubles; + public function testMapUserFromAccessToken(): void { - $provider = new GoogleTestProviderStub( - m::mock(Request::class), + // Upstream's stub bypasses both the HTTP request and Google profile mapping. + $provider = new GoogleProvider( + new Request, 'client_id', 'client_secret', 'redirect_uri' ); - $provider->http = m::mock(Client::class); + $http = Double::for(Client::class)->strict(); + $provider->setHttpClient($http); - $provider->http->allows('get')->with('https://www.googleapis.com/oauth2/v3/userinfo', [ + $http->expects('get')->with('https://www.googleapis.com/oauth2/v3/userinfo', [ RequestOptions::QUERY => [ 'prettyPrint' => 'false', ], @@ -35,12 +39,12 @@ public function testMapUserFromAccessToken(): void 'Accept' => 'application/json', 'Authorization' => 'Bearer fake-token', ], - ])->andReturns($response = m::mock(ResponseInterface::class)); - - $response->allows('getBody')->andReturns(m::mock(StreamInterface::class)); + ])->returns(new Response(body: json_encode(['sub' => 'user-id', 'email' => 'taylor@example.com']))); $user = $provider->userFromToken('fake-token'); $this->assertInstanceOf(User::class, $user); + $this->assertSame('user-id', $user->getId()); + $this->assertSame('taylor@example.com', $user->getEmail()); } } diff --git a/tests/Socialite/LinkedInOpenIdProviderTest.php b/tests/Socialite/LinkedInOpenIdProviderTest.php index ed4a91825d..f7991e205a 100644 --- a/tests/Socialite/LinkedInOpenIdProviderTest.php +++ b/tests/Socialite/LinkedInOpenIdProviderTest.php @@ -5,18 +5,20 @@ namespace Hypervel\Tests\Socialite; use GuzzleHttp\Client; +use GuzzleHttp\Psr7\Response; use GuzzleHttp\RequestOptions; use Hypervel\Http\Request; use Hypervel\Socialite\Contracts\User as UserContract; use Hypervel\Socialite\Two\LinkedInOpenIdProvider; use Hypervel\Socialite\Two\User; use Hypervel\Tests\TestCase; -use Mockery as m; -use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\StreamInterface; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class LinkedInOpenIdProviderTest extends TestCase { + use VerifiesDoubles; + public function testResponse(): void { $user = $this->fromResponse([ @@ -78,26 +80,15 @@ public function testMissingEmailAndAvatar(): void ], $user->attributes); } + /** + * Resolve a user from the given profile response. + */ protected function fromResponse(array $response): UserContract { - $request = m::mock(Request::class); - $request->allows('input')->with('code')->andReturns('fake-code'); - - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturns(json_encode(['access_token' => 'fake-token'])); - - $accessTokenResponse = m::mock(ResponseInterface::class); - $accessTokenResponse->allows('getBody')->andReturns($stream); - - $basicProfileStream = m::mock(StreamInterface::class); - $basicProfileStream->allows('__toString')->andReturns(json_encode($response)); - - $basicProfileResponse = m::mock(ResponseInterface::class); - $basicProfileResponse->allows('getBody')->andReturns($basicProfileStream); - - $guzzle = m::mock(Client::class); - $guzzle->expects('post')->andReturns($accessTokenResponse); - $guzzle->allows('get')->with('https://api.linkedin.com/v2/userinfo', [ + $request = Request::create('/callback', parameters: ['code' => 'fake-code']); + $guzzle = Double::for(Client::class)->strict(); + $guzzle->expects('post')->returns(new Response(body: json_encode(['access_token' => 'fake-token']))); + $guzzle->expects('get')->with('https://api.linkedin.com/v2/userinfo', [ RequestOptions::HEADERS => [ 'Authorization' => 'Bearer fake-token', 'X-RestLi-Protocol-Version' => '2.0.0', @@ -105,7 +96,7 @@ protected function fromResponse(array $response): UserContract RequestOptions::QUERY => [ 'projection' => '(sub,email,email_verified,name,given_name,family_name,picture)', ], - ])->andReturns($basicProfileResponse); + ])->returns(new Response(body: json_encode($response))); $provider = new LinkedInOpenIdProvider( $request, diff --git a/tests/Socialite/LinkedInProviderTest.php b/tests/Socialite/LinkedInProviderTest.php index 0abb8bddfb..442872faf5 100644 --- a/tests/Socialite/LinkedInProviderTest.php +++ b/tests/Socialite/LinkedInProviderTest.php @@ -6,45 +6,33 @@ use ErrorException; use GuzzleHttp\Client; +use GuzzleHttp\Psr7\Response; use GuzzleHttp\RequestOptions; use Hypervel\Http\Request; use Hypervel\Socialite\Two\LinkedInProvider; use Hypervel\Socialite\Two\User; use Hypervel\Tests\TestCase; -use Mockery as m; -use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\StreamInterface; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionMethod; class LinkedInProviderTest extends TestCase { + use VerifiesDoubles; + public function testItCanMapAUserWithoutAnEmailAddress(): void { - $request = m::mock(Request::class); - $request->allows('input')->with('code')->andReturns('fake-code'); - - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturns(json_encode(['access_token' => 'fake-token'])); - - $accessTokenResponse = m::mock(ResponseInterface::class); - $accessTokenResponse->allows('getBody')->andReturns($stream); - - $basicProfileStream = m::mock(StreamInterface::class); - $basicProfileStream->allows('__toString')->andReturns(json_encode(['id' => $userId = 1])); + $request = Request::create('/callback', parameters: ['code' => 'fake-code']); - $basicProfileResponse = m::mock(ResponseInterface::class); - $basicProfileResponse->allows('getBody')->andReturns($basicProfileStream); + $accessTokenResponse = new Response(body: json_encode(['access_token' => 'fake-token'])); - $emailAddressStream = m::mock(StreamInterface::class); - $emailAddressStream->allows('__toString')->andReturns(json_encode(['elements' => []])); + $basicProfileResponse = new Response(body: json_encode(['id' => $userId = 1])); - // Make sure email address response contains no values. - $emailAddressResponse = m::mock(ResponseInterface::class); - $emailAddressResponse->allows('getBody')->andReturns($emailAddressStream); + $emailAddressResponse = new Response(body: json_encode(['elements' => []])); - $guzzle = m::mock(Client::class); - $guzzle->expects('post')->andReturns($accessTokenResponse); - $guzzle->allows('get')->with('https://api.linkedin.com/v2/me', [ + $guzzle = Double::for(Client::class)->strict(); + $guzzle->expects('post')->returns($accessTokenResponse); + $guzzle->expects('get')->with('https://api.linkedin.com/v2/me', [ RequestOptions::HEADERS => [ 'Authorization' => 'Bearer fake-token', 'X-RestLi-Protocol-Version' => '2.0.0', @@ -52,8 +40,8 @@ public function testItCanMapAUserWithoutAnEmailAddress(): void RequestOptions::QUERY => [ 'projection' => '(id,firstName,lastName,profilePicture(displayImage~:playableStreams),vanityName)', ], - ])->andReturns($basicProfileResponse); - $guzzle->allows('get')->with('https://api.linkedin.com/v2/emailAddress', [ + ])->returns($basicProfileResponse); + $guzzle->expects('get')->with('https://api.linkedin.com/v2/emailAddress', [ RequestOptions::HEADERS => [ 'Authorization' => 'Bearer fake-token', 'X-RestLi-Protocol-Version' => '2.0.0', @@ -62,7 +50,7 @@ public function testItCanMapAUserWithoutAnEmailAddress(): void 'q' => 'members', 'projection' => '(elements*(handle~))', ], - ])->andReturns($emailAddressResponse); + ])->returns($emailAddressResponse); $provider = new LinkedInProvider( $request, @@ -82,17 +70,11 @@ public function testItCanMapAUserWithoutAnEmailAddress(): void public function testItCanMapAUserWhenTheStillImageKeyIsMissing(): void { - $request = m::mock(Request::class); - $request->allows('input')->with('code')->andReturns('fake-code'); + $request = Request::create('/callback', parameters: ['code' => 'fake-code']); - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturns(json_encode(['access_token' => 'fake-token'])); + $accessTokenResponse = new Response(body: json_encode(['access_token' => 'fake-token'])); - $accessTokenResponse = m::mock(ResponseInterface::class); - $accessTokenResponse->allows('getBody')->andReturns($stream); - - $basicProfileStream = m::mock(StreamInterface::class); - $basicProfileStream->allows('__toString')->andReturns(json_encode([ + $basicProfileResponse = new Response(body: json_encode([ 'id' => $userId = 1, 'profilePicture' => [ 'displayImage~' => [ @@ -108,18 +90,11 @@ public function testItCanMapAUserWhenTheStillImageKeyIsMissing(): void ], ])); - $basicProfileResponse = m::mock(ResponseInterface::class); - $basicProfileResponse->allows('getBody')->andReturns($basicProfileStream); - - $emailAddressStream = m::mock(StreamInterface::class); - $emailAddressStream->allows('__toString')->andReturns(json_encode(['elements' => []])); - - $emailAddressResponse = m::mock(ResponseInterface::class); - $emailAddressResponse->allows('getBody')->andReturns($emailAddressStream); + $emailAddressResponse = new Response(body: json_encode(['elements' => []])); - $guzzle = m::mock(Client::class); - $guzzle->expects('post')->andReturns($accessTokenResponse); - $guzzle->allows('get')->with('https://api.linkedin.com/v2/me', [ + $guzzle = Double::for(Client::class)->strict(); + $guzzle->expects('post')->returns($accessTokenResponse); + $guzzle->expects('get')->with('https://api.linkedin.com/v2/me', [ RequestOptions::HEADERS => [ 'Authorization' => 'Bearer fake-token', 'X-RestLi-Protocol-Version' => '2.0.0', @@ -127,8 +102,8 @@ public function testItCanMapAUserWhenTheStillImageKeyIsMissing(): void RequestOptions::QUERY => [ 'projection' => '(id,firstName,lastName,profilePicture(displayImage~:playableStreams),vanityName)', ], - ])->andReturns($basicProfileResponse); - $guzzle->allows('get')->with('https://api.linkedin.com/v2/emailAddress', [ + ])->returns($basicProfileResponse); + $guzzle->expects('get')->with('https://api.linkedin.com/v2/emailAddress', [ RequestOptions::HEADERS => [ 'Authorization' => 'Bearer fake-token', 'X-RestLi-Protocol-Version' => '2.0.0', @@ -137,7 +112,7 @@ public function testItCanMapAUserWhenTheStillImageKeyIsMissing(): void 'q' => 'members', 'projection' => '(elements*(handle~))', ], - ])->andReturns($emailAddressResponse); + ])->returns($emailAddressResponse); $provider = new LinkedInProvider($request, 'client_id', 'client_secret', 'redirect'); $provider->stateless(); @@ -163,7 +138,7 @@ public function testItCanMapAUserWhenTheStillImageKeyIsMissing(): void public function testMapUserSkipsImagesWithoutStillImageMetadata(): void { $provider = new LinkedInProvider( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect', diff --git a/tests/Socialite/OAuthTwoTest.php b/tests/Socialite/OAuthTwoTest.php index a7c27a4eea..e6edcd80d0 100644 --- a/tests/Socialite/OAuthTwoTest.php +++ b/tests/Socialite/OAuthTwoTest.php @@ -5,6 +5,7 @@ namespace Hypervel\Tests\Socialite; use GuzzleHttp\Client; +use GuzzleHttp\Psr7\Response; use Hypervel\Contracts\Session\Session as SessionContract; use Hypervel\Coroutine\Coroutine; use Hypervel\Http\RedirectResponse; @@ -20,22 +21,23 @@ use Hypervel\Tests\Socialite\Fixtures\OAuthTwoWithConfigTestProviderStub; use Hypervel\Tests\Socialite\Fixtures\OAuthTwoWithPKCETestProviderStub; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; -use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\StreamInterface; use SensitiveParameter; use Swoole\Coroutine\Channel; use TypeError; class OAuthTwoTest extends TestCase { + use VerifiesDoubles; + public function testRedirectGeneratesTheProperRedirectResponseWithoutPKCE(): void { - $request = m::mock(Request::class); - $request->shouldReceive('session') - ->once() - ->andReturn($session = m::mock(SessionContract::class)); + $request = Double::for(Request::class, override: true)->strict(); + $request->expects('session') + ->returns($session = Double::for(SessionContract::class)->strict()); $state = null; $closure = function ($name, $stateInput) use (&$state) { @@ -48,9 +50,9 @@ public function testRedirectGeneratesTheProperRedirectResponseWithoutPKCE(): voi return false; }; - $session->expects('put')->withArgs($closure); + $session->expects('put')->with(Argument::all($closure)); $provider = new OAuthTwoTestProviderStub( - $request, + $request->instance(), 'client_id', 'client_secret', 'redirect' @@ -69,7 +71,7 @@ public function testDirectProviderRedirectClosureIsResolvedOncePerExecution(): v { $resolutions = 0; $provider = new OAuthTwoTestProviderStub( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', function () use (&$resolutions): string { @@ -94,7 +96,7 @@ public function testRedirectFormatterUsesCurrentConfigAndSetConfigInvalidatesThe $resolutions = 0; $redirectResolutions = 0; $provider = new OAuthTwoTestProviderStub( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', '/callback', @@ -146,7 +148,7 @@ public function testLiteralRedirectOverrideDoesNotEvaluateTheConfiguredClosure() { $resolutions = 0; $provider = new OAuthTwoTestProviderStub( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', function () use (&$resolutions): string { @@ -168,9 +170,9 @@ function () use (&$resolutions): string { public function testRedirectGeneratesTheProperRedirectResponseWithPKCE(): void { - $request = m::mock(Request::class); - $request->shouldReceive('session') - ->andReturn($session = m::mock(SessionContract::class)); + $request = Double::for(Request::class, override: true)->strict(); + $request->allows('session') + ->returns($session = Double::for(SessionContract::class)->strict()); $state = null; $codeVerifier = ''; @@ -189,13 +191,13 @@ public function testRedirectGeneratesTheProperRedirectResponseWithPKCE(): void return false; }; - $session->expects('put')->twice()->withArgs($sessionPutClosure); - $session->expects('get')->once()->with('code_verifier')->andReturnUsing(function () use (&$codeVerifier) { + $session->expects('put')->times(2)->with(Argument::all($sessionPutClosure)); + $session->expects('get')->with('code_verifier')->resolves(function () use (&$codeVerifier) { return $codeVerifier; }); $provider = new OAuthTwoWithPKCETestProviderStub( - $request, + $request->instance(), 'client_id', 'client_secret', 'redirect' @@ -213,37 +215,32 @@ public function testRedirectGeneratesTheProperRedirectResponseWithPKCE(): void public function testTokenRequestIncludesPKCECodeVerifier(): void { - $request = m::mock(Request::class); - $request->shouldReceive('has') - ->andReturn(true); - $request->shouldReceive('input') + $request = Double::for(Request::class, override: true)->strict(); + $request->allows('has') + ->returns(true); + $request->expects('input') ->with('state') - ->once() - ->andReturn(str_repeat('A', 40)); - $request->shouldReceive('input') + ->returns(str_repeat('A', 40)); + $request->expects('input') ->with('code') - ->once() - ->andReturn('code'); - $request->shouldReceive('session') - ->andReturn($session = m::mock(SessionContract::class)); + ->returns('code'); + $request->allows('session') + ->returns($session = Double::for(SessionContract::class)->strict()); $codeVerifier = Str::random(32); - $session->expects('pull')->with('state')->andReturns(str_repeat('A', 40)); - $session->expects('pull')->with('code_verifier')->andReturns($codeVerifier); + $session->expects('pull')->with('state')->returns(str_repeat('A', 40)); + $session->expects('pull')->with('code_verifier')->returns($codeVerifier); $provider = new OAuthTwoWithPKCETestProviderStub( - $request, + $request->instance(), 'client_id', 'client_secret', 'redirect_uri' ); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('post')->with('http://token.url', [ 'headers' => ['Accept' => 'application/json'], 'form_params' => ['grant_type' => 'authorization_code', 'client_id' => 'client_id', 'client_secret' => 'client_secret', 'code' => 'code', 'redirect_uri' => 'redirect_uri', 'code_verifier' => $codeVerifier], - ])->andReturns($response = m::mock(ResponseInterface::class)); - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturns('{ "access_token" : "access_token", "refresh_token" : "refresh_token", "expires_in" : 3600 }'); - $response->expects('getBody')->andReturns($stream); + ])->returns(new Response(body: '{ "access_token" : "access_token", "refresh_token" : "refresh_token", "expires_in" : 3600 }')); $user = $provider->user(); $this->assertInstanceOf(User::class, $user); @@ -256,35 +253,30 @@ public function testTokenRequestIncludesPKCECodeVerifier(): void public function testUserReturnsAUserInstanceForTheAuthenticatedRequest(): void { - $request = m::mock(Request::class); - $request->shouldReceive('session') - ->andReturn($session = m::mock(SessionContract::class)); - $request->shouldReceive('has') - ->andReturn(true); - $request->shouldReceive('input') + $request = Double::for(Request::class, override: true)->strict(); + $request->allows('session') + ->returns($session = Double::for(SessionContract::class)->strict()); + $request->allows('has') + ->returns(true); + $request->expects('input') ->with('state') - ->once() - ->andReturn(str_repeat('A', 40)); - $request->shouldReceive('input') + ->returns(str_repeat('A', 40)); + $request->expects('input') ->with('code') - ->once() - ->andReturn('code'); + ->returns('code'); - $session->expects('pull')->with('state')->andReturns(str_repeat('A', 40)); + $session->expects('pull')->with('state')->returns(str_repeat('A', 40)); $provider = new OAuthTwoTestProviderStub( - $request, + $request->instance(), 'client_id', 'client_secret', 'redirect_uri' ); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('post')->with('http://token.url', [ 'headers' => ['Accept' => 'application/json'], 'form_params' => ['grant_type' => 'authorization_code', 'client_id' => 'client_id', 'client_secret' => 'client_secret', 'code' => 'code', 'redirect_uri' => 'redirect_uri'], - ])->andReturns($response = m::mock(ResponseInterface::class)); - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturns('{ "access_token" : "access_token", "refresh_token" : "refresh_token", "expires_in" : 3600 }'); - $response->expects('getBody')->andReturns($stream); + ])->returns(new Response(body: '{ "access_token" : "access_token", "refresh_token" : "refresh_token", "expires_in" : 3600 }')); $user = $provider->user(); $this->assertInstanceOf(User::class, $user); @@ -302,33 +294,28 @@ public function testUserReturnsAUserInstanceForTheAuthenticatedRequest(): void public function testUserReturnsAUserInstanceForTheAuthenticatedFacebookRequest(): void { - $request = m::mock(Request::class); - $request->shouldReceive('session') - ->andReturn($session = m::mock(SessionContract::class)); - $request->shouldReceive('has') - ->andReturn(true); - $request->shouldReceive('input') + $request = Double::for(Request::class, override: true)->strict(); + $request->allows('session') + ->returns($session = Double::for(SessionContract::class)->strict()); + $request->allows('has') + ->returns(true); + $request->expects('input') ->with('state') - ->once() - ->andReturn(str_repeat('A', 40)); - $request->shouldReceive('input') + ->returns(str_repeat('A', 40)); + $request->expects('input') ->with('code') - ->once() - ->andReturn('code'); - $session->expects('pull')->with('state')->andReturns(str_repeat('A', 40)); + ->returns('code'); + $session->expects('pull')->with('state')->returns(str_repeat('A', 40)); $provider = new FacebookTestProviderStub( - $request, + $request->instance(), 'client_id', 'client_secret', 'redirect_uri' ); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('post')->with('https://graph.facebook.com/v23.0/oauth/access_token', [ 'form_params' => ['grant_type' => 'authorization_code', 'client_id' => 'client_id', 'client_secret' => 'client_secret', 'code' => 'code', 'redirect_uri' => 'redirect_uri'], - ])->andReturns($response = m::mock(ResponseInterface::class)); - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturns(json_encode(['access_token' => 'access_token', 'expires' => 5183085])); - $response->expects('getBody')->andReturns($stream); + ])->returns(new Response(body: json_encode(['access_token' => 'access_token', 'expires' => 5183085]))); $user = $provider->user(); $this->assertInstanceOf(User::class, $user); @@ -343,19 +330,18 @@ public function testExceptionIsThrownIfStateIsInvalid(): void { $this->expectException(InvalidStateException::class); - $request = m::mock(Request::class); - $request->shouldReceive('session') - ->andReturn($session = m::mock(SessionContract::class)); - $request->shouldReceive('has') - ->andReturn(true); - $request->shouldReceive('input') + $request = Double::for(Request::class, override: true)->strict(); + $request->allows('session') + ->returns($session = Double::for(SessionContract::class)->strict()); + $request->allows('has') + ->returns(true); + $request->expects('input') ->with('state') - ->once() - ->andReturn(str_repeat('B', 40)); + ->returns(str_repeat('B', 40)); - $session->expects('pull')->with('state')->andReturns(str_repeat('A', 40)); + $session->expects('pull')->with('state')->returns(str_repeat('A', 40)); $provider = new OAuthTwoTestProviderStub( - $request, + $request->instance(), 'client_id', 'client_secret', 'redirect' @@ -367,17 +353,16 @@ public function testExceptionIsThrownIfStateIsNotAString(): void { $this->expectException(InvalidStateException::class); - $request = m::mock(Request::class); - $request->shouldReceive('session') - ->andReturn($session = m::mock(SessionContract::class)); - $request->shouldReceive('input') + $request = Double::for(Request::class, override: true)->strict(); + $request->allows('session') + ->returns($session = Double::for(SessionContract::class)->strict()); + $request->expects('input') ->with('state') - ->once() - ->andReturn([str_repeat('A', 40)]); + ->returns([str_repeat('A', 40)]); - $session->expects('pull')->with('state')->andReturns(str_repeat('A', 40)); + $session->expects('pull')->with('state')->returns(str_repeat('A', 40)); $provider = new OAuthTwoTestProviderStub( - $request, + $request->instance(), 'client_id', 'client_secret', 'redirect' @@ -389,12 +374,12 @@ public function testExceptionIsThrownIfStateIsNotSet(): void { $this->expectException(InvalidStateException::class); - $request = m::mock(Request::class); - $request->shouldReceive('session') - ->andReturn($session = m::mock(SessionContract::class)); + $request = Double::for(Request::class, override: true)->strict(); + $request->allows('session') + ->returns($session = Double::for(SessionContract::class)->strict()); $session->expects('pull')->with('state'); $provider = new OAuthTwoTestProviderStub( - $request, + $request->instance(), 'client_id', 'client_secret', 'redirect' @@ -405,27 +390,25 @@ public function testExceptionIsThrownIfStateIsNotSet(): void #[DataProvider('invalidAuthorizationCodeProvider')] public function testExceptionIsThrownIfAuthorizationCodeIsInvalid(mixed $code): void { - $request = m::mock(Request::class); - $request->shouldReceive('session') - ->andReturn($session = m::mock(SessionContract::class)); - $request->shouldReceive('input') + $request = Double::for(Request::class, override: true)->strict(); + $request->allows('session') + ->returns($session = Double::for(SessionContract::class)->strict()); + $request->expects('input') ->with('state') - ->once() - ->andReturn(str_repeat('A', 40)); - $request->shouldReceive('input') + ->returns(str_repeat('A', 40)); + $request->expects('input') ->with('code') - ->once() - ->andReturn($code); + ->returns($code); - $session->expects('pull')->with('state')->andReturns(str_repeat('A', 40)); + $session->expects('pull')->with('state')->returns(str_repeat('A', 40)); $provider = new OAuthTwoTestProviderStub( - $request, + $request->instance(), 'client_id', 'client_secret', 'redirect' ); - $provider->http = m::mock(Client::class); - $provider->http->shouldNotReceive('post'); + $provider->http = Double::for(Client::class)->strict(); + $provider->http->expects('post')->never(); $this->expectException(InvalidCodeException::class); $this->expectExceptionMessageIs('The authorization code is missing or invalid.'); @@ -433,6 +416,9 @@ public function testExceptionIsThrownIfAuthorizationCodeIsInvalid(mixed $code): $provider->user(); } + /** + * Provide invalid authorization codes. + */ public static function invalidAuthorizationCodeProvider(): array { return [ @@ -444,21 +430,18 @@ public static function invalidAuthorizationCodeProvider(): array public function testUserRefreshesToken(): void { - $request = m::mock(Request::class); + $request = new Request; $provider = new OAuthTwoTestProviderStub( $request, 'client_id', 'client_secret', 'redirect_uri' ); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('post')->with('http://token.url', [ 'headers' => ['Accept' => 'application/json'], - 'form_params' => ['grant_type' => 'refresh_token', 'client_id' => 'client_id', 'client_secret' => 'client_secret', 'refresh_token' => 'refresh_token'], - ])->andReturns($response = m::mock(ResponseInterface::class)); - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturns('{ "access_token" : "access_token", "refresh_token" : "refresh_token", "expires_in" : 3600, "scope" : "scope1,scope2" }'); - $response->expects('getBody')->andReturns($stream); + 'form_params' => ['grant_type' => 'refresh_token', 'refresh_token' => 'refresh_token', 'client_id' => 'client_id', 'client_secret' => 'client_secret'], + ])->returns(new Response(body: '{ "access_token" : "access_token", "refresh_token" : "refresh_token", "expires_in" : 3600, "scope" : "scope1,scope2" }')); $token = $provider->refreshToken('refresh_token'); $this->assertInstanceOf(Token::class, $token); @@ -470,21 +453,18 @@ public function testUserRefreshesToken(): void public function testUserRefreshesGoogleToken(): void { - $request = m::mock(Request::class); + $request = new Request; $provider = new GoogleTestProviderStub( $request, 'client_id', 'client_secret', 'redirect_uri' ); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('post')->with('http://token.url', [ 'headers' => ['Accept' => 'application/json'], - 'form_params' => ['grant_type' => 'refresh_token', 'client_id' => 'client_id', 'client_secret' => 'client_secret', 'refresh_token' => 'refresh_token'], - ])->andReturns($response = m::mock(ResponseInterface::class)); - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturns('{ "access_token" : "access_token", "expires_in" : 3600, "scope" : "scope1 scope2" }'); - $response->expects('getBody')->andReturns($stream); + 'form_params' => ['grant_type' => 'refresh_token', 'refresh_token' => 'refresh_token', 'client_id' => 'client_id', 'client_secret' => 'client_secret'], + ])->returns(new Response(body: '{ "access_token" : "access_token", "expires_in" : 3600, "scope" : "scope1 scope2" }')); $token = $provider->refreshToken('refresh_token'); $this->assertInstanceOf(Token::class, $token); @@ -497,7 +477,7 @@ public function testUserRefreshesGoogleToken(): void public function testTokenResponseParsersNormalizeProviderValues(): void { $provider = new OAuthTwoTestProviderStub( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect' @@ -516,7 +496,7 @@ public function testTokenResponseParsersNormalizeProviderValues(): void public function testExpiresInParserAcceptsNonNegativeIntegers(array $response, ?int $expected): void { $provider = new OAuthTwoTestProviderStub( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect' @@ -525,6 +505,9 @@ public function testExpiresInParserAcceptsNonNegativeIntegers(array $response, ? $this->assertSame($expected, $provider->parseProviderExpiresIn($response)); } + /** + * Provide token lifetime values. + */ public static function expiresInProvider(): array { return [ @@ -546,7 +529,7 @@ public static function expiresInProvider(): array public function testMissingAccessTokenFailsAtTheParserBoundary(): void { $provider = new OAuthTwoTestProviderStub( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect' @@ -559,24 +542,21 @@ public function testMissingAccessTokenFailsAtTheParserBoundary(): void public function testWholeTokenResponseCanMapAndPopulateTheUser(): void { - $request = m::mock(Request::class); - $request->expects('input')->with('code')->andReturn('code'); + $request = Double::for(Request::class, override: true)->strict(); + $request->expects('input')->with('code')->returns('code'); $provider = new OAuthTwoWholeResponseTestProviderStub( - $request, + $request->instance(), 'client_id', 'client_secret', 'redirect' ); $provider->stateless(); - $provider->http = m::mock(Client::class); - $provider->http->expects('post')->andReturn($response = m::mock(ResponseInterface::class)); - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturn(json_encode([ + $provider->http = Double::for(Client::class)->strict(); + $provider->http->expects('post')->returns(new Response(body: json_encode([ 'access_token' => 'access-token', 'profile_id' => 'response-user', - ])); - $response->expects('getBody')->andReturn($stream); + ]))); $user = $provider->user(); @@ -593,27 +573,23 @@ public function testWholeTokenResponseCanMapAndPopulateTheUser(): void public function testFailedUserDecorationDoesNotCachePartialUser(): void { - $request = m::mock(Request::class); - $request->expects('input')->with('code')->andReturn('code'); + $request = Double::for(Request::class, override: true)->strict(); + $request->expects('input')->with('code')->returns('code'); $provider = new OAuthTwoWholeResponseTestProviderStub( - $request, + $request->instance(), 'client_id', 'client_secret', 'redirect' ); $provider->stateless(); - $provider->http = m::mock(Client::class); - $provider->http->expects('post')->andReturn($response = m::mock(ResponseInterface::class)); - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturn('{"profile_id":"response-user"}'); - $response->expects('getBody')->andReturn($stream); + $provider->http = Double::for(Client::class)->strict(); + $provider->http->expects('post')->returns(new Response(body: '{"profile_id":"response-user"}')); try { $provider->user(); $this->fail('Expected token parsing to fail.'); } catch (TypeError) { - $this->addToAssertionCount(1); } $this->assertNull($provider->getProviderUser()); @@ -621,7 +597,7 @@ public function testFailedUserDecorationDoesNotCachePartialUser(): void public function testSetConfigOverridesCredentialsInRedirect(): void { - $request = m::mock(Request::class); + $request = new Request; $provider = new OAuthTwoTestProviderStub( $request, @@ -647,24 +623,22 @@ public function testSetConfigOverridesCredentialsInRedirect(): void public function testSetConfigOverridesCredentialsInTokenRequest(): void { - $request = m::mock(Request::class); - $request->shouldReceive('session') - ->andReturn($session = m::mock(SessionContract::class)); - $request->shouldReceive('has') - ->andReturn(true); - $request->shouldReceive('input') + $request = Double::for(Request::class, override: true)->strict(); + $request->allows('session') + ->returns($session = Double::for(SessionContract::class)->strict()); + $request->allows('has') + ->returns(true); + $request->expects('input') ->with('state') - ->once() - ->andReturn(str_repeat('A', 40)); - $request->shouldReceive('input') + ->returns(str_repeat('A', 40)); + $request->expects('input') ->with('code') - ->once() - ->andReturn('code'); + ->returns('code'); - $session->expects('pull')->with('state')->andReturns(str_repeat('A', 40)); + $session->expects('pull')->with('state')->returns(str_repeat('A', 40)); $provider = new OAuthTwoTestProviderStub( - $request, + $request->instance(), 'original_id', 'original_secret', 'original_redirect' @@ -674,7 +648,7 @@ public function testSetConfigOverridesCredentialsInTokenRequest(): void 'client_secret' => 'tenant_secret', 'redirect' => 'tenant_redirect', ]); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('post')->with('http://token.url', [ 'headers' => ['Accept' => 'application/json'], 'form_params' => [ @@ -684,10 +658,7 @@ public function testSetConfigOverridesCredentialsInTokenRequest(): void 'code' => 'code', 'redirect_uri' => 'tenant_redirect', ], - ])->andReturns($response = m::mock(ResponseInterface::class)); - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturns('{ "access_token" : "access_token", "refresh_token" : "refresh_token", "expires_in" : 3600 }'); - $response->expects('getBody')->andReturns($stream); + ])->returns(new Response(body: '{ "access_token" : "access_token", "refresh_token" : "refresh_token", "expires_in" : 3600 }')); $user = $provider->user(); @@ -697,7 +668,7 @@ public function testSetConfigOverridesCredentialsInTokenRequest(): void public function testSetConfigOverridesCredentialsInRefreshToken(): void { - $request = m::mock(Request::class); + $request = new Request; $provider = new OAuthTwoTestProviderStub( $request, @@ -709,7 +680,7 @@ public function testSetConfigOverridesCredentialsInRefreshToken(): void 'client_id' => 'tenant_id', 'client_secret' => 'tenant_secret', ]); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('post')->with('http://token.url', [ 'headers' => ['Accept' => 'application/json'], 'form_params' => [ @@ -718,10 +689,7 @@ public function testSetConfigOverridesCredentialsInRefreshToken(): void 'client_id' => 'tenant_id', 'client_secret' => 'tenant_secret', ], - ])->andReturns($response = m::mock(ResponseInterface::class)); - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturns('{ "access_token" : "access_token", "refresh_token" : "new_refresh_token", "expires_in" : 3600, "scope" : "scope1,scope2" }'); - $response->expects('getBody')->andReturns($stream); + ])->returns(new Response(body: '{ "access_token" : "access_token", "refresh_token" : "new_refresh_token", "expires_in" : 3600, "scope" : "scope1,scope2" }')); $token = $provider->refreshToken('refresh_token'); @@ -731,7 +699,7 @@ public function testSetConfigOverridesCredentialsInRefreshToken(): void public function testSetConfigPartialOverridePreservesDefaults(): void { - $request = m::mock(Request::class); + $request = new Request; $provider = new OAuthTwoTestProviderStub( $request, @@ -752,7 +720,7 @@ public function testSetConfigPartialOverridePreservesDefaults(): void public function testGetConfigReturnsAdditionalKeys(): void { - $request = m::mock(Request::class); + $request = new Request; $provider = new OAuthTwoWithConfigTestProviderStub( $request, @@ -774,7 +742,7 @@ public function testGetConfigReturnsAdditionalKeys(): void public function testWithConfigBaselineSurvivesAcrossCoroutines(): void { - $request = m::mock(Request::class); + $request = new Request; $provider = new OAuthTwoWithConfigTestProviderStub( $request, @@ -815,7 +783,7 @@ public function testWithConfigBaselineSurvivesAcrossCoroutines(): void public function testSetConfigIsIsolatedPerCoroutine(): void { - $request = m::mock(Request::class); + $request = new Request; $provider = new OAuthTwoTestProviderStub( $request, @@ -860,6 +828,9 @@ public function testSetConfigIsIsolatedPerCoroutine(): void class OAuthTwoWholeResponseTestProviderStub extends OAuthTwoTestProviderStub { + /** + * Map the profile identifier from the full token response. + */ protected function getUserByTokenResponse(#[SensitiveParameter] array $response): array { return ['id' => $response['profile_id']]; diff --git a/tests/Socialite/OpenIdProviderTest.php b/tests/Socialite/OpenIdProviderTest.php index 60031c8032..d7142ff4be 100644 --- a/tests/Socialite/OpenIdProviderTest.php +++ b/tests/Socialite/OpenIdProviderTest.php @@ -19,10 +19,11 @@ use Hypervel\Tests\Socialite\Fixtures\OpenIdTestProviderStub; use Hypervel\Tests\Socialite\Fixtures\VerifyingOpenIdTestProviderStub; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; -use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\StreamInterface; use ReflectionMethod; use RuntimeException; use TypeError; @@ -31,12 +32,13 @@ class OpenIdProviderTest extends TestCase { use CreatesJwksFixtures; + use VerifiesDoubles; public function testRedirectGeneratesTheProperRedirectResponseWithoutPKCE(): void { - $request = m::mock(Request::class); - $request->shouldReceive('session') - ->andReturn($session = m::mock(SessionContract::class)); + $request = Double::for(Request::class, override: true)->strict(); + $request->allows('session') + ->returns($session = Double::for(SessionContract::class)->strict()); $state = null; $nonce = null; @@ -55,9 +57,9 @@ public function testRedirectGeneratesTheProperRedirectResponseWithoutPKCE(): voi return false; }; - $session->expects('put')->twice()->withArgs($closure); + $session->expects('put')->times(2)->with(Argument::all($closure)); $provider = new OpenIdTestProviderStub( - $request, + $request->instance(), 'client_id', 'client_secret', 'redirect' @@ -74,31 +76,29 @@ public function testRedirectGeneratesTheProperRedirectResponseWithoutPKCE(): voi public function testUserReturnsAUserInstanceForTheAuthenticatedRequest(): void { - $request = m::mock(Request::class); - $request->shouldReceive('session') - ->andReturn($session = m::mock(SessionContract::class)); - $request->shouldReceive('has') - ->andReturn(true); - $request->shouldReceive('input') + $request = Double::for(Request::class, override: true)->strict(); + $request->allows('session') + ->returns($session = Double::for(SessionContract::class)->strict()); + $request->allows('has') + ->returns(true); + $request->expects('input') ->with('state') - ->once() - ->andReturn(str_repeat('A', 40)); - $request->shouldReceive('input') + ->returns(str_repeat('A', 40)); + $request->expects('input') ->with('code') - ->once() - ->andReturn('code'); + ->returns('code'); - $session->expects('pull')->with('state')->andReturns(str_repeat('A', 40)); - $session->expects('pull')->with('nonce')->andReturns('nonce'); + $session->expects('pull')->with('state')->returns(str_repeat('A', 40)); + $session->expects('pull')->with('nonce')->returns('nonce'); $provider = new OpenIdTestProviderStub( - $request, + $request->instance(), 'client_id', 'client_secret', 'redirect_uri' ); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('get')->with('http://base.url/.well-known/openid-configuration') - ->andReturns(new Response( + ->returns(new Response( body: json_encode([ 'issuer' => 'http://base.url', 'token_endpoint' => 'http://token.url', @@ -108,10 +108,7 @@ public function testUserReturnsAUserInstanceForTheAuthenticatedRequest(): void $provider->http->expects('post')->with('http://token.url', [ 'headers' => ['Accept' => 'application/json'], 'form_params' => ['grant_type' => 'authorization_code', 'client_id' => 'client_id', 'client_secret' => 'client_secret', 'code' => 'code', 'redirect_uri' => 'redirect_uri'], - ])->andReturns($response = m::mock(ResponseInterface::class)); - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturns('{ "access_token" : "access_token", "id_token" : "id_token", "refresh_token" : "refresh_token", "expires_in" : 3600 }'); - $response->expects('getBody')->andReturns($stream); + ])->returns(new Response(body: '{ "access_token" : "access_token", "id_token" : "id_token", "refresh_token" : "refresh_token", "expires_in" : 3600 }')); $user = $provider->user(); $this->assertInstanceOf(User::class, $user); @@ -130,20 +127,20 @@ public function testUserReturnsAUserInstanceForTheAuthenticatedRequest(): void public function testSetConfigOverridesAudienceValidationPass(): void { - $request = m::mock(Request::class); - $request->shouldReceive('session') - ->andReturn($session = m::mock(SessionContract::class)); - $session->expects('pull')->with('nonce')->andReturns('test-nonce'); + $request = Double::for(Request::class, override: true)->strict(); + $request->allows('session') + ->returns($session = Double::for(SessionContract::class)->strict()); + $session->expects('pull')->with('nonce')->returns('test-nonce'); $provider = new OpenIdTestProviderStub( - $request, + $request->instance(), 'original_id', 'client_secret', 'redirect' ); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->allows('get')->with('http://base.url/.well-known/openid-configuration') - ->andReturns(new Response( + ->returns(new Response( body: json_encode(['issuer' => 'http://base.url']) )); @@ -157,19 +154,17 @@ public function testSetConfigOverridesAudienceValidationPass(): void 'aud' => 'tenant_id', 'iss' => 'http://base.url', ]); - - $this->assertTrue(true); } public function testSetConfigOverridesAudienceValidationFail(): void { - $request = m::mock(Request::class); - $request->shouldReceive('session') - ->andReturn($session = m::mock(SessionContract::class)); - $session->expects('pull')->with('nonce')->andReturns('test-nonce'); + $request = Double::for(Request::class, override: true)->strict(); + $request->allows('session') + ->returns($session = Double::for(SessionContract::class)->strict()); + $session->expects('pull')->with('nonce')->returns('test-nonce'); $provider = new OpenIdTestProviderStub( - $request, + $request->instance(), 'original_id', 'client_secret', 'redirect' @@ -191,16 +186,16 @@ public function testSetConfigOverridesAudienceValidationFail(): void public function testTrustedAudiencesAcceptScalarConfigurationAndIgnoreAzp(): void { - $request = m::mock(Request::class); - $request->expects('session')->andReturn($session = m::mock(SessionContract::class)); - $session->expects('pull')->with('nonce')->andReturn('nonce'); + $request = Double::for(Request::class, override: true)->strict(); + $request->expects('session')->returns($session = Double::for(SessionContract::class)->strict()); + $session->expects('pull')->with('nonce')->returns('nonce'); - $provider = new OpenIdTestProviderStub($request, 'client_id', 'client_secret', 'redirect'); + $provider = new OpenIdTestProviderStub($request->instance(), 'client_id', 'client_secret', 'redirect'); $provider->withConfig(['trusted_audiences' => 'trusted-api']); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('get') ->with('http://base.url/.well-known/openid-configuration') - ->andReturn(new Response(body: json_encode(['issuer' => 'http://base.url']))); + ->returns(new Response(body: json_encode(['issuer' => 'http://base.url']))); $provider->validateProviderPayload([ 'nonce' => 'nonce', @@ -208,17 +203,15 @@ public function testTrustedAudiencesAcceptScalarConfigurationAndIgnoreAzp(): voi 'azp' => 'another-party', 'iss' => 'http://base.url', ]); - - $this->addToAssertionCount(1); } public function testAudienceRejectsUntrustedAndNonStringEntries(): void { - $request = m::mock(Request::class); - $request->expects('session')->andReturn($session = m::mock(SessionContract::class)); - $session->expects('pull')->with('nonce')->andReturn('nonce'); + $request = Double::for(Request::class, override: true)->strict(); + $request->expects('session')->returns($session = Double::for(SessionContract::class)->strict()); + $session->expects('pull')->with('nonce')->returns('nonce'); - $provider = new OpenIdTestProviderStub($request, 'client_id', 'client_secret', 'redirect'); + $provider = new OpenIdTestProviderStub($request->instance(), 'client_id', 'client_secret', 'redirect'); $this->expectException(InvalidAudienceException::class); @@ -231,15 +224,15 @@ public function testAudienceRejectsUntrustedAndNonStringEntries(): void public function testNonceIsConsumedAfterOneValidation(): void { - $request = m::mock(Request::class); - $request->expects('session')->twice()->andReturn($session = m::mock(SessionContract::class)); - $session->expects('pull')->with('nonce')->twice()->andReturn('nonce', null); + $request = Double::for(Request::class, override: true)->strict(); + $request->expects('session')->times(2)->returns($session = Double::for(SessionContract::class)->strict()); + $session->expects('pull')->with('nonce')->times(2)->returns('nonce', null); - $provider = new OpenIdTestProviderStub($request, 'client_id', 'client_secret', 'redirect'); - $provider->http = m::mock(Client::class); + $provider = new OpenIdTestProviderStub($request->instance(), 'client_id', 'client_secret', 'redirect'); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('get') ->with('http://base.url/.well-known/openid-configuration') - ->andReturn(new Response(body: json_encode(['issuer' => 'http://base.url']))); + ->returns(new Response(body: json_encode(['issuer' => 'http://base.url']))); $payload = [ 'nonce' => 'nonce', @@ -257,15 +250,15 @@ public function testNonceIsConsumedAfterOneValidation(): void public function testUserInfoUsesBearerAuthorizationWithoutTokenQuery(): void { $provider = new OpenIdTestProviderStub( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect' ); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('get') ->with('http://base.url/.well-known/openid-configuration') - ->andReturn(new Response(body: json_encode([ + ->returns(new Response(body: json_encode([ 'userinfo_endpoint' => 'http://userinfo.url', ]))); $provider->http->expects('get')->with('http://userinfo.url', [ @@ -273,7 +266,7 @@ public function testUserInfoUsesBearerAuthorizationWithoutTokenQuery(): void 'Accept' => 'application/json', 'Authorization' => 'Bearer access-token', ], - ])->andReturn(new Response(body: '{"sub":"foo"}')); + ])->returns(new Response(body: '{"sub":"foo"}')); $this->assertSame(['sub' => 'foo'], $provider->getProviderUserByToken('access-token')); } @@ -281,7 +274,7 @@ public function testUserInfoUsesBearerAuthorizationWithoutTokenQuery(): void public function testMissingIdTokenFailsAtTheRequiredResponseBoundary(): void { $provider = new OpenIdTestProviderStub( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect' @@ -311,20 +304,18 @@ public function testMissingIdTokenFailsAtTheRequiredResponseBoundary(): void public function testDiscoveryCacheIsKeyedByTheExactConfigurationUrl(): void { $provider = new OpenIdTestProviderStub( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect' ); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('get') ->with('https://tenant-a.example/.well-known/openid-configuration') - ->once() - ->andReturn(new Response(body: '{"issuer":"tenant-a"}')); + ->returns(new Response(body: '{"issuer":"tenant-a"}')); $provider->http->expects('get') ->with('https://tenant-b.example/.well-known/openid-configuration') - ->once() - ->andReturn(new Response(body: '{"issuer":"tenant-b"}')); + ->returns(new Response(body: '{"issuer":"tenant-b"}')); $provider->setConfig(['base_url' => 'https://tenant-a.example']); $this->assertSame('tenant-a', $provider->getProviderOpenIdConfig()['issuer']); @@ -337,16 +328,16 @@ public function testDiscoveryCacheIsKeyedByTheExactConfigurationUrl(): void public function testDiscoveryRefreshReachesTheNetwork(): void { $provider = new OpenIdTestProviderStub( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect' ); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('get') ->with('http://base.url/.well-known/openid-configuration') - ->twice() - ->andReturn( + ->times(2) + ->returns( new Response(body: '{"issuer":"first"}'), new Response(body: '{"issuer":"refreshed"}'), ); @@ -359,20 +350,18 @@ public function testDiscoveryRefreshReachesTheNetwork(): void public function testFailedDiscoveryDoesNotReplaceThePreviousExactUrlEntry(): void { $provider = new OpenIdTestProviderStub( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect' ); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); $provider->http->expects('get') ->with('https://tenant-a.example/.well-known/openid-configuration') - ->once() - ->andReturn(new Response(body: '{"issuer":"tenant-a"}')); + ->returns(new Response(body: '{"issuer":"tenant-a"}')); $provider->http->expects('get') ->with('https://tenant-b.example/.well-known/openid-configuration') - ->once() - ->andThrow($failure = new RuntimeException('Discovery unavailable.')); + ->throws($failure = new RuntimeException('Discovery unavailable.')); $provider->setConfig(['base_url' => 'https://tenant-a.example']); $this->assertSame('tenant-a', $provider->getProviderOpenIdConfig()['issuer']); @@ -393,13 +382,13 @@ public function testFailedDiscoveryDoesNotReplaceThePreviousExactUrlEntry(): voi public function testDiscoveryRejectsJsonWithoutNamedFields(): void { $provider = new OpenIdTestProviderStub( - m::mock(Request::class), + new Request, 'client_id', 'client_secret', 'redirect' ); - $provider->http = m::mock(Client::class); - $provider->http->expects('get')->andReturn(new Response(body: '{}')); + $provider->http = Double::for(Client::class)->strict(); + $provider->http->expects('get')->returns(new Response(body: '{}')); try { $provider->getProviderOpenIdConfig(); @@ -504,6 +493,9 @@ public function testOidcJwksLetsJwtLibraryRejectMismatchedAndUnsupportedAlgorith $provider->verifyToken($this->createSignedToken($key)); } + /** + * Provide invalid ID token algorithms. + */ public static function invalidIdTokenAlgorithmProvider(): array { return [ @@ -640,10 +632,11 @@ public function testOidcJwksNoCacheDirectivesWinAcrossRepeatedHeaders(string $di $provider->verifyToken($token); $provider->verifyToken($token); - - $this->addToAssertionCount(1); } + /** + * Provide directives that prevent key caching. + */ public static function immediateStalenessDirectiveProvider(): array { return [ @@ -669,8 +662,6 @@ public function testOidcJwksUsesTheSmallestRepeatedMaxAge(): void $provider->verifyToken($token); $provider->verifyToken($token); - - $this->addToAssertionCount(1); } public function testOidcJwksFallsBackToDefaultTtlForMalformedAndOverflowingMaxAgeValues(): void @@ -689,8 +680,6 @@ public function testOidcJwksFallsBackToDefaultTtlForMalformedAndOverflowingMaxAg $provider->verifyToken($token); $provider->verifyToken($token); - - $this->addToAssertionCount(1); } public function testOidcJwksUsesDefaultTtlWhenCacheDirectivesAreMissing(): void @@ -719,26 +708,22 @@ public function testOidcJwksSwitchesWithTheExactDiscoveryUrl(): void $provider->http->expects('get') ->with('https://tenant-a.example/.well-known/openid-configuration') - ->once() - ->andReturn(new Response(body: json_encode([ + ->returns(new Response(body: json_encode([ 'issuer' => 'tenant-a', 'jwks_uri' => 'https://tenant-a.example/jwks', ]))); $provider->http->expects('get') ->with('https://tenant-b.example/.well-known/openid-configuration') - ->once() - ->andReturn(new Response(body: json_encode([ + ->returns(new Response(body: json_encode([ 'issuer' => 'tenant-b', 'jwks_uri' => 'https://tenant-b.example/jwks', ]))); $provider->http->expects('get') ->with('https://tenant-a.example/jwks') - ->once() - ->andReturn(new Response(body: json_encode($this->jwks($tenantAKey)))); + ->returns(new Response(body: json_encode($this->jwks($tenantAKey)))); $provider->http->expects('get') ->with('https://tenant-b.example/jwks') - ->once() - ->andReturn(new Response(body: json_encode($this->jwks($tenantBKey)))); + ->returns(new Response(body: json_encode($this->jwks($tenantBKey)))); $provider->setConfig(['base_url' => 'https://tenant-a.example']); $this->assertSame('foo', $provider->verifyToken($this->createSignedToken($tenantAKey, issuer: 'tenant-a'))['sub']); @@ -756,8 +741,8 @@ public function testOidcColdJwksFailureRetriesOnTheNextLogin(): void $attempt = 0; $provider->http->expects('get') ->with('http://jwks.url') - ->twice() - ->andReturnUsing(function () use (&$attempt, $key): Response { + ->times(2) + ->resolves(function () use (&$attempt, $key): Response { if ($attempt++ === 0) { throw new RuntimeException('JWKS unavailable.'); } @@ -786,8 +771,8 @@ public function testOidcFailedForcedRefreshIsThrottledWhenCachedKeysRemain(): vo $attempt = 0; $provider->http->expects('get') ->with('http://jwks.url') - ->twice() - ->andReturnUsing(function () use (&$attempt, $oldKey): Response { + ->times(2) + ->resolves(function () use (&$attempt, $oldKey): Response { if ($attempt++ === 0) { return new Response(body: json_encode($this->jwks($oldKey))); } @@ -818,8 +803,8 @@ public function testOidcChangedJwksUrlFailureRetriesWithoutPublishingPartialStat $provider->http->expects('get') ->with('http://base.url/.well-known/openid-configuration') - ->twice() - ->andReturn( + ->times(2) + ->returns( new Response(body: json_encode([ 'issuer' => 'http://base.url', 'jwks_uri' => 'http://old-jwks.url', @@ -831,13 +816,12 @@ public function testOidcChangedJwksUrlFailureRetriesWithoutPublishingPartialStat ); $provider->http->expects('get') ->with('http://old-jwks.url') - ->once() - ->andReturn(new Response(body: json_encode($this->jwks($oldKey)))); + ->returns(new Response(body: json_encode($this->jwks($oldKey)))); $newJwksAttempt = 0; $provider->http->expects('get') ->with('http://new-jwks.url') - ->twice() - ->andReturnUsing(function () use (&$newJwksAttempt, $newKey): Response { + ->times(2) + ->resolves(function () use (&$newJwksAttempt, $newKey): Response { if ($newJwksAttempt++ === 0) { throw new RuntimeException('New JWKS unavailable.'); } @@ -857,9 +841,12 @@ public function testOidcChangedJwksUrlFailureRetriesWithoutPublishingPartialStat $this->assertSame('foo', $provider->verifyToken($token)['sub']); } + /** + * Create a provider with real token verification. + */ private function createVerifyingProvider(): VerifyingOpenIdTestProviderStub { - $request = m::mock(Request::class); + $request = new Request; $provider = new VerifyingOpenIdTestProviderStub( $request, @@ -867,17 +854,20 @@ private function createVerifyingProvider(): VerifyingOpenIdTestProviderStub 'client_secret', 'redirect' ); - $provider->http = m::mock(Client::class); + $provider->http = Double::for(Client::class)->strict(); return $provider; } - private function expectOpenIdConfigRequests(Client $http, int $times): void + /** + * Expect the requested number of discovery fetches. + */ + private function expectOpenIdConfigRequests(Client&DoubleInterface $http, int $times): void { - $http->shouldReceive('get') + $http->expects('get') ->with('http://base.url/.well-known/openid-configuration') ->times($times) - ->andReturn(new Response( + ->returns(new Response( body: json_encode([ 'issuer' => 'http://base.url', 'token_endpoint' => 'http://token.url', @@ -886,12 +876,15 @@ private function expectOpenIdConfigRequests(Client $http, int $times): void )); } - private function expectJwksRequests(Client $http, array $jwksResponses): void + /** + * Expect key-set responses in order. + */ + private function expectJwksRequests(Client&DoubleInterface $http, array $jwksResponses): void { - $http->shouldReceive('get') + $http->expects('get') ->with('http://jwks.url') ->times(count($jwksResponses)) - ->andReturn(...array_map( + ->returns(...array_map( fn (array|Response $response): Response => $response instanceof Response ? $response : new Response(body: json_encode($response)), @@ -899,6 +892,9 @@ private function expectJwksRequests(Client $http, array $jwksResponses): void )); } + /** + * Create a signed ID token. + */ private function createSignedToken( array $key, bool $includeKid = true, @@ -914,6 +910,9 @@ private function createSignedToken( ], $key['private'], $algorithm, $includeKid ? $key['kid'] : null); } + /** + * Create a key set without an explicit algorithm. + */ private function jwksWithoutAlgorithm(array $key): array { $jwks = $this->jwks($key); diff --git a/tests/Socialite/SlackOpenIdProviderTest.php b/tests/Socialite/SlackOpenIdProviderTest.php index 03b5f4a38a..38cf4b070c 100644 --- a/tests/Socialite/SlackOpenIdProviderTest.php +++ b/tests/Socialite/SlackOpenIdProviderTest.php @@ -5,18 +5,20 @@ namespace Hypervel\Tests\Socialite; use GuzzleHttp\Client; +use GuzzleHttp\Psr7\Response; use GuzzleHttp\RequestOptions; use Hypervel\Http\Request; use Hypervel\Socialite\Contracts\User as UserContract; use Hypervel\Socialite\Two\SlackOpenIdProvider; use Hypervel\Socialite\Two\User; use Hypervel\Tests\TestCase; -use Mockery as m; -use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\StreamInterface; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class SlackOpenIdProviderTest extends TestCase { + use VerifiesDoubles; + public function testResponse(): void { $user = $this->fromResponse([ @@ -73,30 +75,19 @@ public function testMissingEmailAndAvatar(): void ], $user->attributes); } + /** + * Resolve a user from the given profile response. + */ protected function fromResponse(array $response): UserContract { - $request = m::mock(Request::class); - $request->allows('input')->with('code')->andReturns('fake-code'); - - $stream = m::mock(StreamInterface::class); - $stream->allows('__toString')->andReturns(json_encode(['access_token' => 'fake-token'])); - - $accessTokenResponse = m::mock(ResponseInterface::class); - $accessTokenResponse->allows('getBody')->andReturns($stream); - - $basicProfileStream = m::mock(StreamInterface::class); - $basicProfileStream->allows('__toString')->andReturns(json_encode($response)); - - $basicProfileResponse = m::mock(ResponseInterface::class); - $basicProfileResponse->allows('getBody')->andReturns($basicProfileStream); - - $guzzle = m::mock(Client::class); - $guzzle->expects('post')->andReturns($accessTokenResponse); - $guzzle->allows('get')->with('https://slack.com/api/openid.connect.userInfo', [ + $request = Request::create('/callback', parameters: ['code' => 'fake-code']); + $guzzle = Double::for(Client::class)->strict(); + $guzzle->expects('post')->returns(new Response(body: json_encode(['access_token' => 'fake-token']))); + $guzzle->expects('get')->with('https://slack.com/api/openid.connect.userInfo', [ RequestOptions::HEADERS => [ 'Authorization' => 'Bearer fake-token', ], - ])->andReturns($basicProfileResponse); + ])->returns(new Response(body: json_encode($response))); $provider = new SlackOpenIdProvider( $request, diff --git a/tests/Socialite/SlackProviderTest.php b/tests/Socialite/SlackProviderTest.php index 08ac603af9..d42acca3a4 100644 --- a/tests/Socialite/SlackProviderTest.php +++ b/tests/Socialite/SlackProviderTest.php @@ -7,13 +7,12 @@ use Hypervel\Http\Request; use Hypervel\Socialite\Two\SlackProvider; use Hypervel\Tests\TestCase; -use Mockery as m; class SlackProviderTest extends TestCase { public function testDefaultScopeKeyIsUserScope(): void { - $request = m::mock(Request::class); + $request = new Request; $provider = new SlackProvider( $request, @@ -34,7 +33,7 @@ public function testDefaultScopeKeyIsUserScope(): void public function testAsBotUserChangesScopeKey(): void { - $request = m::mock(Request::class); + $request = new Request; $provider = new SlackProvider( $request, diff --git a/tests/Support/Facades/GrpcTest.php b/tests/Support/Facades/GrpcTest.php index a975a32215..8ffbd268a9 100644 --- a/tests/Support/Facades/GrpcTest.php +++ b/tests/Support/Facades/GrpcTest.php @@ -11,20 +11,22 @@ use Hypervel\Support\Facades\Facade; use Hypervel\Support\Facades\Grpc; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class GrpcTest extends TestCase { + use VerifiesDoubles; + public function testResolvesAndForwardsToThePackageRegistrar(): void { $container = new Container; - $registrar = m::mock(GrpcRouteRegistrar::class); - $route = m::mock(Route::class); + $registrar = Double::for(GrpcRouteRegistrar::class)->strict(); + $route = Double::for(Route::class)->strict(); $action = static fn (GPBEmpty $request): GPBEmpty => $request; - $registrar->shouldReceive('unary') - ->once() + $registrar->expects('unary') ->with('testing.Service/Call', $action) - ->andReturn($route); + ->returns($route); $container->instance(GrpcRouteRegistrar::class, $registrar); Facade::setFacadeApplication($container); @@ -35,8 +37,8 @@ public function testResolvesAndForwardsToThePackageRegistrar(): void public function testUsesTheOrdinaryFacadeResolutionCache(): void { $container = new Container; - $first = m::mock(GrpcRouteRegistrar::class); - $second = m::mock(GrpcRouteRegistrar::class); + $first = Double::for(GrpcRouteRegistrar::class)->strict(); + $second = Double::for(GrpcRouteRegistrar::class)->strict(); $container->instance(GrpcRouteRegistrar::class, $first); Facade::setFacadeApplication($container); diff --git a/tests/Support/FailureReporterTest.php b/tests/Support/FailureReporterTest.php index e47518b22c..c4f18627ba 100644 --- a/tests/Support/FailureReporterTest.php +++ b/tests/Support/FailureReporterTest.php @@ -10,13 +10,16 @@ use Hypervel\Support\FailureReporter; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Swoole\Coroutine\CanceledException; class FailureReporterTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; protected string $tempDir; @@ -27,6 +30,9 @@ class FailureReporterTest extends TestCase protected string|false|null $previousLogErrors = null; + /** + * Create the temporary error log directory. + */ protected function setUp(): void { parent::setUp(); @@ -37,6 +43,9 @@ protected function setUp(): void $this->errorLog = $this->tempDir . '/php-error.log'; } + /** + * Restore error logging and remove temporary files. + */ protected function tearDown(): void { if ($this->previousErrorLog !== null && $this->previousErrorLog !== false) { @@ -57,8 +66,8 @@ public function testReportsThroughTheBoundExceptionHandler(): void $container = new Container; Container::setInstance($container); $exception = new RuntimeException('reported through handler'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($exception); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($exception); $container->instance(ExceptionHandler::class, $handler); FailureReporter::report($exception); @@ -81,8 +90,8 @@ public function testHandlerFailureFallsBackWithoutPropagating(): void $container = new Container; Container::setInstance($container); $exception = new RuntimeException('original cleanup failure'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($exception)->andThrow(new RuntimeException('handler failed')); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($exception)->throws(new RuntimeException('handler failed')); $container->instance(ExceptionHandler::class, $handler); $this->routeErrorsToTempFile(); @@ -97,8 +106,8 @@ public function testCancellationIsNotReportedOrLogged(): void { $container = new Container; Container::setInstance($container); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->never(); $container->instance(ExceptionHandler::class, $handler); $this->routeErrorsToTempFile(); @@ -112,8 +121,8 @@ public function testCancellationFromTheExceptionHandlerIsNotLogged(): void $container = new Container; Container::setInstance($container); $exception = new RuntimeException('original cleanup failure'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($exception)->andThrow( + $handler = Double::for(ExceptionHandler::class)->strict(); + $handler->expects('report')->with($exception)->throws( new CanceledException('reporting canceled') ); $container->instance(ExceptionHandler::class, $handler); @@ -128,7 +137,7 @@ public function testPreferCancellationReportsTheFailureDisplacedByCancellation() { $failure = new RuntimeException('displaced failure'); $cancellation = new CanceledException('canceled'); - $this->bindReportingHandler()->shouldReceive('report')->once()->with($failure); + $this->bindReportingHandler()->expects('report')->with($failure); $this->assertSame($cancellation, FailureReporter::preferCancellation($failure, $cancellation)); } @@ -137,7 +146,7 @@ public function testPreferCancellationKeepsTheFirstFailureAndReportsTheLaterOne( { $first = new RuntimeException('first failure'); $later = new RuntimeException('later failure'); - $this->bindReportingHandler()->shouldReceive('report')->once()->with($later); + $this->bindReportingHandler()->expects('report')->with($later); $this->assertSame($first, FailureReporter::preferCancellation($first, $later)); } @@ -145,22 +154,28 @@ public function testPreferCancellationKeepsTheFirstFailureAndReportsTheLaterOne( public function testPreferCancellationReportsNothingWithoutADistinctLoser(): void { $failure = new RuntimeException('failure'); - $this->bindReportingHandler()->shouldNotReceive('report'); + $this->bindReportingHandler()->expects('report')->never(); $this->assertSame($failure, FailureReporter::preferCancellation(null, $failure)); $this->assertSame($failure, FailureReporter::preferCancellation($failure, $failure)); } - private function bindReportingHandler(): MockInterface + /** + * Bind an isolated exception handler. + */ + private function bindReportingHandler(): ExceptionHandler&DoubleInterface { $container = new Container; Container::setInstance($container); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class)->strict(); $container->instance(ExceptionHandler::class, $handler); return $handler; } + /** + * Read the temporary error log. + */ private function errorLogContents(): string { $contents = file_get_contents($this->errorLog); @@ -169,6 +184,9 @@ private function errorLogContents(): string return $contents; } + /** + * Route PHP errors to the temporary log. + */ private function routeErrorsToTempFile(): void { $this->previousErrorLog = ini_set('error_log', $this->errorLog); diff --git a/tests/Support/PendingBatchFakeTest.php b/tests/Support/PendingBatchFakeTest.php index 44a8f83e2a..155ee68bc9 100644 --- a/tests/Support/PendingBatchFakeTest.php +++ b/tests/Support/PendingBatchFakeTest.php @@ -9,10 +9,13 @@ use Hypervel\Support\Testing\Fakes\BusFake; use Hypervel\Support\Testing\Fakes\PendingBatchFake; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class PendingBatchFakeTest extends TestCase { + use VerifiesDoubles; + public function testHasJobsMatchesObjectsClassesAndTypedClosuresInOrder(): void { $batch = $this->batch([ @@ -47,9 +50,12 @@ public function testJobsAreFilteredAndReindexed(): void $this->assertSame([$first, $second], $batch->jobs->all()); } + /** + * Create a fake pending batch for the given jobs. + */ private function batch(array $jobs): PendingBatchFake { - $bus = new BusFake(m::mock(QueueingDispatcher::class)); + $bus = new BusFake(Double::for(QueueingDispatcher::class)->strict()); return new PendingBatchFake($bus, new Collection($jobs)); } diff --git a/tests/Support/SafeCallerTest.php b/tests/Support/SafeCallerTest.php index f054070443..a5591a8994 100644 --- a/tests/Support/SafeCallerTest.php +++ b/tests/Support/SafeCallerTest.php @@ -4,13 +4,15 @@ namespace Hypervel\Tests\Support; -use Hypervel\Contracts\Container\Container; +use Hypervel\Container\Container; +use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\Contracts\Debug\ExceptionHandler as ExceptionHandlerContract; use Hypervel\Filesystem\Filesystem; use Hypervel\Support\SafeCaller; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -18,10 +20,12 @@ class SafeCallerTest extends TestCase { + use VerifiesDoubles; + public function testCallReturnsClosureResult(): void { - $container = m::mock(Container::class); - $caller = new SafeCaller($container); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $caller = new SafeCaller($container->instance()); $result = $caller->call(fn () => 'hello'); @@ -32,12 +36,11 @@ public function testCallReportsExceptionAndReturnsNull(): void { $exception = new RuntimeException('test error'); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->once()->with($exception); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report')->with($exception); - $container = m::mock(Container::class); - $container->shouldReceive('has')->with(ExceptionHandlerContract::class)->andReturnTrue(); - $container->shouldReceive('make')->with(ExceptionHandlerContract::class)->andReturn($handler); + $container = new Container; + $container->instance(ExceptionHandlerContract::class, $handler); $caller = new SafeCaller($container); $result = $caller->call(fn () => throw $exception); @@ -47,12 +50,11 @@ public function testCallReportsExceptionAndReturnsNull(): void public function testCallReturnsDefaultClosureOnException(): void { - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->once(); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report'); - $container = m::mock(Container::class); - $container->shouldReceive('has')->with(ExceptionHandlerContract::class)->andReturnTrue(); - $container->shouldReceive('make')->with(ExceptionHandlerContract::class)->andReturn($handler); + $container = new Container; + $container->instance(ExceptionHandlerContract::class, $handler); $caller = new SafeCaller($container); $result = $caller->call( @@ -72,14 +74,14 @@ public function testCallReturnsDefaultWhenExceptionReportingFails(): void $previousErrorLog = ini_set('error_log', $errorLog); $exception = new RuntimeException('protected operation failed'); $reportingFailure = new RuntimeException('exception reporting failed'); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->once()->with($exception)->andThrow($reportingFailure); - $container = m::mock(Container::class); - $container->shouldReceive('has')->once()->with(ExceptionHandlerContract::class)->andReturnTrue(); - $container->shouldReceive('make')->once()->with(ExceptionHandlerContract::class)->andReturn($handler); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report')->with($exception)->throws($reportingFailure); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->expects('has')->with(ExceptionHandlerContract::class)->returns(true); + $container->expects('make')->with(ExceptionHandlerContract::class)->returns($handler); try { - $result = (new SafeCaller($container))->call( + $result = (new SafeCaller($container->instance()))->call( static fn () => throw $exception, static fn () => 'fallback', ); @@ -107,9 +109,9 @@ public function testCallPreservesCancellationFromCallback(bool $wrapped): void if ($wrapped) { $cancellation = new RuntimeException('Callback cleanup failed.', previous: $cancellation); } - $container = m::mock(Container::class); - $container->shouldNotReceive('has'); - $caller = new SafeCaller($container); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->expects('has')->never(); + $caller = new SafeCaller($container->instance()); try { $caller->call(fn () => throw $cancellation); @@ -132,12 +134,12 @@ public function testCallPreservesCancellationFromExceptionReporter(bool $wrapped } $defaultCalled = false; - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->once()->with($failure)->andThrow($cancellation); - $container = m::mock(Container::class); - $container->shouldReceive('has')->once()->with(ExceptionHandlerContract::class)->andReturnTrue(); - $container->shouldReceive('make')->once()->with(ExceptionHandlerContract::class)->andReturn($handler); - $caller = new SafeCaller($container); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report')->with($failure)->throws($cancellation); + $container = Double::for(ContainerContract::class, override: true)->strict(); + $container->expects('has')->with(ExceptionHandlerContract::class)->returns(true); + $container->expects('make')->with(ExceptionHandlerContract::class)->returns($handler); + $caller = new SafeCaller($container->instance()); try { $caller->call( @@ -157,8 +159,7 @@ function () use (&$defaultCalled): void { public function testCallWithoutExceptionHandlerInContainer(): void { - $container = m::mock(Container::class); - $container->shouldReceive('has')->with(ExceptionHandlerContract::class)->andReturnFalse(); + $container = new Container; $caller = new SafeCaller($container); $result = $caller->call(fn () => throw new RuntimeException('fail')); @@ -168,12 +169,11 @@ public function testCallWithoutExceptionHandlerInContainer(): void public function testCallWithNullDefaultReturnsNull(): void { - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->once(); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report'); - $container = m::mock(Container::class); - $container->shouldReceive('has')->with(ExceptionHandlerContract::class)->andReturnTrue(); - $container->shouldReceive('make')->with(ExceptionHandlerContract::class)->andReturn($handler); + $container = new Container; + $container->instance(ExceptionHandlerContract::class, $handler); $caller = new SafeCaller($container); $result = $caller->call( diff --git a/tests/Support/SupportTestingEventFakeTest.php b/tests/Support/SupportTestingEventFakeTest.php index b599610cc5..bd8eef9a4a 100644 --- a/tests/Support/SupportTestingEventFakeTest.php +++ b/tests/Support/SupportTestingEventFakeTest.php @@ -8,18 +8,24 @@ use Hypervel\Events\Dispatcher as EventDispatcher; use Hypervel\Support\Testing\Fakes\EventFake; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\ExpectationFailedException; class SupportTestingEventFakeTest extends TestCase { + use VerifiesDoubles; + protected EventFake $fake; + /** + * Create an isolated event fake. + */ protected function setUp(): void { parent::setUp(); - $this->fake = new EventFake(m::mock(Dispatcher::class)); + $this->fake = new EventFake(Double::for(Dispatcher::class)->strict()); } public function testAssertDispatched(): void diff --git a/tests/Support/SupportUriTest.php b/tests/Support/SupportUriTest.php index 6fb5296a7b..646d0661de 100644 --- a/tests/Support/SupportUriTest.php +++ b/tests/Support/SupportUriTest.php @@ -13,9 +13,10 @@ use Hypervel\Support\Uri; use Hypervel\Tests\Support\Concerns\TestsInteractsWithDataContract; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use League\Uri\Contracts\UriInterface; use League\Uri\Uri as LeagueUri; -use Mockery as m; use stdClass; use Stringable; use TypeError; @@ -23,6 +24,7 @@ class SupportUriTest extends TestCase { use TestsInteractsWithDataContract; + use VerifiesDoubles; public function testCanBuildSpecialUrls(): void { @@ -39,7 +41,7 @@ public function testSpecialUrlParametersAcceptUrlRoutableInstances(): void { Uri::setUrlGeneratorResolver(fn () => new CustomUrlGeneratorResolver); - $parameter = m::mock(UrlRoutable::class); + $parameter = Double::for(UrlRoutable::class)->strict(); $this->assertSame('https://hypervel.org/route', Uri::route('', $parameter)->value()); $this->assertSame('https://hypervel.org/signed-route', Uri::signedRoute('', $parameter)->value()); @@ -96,8 +98,8 @@ public function testOrigin(): void $this->assertNull(Uri::of('file:///etc/hosts')->origin()); $this->assertNull(Uri::of('')->origin()); - $customUri = m::mock(UriInterface::class); - $customUri->shouldReceive('toString')->once()->andReturn('https://example.com:8443/path'); + $customUri = Double::for(UriInterface::class)->strict(); + $customUri->expects('toString')->returns('https://example.com:8443/path'); $this->assertSame('https://example.com:8443', Uri::of($customUri)->origin()); } diff --git a/tests/Telescope/Console/InstallCommandTest.php b/tests/Telescope/Console/InstallCommandTest.php index f4897f6923..1aa23676c3 100644 --- a/tests/Telescope/Console/InstallCommandTest.php +++ b/tests/Telescope/Console/InstallCommandTest.php @@ -11,12 +11,15 @@ use Hypervel\Telescope\TelescopeServiceProvider; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Testing\Fixtures\CleanupActions; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\Console\Command\Command as SymfonyCommand; class InstallCommandTest extends TestCase { + use VerifiesDoubles; + protected ?string $originalProvidersContents = null; protected function setUp(): void @@ -186,8 +189,8 @@ public function testInstallCommandFailsWhenProviderReplacementFails(): void $this->originalProvidersContents, ); - $files = m::mock(Filesystem::class); - $files->shouldReceive('replace')->once()->andThrow(new RuntimeException('replace failed')); + $files = Double::for(Filesystem::class)->strict(); + $files->expects('replace')->throws(new RuntimeException('replace failed')); $this->app->instance(Filesystem::class, $files); $this->artisan('telescope:install') diff --git a/tests/Telescope/FeatureTestCase.php b/tests/Telescope/FeatureTestCase.php index aabb314c3d..78dd9cf781 100644 --- a/tests/Telescope/FeatureTestCase.php +++ b/tests/Telescope/FeatureTestCase.php @@ -18,7 +18,8 @@ use Hypervel\Telescope\TelescopeServiceProvider; use Hypervel\Testbench\Attributes\WithMigration; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionProperty; use function Hypervel\Testbench\load_migration_paths; @@ -27,6 +28,7 @@ class FeatureTestCase extends TestCase { use RefreshDatabase; + use VerifiesDoubles; protected ?ApplicationContract $app = null; @@ -105,20 +107,18 @@ protected function loadTelescopeEntries(): EloquentCollection */ protected function fakeRecordingStore(array &$storedBatches): EntriesRepository { - $store = m::mock(EntriesRepository::class); - $store->shouldReceive('store') - ->twice() - ->withArgs(function (Collection $entries) use (&$storedBatches): bool { + $store = Double::for(EntriesRepository::class)->strict(); + $store->expects('store') + ->times(2) + ->resolves(function (Collection $entries) use (&$storedBatches): void { $storedBatches[] = $entries->map(fn (IncomingEntry $entry): array => [ 'message' => $entry->content['message'], 'batch_id' => $entry->batchId, ])->all(); - - return true; }); - $store->shouldReceive('update') - ->twice() - ->andReturn(Collection::make()); + $store->expects('update') + ->times(2) + ->returns(Collection::make()); (new ReflectionProperty(Telescope::class, 'store'))->setValue($store); diff --git a/tests/Telescope/Http/QueueBatchesControllerTest.php b/tests/Telescope/Http/QueueBatchesControllerTest.php index 7eed990289..59ddbbec0d 100644 --- a/tests/Telescope/Http/QueueBatchesControllerTest.php +++ b/tests/Telescope/Http/QueueBatchesControllerTest.php @@ -11,7 +11,7 @@ use Hypervel\Telescope\EntryType; use Hypervel\Telescope\Http\Controllers\QueueBatchesController; use Hypervel\Tests\Telescope\FeatureTestCase; -use Mockery as m; +use JMac\Testing\Double; class QueueBatchesControllerTest extends FeatureTestCase { @@ -25,11 +25,10 @@ public function testShowHandlesADeletedQueueBatch(): void 'type' => EntryType::BATCH, ]); - $batchRepository = m::mock(BatchRepository::class); - $batchRepository->shouldReceive('find') - ->once() + $batchRepository = Double::for(BatchRepository::class)->strict(); + $batchRepository->expects('find') ->with($batchId) - ->andReturnNull(); + ->returns(null); $this->app->instance(BatchRepository::class, $batchRepository); $result = $this->app->make(QueueBatchesController::class)->show( diff --git a/tests/Telescope/Jobs/ProcessPendingUpdatesTest.php b/tests/Telescope/Jobs/ProcessPendingUpdatesTest.php index fd8ba49523..26c2175e03 100644 --- a/tests/Telescope/Jobs/ProcessPendingUpdatesTest.php +++ b/tests/Telescope/Jobs/ProcessPendingUpdatesTest.php @@ -8,7 +8,7 @@ use Hypervel\Telescope\Contracts\EntriesRepository; use Hypervel\Telescope\Jobs\ProcessPendingUpdates; use Hypervel\Tests\Telescope\FeatureTestCase; -use Mockery as m; +use JMac\Testing\Double; class ProcessPendingUpdatesTest extends FeatureTestCase { @@ -22,13 +22,12 @@ public function testPendingUpdates(): void ]); $failedUpdates = collect(); - $repository = m::mock(EntriesRepository::class); + $repository = Double::for(EntriesRepository::class)->strict(); $repository - ->shouldReceive('update') - ->once() + ->expects('update') ->with($pendingUpdates) - ->andReturn($failedUpdates); + ->returns($failedUpdates); (new ProcessPendingUpdates($pendingUpdates))->handle($repository); @@ -47,13 +46,12 @@ public function testPendingUpdatesMayStayPending(): void $pendingUpdates->get(1), ]); - $repository = m::mock(EntriesRepository::class); + $repository = Double::for(EntriesRepository::class)->strict(); $repository - ->shouldReceive('update') - ->once() + ->expects('update') ->with($pendingUpdates) - ->andReturn($failedUpdates); + ->returns($failedUpdates); (new ProcessPendingUpdates($pendingUpdates))->handle($repository); @@ -74,13 +72,12 @@ public function testPendingUpdatesMayStayPendingOnlyThreeTimes(): void $pendingUpdates->get(1), ]); - $repository = m::mock(EntriesRepository::class); + $repository = Double::for(EntriesRepository::class)->strict(); $repository - ->shouldReceive('update') - ->once() + ->expects('update') ->with($pendingUpdates) - ->andReturn($failedUpdates); + ->returns($failedUpdates); (new ProcessPendingUpdates($pendingUpdates, 2))->handle($repository); @@ -95,11 +92,10 @@ public function testNullableCustomRepositoryResultDoesNotDispatchAnotherUpdate() ['id' => 1, 'content' => 'foo'], ]); - $repository = m::mock(EntriesRepository::class); - $repository->shouldReceive('update') - ->once() + $repository = Double::for(EntriesRepository::class)->strict(); + $repository->expects('update') ->with($pendingUpdates) - ->andReturnNull(); + ->returns(null); (new ProcessPendingUpdates($pendingUpdates))->handle($repository); diff --git a/tests/Telescope/Storage/DatabaseEntriesRepositoryTest.php b/tests/Telescope/Storage/DatabaseEntriesRepositoryTest.php index 292ea8fb7e..b4b307778b 100644 --- a/tests/Telescope/Storage/DatabaseEntriesRepositoryTest.php +++ b/tests/Telescope/Storage/DatabaseEntriesRepositoryTest.php @@ -16,8 +16,8 @@ use Hypervel\Telescope\Storage\DatabaseEntriesRepository; use Hypervel\Telescope\Storage\EntryQueryOptions; use Hypervel\Tests\Telescope\FeatureTestCase; +use JMac\Testing\Double; use JsonException; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -136,8 +136,8 @@ public function testMonitorStoresEveryUniqueNewTag(): void public function testMonitoredTagFallbackPreservesCancellation(bool $canceled): void { $failure = new RuntimeException('Monitoring failed.', previous: $canceled ? new CanceledException : null); - $repository = m::mock(DatabaseEntriesRepository::class, ['testing'])->makePartial(); - $repository->shouldReceive('monitoring')->once()->andThrow($failure); + $repository = Double::for(new DatabaseEntriesRepository('testing'))->passthru(); + $repository->expects('monitoring')->throws($failure); $repository->setMonitorTags(['existing']); $caught = null; diff --git a/tests/Telescope/Telescope/TelescopeTest.php b/tests/Telescope/Telescope/TelescopeTest.php index e517031423..f83010e52e 100644 --- a/tests/Telescope/Telescope/TelescopeTest.php +++ b/tests/Telescope/Telescope/TelescopeTest.php @@ -11,6 +11,7 @@ use Hypervel\Console\Scheduling\Event; use Hypervel\Context\RequestContext; use Hypervel\Contracts\Bus\Dispatcher; +use Hypervel\Contracts\Cache\Repository as CacheRepository; use Hypervel\Contracts\Debug\ExceptionHandler; use Hypervel\Contracts\Events\Dispatcher as EventDispatcher; use Hypervel\Contracts\Queue\ShouldQueue; @@ -26,7 +27,7 @@ use Hypervel\Telescope\Watchers\QueryWatcher; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Tests\Telescope\FeatureTestCase; -use Mockery as m; +use JMac\Testing\Double; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -302,8 +303,10 @@ public function testStartingRecordingPreservesCacheCancellation(): void Telescope::stopRecording(); $failure = new RuntimeException('Pause lookup cleanup failed.', previous: new CanceledException); $original = $this->app->make('cache'); - $cache = m::mock(CacheManager::class); - $cache->shouldReceive('get')->once()->with('telescope:pause-recording', false)->andThrow($failure); + $repository = Double::for(CacheRepository::class)->strict(); + $repository->expects('get')->with('telescope:pause-recording', false)->throws($failure); + $cache = Double::for(new CacheManager($this->app))->passthru(); + $cache->expects('store')->returns($repository); $this->app->instance('cache', $cache); $caught = null; @@ -400,7 +403,7 @@ public function testScheduledTaskStartsRecordingWhenSchedulerIsApproved(): void Telescope::stopRecording(); $this->app->make(EventDispatcher::class) - ->dispatch(new ScheduledTaskStarting(m::mock(Event::class))); + ->dispatch(new ScheduledTaskStarting(Double::for(Event::class)->strict())); $this->assertTrue(Telescope::isRecording()); } @@ -411,7 +414,7 @@ public function testConfiguredIgnoredSchedulerDoesNotStartTaskRecording(): void Telescope::stopRecording(); $this->app->make(EventDispatcher::class) - ->dispatch(new ScheduledTaskStarting(m::mock(Event::class))); + ->dispatch(new ScheduledTaskStarting(Double::for(Event::class)->strict())); $this->assertFalse(Telescope::isRecording()); } diff --git a/tests/Telescope/Watchers/CommandWatcherTest.php b/tests/Telescope/Watchers/CommandWatcherTest.php index 48fe19ee98..bb1e33da82 100644 --- a/tests/Telescope/Watchers/CommandWatcherTest.php +++ b/tests/Telescope/Watchers/CommandWatcherTest.php @@ -13,7 +13,7 @@ use Hypervel\Telescope\Watchers\CommandWatcher; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Tests\Telescope\FeatureTestCase; -use Mockery as m; +use JMac\Testing\Double; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; @@ -100,9 +100,9 @@ public function testCommandWatcherRedactsUnknownInput(): void $command = new SensitiveInputCommand; $watcher = $this->app->make(CommandWatcher::class); - $input = m::mock(InputInterface::class); - $input->shouldReceive('getArguments')->once()->andReturn([]); - $input->shouldReceive('getOptions')->once()->andReturn(['unknown' => 'unknown-secret']); + $input = Double::for(InputInterface::class)->strict(); + $input->expects('getArguments')->returns([]); + $input->expects('getOptions')->returns(['unknown' => 'unknown-secret']); $watcher->recordCommand(new AfterExecute($command, null, $input, 0)); diff --git a/tests/Telescope/Watchers/DumpWatcherTest.php b/tests/Telescope/Watchers/DumpWatcherTest.php index 2a14e836a8..0fb4209f6d 100644 --- a/tests/Telescope/Watchers/DumpWatcherTest.php +++ b/tests/Telescope/Watchers/DumpWatcherTest.php @@ -11,7 +11,7 @@ use Hypervel\Telescope\Watchers\DumpWatcher; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Tests\Telescope\FeatureTestCase; -use Mockery as m; +use JMac\Testing\Double; use PHPUnit\Framework\Attributes\TestWith; use ReflectionProperty; use RuntimeException; @@ -64,8 +64,8 @@ public function testInactiveDumpWatcherDelegatesWithLabel(): void public function testDumpDelegatesWithoutResolvingCacheWhenTelescopeIsNotRecording(): void { Telescope::stopRecording(); - $cache = m::mock(CacheFactory::class); - $cache->shouldNotReceive('store'); + $cache = Double::for(CacheFactory::class)->strict(); + $cache->expects('store')->never(); $delegated = []; $this->installWatcher( $cache, @@ -85,15 +85,13 @@ public function testDumpDelegatesWithoutResolvingCacheWhenTelescopeIsNotRecordin public function testCacheFailureDelegatesTheDumpUnlessCanceled(bool $canceled): void { $failure = new RuntimeException('Cache unavailable.', previous: $canceled ? new CanceledException : null); - $cache = m::mock(CacheFactory::class); - $repository = m::mock(CacheRepository::class); - $cache->shouldReceive('store') - ->once() - ->andReturn($repository); - $repository->shouldReceive('get') - ->once() + $cache = Double::for(CacheFactory::class)->strict(); + $repository = Double::for(CacheRepository::class)->strict(); + $cache->expects('store') + ->returns($repository); + $repository->expects('get') ->with('telescope:dump-watcher') - ->andThrow($failure); + ->throws($failure); $delegated = []; $this->installWatcher( $cache, @@ -117,8 +115,8 @@ public function testCacheFailureDelegatesTheDumpUnlessCanceled(bool $canceled): public function testAlwaysOptionRecordsWithoutResolvingCache(): void { - $cache = m::mock(CacheFactory::class); - $cache->shouldNotReceive('store'); + $cache = Double::for(CacheFactory::class)->strict(); + $cache->expects('store')->never(); $delegated = []; $this->installWatcher( $cache, diff --git a/tests/Telescope/Watchers/JobWatcherTest.php b/tests/Telescope/Watchers/JobWatcherTest.php index fd367a7b07..b6992098b2 100644 --- a/tests/Telescope/Watchers/JobWatcherTest.php +++ b/tests/Telescope/Watchers/JobWatcherTest.php @@ -28,8 +28,8 @@ use Hypervel\Testbench\Attributes\WithMigration; use Hypervel\Testbench\Factories\UserFactory; use Hypervel\Tests\Telescope\FeatureTestCase; +use JMac\Testing\Double; use JsonSerializable; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Throwable; @@ -125,8 +125,8 @@ public function testProcessedJobClearsStaleFailureStateLeftByADuplicateReservati 'data' => ['payload' => 'long-running'], ]); - $job = m::mock(Job::class); - $job->shouldReceive('payload')->andReturn(['telescope_uuid' => $entry->uuid]); + $job = Double::for(Job::class)->strict(); + $job->allows('payload')->returns(['telescope_uuid' => $entry->uuid]); $watcher->recordFailedJob(new QueueJobFailed( 'redis', @@ -229,15 +229,12 @@ public function testJobCanHandleDeletedSerializedModel(): void public function testJobRegistersProcessingEntryWithBatchFamilyHash(): void { - $batch = m::mock(Batch::class); - $batch->shouldReceive('toArray') - ->once() - ->andReturn(['foo' => 'bar']); - $batchRepository = m::mock(BatchRepository::class); - $batchRepository->shouldReceive('find') + $batch = Double::for(Batch::class)->strict(); + $batch->expects('toArray')->returns(['foo' => 'bar']); + $batchRepository = Double::for(BatchRepository::class)->strict(); + $batchRepository->expects('find') ->with('batch-id') - ->once() - ->andReturn($batch); + ->returns($batch); $this->app->instance(BatchRepository::class, $batchRepository); diff --git a/tests/Telescope/Watchers/QueryWatcherTest.php b/tests/Telescope/Watchers/QueryWatcherTest.php index a7e959d451..38eb850ac1 100644 --- a/tests/Telescope/Watchers/QueryWatcherTest.php +++ b/tests/Telescope/Watchers/QueryWatcherTest.php @@ -18,7 +18,8 @@ use Hypervel\Tests\Di\Fixtures\ProxySources; use Hypervel\Tests\Telescope\FeatureTestCase; use Hypervel\Tests\Telescope\Fixtures\ProxyFrameQueryWatcher; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; use ReflectionClass; use TypeError; @@ -156,10 +157,9 @@ public function testQueryWatcherUsesTheConnectionsEscapingContract(): void 'select * from records where external_id = ?', ['=ABC001'], ); - $connection->shouldReceive('escape') - ->once() + $connection->expects('escape') ->with('=ABC001') - ->andReturn('FILEMAKER_STRING[=ABC001]'); + ->returns('FILEMAKER_STRING[=ABC001]'); $sql = $this->app->make(QueryWatcher::class)->replaceBindings($event); @@ -221,10 +221,9 @@ public function testQueryWatcherSubstitutesEscapedBindingsLiterally(): void 'O''Reilly \\ café $1 \1' TEXT; [$event, $connection] = $this->queryEvent('select ?, ?', [$binding, 1.234567890123456]); - $connection->shouldReceive('escape') - ->once() + $connection->expects('escape') ->with($binding) - ->andReturn($quotedBinding); + ->returns($quotedBinding); $this->assertSame( 'select ' . $quotedBinding . ', 1.234567890123456', @@ -298,7 +297,7 @@ public function testQueryWatcherDoesNotHideBrokenDriverErrors(): void { [$event, $connection] = $this->queryEvent('select ?', ['value']); $failure = new TypeError('Broken driver.'); - $connection->shouldReceive('escape')->once()->andThrow($failure); + $connection->expects('escape')->throws($failure); try { $this->app->make(QueryWatcher::class)->replaceBindings($event); @@ -360,13 +359,13 @@ public function testQueryWatcherClassifiesGeneratedProxyFramesByTheirSourceFile( /** * Create a query event and its test connection. * - * @return array{QueryExecuted, Connection} + * @return array{QueryExecuted, Connection&DoubleInterface} */ private function queryEvent(string $sql, array $bindings): array { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getName')->once()->andReturn('filemaker'); - $connection->shouldReceive('prepareBindings')->once()->with($bindings)->andReturn($bindings); + $connection = Double::for(Connection::class)->strict(); + $connection->expects('getName')->returns('filemaker'); + $connection->expects('prepareBindings')->with($bindings)->returns($bindings); return [new QueryExecuted($sql, $bindings, 500, $connection), $connection]; } diff --git a/tests/Telescope/Watchers/RedisWatcherTest.php b/tests/Telescope/Watchers/RedisWatcherTest.php index 53df727ee4..9c3603cd49 100644 --- a/tests/Telescope/Watchers/RedisWatcherTest.php +++ b/tests/Telescope/Watchers/RedisWatcherTest.php @@ -13,8 +13,8 @@ use Hypervel\Telescope\Watchers\RedisWatcher; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Tests\Telescope\FeatureTestCase; +use JMac\Testing\Double; use JsonSerializable; -use Mockery as m; use ReflectionClass; use RuntimeException; @@ -141,26 +141,24 @@ public function testRedisWatcherIgnoresBatchOpenersCaseInsensitively(): void public function testDoesNotRegisterWhenRedisUnbound(): void { - $app = m::mock(Application::class); - - $app->makePartial(); + $app = Double::for(Application::class, override: true)->strict(); $app->expects('bound') ->with('redis') - ->andReturn(false); + ->returns(false); - $app->shouldNotReceive('make') + $app->expects('make')->never() ->with('redis'); $watcher = new RedisWatcher([]); - $watcher->register($app); + $watcher->register($app->instance()); } private function dispatchRedisCommand(string $command, array $parameters = []): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getName')->andReturn('connection'); + $connection = Double::for(PhpRedisConnection::class)->strict(); + $connection->allows('getName')->returns('connection'); $this->app->make(Dispatcher::class) ->dispatch(new CommandExecuted( diff --git a/tests/Telescope/Watchers/ReverbWatcherTest.php b/tests/Telescope/Watchers/ReverbWatcherTest.php index 0da9059d0a..057fed3e6c 100644 --- a/tests/Telescope/Watchers/ReverbWatcherTest.php +++ b/tests/Telescope/Watchers/ReverbWatcherTest.php @@ -23,7 +23,7 @@ use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Tests\Reverb\Fixtures\FakeConnection; use Hypervel\Tests\Telescope\FeatureTestCase; -use Mockery as m; +use JMac\Testing\Double; use Swoole\Server; #[WithConfig('telescope.watchers', [ @@ -92,8 +92,8 @@ protected function defineEnvironment(ApplicationContract $app): void $config->set('database.redis.queue', $redisConnection); $config->set('database.redis.reverb', $redisConnection); - $server = m::mock(Server::class); - $server->shouldReceive('sendMessage')->zeroOrMoreTimes(); + $server = Double::for(Server::class)->strict(); + $server->allows('sendMessage'); $server->setting = ['worker_num' => 1]; $server->worker_id = 0; $app->instance(Server::class, $server); diff --git a/tests/Telescope/Watchers/ScheduleWatcherTest.php b/tests/Telescope/Watchers/ScheduleWatcherTest.php index ed85c279fa..09055c9cba 100644 --- a/tests/Telescope/Watchers/ScheduleWatcherTest.php +++ b/tests/Telescope/Watchers/ScheduleWatcherTest.php @@ -22,7 +22,7 @@ use Hypervel\Telescope\Watchers\ScheduleWatcher; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Tests\Telescope\FeatureTestCase; -use Mockery as m; +use JMac\Testing\Double; use RuntimeException; #[WithConfig('telescope.watchers', [ @@ -206,8 +206,8 @@ public function testIgnoredSchedulerDoesNotRegisterAnEntry(): void config(['telescope.ignore_commands' => ['schedule:run']]); Telescope::stopRecording(); - $task = m::mock(Event::class); - $task->shouldNotReceive('getOutput'); + $task = Double::for(Event::class)->strict(); + $task->expects('getOutput')->never(); $events = $this->app->make(Dispatcher::class); $events->dispatch(new ScheduledTaskStarting($task)); $events->dispatch(new ScheduledTaskFinished($task, 0.1)); @@ -279,17 +279,17 @@ protected function makeTask( int $outputCalls = 1, ?string $output = null, ): Event { - $task = m::mock(Event::class); + $task = Double::for(Event::class)->strict(); $task->command = $command; $task->description = $command . ' description'; $task->expression = '* * * * *'; $task->timezone = 'UTC'; - $task->shouldReceive('exitCode')->andReturn($exitCode); - $task->shouldReceive('wasSkippedDueToOverlapping')->andReturn($skippedBecauseOverlapping); - $task->shouldReceive('getOutput') + $task->allows('exitCode')->returns($exitCode); + $task->allows('wasSkippedDueToOverlapping')->returns($skippedBecauseOverlapping); + $task->expects('getOutput') ->times($outputCalls) ->with($this->app) - ->andReturn($output ?? $command . ' output'); + ->returns($output ?? $command . ' output'); return $task; } diff --git a/tests/Testbench/Attributes/DefineDatabaseTest.php b/tests/Testbench/Attributes/DefineDatabaseTest.php index 39e5d03599..a2a221bc19 100644 --- a/tests/Testbench/Attributes/DefineDatabaseTest.php +++ b/tests/Testbench/Attributes/DefineDatabaseTest.php @@ -5,10 +5,8 @@ namespace Hypervel\Tests\Testbench\Attributes; use Closure; -use Hypervel\Contracts\Foundation\Application as ApplicationContract; use Hypervel\Testbench\Attributes\DefineDatabase; use Hypervel\Testbench\TestCase; -use Mockery as m; use PHPUnit\Framework\Attributes\Test; class DefineDatabaseTest extends TestCase @@ -32,9 +30,9 @@ public function itCanHandleDeferDefinition(): void $this->assertSame('defineCallback', $attribute->method); $this->assertTrue($attribute->defer); - $callback = $attribute->handle($app = m::mock(ApplicationContract::class), function ($method, $parameters) use ($app): void { + $callback = $attribute->handle($this->app, function ($method, $parameters): void { $this->assertSame('defineCallback', $method); - $this->assertSame([$app], $parameters); + $this->assertSame([$this->app], $parameters); }); $this->assertInstanceOf(Closure::class, $callback); @@ -51,9 +49,9 @@ public function itCanHandleEagerDefinition(): void $this->assertSame('defineCallback', $attribute->method); $this->assertFalse($attribute->defer); - $callback = $attribute->handle($app = m::mock(ApplicationContract::class), function ($method, $parameters) use ($app): void { + $callback = $attribute->handle($this->app, function ($method, $parameters): void { $this->assertSame('defineCallback', $method); - $this->assertSame([$app], $parameters); + $this->assertSame([$this->app], $parameters); }); $this->assertNull($callback); diff --git a/tests/Testbench/Attributes/DefineRouteTest.php b/tests/Testbench/Attributes/DefineRouteTest.php index f5e93708a3..19fe787a81 100644 --- a/tests/Testbench/Attributes/DefineRouteTest.php +++ b/tests/Testbench/Attributes/DefineRouteTest.php @@ -4,11 +4,9 @@ namespace Hypervel\Tests\Testbench\Attributes; -use Hypervel\Contracts\Foundation\Application as ApplicationContract; use Hypervel\Routing\Router; use Hypervel\Testbench\Attributes\DefineRoute; use Hypervel\Testbench\TestCase; -use Mockery as m; use PHPUnit\Framework\Attributes\Test; class DefineRouteTest extends TestCase @@ -30,10 +28,9 @@ public function itCanHandleDefinition(): void $this->assertInstanceOf(DefineRoute::class, $attribute); $this->assertSame('defineCallback', $attribute->method); - $app = m::mock(ApplicationContract::class); - $app->shouldReceive('make')->with('router')->andReturn($router = m::mock(Router::class)); + $router = $this->app->make(Router::class); - $callback = $attribute->handle($app, function ($method, $parameters) use ($router): void { + $callback = $attribute->handle($this->app, function ($method, $parameters) use ($router): void { $this->assertSame('defineCallback', $method); $this->assertSame([$router], $parameters); }); diff --git a/tests/Testbench/Attributes/RequiresEnvTest.php b/tests/Testbench/Attributes/RequiresEnvTest.php index 620b5c53f5..ce9ceaac9e 100644 --- a/tests/Testbench/Attributes/RequiresEnvTest.php +++ b/tests/Testbench/Attributes/RequiresEnvTest.php @@ -4,10 +4,8 @@ namespace Hypervel\Tests\Testbench\Attributes; -use Hypervel\Contracts\Foundation\Application as ApplicationContract; use Hypervel\Testbench\Attributes\RequiresEnv; use Hypervel\Testbench\TestCase; -use Mockery as m; use PHPUnit\Framework\Attributes\Test; class RequiresEnvTest extends TestCase @@ -17,7 +15,7 @@ public function itShouldRunTheTestWhenEnvVariableIsMissing(): void { $attribute = new RequiresEnv('TESTBENCH_MISSING_ENV'); - $callback = $attribute->handle(m::mock(ApplicationContract::class), function ($method, $parameters): void { + $callback = $attribute->handle($this->app, function ($method, $parameters): void { $this->assertSame('markTestSkipped', $method); $this->assertSame(['Missing required environment variable `TESTBENCH_MISSING_ENV`'], $parameters); }); diff --git a/tests/Testbench/Attributes/WithEnvTest.php b/tests/Testbench/Attributes/WithEnvTest.php index 42c9f5e3bf..bec376a810 100644 --- a/tests/Testbench/Attributes/WithEnvTest.php +++ b/tests/Testbench/Attributes/WithEnvTest.php @@ -4,11 +4,9 @@ namespace Hypervel\Tests\Testbench\Attributes; -use Hypervel\Contracts\Foundation\Application as ApplicationContract; use Hypervel\Testbench\Attributes\WithEnv; use Hypervel\Testbench\Foundation\Env; use Hypervel\Testbench\TestCase; -use Mockery as m; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\Attributes\TestWith; @@ -23,7 +21,7 @@ public function itCanResolveDefinedEnvVariables(): void try { $this->assertNull(Env::get('TESTING_USING_ATTRIBUTE')); - $callback = $attribute(m::mock(ApplicationContract::class)); + $callback = $attribute($this->app); $this->assertTrue(Env::get('TESTING_USING_ATTRIBUTE')); } finally { @@ -39,13 +37,12 @@ public function itCanResolveDefinedEnvVariables(): void public function itCanResolveSpecialCharactersAndZero(): void { $value = "O'Reilly\\path\" \$HOME\nline\rreturn\fform\ttab\vvertical # hash"; - $app = m::mock(ApplicationContract::class); $specialCallback = null; $zeroCallback = null; try { - $specialCallback = (new WithEnv('TESTING_SPECIAL_ATTRIBUTE', $value))($app); - $zeroCallback = (new WithEnv('TESTING_ZERO_ATTRIBUTE', '0'))($app); + $specialCallback = (new WithEnv('TESTING_SPECIAL_ATTRIBUTE', $value))($this->app); + $zeroCallback = (new WithEnv('TESTING_ZERO_ATTRIBUTE', '0'))($this->app); $this->assertSame($value, Env::get('TESTING_SPECIAL_ATTRIBUTE')); $this->assertSame('0', Env::get('TESTING_ZERO_ATTRIBUTE')); @@ -83,7 +80,7 @@ public function itRestoresValuesAfterScopedEnvironmentChanges(bool $hasOriginalV Env::getRepository()->set($key, $originalValue); } - $restore = (new WithEnv($key, 'temporary'))(m::mock(ApplicationContract::class)); + $restore = (new WithEnv($key, 'temporary'))($this->app); try { $this->assertSame('temporary', Env::get($key)); @@ -111,7 +108,7 @@ public function itCannotChangeDefinedEnvVariables(): void $this->assertSame('AckfSECXIvnK5r28GVIWUAxmbBSjTsmF', Env::get('HYPERVEL_KEY')); - $callback = $attribute(m::mock(ApplicationContract::class)); + $callback = $attribute($this->app); $this->assertSame('AckfSECXIvnK5r28GVIWUAxmbBSjTsmF', Env::get('HYPERVEL_KEY')); diff --git a/tests/Testbench/CommanderTest.php b/tests/Testbench/CommanderTest.php index 687f1cfaa6..5c675673f9 100644 --- a/tests/Testbench/CommanderTest.php +++ b/tests/Testbench/CommanderTest.php @@ -17,7 +17,8 @@ use Hypervel\Testbench\Workbench\Workbench; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Testbench\Fixtures\Providers\MergedConfigServiceProvider; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\RequiresOperatingSystem; use PHPUnit\Framework\Attributes\RequiresPhpExtension; use PHPUnit\Framework\Attributes\Test; @@ -38,6 +39,7 @@ class CommanderTest extends TestCase { use InteractsWithSqliteDatabaseFile; + use VerifiesDoubles; protected string $tempDir; @@ -299,7 +301,7 @@ public function itRendersApplicationThrowablesToTheConsoleErrorOutput(): void $errorOutput = new BufferedOutput; $output->setErrorOutput($errorOutput); - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); $handler->expects('report')->with($exception); $handler->expects('renderForConsole')->with($errorOutput, $exception); $this->app->instance(ExceptionHandlerContract::class, $handler); @@ -315,9 +317,9 @@ public function itRetainsApplicationThrowableWhenReportingFails(): void { $original = new RuntimeException('Application failure'); $reportingFailure = new RuntimeException('Reporting failure'); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->expects('report')->with($original)->andThrow($reportingFailure); - $handler->shouldNotReceive('renderForConsole'); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report')->with($original)->throws($reportingFailure); + $handler->expects('renderForConsole')->never(); $this->app->instance(ExceptionHandlerContract::class, $handler); $commander = new CommanderThrowableHarness([], __DIR__); diff --git a/tests/Testbench/Databases/MigrateProcessorTest.php b/tests/Testbench/Databases/MigrateProcessorTest.php index bc6747af53..54a35eed2a 100644 --- a/tests/Testbench/Databases/MigrateProcessorTest.php +++ b/tests/Testbench/Databases/MigrateProcessorTest.php @@ -9,36 +9,38 @@ use Hypervel\Testbench\Contracts\TestCase as TestCaseContract; use Hypervel\Testbench\Database\MigrateProcessor; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\Test; use RuntimeException; class MigrateProcessorTest extends TestCase { + use VerifiesDoubles; + #[Test] public function itRollsBackOnlyTheBatchCreatedByTheProcessor(): void { - $repository = m::mock(MigrationRepositoryInterface::class); - $repository->shouldReceive('repositoryExists')->twice()->andReturnTrue(); - $repository->shouldReceive('getNextBatchNumber')->twice()->andReturn(4, 5); - $repository->shouldReceive('getMigrationsByBatch')->once()->with(4)->andReturn([]); - $testbench = m::mock(TestCaseContract::class); - $testbench->shouldReceive('artisan') - ->once() + $repository = Double::for(MigrationRepositoryInterface::class)->strict(); + $repository->expects('repositoryExists')->times(2)->returns(true); + $repository->expects('getNextBatchNumber')->times(2)->returns(4, 5); + $repository->expects('getMigrationsByBatch')->with(4)->returns([]); + $testbench = Double::for(TestCaseContract::class)->strict(); + $testbench->expects('artisan') ->with('migrate', [ '--database' => 'secondary', '--path' => ['/migrations'], '--step' => true, ]) - ->andReturn(0); - $testbench->shouldReceive('artisan') - ->once() + ->returns(0); + $testbench->expects('artisan') ->with('migrate:rollback', [ '--database' => 'secondary', '--path' => ['/migrations'], '--batch' => 4, ]) - ->andReturn(0); + ->returns(0); $processor = new MigrateProcessor( $testbench, $this->migrator($repository, 'secondary'), @@ -55,21 +57,20 @@ public function itRollsBackOnlyTheBatchCreatedByTheProcessor(): void #[Test] public function itRollsBackEveryOwnedStepBatchInDescendingOrder(): void { - $repository = m::mock(MigrationRepositoryInterface::class); - $repository->shouldReceive('repositoryExists')->twice()->andReturnTrue(); - $repository->shouldReceive('getNextBatchNumber')->twice()->andReturn(1, 4); - $repository->shouldReceive('getMigrationsByBatch')->once()->with(3)->andReturn([]); - $repository->shouldReceive('getMigrationsByBatch')->once()->with(2)->andReturn([]); - $repository->shouldReceive('getMigrationsByBatch')->once()->with(1)->andReturn([]); - $testbench = m::mock(TestCaseContract::class); - $testbench->shouldReceive('artisan')->once()->with('migrate', ['--step' => true])->andReturn(0); + $repository = Double::for(MigrationRepositoryInterface::class)->strict(); + $repository->expects('repositoryExists')->times(2)->returns(true); + $repository->expects('getNextBatchNumber')->times(2)->returns(1, 4); + $repository->expects('getMigrationsByBatch')->with(3)->returns([]); + $repository->expects('getMigrationsByBatch')->with(2)->returns([]); + $repository->expects('getMigrationsByBatch')->with(1)->returns([]); + $testbench = Double::for(TestCaseContract::class)->strict(); + $testbench->expects('artisan')->with('migrate', ['--step' => true])->returns(0); foreach ([3, 2, 1] as $batch) { - $testbench->shouldReceive('artisan') - ->once() + $testbench->expects('artisan') ->with('migrate:rollback', ['--batch' => $batch]) ->ordered() - ->andReturn(0); + ->returns(0); } $processor = new MigrateProcessor( @@ -84,12 +85,12 @@ public function itRollsBackEveryOwnedStepBatchInDescendingOrder(): void #[Test] public function itDoesNotRollbackWhenTheMigrationCreatedNoBatch(): void { - $repository = m::mock(MigrationRepositoryInterface::class); - $repository->shouldReceive('repositoryExists')->twice()->andReturnTrue(); - $repository->shouldReceive('getNextBatchNumber')->twice()->andReturn(4, 4); - $testbench = m::mock(TestCaseContract::class); - $testbench->shouldReceive('artisan')->once()->with('migrate', [])->andReturn(0); - $testbench->shouldNotReceive('artisan')->with('migrate:rollback', m::any()); + $repository = Double::for(MigrationRepositoryInterface::class)->strict(); + $repository->expects('repositoryExists')->times(2)->returns(true); + $repository->expects('getNextBatchNumber')->times(2)->returns(4, 4); + $testbench = Double::for(TestCaseContract::class)->strict(); + $testbench->expects('artisan')->with('migrate', [])->returns(0); + $testbench->expects('artisan')->never()->with('migrate:rollback', Argument::any()); $processor = new MigrateProcessor($testbench, $this->migrator($repository)); $processor->up()->rollback(); @@ -98,19 +99,17 @@ public function itDoesNotRollbackWhenTheMigrationCreatedNoBatch(): void #[Test] public function itCapturesACompletedBatchWhenAFollowingMigrationFails(): void { - $repository = m::mock(MigrationRepositoryInterface::class); - $repository->shouldReceive('repositoryExists')->twice()->andReturnTrue(); - $repository->shouldReceive('getNextBatchNumber')->twice()->andReturn(1, 2); - $repository->shouldReceive('getMigrationsByBatch')->once()->with(1)->andReturn([]); - $testbench = m::mock(TestCaseContract::class); - $testbench->shouldReceive('artisan') - ->once() + $repository = Double::for(MigrationRepositoryInterface::class)->strict(); + $repository->expects('repositoryExists')->times(2)->returns(true); + $repository->expects('getNextBatchNumber')->times(2)->returns(1, 2); + $repository->expects('getMigrationsByBatch')->with(1)->returns([]); + $testbench = Double::for(TestCaseContract::class)->strict(); + $testbench->expects('artisan') ->with('migrate', []) - ->andThrow(new RuntimeException('Migration failed.')); - $testbench->shouldReceive('artisan') - ->once() + ->throws(new RuntimeException('Migration failed.')); + $testbench->expects('artisan') ->with('migrate:rollback', ['--batch' => 1]) - ->andReturn(0); + ->returns(0); $processor = new MigrateProcessor($testbench, $this->migrator($repository)); try { @@ -126,16 +125,15 @@ public function itCapturesACompletedBatchWhenAFollowingMigrationFails(): void #[Test] public function itRejectsANonzeroMigrationResultAndRetainsItsOwnedBatchForCleanup(): void { - $repository = m::mock(MigrationRepositoryInterface::class); - $repository->shouldReceive('repositoryExists')->twice()->andReturnTrue(); - $repository->shouldReceive('getNextBatchNumber')->twice()->andReturn(1, 2); - $repository->shouldReceive('getMigrationsByBatch')->once()->with(1)->andReturn([]); - $testbench = m::mock(TestCaseContract::class); - $testbench->shouldReceive('artisan')->once()->with('migrate', [])->andReturn(1); - $testbench->shouldReceive('artisan') - ->once() + $repository = Double::for(MigrationRepositoryInterface::class)->strict(); + $repository->expects('repositoryExists')->times(2)->returns(true); + $repository->expects('getNextBatchNumber')->times(2)->returns(1, 2); + $repository->expects('getMigrationsByBatch')->with(1)->returns([]); + $testbench = Double::for(TestCaseContract::class)->strict(); + $testbench->expects('artisan')->with('migrate', [])->returns(1); + $testbench->expects('artisan') ->with('migrate:rollback', ['--batch' => 1]) - ->andReturn(0); + ->returns(0); $processor = new MigrateProcessor($testbench, $this->migrator($repository)); try { @@ -151,20 +149,18 @@ public function itRejectsANonzeroMigrationResultAndRetainsItsOwnedBatchForCleanu #[Test] public function itContinuesAfterARollbackFailureAndVerifiesEverySuccessfulBatch(): void { - $repository = m::mock(MigrationRepositoryInterface::class); - $repository->shouldReceive('repositoryExists')->twice()->andReturnTrue(); - $repository->shouldReceive('getNextBatchNumber')->twice()->andReturn(1, 3); - $repository->shouldReceive('getMigrationsByBatch')->once()->with(1)->andReturn([]); - $testbench = m::mock(TestCaseContract::class); - $testbench->shouldReceive('artisan')->once()->with('migrate', ['--step' => true])->andReturn(0); - $testbench->shouldReceive('artisan') - ->once() + $repository = Double::for(MigrationRepositoryInterface::class)->strict(); + $repository->expects('repositoryExists')->times(2)->returns(true); + $repository->expects('getNextBatchNumber')->times(2)->returns(1, 3); + $repository->expects('getMigrationsByBatch')->with(1)->returns([]); + $testbench = Double::for(TestCaseContract::class)->strict(); + $testbench->expects('artisan')->with('migrate', ['--step' => true])->returns(0); + $testbench->expects('artisan') ->with('migrate:rollback', ['--batch' => 2]) - ->andReturn(1); - $testbench->shouldReceive('artisan') - ->once() + ->returns(1); + $testbench->expects('artisan') ->with('migrate:rollback', ['--batch' => 1]) - ->andReturn(0); + ->returns(0); $processor = new MigrateProcessor( $testbench, $this->migrator($repository), @@ -181,16 +177,15 @@ public function itContinuesAfterARollbackFailureAndVerifiesEverySuccessfulBatch( #[Test] public function itRejectsAReportedRollbackThatLeavesTheBatchRecorded(): void { - $repository = m::mock(MigrationRepositoryInterface::class); - $repository->shouldReceive('repositoryExists')->twice()->andReturnTrue(); - $repository->shouldReceive('getNextBatchNumber')->twice()->andReturn(1, 2); - $repository->shouldReceive('getMigrationsByBatch')->once()->with(1)->andReturn(['migration']); - $testbench = m::mock(TestCaseContract::class); - $testbench->shouldReceive('artisan')->once()->with('migrate', [])->andReturn(0); - $testbench->shouldReceive('artisan') - ->once() + $repository = Double::for(MigrationRepositoryInterface::class)->strict(); + $repository->expects('repositoryExists')->times(2)->returns(true); + $repository->expects('getNextBatchNumber')->times(2)->returns(1, 2); + $repository->expects('getMigrationsByBatch')->with(1)->returns(['migration']); + $testbench = Double::for(TestCaseContract::class)->strict(); + $testbench->expects('artisan')->with('migrate', [])->returns(0); + $testbench->expects('artisan') ->with('migrate:rollback', ['--batch' => 1]) - ->andReturn(0); + ->returns(0); $processor = new MigrateProcessor($testbench, $this->migrator($repository)); $processor->up(); @@ -207,11 +202,11 @@ private function migrator( MigrationRepositoryInterface $repository, ?string $connection = null, ): Migrator { - $migrator = m::mock(Migrator::class); - $migrator->shouldReceive('getRepository')->andReturn($repository); - $migrator->shouldReceive('usingConnection') - ->with($connection, m::type('callable')) - ->andReturnUsing(static fn (?string $name, callable $callback): mixed => $callback()); + $migrator = Double::for(Migrator::class)->strict(); + $migrator->allows('getRepository')->returns($repository); + $migrator->allows('usingConnection') + ->with($connection, Argument::type('callable')) + ->resolves(static fn (?string $name, callable $callback): mixed => $callback()); return $migrator; } diff --git a/tests/Testbench/Databases/MigrateWithHypervelTest.php b/tests/Testbench/Databases/MigrateWithHypervelTest.php index 8da022c01e..08253a9590 100644 --- a/tests/Testbench/Databases/MigrateWithHypervelTest.php +++ b/tests/Testbench/Databases/MigrateWithHypervelTest.php @@ -14,7 +14,8 @@ use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\Database\MigrateProcessor; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\Test; use RuntimeException; @@ -25,6 +26,8 @@ #[WithConfig('database.default', 'testing')] class MigrateWithHypervelTest extends TestCase { + use VerifiesDoubles; + #[Test] #[DefineDatabase('loadApplicationMigrations')] public function itLoadsTheMigrations(): void @@ -92,10 +95,10 @@ public function itOwnsAndCleansMigrationBatchesOnASecondaryConnection(): void public function itDetachesProcessorsAndContinuesMigrationCleanupAfterFailure(): void { $failure = new RuntimeException('First rollback failed.'); - $first = m::mock(MigrateProcessor::class); - $first->shouldReceive('rollback')->once()->andThrow($failure); - $second = m::mock(MigrateProcessor::class); - $second->shouldReceive('rollback')->once()->andReturnSelf(); + $first = Double::for(MigrateProcessor::class)->strict(); + $first->expects('rollback')->throws($failure); + $second = Double::for(MigrateProcessor::class)->strict(); + $second->expects('rollback')->returns($second); $this->cachedTestMigratorProcessors = [$first, $second]; try { diff --git a/tests/Testbench/Foundation/Bootstrap/CreateVendorSymlinkTest.php b/tests/Testbench/Foundation/Bootstrap/CreateVendorSymlinkTest.php index f6d3b8ee22..14cf68f5f4 100644 --- a/tests/Testbench/Foundation/Bootstrap/CreateVendorSymlinkTest.php +++ b/tests/Testbench/Foundation/Bootstrap/CreateVendorSymlinkTest.php @@ -13,7 +13,8 @@ use Hypervel\Testbench\Foundation\Application as TestbenchApplication; use Hypervel\Testbench\Foundation\Bootstrap\CreateVendorSymlink; use Hypervel\Testbench\PHPUnit\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Override; use PHPUnit\Framework\Attributes\RequiresOperatingSystem; use PHPUnit\Framework\Attributes\Test; @@ -26,6 +27,8 @@ class CreateVendorSymlinkTest extends TestCase { + use VerifiesDoubles; + private ?ApplicationContract $application = null; private bool $ownsVendorDirectory = false; @@ -116,11 +119,10 @@ public function itRemovesItsVendorLinkWhenPackageDiscoveryFails(): void $workingPath = package_path('vendor'); $application = $this->createApplication(); (new DeleteVendorSymlink)->handle($application); - $manifest = m::mock(PackageManifest::class); + $manifest = Double::for(PackageManifest::class)->strict(); $manifest->manifestPath = $application->getCachedPackagesPath(); - $manifest->shouldReceive('build') - ->once() - ->andThrow(new RuntimeException('Package discovery failed.')); + $manifest->expects('build') + ->throws(new RuntimeException('Package discovery failed.')); $application->instance(PackageManifest::class, $manifest); try { @@ -162,14 +164,14 @@ public function itDoesNotDeleteARealVendorDirectoryWhenLinkCreationFails(): void #[RequiresOperatingSystem('Linux')] public function itReportsADeletionFailureThroughTheNamedException(): void { - $application = m::mock(ApplicationContract::class); + $application = Double::for(ApplicationContract::class, override: true)->strict(); $vendorPath = '/proc/self/fd/0'; - $application->shouldReceive('basePath')->once()->with('vendor')->andReturn($vendorPath); + $application->expects('basePath')->with('vendor')->returns($vendorPath); $this->assertTrue(is_link($vendorPath)); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs("Unable to remove vendor symlink [{$vendorPath}]."); - (new DeleteVendorSymlink)->handle($application); + (new DeleteVendorSymlink)->handle($application->instance()); } #[Test] @@ -182,9 +184,9 @@ public function itDoesNotRebuildDiscoveryWhenTheManifestCannotBeDeleted(): void $filesystem->ensureDirectoryExists($cachedPath); $this->manifestDirectory = $cachedPath; - $manifest = m::mock(PackageManifest::class); + $manifest = Double::for(PackageManifest::class)->strict(); $manifest->manifestPath = $cachedPath; - $manifest->shouldNotReceive('build'); + $manifest->expects('build')->never(); $application->instance(PackageManifest::class, $manifest); $this->expectException(RuntimeException::class); diff --git a/tests/Testbench/Foundation/Bootstrap/LoadMigrationsFromArrayTest.php b/tests/Testbench/Foundation/Bootstrap/LoadMigrationsFromArrayTest.php index ab77e42b5c..752e03d92c 100644 --- a/tests/Testbench/Foundation/Bootstrap/LoadMigrationsFromArrayTest.php +++ b/tests/Testbench/Foundation/Bootstrap/LoadMigrationsFromArrayTest.php @@ -10,7 +10,8 @@ use Hypervel\Testbench\Foundation\Bootstrap\LoadMigrationsFromArray; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\Test; use RuntimeException; use Workbench\Database\Seeders\TestbenchDatabaseSeeder; @@ -20,15 +21,17 @@ class LoadMigrationsFromArrayTest extends TestCase { + use VerifiesDoubles; + #[Test] public function itCanRegisterMigrations(): void { - $this->instance('migrator', $migrator = m::mock(Migrator::class)); + $this->instance('migrator', $migrator = Double::for(Migrator::class)->strict()); $paths = [workbench_path('database/migrations')]; - $migrator->shouldReceive('path')->once()->with($paths[0])->andReturnNull() - ->shouldReceive('path')->once()->with(default_migration_path())->andReturnNull(); + $migrator->expects('path')->with($paths[0]); + $migrator->expects('path')->with(default_migration_path()); (new LoadMigrationsFromArray($paths))->bootstrap($this->app); } @@ -36,9 +39,9 @@ public function itCanRegisterMigrations(): void #[Test] public function itCanSkipMigrationsRegistration(): void { - $this->instance('migrator', $migrator = m::mock(Migrator::class)); + $this->instance('migrator', $migrator = Double::for(Migrator::class)->strict()); - $migrator->shouldReceive('path')->never(); + $migrator->expects('path')->never(); (new LoadMigrationsFromArray(false))->bootstrap($this->app); } @@ -50,11 +53,11 @@ public function itCanSeedDatabaseAfterRefreshed(): void 'seeders' => [TestbenchDatabaseSeeder::class], ]))->bootstrap($this->app); - $this->instance(TestbenchDatabaseSeeder::class, $seeder = m::mock(TestbenchDatabaseSeeder::class)); + $this->instance(TestbenchDatabaseSeeder::class, $seeder = Double::for(TestbenchDatabaseSeeder::class)->strict()); - $seeder->shouldReceive('setContainer')->once()->with($this->app)->andReturnSelf() - ->shouldReceive('setCommand')->once()->andReturnSelf() - ->shouldReceive('__invoke')->once()->andReturnNull(); + $seeder->expects('setContainer')->with($this->app)->returns($seeder); + $seeder->expects('setCommand')->returns($seeder); + $seeder->expects('__invoke'); app('events')->dispatch(new DatabaseRefreshed); } @@ -62,10 +65,10 @@ public function itCanSeedDatabaseAfterRefreshed(): void #[Test] public function itCanRunTheDefaultSeederAfterRefreshed(): void { - $kernel = m::mock(ConsoleKernel::class); + $kernel = Double::for(ConsoleKernel::class)->strict(); $this->app->instance(ConsoleKernel::class, $kernel); (new LoadMigrationsFromArray(false, true))->bootstrap($this->app); - $kernel->expects('call')->with('db:seed')->andReturn(0); + $kernel->expects('call')->with('db:seed')->returns(0); app('events')->dispatch(new DatabaseRefreshed); } @@ -95,10 +98,10 @@ public function itRejectsNonStringSeederConfiguration(): void #[Test] public function itFailsWhenTheDefaultSeederCommandFails(): void { - $kernel = m::mock(ConsoleKernel::class); + $kernel = Double::for(ConsoleKernel::class)->strict(); $this->app->instance(ConsoleKernel::class, $kernel); (new LoadMigrationsFromArray(false, true))->bootstrap($this->app); - $kernel->expects('call')->with('db:seed')->andReturn(1); + $kernel->expects('call')->with('db:seed')->returns(1); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Default seeder failed.'); @@ -109,12 +112,12 @@ public function itFailsWhenTheDefaultSeederCommandFails(): void #[Test] public function itFailsWhenAnExplicitSeederCommandFails(): void { - $kernel = m::mock(ConsoleKernel::class); + $kernel = Double::for(ConsoleKernel::class)->strict(); $this->app->instance(ConsoleKernel::class, $kernel); (new LoadMigrationsFromArray(false, TestbenchDatabaseSeeder::class))->bootstrap($this->app); $kernel->expects('call')->with('db:seed', [ '--class' => TestbenchDatabaseSeeder::class, - ])->andReturn(1); + ])->returns(1); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs(sprintf('Seeder [%s] failed.', TestbenchDatabaseSeeder::class)); @@ -125,12 +128,12 @@ public function itFailsWhenAnExplicitSeederCommandFails(): void #[Test] public function itCanSkipDatabaseSeedingAfterRefreshed(): void { - $kernel = m::mock(ConsoleKernel::class); + $kernel = Double::for(ConsoleKernel::class)->strict(); $this->app->instance(ConsoleKernel::class, $kernel); (new LoadMigrationsFromArray(false, false))->bootstrap($this->app); - $kernel->shouldNotReceive('call'); + $kernel->expects('call')->never(); app('events')->dispatch(new DatabaseRefreshed); } diff --git a/tests/Testbench/Foundation/Concerns/HandlesDatabaseConnectionsTest.php b/tests/Testbench/Foundation/Concerns/HandlesDatabaseConnectionsTest.php index aa9bbef012..7b7bfeac65 100644 --- a/tests/Testbench/Foundation/Concerns/HandlesDatabaseConnectionsTest.php +++ b/tests/Testbench/Foundation/Concerns/HandlesDatabaseConnectionsTest.php @@ -9,41 +9,45 @@ use Hypervel\Testbench\Foundation\Concerns\HandlesDatabaseConnections; use Hypervel\Testbench\PHPUnit\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; class HandlesDatabaseConnectionsTest extends TestCase { use HandlesDatabaseConnections; + use VerifiesDoubles; #[Test] public function itCanBuildMysqlConnection(): void { - $config = m::mock(Repository::class); + $config = Double::for(Repository::class)->strict(); $_ENV['MYSQL_URL'] = 'mysql://127.0.0.1:3306'; - $config->shouldNotReceive('get')->with('database.connections.mysql.url') - ->shouldReceive('get')->once()->with('database.connections.mysql.host')->andReturn('127.0.0.1') - ->shouldReceive('get')->once()->with('database.connections.mysql.port')->andReturn('3306') - ->shouldReceive('get')->once()->with('database.connections.mysql.database')->andReturn('hypervel') - ->shouldReceive('get')->once()->with('database.connections.mysql.username')->andReturn('root') - ->shouldReceive('get')->once()->with('database.connections.mysql.password')->andReturn('secret') - ->shouldReceive('get')->once()->with('database.connections.mysql.collation')->andReturn('utf8mb4_0900_ai_ci') - ->shouldReceive('set')->once()->with([ - 'database.connections.mysql.url' => 'mysql://127.0.0.1:3306', - 'database.connections.mysql.host' => '127.0.0.1', - 'database.connections.mysql.port' => '3306', - 'database.connections.mysql.database' => 'hypervel', - 'database.connections.mysql.username' => 'root', - 'database.connections.mysql.password' => 'secret', - 'database.connections.mysql.collation' => 'utf8mb4_0900_ai_ci', - ]); - - $this->usesDatabaseConnectionsEnvironmentVariables($config, 'mysql', 'MYSQL'); - - unset($_ENV['MYSQL_URL']); + $config->expects('get')->never()->with('database.connections.mysql.url'); + $config->expects('get')->with('database.connections.mysql.host')->returns('127.0.0.1'); + $config->expects('get')->with('database.connections.mysql.port')->returns('3306'); + $config->expects('get')->with('database.connections.mysql.database')->returns('hypervel'); + $config->expects('get')->with('database.connections.mysql.username')->returns('root'); + $config->expects('get')->with('database.connections.mysql.password')->returns('secret'); + $config->expects('get')->with('database.connections.mysql.collation')->returns('utf8mb4_0900_ai_ci'); + $config->expects('set')->with([ + 'database.connections.mysql.url' => 'mysql://127.0.0.1:3306', + 'database.connections.mysql.host' => '127.0.0.1', + 'database.connections.mysql.port' => '3306', + 'database.connections.mysql.database' => 'hypervel', + 'database.connections.mysql.username' => 'root', + 'database.connections.mysql.password' => 'secret', + 'database.connections.mysql.collation' => 'utf8mb4_0900_ai_ci', + ]); + + try { + $this->usesDatabaseConnectionsEnvironmentVariables($config, 'mysql', 'MYSQL'); + } finally { + unset($_ENV['MYSQL_URL']); + } } #[DataProvider('validPorts')] diff --git a/tests/Testbench/Foundation/Console/Actions/DeleteDirectoriesTest.php b/tests/Testbench/Foundation/Console/Actions/DeleteDirectoriesTest.php index c10fbd9d39..772fee8eb8 100644 --- a/tests/Testbench/Foundation/Console/Actions/DeleteDirectoriesTest.php +++ b/tests/Testbench/Foundation/Console/Actions/DeleteDirectoriesTest.php @@ -4,18 +4,21 @@ namespace Hypervel\Tests\Testbench\Foundation\Console\Actions; -use Hypervel\Console\View\Components\Factory as ComponentsFactory; use Hypervel\Filesystem\Filesystem; use Hypervel\Testbench\Foundation\Console\Actions\DeleteDirectories; use Hypervel\Testing\ParallelTesting; +use Hypervel\Tests\Console\Fixtures\ComponentsFactory; use Hypervel\Tests\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\RequiresOperatingSystem; use PHPUnit\Framework\Attributes\Test; use RuntimeException; class DeleteDirectoriesTest extends TestCase { + use VerifiesDoubles; + protected string $tempDir; protected function setUp(): void @@ -38,19 +41,19 @@ protected function tearDown(): void #[Test] public function itCanDeleteDirectories(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); - $filesystem->shouldReceive('isDirectory')->once()->with('a')->andReturnTrue() - ->shouldReceive('deleteDirectory')->once()->with('a')->andReturnTrue() - ->shouldReceive('isDirectory')->once()->with('b')->andReturnFalse() - ->shouldReceive('deleteDirectory')->never()->with('b') - ->shouldReceive('isDirectory')->once()->with('c/d')->andReturnTrue() - ->shouldReceive('deleteDirectory')->once()->with('c/d')->andReturnTrue(); + $filesystem->expects('isDirectory')->with('a')->returns(true); + $filesystem->expects('deleteDirectory')->with('a')->returns(true); + $filesystem->expects('isDirectory')->with('b')->returns(false); + $filesystem->expects('deleteDirectory')->never()->with('b'); + $filesystem->expects('isDirectory')->with('c/d')->returns(true); + $filesystem->expects('deleteDirectory')->with('c/d')->returns(true); - $components->shouldReceive('task')->once()->with('Directory [a] has been deleted')->andReturnNull() - ->shouldReceive('twoColumnDetail')->once()->with('Directory [b] doesn\'t exist', 'SKIPPED')->andReturnNull() - ->shouldReceive('task')->once()->with('Directory [c/d] has been deleted')->andReturnNull(); + $components->expects('task')->with('Directory [a] has been deleted'); + $components->expects('twoColumnDetail')->with('Directory [b] doesn\'t exist', 'SKIPPED'); + $components->expects('task')->with('Directory [c/d] has been deleted'); (new DeleteDirectories( filesystem: $filesystem, @@ -61,15 +64,15 @@ public function itCanDeleteDirectories(): void #[Test] public function itCanPretendToDeleteDirectories(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); - $filesystem->shouldReceive('isDirectory')->once()->with('a')->andReturnTrue() - ->shouldReceive('isDirectory')->once()->with('b')->andReturnFalse() - ->shouldReceive('deleteDirectory')->never(); + $filesystem->expects('isDirectory')->with('a')->returns(true); + $filesystem->expects('isDirectory')->with('b')->returns(false); + $filesystem->expects('deleteDirectory')->never(); - $components->shouldReceive('task')->once()->with('Directory [a] would be deleted')->andReturnNull() - ->shouldReceive('twoColumnDetail')->once()->with('Directory [b] doesn\'t exist', 'SKIPPED')->andReturnNull(); + $components->expects('task')->with('Directory [a] would be deleted'); + $components->expects('twoColumnDetail')->with('Directory [b] doesn\'t exist', 'SKIPPED'); (new DeleteDirectories( filesystem: $filesystem, @@ -81,13 +84,13 @@ public function itCanPretendToDeleteDirectories(): void #[Test] public function itAttemptsEveryDirectoryBeforeReportingDeletionFailures(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); - $filesystem->expects('isDirectory')->with('a')->andReturnTrue(); - $filesystem->expects('deleteDirectory')->with('a')->andReturnFalse(); - $filesystem->expects('isDirectory')->with('b')->andReturnTrue(); - $filesystem->expects('deleteDirectory')->with('b')->andReturnTrue(); - $components->shouldNotReceive('task')->with('Directory [a] has been deleted'); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); + $filesystem->expects('isDirectory')->with('a')->returns(true); + $filesystem->expects('deleteDirectory')->with('a')->returns(false); + $filesystem->expects('isDirectory')->with('b')->returns(true); + $filesystem->expects('deleteDirectory')->with('b')->returns(true); + $components->expects('task')->never()->with('Directory [a] has been deleted'); $components->expects('task')->with('Directory [b] has been deleted'); $this->expectException(RuntimeException::class); diff --git a/tests/Testbench/Foundation/Console/Actions/DeleteFilesTest.php b/tests/Testbench/Foundation/Console/Actions/DeleteFilesTest.php index acf6d32505..967550f0a4 100644 --- a/tests/Testbench/Foundation/Console/Actions/DeleteFilesTest.php +++ b/tests/Testbench/Foundation/Console/Actions/DeleteFilesTest.php @@ -4,18 +4,21 @@ namespace Hypervel\Tests\Testbench\Foundation\Console\Actions; -use Hypervel\Console\View\Components\Factory as ComponentsFactory; use Hypervel\Filesystem\Filesystem; use Hypervel\Testbench\Foundation\Console\Actions\DeleteFiles; use Hypervel\Testing\ParallelTesting; +use Hypervel\Tests\Console\Fixtures\ComponentsFactory; use Hypervel\Tests\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\RequiresOperatingSystem; use PHPUnit\Framework\Attributes\Test; use RuntimeException; class DeleteFilesTest extends TestCase { + use VerifiesDoubles; + protected string $tempDir; protected function setUp(): void @@ -38,20 +41,20 @@ protected function tearDown(): void #[Test] public function itCanDeleteFiles(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); - $filesystem->shouldReceive('isFile')->once()->with('a')->andReturnTrue() - ->shouldReceive('delete')->once()->with('a')->andReturnTrue() - ->shouldReceive('isFile')->once()->with('b')->andReturnFalse() - ->shouldReceive('isDirectory')->once()->with('b')->andReturnFalse() - ->shouldReceive('delete')->never()->with('b') - ->shouldReceive('isFile')->once()->with('c/d')->andReturnTrue() - ->shouldReceive('delete')->once()->with('c/d')->andReturnTrue(); + $filesystem->expects('isFile')->with('a')->returns(true); + $filesystem->expects('delete')->with('a')->returns(true); + $filesystem->expects('isFile')->with('b')->returns(false); + $filesystem->expects('isDirectory')->with('b')->returns(false); + $filesystem->expects('delete')->never()->with('b'); + $filesystem->expects('isFile')->with('c/d')->returns(true); + $filesystem->expects('delete')->with('c/d')->returns(true); - $components->shouldReceive('task')->once()->with('File [a] has been deleted')->andReturnNull() - ->shouldReceive('twoColumnDetail')->once()->with('File [b] doesn\'t exist', 'SKIPPED')->andReturnNull() - ->shouldReceive('task')->once()->with('File [c/d] has been deleted')->andReturnNull(); + $components->expects('task')->with('File [a] has been deleted'); + $components->expects('twoColumnDetail')->with('File [b] doesn\'t exist', 'SKIPPED'); + $components->expects('task')->with('File [c/d] has been deleted'); (new DeleteFiles( filesystem: $filesystem, @@ -62,16 +65,16 @@ public function itCanDeleteFiles(): void #[Test] public function itCanPretendToDeleteFiles(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); - $filesystem->shouldReceive('isFile')->once()->with('a')->andReturnTrue() - ->shouldReceive('isFile')->once()->with('b')->andReturnFalse() - ->shouldReceive('isDirectory')->once()->with('b')->andReturnFalse() - ->shouldReceive('delete')->never(); + $filesystem->expects('isFile')->with('a')->returns(true); + $filesystem->expects('isFile')->with('b')->returns(false); + $filesystem->expects('isDirectory')->with('b')->returns(false); + $filesystem->expects('delete')->never(); - $components->shouldReceive('task')->once()->with('File [a] would be deleted')->andReturnNull() - ->shouldReceive('twoColumnDetail')->once()->with('File [b] doesn\'t exist', 'SKIPPED')->andReturnNull(); + $components->expects('task')->with('File [a] would be deleted'); + $components->expects('twoColumnDetail')->with('File [b] doesn\'t exist', 'SKIPPED'); (new DeleteFiles( filesystem: $filesystem, @@ -83,13 +86,13 @@ public function itCanPretendToDeleteFiles(): void #[Test] public function itAttemptsEveryFileBeforeReportingDeletionFailures(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); - $filesystem->expects('isFile')->with('a')->andReturnTrue(); - $filesystem->expects('delete')->with('a')->andReturnFalse(); - $filesystem->expects('isFile')->with('b')->andReturnTrue(); - $filesystem->expects('delete')->with('b')->andReturnTrue(); - $components->shouldNotReceive('task')->with('File [a] has been deleted'); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); + $filesystem->expects('isFile')->with('a')->returns(true); + $filesystem->expects('delete')->with('a')->returns(false); + $filesystem->expects('isFile')->with('b')->returns(true); + $filesystem->expects('delete')->with('b')->returns(true); + $components->expects('task')->never()->with('File [a] has been deleted'); $components->expects('task')->with('File [b] has been deleted'); $this->expectException(RuntimeException::class); @@ -104,13 +107,13 @@ public function itAttemptsEveryFileBeforeReportingDeletionFailures(): void #[Test] public function itSkipsRealDirectoriesAndContinuesDeletingFiles(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); - $filesystem->expects('isFile')->with('directory')->andReturnFalse(); - $filesystem->expects('isDirectory')->with('directory')->andReturnTrue(); - $filesystem->shouldNotReceive('delete')->with('directory'); - $filesystem->expects('isFile')->with('file')->andReturnTrue(); - $filesystem->expects('delete')->with('file')->andReturnTrue(); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); + $filesystem->expects('isFile')->with('directory')->returns(false); + $filesystem->expects('isDirectory')->with('directory')->returns(true); + $filesystem->expects('delete')->never()->with('directory'); + $filesystem->expects('isFile')->with('file')->returns(true); + $filesystem->expects('delete')->with('file')->returns(true); $components->expects('twoColumnDetail') ->with('[directory] is a directory', 'SKIPPED'); $components->expects('task')->with('File [file] has been deleted'); diff --git a/tests/Testbench/Foundation/Console/Actions/EnsureDirectoryExistsTest.php b/tests/Testbench/Foundation/Console/Actions/EnsureDirectoryExistsTest.php index 31736808cb..bc10d3c7ef 100644 --- a/tests/Testbench/Foundation/Console/Actions/EnsureDirectoryExistsTest.php +++ b/tests/Testbench/Foundation/Console/Actions/EnsureDirectoryExistsTest.php @@ -4,11 +4,13 @@ namespace Hypervel\Tests\Testbench\Foundation\Console\Actions; -use Hypervel\Console\View\Components\Factory as ComponentsFactory; use Hypervel\Filesystem\Filesystem; use Hypervel\Testbench\Foundation\Console\Actions\EnsureDirectoryExists; +use Hypervel\Tests\Console\Fixtures\ComponentsFactory; use Hypervel\Tests\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\Test; use RuntimeException; @@ -16,25 +18,27 @@ class EnsureDirectoryExistsTest extends TestCase { + use VerifiesDoubles; + #[Test] public function itCanEnsureDirectoryExists(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); - - $filesystem->shouldReceive('isDirectory')->once()->with('a')->andReturnFalse() - ->shouldReceive('ensureDirectoryExists')->once()->with('a', 493, true)->andReturnNull() - ->shouldReceive('copy')->once()->with(m::type('string'), join_paths('a', '.gitkeep'))->andReturnTrue() - ->shouldReceive('isDirectory')->once()->with('b')->andReturnTrue() - ->shouldReceive('ensureDirectoryExists')->never()->with('b', 493, true) - ->shouldReceive('copy')->never()->with(m::type('string'), join_paths('b', '.gitkeep')) - ->shouldReceive('isDirectory')->once()->with(join_paths('c', 'd'))->andReturnFalse() - ->shouldReceive('ensureDirectoryExists')->once()->with(join_paths('c', 'd'), 493, true)->andReturnNull() - ->shouldReceive('copy')->once()->with(m::type('string'), join_paths('c', 'd', '.gitkeep'))->andReturnTrue(); - - $components->shouldReceive('task')->once()->with('Prepare [a] directory')->andReturnNull() - ->shouldReceive('twoColumnDetail')->once()->with('Directory [b] already exists', 'SKIPPED')->andReturnNull() - ->shouldReceive('task')->once()->with(sprintf('Prepare [%s] directory', join_paths('c', 'd')))->andReturnNull(); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); + + $filesystem->expects('isDirectory')->with('a')->returns(false); + $filesystem->expects('ensureDirectoryExists')->with('a', 493, true); + $filesystem->expects('copy')->with(Argument::type('string'), join_paths('a', '.gitkeep'))->returns(true); + $filesystem->expects('isDirectory')->with('b')->returns(true); + $filesystem->expects('ensureDirectoryExists')->never()->with('b', 493, true); + $filesystem->expects('copy')->never()->with(Argument::type('string'), join_paths('b', '.gitkeep')); + $filesystem->expects('isDirectory')->with(join_paths('c', 'd'))->returns(false); + $filesystem->expects('ensureDirectoryExists')->with(join_paths('c', 'd'), 493, true); + $filesystem->expects('copy')->with(Argument::type('string'), join_paths('c', 'd', '.gitkeep'))->returns(true); + + $components->expects('task')->with('Prepare [a] directory'); + $components->expects('twoColumnDetail')->with('Directory [b] already exists', 'SKIPPED'); + $components->expects('task')->with(sprintf('Prepare [%s] directory', join_paths('c', 'd'))); (new EnsureDirectoryExists( filesystem: $filesystem, @@ -45,16 +49,16 @@ public function itCanEnsureDirectoryExists(): void #[Test] public function itCanPretendToEnsureDirectoryExists(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); - $filesystem->shouldReceive('isDirectory')->once()->with('a')->andReturnFalse() - ->shouldReceive('isDirectory')->once()->with('b')->andReturnTrue() - ->shouldReceive('ensureDirectoryExists')->never() - ->shouldReceive('copy')->never(); + $filesystem->expects('isDirectory')->with('a')->returns(false); + $filesystem->expects('isDirectory')->with('b')->returns(true); + $filesystem->expects('ensureDirectoryExists')->never(); + $filesystem->expects('copy')->never(); - $components->shouldReceive('task')->once()->with('Prepare [a] directory')->andReturnNull() - ->shouldReceive('twoColumnDetail')->once()->with('Directory [b] already exists', 'SKIPPED')->andReturnNull(); + $components->expects('task')->with('Prepare [a] directory'); + $components->expects('twoColumnDetail')->with('Directory [b] already exists', 'SKIPPED'); (new EnsureDirectoryExists( filesystem: $filesystem, @@ -66,14 +70,14 @@ public function itCanPretendToEnsureDirectoryExists(): void #[Test] public function itFailsWhenThePlaceholderCannotBeCopied(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); - $filesystem->expects('isDirectory')->with('a')->andReturnFalse(); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); + $filesystem->expects('isDirectory')->with('a')->returns(false); $filesystem->expects('ensureDirectoryExists')->with('a', 493, true); $filesystem->expects('copy') - ->with(m::type('string'), join_paths('a', '.gitkeep')) - ->andReturnFalse(); - $components->shouldNotReceive('task'); + ->with(Argument::type('string'), join_paths('a', '.gitkeep')) + ->returns(false); + $components->expects('task')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to create placeholder file [a/.gitkeep].'); diff --git a/tests/Testbench/Foundation/Console/Actions/GeneratesFileTest.php b/tests/Testbench/Foundation/Console/Actions/GeneratesFileTest.php index 1968bf99f7..4f8c497cee 100644 --- a/tests/Testbench/Foundation/Console/Actions/GeneratesFileTest.php +++ b/tests/Testbench/Foundation/Console/Actions/GeneratesFileTest.php @@ -4,11 +4,12 @@ namespace Hypervel\Tests\Testbench\Foundation\Console\Actions; -use Hypervel\Console\View\Components\Factory as ComponentsFactory; use Hypervel\Filesystem\Filesystem; use Hypervel\Testbench\Foundation\Console\Actions\GeneratesFile; +use Hypervel\Tests\Console\Fixtures\ComponentsFactory; use Hypervel\Tests\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\Test; use RuntimeException; @@ -16,19 +17,21 @@ class GeneratesFileTest extends TestCase { + use VerifiesDoubles; + #[Test] public function itCanGeneratesFile(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); - $filesystem->shouldReceive('exists')->once()->with('a')->andReturnTrue() - ->shouldReceive('exists')->once()->with('b')->andReturnFalse() - ->shouldReceive('copy')->once()->with('a', 'b')->andReturnTrue() - ->shouldReceive('exists')->once()->with(join_paths('.', '.gitkeep'))->andReturnTrue() - ->shouldReceive('delete')->once()->with(join_paths('.', '.gitkeep')); + $filesystem->expects('exists')->with('a')->returns(true); + $filesystem->expects('exists')->with('b')->returns(false); + $filesystem->expects('copy')->with('a', 'b')->returns(true); + $filesystem->expects('exists')->with(join_paths('.', '.gitkeep'))->returns(true); + $filesystem->expects('delete')->with(join_paths('.', '.gitkeep')); - $components->shouldReceive('task')->once()->with('File [b] generated'); + $components->expects('task')->with('File [b] generated'); (new GeneratesFile( filesystem: $filesystem, @@ -39,14 +42,14 @@ public function itCanGeneratesFile(): void #[Test] public function itCannotGeneratesFileWhenFileAlreadyGenerated(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); - $filesystem->shouldReceive('exists')->once()->with('a')->andReturnTrue() - ->shouldReceive('exists')->once()->with('b')->andReturnTrue() - ->shouldReceive('copy')->never()->with('a', 'b'); + $filesystem->expects('exists')->with('a')->returns(true); + $filesystem->expects('exists')->with('b')->returns(true); + $filesystem->expects('copy')->never()->with('a', 'b'); - $components->shouldReceive('twoColumnDetail')->once()->with('File [b] already exists', 'SKIPPED'); + $components->expects('twoColumnDetail')->with('File [b] already exists', 'SKIPPED'); (new GeneratesFile( filesystem: $filesystem, @@ -58,16 +61,16 @@ public function itCannotGeneratesFileWhenFileAlreadyGenerated(): void #[Test] public function itCanGeneratesFileWhenFileAlreadyGeneratedUsingForce(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); - $filesystem->shouldReceive('exists')->once()->with('a')->andReturnTrue() - ->shouldReceive('exists')->never()->with('b') - ->shouldReceive('copy')->once()->with('a', 'b')->andReturnTrue() - ->shouldReceive('exists')->once()->with(join_paths('.', '.gitkeep'))->andReturnTrue() - ->shouldReceive('delete')->once()->with(join_paths('.', '.gitkeep')); + $filesystem->expects('exists')->with('a')->returns(true); + $filesystem->expects('exists')->never()->with('b'); + $filesystem->expects('copy')->with('a', 'b')->returns(true); + $filesystem->expects('exists')->with(join_paths('.', '.gitkeep'))->returns(true); + $filesystem->expects('delete')->with(join_paths('.', '.gitkeep')); - $components->shouldReceive('task')->once()->with('File [b] generated'); + $components->expects('task')->with('File [b] generated'); (new GeneratesFile( filesystem: $filesystem, @@ -79,15 +82,15 @@ public function itCanGeneratesFileWhenFileAlreadyGeneratedUsingForce(): void #[Test] public function itCanPretendToGenerateFile(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); - $filesystem->shouldReceive('exists')->once()->with('a')->andReturnTrue() - ->shouldReceive('exists')->once()->with('b')->andReturnFalse() - ->shouldReceive('copy')->never() - ->shouldReceive('delete')->never(); + $filesystem->expects('exists')->with('a')->returns(true); + $filesystem->expects('exists')->with('b')->returns(false); + $filesystem->expects('copy')->never(); + $filesystem->expects('delete')->never(); - $components->shouldReceive('task')->once()->with('File [b] would be generated'); + $components->expects('task')->with('File [b] would be generated'); (new GeneratesFile( filesystem: $filesystem, @@ -99,14 +102,14 @@ public function itCanPretendToGenerateFile(): void #[Test] public function itCannotGeneratesFileWhenSourceFileDoesNotExists(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); - $filesystem->shouldReceive('exists')->once()->with('a')->andReturnFalse() - ->shouldReceive('exists')->never()->with('b') - ->shouldReceive('copy')->never()->with('a', 'b'); + $filesystem->expects('exists')->with('a')->returns(false); + $filesystem->expects('exists')->never()->with('b'); + $filesystem->expects('copy')->never()->with('a', 'b'); - $components->shouldReceive('twoColumnDetail')->once()->with('Source file [a] doesn\'t exist', 'SKIPPED'); + $components->expects('twoColumnDetail')->with('Source file [a] doesn\'t exist', 'SKIPPED'); (new GeneratesFile( filesystem: $filesystem, @@ -118,13 +121,13 @@ public function itCannotGeneratesFileWhenSourceFileDoesNotExists(): void #[Test] public function itDoesNotReportSuccessOrDeleteThePlaceholderWhenCopyingFails(): void { - $filesystem = m::mock(Filesystem::class); - $components = m::mock(ComponentsFactory::class); - $filesystem->expects('exists')->with('a')->andReturnTrue(); - $filesystem->expects('exists')->with('b')->andReturnFalse(); - $filesystem->expects('copy')->with('a', 'b')->andReturnFalse(); - $filesystem->shouldNotReceive('delete'); - $components->shouldNotReceive('task'); + $filesystem = Double::for(Filesystem::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); + $filesystem->expects('exists')->with('a')->returns(true); + $filesystem->expects('exists')->with('b')->returns(false); + $filesystem->expects('copy')->with('a', 'b')->returns(false); + $filesystem->expects('delete')->never(); + $components->expects('task')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to generate file [b].'); diff --git a/tests/Testbench/Foundation/Console/Actions/RunCommandTest.php b/tests/Testbench/Foundation/Console/Actions/RunCommandTest.php index 8cce0b8e1a..c2edd63f1c 100644 --- a/tests/Testbench/Foundation/Console/Actions/RunCommandTest.php +++ b/tests/Testbench/Foundation/Console/Actions/RunCommandTest.php @@ -5,23 +5,26 @@ namespace Hypervel\Tests\Testbench\Foundation\Console\Actions; use Hypervel\Console\Command; -use Hypervel\Console\View\Components\Factory as ComponentsFactory; use Hypervel\Testbench\Foundation\Console\Actions\RunCommand; +use Hypervel\Tests\Console\Fixtures\ComponentsFactory; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\Test; use RuntimeException; class RunCommandTest extends TestCase { + use VerifiesDoubles; + #[Test] public function itCanRunCommand(): void { - $console = m::mock(Command::class); - $components = m::mock(ComponentsFactory::class); + $console = Double::for(Command::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); - $console->shouldReceive('call')->once()->with('config:clear', ['--force' => true])->andReturn(Command::SUCCESS); - $components->shouldReceive('task')->never(); + $console->expects('call')->with('config:clear', ['--force' => true])->returns(Command::SUCCESS); + $components->expects('task')->never(); (new RunCommand( console: $console, @@ -32,11 +35,11 @@ public function itCanRunCommand(): void #[Test] public function itCanPretendToRunCommand(): void { - $console = m::mock(Command::class); - $components = m::mock(ComponentsFactory::class); + $console = Double::for(Command::class)->strict(); + $components = Double::for(ComponentsFactory::class)->strict(); - $console->shouldReceive('call')->never(); - $components->shouldReceive('task')->once()->with('Command [config:clear] would be executed')->andReturnNull(); + $console->expects('call')->never(); + $components->expects('task')->with('Command [config:clear] would be executed'); (new RunCommand( console: $console, @@ -48,9 +51,9 @@ public function itCanPretendToRunCommand(): void #[Test] public function itFailsWhenTheCommandFails(): void { - $console = m::mock(Command::class); + $console = Double::for(Command::class)->strict(); - $console->shouldReceive('call')->once()->with('config:clear', [])->andReturn(Command::FAILURE); + $console->expects('call')->with('config:clear', [])->returns(Command::FAILURE); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to run command [config:clear].'); diff --git a/tests/Testbench/Foundation/Console/InstallCommandTest.php b/tests/Testbench/Foundation/Console/InstallCommandTest.php index 4e1bd1bbef..470f60ee21 100644 --- a/tests/Testbench/Foundation/Console/InstallCommandTest.php +++ b/tests/Testbench/Foundation/Console/InstallCommandTest.php @@ -13,8 +13,11 @@ use Hypervel\Testbench\Foundation\Config; use Hypervel\Testbench\Foundation\Console\InstallCommand; use Hypervel\Testing\ParallelTesting; +use Hypervel\Tests\Console\Fixtures\ComponentsFactory; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Override; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RequiresOperatingSystem; @@ -30,6 +33,8 @@ #[RequiresOperatingSystem('Linux|Darwin')] class InstallCommandTest extends TestCase { + use VerifiesDoubles; + private Filesystem $filesystem; private string $workingPath; @@ -268,7 +273,7 @@ public function itCanSkipExportingTheWorkbenchEnvironmentFile(): void $this->runInstallCommandStep( 'copyWorkbenchDotEnvFile', [], - fn (Factory $components) => $components + fn (ComponentsFactory&DoubleInterface $components) => $components ->expects('choice') ->with("Export '.env' file as?", [ 'skip' => 'Skip exporting .env', @@ -276,7 +281,7 @@ public function itCanSkipExportingTheWorkbenchEnvironmentFile(): void '.env.example' => '.env.example', '.env.dist' => '.env.dist', ], null) - ->andReturn('skip') + ->returns('skip') ); $this->assertFileDoesNotExist($this->path('workbench/.env')); @@ -292,7 +297,7 @@ public function itExportsTheSelectedWorkbenchEnvironmentFile(): void $this->runInstallCommandStep( 'copyWorkbenchDotEnvFile', [], - fn (Factory $components) => $components + fn (ComponentsFactory&DoubleInterface $components) => $components ->expects('choice') ->with("Export '.env' file as?", [ 'skip' => 'Skip exporting .env', @@ -300,7 +305,7 @@ public function itExportsTheSelectedWorkbenchEnvironmentFile(): void '.env.example' => '.env.example', '.env.dist' => '.env.dist', ], null) - ->andReturn('.env') + ->returns('.env') ); $this->assertSame('APP_NAME=Workbench', $this->filesystem->get($this->path('workbench/.env'))); @@ -314,7 +319,7 @@ public function itDoesNotExportTheWorkbenchEnvironmentFileWhenPretending(): void $this->runInstallCommandStep( 'copyWorkbenchDotEnvFile', ['--pretend' => true], - fn (Factory $components) => $components + fn (ComponentsFactory&DoubleInterface $components) => $components ->expects('choice') ->with("Export '.env' file as?", [ 'skip' => 'Skip exporting .env', @@ -322,7 +327,7 @@ public function itDoesNotExportTheWorkbenchEnvironmentFileWhenPretending(): void '.env.example' => '.env.example', '.env.dist' => '.env.dist', ], null) - ->andReturn('.env') + ->returns('.env') ); $this->assertFileDoesNotExist($this->path('workbench/.env')); @@ -340,7 +345,7 @@ public function itSkipsEnvironmentExportWhenEveryEnvironmentFileAlreadyExists(): $this->runInstallCommandStep( 'copyWorkbenchDotEnvFile', [], - fn (Factory $components) => $components + fn (ComponentsFactory&DoubleInterface $components) => $components ->expects('twoColumnDetail') ->with('File [.env] already exists', 'SKIPPED') ); @@ -360,7 +365,7 @@ public function itOffersExistingEnvironmentFilesWhenForced(): void $this->runInstallCommandStep( 'copyWorkbenchDotEnvFile', ['--force' => true], - fn (Factory $components) => $components + fn (ComponentsFactory&DoubleInterface $components) => $components ->expects('choice') ->with("Export '.env' file as?", [ 'skip' => 'Skip exporting .env', @@ -368,7 +373,7 @@ public function itOffersExistingEnvironmentFilesWhenForced(): void '.env.example' => '.env.example', '.env.dist' => '.env.dist', ], null) - ->andReturn('.env.dist') + ->returns('.env.dist') ); $this->assertSame('APP_NAME=Workbench', $this->filesystem->get($this->path('workbench/.env.dist'))); @@ -382,9 +387,9 @@ public function itGeneratesTheSelectedWorkbenchBootstrapFiles(): void $this->runInstallCommandStep( 'copyWorkbenchBootstrapFiles', [], - function (Factory $components): void { - $components->expects('confirm')->with('Generate `workbench/bootstrap/app.php` file?', true)->andReturn(true); - $components->expects('confirm')->with('Generate `workbench/bootstrap/providers.php` file?', false)->andReturn(true); + function (ComponentsFactory&DoubleInterface $components): void { + $components->expects('confirm')->with('Generate `workbench/bootstrap/app.php` file?', true)->returns(true); + $components->expects('confirm')->with('Generate `workbench/bootstrap/providers.php` file?', false)->returns(true); } ); @@ -406,9 +411,9 @@ public function itGeneratesABasicWorkbenchApplicationBootstrapThatBootsWithoutRo $this->runInstallCommandStep( 'copyWorkbenchBootstrapFiles', ['--basic' => true], - function (Factory $components): void { - $components->expects('confirm')->with('Generate `workbench/bootstrap/app.php` file?', true)->andReturn(true); - $components->expects('confirm')->with('Generate `workbench/bootstrap/providers.php` file?', false)->andReturn(false); + function (ComponentsFactory&DoubleInterface $components): void { + $components->expects('confirm')->with('Generate `workbench/bootstrap/app.php` file?', true)->returns(true); + $components->expects('confirm')->with('Generate `workbench/bootstrap/providers.php` file?', false)->returns(false); } ); @@ -483,9 +488,9 @@ public function itStopsWhenSqliteDatabaseCreationFails(): void { $command = new InstallCommandFailureHarness; $command->setInput(new ArrayInput([], $command->getDefinition())); - $composer = m::mock(Composer::class); - $composer->shouldNotReceive('setWorkingPath'); - $composer->shouldNotReceive('dumpAutoloads'); + $composer = Double::for(Composer::class)->strict(); + $composer->expects('setWorkingPath')->never(); + $composer->expects('dumpAutoloads')->never(); $this->assertSame(InstallCommand::FAILURE, $command->handle($this->filesystem, $composer)); $this->assertSame(['package:create-sqlite-db'], $command->calls); @@ -563,7 +568,7 @@ private function runInstallCommand(array $arguments = [], array $environment = [ * * @param 'copyWorkbenchBootstrapFiles'|'copyWorkbenchDotEnvFile' $step * @param array $input - * @param Closure(Factory): void $expectations + * @param Closure(ComponentsFactory&DoubleInterface): mixed $expectations */ private function runInstallCommandStep(string $step, array $input, Closure $expectations): void { @@ -587,23 +592,23 @@ public function handle(Filesystem $filesystem, Composer $composer): int } }; - $application = m::mock(Application::class); + $application = Double::for(Application::class, override: true)->strict(); $consoleInput = new ArrayInput($input); $output = new NullOutput; $outputStyle = new OutputStyle($consoleInput, $output); - $components = m::mock(Factory::class); + $components = Double::for(ComponentsFactory::class)->strict(); $this->filesystem->ensureDirectoryExists($this->path('workbench')); - $command->setHypervel($application); + $command->setHypervel($application->instance()); - $application->shouldReceive('make')->withArgs(fn (string $abstract): bool => $abstract === OutputStyle::class)->andReturn($outputStyle); - $application->shouldReceive('make')->withArgs(fn (string $abstract): bool => $abstract === Factory::class)->andReturn($components); - $application->shouldReceive('bound')->andReturn(false); - $application->shouldReceive('basePath')->with('.env.example')->andReturn($this->path('.env.example')); - $application->shouldReceive('runningUnitTests')->andReturn(true); - $application->shouldReceive('call')->with([$command, 'handle'])->andReturnUsing(fn (array $callback): int => $callback[0]->handle($this->filesystem, m::mock(Composer::class))); - $components->shouldReceive('task')->zeroOrMoreTimes(); + $application->allows('make')->with(OutputStyle::class, ['input' => $consoleInput, 'output' => $output])->returns($outputStyle); + $application->allows('make')->with(Factory::class, ['output' => $outputStyle])->returns($components); + $application->allows('bound')->returns(false); + $application->allows('basePath')->with('.env.example')->returns($this->path('.env.example')); + $application->allows('runningUnitTests')->returns(true); + $application->allows('call')->with([$command, 'handle'])->resolves(fn (array $callback): int => $callback[0]->handle($this->filesystem, Double::for(Composer::class)->strict())); + $components->allows('task'); $expectations($components); diff --git a/tests/Testbench/Foundation/Console/ServeCommandTest.php b/tests/Testbench/Foundation/Console/ServeCommandTest.php index 48437bd21e..f7545bb48b 100644 --- a/tests/Testbench/Foundation/Console/ServeCommandTest.php +++ b/tests/Testbench/Foundation/Console/ServeCommandTest.php @@ -21,7 +21,9 @@ use Hypervel\Testbench\Foundation\Events\ServeCommandEnded; use Hypervel\Testbench\Foundation\Events\ServeCommandStarted; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\Test; use RuntimeException; use Symfony\Component\Console\Input\ArrayInput; @@ -32,6 +34,8 @@ class ServeCommandTest extends TestCase { + use VerifiesDoubles; + private const array ENVIRONMENT_VARIABLES = ['TESTBENCH_WORKING_PATH', 'SERVER_HOST']; /** @var array */ @@ -100,11 +104,11 @@ public function itStartsTheUnderlyingServerCommandAndDispatchesLifecycleEvents() { $linkedWhileServing = false; - $serverFactory = m::mock(ServerFactory::class); - $serverFactory->shouldReceive('setEventDispatcher')->once()->andReturnSelf(); - $serverFactory->shouldReceive('setLogger')->once()->andReturnSelf(); - $serverFactory->shouldReceive('configure')->once(); - $serverFactory->shouldReceive('start')->once()->andReturnUsing(function () use (&$linkedWhileServing): void { + $serverFactory = Double::for(ServerFactory::class)->strict(); + $serverFactory->expects('setEventDispatcher')->returns($serverFactory); + $serverFactory->expects('setLogger')->returns($serverFactory); + $serverFactory->expects('configure'); + $serverFactory->expects('start')->resolves(function () use (&$linkedWhileServing): void { $linkedWhileServing = is_link($this->syncLinkPath()); }); @@ -151,11 +155,11 @@ class_exists(ComposerConfig::class); #[Test] public function passiveObserversDoNotCauseServeLifecycleEventsToDispatch(): void { - $serverFactory = m::mock(ServerFactory::class); - $serverFactory->shouldReceive('setEventDispatcher')->once()->andReturnSelf(); - $serverFactory->shouldReceive('setLogger')->once()->andReturnSelf(); - $serverFactory->shouldReceive('configure')->once(); - $serverFactory->shouldReceive('start')->once(); + $serverFactory = Double::for(ServerFactory::class)->strict(); + $serverFactory->expects('setEventDispatcher')->returns($serverFactory); + $serverFactory->expects('setLogger')->returns($serverFactory); + $serverFactory->expects('configure'); + $serverFactory->expects('start'); $this->bindServer($serverFactory); $this->app->instance(ConfigContract::class, new Config); @@ -230,11 +234,11 @@ public function itRemovesSyncLinksAndRethrowsWhenTheServerFailsToStart(): void $failure = new RuntimeException('Unable to bind the server.'); $linkedWhenFailing = false; - $serverFactory = m::mock(ServerFactory::class); - $serverFactory->shouldReceive('setEventDispatcher')->once()->andReturnSelf(); - $serverFactory->shouldReceive('setLogger')->once()->andReturnSelf(); - $serverFactory->shouldReceive('configure')->once(); - $serverFactory->shouldReceive('start')->once()->andReturnUsing(function () use ($failure, &$linkedWhenFailing): never { + $serverFactory = Double::for(ServerFactory::class)->strict(); + $serverFactory->expects('setEventDispatcher')->returns($serverFactory); + $serverFactory->expects('setLogger')->returns($serverFactory); + $serverFactory->expects('configure'); + $serverFactory->expects('start')->resolves(function () use ($failure, &$linkedWhenFailing): never { $linkedWhenFailing = is_link($this->syncLinkPath()); throw $failure; @@ -271,8 +275,8 @@ public function itRemovesCreatedSyncLinksWhenALaterSyncEntryFails(): void $this->filesystem->put($occupiedPath, 'existing'); $this->filesystem->put($this->backupPath($occupiedPath), 'existing backup'); - $serverFactory = m::mock(ServerFactory::class); - $serverFactory->shouldNotReceive('start'); + $serverFactory = Double::for(ServerFactory::class)->strict(); + $serverFactory->expects('start')->never(); $this->app->instance(ServerFactory::class, $serverFactory); $this->app->instance(ConfigContract::class, new Config([ @@ -313,8 +317,8 @@ public function itKeepsTheFirstFailureWhenEndingServeAlsoFails(): void { $startedFailure = new RuntimeException('Started listener failed.'); - $serverFactory = m::mock(ServerFactory::class); - $serverFactory->shouldNotReceive('start'); + $serverFactory = Double::for(ServerFactory::class)->strict(); + $serverFactory->expects('start')->never(); $this->app->instance(ServerFactory::class, $serverFactory); $this->app->instance(ConfigContract::class, $this->syncConfiguration()); @@ -344,16 +348,16 @@ public function itKeepsTheFirstFailureWhenEndingServeAlsoFails(): void */ private function bindServer(ServerFactory $serverFactory): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array')->once()->with('server')->andReturn([ + $config = Double::for(Repository::class)->strict(); + $config->expects('array')->with('server')->returns([ 'servers' => [ ['name' => 'http', 'type' => ServerInterface::SERVER_HTTP, 'host' => '0.0.0.0', 'port' => 9501], ], ]); - $config->shouldReceive('set')->once()->with('server.servers', m::type('array')); + $config->expects('set')->with('server.servers', Argument::type('array')); $this->app->instance(ServerFactory::class, $serverFactory); - $this->app->instance(StdoutLoggerInterface::class, m::mock(StdoutLoggerInterface::class)); + $this->app->instance(StdoutLoggerInterface::class, Double::for(StdoutLoggerInterface::class)->strict()); $this->app->instance('config', $config); } @@ -366,13 +370,13 @@ private function servedHost(array $input): string { $host = null; - $serverFactory = m::mock(ServerFactory::class); - $serverFactory->shouldReceive('setEventDispatcher')->once()->andReturnSelf(); - $serverFactory->shouldReceive('setLogger')->once()->andReturnSelf(); - $serverFactory->shouldReceive('configure')->once()->andReturnUsing(static function (array $config) use (&$host): void { + $serverFactory = Double::for(ServerFactory::class)->strict(); + $serverFactory->expects('setEventDispatcher')->returns($serverFactory); + $serverFactory->expects('setLogger')->returns($serverFactory); + $serverFactory->expects('configure')->resolves(static function (array $config) use (&$host): void { $host = $config['servers'][0]['host']; }); - $serverFactory->shouldReceive('start')->once(); + $serverFactory->expects('start'); $this->bindServer($serverFactory); $this->app->instance(ConfigContract::class, new Config); diff --git a/tests/Testbench/Foundation/Process/ProcessResultTest.php b/tests/Testbench/Foundation/Process/ProcessResultTest.php index 60395f6863..35a5a7676a 100644 --- a/tests/Testbench/Foundation/Process/ProcessResultTest.php +++ b/tests/Testbench/Foundation/Process/ProcessResultTest.php @@ -8,11 +8,14 @@ use Hypervel\Testbench\Foundation\Process\ProcessResult; use Hypervel\Tests\Concurrency\Fixtures\ConcurrentProcessExceptionFixtures; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Process\Process; class ProcessResultTest extends TestCase { + use VerifiesDoubles; + public function testItReturnsBinaryResultsLosslessly(): void { $result = $this->processResultFor([ @@ -55,8 +58,10 @@ public function testItPreservesPublicFalseyExceptionParameters(): void public function testItReturnsRawNonClosureOutputWithoutInterpretingGzipMarkers(): void { $output = "raw\x1f\x8boutput"; - $process = m::mock(Process::class); - $process->shouldReceive('getOutput')->once()->andReturn($output); + $process = Double::for(Process::class)->strict(); + // Symfony's destructor stops the process even when no child was started. + $process->allows('stop')->with(0.0); + $process->expects('getOutput')->returns($output); $result = new ProcessResult($process, ['php', '--version']); $this->assertSame($output, $result->output()); @@ -72,9 +77,11 @@ private function processResultFor(array $payload): ProcessResult $key = 'test-envelope-key'; $encoded = base64_encode(json_encode($payload, JSON_THROW_ON_ERROR)); $signature = hash_hmac('sha256', $encoded, $key); - $process = m::mock(Process::class); - $process->shouldReceive('getOutput')->once()->andReturn("\n@@HYPERVEL-CONCURRENCY-V1@@{$encoded}@@{$signature}@@\n"); - $process->shouldReceive('getEnv')->once()->andReturn(['HYPERVEL_CONCURRENCY_HMAC_KEY' => $key]); + $process = Double::for(Process::class)->strict(); + // Symfony's destructor stops the process even when no child was started. + $process->allows('stop')->with(0.0); + $process->expects('getOutput')->returns("\n@@HYPERVEL-CONCURRENCY-V1@@{$encoded}@@{$signature}@@\n"); + $process->expects('getEnv')->returns(['HYPERVEL_CONCURRENCY_HMAC_KEY' => $key]); return new ProcessResult($process, static fn (): null => null); } diff --git a/tests/Testing/Constraints/DatabaseConstraintsTest.php b/tests/Testing/Constraints/DatabaseConstraintsTest.php index 21a09d449b..5be31b521d 100644 --- a/tests/Testing/Constraints/DatabaseConstraintsTest.php +++ b/tests/Testing/Constraints/DatabaseConstraintsTest.php @@ -10,14 +10,17 @@ use Hypervel\Testing\Constraints\NotSoftDeletedInDatabase; use Hypervel\Testing\Constraints\SoftDeletedInDatabase; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\ExpectationFailedException; class DatabaseConstraintsTest extends TestCase { + use VerifiesDoubles; + public function testStringRepresentationsSubstituteInvalidUtf8(): void { - $database = m::mock(Connection::class); + $database = Double::for(Connection::class)->strict(); $invalidUtf8 = "\xB1"; $constraints = [ new HasInDatabase($database, ['value' => $invalidUtf8]), @@ -35,7 +38,7 @@ public function testStringRepresentationsSubstituteInvalidUtf8(): void public function testHasInDatabaseFailureDescriptionKeepsUnicodeReadable(): void { $constraint = new HasInDatabaseWithoutAdditionalInfo( - m::mock(Connection::class), + Double::for(Connection::class)->strict(), ['name' => '世界'], ); @@ -48,17 +51,17 @@ public function testHasInDatabaseFailureDescriptionKeepsUnicodeReadable(): void public function testHasInDatabaseAssertionFailureIncludesMalformedSimilarResults(): void { $invalidUtf8 = "\xB1"; - $builder = m::mock(Builder::class); - $builder->shouldReceive('where')->with(['name' => 'expected'])->once()->andReturnSelf(); - $builder->shouldReceive('exists')->once()->andReturnFalse(); - $builder->shouldReceive('where')->with('name', 'expected')->once()->andReturnSelf(); - $builder->shouldReceive('select')->with(['name'])->once()->andReturnSelf(); - $builder->shouldReceive('limit')->with(3)->once()->andReturnSelf(); - $builder->shouldReceive('get')->once()->andReturn(collect([['name' => $invalidUtf8]])); - $builder->shouldReceive('count')->once()->andReturn(1); - - $database = m::mock(Connection::class); - $database->shouldReceive('table')->with('users')->twice()->andReturn($builder); + $builder = Double::for(Builder::class)->strict(); + $builder->expects('where')->with(['name' => 'expected'])->returns($builder); + $builder->expects('exists')->returns(false); + $builder->expects('where')->with('name', 'expected')->returns($builder); + $builder->expects('select')->with(['name'])->returns($builder); + $builder->expects('limit')->with(3)->returns($builder); + $builder->expects('get')->returns(collect([['name' => $invalidUtf8]])); + $builder->expects('count')->returns(1); + + $database = Double::for(Connection::class)->strict(); + $database->expects('table')->with('users')->times(2)->returns($builder); $failure = null; @@ -76,20 +79,20 @@ public function testHasInDatabaseAssertionFailureIncludesMalformedSimilarResults public function testHasInDatabaseAdditionalInfoIncludesMalformedFallbackResults(): void { $invalidUtf8 = "\xB1"; - $similarBuilder = m::mock(Builder::class); - $similarBuilder->shouldReceive('where')->with('name', 'expected')->once()->andReturnSelf(); - $similarBuilder->shouldReceive('select')->with(['name'])->once()->andReturnSelf(); - $similarBuilder->shouldReceive('limit')->with(3)->once()->andReturnSelf(); - $similarBuilder->shouldReceive('get')->once()->andReturn(collect()); + $similarBuilder = Double::for(Builder::class)->strict(); + $similarBuilder->expects('where')->with('name', 'expected')->returns($similarBuilder); + $similarBuilder->expects('select')->with(['name'])->returns($similarBuilder); + $similarBuilder->expects('limit')->with(3)->returns($similarBuilder); + $similarBuilder->expects('get')->returns(collect()); - $fallbackBuilder = m::mock(Builder::class); - $fallbackBuilder->shouldReceive('select')->with(['name'])->once()->andReturnSelf(); - $fallbackBuilder->shouldReceive('limit')->with(3)->once()->andReturnSelf(); - $fallbackBuilder->shouldReceive('get')->once()->andReturn(collect([['name' => $invalidUtf8]])); - $fallbackBuilder->shouldReceive('count')->once()->andReturn(1); + $fallbackBuilder = Double::for(Builder::class)->strict(); + $fallbackBuilder->expects('select')->with(['name'])->returns($fallbackBuilder); + $fallbackBuilder->expects('limit')->with(3)->returns($fallbackBuilder); + $fallbackBuilder->expects('get')->returns(collect([['name' => $invalidUtf8]])); + $fallbackBuilder->expects('count')->returns(1); - $database = m::mock(Connection::class); - $database->shouldReceive('table')->with('users')->twice()->andReturn($similarBuilder, $fallbackBuilder); + $database = Double::for(Connection::class)->strict(); + $database->expects('table')->with('users')->times(2)->returns($similarBuilder, $fallbackBuilder); $constraint = new ExposedHasInDatabase($database, ['name' => 'expected']); $description = $constraint->additionalInfo('users'); @@ -101,13 +104,13 @@ public function testHasInDatabaseAdditionalInfoIncludesMalformedFallbackResults( public function testSoftDeleteAdditionalInfoSubstitutesMalformedResults(): void { foreach ([ExposedSoftDeletedInDatabase::class, ExposedNotSoftDeletedInDatabase::class] as $constraintClass) { - $builder = m::mock(Builder::class); - $builder->shouldReceive('limit')->with(3)->once()->andReturnSelf(); - $builder->shouldReceive('get')->once()->andReturn(collect([['name' => "\xB1"]])); - $builder->shouldReceive('count')->once()->andReturn(1); + $builder = Double::for(Builder::class)->strict(); + $builder->expects('limit')->with(3)->returns($builder); + $builder->expects('get')->returns(collect([['name' => "\xB1"]])); + $builder->expects('count')->returns(1); - $database = m::mock(Connection::class); - $database->shouldReceive('table')->with('users')->once()->andReturn($builder); + $database = Double::for(Connection::class)->strict(); + $database->expects('table')->with('users')->returns($builder); $constraint = new $constraintClass($database, ['name' => 'expected'], 'deleted_at'); @@ -117,7 +120,7 @@ public function testSoftDeleteAdditionalInfoSubstitutesMalformedResults(): void public function testStringRepresentationUsesPartialOutputForNonFiniteNumbers(): void { - $constraint = new HasInDatabase(m::mock(Connection::class), ['number' => INF]); + $constraint = new HasInDatabase(Double::for(Connection::class)->strict(), ['number' => INF]); $this->assertSame('{"number":0}', $constraint->toString()); } diff --git a/tests/Testing/PHPUnit/AfterEachTestSubscriberTest.php b/tests/Testing/PHPUnit/AfterEachTestSubscriberTest.php index bf03c53280..478f661056 100644 --- a/tests/Testing/PHPUnit/AfterEachTestSubscriberTest.php +++ b/tests/Testing/PHPUnit/AfterEachTestSubscriberTest.php @@ -48,6 +48,8 @@ use Hypervel\Testing\PHPUnit\AfterEachTestSubscriber; use Hypervel\Tests\TestCase; use Hypervel\Validation\ValidationData; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Laravel\SerializableClosure\SerializableClosure; use Laravel\SerializableClosure\Serializers\Native; use Laravel\SerializableClosure\Serializers\Signed; @@ -65,6 +67,8 @@ class AfterEachTestSubscriberTest extends TestCase { + use VerifiesDoubles; + private const string CALLBACK_NAME = self::class; #[Override] @@ -529,8 +533,8 @@ public function testTelescopeCleanupReleasesTheDumpHandler(): void DumpWatcher::flushState(); VarDumper::setHandler(static function (): void { }); - (new DumpWatcher(m::mock(CacheFactory::class), ['always' => true])) - ->register(m::mock(ApplicationContract::class)); + (new DumpWatcher(Double::for(CacheFactory::class)->strict(), ['always' => true])) + ->register(Double::for(ApplicationContract::class, override: true)->strict()->instance()); $handler = new ReflectionProperty(VarDumper::class, 'handler'); $this->assertNotNull($handler->getValue()); diff --git a/tests/Testing/TestViewTest.php b/tests/Testing/TestViewTest.php index 5e110e4838..b1ec64c924 100644 --- a/tests/Testing/TestViewTest.php +++ b/tests/Testing/TestViewTest.php @@ -12,12 +12,15 @@ use Hypervel\Tests\TestCase; use Hypervel\View\Component; use Hypervel\View\View; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\Attributes\DataProvider; class TestViewTest extends TestCase { + use VerifiesDoubles; + public function testViewDataAssertionsSupportKeysValuesClosuresAndLists(): void { $view = $this->makeTestView([ @@ -192,11 +195,12 @@ public function testAssertViewEmptyRejectsRenderedContent(): void public function testRenderedComponentAssertionsSupportArraysHtmlAndNormalizedText(): void { + $view = Double::for(View::class)->strict(); + $view->allows('render')->returns('

Hello World

0
'); + $component = new TestComponent( new TestViewComponent, - m::mock(View::class, [ - 'render' => '

Hello World

0
', - ]), + $view, ); $component @@ -224,10 +228,11 @@ public function testRenderedViewTextRetainsMalformedUtf8Matching(): void */ private function makeTestView(array $data, string $rendered = 'hello world'): TestView { - return new TestView(m::mock(View::class, [ - 'render' => $rendered, - 'gatherData' => $data, - ])); + $view = Double::for(View::class)->strict(); + $view->allows('render')->returns($rendered); + $view->allows('gatherData')->returns($data); + + return new TestView($view); } } diff --git a/tests/Tinker/TinkerCasterTest.php b/tests/Tinker/TinkerCasterTest.php index f234497b95..2728eee95c 100644 --- a/tests/Tinker/TinkerCasterTest.php +++ b/tests/Tinker/TinkerCasterTest.php @@ -10,11 +10,14 @@ use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; use Hypervel\Tinker\TinkerCaster; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\VarDumper\Caster\Caster; class TinkerCasterTest extends TestCase { + use VerifiesDoubles; + public function testCanCastCollection(): void { $result = TinkerCaster::castCollection(new Collection(['foo', 'bar'])); @@ -24,11 +27,11 @@ public function testCanCastCollection(): void public function testApplicationPropertyErrorsDoNotSuppressLaterValues(): void { - $application = m::mock(Application::class); - $application->shouldReceive('configurationIsCached')->once()->andThrow(new Error('Unavailable')); - $application->shouldReceive('version')->once()->andReturn('1.0.0'); + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('configurationIsCached')->throws(new Error('Unavailable')); + $application->expects('version')->returns('1.0.0'); - $result = TinkerCaster::castApplication($application); + $result = TinkerCaster::castApplication($application->instance()); $this->assertSame('1.0.0', $result[Caster::PREFIX_VIRTUAL . 'version']); } diff --git a/tests/Validation/ValidationBatchDatabaseCheckerTest.php b/tests/Validation/ValidationBatchDatabaseCheckerTest.php index 85884a9518..aff2cf8c0f 100644 --- a/tests/Validation/ValidationBatchDatabaseCheckerTest.php +++ b/tests/Validation/ValidationBatchDatabaseCheckerTest.php @@ -12,13 +12,17 @@ use Hypervel\Validation\DatabasePresenceVerifier; use Hypervel\Validation\PrecomputedPresenceVerifier; use Hypervel\Validation\PresenceQuery; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use stdClass; use Stringable; class ValidationBatchDatabaseCheckerTest extends TestCase { + use VerifiesDoubles; + public function testUsesTheCompleteQueryShapeAndRetainsCandidateValues(): void { $query = new PresenceQuery( @@ -29,12 +33,11 @@ public function testUsesTheCompleteQueryShapeAndRetainsCandidateValues(): void 'ignored', 'uuid', ); - $presenceVerifier = m::mock(DatabasePresenceVerifier::class); - $presenceVerifier->shouldReceive('getExistingValues') - ->once() + $presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict(); + $presenceVerifier->expects('getExistingValues') ->with($query, [1, 2.5]) - ->andReturn(['1', '2.5']); - $presenceVerifier->shouldNotReceive('getCount'); + ->returns(['1', '2.5']); + $presenceVerifier->expects('getCount')->never(); $verifier = BatchDatabaseChecker::buildVerifier($this->batchGroups($query, [1, 2.5]), $presenceVerifier); @@ -60,15 +63,13 @@ public function __toString(): string } }; $query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions); - $presenceVerifier = m::mock(DatabasePresenceVerifier::class); - $presenceVerifier->shouldReceive('getExistingValues') - ->once() + $presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict(); + $presenceVerifier->expects('getExistingValues') ->with($query, [1, 2]) - ->andReturn(['1', '2']); - $presenceVerifier->shouldReceive('getCount') - ->once() - ->with($query, m::on(static fn (mixed $value): bool => $value === $stringable)) - ->andReturn(1); + ->returns(['1', '2']); + $presenceVerifier->expects('getCount') + ->with($query, Argument::same($stringable)) + ->returns(1); $verifier = BatchDatabaseChecker::buildVerifier($this->batchGroups($query, [[1, 2], 2, $stringable]), $presenceVerifier); @@ -95,15 +96,13 @@ public function __toString(): string } }; $candidate = ['safe-in-array', $stringable]; - $presenceVerifier = m::mock(DatabasePresenceVerifier::class); - $presenceVerifier->shouldReceive('getExistingValues') - ->once() + $presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict(); + $presenceVerifier->expects('getExistingValues') ->with($query, ['safe-sibling']) - ->andReturn(['safe-sibling']); - $presenceVerifier->shouldReceive('getMultiCount') - ->once() - ->with($query, m::on(static fn (array $values): bool => $values === $candidate)) - ->andReturn(1); + ->returns(['safe-sibling']); + $presenceVerifier->expects('getMultiCount') + ->with($query, Argument::same($candidate)) + ->returns(1); $verifier = BatchDatabaseChecker::buildVerifier( $this->batchGroups($query, [$candidate, 'safe-sibling']), @@ -119,11 +118,10 @@ public function __toString(): string public function testEqualLookingIntegerAndStringCandidatesShareOneBinding(): void { $query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions); - $presenceVerifier = m::mock(DatabasePresenceVerifier::class); - $presenceVerifier->shouldReceive('getExistingValues') - ->once() + $presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict(); + $presenceVerifier->expects('getExistingValues') ->with($query, ['1']) - ->andReturn(['1']); + ->returns(['1']); $verifier = BatchDatabaseChecker::buildVerifier( $this->batchGroups($query, ['1', 1]), @@ -141,15 +139,15 @@ public function testChunksLargeValueSetsAndMarksCrossChunkMultiCountsUncertain() $query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions); $chunkSizes = []; $values = range(1, 1001); - $presenceVerifier = m::mock(DatabasePresenceVerifier::class); - $presenceVerifier->shouldReceive('getExistingValues') - ->twice() - ->andReturnUsing(function (PresenceQuery $query, array $chunk) use (&$chunkSizes): array { + $presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict(); + $presenceVerifier->expects('getExistingValues') + ->times(2) + ->resolves(function (PresenceQuery $query, array $chunk) use (&$chunkSizes): array { $chunkSizes[] = count($chunk); return array_map(strval(...), $chunk); }); - $presenceVerifier->shouldReceive('getMultiCount')->once()->with($query, $values)->andReturn(1001); + $presenceVerifier->expects('getMultiCount')->with($query, $values)->returns(1001); $verifier = BatchDatabaseChecker::buildVerifier($this->batchGroups($query, $values), $presenceVerifier); @@ -161,8 +159,8 @@ public function testChunksLargeValueSetsAndMarksCrossChunkMultiCountsUncertain() public function testEmptyFirstStageProvesEverySubmittedValueAbsent(): void { $query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions); - $presenceVerifier = m::mock(DatabasePresenceVerifier::class); - $presenceVerifier->shouldReceive('getExistingValues')->once()->andReturn([]); + $presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict(); + $presenceVerifier->expects('getExistingValues')->returns([]); $verifier = BatchDatabaseChecker::buildVerifier( $this->batchGroups($query, ['first', 'second']), @@ -177,8 +175,8 @@ public function testEmptyFirstStageProvesEverySubmittedValueAbsent(): void public function testSoleNonExactDatabaseMatchIsKnownPresentWithoutASecondQuery(): void { $query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions); - $presenceVerifier = m::mock(DatabasePresenceVerifier::class); - $presenceVerifier->shouldReceive('getExistingValues')->once()->with($query, ['Case'])->andReturn(['case']); + $presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict(); + $presenceVerifier->expects('getExistingValues')->with($query, ['Case'])->returns(['case']); $verifier = BatchDatabaseChecker::buildVerifier( $this->batchGroups($query, ['Case']), @@ -193,13 +191,12 @@ public function testSoleNonExactDatabaseMatchIsKnownPresentWithoutASecondQuery() public function testMultipleNonExactMatchesDelegateWithoutRepeatingTheGroupedQuery(): void { $query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions); - $presenceVerifier = m::mock(DatabasePresenceVerifier::class); - $presenceVerifier->shouldReceive('getExistingValues') - ->once() + $presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict(); + $presenceVerifier->expects('getExistingValues') ->with($query, ['Case', 'Other']) - ->andReturn(['case', 'other']); - $presenceVerifier->shouldReceive('getCount')->once()->with($query, 'Case')->andReturn(1); - $presenceVerifier->shouldReceive('getCount')->once()->with($query, 'Other')->andReturn(1); + ->returns(['case', 'other']); + $presenceVerifier->expects('getCount')->with($query, 'Case')->returns(1); + $presenceVerifier->expects('getCount')->with($query, 'Other')->returns(1); $verifier = BatchDatabaseChecker::buildVerifier( $this->batchGroups($query, ['Case', 'Other']), @@ -214,9 +211,9 @@ public function testMultipleNonExactMatchesDelegateWithoutRepeatingTheGroupedQue public function testSecondStageProvesMissesAbsentAfterAnExactHit(): void { $query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions); - $presenceVerifier = m::mock(DatabasePresenceVerifier::class); - $presenceVerifier->shouldReceive('getExistingValues')->once()->with($query, ['exact', 'missing'])->andReturn(['exact']); - $presenceVerifier->shouldReceive('getExistingValues')->once()->with($query, ['missing'])->andReturn([]); + $presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict(); + $presenceVerifier->expects('getExistingValues')->with($query, ['exact', 'missing'])->returns(['exact']); + $presenceVerifier->expects('getExistingValues')->with($query, ['missing'])->returns([]); $verifier = BatchDatabaseChecker::buildVerifier( $this->batchGroups($query, ['exact', 'missing']), @@ -231,10 +228,10 @@ public function testSecondStageProvesMissesAbsentAfterAnExactHit(): void public function testSecondStageExactMatchesBecomeScalarKnownFacts(): void { $query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions); - $presenceVerifier = m::mock(DatabasePresenceVerifier::class); - $presenceVerifier->shouldReceive('getExistingValues')->once()->with($query, ['exact', 'Case', 'unknown'])->andReturn(['exact', 'case']); - $presenceVerifier->shouldReceive('getExistingValues')->once()->with($query, ['Case', 'unknown'])->andReturn(['Case']); - $presenceVerifier->shouldReceive('getCount')->once()->with($query, 'unknown')->andReturn(0); + $presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict(); + $presenceVerifier->expects('getExistingValues')->with($query, ['exact', 'Case', 'unknown'])->returns(['exact', 'case']); + $presenceVerifier->expects('getExistingValues')->with($query, ['Case', 'unknown'])->returns(['Case']); + $presenceVerifier->expects('getCount')->with($query, 'unknown')->returns(0); $verifier = BatchDatabaseChecker::buildVerifier( $this->batchGroups($query, ['exact', 'Case', 'unknown']), @@ -249,8 +246,8 @@ public function testSecondStageExactMatchesBecomeScalarKnownFacts(): void public function testUnsupportedCandidateDoesNotDisableSafeSiblings(): void { $query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions); - $presenceVerifier = m::mock(DatabasePresenceVerifier::class); - $presenceVerifier->shouldReceive('getExistingValues')->once()->with($query, ['safe'])->andReturn(['safe']); + $presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict(); + $presenceVerifier->expects('getExistingValues')->with($query, ['safe'])->returns(['safe']); $verifier = BatchDatabaseChecker::buildVerifier( $this->batchGroups($query, [[1, new stdClass], false, 'safe']), @@ -264,8 +261,8 @@ public function testUnsupportedCandidateDoesNotDisableSafeSiblings(): void public function testAllUnsupportedOrEmptyCandidatesCreateNoLookup(): void { $query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions); - $presenceVerifier = m::mock(DatabasePresenceVerifier::class); - $presenceVerifier->shouldNotReceive('getExistingValues'); + $presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict(); + $presenceVerifier->expects('getExistingValues')->never(); $this->assertNull(BatchDatabaseChecker::buildVerifier( $this->batchGroups($query, [[1, new stdClass], false, true, []]), diff --git a/tests/Validation/ValidationCompiledExecutionTest.php b/tests/Validation/ValidationCompiledExecutionTest.php index 8dbbf9809f..52b6a3f4b9 100644 --- a/tests/Validation/ValidationCompiledExecutionTest.php +++ b/tests/Validation/ValidationCompiledExecutionTest.php @@ -24,7 +24,9 @@ use Hypervel\Validation\Rules\Exists; use Hypervel\Validation\Rules\In; use Hypervel\Validation\Validator; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use ReflectionProperty; @@ -35,6 +37,8 @@ class ValidationCompiledExecutionTest extends TestCase { + use VerifiesDoubles; + public function testBasicPassFail(): void { $v = $this->makeValidator(['name' => 'John'], ['name' => 'required|string|max:255']); @@ -810,12 +814,12 @@ public function testDependentFieldsPreservePercentSigns(): void public function testUniqueWhereValuesRemainLiteralWhileIgnoreFieldsResolve(): void { foreach ([Validator::class, DelegatedValidationValidator::class] as $validatorClass) { - $verifier = m::mock(PresenceVerifierInterface::class); - $verifier->shouldReceive('getCount')->once()->with( - m::on(static function (PresenceQuery $query): bool { + $verifier = Double::for(PresenceVerifierInterface::class)->strict(); + $verifier->expects('getCount')->with( + Argument::satisfies(static function (PresenceQuery $query): bool { $actual = get_object_vars($query); $actual['conditions'] = $query->conditions->toArray(); - self::assertSame([ + return $actual === [ 'connection' => null, 'collection' => 'users', 'column' => 'email', @@ -826,12 +830,10 @@ public function testUniqueWhereValuesRemainLiteralWhileIgnoreFieldsResolve(): vo ], 'excludeId' => '42', 'idColumn' => 'id', - ], $actual); - - return true; + ]; }), 'user@example.com', - )->andReturn(0); + )->returns(0); $validator = $this->makeValidator( ['items' => [['id' => 42, 'email' => 'user@example.com']]], ['items.*.email' => [Rule::unique('users', 'email')->ignore('[items.*.id]') @@ -855,11 +857,11 @@ public function testFloatUniqueExclusionsRetainTheirValue(): void Rule::unique('users', 'email')->ignore('[identifier]'), ['unique', 'users', 'email', '[identifier]'], ] as $rule) { - $verifier = m::mock(PresenceVerifierInterface::class); - $verifier->shouldReceive('getCount')->once()->with( - m::on(static fn (PresenceQuery $query): bool => $query->excludeId === '123.00000000000001'), + $verifier = Double::for(PresenceVerifierInterface::class)->strict(); + $verifier->expects('getCount')->with( + Argument::satisfies(static fn (PresenceQuery $query): bool => $query->excludeId === '123.00000000000001'), 'user@example.com', - )->andReturn(0); + )->returns(0); $validator = $this->makeValidator( ['identifier' => $identifier, 'email' => 'user@example.com'], ['email' => [$rule]], @@ -1319,8 +1321,8 @@ public function queryConditions(): DatabaseConditions return true; }); $conditions = []; - $verifier = m::mock(PresenceVerifierInterface::class); - $verifier->expects('getCount')->times(6)->andReturnUsing(function (PresenceQuery $query, mixed $value) use (&$conditions): int { + $verifier = Double::for(PresenceVerifierInterface::class)->strict(); + $verifier->expects('getCount')->times(6)->resolves(function (PresenceQuery $query, mixed $value) use (&$conditions): int { $this->assertSame('users', $query->collection); $this->assertSame('custom_email', $query->column); $this->assertSame('user@example.com', $value); @@ -1430,8 +1432,8 @@ public function validateExists(string $attribute, mixed $value, mixed $parameter return parent::validateExists($attribute, $value, $parameters); } }; - $verifier = m::mock(PresenceVerifierInterface::class); - $verifier->expects('getCount')->times($wildcard ? 2 : 1)->andReturn(1); + $verifier = Double::for(PresenceVerifierInterface::class)->strict(); + $verifier->expects('getCount')->times($wildcard ? 2 : 1)->returns(1); $validator->setPresenceVerifier($verifier); $this->assertTrue($validator->passes()); diff --git a/tests/Validation/ValidationFactoryTest.php b/tests/Validation/ValidationFactoryTest.php index 67b21c2519..6c593ffa64 100755 --- a/tests/Validation/ValidationFactoryTest.php +++ b/tests/Validation/ValidationFactoryTest.php @@ -4,7 +4,7 @@ namespace Hypervel\Tests\Validation; -use Hypervel\Contracts\Container\Container; +use Hypervel\Container\Container; use Hypervel\Contracts\Translation\Translator as TranslatorInterface; use Hypervel\Tests\TestCase; use Hypervel\Translation\ArrayLoader; @@ -13,7 +13,6 @@ use Hypervel\Validation\PresenceQuery; use Hypervel\Validation\PresenceVerifierInterface; use Hypervel\Validation\Validator; -use Mockery as m; use ReflectionProperty; class ValidationFactoryTest extends TestCase @@ -135,7 +134,7 @@ public function testExcludeAndIncludeUnvalidatedArrayKeys(): void public function testSetContainer(): void { $translator = new Translator(new ArrayLoader, 'en'); - $container = m::mock(Container::class); + $container = new Container; $factory = new Factory($translator); $this->assertNull($factory->getContainer()); @@ -145,7 +144,7 @@ public function testSetContainer(): void public function testPresenceVerifierIsNullableWhenFactoryIsConstructedDirectly(): void { - $factory = new Factory(m::mock(TranslatorInterface::class)); + $factory = new Factory(new Translator(new ArrayLoader, 'en')); $this->assertNull($factory->getPresenceVerifier()); } diff --git a/tests/Validation/ValidationPrecomputedPresenceVerifierTest.php b/tests/Validation/ValidationPrecomputedPresenceVerifierTest.php index 65d454e58c..709f860c45 100644 --- a/tests/Validation/ValidationPrecomputedPresenceVerifierTest.php +++ b/tests/Validation/ValidationPrecomputedPresenceVerifierTest.php @@ -12,13 +12,17 @@ use Hypervel\Validation\PrecomputedPresenceVerifier; use Hypervel\Validation\PresenceQuery; use Hypervel\Validation\PresenceVerifierInterface; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use stdClass; use Stringable; class ValidationPrecomputedPresenceVerifierTest extends TestCase { + use VerifiesDoubles; + public function testLookupKeyModelsTheCompleteEffectiveQueryShape(): void { $status = new DatabaseCondition('status', DatabaseConditionOperator::Equals, 'active'); @@ -122,13 +126,12 @@ public function __toString(): string return '3'; } }; - $fallback = m::mock(PresenceVerifierInterface::class); + $fallback = Double::for(PresenceVerifierInterface::class)->strict(); $presenceQuery = new PresenceQuery(null, 'users', 'id', new DatabaseConditions); - $fallback->shouldReceive('getCount') - ->once() - ->with($presenceQuery, m::on(static fn (mixed $value): bool => $value === $stringable)) - ->andReturn(1); + $fallback->expects('getCount') + ->with($presenceQuery, Argument::same($stringable)) + ->returns(1); $verifier = new PrecomputedPresenceVerifier($fallback); $verifier->addLookup( self::lookupKey($presenceQuery), @@ -150,31 +153,27 @@ public function __toString(): string public function testUnknownScalarFallbackCountsAreMemoizedPerQueryShapeAndValue(): void { - $fallback = m::mock(PresenceVerifierInterface::class); + $fallback = Double::for(PresenceVerifierInterface::class)->strict(); $activeQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions(new DatabaseCondition('status', DatabaseConditionOperator::Equals, 'active'))); - $fallback->shouldReceive('getCount') + $fallback->expects('getCount') ->with($activeQuery, 'shared') - ->once() - ->andReturn(1); + ->returns(1); $inactiveQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions(new DatabaseCondition('status', DatabaseConditionOperator::Equals, 'inactive'))); - $fallback->shouldReceive('getCount') + $fallback->expects('getCount') ->with($inactiveQuery, 'shared') - ->once() - ->andReturn(0); + ->returns(0); $adminQuery = new PresenceQuery(null, 'admins', 'email', new DatabaseConditions); - $fallback->shouldReceive('getCount') + $fallback->expects('getCount') ->with($adminQuery, 'shared') - ->once() - ->andReturn(2); + ->returns(2); $unfilteredQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions); - $fallback->shouldReceive('getCount') - ->with($unfilteredQuery, m::on(static fn (mixed $value): bool => $value === '1')) - ->once() - ->andReturn(1); + $fallback->expects('getCount') + ->with($unfilteredQuery, Argument::same('1')) + ->returns(1); $verifier = new PrecomputedPresenceVerifier($fallback); $verifier->addLookup(self::lookupKey($activeQuery), [], [], [], true); @@ -194,19 +193,19 @@ public function testUnknownScalarFallbackCountsAreMemoizedPerQueryShapeAndValue( public function testUnregisteredAndUnsupportedScalarShapesDelegateWithoutMemoization(): void { $unsupported = false; - $fallback = m::mock(PresenceVerifierInterface::class); + $fallback = Double::for(PresenceVerifierInterface::class)->strict(); $unregisteredQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions(new DatabaseCondition('status', DatabaseConditionOperator::Equals, 'active'))); - $fallback->shouldReceive('getCount') + $fallback->expects('getCount') ->with($unregisteredQuery, 'unregistered') - ->twice() - ->andReturn(1); + ->times(2) + ->returns(1); $registeredQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions); - $fallback->shouldReceive('getCount') + $fallback->expects('getCount') ->with($registeredQuery, $unsupported) - ->twice() - ->andReturn(0); + ->times(2) + ->returns(0); $verifier = new PrecomputedPresenceVerifier($fallback); $verifier->addLookup(self::lookupKey($registeredQuery), [], [], [], true); @@ -219,10 +218,10 @@ public function testUnregisteredAndUnsupportedScalarShapesDelegateWithoutMemoiza public function testConnectionIsPartOfTheLookupAndForwardedToTheFallback(): void { - $fallback = m::mock(PresenceVerifierInterface::class); + $fallback = Double::for(PresenceVerifierInterface::class)->strict(); $presenceQuery = new PresenceQuery('tenant', 'users', 'email', new DatabaseConditions); - $fallback->shouldReceive('getCount')->once()->with($presenceQuery, 'unknown')->andReturn(1); + $fallback->expects('getCount')->with($presenceQuery, 'unknown')->returns(1); $verifier = new PrecomputedPresenceVerifier($fallback); $verifier->addLookup( @@ -255,10 +254,10 @@ public function testMultiCountUsesExactAndAbsentFactsFromOneDistinctQuery(): voi public function testMultiCountUsesKnownPresentOnlyForASoleDistinctInput(): void { - $fallback = m::mock(PresenceVerifierInterface::class); + $fallback = Double::for(PresenceVerifierInterface::class)->strict(); $presenceQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions); - $fallback->shouldReceive('getMultiCount')->once()->with($presenceQuery, ['case', 'exact'])->andReturn(1); + $fallback->expects('getMultiCount')->with($presenceQuery, ['case', 'exact'])->returns(1); $verifier = new PrecomputedPresenceVerifier($fallback); $verifier->addLookup( self::lookupKey($presenceQuery), @@ -287,16 +286,15 @@ public function __toString(): string return 'exact'; } }; - $fallback = m::mock(PresenceVerifierInterface::class); + $fallback = Double::for(PresenceVerifierInterface::class)->strict(); $presenceQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions); - $fallback->shouldReceive('getMultiCount')->once()->with($presenceQuery, ['unknown'])->andReturn(1); - $fallback->shouldReceive('getMultiCount')->once()->with($presenceQuery, [false])->andReturn(0); - $fallback->shouldReceive('getMultiCount') - ->once() - ->with($presenceQuery, m::on(static fn (array $values): bool => $values === [$stringable])) - ->andReturn(1); - $fallback->shouldReceive('getMultiCount')->once()->with($presenceQuery, ['exact'])->andReturn(1); + $fallback->expects('getMultiCount')->with($presenceQuery, ['unknown'])->returns(1); + $fallback->expects('getMultiCount')->with($presenceQuery, [false])->returns(0); + $fallback->expects('getMultiCount') + ->with($presenceQuery, Argument::same([$stringable])) + ->returns(1); + $fallback->expects('getMultiCount')->with($presenceQuery, ['exact'])->returns(1); $verifier = new PrecomputedPresenceVerifier($fallback); $verifier->addLookup( self::lookupKey($presenceQuery), @@ -321,13 +319,12 @@ public function __toString(): string return $this->format(DATE_ATOM); } }; - $fallback = m::mock(PresenceVerifierInterface::class); + $fallback = Double::for(PresenceVerifierInterface::class)->strict(); $presenceQuery = new PresenceQuery(null, 'users', 'created_at', new DatabaseConditions); - $fallback->shouldReceive('getCount') - ->once() + $fallback->expects('getCount') ->with($presenceQuery, $value) - ->andReturn(1); + ->returns(1); $verifier = new PrecomputedPresenceVerifier($fallback); $verifier->addLookup(self::lookupKey($presenceQuery), [], [], [], true); @@ -378,9 +375,9 @@ private static function bindingMap(array $values): array */ private function makeVerifierWithUnusedFallback(): PrecomputedPresenceVerifier { - $fallback = m::mock(PresenceVerifierInterface::class); - $fallback->shouldNotReceive('getCount'); - $fallback->shouldNotReceive('getMultiCount'); + $fallback = Double::for(PresenceVerifierInterface::class)->strict(); + $fallback->expects('getCount')->never(); + $fallback->expects('getMultiCount')->never(); return new PrecomputedPresenceVerifier($fallback); } diff --git a/tests/Validation/ValidationRuleCanTest.php b/tests/Validation/ValidationRuleCanTest.php index fc95ec9977..a9d3c3db43 100644 --- a/tests/Validation/ValidationRuleCanTest.php +++ b/tests/Validation/ValidationRuleCanTest.php @@ -11,13 +11,18 @@ use Hypervel\Testbench\TestCase; use Hypervel\Translation\ArrayLoader; use Hypervel\Translation\Translator; +use Hypervel\Validation\Rule; use Hypervel\Validation\Rules\Can; use Hypervel\Validation\Validator; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use PHPUnit\Framework\Attributes\TestWith; use stdClass; class ValidationRuleCanTest extends TestCase { + use VerifiesDoubles; + protected $user; protected $router; @@ -26,7 +31,7 @@ protected function setUp(): void { parent::setUp(); - $this->user = m::mock(Authenticatable::class); + $this->user = Double::for(Authenticatable::class)->strict(); $this->app->singleton(GateContract::class, function () { return new Gate($this->app, function () { @@ -73,12 +78,53 @@ public function testValidationPasses(): void $v = new Validator( resolve('translator'), ['company' => '1'], - ['company' => new Can('update-company', [\App\Models\Company::class, m::mock(Authenticatable::class)])] + ['company' => new Can('update-company', [\App\Models\Company::class, Double::for(Authenticatable::class)->strict()])] ); $this->assertTrue($v->passes()); } + public function testNamedFactoryArgumentsArePassedPositionally(): void + { + $this->gate()->define('check-value', function ($user, ...$arguments): bool { + $this->assertSame([stdClass::class, false, 0], $arguments); + + return true; + }); + + $validator = new Validator( + $this->app->make('translator'), + ['value' => 0], + ['value' => Rule::can('check-value', model: stdClass::class, enabled: false)], + ); + + $this->assertTrue($validator->passes()); + } + + #[TestWith([0, []])] + #[TestWith(['0', []])] + #[TestWith([false, []])] + #[TestWith([null, []])] + #[TestWith(['0', ['scope', false, 0, null, '']])] + public function testAuthorizationReceivesFalseyValuesAndArguments(mixed $value, array $arguments): void + { + foreach ([true, false] as $allowed) { + $this->gate()->define('check-value', function ($user, ...$received) use ($value, $arguments, $allowed): bool { + $this->assertSame([...$arguments, $value], $received); + + return $allowed; + }); + + $validator = new Validator( + $this->app->make('translator'), + ['value' => $value], + ['value' => new Can('check-value', $arguments)], + ); + + $this->assertSame($allowed, $validator->passes()); + } + } + public function testCustomMessageUsingDotNotationAndFqcnWorks(): void { $v = new Validator( diff --git a/tests/View/RequestSharedDataTest.php b/tests/View/RequestSharedDataTest.php index 11b5e0aef2..3152cce607 100644 --- a/tests/View/RequestSharedDataTest.php +++ b/tests/View/RequestSharedDataTest.php @@ -15,7 +15,8 @@ use Hypervel\View\Middleware\ShareErrorsFromSession; use Hypervel\View\RequestSharedData; use Hypervel\View\ViewFinderInterface; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\HttpFoundation\Response; @@ -23,6 +24,8 @@ class RequestSharedDataTest extends TestCase { + use VerifiesDoubles; + public function testRequestDataMergesBetweenGlobalAndLocalData(): void { $factory = $this->factory(); @@ -113,16 +116,16 @@ function (Request $request) use ($factory, $secondErrors, $releaseFirst): Respon private function factory(): Factory { return new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - m::mock(Dispatcher::class), + new EngineResolver, + Double::for(ViewFinderInterface::class)->strict(), + Double::for(Dispatcher::class)->strict(), ); } private function requestWithErrors(ViewErrorBag $errors): Request { - $session = m::mock(Session::class); - $session->shouldReceive('get')->once()->with('errors')->andReturn($errors); + $session = Double::for(Session::class)->strict(); + $session->expects('get')->with('errors')->returns($errors); $request = Request::create('/'); $request->setHypervelSession($session); diff --git a/tests/View/ViewExceptionTest.php b/tests/View/ViewExceptionTest.php index b4fed604ec..30a5f47607 100644 --- a/tests/View/ViewExceptionTest.php +++ b/tests/View/ViewExceptionTest.php @@ -11,15 +11,18 @@ use Hypervel\Http\Response; use Hypervel\Tests\TestCase; use Hypervel\View\ViewException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; class ViewExceptionTest extends TestCase { + use VerifiesDoubles; + public function testRenderForwardsThePreviousExceptionResult(): void { $request = Request::create('/'); - $view = m::mock(ViewContract::class); + $view = Double::for(ViewContract::class)->strict(); $responsable = new ViewExceptionResponsable; $response = new Response('hypervel'); $symfonyResponse = new SymfonyResponse('symfony'); diff --git a/tests/View/ViewStaticStateTest.php b/tests/View/ViewStaticStateTest.php index c1e7d976fa..670b973b50 100644 --- a/tests/View/ViewStaticStateTest.php +++ b/tests/View/ViewStaticStateTest.php @@ -12,11 +12,14 @@ use Hypervel\View\DynamicComponent; use Hypervel\View\Factory; use Hypervel\View\View; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionProperty; class ViewStaticStateTest extends TestCase { + use VerifiesDoubles; + public function testViewFlushStateClearsMacros(): void { View::macro('testingStaticStateProbe', static fn (): string => 'ok'); @@ -94,7 +97,7 @@ public function testComponentFlushCacheClearsEveryCache(): void public function testComponentFlushStateClearsAllStaticState(): void { - (new ReflectionProperty(Component::class, 'factory'))->setValue(null, m::mock(FactoryContract::class)); + (new ReflectionProperty(Component::class, 'factory'))->setValue(null, Double::for(FactoryContract::class)->strict()); (new ReflectionProperty(Component::class, 'componentsResolver'))->setValue(null, static fn (): null => null); (new ReflectionProperty(Component::class, 'bladeViewCache'))->setValue(null, ['cached']); diff --git a/tests/Watcher/Driver/FindDriverTest.php b/tests/Watcher/Driver/FindDriverTest.php index dacfcc14ef..dd78629c82 100644 --- a/tests/Watcher/Driver/FindDriverTest.php +++ b/tests/Watcher/Driver/FindDriverTest.php @@ -18,11 +18,14 @@ use Hypervel\Watcher\WatchPath; use Hypervel\Watcher\WatchPathType; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class FindDriverTest extends TestCase { + use VerifiesDoubles; + protected string $tempDir; protected function setUp(): void @@ -418,9 +421,8 @@ public function testEmptyCompleteInventoryDeletesRetainedPathsAndBoundsState(): public function testChangedTraversalFailurePublishesCompleteRecordsAndHoldsTheCutoff(): void { $path = base_path('composer.json'); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('warning') - ->once() + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('warning') ->with( 'One or more find commands exited with code 1. ' . 'Detected changes may repeat until the filesystem error is fixed.', @@ -450,9 +452,8 @@ public function testChangedTraversalFailurePublishesCompleteRecordsAndHoldsTheCu public function testInventoryFailureSuspendsDeletionsButAdvancesACompleteChangedCutoff(): void { $path = base_path('composer.json'); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('warning') - ->once() + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('warning') ->with( 'One or more find commands exited with code 2. ' . 'Deletion detection is suspended until the filesystem error is fixed.', @@ -480,9 +481,8 @@ public function testInventoryFailureSuspendsDeletionsButAdvancesACompleteChanged public function testMultipleTraversalFailuresLogTheFirstCodeAndBothAffectedGuaranteesOnce(): void { - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('warning') - ->once() + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('warning') ->with( 'One or more find commands exited with code 2. ' . 'Detected changes may repeat until the filesystem error is fixed. ' diff --git a/tests/Watcher/Driver/ScanFileDriverTest.php b/tests/Watcher/Driver/ScanFileDriverTest.php index a845b39ddc..f1dc68f7d3 100644 --- a/tests/Watcher/Driver/ScanFileDriverTest.php +++ b/tests/Watcher/Driver/ScanFileDriverTest.php @@ -16,10 +16,13 @@ use Hypervel\Watcher\Option; use Hypervel\Watcher\WatchPath; use Hypervel\Watcher\WatchPathType; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class ScanFileDriverTest extends TestCase { + use VerifiesDoubles; + protected string $fixturePath; protected string $fixtureRelativePath = 'watcher-scan-driver-test'; @@ -143,9 +146,8 @@ public function testSnapshotOrderingDoesNotCreateFalseChanges(): void public function testLogsOnlyWhenAProcessedSnapshotContainsChanges(): void { - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('debug') - ->once() + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('debug') ->with(ScanFileDriver::class . ' Watching: Total:2, Change:1, Add:1, Delete:1.'); $driver = new ScanFileDriverTestProxy(new Option, $logger); $channel = new Channel(3); @@ -365,8 +367,8 @@ public function testHashFailureOmitsTheFileFromTheSnapshot(): void { $this->putFixture('unreadable.php', 'contents'); $path = $this->fixturePath . '/unreadable.php'; - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('hash')->once()->with($path)->andReturn(false); + $filesystem = Double::for(Filesystem::class)->strict(); + $filesystem->expects('hash')->with($path)->returns(false); $driver = new ScanFileDriverTestProxy(new Option(watchPaths: [ new WatchPath($this->fixtureRelativePath . '/unreadable.php', WatchPathType::File), ]), ContainerStub::getLogger(), $filesystem); diff --git a/tests/Watcher/Fixtures/ContainerStub.php b/tests/Watcher/Fixtures/ContainerStub.php index 89c3ec7f6e..8ad146450d 100644 --- a/tests/Watcher/Fixtures/ContainerStub.php +++ b/tests/Watcher/Fixtures/ContainerStub.php @@ -5,17 +5,19 @@ namespace Hypervel\Tests\Watcher\Fixtures; use Hypervel\Contracts\Log\StdoutLoggerInterface; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; class ContainerStub { - public static function getLogger(): StdoutLoggerInterface|MockInterface + /** + * Create a logger that accepts routine watcher messages. + */ + public static function getLogger(): StdoutLoggerInterface { - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('debug')->andReturn(null); - $logger->shouldReceive('warning')->andReturn(null); - $logger->shouldReceive('log')->andReturn(null); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->allows('debug'); + $logger->allows('warning'); + $logger->allows('log'); return $logger; } diff --git a/tests/Watcher/ServerRestartStrategyTest.php b/tests/Watcher/ServerRestartStrategyTest.php index 818b32986b..e1db8913b8 100644 --- a/tests/Watcher/ServerRestartStrategyTest.php +++ b/tests/Watcher/ServerRestartStrategyTest.php @@ -10,7 +10,9 @@ use Hypervel\Testbench\TestCase; use Hypervel\Watcher\ServerRestartStrategy; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Symfony\Component\Console\Output\BufferedOutput; @@ -20,6 +22,8 @@ class ServerRestartStrategyTest extends TestCase { + use VerifiesDoubles; + public function testConstructorDefaultsMissingDaemonizeSettingToFalse(): void { $this->app->instance('config', new Repository([ @@ -355,10 +359,9 @@ public function testRestartAfterFinalStopDoesNotRelaunch(): void public function testOpenFailureClearsLifecycleOwnershipAndAllowsRetry(): void { - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report') - ->once() - ->with(m::on( + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report') + ->with(Argument::satisfies( fn (mixed $exception): bool => $exception instanceof RuntimeException && $exception->getMessage() === 'Unable to launch the watched server process.', )); @@ -379,8 +382,8 @@ public function testOpenFailureClearsLifecycleOwnershipAndAllowsRetry(): void public function testCloseFailureClearsLifecycleOwnershipAndAllowsRetry(): void { $failure = new RuntimeException('expected close failure'); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->once()->with($failure); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report')->with($failure); $this->app->instance(ExceptionHandlerContract::class, $handler); $strategy = $this->createProbeStrategy(); $strategy->closeFailures = [$failure, null]; @@ -397,8 +400,8 @@ public function testCloseFailureClearsLifecycleOwnershipAndAllowsRetry(): void public function testMalformedEnvironmentDuringRestartClearsOwnershipAndAllowsRetry(): void { $failure = new RuntimeException('malformed environment'); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->once()->with($failure); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report')->with($failure); $this->app->instance(ExceptionHandlerContract::class, $handler); $strategy = $this->createProbeStrategy(); $strategy->reloadFailures = [null, $failure, null]; @@ -426,8 +429,8 @@ public function testMalformedEnvironmentDuringRestartClearsOwnershipAndAllowsRet public function testNormalServerExitClearsLifecycleOwnership(): void { - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandlerContract::class)->strict(); + $handler->expects('report')->never(); $this->app->instance(ExceptionHandlerContract::class, $handler); $strategy = $this->createProbeStrategy(); diff --git a/tests/Watcher/WatchCommandTest.php b/tests/Watcher/WatchCommandTest.php index 3558835589..97df329e53 100644 --- a/tests/Watcher/WatchCommandTest.php +++ b/tests/Watcher/WatchCommandTest.php @@ -6,7 +6,7 @@ use Closure; use Hypervel\Config\Repository; -use Hypervel\Contracts\Container\Container; +use Hypervel\Container\Container; use Hypervel\Contracts\Foundation\Application as ApplicationContract; use Hypervel\Testbench\TestCase; use Hypervel\Watcher\Console\WatchCommand; @@ -16,7 +16,8 @@ use Hypervel\Watcher\ServerRestartStrategy; use Hypervel\Watcher\Watcher; use Hypervel\Watcher\WatchPath; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\Console\Exception\RuntimeException as ConsoleRuntimeException; use Symfony\Component\Console\Input\ArrayInput; @@ -25,6 +26,8 @@ class WatchCommandTest extends TestCase { + use VerifiesDoubles; + protected function tearDown(): void { putenv('APP_RUNNING_IN_CONSOLE'); @@ -34,10 +37,10 @@ protected function tearDown(): void public function testWatchCommandFailsFastWhenRunningInConsoleIsTrue(): void { - $container = m::mock(Container::class); - $application = m::mock(ApplicationContract::class); - $container->shouldReceive('make')->with(ApplicationContract::class)->once()->andReturn($application); - $application->shouldReceive('runningInConsole')->once()->andReturnTrue(); + $container = new Container; + $application = Double::for(ApplicationContract::class, override: true)->strict(); + $container->instance(ApplicationContract::class, $application->instance()); + $application->expects('runningInConsole')->returns(true); $command = new WatchCommand($container); $command->setHypervel($this->app); @@ -58,16 +61,16 @@ public function testWatchCommandRunsWatcherWhenRunningInConsoleIsFalse(): void ], ])); - $watcher = m::mock(Watcher::class); - $watcher->shouldReceive('run')->once(); + $watcher = Double::for(Watcher::class)->strict(); + $watcher->expects('run'); $this->app->bind(ScanFileDriver::class, function ($app, array $parameters) { $this->assertInstanceOf(Option::class, $parameters['option']); - return m::mock(DriverInterface::class); + return Double::for(DriverInterface::class)->strict(); }); $this->app->bind(ServerRestartStrategy::class, function () { - return m::mock(ServerRestartStrategy::class); + return Double::for(ServerRestartStrategy::class)->strict(); }); $this->app->bind(Watcher::class, function ($app, array $parameters) use ($watcher) { $this->assertInstanceOf(DriverInterface::class, $parameters['driver']); @@ -97,11 +100,11 @@ public function testWatchCommandWithNoRestartPassesNullStrategy(): void ], ])); - $watcher = m::mock(Watcher::class); - $watcher->shouldReceive('run')->once(); + $watcher = Double::for(Watcher::class)->strict(); + $watcher->expects('run'); $this->app->bind(ScanFileDriver::class, function () { - return m::mock(DriverInterface::class); + return Double::for(DriverInterface::class)->strict(); }); $this->app->bind(Watcher::class, function ($app, array $parameters) use ($watcher) { $this->assertNull($parameters['strategy']); @@ -121,25 +124,32 @@ public function testWatchCommandWithNoRestartPassesNullStrategy(): void public function testTerminationSignalStopsDriverBeforeRestartStrategy(): void { - $driver = m::mock(DriverInterface::class); - $strategy = m::mock(ServerRestartStrategy::class); - $driver->shouldReceive('stop')->once()->ordered(); - $strategy->shouldReceive('stop')->once()->ordered(); + $driver = Double::for(DriverInterface::class)->strict(); + $strategy = Double::for(ServerRestartStrategy::class)->strict(); + $stops = []; + $driver->expects('stop')->resolves(function () use (&$stops): void { + $stops[] = 'driver'; + }); + $strategy->expects('stop')->resolves(function () use (&$stops): void { + $stops[] = 'strategy'; + }); $command = $this->runSignalCapturingCommand($driver, $strategy); $this->assertSame([SIGINT, SIGTERM, SIGQUIT], $command->signals); $command->invokeSignalHandler(SIGTERM); + + $this->assertSame(['driver', 'strategy'], $stops); } public function testTerminationSignalStopsRestartStrategyWhenDriverCleanupFails(): void { $failure = new RuntimeException('driver cleanup failed'); - $driver = m::mock(DriverInterface::class); - $strategy = m::mock(ServerRestartStrategy::class); - $driver->shouldReceive('stop')->once()->andThrow($failure); - $strategy->shouldReceive('stop')->once(); + $driver = Double::for(DriverInterface::class)->strict(); + $strategy = Double::for(ServerRestartStrategy::class)->strict(); + $driver->expects('stop')->throws($failure); + $strategy->expects('stop'); $command = $this->runSignalCapturingCommand($driver, $strategy); @@ -161,17 +171,17 @@ public function testWatchCommandWithExtraPaths(): void ], ])); - $watcher = m::mock(Watcher::class); - $watcher->shouldReceive('run')->once(); + $watcher = Double::for(Watcher::class)->strict(); + $watcher->expects('run'); $capturedOption = null; $this->app->bind(ScanFileDriver::class, function ($app, array $parameters) use (&$capturedOption) { $capturedOption = $parameters['option']; - return m::mock(DriverInterface::class); + return Double::for(DriverInterface::class)->strict(); }); $this->app->bind(ServerRestartStrategy::class, function () { - return m::mock(ServerRestartStrategy::class); + return Double::for(ServerRestartStrategy::class)->strict(); }); $this->app->bind(Watcher::class, function () use ($watcher) { return $watcher; @@ -204,7 +214,7 @@ public function testWatchCommandWithExtraPaths(): void public function testPathOptionRequiresAValue(): void { - $command = new WatchCommand(m::mock(Container::class)); + $command = new WatchCommand($this->app); $input = new StringInput('--path'); $this->expectException(ConsoleRuntimeException::class); @@ -228,8 +238,8 @@ protected function runSignalCapturingCommand( ], ])); - $watcher = m::mock(Watcher::class); - $watcher->shouldReceive('run')->once(); + $watcher = Double::for(Watcher::class)->strict(); + $watcher->expects('run'); $this->app->bind(ScanFileDriver::class, fn () => $driver); $this->app->bind(ServerRestartStrategy::class, fn () => $strategy); diff --git a/tests/Watcher/WatcherTest.php b/tests/Watcher/WatcherTest.php index 0b6d1ad6c1..ec29db120d 100644 --- a/tests/Watcher/WatcherTest.php +++ b/tests/Watcher/WatcherTest.php @@ -12,7 +12,8 @@ use Hypervel\Watcher\Driver\DriverInterface; use Hypervel\Watcher\RestartStrategy; use Hypervel\Watcher\Watcher; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Swoole\Coroutine\CanceledException; use Symfony\Component\Console\Output\BufferedOutput; @@ -20,6 +21,8 @@ class WatcherTest extends TestCase { + use VerifiesDoubles; + public function testSynchronousFinalBatchIsDrainedAndRestartedOnce(): void { $driver = new WatcherDriver(static function (Channel $channel): void { @@ -131,8 +134,8 @@ public function testCleanupUnblocksADriverPushingToTheFullChangeChannel(): void $driverCompleted = true; } }); - $output = m::mock(BufferedOutput::class); - $output->shouldReceive('writeln')->once()->andThrow($failure); + $output = Double::for(BufferedOutput::class)->strict(); + $output->expects('writeln')->throws($failure); try { (new Watcher($driver, $output))->run(); @@ -170,8 +173,8 @@ public function testOriginalCancellationSurvivesCleanupCancellation(): void static fn (Channel $channel): bool => $channel->push('changed.php'), $cleanupCancellation, ); - $output = m::mock(BufferedOutput::class); - $output->shouldReceive('writeln')->once()->andThrow($originalCancellation); + $output = Double::for(BufferedOutput::class)->strict(); + $output->expects('writeln')->throws($originalCancellation); try { (new Watcher($driver, $output))->run(); @@ -189,8 +192,8 @@ public function testCancellationRunsRequiredTeardownWithoutWaitingForTrailingChi $result = new Channel(1); $driver = new TrailingCleanupWatcherDriver($trailingCleanupStarted, $releaseTrailingCleanup); $strategy = new WatcherRestartStrategy; - $output = m::mock(BufferedOutput::class); - $output->shouldReceive('writeln')->once()->andThrow($cancellation); + $output = Double::for(BufferedOutput::class)->strict(); + $output->expects('writeln')->throws($cancellation); $watcher = Coroutine::create(static function () use ($driver, $output, $strategy, $result): void { try { (new Watcher($driver, $output, $strategy))->run(); diff --git a/tests/Wayfinder/BindingResolverTest.php b/tests/Wayfinder/BindingResolverTest.php index 8ee3f3fde2..b9eaead21d 100644 --- a/tests/Wayfinder/BindingResolverTest.php +++ b/tests/Wayfinder/BindingResolverTest.php @@ -9,13 +9,16 @@ use Hypervel\Database\Schema\Builder; use Hypervel\Testbench\TestCase; use Hypervel\Wayfinder\BindingResolver; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionClass; class BindingResolverTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('castTypes')] public function testPrimitiveCastEvidenceTakesPrecedence(string $cast, array $expected): void { @@ -130,11 +133,11 @@ private function bindModel(array $casts, ?array $columns = null): void private function mockConnection(string $table, array $columns): Connection { - $schema = m::mock(Builder::class); - $schema->shouldReceive('getColumns')->once()->with($table)->andReturn($columns); + $schema = Double::for(Builder::class)->strict(); + $schema->expects('getColumns')->with($table)->returns($columns); - $connection = m::mock(Connection::class); - $connection->shouldReceive('getSchemaBuilder')->once()->andReturn($schema); + $connection = Double::for(Connection::class)->strict(); + $connection->expects('getSchemaBuilder')->returns($schema); return $connection; } diff --git a/tests/WebSocketServer/HandshakeHandlerTest.php b/tests/WebSocketServer/HandshakeHandlerTest.php index 8936c5932a..47365a9f35 100644 --- a/tests/WebSocketServer/HandshakeHandlerTest.php +++ b/tests/WebSocketServer/HandshakeHandlerTest.php @@ -4,14 +4,13 @@ namespace Hypervel\Tests\WebSocketServer; -use Hypervel\Contracts\Container\Container; +use Hypervel\Container\Container; use Hypervel\Http\Request; use Hypervel\Routing\Route; use Hypervel\Tests\TestCase; use Hypervel\Tests\WebSocketServer\Fixtures\WebSocketStub; use Hypervel\WebSocketServer\HandshakeHandler; use Hypervel\WebSocketServer\Security; -use Mockery as m; use RuntimeException; use Symfony\Component\HttpFoundation\HeaderBag; @@ -19,7 +18,7 @@ class HandshakeHandlerTest extends TestCase { public function testBuildsHandshakeWithoutImplicitlySelectingAProtocol(): void { - $handler = new HandshakeHandler($this->container()); + $handler = new HandshakeHandler(new Container); $request = $this->request(WebSocketStub::class); $request->headers = new HeaderBag([ Security::SEC_WEBSOCKET_KEY => 'dGhlIHNhbXBsZSBub25jZQ==', @@ -35,7 +34,7 @@ public function testBuildsHandshakeWithoutImplicitlySelectingAProtocol(): void public function testMissingHandlerIsAServerConfigurationFailure(): void { - $handler = new HandshakeHandler($this->container()); + $handler = new HandshakeHandler(new Container); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('WebSocket handler not found.'); @@ -43,17 +42,6 @@ public function testMissingHandlerIsAServerConfigurationFailure(): void $handler->handleHandshake($this->request('MissingWebSocketHandler')); } - /** - * Create the container used by the handshake handler. - */ - protected function container(): Container - { - $container = m::mock(Container::class); - $container->shouldReceive('make')->with(Security::class)->andReturn(new Security); - - return $container; - } - /** * Create a request with the given route controller. * @@ -61,11 +49,9 @@ protected function container(): Container */ protected function request(string $controller): Request { - $route = m::mock(Route::class); - $route->shouldReceive('getControllerClass')->andReturn($controller); - - $request = m::mock(Request::class)->makePartial(); - $request->shouldReceive('route')->andReturn($route); + $route = new Route('GET', '/', ['uses' => $controller . '@onOpen']); + $request = Request::create('/'); + $request->setRouteResolver(fn (): Route => $route); $request->headers = new HeaderBag([ Security::SEC_WEBSOCKET_KEY => 'dGhlIHNhbXBsZSBub25jZQ==', ]); diff --git a/tests/WebSocketServer/SenderTest.php b/tests/WebSocketServer/SenderTest.php index 07e4ac5744..6bcd43aa46 100644 --- a/tests/WebSocketServer/SenderTest.php +++ b/tests/WebSocketServer/SenderTest.php @@ -9,20 +9,26 @@ use Hypervel\Tests\TestCase; use Hypervel\WebSocketServer\Sender; use Hypervel\WebSocketServer\SenderPipeMessage; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Swoole\Server; use Swoole\WebSocket\Server as WebSocketServer; class SenderTest extends TestCase { + use VerifiesDoubles; + public function testCheckUsesCachedServerAndRecognizesOnlyActiveConnections(): void { $server = $this->server(); - $server->shouldReceive('connection_info')->once()->andReturn(false); - $server->shouldReceive('connection_info')->once()->andReturn([]); - $server->shouldReceive('connection_info')->once()->andReturn(['websocket_status' => WEBSOCKET_STATUS_CLOSING]); - $server->shouldReceive('connection_info')->once()->andReturn(['websocket_status' => WEBSOCKET_STATUS_ACTIVE]); + $server->expects('connection_info')->times(4)->returns( + false, + [], + ['websocket_status' => WEBSOCKET_STATUS_CLOSING], + ['websocket_status' => WEBSOCKET_STATUS_ACTIVE], + ); $sender = $this->sender($server); $this->assertFalse($sender->check(1)); @@ -36,10 +42,10 @@ public function testCheckUsesCachedServerAndRecognizesOnlyActiveConnections(): v public function testReturnsVerbatimNativeResultsForLocalConnections(): void { $server = $this->server(); - $server->shouldReceive('connection_info')->twice()->andReturn(['websocket_status' => WEBSOCKET_STATUS_ACTIVE]); - $server->shouldReceive('push')->once()->with(42, 'first')->andReturnTrue(); - $server->shouldReceive('push')->once()->with(42, 'second')->andReturnFalse(); - $server->shouldNotReceive('sendMessage'); + $server->expects('connection_info')->times(2)->returns(['websocket_status' => WEBSOCKET_STATUS_ACTIVE]); + $server->expects('push')->with(42, 'first')->returns(true); + $server->expects('push')->with(42, 'second')->returns(false); + $server->expects('sendMessage')->never(); $sender = $this->sender($server); $this->assertTrue($sender->push(42, 'first')); @@ -49,8 +55,8 @@ public function testReturnsVerbatimNativeResultsForLocalConnections(): void public function testDoesNotFanOutMissingProcessModeConnections(): void { $server = $this->server(); - $server->shouldReceive('connection_info')->once()->with(42)->andReturnFalse(); - $server->shouldNotReceive('sendMessage'); + $server->expects('connection_info')->with(42)->returns(false); + $server->expects('sendMessage')->never(); $this->assertFalse($this->sender($server)->disconnect(42)); } @@ -58,9 +64,9 @@ public function testDoesNotFanOutMissingProcessModeConnections(): void public function testDoesNotFanOutAfterLocalNativeFailure(): void { $server = $this->server(SWOOLE_BASE, workerCount: 2); - $server->shouldReceive('connection_info')->once()->with(42)->andReturn(['websocket_status' => WEBSOCKET_STATUS_ACTIVE]); - $server->shouldReceive('disconnect')->once()->with(42)->andReturnFalse(); - $server->shouldNotReceive('sendMessage'); + $server->expects('connection_info')->with(42)->returns(['websocket_status' => WEBSOCKET_STATUS_ACTIVE]); + $server->expects('disconnect')->with(42)->returns(false); + $server->expects('sendMessage')->never(); $this->assertFalse($this->sender($server)->disconnect(42)); } @@ -68,14 +74,14 @@ public function testDoesNotFanOutAfterLocalNativeFailure(): void public function testBaseModeFanOutReturnsTrueWhenEveryOtherWorkerAcceptsTheMessage(): void { $server = $this->server(SWOOLE_BASE, workerId: 1, workerCount: 3); - $server->shouldReceive('connection_info')->once()->with(42)->andReturnFalse(); - $server->shouldReceive('sendMessage')->once() - ->with(m::on(fn (SenderPipeMessage $message): bool => $message->name === 'disconnect' + $server->expects('connection_info')->with(42)->returns(false); + $server->expects('sendMessage') + ->with(Argument::satisfies(fn (SenderPipeMessage $message): bool => $message->name === 'disconnect' && $message->arguments === [42]), 0) - ->andReturnTrue(); - $server->shouldReceive('sendMessage')->once() - ->with(m::type(SenderPipeMessage::class), 2) - ->andReturnTrue(); + ->returns(true); + $server->expects('sendMessage') + ->with(Argument::type(SenderPipeMessage::class), 2) + ->returns(true); $this->assertTrue($this->sender($server)->disconnect(42)); } @@ -83,10 +89,10 @@ public function testBaseModeFanOutReturnsTrueWhenEveryOtherWorkerAcceptsTheMessa public function testBaseModeFanOutAttemptsEveryWorkerAndReturnsFalseWhenOneRejectsTheMessage(): void { $server = $this->server(SWOOLE_BASE, workerId: 1, workerCount: 4); - $server->shouldReceive('connection_info')->once()->with(42)->andReturnFalse(); - $server->shouldReceive('sendMessage')->once()->with(m::type(SenderPipeMessage::class), 0)->andReturnTrue(); - $server->shouldReceive('sendMessage')->once()->with(m::type(SenderPipeMessage::class), 2)->andReturnFalse(); - $server->shouldReceive('sendMessage')->once()->with(m::type(SenderPipeMessage::class), 3)->andReturnTrue(); + $server->expects('connection_info')->with(42)->returns(false); + $server->expects('sendMessage')->with(Argument::type(SenderPipeMessage::class), 0)->returns(true); + $server->expects('sendMessage')->with(Argument::type(SenderPipeMessage::class), 2)->returns(false); + $server->expects('sendMessage')->with(Argument::type(SenderPipeMessage::class), 3)->returns(true); $this->assertFalse($this->sender($server)->disconnect(42)); } @@ -94,8 +100,8 @@ public function testBaseModeFanOutAttemptsEveryWorkerAndReturnsFalseWhenOneRejec public function testBaseModeFanOutReturnsFalseWithoutAnotherWorker(): void { $server = $this->server(SWOOLE_BASE); - $server->shouldReceive('connection_info')->once()->with(42)->andReturnFalse(); - $server->shouldNotReceive('sendMessage'); + $server->expects('connection_info')->with(42)->returns(false); + $server->expects('sendMessage')->never(); $this->assertFalse($this->sender($server)->disconnect(42)); } @@ -103,11 +109,11 @@ public function testBaseModeFanOutReturnsFalseWithoutAnotherWorker(): void public function testPushFrameReturnsLocalNativeFailureWithoutFanOut(): void { $server = $this->server(SWOOLE_BASE, workerCount: 2); - $server->shouldReceive('connection_info')->once()->with(42)->andReturn(['websocket_status' => WEBSOCKET_STATUS_ACTIVE]); - $server->shouldReceive('push')->once() + $server->expects('connection_info')->with(42)->returns(['websocket_status' => WEBSOCKET_STATUS_ACTIVE]); + $server->expects('push') ->with(42, 'payload', WEBSOCKET_OPCODE_TEXT, SWOOLE_WEBSOCKET_FLAG_FIN) - ->andReturnFalse(); - $server->shouldNotReceive('sendMessage'); + ->returns(false); + $server->expects('sendMessage')->never(); $this->assertFalse($this->sender($server)->pushFrame(42, new Frame(payloadData: 'payload'))); } @@ -115,11 +121,11 @@ public function testPushFrameReturnsLocalNativeFailureWithoutFanOut(): void public function testPushFrameUsesBaseModeFanOutForANonLocalConnection(): void { $server = $this->server(SWOOLE_BASE, workerCount: 2); - $server->shouldReceive('connection_info')->once()->with(42)->andReturnFalse(); - $server->shouldReceive('sendMessage')->once() - ->with(m::on(fn (SenderPipeMessage $message): bool => $message->name === 'push' + $server->expects('connection_info')->with(42)->returns(false); + $server->expects('sendMessage') + ->with(Argument::satisfies(fn (SenderPipeMessage $message): bool => $message->name === 'push' && $message->arguments === [42, 'payload', WEBSOCKET_OPCODE_TEXT, SWOOLE_WEBSOCKET_FLAG_FIN]), 1) - ->andReturnTrue(); + ->returns(true); $this->assertTrue($this->sender($server)->pushFrame(42, new Frame(payloadData: 'payload'))); } @@ -129,10 +135,10 @@ public function testPushFrameUsesBaseModeFanOutForANonLocalConnection(): void */ protected function sender(WebSocketServer $server): Sender { - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with(Server::class)->andReturn($server); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(Server::class)->returns($server); - return new Sender($container); + return new Sender($container->instance()); } /** @@ -142,8 +148,8 @@ protected function server( int $mode = SWOOLE_PROCESS, int $workerId = 0, int $workerCount = 1, - ): WebSocketServer&MockInterface { - $server = m::mock(WebSocketServer::class); + ): WebSocketServer&DoubleInterface { + $server = Double::for(WebSocketServer::class)->strict(); $server->mode = $mode; $server->worker_id = $workerId; $server->setting = ['worker_num' => $workerCount]; diff --git a/tests/WebSocketServer/ServerBootstrapTest.php b/tests/WebSocketServer/ServerBootstrapTest.php index 2bac6aab9b..51fe5434b7 100644 --- a/tests/WebSocketServer/ServerBootstrapTest.php +++ b/tests/WebSocketServer/ServerBootstrapTest.php @@ -4,29 +4,31 @@ namespace Hypervel\Tests\WebSocketServer; -use Hypervel\Contracts\Container\Container; +use Hypervel\Container\Container; +use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\Contracts\Http\Kernel; use Hypervel\Contracts\Log\StdoutLoggerInterface; use Hypervel\Routing\Router; use Hypervel\Tests\TestCase; use Hypervel\WebSocketServer\Server; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class ServerBootstrapTest extends TestCase { + use VerifiesDoubles; + public function testBootstrapCompilesTheRouterFromTheExtensionHook(): void { - $kernel = m::mock(Kernel::class); - $kernel->shouldReceive('bootstrap')->once(); + $kernel = Double::for(Kernel::class)->strict(); + $kernel->expects('bootstrap'); - $router = m::mock(Router::class); - $router->shouldReceive('compileAndWarm')->once(); + $router = Double::for(Router::class)->strict(); + $router->expects('compileAndWarm'); - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with(StdoutLoggerInterface::class) - ->andReturn(m::mock(StdoutLoggerInterface::class)); - $container->shouldReceive('bound')->once()->with('events')->andReturnFalse(); - $container->shouldReceive('make')->once()->with(Kernel::class)->andReturn($kernel); + $container = new Container; + $container->instance(StdoutLoggerInterface::class, Double::for(StdoutLoggerInterface::class)->strict()); + $container->instance(Kernel::class, $kernel); $server = new BootstrapRouterServer($container, $router); $server->bootstrapForServer('reverb'); @@ -37,7 +39,7 @@ public function testBootstrapCompilesTheRouterFromTheExtensionHook(): void class BootstrapRouterServer extends Server { - public function __construct(Container $container, protected Router $router) + public function __construct(ContainerContract $container, protected Router $router) { parent::__construct($container); } diff --git a/tests/WebSocketServer/ServerHandshakeTest.php b/tests/WebSocketServer/ServerHandshakeTest.php index dd9e1fb04c..89463fc167 100644 --- a/tests/WebSocketServer/ServerHandshakeTest.php +++ b/tests/WebSocketServer/ServerHandshakeTest.php @@ -31,7 +31,10 @@ use Hypervel\WebSocketServer\Exceptions\Handler\WebSocketExceptionHandler; use Hypervel\WebSocketServer\Security; use Hypervel\WebSocketServer\Server; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; +use JMac\Testing\OverriddenDouble; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -45,6 +48,8 @@ class ServerHandshakeTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('acceptedTerminationOutcomes')] public function testAcceptedHandshakeTerminatesAfterOpenAndDrainsOnce(string $outcome, array $expected): void { @@ -64,20 +69,20 @@ public function testAcceptedHandshakeTerminatesAfterOpenAndDrainsOnce(string $ou $calls[] = 'request canceled'; }); $container = $this->container($events); - $reporter = m::mock(ExceptionHandler::class); + $reporter = Double::for(ExceptionHandler::class)->strict(); if ($outcome === 'failed' || $outcome === 'wrapped') { $reporter->expects('report')->with($exception); } else { - $reporter->shouldNotReceive('report'); + $reporter->expects('report')->never(); } - $container->shouldReceive('make')->with(ExceptionHandler::class)->andReturn($reporter); - $container->shouldReceive('make')->with(Security::class)->andReturn(new Security); - $handler = m::mock(OnOpenInterface::class); - $handler->expects('onOpen')->andReturnUsing(function () use (&$calls): void { + $container->allows('make')->with(ExceptionHandler::class)->returns($reporter); + $container->allows('make')->with(Security::class)->returns(new Security); + $handler = Double::for(OnOpenInterface::class)->strict(); + $handler->expects('onOpen')->resolves(function () use (&$calls): void { $calls[] = 'open'; defer(function () use (&$calls): void { $calls[] = 'open deferred'; }); }); - $container->shouldReceive('make')->with(WebSocketStub::class)->andReturn($handler); + $container->allows('make')->with(WebSocketStub::class)->returns($handler); $middleware = new HandshakeTerminationStub(function () use (&$calls, $outcome, $exception): void { $calls[] = FdCollector::get(42); $calls[] = 'terminated'; @@ -86,10 +91,10 @@ public function testAcceptedHandshakeTerminatesAfterOpenAndDrainsOnce(string $ou throw $exception; } }); - $container->shouldReceive('make')->with(HandshakeTerminationStub::class)->andReturn($middleware); - $native = m::mock(SwooleWebSocketServer::class); - $native->expects('isEstablished')->with(42)->andReturnTrue(); - $server = new HandshakeLifecycleServer($container, $this->router(101, [HandshakeTerminationStub::class . ':value']), $native); + $container->allows('make')->with(HandshakeTerminationStub::class)->returns($middleware); + $native = Double::for(SwooleWebSocketServer::class)->strict(); + $native->expects('isEstablished')->with(42)->returns(true); + $server = new HandshakeLifecycleServer($container->instance(), $this->router(101, [HandshakeTerminationStub::class . ':value']), $native); $response = $this->response(101, onEnd: function () use (&$calls): bool { $calls[] = 'sent'; return true; @@ -134,8 +139,8 @@ public function testUncommittedHandshakeTerminatesBeforeDrainingAndReleasesConte $calls[] = 'request canceled'; }); $container = $this->container($events); - $container->shouldReceive('make')->with(Security::class)->andReturn(new Security); - $container->shouldReceive('make')->with(HandshakeTerminationStub::class)->andReturn( + $container->allows('make')->with(Security::class)->returns(new Security); + $container->allows('make')->with(HandshakeTerminationStub::class)->returns( new HandshakeTerminationStub(function () use (&$calls, $outcome, $exception): void { $calls[] = 'first'; if ($outcome !== 'success') { @@ -143,13 +148,13 @@ public function testUncommittedHandshakeTerminatesBeforeDrainingAndReleasesConte } }), ); - $container->shouldReceive('make')->with('second.middleware')->andReturn( + $container->allows('make')->with('second.middleware')->returns( new HandshakeTerminationStub(function () use (&$calls): void { $calls[] = 'second'; }), ); $server = new HandshakeLifecycleServer( - $container, + $container->instance(), $this->router($status, [HandshakeTerminationStub::class, 'second.middleware']), - m::mock(SwooleWebSocketServer::class), + Double::for(SwooleWebSocketServer::class)->strict(), ); $caught = null; @@ -190,11 +195,11 @@ public function testHandledHandshakeExceptionUsesTheRenderedStatusForDeferredWor throw $exception; }); $container = $this->container($events); - $container->expects('make')->with(SafeCaller::class)->andReturn(new SafeCaller($container)); - $handler = m::mock(WebSocketExceptionHandler::class); - $handler->expects('handle')->with($exception, m::type(Response::class))->andReturn(new Response('', 302)); - $container->expects('make')->with(WebSocketExceptionHandler::class)->andReturn($handler); - $server = new HandshakeLifecycleServer($container, m::mock(Router::class), m::mock(SwooleWebSocketServer::class)); + $container->expects('make')->with(SafeCaller::class)->returns(new SafeCaller($container->instance())); + $handler = Double::for(WebSocketExceptionHandler::class)->strict(); + $handler->expects('handle')->with($exception, Argument::type(Response::class))->returns(new Response('', 302)); + $container->expects('make')->with(WebSocketExceptionHandler::class)->returns($handler); + $server = new HandshakeLifecycleServer($container->instance(), Double::for(Router::class)->strict(), Double::for(SwooleWebSocketServer::class)->strict()); $server->onHandshake($this->request(), $this->response(302)); @@ -203,15 +208,14 @@ public function testHandledHandshakeExceptionUsesTheRenderedStatusForDeferredWor public function testDisabledHandshakeMiddlewareIsNotTerminated(): void { - $container = $this->container(); - $container->shouldReceive('bound')->with('middleware.disable')->andReturnTrue(); - $container->shouldReceive('make')->with('middleware.disable')->andReturnTrue(); - $container->shouldReceive('make')->with(Security::class)->andReturn(new Security); - $container->shouldNotReceive('make')->with(HandshakeTerminationStub::class); + $container = $this->container(middlewareDisabled: true); + $container->allows('make')->with('middleware.disable')->returns(true); + $container->allows('make')->with(Security::class)->returns(new Security); + $container->expects('make')->never()->with(HandshakeTerminationStub::class); $server = new HandshakeLifecycleServer( - $container, + $container->instance(), $this->router(403, [HandshakeTerminationStub::class]), - m::mock(SwooleWebSocketServer::class), + Double::for(SwooleWebSocketServer::class)->strict(), ); $server->onHandshake($this->request(), $this->response(403, 'Forbidden')); @@ -233,10 +237,10 @@ public function testDispatchesHttpLifecycleAroundNativeHandshakeEmission(): void } $container = $this->container($events); - $container->shouldReceive('make')->once()->with(Security::class)->andReturn(new Security); - $container->shouldReceive('make')->once()->with(WebSocketStub::class)->andReturn(new WebSocketStub); - $nativeServer = m::mock(SwooleWebSocketServer::class); - $nativeServer->shouldReceive('isEstablished')->once()->with(42)->andReturnTrue(); + $container->expects('make')->with(Security::class)->returns(new Security); + $container->expects('make')->with(WebSocketStub::class)->returns(new WebSocketStub); + $nativeServer = Double::for(SwooleWebSocketServer::class)->strict(); + $nativeServer->expects('isEstablished')->with(42)->returns(true); $response = $this->response( Response::HTTP_SWITCHING_PROTOCOLS, onEnd: function () use (&$order): bool { @@ -247,7 +251,7 @@ public function testDispatchesHttpLifecycleAroundNativeHandshakeEmission(): void ); (new HandshakeLifecycleServer( - $container, + $container->instance(), $this->router(Response::HTTP_SWITCHING_PROTOCOLS), $nativeServer, ))->onHandshake($this->request(), $response); @@ -272,18 +276,18 @@ public function testDispatchesHttpLifecycleAroundNativeHandshakeEmission(): void public function testPublishesConnectionOnlyAfterSuccessfulLiveHandshakeEmission(): void { $container = $this->container(); - $container->shouldReceive('make')->once()->with(Security::class)->andReturn(new Security); - $container->shouldReceive('make')->once()->with(WebSocketStub::class)->andReturn(new WebSocketStub); + $container->expects('make')->with(Security::class)->returns(new Security); + $container->expects('make')->with(WebSocketStub::class)->returns(new WebSocketStub); - $nativeServer = m::mock(SwooleWebSocketServer::class); - $nativeServer->shouldReceive('isEstablished')->once()->with(42)->andReturnUsing(function (): bool { + $nativeServer = Double::for(SwooleWebSocketServer::class)->strict(); + $nativeServer->expects('isEstablished')->with(42)->resolves(function (): bool { $this->assertNull(FdCollector::get(42)); return true; }); $server = new HandshakeLifecycleServer( - $container, + $container->instance(), $this->router(Response::HTTP_SWITCHING_PROTOCOLS), $nativeServer, ); @@ -302,17 +306,17 @@ public function testEmissionFailureRollsBackUnpublishedConnectionState(): void $sentEvent = $event; }); $container = $this->container($events); - $container->shouldReceive('make')->once()->with(Security::class)->andReturn(new Security); - $container->shouldReceive('make')->once()->with(WebSocketStub::class)->andReturn(new WebSocketStub); + $container->expects('make')->with(Security::class)->returns(new Security); + $container->expects('make')->with(WebSocketStub::class)->returns(new WebSocketStub); - $nativeServer = m::mock(SwooleWebSocketServer::class); - $nativeServer->shouldNotReceive('isEstablished'); + $nativeServer = Double::for(SwooleWebSocketServer::class)->strict(); + $nativeServer->expects('isEstablished')->never(); $response = $this->response(Response::HTTP_SWITCHING_PROTOCOLS, endResult: false); try { (new HandshakeLifecycleServer( - $container, + $container->instance(), $this->router(Response::HTTP_SWITCHING_PROTOCOLS), $nativeServer, ))->onHandshake($this->request(), $response); @@ -329,13 +333,13 @@ public function testEmissionFailureRollsBackUnpublishedConnectionState(): void public function testRejectedHandshakeReleasesConnectionContext(): void { $container = $this->container(); - $container->shouldReceive('make')->once()->with(Security::class)->andReturn(new Security); + $container->expects('make')->with(Security::class)->returns(new Security); - $nativeServer = m::mock(SwooleWebSocketServer::class); - $nativeServer->shouldNotReceive('isEstablished'); + $nativeServer = Double::for(SwooleWebSocketServer::class)->strict(); + $nativeServer->expects('isEstablished')->never(); (new HandshakeLifecycleServer( - $container, + $container->instance(), $this->router(Response::HTTP_FORBIDDEN), $nativeServer, ))->onHandshake($this->request(), $this->response(Response::HTTP_FORBIDDEN, 'Forbidden')); @@ -352,17 +356,17 @@ public function testUnsupportedWebSocketVersionIsRejectedBeforeRouting(): void $sentEvent = $event; }); $container = $this->container($events); - $container->shouldReceive('make')->once()->with(Security::class)->andReturn(new Security); - $container->shouldReceive('make')->once()->with(SafeCaller::class)->andReturn(new SafeCaller($container)); - $container->shouldReceive('make')->once()->with(WebSocketExceptionHandler::class)->andReturn( - new WebSocketExceptionHandler(m::mock(StdoutLoggerInterface::class)->shouldIgnoreMissing()), + $container->expects('make')->with(Security::class)->returns(new Security); + $container->expects('make')->with(SafeCaller::class)->returns(new SafeCaller($container->instance())); + $container->expects('make')->with(WebSocketExceptionHandler::class)->returns( + new WebSocketExceptionHandler(Double::for(StdoutLoggerInterface::class)), ); - $router = m::mock(Router::class); - $router->shouldNotReceive('dispatchToCallback'); - $nativeServer = m::mock(SwooleWebSocketServer::class); - $nativeServer->shouldNotReceive('isEstablished'); + $router = Double::for(Router::class)->strict(); + $router->expects('dispatchToCallback')->never(); + $nativeServer = Double::for(SwooleWebSocketServer::class)->strict(); + $nativeServer->expects('isEstablished')->never(); - (new HandshakeLifecycleServer($container, $router, $nativeServer))->onHandshake( + (new HandshakeLifecycleServer($container->instance(), $router, $nativeServer))->onHandshake( $this->request(version: '8'), $this->response(Response::HTTP_UPGRADE_REQUIRED, 'sec-websocket-version is unsupported!'), ); @@ -378,18 +382,18 @@ public function testUnsupportedWebSocketVersionIsRejectedBeforeRouting(): void public function testConnectionClosedDuringEmissionIsNotPublishedAfterward(): void { $container = $this->container(); - $container->shouldReceive('make')->once()->with(Security::class)->andReturn(new Security); - $container->shouldReceive('make')->once()->with(WebSocketStub::class)->andReturn(new WebSocketStub); + $container->expects('make')->with(Security::class)->returns(new Security); + $container->expects('make')->with(WebSocketStub::class)->returns(new WebSocketStub); - $nativeServer = m::mock(SwooleWebSocketServer::class); - $nativeServer->shouldReceive('isEstablished')->once()->with(42)->andReturnUsing(function (): bool { + $nativeServer = Double::for(SwooleWebSocketServer::class)->strict(); + $nativeServer->expects('isEstablished')->with(42)->resolves(function (): bool { $this->assertNull(FdCollector::get(42)); return false; }); (new HandshakeLifecycleServer( - $container, + $container->instance(), $this->router(Response::HTTP_SWITCHING_PROTOCOLS), $nativeServer, ))->onHandshake($this->request(), $this->response(Response::HTTP_SWITCHING_PROTOCOLS)); @@ -408,24 +412,26 @@ public function testHandshakeCancellationSkipsFallbackEmissionAndReleasesContext }); } $container = $this->container($events); - $container->shouldReceive('make')->once()->with(Security::class)->andReturn(new Security); + $container->expects('make')->with(Security::class)->returns(new Security); - $router = m::mock(Router::class); - $router->shouldReceive('dispatchToCallback')->once() - ->andReturnUsing(function (): never { + $router = Double::for(Router::class)->strict(); + $router->expects('dispatchToCallback') + ->resolves(function (): never { WebSocketContext::set('middleware.value', 'preserved'); throw new CanceledException; }); - $nativeServer = m::mock(SwooleWebSocketServer::class); - $nativeServer->shouldNotReceive('isEstablished'); + $nativeServer = Double::for(SwooleWebSocketServer::class)->strict(); + $nativeServer->expects('isEstablished')->never(); - $response = m::mock(SwooleResponse::class); - $response->shouldReceive('status', 'header', 'end')->never(); + $response = Double::for(SwooleResponse::class)->strict(); + $response->expects('status')->never(); + $response->expects('header')->never(); + $response->expects('end')->never(); try { - (new HandshakeLifecycleServer($container, $router, $nativeServer)) + (new HandshakeLifecycleServer($container->instance(), $router, $nativeServer)) ->onHandshake($this->request(), $response); $this->fail('Expected handshake cancellation to be rethrown.'); } catch (CanceledException) { @@ -447,13 +453,13 @@ public function testHandshakeCancellationReportsTheHeldFailure(): void $canceled = $event; }); $container = $this->container($events); - $container->shouldReceive('make')->with(Security::class)->andReturn(new Security); - $reporter = m::mock(ExceptionHandler::class); + $container->allows('make')->with(Security::class)->returns(new Security); + $reporter = Double::for(ExceptionHandler::class)->strict(); $reporter->expects('report')->with($heldFailure); $reportingContainer = new BaseContainer; $reportingContainer->instance(ExceptionHandler::class, $reporter); BaseContainer::setInstance($reportingContainer); - $server = new HandshakeLifecycleServer($container, $this->router(302), m::mock(SwooleWebSocketServer::class)); + $server = new HandshakeLifecycleServer($container->instance(), $this->router(302), Double::for(SwooleWebSocketServer::class)->strict()); try { $server->onHandshake($this->request(), $this->response(302)); @@ -478,16 +484,16 @@ public function testConnectionOpeningFailureIsRenderedAndReleasesContext(): void $handledEvent = $event; }); $container = $this->container($events); - $container->shouldNotReceive('make')->with(Security::class); - $container->shouldReceive('make')->once()->with(SafeCaller::class) - ->andReturn(new SafeCaller($container)); - $router = m::mock(Router::class); - $router->shouldNotReceive('dispatchToCallback'); - $nativeServer = m::mock(SwooleWebSocketServer::class); - $nativeServer->shouldNotReceive('isEstablished'); + $container->expects('make')->never()->with(Security::class); + $container->expects('make')->with(SafeCaller::class) + ->returns(new SafeCaller($container->instance())); + $router = Double::for(Router::class)->strict(); + $router->expects('dispatchToCallback')->never(); + $nativeServer = Double::for(SwooleWebSocketServer::class)->strict(); + $nativeServer->expects('isEstablished')->never(); (new RenderingHandshakeLifecycleServer( - $container, + $container->instance(), $router, $nativeServer, ))->onHandshake($this->request(), $this->response( @@ -508,16 +514,18 @@ public function testConnectionOpeningCancellationSkipsFallbackEmissionAndRelease throw new CanceledException; }); $container = $this->container($events); - $container->shouldNotReceive('make')->with(Security::class); - $router = m::mock(Router::class); - $router->shouldNotReceive('dispatchToCallback'); - $nativeServer = m::mock(SwooleWebSocketServer::class); - $nativeServer->shouldNotReceive('isEstablished'); - $response = m::mock(SwooleResponse::class); - $response->shouldReceive('status', 'header', 'end')->never(); + $container->expects('make')->never()->with(Security::class); + $router = Double::for(Router::class)->strict(); + $router->expects('dispatchToCallback')->never(); + $nativeServer = Double::for(SwooleWebSocketServer::class)->strict(); + $nativeServer->expects('isEstablished')->never(); + $response = Double::for(SwooleResponse::class)->strict(); + $response->expects('status')->never(); + $response->expects('header')->never(); + $response->expects('end')->never(); try { - (new HandshakeLifecycleServer($container, $router, $nativeServer)) + (new HandshakeLifecycleServer($container->instance(), $router, $nativeServer)) ->onHandshake($this->request(), $response); $this->fail('Expected connection opening cancellation to be rethrown.'); } catch (CanceledException) { @@ -529,16 +537,16 @@ public function testConnectionOpeningCancellationSkipsFallbackEmissionAndRelease /** * Create the package container mock. */ - protected function container(?Dispatcher $events = null): Container + protected function container(?Dispatcher $events = null, bool $middlewareDisabled = false): OverriddenDouble { - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with(StdoutLoggerInterface::class) - ->andReturn(m::mock(StdoutLoggerInterface::class)->shouldIgnoreMissing()); - $container->shouldReceive('bound')->once()->with('events')->andReturn($events !== null); - $container->shouldReceive('bound')->with('middleware.disable')->andReturnFalse()->byDefault(); + $container = Double::for(Container::class, override: true)->strict(); + $container->expects('make')->with(StdoutLoggerInterface::class) + ->returns(Double::for(StdoutLoggerInterface::class)); + $container->expects('bound')->with('events')->returns($events !== null); + $container->allows('bound')->with('middleware.disable')->returns($middlewareDisabled); if ($events !== null) { - $container->shouldReceive('make')->once()->with('events')->andReturn($events); + $container->expects('make')->with('events')->returns($events); } return $container; @@ -549,14 +557,14 @@ protected function container(?Dispatcher $events = null): Container */ protected function router(int $status, array $middleware = []): Router { - $route = m::mock(Route::class); - $route->shouldReceive('getControllerClass')->andReturn(WebSocketStub::class); - - $router = m::mock(Router::class); - $router->shouldReceive('gatherRouteMiddleware')->with($route)->andReturn($middleware); - $router->shouldReceive('dispatchToCallback')->once() - ->with(m::type(HttpRequest::class), m::type(Closure::class)) - ->andReturnUsing(function (HttpRequest $request) use ($route, $status): Response { + $route = Double::for(Route::class)->strict(); + $route->allows('getControllerClass')->returns(WebSocketStub::class); + + $router = Double::for(Router::class)->strict(); + $router->allows('gatherRouteMiddleware')->with($route)->returns($middleware); + $router->expects('dispatchToCallback') + ->with(Argument::type(HttpRequest::class), Argument::type(Closure::class)) + ->resolves(function (HttpRequest $request) use ($route, $status): Response { WebSocketContext::set('middleware.value', 'preserved'); $request->setRouteResolver(static fn (): Route => $route); @@ -571,7 +579,7 @@ protected function router(int $status, array $middleware = []): Router */ protected function request(string $version = Security::VERSION): SwooleRequest { - $request = m::mock(SwooleRequest::class); + $request = Double::for(SwooleRequest::class)->strict(); $request->fd = 42; $request->server = [ 'request_method' => 'get', @@ -586,7 +594,7 @@ protected function request(string $version = Security::VERSION): SwooleRequest $request->post = []; $request->cookie = []; $request->files = []; - $request->shouldReceive('rawContent')->once()->andReturnFalse(); + $request->expects('rawContent')->returns(false); return $request; } @@ -600,14 +608,14 @@ protected function response( bool $endResult = true, ?Closure $onEnd = null, ): SwooleResponse { - $response = m::mock(SwooleResponse::class); - $response->shouldReceive('status')->once()->with($status)->andReturnTrue(); - $response->shouldReceive('header')->zeroOrMoreTimes()->andReturnTrue(); - $expectation = $response->shouldReceive('end')->once()->with($content); + $response = Double::for(SwooleResponse::class)->strict(); + $response->expects('status')->with($status)->returns(true); + $response->allows('header')->returns(true); + $expectation = $response->expects('end')->with($content); $onEnd === null - ? $expectation->andReturn($endResult) - : $expectation->andReturnUsing($onEnd); + ? $expectation->returns($endResult) + : $expectation->resolves($onEnd); return $response; } diff --git a/tests/WebSocketServer/ServerTest.php b/tests/WebSocketServer/ServerTest.php index 5be6ccd282..59d594d2bf 100644 --- a/tests/WebSocketServer/ServerTest.php +++ b/tests/WebSocketServer/ServerTest.php @@ -31,7 +31,10 @@ use Hypervel\WebSocketServer\Events\MessageReceived; use Hypervel\WebSocketServer\Exceptions\Handler\WebSocketExceptionHandler; use Hypervel\WebSocketServer\Server; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; +use JMac\Testing\OverriddenDouble; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -47,6 +50,8 @@ class ServerTest extends TestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -72,10 +77,10 @@ public function testDeferOnOpenCallsOnOpen(): void WebSocketStub::$coroutineId = 0; $container = $this->createContainer(); - $server = new Server($container); + $server = new Server($container->instance()); $invoker = new ClassInvoker($server); - $swooleServer = m::mock(WebSocketSwooleServer::class); + $swooleServer = Double::for(WebSocketSwooleServer::class)->strict(); // Run deferOnOpen inside a child coroutine so that defer() fires // when that coroutine exits, before we make our assertions. @@ -90,126 +95,94 @@ public function testDeferOnOpenCallsOnOpen(): void public function testDeferOnOpenLogsExceptionFromOnOpen(): void { - $logged = false; - - $logger = m::mock(StdoutLoggerInterface::class)->shouldIgnoreMissing(); - $logger->shouldReceive('error')->once()->with(m::on( - function (string $message) use (&$logged): bool { - $logged = str_contains($message, 'onOpen failed'); - - return $logged; - } + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error')->with(Argument::satisfies( + fn (string $message): bool => str_contains($message, 'onOpen failed') )); $container = $this->createContainer($logger); - $server = new Server($container); + $server = new Server($container->instance()); $invoker = new ClassInvoker($server); - $swooleServer = m::mock(WebSocketSwooleServer::class); + $swooleServer = Double::for(WebSocketSwooleServer::class)->strict(); $coroutineId = Coroutine::create(function () use ($invoker, $swooleServer) { $invoker->deferOnOpen(new SwooleRequest, new WebSocketThrowingStub, $swooleServer, 1, new HttpRequest, new Response('', 101)); }); $this->waitForCoroutine($coroutineId); - - $this->assertTrue($logged); } public function testConnectionOpenedEventIsDispatched(): void { - $dispatched = false; - - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionOpened::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on( - function (ConnectionOpened $event) use (&$dispatched) { - $dispatched = ($event->fd === 1 && $event->server === 'websocket'); - return $dispatched; - } + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->allows('hasListeners')->with(ConnectionOpened::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::satisfies( + fn (ConnectionOpened $event): bool => $event->fd === 1 && $event->server === 'websocket' )); $container = $this->createContainer(dispatcher: $dispatcher); - $server = new Server($container); + $server = new Server($container->instance()); $invoker = new ClassInvoker($server); - $swooleServer = m::mock(WebSocketSwooleServer::class); + $swooleServer = Double::for(WebSocketSwooleServer::class)->strict(); $coroutineId = Coroutine::create(function () use ($invoker, $swooleServer) { $invoker->deferOnOpen(new SwooleRequest, new WebSocketStub, $swooleServer, 1, new HttpRequest, new Response('', 101)); }); $this->waitForCoroutine($coroutineId); - - $this->assertTrue($dispatched); } public function testConnectionOpenedEventNotDispatchedWithoutListeners(): void { - $hasListenersChecked = false; - - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionOpened::class)->andReturnUsing( - function () use (&$hasListenersChecked): bool { - $hasListenersChecked = true; - - return false; - } - ); - $dispatcher->shouldNotReceive('dispatch'); + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(ConnectionOpened::class)->returns(false); + $dispatcher->expects('dispatch')->never(); $container = $this->createContainer(dispatcher: $dispatcher); - $server = new Server($container); + $server = new Server($container->instance()); $invoker = new ClassInvoker($server); - $swooleServer = m::mock(WebSocketSwooleServer::class); + $swooleServer = Double::for(WebSocketSwooleServer::class)->strict(); $coroutineId = Coroutine::create(function () use ($invoker, $swooleServer) { $invoker->deferOnOpen(new SwooleRequest, new WebSocketStub, $swooleServer, 1, new HttpRequest, new Response('', 101)); }); $this->waitForCoroutine($coroutineId); - - $this->assertTrue($hasListenersChecked); } public function testConnectionOpenedEventDispatchedEvenWhenOnOpenThrows(): void { - $dispatched = false; - - $logger = m::mock(StdoutLoggerInterface::class)->shouldIgnoreMissing(); - $logger->shouldReceive('error')->once(); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error'); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionOpened::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on( - function (ConnectionOpened $event) use (&$dispatched) { - $dispatched = ($event->fd === 1); - return $dispatched; - } + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->allows('hasListeners')->with(ConnectionOpened::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::satisfies( + fn (ConnectionOpened $event): bool => $event->fd === 1 )); $container = $this->createContainer($logger, $dispatcher); - $server = new Server($container); + $server = new Server($container->instance()); $invoker = new ClassInvoker($server); - $swooleServer = m::mock(WebSocketSwooleServer::class); + $swooleServer = Double::for(WebSocketSwooleServer::class)->strict(); $coroutineId = Coroutine::create(function () use ($invoker, $swooleServer) { $invoker->deferOnOpen(new SwooleRequest, new WebSocketThrowingStub, $swooleServer, 1, new HttpRequest, new Response('', 101)); }); $this->waitForCoroutine($coroutineId); - - $this->assertTrue($dispatched); } public function testOnOpenRunsWhenConnectionOpenedEventThrows(): void { WebSocketStub::$coroutineId = 0; - $logger = m::mock(StdoutLoggerInterface::class)->shouldIgnoreMissing(); - $logger->shouldReceive('error')->once()->with(m::type('string')); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error')->with(Argument::type('string')); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionOpened::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->andThrow(new RuntimeException('event failed')); + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->allows('hasListeners')->with(ConnectionOpened::class)->returns(true); + $dispatcher->expects('dispatch')->throws(new RuntimeException('event failed')); - $server = new Server($this->createContainer($logger, $dispatcher)); + $server = new Server($this->createContainer($logger, $dispatcher)->instance()); $invoker = new ClassInvoker($server); - $swooleServer = m::mock(WebSocketSwooleServer::class); + $swooleServer = Double::for(WebSocketSwooleServer::class)->strict(); $coroutineId = Coroutine::create(function () use ($invoker, $swooleServer) { $invoker->deferOnOpen(new SwooleRequest, new WebSocketStub, $swooleServer, 1, new HttpRequest, new Response('', 101)); @@ -228,9 +201,9 @@ public function testMessageDeferredWorkFollowsTheCallbackOutcome(?string $failur 'wrapped' => new RuntimeException('message cleanup failed', previous: new CanceledException), default => new RuntimeException('message failed'), }; - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->andReturnUsing(function (object $event) use (&$calls, $failureAt, $exception): void { + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->allows('hasListeners')->returns(true); + $dispatcher->allows('dispatch')->resolves(function (object $event) use (&$calls, $failureAt, $exception): void { $phase = $event instanceof MessageReceived ? 'received' : 'handled'; $calls[] = $phase; @@ -243,20 +216,20 @@ public function testMessageDeferredWorkFollowsTheCallbackOutcome(?string $failur throw $exception; } }); - $handler = m::mock(OnMessageInterface::class); - $handler->shouldReceive('onMessage')->andReturnUsing(function () use (&$calls, $failureAt, $exception): void { + $handler = Double::for(OnMessageInterface::class)->strict(); + $handler->allows('onMessage')->resolves(function () use (&$calls, $failureAt, $exception): void { $calls[] = 'handler'; if ($failureAt === 'handler') { throw $exception; } }); $container = $this->createContainer(dispatcher: $dispatcher); - $container->shouldReceive('make')->with(OnMessageInterface::class)->andReturn($handler); + $container->allows('make')->with(OnMessageInterface::class)->returns($handler); FdCollector::set(1, OnMessageInterface::class); $frame = new Frame; $frame->fd = 1; - (new Server($container))->onMessage(m::mock(WebSocketSwooleServer::class), $frame); + (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame); $this->assertSame($expected, $calls); } @@ -284,22 +257,22 @@ public static function messageDeferredOutcomes(): array public function testOpenDeferredWorkRunsAfterTheHandler(bool $fail): void { $calls = []; - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionOpened::class)->andReturnTrue(); - $dispatcher->expects('dispatch')->andReturnUsing(function () use (&$calls): void { + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->allows('hasListeners')->with(ConnectionOpened::class)->returns(true); + $dispatcher->expects('dispatch')->resolves(function () use (&$calls): void { $calls[] = 'opened'; defer(function () use (&$calls): void { $calls[] = 'event deferred'; })->always(); }); - $handler = m::mock(OnOpenInterface::class); - $handler->expects('onOpen')->andReturnUsing(function () use (&$calls, $fail): void { + $handler = Double::for(OnOpenInterface::class)->strict(); + $handler->expects('onOpen')->resolves(function () use (&$calls, $fail): void { $calls[] = 'handler'; defer(function () use (&$calls): void { $calls[] = 'handler deferred'; }); if ($fail) { throw new RuntimeException('open failed'); } }); - $server = new Server($this->createContainer(dispatcher: $dispatcher)); - $native = m::mock(WebSocketSwooleServer::class); + $server = new Server($this->createContainer(dispatcher: $dispatcher)->instance()); + $native = Double::for(WebSocketSwooleServer::class)->strict(); (new Waiter(1))->wait(fn () => (new ClassInvoker($server))->deferOnOpen( new SwooleRequest, @@ -319,11 +292,12 @@ public function testOpenDeferredWorkRunsAfterTheHandler(bool $fail): void public function testCloseDeferredWorkRunsBeforeConnectionContextIsReleased(bool $fail): void { $calls = []; - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionClosed::class)->andReturnTrue(); - $dispatcher->expects('dispatch')->andReturnUsing(function () use (&$calls): void { $calls[] = 'closed'; }); - $handler = m::mock(OnCloseInterface::class); - $handler->expects('onClose')->andReturnUsing(function () use (&$calls, $fail): void { + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->allows('hasListeners')->with(ConnectionClosing::class)->returns(false); + $dispatcher->allows('hasListeners')->with(ConnectionClosed::class)->returns(true); + $dispatcher->expects('dispatch')->resolves(function () use (&$calls): void { $calls[] = 'closed'; }); + $handler = Double::for(OnCloseInterface::class)->strict(); + $handler->expects('onClose')->resolves(function () use (&$calls, $fail): void { defer(function () use (&$calls): void { $calls[] = 'deferred'; }); defer(function () use (&$calls): void { $calls[] = WebSocketContext::get('value'); })->always(); if ($fail) { @@ -331,12 +305,12 @@ public function testCloseDeferredWorkRunsBeforeConnectionContextIsReleased(bool } }); $container = $this->createContainer(dispatcher: $dispatcher); - $container->shouldReceive('make')->with(OnCloseInterface::class)->andReturn($handler); + $container->allows('make')->with(OnCloseInterface::class)->returns($handler); FdCollector::set(1, OnCloseInterface::class); CoroutineContext::set(WebSocketContext::FD, 1); WebSocketContext::set('value', 'context'); - (new Server($container))->onClose(m::mock(SwooleServer::class), 1, 0); + (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0); $this->assertSame($fail ? ['closed', 'context'] : ['closed', 'deferred', 'context'], $calls); $this->assertNull(WebSocketContext::get('value', fd: 1)); @@ -354,18 +328,18 @@ public static function callbackFailures(): array public function testCancellationDuringDeferredWorkStillReleasesConnectionContext(): void { $calls = []; - $handler = m::mock(OnCloseInterface::class); - $handler->expects('onClose')->andReturnUsing(function () use (&$calls): void { + $handler = Double::for(OnCloseInterface::class)->strict(); + $handler->expects('onClose')->resolves(function () use (&$calls): void { defer(static fn () => throw new CanceledException); defer(function () use (&$calls): void { $calls[] = 'later'; })->always(); }); $container = $this->createContainer(); - $container->shouldReceive('make')->with(OnCloseInterface::class)->andReturn($handler); + $container->allows('make')->with(OnCloseInterface::class)->returns($handler); FdCollector::set(1, OnCloseInterface::class); CoroutineContext::set(WebSocketContext::FD, 1); WebSocketContext::set('value', 'context'); - (new Server($container))->onClose(m::mock(SwooleServer::class), 1, 0); + (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0); $this->assertSame([], $calls); $this->assertNull(WebSocketContext::get('value', fd: 1)); @@ -374,14 +348,14 @@ public function testCancellationDuringDeferredWorkStillReleasesConnectionContext public function testMessageLifecycleEventsAreDispatchedInOrder(): void { - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageReceived::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on( - fn (MessageReceived $event) => $event->fd === 1 && $event->server === 'websocket' + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::satisfies( + fn (mixed $event): bool => $event instanceof MessageReceived && $event->fd === 1 && $event->server === 'websocket' ))->ordered(); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageHandled::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on( - fn (MessageHandled $event) => WebSocketMessageStub::$messageHandled + $dispatcher->expects('hasListeners')->with(MessageHandled::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::satisfies( + fn (mixed $event): bool => $event instanceof MessageHandled && WebSocketMessageStub::$messageHandled && $event->fd === 1 && $event->frame->data === 'test' && $event->server === 'websocket' @@ -389,12 +363,12 @@ public function testMessageLifecycleEventsAreDispatchedInOrder(): void ))->ordered(); $container = $this->createContainer(dispatcher: $dispatcher); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); FdCollector::set(1, WebSocketMessageStub::class); - $server = new Server($container); - $swooleServer = m::mock(WebSocketSwooleServer::class); + $server = new Server($container->instance()); + $swooleServer = Double::for(WebSocketSwooleServer::class)->strict(); $frame = new Frame; $frame->fd = 1; @@ -407,18 +381,18 @@ public function testMessageLifecycleEventsAreDispatchedInOrder(): void public function testMessageReceivedEventNotDispatchedWithoutListeners(): void { - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageReceived::class)->andReturnFalse(); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageHandled::class)->andReturnFalse(); - $dispatcher->shouldNotReceive('dispatch'); + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(false); + $dispatcher->expects('hasListeners')->with(MessageHandled::class)->returns(false); + $dispatcher->expects('dispatch')->never(); $container = $this->createContainer(dispatcher: $dispatcher); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); FdCollector::set(1, WebSocketMessageStub::class); - $server = new Server($container); - $swooleServer = m::mock(WebSocketSwooleServer::class); + $server = new Server($container->instance()); + $swooleServer = Double::for(WebSocketSwooleServer::class)->strict(); $frame = new Frame; $frame->fd = 1; @@ -433,26 +407,26 @@ public function testMessageHandlerRunsWhenMessageReceivedEventThrows(): void { $exception = new RuntimeException('event failed'); - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $exceptionHandler->shouldReceive('report')->once()->with($exception); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $exceptionHandler->expects('report')->with($exception); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageReceived::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(MessageReceived::class))->andThrow($exception); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageHandled::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on( - fn (MessageHandled $event) => WebSocketMessageStub::$messageHandled + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(MessageReceived::class))->throws($exception); + $dispatcher->expects('hasListeners')->with(MessageHandled::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::satisfies( + fn (mixed $event): bool => $event instanceof MessageHandled && WebSocketMessageStub::$messageHandled && $event->exception === $exception )); $container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); FdCollector::set(1, WebSocketMessageStub::class); $frame = new Frame; $frame->fd = 1; - (new Server($container))->onMessage(m::mock(WebSocketSwooleServer::class), $frame); + (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame); $this->assertTrue(WebSocketMessageStub::$messageHandled); } @@ -464,24 +438,24 @@ public function testMessageReceivedCancellationSkipsTheHandlerAndCompletesWithTh $cancellation = $wrapped ? new RuntimeException('received cleanup failed', previous: new CanceledException) : new CanceledException; - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $exceptionHandler->shouldReceive('report')->times($wrapped ? 1 : 0)->with($cancellation); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageReceived::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(MessageReceived::class))->andThrow($cancellation); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageHandled::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on( - fn (MessageHandled $event) => $event->exception === $cancellation + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $exceptionHandler->expects('report')->times($wrapped ? 1 : 0)->with($cancellation); + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(MessageReceived::class))->throws($cancellation); + $dispatcher->expects('hasListeners')->with(MessageHandled::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::satisfies( + fn (mixed $event): bool => $event instanceof MessageHandled && $event->exception === $cancellation )); $container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); FdCollector::set(1, WebSocketMessageStub::class); $frame = new Frame; $frame->fd = 1; - (new Server($container))->onMessage(m::mock(WebSocketSwooleServer::class), $frame); + (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame); $this->assertFalse(WebSocketMessageStub::$messageHandled); } @@ -491,27 +465,27 @@ public function testMessageHandlerFailuresAreReportedWithoutEscaping(): void $exception = new RuntimeException('message failed'); WebSocketMessageStub::$messageException = $exception; - $logger = m::mock(StdoutLoggerInterface::class)->shouldIgnoreMissing(); - $logger->shouldNotReceive('error'); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error')->never(); - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $exceptionHandler->shouldReceive('report')->once()->with($exception); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $exceptionHandler->expects('report')->with($exception); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageReceived::class)->andReturnFalse(); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageHandled::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on( - fn (MessageHandled $event) => $event->exception === $exception + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(false); + $dispatcher->expects('hasListeners')->with(MessageHandled::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::satisfies( + fn (mixed $event): bool => $event instanceof MessageHandled && $event->exception === $exception )); $container = $this->createContainer($logger, $dispatcher, $exceptionHandler); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); FdCollector::set(1, WebSocketMessageStub::class); $frame = new Frame; $frame->fd = 1; - (new Server($container))->onMessage(m::mock(WebSocketSwooleServer::class), $frame); + (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame); $this->assertTrue(WebSocketMessageStub::$messageHandled); } @@ -523,29 +497,29 @@ public function testMessageHandledKeepsTheFirstFailure(): void WebSocketMessageStub::$messageException = $messageException; $reported = []; - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $exceptionHandler->shouldReceive('report')->twice()->andReturnUsing( + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $exceptionHandler->expects('report')->times(2)->resolves( function (Throwable $throwable) use (&$reported): void { $reported[] = $throwable; } ); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageReceived::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(MessageReceived::class))->andThrow($receivedException); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageHandled::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on( - fn (MessageHandled $event) => $event->exception === $receivedException + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(MessageReceived::class))->throws($receivedException); + $dispatcher->expects('hasListeners')->with(MessageHandled::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::satisfies( + fn (mixed $event): bool => $event instanceof MessageHandled && $event->exception === $receivedException )); $container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); FdCollector::set(1, WebSocketMessageStub::class); $frame = new Frame; $frame->fd = 1; - (new Server($container))->onMessage(m::mock(WebSocketSwooleServer::class), $frame); + (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame); $this->assertSame([$receivedException, $messageException], $reported); } @@ -558,27 +532,27 @@ public function testMessageHandlerCancellationCompletesWithTheKnownOutcome(bool $receivedFailure = new RuntimeException('received failed'); WebSocketMessageStub::$messageException = $cancellation; - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $exceptionHandler->shouldReceive('report')->times($receivedFails ? 1 : 0)->with($receivedFailure); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $exceptionHandler->expects('report')->times($receivedFails ? 1 : 0)->with($receivedFailure); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageReceived::class)->andReturn($receivedFails); + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns($receivedFails); if ($receivedFails) { - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(MessageReceived::class))->andThrow($receivedFailure); + $dispatcher->expects('dispatch')->with(Argument::type(MessageReceived::class))->throws($receivedFailure); } - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageHandled::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on( - fn (MessageHandled $event) => $event->exception === ($receivedFails ? $receivedFailure : $cancellation) + $dispatcher->expects('hasListeners')->with(MessageHandled::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::satisfies( + fn (mixed $event): bool => $event instanceof MessageHandled && $event->exception === ($receivedFails ? $receivedFailure : $cancellation) )); $container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); FdCollector::set(1, WebSocketMessageStub::class); $frame = new Frame; $frame->fd = 1; - (new Server($container))->onMessage(m::mock(WebSocketSwooleServer::class), $frame); + (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame); $this->assertTrue(WebSocketMessageStub::$messageHandled); } @@ -590,22 +564,22 @@ public function testCanceledMessageCompletionContainsListenerFailures(bool $canc WebSocketMessageStub::$messageException = new CanceledException; $listenerFailure = $cancel ? new CanceledException : new RuntimeException('completion failed'); - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $exceptionHandler->shouldReceive('report')->times($cancel ? 0 : 1)->with($listenerFailure); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $exceptionHandler->expects('report')->times($cancel ? 0 : 1)->with($listenerFailure); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageReceived::class)->andReturnFalse(); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageHandled::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(MessageHandled::class))->andThrow($listenerFailure); + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(false); + $dispatcher->expects('hasListeners')->with(MessageHandled::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(MessageHandled::class))->throws($listenerFailure); $container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); FdCollector::set(1, WebSocketMessageStub::class); $frame = new Frame; $frame->fd = 1; - (new Server($container))->onMessage(m::mock(WebSocketSwooleServer::class), $frame); + (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame); $this->assertTrue(WebSocketMessageStub::$messageHandled); } @@ -614,73 +588,73 @@ public function testMessageHandledFailureIsReportedWithoutEscaping(): void { $exception = new RuntimeException('completion failed'); - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $exceptionHandler->shouldReceive('report')->once()->with($exception); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $exceptionHandler->expects('report')->with($exception); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageReceived::class)->andReturnFalse(); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageHandled::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(MessageHandled::class))->andThrow($exception); + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(false); + $dispatcher->expects('hasListeners')->with(MessageHandled::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(MessageHandled::class))->throws($exception); $container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); FdCollector::set(1, WebSocketMessageStub::class); $frame = new Frame; $frame->fd = 1; - (new Server($container))->onMessage(m::mock(WebSocketSwooleServer::class), $frame); + (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame); $this->assertTrue(WebSocketMessageStub::$messageHandled); } public function testMessageHandledCancellationIsContained(): void { - $logger = m::mock(StdoutLoggerInterface::class)->shouldIgnoreMissing(); - $logger->shouldNotReceive('error'); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error')->never(); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageReceived::class)->andReturnFalse(); - $dispatcher->shouldReceive('hasListeners')->once()->with(MessageHandled::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(MessageHandled::class))->andThrow(new CanceledException); + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(false); + $dispatcher->expects('hasListeners')->with(MessageHandled::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(MessageHandled::class))->throws(new CanceledException); $container = $this->createContainer($logger, $dispatcher); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); FdCollector::set(1, WebSocketMessageStub::class); $frame = new Frame; $frame->fd = 1; - (new Server($container))->onMessage(m::mock(WebSocketSwooleServer::class), $frame); + (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame); $this->assertTrue(WebSocketMessageStub::$messageHandled); } public function testConnectionLifecycleEventsAreDispatchedAroundTheCloseHandler(): void { - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionClosing::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on( - fn (ConnectionClosing $event) => ! WebSocketMessageStub::$closeHandled + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->allows('hasListeners')->with(ConnectionClosing::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::satisfies( + fn (mixed $event): bool => $event instanceof ConnectionClosing && ! WebSocketMessageStub::$closeHandled && $event->fd === 1 && $event->reactorId === 0 && $event->server === 'websocket' ))->ordered(); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionClosed::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on( - fn (ConnectionClosed $event) => WebSocketMessageStub::$closeHandled + $dispatcher->allows('hasListeners')->with(ConnectionClosed::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::satisfies( + fn (mixed $event): bool => $event instanceof ConnectionClosed && WebSocketMessageStub::$closeHandled && $event->fd === 1 && $event->reactorId === 0 && $event->server === 'websocket' ))->ordered(); $container = $this->createContainer(dispatcher: $dispatcher); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); FdCollector::set(1, WebSocketMessageStub::class); - $server = new Server($container); - $swooleServer = m::mock(SwooleServer::class); + $server = new Server($container->instance()); + $swooleServer = Double::for(SwooleServer::class)->strict(); $server->onClose($swooleServer, 1, 0); @@ -689,18 +663,18 @@ public function testConnectionLifecycleEventsAreDispatchedAroundTheCloseHandler( public function testConnectionClosedEventNotDispatchedWithoutListeners(): void { - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionClosing::class)->andReturnFalse(); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionClosed::class)->andReturnFalse(); - $dispatcher->shouldNotReceive('dispatch'); + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->allows('hasListeners')->with(ConnectionClosing::class)->returns(false); + $dispatcher->allows('hasListeners')->with(ConnectionClosed::class)->returns(false); + $dispatcher->expects('dispatch')->never(); $container = $this->createContainer(dispatcher: $dispatcher); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); FdCollector::set(1, WebSocketMessageStub::class); - $server = new Server($container); - $swooleServer = m::mock(SwooleServer::class); + $server = new Server($container->instance()); + $swooleServer = Double::for(SwooleServer::class)->strict(); $server->onClose($swooleServer, 1, 0); @@ -710,26 +684,25 @@ public function testConnectionClosedEventNotDispatchedWithoutListeners(): void public function testConnectionClosingFailureDoesNotSkipCloseCallbacksOrCleanup(): void { $exception = new RuntimeException('closing event failed'); - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $exceptionHandler->shouldReceive('report')->once()->with($exception); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionClosing::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(ConnectionClosing::class)) - ->andThrow($exception); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionClosed::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(ConnectionClosed::class)); + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $exceptionHandler->expects('report')->with($exception); + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->allows('hasListeners')->with(ConnectionClosing::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(ConnectionClosing::class)) + ->throws($exception); + $dispatcher->allows('hasListeners')->with(ConnectionClosed::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(ConnectionClosed::class)); $container = $this->createContainer( dispatcher: $dispatcher, exceptionHandler: $exceptionHandler, ); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); CoroutineContext::set(WebSocketContext::FD, 1); WebSocketContext::set('connection.id', 'one'); FdCollector::set(1, WebSocketMessageStub::class); - (new Server($container))->onClose(m::mock(SwooleServer::class), 1, 0); + (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0); $this->assertTrue(WebSocketMessageStub::$closeHandled); $this->assertNull(FdCollector::get(1)); @@ -745,25 +718,24 @@ public function testConnectionClosingCancellationSkipsCloseCallbacksButCompletes : new CanceledException; $listenerFailure = new RuntimeException('closed listener failed'); $reported = []; - $exceptionHandler = m::mock(ExceptionHandlerContract::class); - $exceptionHandler->shouldReceive('report')->andReturnUsing(function (Throwable $throwable) use (&$reported): void { + $exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict(); + $exceptionHandler->allows('report')->resolves(function (Throwable $throwable) use (&$reported): void { $reported[] = $throwable; }); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionClosing::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(ConnectionClosing::class)) - ->andThrow($cancellation); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionClosed::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(ConnectionClosed::class))->andThrow($listenerFailure); + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->allows('hasListeners')->with(ConnectionClosing::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(ConnectionClosing::class)) + ->throws($cancellation); + $dispatcher->allows('hasListeners')->with(ConnectionClosed::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(ConnectionClosed::class))->throws($listenerFailure); $container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler); - $container->shouldNotReceive('make')->with(WebSocketMessageStub::class); + $container->expects('make')->never()->with(WebSocketMessageStub::class); CoroutineContext::set(WebSocketContext::FD, 1); WebSocketContext::set('connection.id', 'one'); FdCollector::set(1, WebSocketMessageStub::class); - (new Server($container))->onClose(m::mock(SwooleServer::class), 1, 0); + (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0); $this->assertSame($wrapped ? [$cancellation, $listenerFailure] : [$listenerFailure], $reported); $this->assertFalse(WebSocketMessageStub::$closeHandled); @@ -776,7 +748,7 @@ public function testCloseWithoutCollectorStillReleasesConnectionContext(): void CoroutineContext::set(WebSocketContext::FD, 1); WebSocketContext::set('connection.id', 'one'); - (new Server($this->createContainer()))->onClose(m::mock(SwooleServer::class), 1, 0); + (new Server($this->createContainer()->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0); $this->assertArrayNotHasKey(1, WebSocketContext::getStorage()); } @@ -785,21 +757,22 @@ public function testCloseHandlerFailureDoesNotSkipEventOrCleanup(): void { WebSocketMessageStub::$closeException = new RuntimeException('close failed'); - $logger = m::mock(StdoutLoggerInterface::class)->shouldIgnoreMissing(); - $logger->shouldReceive('error')->once()->with(m::type('string')); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error')->with(Argument::type('string')); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionClosed::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once(); + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->allows('hasListeners')->with(ConnectionClosing::class)->returns(false); + $dispatcher->allows('hasListeners')->with(ConnectionClosed::class)->returns(true); + $dispatcher->expects('dispatch'); $container = $this->createContainer($logger, $dispatcher); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); CoroutineContext::set(WebSocketContext::FD, 1); WebSocketContext::set('connection.id', 'one'); FdCollector::set(1, WebSocketMessageStub::class); - (new Server($container))->onClose(m::mock(SwooleServer::class), 1, 0); + (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0); $this->assertTrue(WebSocketMessageStub::$closeHandled); $this->assertNull(FdCollector::get(1)); @@ -808,21 +781,22 @@ public function testCloseHandlerFailureDoesNotSkipEventOrCleanup(): void public function testCloseEventFailureDoesNotSkipCleanup(): void { - $logger = m::mock(StdoutLoggerInterface::class)->shouldIgnoreMissing(); - $logger->shouldReceive('error')->once()->with(m::type('string')); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error')->with(Argument::type('string')); - $dispatcher = m::mock(EventDispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->with(ConnectionClosed::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->andThrow(new RuntimeException('event failed')); + $dispatcher = Double::for(EventDispatcherContract::class)->strict(); + $dispatcher->allows('hasListeners')->with(ConnectionClosing::class)->returns(false); + $dispatcher->allows('hasListeners')->with(ConnectionClosed::class)->returns(true); + $dispatcher->expects('dispatch')->throws(new RuntimeException('event failed')); $container = $this->createContainer($logger, $dispatcher); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); CoroutineContext::set(WebSocketContext::FD, 1); WebSocketContext::set('connection.id', 'one'); FdCollector::set(1, WebSocketMessageStub::class); - (new Server($container))->onClose(m::mock(SwooleServer::class), 1, 0); + (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0); $this->assertTrue(WebSocketMessageStub::$closeHandled); $this->assertNull(FdCollector::get(1)); @@ -833,17 +807,17 @@ public function testCloseCancellationIsContainedAfterCleanup(): void { WebSocketMessageStub::$closeException = new CanceledException; - $logger = m::mock(StdoutLoggerInterface::class)->shouldIgnoreMissing(); - $logger->shouldNotReceive('error'); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error')->never(); $container = $this->createContainer($logger); - $container->shouldReceive('make')->with(WebSocketMessageStub::class)->andReturn(new WebSocketMessageStub); + $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub); CoroutineContext::set(WebSocketContext::FD, 1); WebSocketContext::set('connection.id', 'one'); FdCollector::set(1, WebSocketMessageStub::class); - (new Server($container))->onClose(m::mock(SwooleServer::class), 1, 0); + (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0); $this->assertTrue(WebSocketMessageStub::$closeHandled); $this->assertNull(FdCollector::get(1)); @@ -854,21 +828,19 @@ public function testExceptionHandlerResponseSuppressesHandshakeException(): void { $original = new RuntimeException('handshake failed'); $response = new Response('Unauthorized', Response::HTTP_UNAUTHORIZED); - $handler = m::mock(WebSocketExceptionHandler::class); - $handler->shouldReceive('handle') - ->once() - ->with($original, m::type(Response::class)) - ->andReturn($response); + $handler = Double::for(WebSocketExceptionHandler::class)->strict(); + $handler->expects('handle') + ->with($original, Argument::type(Response::class)) + ->returns($response); $container = $this->createContainer(); - $container->shouldReceive('make') - ->once() + $container->expects('make') ->with(WebSocketExceptionHandler::class) - ->andReturn($handler); + ->returns($handler); $this->assertSame( $response, - (new ClassInvoker(new Server($container)))->handleException($original) + (new ClassInvoker(new Server($container->instance())))->handleException($original) ); } @@ -876,20 +848,18 @@ public function testExceptionHandlerFailureRetainsHandshakeException(): void { $original = new RuntimeException('handshake failed'); $handlingFailure = new RuntimeException('exception handler failed'); - $handler = m::mock(WebSocketExceptionHandler::class); - $handler->shouldReceive('handle') - ->once() - ->with($original, m::type(Response::class)) - ->andThrow($handlingFailure); + $handler = Double::for(WebSocketExceptionHandler::class)->strict(); + $handler->expects('handle') + ->with($original, Argument::type(Response::class)) + ->throws($handlingFailure); $container = $this->createContainer(); - $container->shouldReceive('make') - ->once() + $container->expects('make') ->with(WebSocketExceptionHandler::class) - ->andReturn($handler); + ->returns($handler); try { - (new ClassInvoker(new Server($container)))->handleException($original); + (new ClassInvoker(new Server($container->instance())))->handleException($original); $this->fail('Expected exception handling to fail.'); } catch (RuntimeException $exception) { $this->assertSame($handlingFailure, $exception); @@ -920,27 +890,23 @@ protected function createContainer( ?StdoutLoggerInterface $logger = null, ?EventDispatcherContract $dispatcher = null, ?ExceptionHandlerContract $exceptionHandler = null, - ): Container&\Mockery\MockInterface { - $logger ??= m::mock(StdoutLoggerInterface::class)->shouldIgnoreMissing(); + ): OverriddenDouble { + $logger ??= Double::for(StdoutLoggerInterface::class); - $container = m::mock(Container::class); - $container->shouldReceive('make')->with(StdoutLoggerInterface::class)->andReturn($logger); + $container = Double::for(Container::class, override: true)->strict(); + $container->allows('make')->with(StdoutLoggerInterface::class)->returns($logger); if ($exceptionHandler !== null) { - $container->shouldReceive('make') + $container->allows('make') ->with(ExceptionHandlerContract::class) - ->andReturn($exceptionHandler); + ->returns($exceptionHandler); } if ($dispatcher) { - $dispatcher->shouldReceive('hasListeners') - ->with(ConnectionClosing::class) - ->andReturnFalse() - ->byDefault(); - $container->shouldReceive('bound')->with('events')->andReturnTrue(); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($dispatcher); } else { - $container->shouldReceive('bound')->with('events')->andReturnFalse(); + $container->allows('bound')->with('events')->returns(false); } return $container; diff --git a/tests/WebSocketServer/WebSocketExceptionHandlerTest.php b/tests/WebSocketServer/WebSocketExceptionHandlerTest.php index 292413c736..4eecf4114e 100644 --- a/tests/WebSocketServer/WebSocketExceptionHandlerTest.php +++ b/tests/WebSocketServer/WebSocketExceptionHandlerTest.php @@ -7,13 +7,16 @@ use Hypervel\Contracts\Log\StdoutLoggerInterface; use Hypervel\Tests\TestCase; use Hypervel\WebSocketServer\Exceptions\Handler\WebSocketExceptionHandler; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\HttpException; class WebSocketExceptionHandlerTest extends TestCase { + use VerifiesDoubles; + public function testPreservesClientHttpExceptionDetailsAndHeaders(): void { $handler = $this->handler(); @@ -58,8 +61,8 @@ public function testHidesNonHttpExceptionDetails(): void */ protected function handler(): WebSocketExceptionHandler { - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('warning')->once(); + $logger = Double::for(StdoutLoggerInterface::class)->strict(); + $logger->expects('warning'); return new WebSocketExceptionHandler($logger); } diff --git a/tests/WebSocketServer/WebSocketServerServiceProviderTest.php b/tests/WebSocketServer/WebSocketServerServiceProviderTest.php index 81499ea156..e3393636fc 100644 --- a/tests/WebSocketServer/WebSocketServerServiceProviderTest.php +++ b/tests/WebSocketServer/WebSocketServerServiceProviderTest.php @@ -12,36 +12,38 @@ use Hypervel\WebSocketServer\Listeners\OnPipeMessageListener; use Hypervel\WebSocketServer\SenderPipeMessage; use Hypervel\WebSocketServer\WebSocketServerServiceProvider; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use stdClass; use Swoole\Server; class WebSocketServerServiceProviderTest extends TestCase { + use VerifiesDoubles; + public function testResolvesPipeListenerOnlyForWebSocketSenderMessages(): void { $registeredListener = null; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('listen') - ->once() - ->with(OnPipeMessage::class, m::on(function (Closure $listener) use (&$registeredListener): bool { + $events = Double::for(Dispatcher::class)->strict(); + $events->expects('listen') + ->with(OnPipeMessage::class, Argument::type(Closure::class)) + ->resolves(function (string $event, Closure $listener) use (&$registeredListener): void { $registeredListener = $listener; - - return true; - })); + }); $message = new SenderPipeMessage('disconnect', [42]); - $listener = m::mock(OnPipeMessageListener::class); - $listener->shouldReceive('handle')->once()->with($message); + $listener = Double::for(OnPipeMessageListener::class)->strict(); + $listener->expects('handle')->with($message); - $application = m::mock(Application::class); - $application->shouldReceive('make')->once()->with('events')->andReturn($events); - $application->shouldReceive('make')->once()->with(OnPipeMessageListener::class)->andReturn($listener); + $application = Double::for(Application::class, override: true)->strict(); + $application->expects('make')->with('events')->returns($events); + $application->expects('make')->with(OnPipeMessageListener::class)->returns($listener); - (new WebSocketServerServiceProvider($application))->boot(); + (new WebSocketServerServiceProvider($application->instance()))->boot(); - $server = m::mock(Server::class); + $server = Double::for(Server::class)->strict(); $registeredListener(new OnPipeMessage($server, 0, new stdClass)); $registeredListener(new OnPipeMessage($server, 0, $message)); }