Skip to main content

thunderstore_engine/
test_support.rs

1//! A mock Thunderstore for tests: an HTTP server that serves a small package
2//! index and real package archives, so the install pipeline runs end to end
3//! with no network access.
4//!
5//! The index has five packages, each downloaded from `/dl/<archive>.zip`:
6//!
7//! - `Owner-ModA` and `Owner-ModB` 1.0.0, with no dependencies.
8//! - `Owner-ModC` 1.0.0, which depends on `Owner-ModA-1.0.0`.
9//! - `Owner-ModD` at 1.0.0 and a newer 2.0.0, from `ModD-1.0.0.zip` and
10//!   `ModD-2.0.0.zip`.
11//! - `denikson-BepInExPack_Valheim` 5.4.2200, a real mod-loader identifier
12//!   whose archive is shaped by [`loader_zip`](crate::test_support::loader_zip).
13//!
14//! Each mod archive ships a DLL named after its package (`ModA.dll`), so a test
15//! can tell whose files landed where.
16//!
17//! Every version has a [`readme`] except `Owner-ModB`, which answers `404` like
18//! a package Thunderstore has no readme for.
19//!
20//! ```no_run
21//! use thunderstore_engine::test_support::MockThunderstore;
22//!
23//! # async fn demo() -> thunderstore_engine::Result<()> {
24//! let mock = MockThunderstore::start_async().await;
25//! let client = mock.client_builder().cache_dir("/tmp/cache").build()?;
26//! let index = client.get_manifest().await?;
27//!
28//! assert_eq!(index.len(), 5);
29//! # Ok(())
30//! # }
31//! ```
32
33use std::io::{Cursor, Write};
34
35use zip::write::{FileOptions, ZipWriter};
36
37use crate::client::{ThunderstoreClient, ThunderstoreClientBuilder};
38
39/// The `mockito` version the fixture is built on, so a test can add its own
40/// mocks to [`MockThunderstore::server_mut`] without a second copy.
41pub use mockito;
42
43/// Path the package index is served from.
44pub const PACKAGE_INDEX_PATH: &str = "/pkg/";
45
46/// A running mock Thunderstore serving [`index_json`] and every archive it
47/// names.
48pub struct MockThunderstore {
49  server: mockito::ServerGuard,
50}
51
52impl MockThunderstore {
53  /// Starts the mock outside an async runtime.
54  ///
55  /// # Panics
56  ///
57  /// Panics inside an async runtime (use [`start_async`](Self::start_async))
58  /// or if the server cannot start.
59  pub fn start() -> Self {
60    Self::serve(mockito::Server::new())
61  }
62
63  /// Starts the mock from async code, such as a `#[tokio::test]`.
64  ///
65  /// # Panics
66  ///
67  /// Panics if the server cannot start.
68  pub async fn start_async() -> Self {
69    Self::serve(mockito::Server::new_async().await)
70  }
71
72  fn serve(mut server: mockito::ServerGuard) -> Self {
73    let url = server.url();
74
75    server
76      .mock("GET", PACKAGE_INDEX_PATH)
77      .with_status(200)
78      .with_header("Content-Type", "application/json")
79      .with_header("Last-Modified", "Wed, 21 Feb 2024 15:30:45 GMT")
80      .with_body(index_json(&url))
81      .create();
82
83    for (archive, body) in [
84      ("ModA", mod_zip_with("1.0.0", "ModA.dll")),
85      ("ModB", mod_zip_with("1.0.0", "ModB.dll")),
86      ("ModC", mod_zip_with("1.0.0", "ModC.dll")),
87      ("ModD-1.0.0", mod_zip_with("1.0.0", "ModD.dll")),
88      ("ModD-2.0.0", mod_zip_with("2.0.0", "ModD.dll")),
89      ("BepInExPack_Valheim", loader_zip()),
90    ] {
91      server
92        .mock("GET", format!("/dl/{archive}.zip").as_str())
93        .with_status(200)
94        .with_header("Content-Type", "application/zip")
95        .with_body(body)
96        .create();
97    }
98
99    for (owner, name, version) in [
100      ("Owner", "ModA", "1.0.0"),
101      ("Owner", "ModC", "1.0.0"),
102      ("Owner", "ModD", "1.0.0"),
103      ("Owner", "ModD", "2.0.0"),
104      ("denikson", "BepInExPack_Valheim", "5.4.2200"),
105    ] {
106      let body = serde_json::json!({ "markdown": readme(name, version) });
107
108      server
109        .mock("GET", readme_path(owner, name, version).as_str())
110        .with_status(200)
111        .with_header("Content-Type", "application/json")
112        .with_body(body.to_string())
113        .create();
114    }
115
116    server
117      .mock("GET", readme_path("Owner", "ModB", "1.0.0").as_str())
118      .with_status(404)
119      .with_header("Content-Type", "application/json")
120      .with_body(r#"{"detail":"Not found."}"#)
121      .create();
122
123    Self { server }
124  }
125
126  /// The server's base URL, such as `http://127.0.0.1:1234`.
127  pub fn url(&self) -> String {
128    self.server.url()
129  }
130
131  /// The full URL of the package index.
132  pub fn package_index_url(&self) -> String {
133    format!("{}{PACKAGE_INDEX_PATH}", self.url())
134  }
135
136  /// The underlying server, for adding mocks such as a profile-code endpoint
137  /// or a failing download.
138  pub fn server_mut(&mut self) -> &mut mockito::ServerGuard {
139    &mut self.server
140  }
141
142  /// A client builder with both the host and the package index pointed at
143  /// this mock. Set a cache directory, then build.
144  pub fn client_builder(&self) -> ThunderstoreClientBuilder {
145    ThunderstoreClient::builder()
146      .base_url(self.url())
147      .package_index_url(self.package_index_url())
148  }
149}
150
151/// The readme markdown the mock serves for `name` at `version`, such as
152/// `"# ModA 1.0.0\n\nA mod."`.
153pub fn readme(name: &str, version: &str) -> String {
154  format!("# {name} {version}\n\nA mod.")
155}
156
157/// Path a version's readme is served from, as Thunderstore lays it out.
158pub fn readme_path(owner: &str, name: &str, version: &str) -> String {
159  format!("/api/experimental/package/{owner}/{name}/{version}/readme/")
160}
161
162/// A mod archive with a manifest at `version` and one DLL, `plugins/ModA.dll`,
163/// which the install rules route to `BepInEx/plugins/<Owner-Name>/`.
164pub fn mod_zip(version: &str) -> Vec<u8> {
165  mod_zip_with(version, "ModA.dll")
166}
167
168/// [`mod_zip`] with the DLL named `dll_name`.
169pub fn mod_zip_with(version: &str, dll_name: &str) -> Vec<u8> {
170  let manifest = format!("{{\"version_number\":\"{version}\"}}");
171
172  stored_zip(&[
173    ("manifest.json", manifest.as_bytes()),
174    (&format!("plugins/{dll_name}"), b"dll-bytes"),
175  ])
176}
177
178/// A mod-loader archive shaped like `denikson-BepInExPack_Valheim`: its payload
179/// sits under the `rootFolder` the bundled ecosystem names for that package, so
180/// an install strips the wrapper and the files land at the target root.
181///
182/// It holds the doorstop proxy `winhttp.dll` and `BepInEx/core/BepInEx.dll`.
183/// The second lands in a declared namespaced route without an `<Owner-Name>/`
184/// folder, which is the case that makes attributing loader files by shape
185/// unsafe.
186pub fn loader_zip() -> Vec<u8> {
187  stored_zip(&[
188    ("manifest.json", b"{\"version_number\":\"5.4.2200\"}"),
189    ("BepInExPack_Valheim/winhttp.dll", b"proxy"),
190    ("BepInExPack_Valheim/BepInEx/core/BepInEx.dll", b"core"),
191  ])
192}
193
194fn stored_zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
195  let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
196  let options: FileOptions<'_, ()> =
197    FileOptions::default().compression_method(zip::CompressionMethod::Stored);
198
199  for (name, body) in entries {
200    zip.start_file(*name, options).expect("start a zip entry");
201    zip.write_all(body).expect("write a zip entry");
202  }
203
204  zip.finish().expect("finish an in-memory zip").into_inner()
205}
206
207/// The package index described in the [module docs](self), with every
208/// download URL under `server_url`.
209pub fn index_json(server_url: &str) -> String {
210  let version =
211    |owner: &str, name: &str, number: &str, dependencies: &str, archive: &str, created: &str| {
212      format!(
213        r#"{{"name":"{name}","full_name":"{owner}-{name}",
214      "description":"A mod","icon":"icon.png","version_number":"{number}",
215      "dependencies":[{dependencies}],"download_url":"{server_url}/dl/{archive}.zip",
216      "downloads":1,"date_created":"{created}",
217      "website_url":"","is_active":true,"uuid4":"ver-{archive}","file_size":1024}}"#
218      )
219    };
220  let package = |owner: &str, name: &str, versions: &[String]| {
221    format!(
222      r#"{{"name":"{name}","full_name":"{owner}-{name}","owner":"{owner}",
223      "package_url":"https://example.com/{name}",
224      "date_created":"2024-01-01T12:00:00Z","date_updated":"2024-01-02T12:00:00Z",
225      "uuid4":"pkg-{name}","rating_score":1,"is_pinned":false,
226      "is_deprecated":false,"has_nsfw_content":false,"categories":[],
227      "versions":[{}]}}"#,
228      versions.join(",")
229    )
230  };
231  let single = |owner: &str, name: &str, number: &str, dependencies: &str| {
232    package(
233      owner,
234      name,
235      &[version(
236        owner,
237        name,
238        number,
239        dependencies,
240        name,
241        "2024-01-01T12:00:00Z",
242      )],
243    )
244  };
245
246  format!(
247    "[{},{},{},{},{}]",
248    single("Owner", "ModA", "1.0.0", ""),
249    single("Owner", "ModB", "1.0.0", ""),
250    single("Owner", "ModC", "1.0.0", "\"Owner-ModA-1.0.0\""),
251    // The engine takes the latest version by `date_created`, so 2.0.0 must be
252    // the later of the two.
253    package(
254      "Owner",
255      "ModD",
256      &[
257        version(
258          "Owner",
259          "ModD",
260          "2.0.0",
261          "",
262          "ModD-2.0.0",
263          "2024-02-01T12:00:00Z",
264        ),
265        version(
266          "Owner",
267          "ModD",
268          "1.0.0",
269          "",
270          "ModD-1.0.0",
271          "2024-01-01T12:00:00Z",
272        ),
273      ],
274    ),
275    single("denikson", "BepInExPack_Valheim", "5.4.2200", "")
276  )
277}