aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/tests/common
AgeCommit message (Collapse)Author
2026-07-20fix(io): widen IOInterface::select choices to PhpMixed for assoc arraysnsfisis
PHP's IOInterface::select accepts an associative choices array whose keys are the selectable values, but the port narrowed it to Vec<String>, making key-based selection unrepresentable. Accept PhpMixed (List or Array) like PHP's array $choices; ConsoleIO already branched on both shapes internally. Also mirror PHP in the single-select array_search fallback for numeric-keyed arrays. All call sites keep their previous list-based behavior. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20fix(event-dispatcher): un-ignore test_dispatcher_outputs_commandnsfisis
The ignore reason went stale: the getListeners override seam and a real ProcessExecutor wired to the IO already cover the PHP setup, and IOStub is the PHPUnit IOInterface-mock equivalent. IOStub now records writeError calls (writeRaw was already recorded) so the expects(once)->with(...) spies on writeError/writeRaw can be reproduced as call-list equality assertions. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20fix(process-executor): un-ignore 11 tests by implementing execute_async mock ↵nsfisis
support ProcessExecutor::execute_async's mock branch was an unimplemented todo!(), blocking every test whose code path calls it (feature-branch git diffing, system-unzip/7z fallback extraction). Implement it by: - Adding Process::__mock (mirroring the existing ZipArchive::__mock pattern) so execute_async can resolve with a fabricated, already- terminated Process instead of spawning a real subprocess. - Extracting the sync mock's expectation-matching logic into a shared ProcessExecutor::mock_match, wrapping the mock state in a RefCell so it works from execute_async's &self/&mut self receivers. - Setting error_output/capture_output from the mock branch, matching PHP's ProcessExecutorMock::executeAsync sharing doExecute with the sync path; execute_async now takes &mut self for this (safe, since the borrow only needs to live through the synchronous setup, not across the .await). - Turning a strict-mode expectation mismatch from a panic!() into a shirabe_php_shim::RuntimeException Err, mirroring PHPUnit's AssertionFailedError extending \RuntimeException: PHP call sites that catch (\RuntimeException $e) around a mocked git/hg/svn call (e.g. Git::get_mirror_default_branch, GitDriver::supports) treat a mismatch as an ordinary recoverable failure, and now so does the port. The RefMut is dropped before firing an expectation's optional callback so a re-entrant callback doesn't panic on double-borrow. Also fixes two real bugs found while porting test_private_repository_ no_interaction: GitHub::authorize_oauth and GitLab::authorize_oauth checked their domains config via PhpMixed::as_array(), which only matches the Array (map) variant, but github-domains/gitlab-domains default to PhpMixed::List, so the check always returned false and OAuth token lookup was silently skipped. Use the in_array shim instead, matching PHP's in_array() semantics. Also fix Git::run_command's "capture credentials from git remote -v" call, which used the panic- swallowing execute_args wrapper instead of a fallible execute(), so a mock mismatch there couldn't reach get_mirror_default_branch's catch. Un-ignores: - zip_downloader_test::test_system_unzip_only_{good,failed} - zip_downloader_test::test_non_windows_fallback_{good,failed} - event_dispatcher_test::test_dispatcher_outputs_error_on_failed_command - root_package_loader_test::test_feature_branch_pretty_version - version_guesser_test::test_guess_version_reads_and_respects_non_feature_branches_configuration_for_arbitrary_naming{,_regex} - version_guesser_test::test_remote_branches_are_selected - github_driver_test::test_private_repository_no_interaction (also adds the missing #[serial], since it seeds the shared Git::VERSION static that vcs_repository_test::test_load_versions depends on for real) - init_command_test::test_get_git_config, made deterministic by pointing HOME at a throwaway dir with its own .gitconfig instead of depending on the host's global git config Deduplicates the GitVersionGuard/RestoreEnv test-drop-guard idioms into tests/common/test_case.rs instead of reimplementing them per file. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-19fix(root-package-loader): un-ignore 4 tests by fixing stability-flag isset() ↵nsfisis
port extract_stability_flags ported PHP's `isset($stabilityFlags[$name]) && $stabilityFlags[$name] > $stability` as `unwrap_or(i64::MAX) > stability`, so the check always short-circuited to "already more unstable" and no flag (e.g. from an explicit `*@dev` requirement) was ever recorded. Fixed using Option::is_some_and, a direct translation of PHP's isset() && ... check. Also fixes tests/common/test_case.rs's shared installation_manager() helper, which built a real InstallationManager::new instead of the __new_mock constructor (mirroring PHP's FactoryMock::createInstallationManager()), so it always had zero installers registered and wrote install-path: null into fixture installed.json files. Un-ignores test_reinstall_command, test_locally_modified_packages_from_source/ _from_dist, and test_package_still_present_error_when_no_install_flag_used — the first three were already passing (their #[ignore] reasons were stale), the last is fixed by the test_case.rs change above. Updates the #[ignore] reasons on installer_test.rs's three fixture-driven integration tests to reflect their current state: the install pipeline now runs end-to-end, but the ~189-fixture installer/ set still hits several independent, unrelated bugs/gaps that need case-by-case triage rather than a single fix. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-19fix(update-command): un-ignore test_update by fixing 3 real bugsnsfisis
test_update was skipped for a stale reason; running it uncovered three distinct bugs it was actually catching: - ApplicationTester::run never restored SHELL_VERBOSITY after Application::configureIO mutates it, so one dataset's -vv verbosity leaked into later runs sharing the process (Symfony's tester restores it in a finally block; the port dropped that). - Installer::do_install built its RepositorySet with a hardcoded empty temporary_constraints map instead of self.temporary_constraints, so --with never actually constrained the resolver. - BumpCommand was missing a <warning> tag pair around one of its output lines.
2026-07-19fix(test-harness): set COMPOSER_TESTS_ARE_RUNNING so interactive tests ↵nsfisis
actually run Without this, Application::do_run force-disabled interactivity whenever stdin wasn't a tty (as under cargo test), so ApplicationTester runs with set_inputs silently produced non-interactive default output instead of consuming the answers, masking real behavior as several stale #[ignore]s blaming already-implemented ProcessExecutor/Process todo!()s. Port composer/tests/bootstrap.php's env setup into a bootstrap() helper called from get_application_tester(), un-ignore the now-passing init/update command tests, and update init_command_test's expected schema-validation wording to match the jsonschema crate (already the accepted wording per 541a8b4f, not an unported gap).
2026-07-18perf(installation-manager): run executeBatch operation chains concurrentlynsfisis
executeBatch now builds one future per operation — the PHP promise chain prepare -> install/update/uninstall -> cleanup -> repo->write, including the '<Op> of <pkg> failed' rejection handler covering the chain up to cleanup — and drives the whole batch through waitOnPromises()/Loop::wait, so archive extraction (the unzip subprocesses gated by ProcessExecutor's semaphore) finally overlaps across packages. Alias operations stay synchronous in the collection loop like PHP. The shared repository is threaded through the chains as RefCell<&mut dyn InstalledRepositoryInterface>: execute() wraps the incoming &mut once, and InstallerInterface::install/update/uninstall take the cell so implementations borrow it only in their synchronous head/tail, never across an await. InstallationManager's own install/update/uninstall/download/get_installer/get_install_path/ mark_for_notification move to &self (cache and notifiable_packages behind RefCell) so every chain can capture &self. WritableRepositoryInterface::write and the InstallationManagerInterface get_install_path it relies on lose their &mut manager requirement — the per-op repo->write inside the chains only reads install paths. Warm-cache create-project laravel/laravel: the package-operations phase (109 installs) drops from ~3.0-3.8s serial to ~1.9s, on par with real Composer (~2.1s) measured back-to-back; the resulting vendor tree, installed.json included, stays byte-identical to Composer's (diff -rq clean). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-18perf(regex): eliminate per-call clone overhead in preg_* dispatchnsfisis
regex::Regex::clone() does not share the underlying meta engine's search-cache pool, so every fresh clone pays a ~10us warmup cost on its first use. Two changes together eliminate this across nearly all preg_* call sites: - A php_regex! macro resolves PHP-style patterns to a per-call-site &'static regex::Regex (via regex-macro's LazyLock), applied at the majority of call sites throughout the codebase. - Call sites still passing dynamic pattern strings go through PATTERN_CACHE, which now stores Arc<(Regex, bool)> and hands out Arc::clone()s instead of cloning the Regex itself. PregPattern::resolve() returns a ResolvedPattern enum (Arc or 'static reference) rather than an owned Regex, so neither path ever clones the Regex proper. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17refactor(tests-async): unify duplicated tokio runtime bridgesnsfisis
11 downloader/installer integration-test files each redefined an identical current_thread `run()` helper to block on async code. Extract one shared multi_thread Runtime into tests/common/async_runtime.rs so concurrent #[test] threads can all block_on it, matching the direction item 7 (top-level Runtime) will take in production code.
2026-07-16refactor(locker-test): reuse test_case's installation_manager helpernsfisis
locker_test.rs defined its own installation_manager, identical to test_case.rs's (both build a bare InstallationManager over a mock HttpDownloader). Expose the shared one via pub(crate) and drop the duplicate. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16test(util): port remaining todo!() tests in util test suitensfisis
Implement previously-todo!() tests in auth_helper_test.rs, process_executor_test.rs, remote_filesystem_test.rs, and stream_context_factory_test.rs by porting the corresponding PHPUnit test methods. Extend IOStub with writeRaw/setAuthentication call tracking and askAndValidate/getAuthentication overrides to model the PHPUnit mocks these tests rely on, deduping the resulting call-recording fields into a small generic CallRecorder<T> helper instead of repeating the same RefCell<Vec<T>> push/borrow().clone() boilerplate five times. testStoreAuthWithPromptInvalidAnswer and testPromptAuthIfNeededMultipleBitbucketDownloads had initially lost the ported PHPUnit mock's argument/call-count assertions (askAndValidate's exact prompt string, and hasAuthentication/getAuthentication's exactly(2) call counts), silently narrowing what the tests verify; IOStub now records these calls and the tests assert on them, matching upstream. Tests left unportable (PHP set_error_handler machinery, closures in data providers, network/subclass-mock dependencies, etc.) keep #[ignore] with a single // TODO(phase-d) reason recorded in the function body. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-11chore: use fully-qualified name for Rc/RefCellnsfisis
2026-06-28refactor: add linternsfisis
2026-06-28test(tests): use mockall for hand-written interface mocksnsfisis
Replace hand-written mock/stub structs that re-implemented PHPUnit mock-builder behavior (record-and-verify, manual call counters, unreachable!() guards) with mockall::mock! locals across: - package/loader: MockLoader, VersionGuesserMock - command: ArchiveManager/RepositoryManager/EventDispatcher mocks - util: ConfigSource/AuthJson mocks (auth_helper, bitbucket, github, forgejo, gitlab) - repository/vcs: github_driver NullConfigSource - installer: CountingInstaller, RecordingBinaryInstaller, and the DownloadManager mock (formerly common/downloader_stub.rs, now deleted) - downloader: download_manager create_downloader_mock Verification (counts/args) now lives in mockall expectations checked on drop. installation_manager BinaryInstaller is left hand-written because its as_binary_presence_interface seam returns Some(&mut self), which mockall cannot express; io_stub and io_mock are left as-is. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28test(util/git): port interactive Bitbucket OAuth runCommand testnsfisis
Implement the four privateBitbucketWithOauthProvider cases that were stubbed as an ignored todo!(). Extend IOStub with per-question askAndHideAnswer responses and auth pre-seeding so the stateful OAuth flow can be driven without willReturnCallback, and inject a mock HttpDownloader plus no-op config sources to mirror PHPUnit's Config mock. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26test: port 32 command/repository/downloader testsnsfisis
Add create_installed_json/create_composer_lock test helpers. Port command (8), repository path/forgejo/perforce/vcs (11), and fossil/hg/download_manager (13) tests. Fix production porting bugs: root_package_loader/forgejo_url/version_bumper regex delimiters, repository_manager create_repository_by_class, array_loader isset, licenses_command RefCell borrow; implement disk_free_space and touch2/touch3 via libc. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26test: port 35 auth/installer/io/zip/bitbucket tests; implement date_creatensfisis
Port auth_helper (14), library_installer (8), console_io (7), zip_downloader (3), git_bitbucket_driver (3) tests. Implement date_create/strtotime for the ISO8601/ RFC3339/relative formats Composer uses (unknown input -> None, no silent guess). Fix production bugs: Question::is_assoc list-vs-assoc, auth_helper gitlab-domains list handling, LibraryInstaller RefCell double-borrow, ZipArchive::extract_to ErrorException propagation. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26test: port 44 vcs/downloader/version tests using mock infransfisis
Port git, version_guesser, gitlab_driver, github_driver, and git_downloader tests using the ProcessExecutor/HttpDownloader mocks and IO/Config stubs. Fix production regex-porting bugs surfaced by the now-reachable paths: Url::sanitize and Response::find_header_value had non-delimited PCRE patterns; implement array_search_mixed non-strict branch and a datetime format mapping. Add HttpDownloader::__new_mock so mocked downloaders skip curl construction. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26feat(test): add HttpDownloaderMock, IOStub, and Config stub helpersnsfisis
IOStub and ConfigStubBuilder provide getMockBuilder-style configurable stubs. Wired into util/repository/downloader/command test targets. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26feat(util): add ProcessExecutorMock test infra; port SymfonyStyle message ↵nsfisis
methods Add an internal mock hook to ProcessExecutor (None in production) so tests can stub command execution without spawning processes, mirroring Composer's ProcessExecutorMock subclass. Add get_process_executor_mock helper and two verification tests. Implement SymfonyStyle's message-handling methods. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24refactor(semver): re-export shirabe-semver at crate root, drop ↵nsfisis
composer::semver stubs Flatten shirabe-semver's modules into glob re-exports at the crate root and route all consumers through the short paths. Remove the duplicate composer::semver stubs from shirabe-external-packages in favor of the shirabe-semver types. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24test(io): add IOMock test helper porting Composer's IOMocknsfisis
Port composer/tests/Composer/Test/Mock/IOMock.php as a BufferIO-backed mock with expects()/assert_complete(), authentication logging, and a Drop guard mirroring TestCase::getIOMock + tearDown. This is the infrastructure many IO-consuming tests need; wiring existing #[ignore] tests onto it is a follow-up, gated on making BufferIO::get_output's look-behind regex regex-crate compatible. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23test(command): port InitCommandTestnsfisis
Port the pure-method cases (parse/namespace/formatAuthors/git/vendor-ignore) and build the ApplicationTester / initTempComposer harness the run cases need. Supporting production changes: - carry the streamable input stream as PhpResource (not PhpMixed) and add InputInterface::as_streamable so QuestionHelper reads the injected stream - add StreamOutput/ConsoleOutput __set_stream test helpers and ApplicationHandle::set_catch_exceptions for the tester - implement the interact() author validator via parse_author_string Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21test(repository): port InstalledRepositoryTestnsfisis
testAddRepository maps the expected LogicException to #[should_panic] since InstalledRepository::add_repository guards with assert!. testFindPackagesWithReplacersAndProviders is #[ignore] because that assert omits InstalledRepositoryInterface, so adding an InstalledArrayRepository panics before the lookup runs. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21test(repository): port ArrayRepositoryTestnsfisis
Seven cases pass against ArrayRepository. testAutomaticallyAddAliased... is #[ignore] because AliasPackage::get_unique_name returns the aliased package's unique name rather than the alias's own version, so has_package cannot find the alias version. Adds a shared get_alias_package helper to the test TestCase, building the alias via from_rc_unchecked since the public handle API exposes link/alias construction only indirectly. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21test(dependency-resolver): port PoolTest with shared TestCase helpersnsfisis
Add tests/common/test_case.rs (get_package, get_version_constraint) ported from the PHP TestCase, included into the dependency_resolver binary via #[path]. PoolTest's testPool/testPackageById/testWhatProvidesWhenPackageCannotBeFound pass; testWhatProvidesPackageWithConstraint is #[ignore] (constraint matching reaches a todo!() in the php-shim). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>