refactor: simplify updater tests

pull/2060/head
amrbashir 7 months ago
parent 7f025e5240
commit 49a4f78806
No known key found for this signature in database
GPG Key ID: BBD7A47A2003FF33

2
Cargo.lock generated

@ -239,6 +239,7 @@ dependencies = [
name = "app-updater" name = "app-updater"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"dunce",
"serde", "serde",
"serde_json", "serde_json",
"tauri", "tauri",
@ -6701,6 +6702,7 @@ version = "2.0.2"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"dirs 5.0.1", "dirs 5.0.1",
"dunce",
"flate2", "flate2",
"futures-util", "futures-util",
"http", "http",

@ -63,6 +63,9 @@ flate2 = { version = "1", optional = true }
tar = "0.4" tar = "0.4"
flate2 = "1" flate2 = "1"
[dev-dependencies]
dunce = { workspace = true }
[features] [features]
default = ["rustls-tls", "zip"] default = ["rustls-tls", "zip"]
zip = ["dep:zip", "dep:tar", "dep:flate2"] zip = ["dep:zip", "dep:tar", "dep:flate2"]

@ -616,12 +616,16 @@ impl Update {
.chain(self.installer_args()) .chain(self.installer_args())
.collect(), .collect(),
WindowsUpdaterType::Msi { path, .. } => { WindowsUpdaterType::Msi { path, .. } => {
let escaped_args = current_args msi_args = if !current_args.is_empty() {
.iter() let escaped_args = current_args
.map(escape_msi_property_arg) .iter()
.collect::<Vec<_>>() .map(escape_msi_property_arg)
.join(" "); .collect::<Vec<_>>()
msi_args = OsString::from(format!("LAUNCHAPPARGS=\"{escaped_args}\"")); .join(" ");
OsString::from(format!("LAUNCHAPPARGS=\"{escaped_args}\""))
} else {
OsString::new()
};
[OsStr::new("/i"), path.as_os_str()] [OsStr::new("/i"), path.as_os_str()]
.into_iter() .into_iter()
@ -629,7 +633,7 @@ impl Update {
.chain(once(OsStr::new("/promptrestart"))) .chain(once(OsStr::new("/promptrestart")))
.chain(self.installer_args()) .chain(self.installer_args())
.chain(once(OsStr::new("AUTOLAUNCHAPP=True"))) .chain(once(OsStr::new("AUTOLAUNCHAPP=True")))
.chain(once(msi_args.as_os_str())) .chain(once(msi_args.as_os_str()).filter(|a| !a.is_empty()))
.collect() .collect()
} }
}; };

@ -14,5 +14,8 @@ tauri-plugin-updater = { path = "../.." }
tiny_http = "0.12" tiny_http = "0.12"
time = { version = "0.3", features = ["formatting"] } time = { version = "0.3", features = ["formatting"] }
[target."cfg(windows)".dependencies]
dunce = { workspace = true }
[features] [features]
prod = ["tauri/custom-protocol"] prod = ["tauri/custom-protocol"]

@ -14,29 +14,33 @@ fn main() {
.plugin(tauri_plugin_updater::Builder::new().build()) .plugin(tauri_plugin_updater::Builder::new().build())
.setup(|app| { .setup(|app| {
let handle = app.handle().clone(); let handle = app.handle().clone();
eprintln!("app version: {}", app.package_info().version);
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
let mut builder = handle.updater_builder(); let mut builder = handle.updater_builder();
if std::env::var("TARGET").unwrap_or_default() == "nsis" {
// /D sets the default installation directory ($INSTDIR), // Overriding installation directory for integration tests on Windows
// overriding InstallDir and InstallDirRegKey. #[cfg(windows)]
// It must be the last parameter used in the command line and must not contain any quotes, even if the path contains spaces. {
// Only absolute paths are supported. let target = std::env::var("TARGET").unwrap_or_default();
// NOTE: we only need this because this is an integration test and we don't want to install the app in the programs folder let exe = tauri::utils::platform::current_exe().unwrap();
builder = builder.installer_args(vec![format!( let dir = dunce::simplified(exe
"/D={}", .parent()
tauri::utils::platform::current_exe() .unwrap())
.unwrap() .display();
.parent() if target == "nsis" {
.unwrap() builder = builder.installer_args(vec![format!("/D=\"{dir}\"",)]);
.display() } else if target == "msi" {
)]); builder = builder.installer_args(vec![format!("INSTALLDIR=\"{dir}\"")]);
}
} }
let updater = builder.build().unwrap(); let updater = builder.build().unwrap();
match updater.check().await { match updater.check().await {
Ok(Some(update)) => { Ok(Some(update)) => {
if let Err(e) = update.download_and_install(|_, _| {}, || {}).await { if let Err(e) = update.download_and_install(|_, _| {}, || {}).await {
println!("{e}"); eprintln!("{e}");
std::process::exit(1); std::process::exit(1);
} }
std::process::exit(0); std::process::exit(0);
@ -45,7 +49,7 @@ fn main() {
std::process::exit(2); std::process::exit(2);
} }
Err(e) => { Err(e) => {
println!("{e}"); eprintln!("{e}");
std::process::exit(1); std::process::exit(1);
} }
} }

@ -5,8 +5,7 @@
"endpoints": ["http://localhost:3007"], "endpoints": ["http://localhost:3007"],
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEUwNDRGMjkwRjg2MDhCRDAKUldUUWkyRDRrUEpFNEQ4SmdwcU5PaXl6R2ZRUUNvUnhIaVkwVUltV0NMaEx6VTkrWVhpT0ZqeEEK", "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEUwNDRGMjkwRjg2MDhCRDAKUldUUWkyRDRrUEpFNEQ4SmdwcU5PaXl6R2ZRUUNvUnhIaVkwVUltV0NMaEx6VTkrWVhpT0ZqeEEK",
"windows": { "windows": {
"installMode": "quiet", "installMode": "passive"
"installerArgs": ["/NS"]
} }
} }
}, },

@ -19,33 +19,45 @@ const UPDATER_PRIVATE_KEY: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IHJzaWduIGVuY3J5cHRlZ
const UPDATED_EXIT_CODE: i32 = 0; const UPDATED_EXIT_CODE: i32 = 0;
const UP_TO_DATE_EXIT_CODE: i32 = 2; const UP_TO_DATE_EXIT_CODE: i32 = 2;
#[derive(Serialize)] #[derive(Serialize, Clone)]
struct Config { struct Config {
version: &'static str, version: &'static str,
bundle: BundleConfig, bundle: BundleConfig,
} }
#[derive(Serialize)] #[derive(Serialize, Clone)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct BundleConfig { struct BundleConfig {
create_updater_artifacts: Updater, create_updater_artifacts: Updater,
} }
#[derive(Serialize)] #[derive(Serialize)]
struct PlatformUpdate { struct Update {
version: &'static str,
date: String,
signature: String, signature: String,
url: &'static str, url: &'static str,
with_elevated_task: bool,
} }
#[derive(Serialize)] fn setup_test() -> (PathBuf, PathBuf, Config) {
struct Update { let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
version: &'static str,
date: String, let target_dir = std::env::var("CARGO_TARGET_DIR")
platforms: HashMap<String, PlatformUpdate>, .or_else(|_| std::env::var("CARGO_BUILD_TARGET_DIR"))
.map(PathBuf::from)
.unwrap_or_else(|_| manifest_dir.join("../../../.."));
let config = Config {
version: "1.0.0",
bundle: BundleConfig {
create_updater_artifacts: Updater::Bool(true),
},
};
(manifest_dir, target_dir, config)
} }
fn build_app(cwd: &Path, config: &Config, bundle_updater: bool, target: BundleTarget) { fn build_app(cwd: &Path, config: &Config, bundle_updater: bool, target: &str) {
let mut command = Command::new("cargo"); let mut command = Command::new("cargo");
command command
.args(["tauri", "build", "--debug", "--verbose"]) .args(["tauri", "build", "--debug", "--verbose"])
@ -55,19 +67,10 @@ fn build_app(cwd: &Path, config: &Config, bundle_updater: bool, target: BundleTa
.env("TAURI_SIGNING_PRIVATE_KEY_PASSWORD", "") .env("TAURI_SIGNING_PRIVATE_KEY_PASSWORD", "")
.current_dir(cwd); .current_dir(cwd);
#[cfg(target_os = "linux")]
command.args(["--bundles", target.name()]);
#[cfg(target_os = "macos")]
command.args(["--bundles", target.name()]);
if bundle_updater { if bundle_updater {
#[cfg(windows)] command.args(["--bundles", target, "updater"]);
command.args(["--bundles", "msi", "nsis"]);
command.args(["--bundles", "updater"]);
} else { } else {
#[cfg(windows)] command.arg("--no-bundle");
command.args(["--bundles", target.name()]);
} }
let status = command let status = command
@ -79,268 +82,174 @@ fn build_app(cwd: &Path, config: &Config, bundle_updater: bool, target: BundleTa
} }
} }
#[derive(Copy, Clone)] fn start_server(update_bundle: PathBuf, signature: PathBuf) -> Arc<tiny_http::Server> {
enum BundleTarget { let server = tiny_http::Server::http("localhost:3007").expect("failed to start updater server");
AppImage, let server = Arc::new(server);
let server_ = server.clone();
std::thread::spawn(move || {
for request in server_.incoming_requests() {
match request.url() {
"/" => {
let signature =
std::fs::read_to_string(&signature).expect("failed to read signature");
let now = time::OffsetDateTime::now_utc()
.format(&time::format_description::well_known::Rfc3339)
.unwrap();
let body = serde_json::to_vec(&Update {
version: "1.0.0",
date: now,
signature,
url: "http://localhost:3007/download",
})
.unwrap();
let len = body.len();
let response = tiny_http::Response::new(
tiny_http::StatusCode(200),
Vec::new(),
std::io::Cursor::new(body),
Some(len),
None,
);
App, let _ = request.respond(response);
}
"/download" => {
let file = File::open(&update_bundle).unwrap_or_else(|_| {
panic!("failed to open updater bundle {}", update_bundle.display())
});
let _ = request.respond(tiny_http::Response::from_file(file));
}
_ => (),
}
}
});
Msi, server
Nsis,
} }
impl BundleTarget { fn test_update(app: &Path, update_bundle: PathBuf, signature: PathBuf, target: &str) {
fn name(self) -> &'static str { // start the updater server
match self { let server = start_server(update_bundle, signature);
Self::AppImage => "appimage",
Self::App => "app", // run app
Self::Msi => "msi", let mut app_cmd = Command::new(app);
Self::Nsis => "nsis", app_cmd.env("TARGET", target);
} let output = app_cmd.output().expect("failed to run app");
// check if updated, or failed during update
let code = output.status.code().unwrap_or(-1);
if code != UPDATED_EXIT_CODE {
let stderr = String::from_utf8_lossy(&output.stderr);
panic!("app failed while updating, expected exit code {UPDATED_EXIT_CODE}, got {code}\n{stderr}");
} }
}
impl Default for BundleTarget { // wait for the update to finish
fn default() -> Self { std::thread::sleep(std::time::Duration::from_secs(10));
#[cfg(any(target_os = "macos", target_os = "ios"))]
return Self::App; // run again
#[cfg(target_os = "linux")] let status = app_cmd.status().expect("failed to run new app");
return Self::AppImage;
#[cfg(windows)] // check if new version is up to date
return Self::Nsis; let code = status.code().unwrap_or(-1);
if code != UP_TO_DATE_EXIT_CODE {
let stderr = String::from_utf8_lossy(&output.stderr);
panic!(
"app failed to update, expected exit code {UP_TO_DATE_EXIT_CODE}, got {code}\n{stderr}"
);
} }
}
#[cfg(target_os = "linux")] // shutdown the server
fn bundle_paths(root_dir: &Path, version: &str) -> Vec<(BundleTarget, PathBuf)> { server.unblock();
vec![(
BundleTarget::AppImage,
root_dir.join(format!(
"target/debug/bundle/appimage/app-updater_{version}_amd64.AppImage"
)),
)]
} }
#[cfg(target_os = "macos")] #[cfg(windows)]
fn bundle_paths(root_dir: &Path, _version: &str) -> Vec<(BundleTarget, PathBuf)> { fn nsis() {
vec![( let (manifest_dir, target_dir, config) = setup_test();
BundleTarget::App,
root_dir.join("target/debug/bundle/macos/app-updater.app"), // build update bundles, normal installer and zipped
)] build_app(&manifest_dir, &config, true, "nsis");
// bundle base app
let mut base_config = config.clone();
base_config.version = "0.1.0";
build_app(&manifest_dir, &base_config, false, "nsis");
let app = target_dir.join("debug/app-updater.exe");
// test nsis installer updates
let update_bundle = target_dir.join(format!(
"debug/bundle/nsis/app-updater_{}_x64-setup.exe",
config.version,
));
let signature = update_bundle.with_extension("exe.sig");
test_update(&app, update_bundle, signature, "nsis");
// cleanup the installed application
let _ = Command::new(target_dir.join("debug/uninstall.exe"))
.arg("/S")
.status()
.expect("failed to run nsis uninstaller");
std::thread::sleep(std::time::Duration::from_secs(5));
} }
#[cfg(target_os = "ios")] #[cfg(windows)]
fn bundle_paths(root_dir: &Path, _version: &str) -> Vec<(BundleTarget, PathBuf)> { fn msi() {
vec![( let (manifest_dir, target_dir, config) = setup_test();
BundleTarget::App,
root_dir.join("target/debug/bundle/ios/app-updater.ipa"), // build update bundles, normal installer and zipped
)] build_app(&manifest_dir, &config, true, "msi");
// bundle base app
let mut base_config = config.clone();
base_config.version = "0.1.0";
build_app(&manifest_dir, &base_config, false, "msi");
let app = target_dir.join("debug/app-updater.exe");
// test msi installer updates
let update_bundle = target_dir.join(format!(
"debug/bundle/msi/app-updater_{}_x64_en-US.msi",
config.version,
));
let signature = update_bundle.with_extension("msi.sig");
test_update(&app, update_bundle, signature, "msi");
// cleanup the installed application
let uninstall = target_dir.join("debug/Uninstall app-updater.lnk");
let _ = Command::new("cmd")
.arg("/c")
.arg(&uninstall)
.arg("/qb")
.status()
.expect("failed to run msi uninstaller");
std::thread::sleep(std::time::Duration::from_secs(5));
} }
#[cfg(target_os = "android")] #[cfg(target_os = "linux")]
fn bundle_path(root_dir: &Path, _version: &str) -> PathBuf { fn appimage() {
root_dir.join("target/debug/bundle/android/app-updater.apk") let (manifest_dir, target_dir, mut config) = setup_test();
} }
#[cfg(windows)] #[cfg(target_os = "macos")]
fn bundle_paths(root_dir: &Path, version: &str) -> Vec<(BundleTarget, PathBuf)> { fn app() {
vec![ let (manifest_dir, target_dir, mut config) = setup_test();
(
BundleTarget::Nsis,
root_dir.join(format!(
"target/debug/bundle/nsis/app-updater_{version}_x64-setup.exe"
)),
),
(
BundleTarget::Msi,
root_dir.join(format!(
"target/debug/bundle/msi/app-updater_{version}_x64_en-US.msi"
)),
),
]
} }
#[test] #[test]
#[ignore] #[ignore]
fn update_app() { fn it_updates() {
let target = #[cfg(windows)]
tauri_plugin_updater::target().expect("running updater test in an unsupported platform"); nsis();
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); // MSI test should be the last one
let root_dir = manifest_dir.join("../../../.."); #[cfg(windows)]
msi();
for mut config in [ #[cfg(target_os = "linux")]
Config { appimage();
version: "1.0.0", #[cfg(target_os = "macos")]
bundle: BundleConfig { app();
create_updater_artifacts: Updater::Bool(true),
},
},
Config {
version: "1.0.0",
bundle: BundleConfig {
create_updater_artifacts: Updater::String(V1Compatible::V1Compatible),
},
},
] {
let v1_compatible = matches!(
config.bundle.create_updater_artifacts,
Updater::String(V1Compatible::V1Compatible)
);
// bundle app update
build_app(&manifest_dir, &config, true, Default::default());
let updater_zip_ext = if v1_compatible {
if cfg!(windows) {
Some("zip")
} else {
Some("tar.gz")
}
} else if cfg!(target_os = "macos") {
Some("tar.gz")
} else {
None
};
for (bundle_target, out_bundle_path) in bundle_paths(&root_dir, "1.0.0") {
let bundle_updater_ext = if v1_compatible {
out_bundle_path
.extension()
.unwrap()
.to_str()
.unwrap()
.replace("exe", "nsis")
} else {
out_bundle_path
.extension()
.unwrap()
.to_str()
.unwrap()
.to_string()
};
let updater_extension = if let Some(updater_zip_ext) = updater_zip_ext {
format!("{bundle_updater_ext}.{updater_zip_ext}")
} else {
bundle_updater_ext
};
let signature_extension = format!("{updater_extension}.sig");
let signature_path = out_bundle_path.with_extension(signature_extension);
let signature = std::fs::read_to_string(&signature_path).unwrap_or_else(|_| {
panic!("failed to read signature file {}", signature_path.display())
});
let out_updater_path = out_bundle_path.with_extension(updater_extension);
let updater_path = root_dir.join(format!(
"target/debug/{}",
out_updater_path.file_name().unwrap().to_str().unwrap()
));
std::fs::rename(&out_updater_path, &updater_path).expect("failed to rename bundle");
let target = target.clone();
// start the updater server
let server = Arc::new(
tiny_http::Server::http("localhost:3007").expect("failed to start updater server"),
);
let server_ = server.clone();
std::thread::spawn(move || {
for request in server_.incoming_requests() {
match request.url() {
"/" => {
let mut platforms = HashMap::new();
platforms.insert(
target.clone(),
PlatformUpdate {
signature: signature.clone(),
url: "http://localhost:3007/download",
with_elevated_task: false,
},
);
let body = serde_json::to_vec(&Update {
version: "1.0.0",
date: time::OffsetDateTime::now_utc()
.format(&time::format_description::well_known::Rfc3339)
.unwrap(),
platforms,
})
.unwrap();
let len = body.len();
let response = tiny_http::Response::new(
tiny_http::StatusCode(200),
Vec::new(),
std::io::Cursor::new(body),
Some(len),
None,
);
let _ = request.respond(response);
}
"/download" => {
let _ = request.respond(tiny_http::Response::from_file(
File::open(&updater_path).unwrap_or_else(|_| {
panic!(
"failed to open updater bundle {}",
updater_path.display()
)
}),
));
}
_ => (),
}
}
});
config.version = "0.1.0";
// bundle initial app version
build_app(&manifest_dir, &config, false, bundle_target);
let status_checks = if matches!(bundle_target, BundleTarget::Msi) {
// for msi we can't really check if the app was updated, because we can't change the install path
vec![UPDATED_EXIT_CODE]
} else {
vec![UPDATED_EXIT_CODE, UP_TO_DATE_EXIT_CODE]
};
for expected_exit_code in status_checks {
let mut binary_cmd = if cfg!(windows) {
Command::new(root_dir.join("target/debug/app-updater.exe"))
} else if cfg!(target_os = "macos") {
Command::new(
bundle_paths(&root_dir, "0.1.0")
.first()
.unwrap()
.1
.join("Contents/MacOS/app-updater"),
)
} else if std::env::var("CI").map(|v| v == "true").unwrap_or_default() {
let mut c = Command::new("xvfb-run");
c.arg("--auto-servernum")
.arg(&bundle_paths(&root_dir, "0.1.0").first().unwrap().1);
c
} else {
Command::new(&bundle_paths(&root_dir, "0.1.0").first().unwrap().1)
};
binary_cmd.env("TARGET", bundle_target.name());
let status = binary_cmd.status().expect("failed to run app");
let code = status.code().unwrap_or(-1);
if code != expected_exit_code {
panic!(
"failed to run app, expected exit code {expected_exit_code}, got {code}"
);
}
#[cfg(windows)]
if code == UPDATED_EXIT_CODE {
// wait for the update to finish
std::thread::sleep(std::time::Duration::from_secs(5));
}
}
// graceful shutdown
server.unblock();
}
}
} }

Loading…
Cancel
Save