1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
|
//! 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::<shirabe::repository::InvalidRepositoryException>(),
"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<RefCell<i64>>,
fixed_path: String,
}
impl InstallationManagerInterface for InstallPathStub {
fn add_installer(&mut self, _installer: Box<dyn InstallerInterface>) {
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<bool> {
unimplemented!()
}
fn ensure_binaries_presence(&mut self, _package: PackageInterfaceHandle) {
unimplemented!()
}
fn execute(
&mut self,
_repo: &mut dyn InstalledRepositoryInterface,
_operations: Vec<Rc<dyn OperationInterface>>,
_dev_mode: bool,
_run_scripts: bool,
_download_only: bool,
) -> anyhow::Result<()> {
unimplemented!()
}
fn get_install_path(&mut self, _package: PackageInterfaceHandle) -> Option<String> {
*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<RefCell<dyn IOInterface>>) {
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<String, PhpMixed> = 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<String, PhpMixed> = 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<String, PhpMixed> = 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<String, PhpMixed> = 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<String, PhpMixed> = IndexMap::new();
expected.insert("root".to_string(), PhpMixed::Array(root));
expected.insert("versions".to_string(), PhpMixed::Array(versions));
assert_eq!(raw_data, expected);
}
|