//! ref: composer/tests/Composer/Test/Repository/FilesystemRepositoryTest.php use std::cell::RefCell; use std::rc::Rc; use indexmap::IndexMap; use shirabe::dependency_resolver::operation::OperationInterface; use shirabe::installed_versions::InstalledVersions; use shirabe::installer::{InstallationManagerInterface, InstallerInterface}; use shirabe::io::IOInterface; use shirabe::json::json_file::JsonFile; use shirabe::package::PackageInterfaceHandle; use shirabe::repository::InstalledRepositoryInterface; use shirabe::repository::RepositoryInterface; use shirabe::repository::filesystem_repository::FilesystemRepository; use shirabe::util::filesystem::Filesystem; use shirabe_php_shim::PhpMixed; use crate::test_case::get_package; /// PHP mocks JsonFile::read()/exists(); without a mocking framework the canned read value is /// materialized as a real temp file whose decoded JSON reproduces the mock return value exactly. fn create_temp_json_file(contents: &str) -> String { let mut path = std::env::temp_dir(); let unique = format!( "shirabe_filesystemrepositorytest_{}_{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos() ); path.push(unique); std::fs::write(&path, contents.as_bytes()).unwrap(); path.to_str().unwrap().to_string() } #[test] fn test_repository_read() { let path = create_temp_json_file( r#"[{"name": "package1", "version": "1.0.0-beta", "type": "vendor"}]"#, ); let json = JsonFile::new(path, None, None).unwrap(); let mut repository = FilesystemRepository::new(json, false, None, None).unwrap(); let packages = repository.get_packages().unwrap(); assert_eq!(packages.len(), 1); assert_eq!(packages[0].get_name(), "package1"); assert_eq!(packages[0].get_version(), "1.0.0.0-beta"); assert_eq!(packages[0].get_type(), "vendor"); } #[ignore] #[test] fn test_corrupted_repository_file() { // PHP mocks read() to return the scalar string 'foo'; a real file containing the JSON string // "foo" decodes to the same value, which the repository rejects as a non-array package list. let path = create_temp_json_file(r#""foo""#); let json = JsonFile::new(path, None, None).unwrap(); let mut repository = FilesystemRepository::new(json, false, None, None).unwrap(); let result = repository.get_packages(); let err = result.unwrap_err(); assert!( err.is::(), "expected InvalidRepositoryException, got: {err}" ); } #[test] fn test_unexistent_repository_file() { let mut path = std::env::temp_dir(); path.push(format!( "shirabe_filesystemrepositorytest_missing_{}_{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos() )); let json = JsonFile::new(path.to_str().unwrap().to_string(), None, None).unwrap(); let mut repository = FilesystemRepository::new(json, false, None, None).unwrap(); let packages = repository.get_packages().unwrap(); assert_eq!(packages.len(), 0); } /// Stub for `InstallationManagerInterface` whose `getInstallPath` returns a fixed path, mirroring /// the PHPUnit mock built with `disableOriginalConstructor()`. Only `get_install_path` is reached by /// `FilesystemRepository::write`; the call counter backs PHP's `expects($this->exactly(2))`. #[derive(Debug)] struct InstallPathStub { calls: Rc>, fixed_path: String, } impl InstallationManagerInterface for InstallPathStub { fn add_installer(&mut self, _installer: Box) { unimplemented!() } fn remove_installer(&mut self, _installer: &dyn InstallerInterface) { unimplemented!() } fn disable_plugins(&mut self) { unimplemented!() } fn is_package_installed( &mut self, _repo: &dyn InstalledRepositoryInterface, _package: PackageInterfaceHandle, ) -> anyhow::Result { unimplemented!() } fn ensure_binaries_presence(&mut self, _package: PackageInterfaceHandle) { unimplemented!() } fn execute( &mut self, _repo: &mut dyn InstalledRepositoryInterface, _operations: Vec>, _dev_mode: bool, _run_scripts: bool, _download_only: bool, ) -> anyhow::Result<()> { unimplemented!() } fn get_install_path(&mut self, _package: PackageInterfaceHandle) -> Option { *self.calls.borrow_mut() += 1; Some(self.fixed_path.clone()) } fn set_output_progress(&mut self, _output_progress: bool) { unimplemented!() } fn notify_installs(&mut self, _io: Rc>) { unimplemented!() } } #[test] fn test_repository_write() { // PHP mocks JsonFile::write/read/getPath; here a real JsonFile under a temp repo dir is written // and read back. write() never reads the file (it dumps the in-memory packages), so the mocked // read()/exists() return values are irrelevant to the result. let base = std::fs::canonicalize(std::env::temp_dir()).unwrap(); let repo_dir = format!( "{}/shirabe_repo_write_test_{}_{}", base.display(), std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_nanos() ); let mut fs = Filesystem::new(None); fs.remove_directory(&repo_dir).ok(); let json_path = format!("{}/vendor/composer/installed.json", repo_dir); let json = JsonFile::new(json_path.clone(), None, None).unwrap(); let mut repository = FilesystemRepository::new(json, false, None, None).unwrap(); let calls = Rc::new(RefCell::new(0i64)); let mut im = InstallPathStub { calls: calls.clone(), fixed_path: format!("{}/vendor/woop/woop", repo_dir), }; repository.set_dev_package_names(vec!["mypkg2".to_string()]); repository .add_package(get_package("mypkg2", "1.2.3")) .unwrap(); repository .add_package(get_package("mypkg", "0.1.10")) .unwrap(); repository.write(true, &mut im).unwrap(); // PHP asserts getInstallPath is called exactly twice (once per installed package). assert_eq!(*calls.borrow(), 2); let written = std::fs::read_to_string(&json_path).unwrap(); let actual: serde_json::Value = serde_json::from_str(&written).unwrap(); let expected = serde_json::json!({ "packages": [ {"name": "mypkg", "type": "library", "version": "0.1.10", "version_normalized": "0.1.10.0", "install-path": "../woop/woop"}, {"name": "mypkg2", "type": "library", "version": "1.2.3", "version_normalized": "1.2.3.0", "install-path": "../woop/woop"}, ], "dev": true, "dev-package-names": ["mypkg2"], }); assert_eq!(actual, expected); fs.remove_directory(&repo_dir).ok(); } #[test] #[ignore = "needs get_root_package + configure_links test helpers (not present in tests/common; project_test_port_link_setters describes them via ArrayLoader::load_packages but this branch lacks them) plus exact byte-match of the generated installed.php fixture under a chdir"] fn test_repository_writes_installed_php() { todo!() } #[ignore] #[test] fn test_safely_load_installed_versions() { let fixtures_dir = format!( "{}/../../composer/tests/Composer/Test/Repository/Fixtures", env!("CARGO_MANIFEST_DIR") ); let path = format!("{}/installed_complex.php", fixtures_dir); let result = FilesystemRepository::safely_load_installed_versions(&path); assert!(result, "The file should be considered valid"); let raw_data = InstalledVersions::get_all_raw_data(); let raw_data = raw_data.last().cloned().unwrap(); let mut root: IndexMap = IndexMap::new(); root.insert( "install_path".to_string(), PhpMixed::String(format!("{}/./", fixtures_dir)), ); root.insert( "aliases".to_string(), PhpMixed::List(vec![ PhpMixed::String("1.10.x-dev".to_string()), PhpMixed::String("2.10.x-dev".to_string()), ]), ); root.insert("name".to_string(), PhpMixed::String("__root__".to_string())); root.insert("true".to_string(), PhpMixed::Bool(true)); root.insert("false".to_string(), PhpMixed::Bool(false)); root.insert("null".to_string(), PhpMixed::Null); let mut a_provider: IndexMap = IndexMap::new(); a_provider.insert( "foo".to_string(), PhpMixed::String("simple string/no backslash".to_string()), ); a_provider.insert( "install_path".to_string(), PhpMixed::String(format!( "{}/vendor/{{${{passthru('bash -i')}}}}", fixtures_dir )), ); a_provider.insert("empty array".to_string(), PhpMixed::List(vec![])); let mut c_c: IndexMap = IndexMap::new(); c_c.insert( "install_path".to_string(), PhpMixed::String("/foo/bar/ven/do{}r/c/c${}".to_string()), ); c_c.insert("aliases".to_string(), PhpMixed::List(vec![])); c_c.insert( "reference".to_string(), PhpMixed::String("{${passthru('bash -i')}} Foo\\Bar\n\ttab\u{0b}verticaltab\0".to_string()), ); let mut versions: IndexMap = IndexMap::new(); versions.insert("a/provider".to_string(), PhpMixed::Array(a_provider)); versions.insert("c/c".to_string(), PhpMixed::Array(c_c)); let mut expected: IndexMap = IndexMap::new(); expected.insert("root".to_string(), PhpMixed::Array(root)); expected.insert("versions".to_string(), PhpMixed::Array(versions)); assert_eq!(raw_data, expected); }