wasm-bindgen/tests/classes.rs

143 lines
3.6 KiB
Rust
Raw Normal View History

2017-12-18 12:39:14 -08:00
extern crate test_support;
#[test]
fn simple() {
test_support::project()
.file("src/lib.rs", r#"
#![feature(proc_macro)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
wasm_bindgen! {
pub struct Foo {
contents: u32,
}
impl Foo {
pub fn new() -> Foo {
Foo::with_contents(0)
}
pub fn with_contents(a: u32) -> Foo {
2017-12-18 14:31:01 -08:00
Foo { contents: a }
2017-12-18 12:39:14 -08:00
}
pub fn add(&mut self, amt: u32) -> u32 {
self.contents += amt;
self.contents
}
}
}
"#)
.file("test.js", r#"
import * as assert from "assert";
export function test(wasm) {
2017-12-18 14:31:01 -08:00
const r = wasm.Foo.new();
2017-12-18 12:39:14 -08:00
assert.strictEqual(r.add(0), 0);
assert.strictEqual(r.add(1), 1);
assert.strictEqual(r.add(1), 2);
2017-12-18 14:31:01 -08:00
r.free();
2017-12-18 12:39:14 -08:00
const r2 = wasm.Foo.with_contents(10);
2017-12-18 14:31:01 -08:00
assert.strictEqual(r2.add(1), 11);
assert.strictEqual(r2.add(2), 13);
assert.strictEqual(r2.add(3), 16);
r2.free();
}
"#)
.test();
}
#[test]
fn strings() {
test_support::project()
.file("src/lib.rs", r#"
#![feature(proc_macro)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
wasm_bindgen! {
pub struct Foo {
name: u32,
}
pub struct Bar {
contents: String,
}
impl Foo {
pub fn new() -> Foo {
Foo { name: 0 }
}
pub fn set(&mut self, amt: u32) {
self.name = amt;
}
pub fn bar(&self, mix: &str) -> Bar {
Bar { contents: format!("foo-{}-{}", mix, self.name) }
}
}
impl Bar {
pub fn name(&self) -> String {
self.contents.clone()
}
}
}
"#)
.file("test.js", r#"
import * as assert from "assert";
export function test(wasm) {
const r = wasm.Foo.new();
r.set(3);
let bar = r.bar('baz');
r.free();
assert.strictEqual(bar.name(), "foo-baz-3");
bar.free();
2017-12-18 12:39:14 -08:00
}
"#)
.test();
}
2017-12-18 14:44:09 -08:00
#[test]
fn exceptions() {
test_support::project()
.file("src/lib.rs", r#"
#![feature(proc_macro)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
wasm_bindgen! {
pub struct A {
}
impl A {
pub fn new() -> A {
A {}
}
}
}
"#)
.file("test.js", r#"
import * as assert from "assert";
export function test(wasm) {
assert.throws(() => new wasm.A(), /cannot invoke `new` directly/);
let a = wasm.A.new();
a.free();
// TODO: figure out a better error message?
assert.throws(() => a.free(), /RuntimeError: unreachable/);
}
"#)
.test();
}