|
| 1 | +use std::{ |
| 2 | + collections::HashMap, |
| 3 | + net::{Ipv4Addr, SocketAddrV4}, |
| 4 | + path::{Path, PathBuf}, |
| 5 | +}; |
| 6 | + |
| 7 | +use oci_client::client::ClientConfig; |
| 8 | +use testcontainers::{ |
| 9 | + core::{IntoContainerPort, WaitFor}, |
| 10 | + runners::AsyncRunner, |
| 11 | + ContainerAsync, GenericImage, ImageExt, |
| 12 | +}; |
| 13 | +use tokio::{net::TcpListener, process::Command}; |
| 14 | +use wasm_pkg_client::{oci::OciRegistryConfig, Config, CustomConfig, Registry, RegistryMetadata}; |
| 15 | + |
| 16 | +/// Returns an open port on localhost |
| 17 | +pub async fn find_open_port() -> u16 { |
| 18 | + TcpListener::bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0)) |
| 19 | + .await |
| 20 | + .expect("failed to bind random port") |
| 21 | + .local_addr() |
| 22 | + .map(|addr| addr.port()) |
| 23 | + .expect("failed to get local address from opened TCP socket") |
| 24 | +} |
| 25 | + |
| 26 | +/// Starts a registry container on an open port, returning a [`Config`] with registry auth |
| 27 | +/// configured for it and the name of the registry. The container handle is also returned as it must |
| 28 | +/// be kept in scope |
| 29 | +pub async fn start_registry() -> (Config, Registry, ContainerAsync<GenericImage>) { |
| 30 | + let port = find_open_port().await; |
| 31 | + let container = GenericImage::new("registry", "2") |
| 32 | + .with_wait_for(WaitFor::message_on_stderr("listening on [::]:5000")) |
| 33 | + .with_mapped_port(port, 5000.tcp()) |
| 34 | + .start() |
| 35 | + .await |
| 36 | + .expect("Failed to start test container"); |
| 37 | + |
| 38 | + let registry: Registry = format!("localhost:{}", port).parse().unwrap(); |
| 39 | + let mut config = Config::empty(); |
| 40 | + // Make sure we add wasi. The default fallbacks don't get written to disk, which we use in |
| 41 | + // tests, so we just start with an empty config and write this into it |
| 42 | + config.set_namespace_registry( |
| 43 | + "wasi".parse().unwrap(), |
| 44 | + wasm_pkg_client::RegistryMapping::Registry("wasi.dev".parse().unwrap()), |
| 45 | + ); |
| 46 | + let reg_conf = config.get_or_insert_registry_config_mut(®istry); |
| 47 | + reg_conf |
| 48 | + .set_backend_config( |
| 49 | + "oci", |
| 50 | + OciRegistryConfig { |
| 51 | + client_config: ClientConfig { |
| 52 | + protocol: oci_client::client::ClientProtocol::Http, |
| 53 | + ..Default::default() |
| 54 | + }, |
| 55 | + credentials: None, |
| 56 | + }, |
| 57 | + ) |
| 58 | + .unwrap(); |
| 59 | + |
| 60 | + (config, registry, container) |
| 61 | +} |
| 62 | + |
| 63 | +/// Clones the given config, mapping the namespace to the given registry at the top level |
| 64 | +pub fn map_namespace(config: &Config, namespace: &str, registry: &Registry) -> Config { |
| 65 | + let mut config = config.clone(); |
| 66 | + let mut metadata = RegistryMetadata::default(); |
| 67 | + metadata.preferred_protocol = Some("oci".to_string()); |
| 68 | + let mut meta = serde_json::Map::new(); |
| 69 | + meta.insert("registry".to_string(), registry.to_string().into()); |
| 70 | + metadata.protocol_configs = HashMap::from_iter([("oci".to_string(), meta)]); |
| 71 | + config.set_namespace_registry( |
| 72 | + namespace.parse().unwrap(), |
| 73 | + wasm_pkg_client::RegistryMapping::Custom(CustomConfig { |
| 74 | + registry: registry.to_owned(), |
| 75 | + metadata, |
| 76 | + }), |
| 77 | + ); |
| 78 | + config |
| 79 | +} |
| 80 | + |
| 81 | +/// A loaded fixture with helpers for running wkg tests |
| 82 | +pub struct Fixture { |
| 83 | + pub temp_dir: tempfile::TempDir, |
| 84 | + pub fixture_path: PathBuf, |
| 85 | +} |
| 86 | + |
| 87 | +impl Fixture { |
| 88 | + /// Returns a base `wkg` command for running tests with the current directory set to the loaded |
| 89 | + /// fixture and with a separate wkg cache dir |
| 90 | + pub fn command(&self) -> Command { |
| 91 | + let mut cmd = Command::new(env!("CARGO_BIN_EXE_wkg")); |
| 92 | + cmd.current_dir(&self.fixture_path); |
| 93 | + cmd.env("WKG_CACHE_DIR", self.temp_dir.path().join("cache")); |
| 94 | + cmd |
| 95 | + } |
| 96 | + |
| 97 | + /// Same as [`Fixture::command`] but also writes the given config to disk and sets the |
| 98 | + /// `WKG_CONFIG` environment variable to the path of the config |
| 99 | + pub async fn command_with_config(&self, config: &Config) -> Command { |
| 100 | + let config_path = self.temp_dir.path().join("config.toml"); |
| 101 | + config |
| 102 | + .to_file(&config_path) |
| 103 | + .await |
| 104 | + .expect("failed to write config"); |
| 105 | + let mut cmd = self.command(); |
| 106 | + cmd.env("WKG_CONFIG_FILE", config_path); |
| 107 | + cmd |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +/// Gets the path to the fixture |
| 112 | +pub fn fixture_dir() -> PathBuf { |
| 113 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 114 | + .join("tests") |
| 115 | + .join("fixtures") |
| 116 | +} |
| 117 | + |
| 118 | +/// Loads the fixture with the given name into a temporary directory. This will copy the fixture |
| 119 | +/// from the tests/fixtures directory into a temporary directory and return the tempdir containing |
| 120 | +/// that directory (and its path) |
| 121 | +pub async fn load_fixture(fixture: &str) -> Fixture { |
| 122 | + let temp_dir = tempfile::tempdir().expect("Failed to create tempdir"); |
| 123 | + let fixture_path = fixture_dir().join(fixture); |
| 124 | + // This will error if it doesn't exist, which is what we want |
| 125 | + tokio::fs::metadata(&fixture_path) |
| 126 | + .await |
| 127 | + .expect("Fixture does not exist or couldn't be read"); |
| 128 | + let copied_path = temp_dir.path().join(fixture_path.file_name().unwrap()); |
| 129 | + copy_dir(&fixture_path, &copied_path) |
| 130 | + .await |
| 131 | + .expect("Failed to copy fixture"); |
| 132 | + Fixture { |
| 133 | + temp_dir, |
| 134 | + fixture_path: copied_path, |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +#[allow(dead_code)] |
| 139 | +async fn copy_dir(source: impl AsRef<Path>, destination: impl AsRef<Path>) -> anyhow::Result<()> { |
| 140 | + tokio::fs::create_dir_all(&destination).await?; |
| 141 | + let mut entries = tokio::fs::read_dir(source).await?; |
| 142 | + while let Some(entry) = entries.next_entry().await? { |
| 143 | + let filetype = entry.file_type().await?; |
| 144 | + if filetype.is_dir() { |
| 145 | + // Skip the deps directory in case it is there from debugging |
| 146 | + if entry.path().file_name().unwrap_or_default() == "deps" { |
| 147 | + continue; |
| 148 | + } |
| 149 | + Box::pin(copy_dir( |
| 150 | + entry.path(), |
| 151 | + destination.as_ref().join(entry.file_name()), |
| 152 | + )) |
| 153 | + .await?; |
| 154 | + } else { |
| 155 | + let path = entry.path(); |
| 156 | + let extension = path.extension().unwrap_or_default(); |
| 157 | + // Skip any .lock files that might be there from debugging |
| 158 | + if extension == "lock" { |
| 159 | + continue; |
| 160 | + } |
| 161 | + tokio::fs::copy(path, destination.as_ref().join(entry.file_name())).await?; |
| 162 | + } |
| 163 | + } |
| 164 | + Ok(()) |
| 165 | +} |
0 commit comments