Skip to content

Commit

Permalink
feat: wasm with logger
Browse files Browse the repository at this point in the history
  • Loading branch information
mrchantey committed Jan 3, 2025
1 parent 4bee2c9 commit 1196580
Show file tree
Hide file tree
Showing 29 changed files with 377 additions and 267 deletions.
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"rust-analyzer.cargo.features": ["bevy"],
// "rust-analyzer.files.excludeDirs": ["tests"],
// "rust-analyzer.cargo.target": "wasm32-unknown-unknown",
"rust-analyzer.cargo.target": "wasm32-unknown-unknown",
"deno.enable": true,
"search.exclude": {
"**/node_modules": true,
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,8 @@ path = "src/main.rs"

[dependencies]
anyhow.workspace = true
clap.workspace = true
clap.workspace = true


[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
sweet.workspace = true
2 changes: 2 additions & 0 deletions cli/src/test_runners/deno.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

import init from './bindgen.js'

// wrapper function to avoid abort
globalThis.__wbg_test_invoke = f => f();
globalThis.read_file = (path:string) => Deno.readTextFileSync(path);

const wasm = await init()
.catch((_err: any) => {
Expand Down
9 changes: 7 additions & 2 deletions cli/src/test_runners/test_wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ pub struct TestWasm {
wasm_bindgen_args: Option<String>,
/// arguments passed to deno, node, etc
wasm_runtime_args: Option<String>, // TODO these are the sweet clap args
#[arg(short, long)]
watch: bool,
#[command(flatten)]
runner_args: sweet::prelude::TestRunnerConfig,
}


Expand Down Expand Up @@ -76,9 +76,14 @@ impl TestWasm {
}

fn run_deno(&self) -> Result<()> {
// args will look like this so skip 3
// sweet test-wasm binary-path *actual-args
// why doesnt it work with three?
let args = std::env::args().skip(2).collect::<Vec<_>>();
let status = Command::new("deno")
.arg("--allow-read")
.arg(DENO_RUNNER_PATH)
.args(args)
.status()?;

if !status.success() {
Expand Down
39 changes: 27 additions & 12 deletions example_tests/hello_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ async fn returns_err() -> Result<(), String> { Err("foo".to_string()) }
#[should_panic]
#[ignore = "its just a dummy"]
async fn dummy1() {
tokio::time::sleep(Duration::from_secs(1)).await;
// tokio::time::sleep(Duration::from_secs(1)).await;

panic!("foo")
}
Expand All @@ -27,13 +27,16 @@ async fn dummy2() {
}
#[sweet::test]
// #[should_panic]
async fn dummy3() { tokio::time::sleep(Duration::from_secs(1)).await; }
async fn dummy3() { sleep(Duration::from_secs(1)).await; }
#[sweet::test]
// #[should_panic]
async fn dummy4() { tokio::time::sleep(Duration::from_secs(1)).await; }
async fn dummy4() { sleep(Duration::from_secs(1)).await; }
#[sweet::test]
async fn dummy5() { tokio::time::sleep(Duration::from_secs(1)).await; }
// #[should_panic]
async fn dummy5() {
sleep(Duration::from_secs(1)).await;
panic!("whaya");
}

// #[sweet::test]
// #[should_panic]
Expand All @@ -43,12 +46,24 @@ async fn dummy5() { tokio::time::sleep(Duration::from_secs(1)).await; }
// }
// }

#[cfg(target_arch = "wasm32")]
async fn sleep(duration: Duration) {
use wasm_bindgen_futures::JsFuture;
use web_sys::window;
let window = window().unwrap();
let promise = js_sys::Promise::new(&mut |resolve, _| {
window
.set_timeout_with_callback_and_timeout_and_arguments_0(
&resolve,
duration.as_millis() as i32,
)
.expect("should register `setTimeout` OK");
});

// /// tokio tests are just `#[test]` wrapped in a tokio runtime,
// /// of course they only run for native targets.
// ///
// /// Use `#[tokio::test]` when you need an isolated async runtime,
// /// 99% of the time you don't need it.
// #[cfg(not(target_arch = "wasm32"))]
// #[tokio::test]
// async fn its_tokio() {}
JsFuture::from(promise)
.await
.expect("should await `setTimeout` OK");
}

#[cfg(not(target_arch = "wasm32"))]
async fn sleep(duration: Duration) { tokio::time::sleep(duration).await; }
12 changes: 7 additions & 5 deletions example_tests/hello_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,17 @@ fn it_succeeds() { assert!(true) }
#[test]
fn it_succeeds2() { assert!(true) }
#[test]
#[should_panic]
// #[should_panic]
fn it_succeeds3() { assert!(true) }


#[test]
#[should_panic]
fn it_panics() { panic!("foo") }
// #[test]
// #[should_panic]
// fn it_panics() { panic!("foo") }


#[test]
// #[should_panic]
// #[ignore]
#[should_panic]
// fn it_panics2() {}
fn it_panics2() { panic!("foo") }
23 changes: 23 additions & 0 deletions examples/foo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use std::sync::Arc;
use std::sync::Mutex;
use wasm_bindgen::prelude::*;


// #[wasm_bindgen]
pub fn main() {
sweet::log!("waddup");

let (send, recv) = flume::unbounded();

send.send("pizza").unwrap();

sweet::log!("chicken");
while let Ok(msg) = recv.try_recv() {
sweet::log!("msg: {}", msg);
}

let a = Arc::new(Mutex::new(0));
sweet::log!("bazz: ");
let foo = a.lock().unwrap();
sweet::log!("foo: {}", foo);
}
2 changes: 2 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ install-cli *args:

run example *args:
just watch 'cargo run --example {{example}} {{args}}'
run-wasm example *args:
just watch 'cargo run --example {{example}} --target wasm32-unknown-unknown {{args}}'

#💡 Test

Expand Down
18 changes: 18 additions & 0 deletions src/backtrace/backtrace_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ impl BacktraceFile {
) -> Result<String> {
//line number is one-indexed
const LINE_CONTEXT_SIZE: usize = 2;
#[cfg(target_arch = "wasm32")]
// let lines = wasm_fs::read_file(&file.to_string_lossy().to_string())
// .map_err(|err| anyhow::anyhow!("Failed to read file: {:?}", err))?
// .as_string()
// .ok_or_else(|| anyhow::anyhow!("No string"))?;
return Ok("wasm cannot backtrace".to_string());
// #[cfg(not(target_arch = "wasm32"))]
let lines = fs::read_to_string(file)?;
let lines: Vec<&str> = lines.split("\n").collect();
let start =
Expand Down Expand Up @@ -127,3 +134,14 @@ fn line_number_buffer(line_no: usize) -> String {
let len = LINE_BUFFER_LEN.saturating_sub(digits);
" ".repeat(len)
}


#[cfg(target_arch = "wasm32")]
mod wasm_fs {
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(catch)]
pub fn read_file(path: &str) -> Result<JsValue, JsValue>;
}
}
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ pub mod prelude {

pub fn test_runner(tests: &[&test::TestDescAndFn]) {
#[cfg(target_arch = "wasm32")]
crate::wasm::run_libtest(tests);
crate::wasm::run_libtest(tests).unwrap();
#[cfg(not(target_arch = "wasm32"))]
crate::native::run_libtest(tests);
crate::native::run_libtest(tests).unwrap();
}
6 changes: 3 additions & 3 deletions src/logging/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
pub mod file_logger;
#[allow(unused_imports)]
pub use self::file_logger::*;
pub mod log;
#[allow(unused_imports)]
pub use self::log::*;
Expand All @@ -10,9 +13,6 @@ pub use self::runner_logger::*;
pub mod sweet_case_logger;
#[allow(unused_imports)]
pub use self::sweet_case_logger::*;
pub mod file_logger;
#[allow(unused_imports)]
pub use self::file_logger::*;
pub mod test_logger;
#[allow(unused_imports)]
pub use self::test_logger::*;
Expand Down
32 changes: 14 additions & 18 deletions src/logging/runner_logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,43 +19,39 @@ impl RunnerLogger {
config: Arc<TestRunnerConfig>,
tests: &[&TestDescAndFn],
) -> Self {
let test_logger = CaseLoggerEnum::new(config.clone(), tests);
if !config.quiet {
crate::log!("\n🤘 sweet as! 🤘\n\n{config}")
}
let case_logger = CaseLoggerEnum::new(config.clone(), tests);

#[cfg(not(target_arch = "wasm32"))]
{
use forky::prelude::terminal;
if !config.quiet && config.watch {
terminal::clear();
}
if !config.quiet {
if config.watch {
terminal::clear();
}
// pretty_env_logger::try_init().ok();
crate::log!("\n🤘 sweet as! 🤘\n\n{config}")
}

Self {
start_time: std::time::Instant::now(),
cases: Vec::new(),
case_logger: test_logger,
case_logger,
config,
}
}
#[cfg(target_arch = "wasm32")]
{
use crate::prelude::*;
use forky::web::*;
use std::time::Duration;
use web_sys::console;
if !config.quiet && config.watch {
console::clear();
}
if !config.quiet {
if config.watch {
console::clear();
}
log_val(&Self::pretty_print_intro(&config));
crate::log!("\n🤘 sweet as! 🤘\n\n{config}")
}
let start_time = performance_now();
Self {
start_time,
test_logger,
case_logger,
cases: Vec::new(),
config,
}
Expand All @@ -75,7 +71,7 @@ impl RunnerLogger {
return self.start_time.elapsed();
#[cfg(target_arch = "wasm32")]
return Duration::from_millis(
(performance_now() - self.start_time) as u64,
(forky::web::performance_now() - self.start_time) as u64,
);
}

Expand All @@ -88,7 +84,7 @@ impl RunnerLogger {
}
self.on_results_printed();
if !self.config.watch && !result_count.succeeded() {
std::process::exit(1);
// std::process::exit(1);
}
}

Expand Down
9 changes: 1 addition & 8 deletions src/native/run_libtest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,7 @@ use anyhow::Result;
use tokio::task::JoinHandle;
/// maybe we can allow test_main_with_filenames() as a feature
pub fn run_libtest(tests: &[&test::TestDescAndFn]) {
if let Err(err) = run_libtest_inner(tests) {
eprintln!("Sweet Internal Error: {}", err);
std::process::exit(1);
}
}

fn run_libtest_inner(tests: &[&test::TestDescAndFn]) -> Result<()> {
pub fn run_libtest(tests: &[&test::TestDescAndFn]) -> Result<()> {
tokio::runtime::Runtime::new()
.unwrap()
.block_on(async move {
Expand Down
14 changes: 5 additions & 9 deletions src/native/test_runner_rayon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,10 @@ impl TestRunner for TestRunnerRayon {
tls_desc_cell.set(Some(test.desc.clone()));

let func = TestDescAndFnExt::func(&test);
let result = SweetTestCollector::with_scope(|| {
std::panic::catch_unwind(func)
});
let result =
SweetTestCollector::with_scope(&test.desc, || {
std::panic::catch_unwind(func)
});
match result {
Ok(Ok(result)) => {
result_tx
Expand All @@ -88,12 +89,7 @@ impl TestRunner for TestRunnerRayon {
// panic result was sent in the hook
}
Err(fut) => {
future_tx
.send(TestDescAndFuture::new(
test.desc.clone(),
fut,
))
.unwrap();
future_tx.send(fut).unwrap();
}
};
let cell = desc_cell.get_or(|| Default::default());
Expand Down
3 changes: 0 additions & 3 deletions src/test_case/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
pub mod panic_store;
#[allow(unused_imports)]
pub use self::panic_store::*;
pub mod sweet_test_collector;
#[allow(unused_imports)]
pub use self::sweet_test_collector::*;
Expand Down
8 changes: 6 additions & 2 deletions src/test_case/sweet_test_collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex;
use test::TestDesc;

pub trait SweetestFuture:
'static + Future<Output = Result<(), String>>
Expand Down Expand Up @@ -37,15 +38,18 @@ impl SweetTestCollector {

/// This function uses the Error type to represent
/// that a future has been registered
pub fn with_scope<F, R>(func: F) -> Result<R, SweetFutFunc>
pub fn with_scope<F, R>(
desc: &TestDesc,
func: F,
) -> Result<R, TestDescAndFuture>
where
F: FnOnce() -> R,
{
// let val = Arc::new(Mutex::new(None));
FUTURE.with(|val| {
let out = func();
if let Some(fut) = val.lock().unwrap().take() {
Err(fut)
Err(TestDescAndFuture::new(desc.clone(), fut))
} else {
Ok(out)
}
Expand Down
Loading

0 comments on commit 1196580

Please sign in to comment.