更新libclamav库1.0.0版本

This commit is contained in:
2023-01-14 18:28:39 +08:00
parent b879ee0b2e
commit 45fe15f472
8531 changed files with 1222046 additions and 177272 deletions

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,72 @@
# `js-sys` Change Log
--------------------------------------------------------------------------------
## Unreleased
Released YYYY-MM-DD.
### Added
* TODO (or remove section if none)
### Changed
* TODO (or remove section if none)
### Deprecated
* TODO (or remove section if none)
### Removed
* TODO (or remove section if none)
### Fixed
* TODO (or remove section if none)
### Security
* TODO (or remove section if none)
--------------------------------------------------------------------------------
## 0.2.1
Released 2018-08-13.
### Added
* Added bindings to `Array.prototype.splice`.
* Added bindings to `RegExp`.
* Added bindings to `ArrayBuffer.prototype.byteLength`.
* Started adding the `#[wasm_bindgen(extends = ...)]` attribute to various JS
types.
* Added bindings to `EvalError`.
* Added bindings to `Promise`. See the new `wasm-bindgen-futures` crate for
integrating JS `Promise`s into Rust `Future`s.
* Added bindings to `JSON.{parse,stringify}`.
* Added bindings to `Array.of`.
* Added bindings to `Intl.Collator`.
* Added bindings to `Object.assign`.
* Added bindings to `Object.create`.
* Added bindings to `RangeError`.
* Added bindings to `ReferenceError`.
* Added bindings to `Symbol.unscopables`.
* Added bindings to `URIError`.
* Added bindings to `SyntaxError`.
* Added bindings to `TypeError`.
### Changed
* The `Intl` namespace was previously a bound object with static methods hanging
off of it. It is now a module with free functions, and nested types.
--------------------------------------------------------------------------------
## 0.2.0
Released 2018-07-26.
Initial release!

View File

@@ -0,0 +1,47 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2018"
name = "js-sys"
version = "0.3.60"
authors = ["The wasm-bindgen Developers"]
description = """
Bindings for all JS global objects and functions in all JS environments like
Node.js and browsers, built on `#[wasm_bindgen]` using the `wasm-bindgen` crate.
"""
homepage = "https://rustwasm.github.io/wasm-bindgen/"
documentation = "https://docs.rs/js-sys"
readme = "./README.md"
categories = ["wasm"]
license = "MIT/Apache-2.0"
repository = "https://github.com/rustwasm/wasm-bindgen/tree/master/crates/js-sys"
[lib]
test = false
doctest = false
[dependencies.wasm-bindgen]
version = "0.2.83"
[target."cfg(target_arch = \"wasm32\")".dev-dependencies.wasm-bindgen-futures]
version = "0.4.33"
[target."cfg(target_arch = \"wasm32\")".dev-dependencies.wasm-bindgen-test]
version = "=0.3.33"
[target."cfg(target_arch = \"wasm32\")".dev-dependencies.web-sys]
version = "0.3.60"
features = [
"Headers",
"Response",
"ResponseInit",
]

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,25 @@
Copyright (c) 2014 Alex Crichton
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,7 @@
# `js-sys`
[API documentation](https://rustwasm.github.io/wasm-bindgen/api/js_sys/)
Raw bindings to JS global APIs for projects using `wasm-bindgen`. This crate is
handwritten and intended to work in *all* JS environments like browsers and
Node.js.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
export function is_array_values_supported() {
return typeof Array.prototype.values === 'function';
}

View File

@@ -0,0 +1,47 @@
#![cfg(target_arch = "wasm32")]
extern crate js_sys;
extern crate wasm_bindgen;
extern crate wasm_bindgen_test;
use js_sys::Array;
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen(module = "/tests/headless.js")]
extern "C" {
fn is_array_values_supported() -> bool;
}
#[wasm_bindgen]
extern "C" {
type ValuesIterator;
#[wasm_bindgen(method, structural)]
fn next(this: &ValuesIterator) -> IterNext;
type IterNext;
#[wasm_bindgen(method, getter, structural)]
fn value(this: &IterNext) -> JsValue;
#[wasm_bindgen(method, getter, structural)]
fn done(this: &IterNext) -> bool;
}
#[wasm_bindgen_test]
fn array_iterator_values() {
if !is_array_values_supported() {
return;
}
let array = Array::new();
array.push(&8.into());
array.push(&3.into());
array.push(&2.into());
let iter = ValuesIterator::from(JsValue::from(array.values()));
assert_eq!(iter.next().value(), 8);
assert_eq!(iter.next().value(), 3);
assert_eq!(iter.next().value(), 2);
assert!(iter.next().done());
}

View File

@@ -0,0 +1,7 @@
// Used for `Array.rs` tests
exports.populate_array = function(arr, start, len) {
var isBigInt = typeof(arr[0]) === "bigint";
for (i = 0; i < len; i++) {
arr[i] = isBigInt ? BigInt(start + i) : start + i;
}
};

View File

@@ -0,0 +1,647 @@
use js_sys::*;
use std::iter::FromIterator;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
macro_rules! js_array {
($($e:expr),*) => ({
let __x = Array::new();
$(__x.push(&JsValue::from($e));)*
__x
})
}
macro_rules! array {
($($e:expr),*) => ({
let mut __x = Vec::new();
$(__x.push(JsValue::from($e));)*
__x
})
}
fn to_rust(arr: &Array) -> Vec<JsValue> {
let mut result = Vec::with_capacity(arr.length() as usize);
arr.for_each(&mut |x, _, _| result.push(x));
result
}
#[wasm_bindgen_test]
fn from_iter() {
assert_eq!(
to_rust(
&vec![JsValue::from("a"), JsValue::from("b"), JsValue::from("c"),]
.into_iter()
.collect()
),
vec!["a", "b", "c"],
);
assert_eq!(
to_rust(
&vec![JsValue::from("a"), JsValue::from("b"), JsValue::from("c"),]
.iter()
.collect()
),
vec!["a", "b", "c"],
);
let array = js_array![1u32, 2u32, 3u32];
assert_eq!(
to_rust(&vec![array.clone(),].into_iter().collect()),
vec![JsValue::from(array.clone())],
);
assert_eq!(
to_rust(&vec![array.clone(),].iter().collect()),
vec![JsValue::from(array)],
);
assert_eq!(
to_rust(&vec![5, 10, 20,].into_iter().map(JsValue::from).collect()),
vec![5, 10, 20],
);
assert_eq!(
to_rust(&Array::from_iter(&[
JsValue::from("a"),
JsValue::from("b"),
JsValue::from("c"),
])),
vec!["a", "b", "c"],
);
let v = vec!["a", "b", "c"];
assert_eq!(
to_rust(&Array::from_iter(v.into_iter().map(|s| JsValue::from(s)))),
vec!["a", "b", "c"],
);
}
#[wasm_bindgen_test]
fn extend() {
let mut array = array!["a", "b"];
array.extend(vec![JsValue::from("c"), JsValue::from("d")]);
assert_eq!(array, array!["a", "b", "c", "d"]);
}
#[wasm_bindgen_test]
fn to_vec() {
let array = vec![JsValue::from("a"), JsValue::from("b"), JsValue::from("c")]
.into_iter()
.collect::<js_sys::Array>();
assert_eq!(
array.to_vec(),
vec![JsValue::from("a"), JsValue::from("b"), JsValue::from("c")]
);
}
#[wasm_bindgen_test]
fn iter() {
let array = vec![JsValue::from("a"), JsValue::from("b"), JsValue::from("c")]
.into_iter()
.collect::<js_sys::Array>();
assert_eq!(
array.iter().collect::<Vec<JsValue>>(),
vec![JsValue::from("a"), JsValue::from("b"), JsValue::from("c")]
);
let mut iter = array.iter();
assert_eq!(iter.size_hint(), (3, Some(3)));
assert_eq!(iter.next(), Some(JsValue::from("a")));
assert_eq!(iter.size_hint(), (2, Some(2)));
assert_eq!(iter.next_back(), Some(JsValue::from("c")));
assert_eq!(iter.size_hint(), (1, Some(1)));
assert_eq!(iter.next_back(), Some(JsValue::from("b")));
assert_eq!(iter.size_hint(), (0, Some(0)));
assert_eq!(iter.next(), None);
assert_eq!(iter.size_hint(), (0, Some(0)));
assert_eq!(iter.next_back(), None);
let mut iter = array.iter();
assert_eq!(iter.size_hint(), (3, Some(3)));
assert_eq!(iter.next(), Some(JsValue::from("a")));
assert_eq!(iter.size_hint(), (2, Some(2)));
assert_eq!(iter.next(), Some(JsValue::from("b")));
assert_eq!(iter.size_hint(), (1, Some(1)));
assert_eq!(iter.next(), Some(JsValue::from("c")));
assert_eq!(iter.size_hint(), (0, Some(0)));
assert_eq!(iter.next(), None);
let mut iter = array.iter();
assert_eq!(iter.size_hint(), (3, Some(3)));
assert_eq!(iter.next_back(), Some(JsValue::from("c")));
assert_eq!(iter.size_hint(), (2, Some(2)));
assert_eq!(iter.next_back(), Some(JsValue::from("b")));
assert_eq!(iter.size_hint(), (1, Some(1)));
assert_eq!(iter.next_back(), Some(JsValue::from("a")));
assert_eq!(iter.size_hint(), (0, Some(0)));
assert_eq!(iter.next_back(), None);
}
#[wasm_bindgen_test]
fn new_with_length() {
let array = Array::new_with_length(5);
assert_eq!(array.length(), 5);
assert_eq!(array.get(4), JsValue::undefined());
array.set(4, JsValue::from("a"));
assert_eq!(array.get(4), "a");
assert_eq!(array.length(), 5);
}
#[wasm_bindgen_test]
fn get() {
let array = js_array!["a", "c", "x", "n"];
assert_eq!(array.length(), 4);
assert_eq!(array.get(0), "a");
assert_eq!(array.get(3), "n");
assert_eq!(array.get(4), JsValue::undefined());
}
#[wasm_bindgen_test]
fn set() {
let array = js_array!["a", "c", "x", "n"];
assert_eq!(array.length(), 4);
assert_eq!(array.get(0), "a");
array.set(0, JsValue::from("b"));
assert_eq!(array.get(0), "b");
assert_eq!(array.get(4), JsValue::undefined());
assert_eq!(array.length(), 4);
array.set(4, JsValue::from("d"));
assert_eq!(array.length(), 5);
assert_eq!(array.get(4), "d");
assert_eq!(array.get(10), JsValue::undefined());
assert_eq!(array.length(), 5);
array.set(10, JsValue::from("z"));
assert_eq!(array.length(), 11);
assert_eq!(array.get(10), "z");
assert_eq!(array.get(9), JsValue::undefined());
}
#[wasm_bindgen_test]
fn delete() {
let array = js_array!["a", "c", "x", "n"];
assert_eq!(array.length(), 4);
assert_eq!(array.get(0), "a");
array.delete(0);
assert_eq!(array.get(0), JsValue::undefined());
}
#[wasm_bindgen_test]
fn filter() {
let array = js_array!["a", "c", "x", "n"];
assert!(array.filter(&mut |x, _, _| x.as_f64().is_some()).length() == 0);
let array = js_array![1, 2, 3, 4];
assert_eq!(
array.filter(&mut |x, _, _| x.as_f64().is_some()).length(),
4
);
let array = js_array!["a", 1, "b", 2];
assert_eq!(
array.filter(&mut |x, _, _| x.as_f64().is_some()).length(),
2
);
}
#[wasm_bindgen_test]
fn flat() {
let array = js_array![
js_array!["a", "b", "c"],
"d",
js_array!["e", js_array!["f", "g"]]
];
assert_eq!(
to_rust(&array.flat(1).slice(0, 5)),
vec!["a", "b", "c", "d", "e"]
);
assert_eq!(array.flat(1).length(), 6);
assert_eq!(
to_rust(&array.flat(2)),
vec!["a", "b", "c", "d", "e", "f", "g"]
);
}
#[wasm_bindgen_test]
fn flat_map() {
let array = js_array![1, 2, 3, 1];
assert_eq!(
to_rust(
&array.flat_map(&mut |val, _, _| match val.as_f64().map(|v| v as i32) {
Some(1) => vec![JsString::from("x").into(), JsString::from("x").into()],
Some(2) => vec![],
Some(3) => vec![JsString::from("z").into()],
_ => panic!("Unexpected conversion"),
})
),
vec!["x", "x", "z", "x", "x"]
);
}
#[wasm_bindgen_test]
fn index_of() {
let chars = js_array!["a", "c", "x", "n"];
assert_eq!(chars.index_of(&"x".into(), 0), 2);
assert_eq!(chars.index_of(&"z".into(), 0), -1);
assert_eq!(chars.index_of(&"x".into(), -3), 2);
assert_eq!(chars.index_of(&"z".into(), -2), -1);
}
#[wasm_bindgen_test]
fn is_array() {
assert!(Array::is_array(&Array::new().into()));
assert!(Array::is_array(&js_array![1].into()));
assert!(!Array::is_array(&JsValue::null()));
assert!(!Array::is_array(&JsValue::undefined()));
assert!(!Array::is_array(&10.into()));
assert!(!Array::is_array(&"x".into()));
assert!(!Array::is_array(&true.into()));
assert!(!Array::is_array(&false.into()));
}
#[wasm_bindgen_test]
fn sort() {
let array = js_array![3, 1, 6, 2];
let sorted = array.sort();
assert_eq!(to_rust(&sorted), array![1, 2, 3, 6]);
}
#[wasm_bindgen_test]
fn some() {
let array = js_array!["z", 1, "y", 2];
assert!(array.some(&mut |e| e == JsValue::from(2)));
assert!(array.some(&mut |e| e == JsValue::from("y")));
assert!(!array.some(&mut |e| e == JsValue::from("nope")));
}
#[wasm_bindgen_test]
fn last_index_of() {
let characters = js_array!["a", "x", "c", "x", "n"];
assert_eq!(characters.last_index_of(&"x".into(), 5), 3);
assert_eq!(characters.last_index_of(&"z".into(), 5), -1);
assert_eq!(characters.last_index_of(&"x".into(), 2), 1);
assert_eq!(characters.last_index_of(&"x".into(), 0), -1);
}
#[wasm_bindgen_test]
fn join() {
let characters = js_array!["a", "c", "x", "n"];
assert_eq!(String::from(characters.join(", ")), "a, c, x, n");
assert_eq!(String::from(characters.join("/")), "a/c/x/n");
}
#[wasm_bindgen_test]
fn slice() {
let characters = js_array!["a", "c", "x", "n", 1, "8"];
let subset = characters.slice(1, 3);
assert_eq!(to_rust(&subset), array!["c", "x"]);
}
#[wasm_bindgen_test]
fn splice() {
let characters = js_array!["a", "c", "x", "n", 1, "8"];
let removed = characters.splice(1, 3, &"b".into());
assert_eq!(to_rust(&removed), array!["c", "x", "n"]);
assert_eq!(to_rust(&characters), array!["a", "b", 1, "8"]);
}
#[wasm_bindgen_test]
fn fill() {
let characters = js_array!["a", "c", "x", "n", 1, "8"];
let subset = characters.fill(&0.into(), 0, 3);
assert_eq!(to_rust(&subset), array![0, 0, 0, "n", 1, "8"]);
}
#[wasm_bindgen_test]
fn copy_within() {
let characters = js_array![8, 5, 4, 3, 1, 2];
characters.copy_within(1, 4, 5);
assert_eq!(to_rust(&characters)[1], JsValue::from(1));
// if negatives were used
characters.copy_within(-1, -3, -2);
assert_eq!(to_rust(&characters)[5], JsValue::from(3));
}
#[wasm_bindgen_test]
fn of() {
let a = JsValue::from("a");
let b = JsValue::from("b");
let c = JsValue::from("c");
let arr = Array::of3(&a, &b, &c);
let vec = to_rust(&arr);
assert_eq!(vec.len(), 3);
assert_eq!(vec[0], a);
assert_eq!(vec[1], b);
assert_eq!(vec[2], c);
}
#[wasm_bindgen_test]
fn pop() {
let characters = js_array![8, 5, 4, 3, 1, 2];
let item = characters.pop();
assert_eq!(item, JsValue::from(2));
assert_eq!(characters.length(), 5);
}
#[wasm_bindgen_test]
fn push() {
let characters = js_array![8, 5, 4, 3, 1, 2];
let length = characters.push(&"a".into());
assert_eq!(length, 7);
assert_eq!(to_rust(&characters)[6], "a");
}
#[wasm_bindgen_test]
fn reverse() {
let characters = js_array![8, 5, 4, 3, 1, 2];
let reversed = characters.reverse();
assert_eq!(to_rust(&reversed), array![2, 1, 3, 4, 5, 8]);
}
#[wasm_bindgen_test]
fn shift() {
let characters = js_array![8, 5, 4, 3, 1, 2];
let shiftedItem = characters.shift();
assert_eq!(shiftedItem, 8);
assert_eq!(characters.length(), 5);
}
#[wasm_bindgen_test]
fn unshift() {
let characters = js_array![8, 5, 4, 3, 1, 2];
let length = characters.unshift(&"abba".into());
assert_eq!(length, 7);
assert_eq!(to_rust(&characters)[0], "abba");
}
#[wasm_bindgen_test]
fn to_string() {
let characters = js_array![8, 5, 4, 3, 1, 2];
assert_eq!(String::from(characters.to_string()), "8,5,4,3,1,2");
}
#[wasm_bindgen_test]
fn includes() {
let characters = js_array![8, 5, 4, 3, 1, 2];
assert!(characters.includes(&2.into(), 0));
assert!(!characters.includes(&9.into(), 0));
assert!(!characters.includes(&3.into(), 4));
}
#[wasm_bindgen_test]
fn concat() {
let arr1 = js_array![1, 2, 3];
let arr2 = js_array![4, 5, 6];
let new_array = arr1.concat(&arr2);
assert_eq!(to_rust(&new_array), array![1, 2, 3, 4, 5, 6]);
}
#[wasm_bindgen_test]
fn length() {
let characters = js_array![8, 5, 4, 3, 1, 2];
assert_eq!(characters.length(), 6);
assert_eq!(Array::new().length(), 0);
}
#[wasm_bindgen_test]
fn every() {
let even = js_array![2, 4, 6, 8];
assert!(even.every(&mut |x, _, _| x.as_f64().unwrap() % 2.0 == 0.0));
let odd = js_array![1, 3, 5, 7];
assert!(!odd.every(&mut |x, _, _| x.as_f64().unwrap() % 2.0 == 0.0));
let mixed = js_array![2, 3, 4, 5];
assert!(!mixed.every(&mut |x, _, _| x.as_f64().unwrap() % 2.0 == 0.0));
}
#[wasm_bindgen_test]
fn find() {
let even = js_array![2, 4, 6, 8];
assert_eq!(
even.find(&mut |x, _, _| x.as_f64().unwrap() % 2.0 == 0.0),
2
);
let odd = js_array![1, 3, 5, 7];
assert_eq!(
odd.find(&mut |x, _, _| x.as_f64().unwrap() % 2.0 == 0.0),
JsValue::undefined(),
);
let mixed = js_array![3, 5, 7, 10];
assert_eq!(
mixed.find(&mut |x, _, _| x.as_f64().unwrap() % 2.0 == 0.0),
10
);
}
#[wasm_bindgen_test]
fn map() {
let numbers = js_array![1, 4, 9];
let sqrt = numbers.map(&mut |x, _, _| x.as_f64().unwrap().sqrt().into());
assert_eq!(to_rust(&sqrt), array![1, 2, 3]);
}
#[wasm_bindgen_test]
fn reduce() {
let arr = js_array!["0", "1", "2", "3", "4"].reduce(
&mut |ac, cr, _, _| {
format!("{}{}", &ac.as_string().unwrap(), &cr.as_string().unwrap()).into()
},
&"".into(),
);
assert_eq!(arr, "01234");
}
#[wasm_bindgen_test]
fn reduce_right() {
let arr = js_array!["0", "1", "2", "3", "4"].reduce_right(
&mut |ac, cr, _, _| {
format!("{}{}", &ac.as_string().unwrap(), &cr.as_string().unwrap()).into()
},
&"".into(),
);
assert_eq!(arr, "43210");
}
#[wasm_bindgen_test]
fn find_index() {
let even = js_array![2, 4, 6, 8];
assert_eq!(
even.find_index(&mut |e, _, _| e.as_f64().unwrap() % 2. == 0.),
0
);
let odd = js_array![1, 3, 5, 7];
assert_eq!(
odd.find_index(&mut |e, _, _| e.as_f64().unwrap() % 2. == 0.),
-1
);
let mixed = js_array![3, 5, 7, 10];
assert_eq!(
mixed.find_index(&mut |e, _, _| e.as_f64().unwrap() % 2. == 0.),
3
);
}
#[wasm_bindgen_test]
fn to_locale_string() {
let output = js_array![1, "a", Date::new(&"21 Dec 1997 14:12:00 UTC".into())]
.to_locale_string(&"en".into(), &JsValue::undefined());
assert!(String::from(output).len() > 0);
}
#[wasm_bindgen_test]
fn for_each() {
fn sum_indices_of_evens(array: &Array) -> u32 {
let mut res = 0;
array.for_each(&mut |elem: JsValue, i, _| match elem.as_f64() {
Some(val) if val % 2. == 0. => res += i,
_ => {}
});
res
}
assert_eq!(sum_indices_of_evens(&js_array![2, 4, 6, 8]), 0 + 1 + 2 + 3);
assert_eq!(sum_indices_of_evens(&js_array![1, 3, 5, 7]), 0);
assert_eq!(sum_indices_of_evens(&js_array![3, 5, 7, 10]), 3);
}
#[wasm_bindgen_test]
fn array_inheritance() {
let array = Array::new();
assert!(array.is_instance_of::<Array>());
assert!(array.is_instance_of::<Object>());
let _: &Object = array.as_ref();
}
#[wasm_bindgen(module = "tests/wasm/Array.js")]
extern "C" {
fn populate_array(arr: JsValue, start: JsValue, len: JsValue) -> JsValue;
}
fn test_array_view_mut_raw<ElemT: std::cmp::PartialEq + std::fmt::Debug, ArrT>(
sut: unsafe fn(*mut ElemT, usize) -> ArrT,
u8ToElem: fn(u8) -> ElemT,
arrToJsValue: fn(ArrT) -> JsValue,
) {
let start: u8 = 10;
let len: usize = 32;
let end: u8 = start + len as u8;
let mut buffer: Vec<ElemT> = Vec::new();
buffer.reserve(len);
unsafe {
let array: ArrT = sut(buffer.as_mut_ptr(), len);
populate_array(
arrToJsValue(array),
JsValue::from(start),
JsValue::from(len as u32),
);
buffer.set_len(len);
}
let expected: Vec<ElemT> = (start..end).map(u8ToElem).collect();
assert_eq!(buffer, expected)
}
#[wasm_bindgen_test]
fn Int8Array_view_mut_raw() {
fn u8Toi8_unsafe(x: u8) -> i8 {
x as i8
}
test_array_view_mut_raw(
js_sys::Int8Array::view_mut_raw,
u8Toi8_unsafe,
JsValue::from,
);
}
#[wasm_bindgen_test]
fn Int16Array_view_mut_raw() {
test_array_view_mut_raw(js_sys::Int16Array::view_mut_raw, i16::from, JsValue::from);
}
#[wasm_bindgen_test]
fn Int32Array_view_mut_raw() {
test_array_view_mut_raw(js_sys::Int32Array::view_mut_raw, i32::from, JsValue::from);
}
#[wasm_bindgen_test]
fn BigInt64Array_view_mut_raw() {
test_array_view_mut_raw(
js_sys::BigInt64Array::view_mut_raw,
i64::from,
JsValue::from,
);
}
#[wasm_bindgen_test]
fn Uint8Array_view_mut_raw() {
test_array_view_mut_raw(js_sys::Uint8Array::view_mut_raw, u8::from, JsValue::from);
}
#[wasm_bindgen_test]
fn Uint8ClampedArray_view_mut_raw() {
test_array_view_mut_raw(
js_sys::Uint8ClampedArray::view_mut_raw,
u8::from,
JsValue::from,
);
}
#[wasm_bindgen_test]
fn Uint16Array_view_mut_raw() {
test_array_view_mut_raw(js_sys::Uint16Array::view_mut_raw, u16::from, JsValue::from);
}
#[wasm_bindgen_test]
fn Uint32Array_view_mut_raw() {
test_array_view_mut_raw(js_sys::Uint32Array::view_mut_raw, u32::from, JsValue::from);
}
#[wasm_bindgen_test]
fn BigUint64Array_view_mut_raw() {
test_array_view_mut_raw(
js_sys::BigUint64Array::view_mut_raw,
u64::from,
JsValue::from,
);
}
#[wasm_bindgen_test]
fn Float32Array_view_mut_raw() {
test_array_view_mut_raw(js_sys::Float32Array::view_mut_raw, f32::from, JsValue::from);
}
#[wasm_bindgen_test]
fn Float64Array_view_mut_raw() {
test_array_view_mut_raw(js_sys::Float64Array::view_mut_raw, f64::from, JsValue::from);
}

View File

@@ -0,0 +1,45 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn new() {
let x = ArrayBuffer::new(42);
let y: JsValue = x.into();
assert!(y.is_object());
}
#[wasm_bindgen_test]
fn byte_length() {
let buf = ArrayBuffer::new(42);
assert_eq!(buf.byte_length(), 42);
}
#[wasm_bindgen_test]
fn is_view() {
let x = Uint8Array::new(&JsValue::from(42));
assert!(ArrayBuffer::is_view(&JsValue::from(x)));
}
#[wasm_bindgen_test]
fn slice() {
let buf = ArrayBuffer::new(4);
let slice = buf.slice(2);
assert!(JsValue::from(slice).is_object());
}
#[wasm_bindgen_test]
fn slice_with_end() {
let buf = ArrayBuffer::new(4);
let slice = buf.slice_with_end(1, 2);
assert!(JsValue::from(slice).is_object());
}
#[wasm_bindgen_test]
fn arraybuffer_inheritance() {
let buf = ArrayBuffer::new(4);
assert!(buf.is_instance_of::<ArrayBuffer>());
assert!(buf.is_instance_of::<Object>());
let _: &Object = buf.as_ref();
}

View File

@@ -0,0 +1,39 @@
use js_sys::*;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn keys() {
let array = Array::new();
array.push(&JsValue::from(1));
array.push(&JsValue::from(2));
array.push(&JsValue::from(3));
array.push(&JsValue::from(4));
array.push(&JsValue::from(5));
let new_array = Array::from(&array.keys().into());
let mut result = Vec::new();
new_array.for_each(&mut |i, _, _| result.push(i.as_f64().unwrap()));
assert_eq!(result, [0.0, 1.0, 2.0, 3.0, 4.0]);
}
#[wasm_bindgen_test]
fn entries() {
let array = Array::new();
array.push(&JsValue::from(1));
array.push(&JsValue::from(2));
array.push(&JsValue::from(3));
array.push(&JsValue::from(4));
array.push(&JsValue::from(5));
let new_array = Array::from(&array.entries().into());
new_array.for_each(&mut |a, i, _| {
assert!(a.is_object());
let array: Array = a.into();
assert_eq!(array.shift().as_f64().unwrap(), i as f64);
assert_eq!(array.shift().as_f64().unwrap(), (i + 1) as f64);
assert_eq!(array.length(), 0);
});
}

View File

@@ -0,0 +1,43 @@
use js_sys::BigInt;
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::wasm_bindgen_test;
/// `assert_eq!`, but the arguments are converted to `JsValue`s.
#[track_caller]
fn assert_jsvalue_eq(a: impl Into<JsValue>, b: impl Into<JsValue>) {
assert_eq!(a.into(), b.into());
}
#[wasm_bindgen_test]
fn from() {
// Test that all the `From` impls work properly.
assert_jsvalue_eq(BigInt::from(1u8), 1u64);
assert_jsvalue_eq(BigInt::from(1u16), 1u64);
assert_jsvalue_eq(BigInt::from(1u32), 1u64);
assert_jsvalue_eq(BigInt::from(1u64), 1u64);
assert_jsvalue_eq(BigInt::from(1u128), 1u64);
assert_jsvalue_eq(BigInt::from(1usize), 1u64);
assert_jsvalue_eq(BigInt::from(-3i8), -3i64);
assert_jsvalue_eq(BigInt::from(-3i16), -3i64);
assert_jsvalue_eq(BigInt::from(-3i32), -3i64);
assert_jsvalue_eq(BigInt::from(-3i64), -3i64);
assert_jsvalue_eq(BigInt::from(-3i128), -3i64);
assert_jsvalue_eq(BigInt::from(-3isize), -3i64);
}
#[wasm_bindgen_test]
fn eq() {
// Test that all the `Eq` impls work properly.
assert_eq!(BigInt::from(1u64), 1u8);
assert_eq!(BigInt::from(1u64), 1u16);
assert_eq!(BigInt::from(1u64), 1u32);
assert_eq!(BigInt::from(1u64), 1u64);
assert_eq!(BigInt::from(1u64), 1u128);
assert_eq!(BigInt::from(1u64), 1usize);
assert_eq!(BigInt::from(-3i64), -3i8);
assert_eq!(BigInt::from(-3i64), -3i16);
assert_eq!(BigInt::from(-3i64), -3i32);
assert_eq!(BigInt::from(-3i64), -3i64);
assert_eq!(BigInt::from(-3i64), -3i128);
assert_eq!(BigInt::from(-3i64), -3isize);
}

View File

@@ -0,0 +1,25 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
#[allow(deprecated)]
#[wasm_bindgen_test]
fn new_undefined() {
assert_eq!(Boolean::new(&JsValue::undefined()).value_of(), false);
}
#[allow(deprecated)]
#[wasm_bindgen_test]
fn new_truely() {
assert_eq!(Boolean::new(&JsValue::from("foo")).value_of(), true);
}
#[allow(deprecated)]
#[wasm_bindgen_test]
fn boolean_inheritance() {
let b = Boolean::new(&JsValue::from(true));
assert!(b.is_instance_of::<Boolean>());
assert!(b.is_instance_of::<Object>());
let _: &Object = b.as_ref();
}

View File

@@ -0,0 +1,84 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn test() {
let bytes = Int8Array::new(&JsValue::from(10));
// TODO: figure out how to do `bytes[2] = 2`
bytes.subarray(2, 3).fill(2, 0, 1);
let v = DataView::new(&bytes.buffer(), 2, 8);
assert_eq!(v.byte_offset(), 2);
assert_eq!(v.byte_length(), 8);
assert_eq!(v.get_int8(0), 2);
assert_eq!(v.get_uint8(0), 2);
v.set_int8(0, 42);
assert_eq!(v.get_int8(0), 42);
v.set_uint8(0, 255);
assert_eq!(v.get_uint8(0), 255);
v.set_int16(0, 32767);
assert_eq!(v.get_int16(0), 32767);
v.set_int16_endian(0, 0x1122, true);
assert_eq!(v.get_int16_endian(0, true), 0x1122);
assert_eq!(v.get_int16_endian(0, false), 0x2211);
v.set_uint16(0, 65535);
assert_eq!(v.get_uint16(0), 65535);
v.set_uint16_endian(0, 0x1122, true);
assert_eq!(v.get_uint16_endian(0, true), 0x1122);
assert_eq!(v.get_uint16_endian(0, false), 0x2211);
v.set_int32(0, 123456789);
assert_eq!(v.get_int32(0), 123456789);
v.set_int32_endian(0, 0x11223344, true);
assert_eq!(v.get_int32_endian(0, true), 0x11223344);
assert_eq!(v.get_int32_endian(0, false), 0x44332211);
v.set_uint32(0, 3_123_456_789);
assert_eq!(v.get_uint32(0), 3_123_456_789);
v.set_uint32_endian(0, 0x11223344, true);
assert_eq!(v.get_uint32_endian(0, true), 0x11223344);
assert_eq!(v.get_uint32_endian(0, false), 0x44332211);
v.set_float32(0, 100.123);
assert_eq!(v.get_float32(0), 100.123);
v.set_float32_endian(0, f32::from_bits(0x11223344), true);
assert_eq!(v.get_float32_endian(0, true), f32::from_bits(0x11223344));
assert_eq!(v.get_float32_endian(0, false), f32::from_bits(0x44332211));
v.set_float64(0, 123456789.123456);
assert_eq!(v.get_float64(0), 123456789.123456);
v.set_float64_endian(0, f64::from_bits(0x1122334411223344), true);
assert_eq!(
v.get_float64_endian(0, true),
f64::from_bits(0x1122334411223344)
);
assert_eq!(
v.get_float64_endian(0, false),
f64::from_bits(0x4433221144332211)
);
v.set_int8(0, 42);
// TODO: figure out how to do `bytes[2]`
bytes
.subarray(2, 3)
.for_each(&mut |x, _, _| assert_eq!(x, 42));
}
#[wasm_bindgen_test]
fn dataview_inheritance() {
let bytes = Int8Array::new(&JsValue::from(10));
// TODO: figure out how to do `bytes[2] = 2`
bytes.subarray(2, 3).fill(2, 0, 1);
let v = DataView::new(&bytes.buffer(), 2, 8);
assert!(v.is_instance_of::<DataView>());
assert!(v.is_instance_of::<Object>());
let _: &Object = v.as_ref();
}

View File

@@ -0,0 +1,530 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn get_date() {
let date = Date::new(&"August 19, 1975 23:15:30".into());
assert_eq!(date.get_date(), 19);
}
#[wasm_bindgen_test]
fn get_day() {
let date = Date::new(&"August 19, 1975 23:15:30".into());
assert_eq!(date.get_day(), 2);
}
#[wasm_bindgen_test]
fn get_full_year() {
let date = Date::new(&"July 20, 1969 00:20:18".into());
let abbr = Date::new(&"Thu, 06 Sep 12 00:00:00".into());
assert_eq!(date.get_full_year(), 1969);
assert_eq!(abbr.get_full_year(), 2012);
}
#[wasm_bindgen_test]
fn get_hours() {
let date = Date::new(&"March 13, 08 04:20".into());
assert_eq!(date.get_hours(), 4);
}
#[wasm_bindgen_test]
fn get_milliseconds() {
let date = Date::new(&"1995-12-17T09:24:00Z".into());
let ms = Date::new(&"1995-12-17T09:24:00.123Z".into());
assert_eq!(date.get_milliseconds(), 0);
assert_eq!(ms.get_milliseconds(), 123);
}
#[wasm_bindgen_test]
fn get_minutes() {
let date = Date::new(&"March 13, 08 04:20".into());
assert_eq!(date.get_minutes(), 20);
}
#[wasm_bindgen_test]
fn get_month() {
let date = Date::new(&"July 20, 69 00:20:18".into());
assert_eq!(date.get_month(), 6);
}
#[wasm_bindgen_test]
fn get_seconds() {
let date = Date::new(&"July 20, 69 00:20:18".into());
assert_eq!(date.get_seconds(), 18);
}
#[wasm_bindgen_test]
fn get_time() {
let date = Date::new(&"July 20, 69 00:20:18 GMT+00:00".into());
assert_eq!(date.get_time(), -14254782000.0);
}
#[wasm_bindgen_test]
fn get_timezone_offset() {
let date1 = Date::new(&"August 19, 1975 23:15:30 GMT+07:00".into());
let date2 = Date::new(&"August 19, 1975 23:15:30 GMT-02:00".into());
assert_eq!(date1.get_timezone_offset(), date2.get_timezone_offset());
}
#[wasm_bindgen_test]
fn get_utc_date() {
let date1 = Date::new(&"August 19, 1975 23:15:30 GMT+11:00".into());
let date2 = Date::new(&"August 19, 1975 23:15:30 GMT-11:00".into());
assert_eq!(date1.get_utc_date(), 19);
assert_eq!(date2.get_utc_date(), 20);
}
#[wasm_bindgen_test]
fn get_utc_day() {
let date1 = Date::new(&"August 19, 1975 23:15:30 GMT+11:00".into());
let date2 = Date::new(&"August 19, 1975 23:15:30 GMT-11:00".into());
assert_eq!(date1.get_utc_day(), 2);
assert_eq!(date2.get_utc_day(), 3);
}
#[wasm_bindgen_test]
fn get_utc_full_year() {
let date1 = Date::new(&"December 31, 1975, 23:15:30 GMT+11:00".into());
let date2 = Date::new(&"December 31, 1975, 23:15:30 GMT-11:00".into());
assert_eq!(date1.get_utc_full_year(), 1975);
assert_eq!(date2.get_utc_full_year(), 1976);
}
#[wasm_bindgen_test]
fn get_utc_hours() {
let date1 = Date::new(&"December 31, 1975, 23:15:30 GMT+11:00".into());
let date2 = Date::new(&"December 31, 1975, 23:15:30 GMT-11:00".into());
assert_eq!(date1.get_utc_hours(), 12);
assert_eq!(date2.get_utc_hours(), 10);
}
#[wasm_bindgen_test]
fn get_utc_milliseconds() {
let date = Date::new(&"2018-01-02T03:04:05.678Z".into());
assert_eq!(date.get_utc_milliseconds(), 678);
}
#[wasm_bindgen_test]
fn get_utc_minutes() {
let date1 = Date::new(&"1 January 2000 03:15:30 GMT+07:00".into());
let date2 = Date::new(&"1 January 2000 03:15:30 GMT+03:30".into());
assert_eq!(date1.get_utc_minutes(), 15);
assert_eq!(date2.get_utc_minutes(), 45);
}
#[wasm_bindgen_test]
fn get_utc_month() {
let date1 = Date::new(&"December 31, 1975, 23:15:30 GMT+11:00".into());
let date2 = Date::new(&"December 31, 1975, 23:15:30 GMT-11:00".into());
assert_eq!(date1.get_utc_month(), 11);
assert_eq!(date2.get_utc_month(), 0);
}
#[wasm_bindgen_test]
fn get_utc_seconds() {
let date = Date::new(&"July 20, 1969, 20:18:04 UTC".into());
assert_eq!(date.get_utc_seconds(), 4);
}
#[wasm_bindgen_test]
fn new() {
assert!(JsValue::from(Date::new(&JsValue::undefined())).is_object());
}
#[wasm_bindgen_test]
fn new_with_year_month() {
let date1 = Date::new_with_year_month(1975, 7);
assert_eq!(date1.get_full_year(), 1975);
assert_eq!(date1.get_month(), 7);
}
#[wasm_bindgen_test]
fn new_with_year_month_day() {
let date1 = Date::new_with_year_month_day(1975, 7, 8);
assert_eq!(date1.get_full_year(), 1975);
assert_eq!(date1.get_month(), 7);
assert_eq!(date1.get_date(), 8);
}
#[wasm_bindgen_test]
fn new_with_year_month_day_hr() {
let date1 = Date::new_with_year_month_day_hr(1975, 7, 8, 4);
assert_eq!(date1.get_full_year(), 1975);
assert_eq!(date1.get_month(), 7);
assert_eq!(date1.get_date(), 8);
assert_eq!(date1.get_hours(), 4);
}
#[wasm_bindgen_test]
fn new_with_year_month_day_hr_min() {
let date1 = Date::new_with_year_month_day_hr_min(1975, 7, 8, 4, 35);
assert_eq!(date1.get_full_year(), 1975);
assert_eq!(date1.get_month(), 7);
assert_eq!(date1.get_date(), 8);
assert_eq!(date1.get_hours(), 4);
assert_eq!(date1.get_minutes(), 35);
}
#[wasm_bindgen_test]
fn new_with_year_month_day_hr_min_sec() {
let date1 = Date::new_with_year_month_day_hr_min_sec(1975, 7, 8, 4, 35, 25);
assert_eq!(date1.get_full_year(), 1975);
assert_eq!(date1.get_month(), 7);
assert_eq!(date1.get_date(), 8);
assert_eq!(date1.get_hours(), 4);
assert_eq!(date1.get_minutes(), 35);
assert_eq!(date1.get_seconds(), 25);
}
#[wasm_bindgen_test]
fn new_with_year_month_day_hr_min_sec_milli() {
let date1 = Date::new_with_year_month_day_hr_min_sec_milli(1975, 7, 8, 4, 35, 25, 300);
assert_eq!(date1.get_full_year(), 1975);
assert_eq!(date1.get_month(), 7);
assert_eq!(date1.get_date(), 8);
assert_eq!(date1.get_hours(), 4);
assert_eq!(date1.get_minutes(), 35);
assert_eq!(date1.get_seconds(), 25);
assert_eq!(date1.get_milliseconds(), 300);
}
#[wasm_bindgen_test]
fn now() {
assert!(Date::now() > 0.);
}
#[wasm_bindgen_test]
fn parse() {
let date = Date::parse("04 Dec 1995 00:12:00 GMT");
let zero = Date::parse("01 Jan 1970 00:00:00 GMT");
assert_eq!(date, 818035920000.0);
assert_eq!(zero, 0.0);
}
#[wasm_bindgen_test]
fn set_date() {
let event1 = Date::new(&"August 19, 1975 23:15:30".into());
let event2 = Date::new(&"August 24, 1975 23:15:30".into());
let ms = event1.set_date(24);
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_date(), 24);
}
#[wasm_bindgen_test]
fn set_full_year() {
let event1 = Date::new(&"August 19, 1975 23:15:30".into());
let event2 = Date::new(&"August 19, 1976 23:15:30".into());
let ms = event1.set_full_year(1976);
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_full_year(), 1976);
}
#[wasm_bindgen_test]
fn set_full_year_with_month() {
let event1 = Date::new(&"August 19, 1976 23:15:30".into());
event1.set_full_year_with_month(1979, 4);
assert_eq!(event1.get_full_year(), 1979);
assert_eq!(event1.get_month(), 4);
}
#[wasm_bindgen_test]
fn set_full_year_with_month_date() {
let event1 = Date::new(&"August 19, 1976 23:15:30".into());
event1.set_full_year_with_month_date(1979, -1, 25);
assert_eq!(event1.get_full_year(), 1978);
assert_eq!(event1.get_month(), 11);
assert_eq!(event1.get_date(), 25);
}
#[wasm_bindgen_test]
fn set_hours() {
let event1 = Date::new(&"August 19, 1975 23:15:30".into());
let event2 = Date::new(&"August 19, 1975 20:15:30".into());
let ms = event1.set_hours(20);
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_hours(), 20);
}
#[wasm_bindgen_test]
fn set_milliseconds() {
let event = Date::new(&"August 19, 1975 23:15:30".into());
let ms = event.set_milliseconds(456);
assert_eq!(ms, event.get_time());
assert_eq!(event.get_milliseconds(), 456);
}
#[wasm_bindgen_test]
fn set_minutes() {
let event1 = Date::new(&"August 19, 1975 23:15:30".into());
let event2 = Date::new(&"August 19, 1975 23:45:30".into());
let ms = event1.set_minutes(45);
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_minutes(), 45);
}
#[wasm_bindgen_test]
fn set_month() {
let event1 = Date::new(&"August 19, 1975 23:15:30".into());
let event2 = Date::new(&"April 19, 1975 23:15:30".into());
let ms = event1.set_month(3);
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_month(), 3);
}
#[wasm_bindgen_test]
fn set_seconds() {
let event1 = Date::new(&"August 19, 1975 23:15:30".into());
let event2 = Date::new(&"August 19, 1975 23:15:42".into());
let ms = event1.set_seconds(42);
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_seconds(), 42);
}
#[wasm_bindgen_test]
fn set_time() {
let event1 = Date::new(&"July 1, 1999".into());
let event2 = Date::new(&JsValue::undefined());
let ms = event2.set_time(event1.get_time());
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
}
#[wasm_bindgen_test]
fn set_utc_date() {
let event1 = Date::new(&"August 19, 1975 23:15:30 GMT-3:00".into());
let event2 = Date::new(&"August 19, 1975 02:15:30 GMT".into());
let ms = event1.set_utc_date(19);
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_utc_date(), 19);
}
#[wasm_bindgen_test]
fn set_utc_full_year() {
let event1 = Date::new(&"December 31, 1975 23:15:30 GMT-3:00".into());
let event2 = Date::new(&"January 01, 1975 02:15:30 GMT".into());
let ms = event1.set_utc_full_year(1975);
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_utc_full_year(), 1975);
}
#[wasm_bindgen_test]
fn set_utc_full_year_with_month() {
let event1 = Date::new(&"December 31, 1975 23:15:30 GMT-3:00".into());
event1.set_utc_full_year_with_month(1975, 6);
assert_eq!(event1.get_utc_full_year(), 1975);
assert_eq!(event1.get_utc_month(), 6);
}
#[wasm_bindgen_test]
fn set_utc_full_year_with_month_date() {
let event1 = Date::new(&"December 31, 1975 23:15:30 GMT-3:00".into());
event1.set_utc_full_year_with_month_date(1975, -2, 21);
assert_eq!(event1.get_utc_full_year(), 1974);
assert_eq!(event1.get_utc_month(), 10);
assert_eq!(event1.get_utc_date(), 21);
}
#[wasm_bindgen_test]
fn set_utc_hours() {
let event1 = Date::new(&"August 19, 1975 23:15:30 GMT-3:00".into());
let event2 = Date::new(&"August 20, 1975 23:15:30 GMT".into());
let ms = event1.set_utc_hours(23);
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_utc_hours(), 23);
}
#[wasm_bindgen_test]
fn set_utc_milliseconds() {
let event1 = Date::new(&"1995-12-17T09:24:00Z".into());
let event2 = Date::new(&"1995-12-17T09:24:00.420Z".into());
let ms = event1.set_utc_milliseconds(420);
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_utc_milliseconds(), 420);
}
#[wasm_bindgen_test]
fn set_utc_minutes() {
let event1 = Date::new(&"December 31, 1975, 23:15:30 GMT-3:00".into());
let event2 = Date::new(&"January 01, 1976 02:25:30 GMT".into());
let ms = event1.set_utc_minutes(25);
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_utc_minutes(), 25);
}
#[wasm_bindgen_test]
fn set_utc_month() {
let event1 = Date::new(&"December 31, 1975 23:15:30 GMT-3:00".into());
let event2 = Date::new(&"December 01, 1976 02:15:30 GMT".into());
let ms = event1.set_utc_month(11);
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_utc_month(), 11);
}
#[wasm_bindgen_test]
fn set_utc_seconds() {
let event1 = Date::new(&"December 31, 1975 23:15:30 GMT-3:00".into());
let event2 = Date::new(&"January 01, 1976 02:15:39 GMT".into());
let ms = event1.set_utc_seconds(39);
assert_eq!(ms, event2.get_time());
assert_eq!(event1.get_time(), event2.get_time());
assert_eq!(event1.get_utc_seconds(), 39);
}
#[wasm_bindgen_test]
fn to_date_string() {
// Create the date from date components rather than a string because this
// constructor interprets it as a date in the local time zone, which is how
// `toDateString` outputs it. This makes sure that this test will work in any
// time zone.
// October is 9 rather than 10 because the months count from 0.
let date = Date::new_with_year_month_day_hr_min(2011, 9, 5, 14, 48);
assert_eq!(JsValue::from(date.to_date_string()), "Wed Oct 05 2011");
}
#[wasm_bindgen_test]
fn to_iso_string() {
let date = Date::new(&"05 October 2011 14:48 UTC".into());
assert_eq!(
JsValue::from(date.to_iso_string()),
"2011-10-05T14:48:00.000Z"
);
}
#[wasm_bindgen_test]
fn to_json() {
let date = Date::new(&"August 19, 1975 23:15:30 UTC".into());
assert_eq!(JsValue::from(date.to_json()), "1975-08-19T23:15:30.000Z");
}
#[wasm_bindgen_test]
fn to_locale_date_string() {
let date = Date::new(&"August 19, 1975 23:15:30 UTC".into());
let s = date.to_locale_date_string("de-DE", &JsValue::undefined());
assert!(s.length() > 0);
}
#[wasm_bindgen_test]
fn to_locale_string() {
let date = Date::new(&"August 19, 1975 23:15:30 UTC".into());
let s = date.to_locale_string("de-DE", &JsValue::undefined());
assert!(s.length() > 0);
}
#[wasm_bindgen_test]
fn to_locale_time_string() {
let date = Date::new(&"August 19, 1975 23:15:30".into());
assert_eq!(
JsValue::from(date.to_locale_time_string("en-US")),
"11:15:30 PM",
);
}
#[wasm_bindgen_test]
fn to_string() {
let date = Date::new(&"August 19, 1975 23:15:30".into());
let s = JsValue::from(date.to_string()).as_string().unwrap();
assert_eq!(&s[0..15], "Tue Aug 19 1975");
}
#[wasm_bindgen_test]
fn to_time_string() {
let date = Date::new(&"August 19, 1975 23:15:30".into());
let s = JsValue::from(date.to_time_string()).as_string().unwrap();
assert_eq!(&s[0..8], "23:15:30");
}
#[wasm_bindgen_test]
fn to_utc_string() {
let date = Date::new(&"14 Jun 2017 00:00:00 PDT".into());
let s = JsValue::from(date.to_utc_string()).as_string().unwrap();
assert_eq!(s, "Wed, 14 Jun 2017 07:00:00 GMT");
}
#[wasm_bindgen_test]
fn utc() {
assert_eq!(Date::utc(2018f64, 6f64), 1530403200000.0);
}
#[wasm_bindgen_test]
fn value_of() {
let date = Date::new(&Date::utc(2018f64, 6f64).into());
assert_eq!(date.value_of(), 1530403200000.0);
}
#[wasm_bindgen_test]
fn date_inheritance() {
let date = Date::new(&"August 19, 1975 23:15:30".into());
assert!(date.is_instance_of::<Date>());
assert!(date.is_instance_of::<Object>());
let _: &Object = date.as_ref();
}

View File

@@ -0,0 +1,75 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn new() {
let error = Error::new("some message");
assert_eq!(JsValue::from(error.message()), "some message");
}
#[wasm_bindgen_test]
fn new_with_cause() {
let options = Object::new();
Reflect::set(
options.as_ref(),
&JsValue::from("cause"),
&JsValue::from("some cause"),
)
.unwrap();
let error = Error::new_with_options("some message", &options);
assert_eq!(error.cause(), "some cause");
}
#[wasm_bindgen_test]
fn empty_cause() {
let error = Error::new("test");
assert_eq!(error.cause(), JsValue::UNDEFINED);
}
#[wasm_bindgen_test]
fn set_cause() {
let error = Error::new("test");
error.set_cause(&JsValue::from("different"));
assert_eq!(error.cause(), "different");
}
#[wasm_bindgen_test]
fn set_message() {
let error = Error::new("test");
error.set_message("another");
assert_eq!(JsValue::from(error.message()), "another");
}
#[wasm_bindgen_test]
fn name() {
let error = Error::new("test");
assert_eq!(JsValue::from(error.name()), "Error");
}
#[wasm_bindgen_test]
fn set_name() {
let error = Error::new("test");
error.set_name("different");
assert_eq!(JsValue::from(error.name()), "different");
}
#[wasm_bindgen_test]
fn to_string() {
let error = Error::new("error message 1");
assert_eq!(JsValue::from(error.to_string()), "Error: error message 1");
error.set_name("error_name_1");
assert_eq!(
JsValue::from(error.to_string()),
"error_name_1: error message 1"
);
}
#[wasm_bindgen_test]
fn error_inheritance() {
let error = Error::new("test");
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Object = error.as_ref();
}

View File

@@ -0,0 +1,62 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
// Note: This error is not thrown any more, so there are no tests that will generate this error.
// Instead we just have to manually construct it
#[wasm_bindgen_test]
fn new() {
let error = EvalError::new("some message");
let base_error: &Error = error.dyn_ref().unwrap();
assert_eq!(JsValue::from(base_error.message()), "some message");
}
#[wasm_bindgen_test]
fn set_message() {
let error = EvalError::new("test");
let base_error: &Error = error.dyn_ref().unwrap();
base_error.set_message("another");
assert_eq!(JsValue::from(base_error.message()), "another");
}
#[wasm_bindgen_test]
fn name() {
let error = EvalError::new("test");
let base_error: &Error = error.dyn_ref().unwrap();
assert_eq!(JsValue::from(base_error.name()), "EvalError");
}
#[wasm_bindgen_test]
fn set_name() {
let error = EvalError::new("test");
let base_error: &Error = error.dyn_ref().unwrap();
base_error.set_name("different");
assert_eq!(JsValue::from(base_error.name()), "different");
}
#[wasm_bindgen_test]
fn to_string() {
let error = EvalError::new("error message 1");
let base_error: &Error = error.dyn_ref().unwrap();
assert_eq!(
JsValue::from(base_error.to_string()),
"EvalError: error message 1"
);
base_error.set_name("error_name_1");
assert_eq!(
JsValue::from(base_error.to_string()),
"error_name_1: error message 1"
);
}
#[wasm_bindgen_test]
fn evalerror_inheritance() {
let error = EvalError::new("some message");
assert!(error.is_instance_of::<EvalError>());
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Error = error.as_ref();
let _: &Object = error.as_ref();
}

View File

@@ -0,0 +1,19 @@
// Used for `Function.rs` tests
exports.get_function_to_bind = function() {
return function() { return this.x || 1; }
};
exports.get_value_to_bind_to = function() {
return { x: 2 };
};
exports.list = function() {
return function() {return Array.prototype.slice.call(arguments);}
};
exports.add_arguments = function() {
return function(arg1, arg2) {return arg1 + arg2}
};
exports.call_function = function(f) {
return f();
};
exports.call_function_arg = function(f, arg1) {
return f(arg1);
};

View File

@@ -0,0 +1,134 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_name = max, js_namespace = Math)]
static MAX: Function;
type ArrayPrototype;
#[wasm_bindgen(method, getter, structural)]
pub fn push(this: &ArrayPrototype) -> Function;
#[wasm_bindgen(js_name = prototype, js_namespace = Array)]
static ARRAY_PROTOTYPE2: ArrayPrototype;
}
#[wasm_bindgen_test]
fn apply() {
let args = Array::new();
args.push(&1.into());
args.push(&2.into());
args.push(&3.into());
assert_eq!(MAX.apply(&JsValue::undefined(), &args).unwrap(), 3);
let arr = JsValue::from(Array::new());
let args = Array::new();
args.push(&1.into());
ARRAY_PROTOTYPE2.push().apply(&arr, &args).unwrap();
assert_eq!(Array::from(&arr).length(), 1);
}
#[wasm_bindgen(module = "tests/wasm/Function.js")]
extern "C" {
fn get_function_to_bind() -> Function;
fn get_value_to_bind_to() -> JsValue;
fn list() -> Function;
fn add_arguments() -> Function;
fn call_function(f: &Function) -> JsValue;
fn call_function_arg(f: &Function, arg0: JsValue) -> JsValue;
}
#[wasm_bindgen_test]
fn bind() {
let f = get_function_to_bind();
let new_f = f.bind(&get_value_to_bind_to());
assert_eq!(call_function(&f), 1);
assert_eq!(call_function(&new_f), 2);
}
#[wasm_bindgen_test]
fn bind0() {
let f = get_function_to_bind();
let new_f = f.bind0(&get_value_to_bind_to());
assert_eq!(call_function(&f), 1);
assert_eq!(call_function(&new_f), 2);
}
#[wasm_bindgen_test]
fn bind1() {
let a_list = list();
let prepended_list = a_list.bind1(&JsValue::NULL, &JsValue::from(2));
assert_eq!(Array::from(&call_function(&prepended_list)).pop(), 2);
let adder = add_arguments();
let add_42 = adder.bind1(&JsValue::NULL, &JsValue::from(42));
assert_eq!(call_function_arg(&add_42, JsValue::from(1)), 43);
assert_eq!(call_function_arg(&add_42, JsValue::from(378)), 420);
}
#[wasm_bindgen_test]
fn bind2() {
let a_list = list();
let prepended_list = a_list.bind2(&JsValue::NULL, &JsValue::from(2), &JsValue::from(3));
let arr = Array::from(&call_function(&prepended_list));
assert_eq!(arr.pop(), 3);
assert_eq!(arr.pop(), 2);
let adder = add_arguments();
let always_69 = adder.bind2(&JsValue::NULL, &JsValue::from(66), &JsValue::from(3));
assert_eq!(call_function(&always_69), 69);
}
#[wasm_bindgen_test]
fn bind3() {
let a_list = list();
let prepended_list = a_list.bind3(
&JsValue::NULL,
&JsValue::from(2),
&JsValue::from(3),
&JsValue::from(4),
);
let arr = Array::from(&call_function(&prepended_list));
assert_eq!(arr.pop(), 4);
assert_eq!(arr.pop(), 3);
assert_eq!(arr.pop(), 2);
let adder = add_arguments();
let always_69 = adder.bind2(&JsValue::NULL, &JsValue::from(66), &JsValue::from(3));
assert_eq!(call_function(&always_69), 69);
}
#[wasm_bindgen_test]
fn length() {
assert_eq!(MAX.length(), 2);
assert_eq!(ARRAY_PROTOTYPE2.push().length(), 1);
}
#[wasm_bindgen_test]
fn name() {
assert_eq!(JsValue::from(MAX.name()), "max");
assert_eq!(JsValue::from(ARRAY_PROTOTYPE2.push().name()), "push");
}
#[wasm_bindgen_test]
fn to_string() {
assert!(MAX.to_string().length() > 0);
}
#[wasm_bindgen_test]
fn function_inheritance() {
assert!(MAX.is_instance_of::<Function>());
assert!(MAX.is_instance_of::<Object>());
let _: &Object = MAX.as_ref();
}

View File

@@ -0,0 +1,23 @@
exports.one_two_generator = function() {
function* generator() {
yield 1;
yield 2;
}
return generator();
};
exports.dummy_generator = function() {
function* generator() {
const reply = yield '2 * 2';
return reply === 4;
}
return generator();
};
exports.broken_generator = function() {
function* brokenGenerator() {
throw new Error('Something went wrong');
yield 1;
}
return brokenGenerator();
};

View File

@@ -0,0 +1,66 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
#[wasm_bindgen(module = "tests/wasm/Generator.js")]
extern "C" {
fn one_two_generator() -> Generator;
fn dummy_generator() -> Generator;
fn broken_generator() -> Generator;
type GeneratorResult;
#[wasm_bindgen(method, getter, structural)]
fn value(this: &GeneratorResult) -> JsValue;
#[wasm_bindgen(method, getter, structural)]
fn done(this: &GeneratorResult) -> bool;
}
#[wasm_bindgen_test]
fn return_() {
let gen = one_two_generator();
gen.next(&JsValue::undefined()).unwrap();
let res = GeneratorResult::from(gen.return_(&42.into()));
assert_eq!(res.value(), 42);
assert!(res.done());
let next = GeneratorResult::from(gen.next(&JsValue::undefined()).unwrap());
assert!(next.value().is_undefined());
assert!(next.done());
}
#[wasm_bindgen_test]
fn next() {
let gen = dummy_generator();
let result = GeneratorResult::from(gen.next(&JsValue::undefined()).unwrap());
assert!(!result.done());
assert_eq!(result.value(), "2 * 2");
let result = GeneratorResult::from(gen.next(&4.into()).unwrap());
assert!(result.done());
assert_eq!(result.value(), true);
assert!(broken_generator().next(&3.into()).is_err());
}
#[wasm_bindgen_test]
fn throw() {
let gen = one_two_generator();
gen.next(&JsValue::undefined()).unwrap();
assert!(gen.throw(&Error::new("something went wrong")).is_err());
let next = GeneratorResult::from(gen.next(&JsValue::undefined()).unwrap());
assert!(next.value().is_undefined());
assert!(next.done());
}
#[wasm_bindgen_test]
fn generator_inheritance() {
let gen = dummy_generator();
assert!(gen.is_instance_of::<Object>());
}

View File

@@ -0,0 +1,124 @@
use js_sys::*;
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn get_canonical_locales() {
let locales = Array::new();
locales.push(&"EN-US".into());
locales.push(&"Fr".into());
let locales = JsValue::from(locales);
let canonical_locales = Intl::get_canonical_locales(&locales);
assert_eq!(canonical_locales.length(), 2);
canonical_locales.for_each(&mut |l, i, _| {
if i == 0 {
assert_eq!(l, "en-US");
} else {
assert_eq!(l, "fr");
}
});
let canonical_locales = Intl::get_canonical_locales(&"EN-US".into());
assert_eq!(canonical_locales.length(), 1);
canonical_locales.for_each(&mut |l, _, _| {
assert_eq!(l, "en-US");
});
}
#[wasm_bindgen_test]
fn collator() {
let locales = Array::of1(&JsValue::from("en-US"));
let opts = Object::new();
let c = Intl::Collator::new(&locales, &opts);
assert!(c.compare().is_instance_of::<Function>());
assert!(c.resolved_options().is_instance_of::<Object>());
let a = Intl::Collator::supported_locales_of(&locales, &opts);
assert!(a.is_instance_of::<Array>());
}
#[wasm_bindgen_test]
fn collator_inheritance() {
let locales = Array::of1(&JsValue::from("en-US"));
let opts = Object::new();
let c = Intl::Collator::new(&locales, &opts);
assert!(c.is_instance_of::<Intl::Collator>());
assert!(c.is_instance_of::<Object>());
let _: &Object = c.as_ref();
}
#[wasm_bindgen_test]
fn date_time_format() {
let locales = Array::of1(&JsValue::from("en-US"));
let opts = Object::new();
let epoch = Date::new(&JsValue::from(0));
let c = Intl::DateTimeFormat::new(&locales, &opts);
assert!(c.format().is_instance_of::<Function>());
assert!(c.format_to_parts(&epoch).is_instance_of::<Array>());
assert!(c.resolved_options().is_instance_of::<Object>());
let a = Intl::DateTimeFormat::supported_locales_of(&locales, &opts);
assert!(a.is_instance_of::<Array>());
}
#[wasm_bindgen_test]
fn date_time_format_inheritance() {
let locales = Array::of1(&JsValue::from("en-US"));
let opts = Object::new();
let c = Intl::DateTimeFormat::new(&locales, &opts);
assert!(c.is_instance_of::<Intl::DateTimeFormat>());
assert!(c.is_instance_of::<Object>());
let _: &Object = c.as_ref();
}
#[wasm_bindgen_test]
fn number_format() {
let locales = Array::of1(&JsValue::from("en-US"));
let opts = Object::new();
let n = Intl::NumberFormat::new(&locales, &opts);
assert!(n.format().is_instance_of::<Function>());
assert!(n.format_to_parts(42.5).is_instance_of::<Array>());
assert!(n.resolved_options().is_instance_of::<Object>());
let a = Intl::NumberFormat::supported_locales_of(&locales, &opts);
assert!(a.is_instance_of::<Array>());
}
#[wasm_bindgen_test]
fn number_format_inheritance() {
let locales = Array::of1(&JsValue::from("en-US"));
let opts = Object::new();
let n = Intl::NumberFormat::new(&locales, &opts);
assert!(n.is_instance_of::<Intl::NumberFormat>());
assert!(n.is_instance_of::<Object>());
let _: &Object = n.as_ref();
}
#[wasm_bindgen_test]
fn plural_rules() {
let locales = Array::of1(&JsValue::from("en-US"));
let opts = Object::new();
let r = Intl::PluralRules::new(&locales, &opts);
assert!(r.resolved_options().is_instance_of::<Object>());
assert_eq!(r.select(1_f64), "one");
let a = Intl::PluralRules::supported_locales_of(&locales, &opts);
assert!(a.is_instance_of::<Array>());
}
#[wasm_bindgen_test]
fn plural_rules_inheritance() {
let locales = Array::of1(&JsValue::from("en-US"));
let opts = Object::new();
let r = Intl::PluralRules::new(&locales, &opts);
assert!(r.is_instance_of::<Intl::PluralRules>());
assert!(r.is_instance_of::<Object>());
let _: &Object = r.as_ref();
}

View File

@@ -0,0 +1,19 @@
exports.get_iterable = () => ["one", "two", "three"];
exports.get_not_iterable = () => new Object;
exports.get_symbol_iterator_throws = () => ({
[Symbol.iterator]: () => { throw new Error("nope"); },
});
exports.get_symbol_iterator_not_function = () => ({
[Symbol.iterator]: 5,
});
exports.get_symbol_iterator_returns_not_object = () => ({
[Symbol.iterator]: () => 5,
});
exports.get_symbol_iterator_returns_object_without_next = () => ({
[Symbol.iterator]: () => new Object,
});

View File

@@ -0,0 +1,42 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
#[wasm_bindgen(module = "tests/wasm/Iterator.js")]
extern "C" {
fn get_iterable() -> JsValue;
fn get_not_iterable() -> JsValue;
fn get_symbol_iterator_throws() -> JsValue;
fn get_symbol_iterator_not_function() -> JsValue;
fn get_symbol_iterator_returns_not_object() -> JsValue;
fn get_symbol_iterator_returns_object_without_next() -> JsValue;
}
#[wasm_bindgen_test]
fn try_iter_handles_iteration_protocol() {
assert_eq!(
try_iter(&get_iterable())
.unwrap()
.unwrap()
.map(|x| x.unwrap().as_string().unwrap())
.collect::<Vec<_>>(),
vec!["one", "two", "three"]
);
assert!(try_iter(&get_not_iterable()).unwrap().is_none());
assert!(try_iter(&get_symbol_iterator_throws()).is_err());
assert!(try_iter(&get_symbol_iterator_not_function())
.unwrap()
.is_none());
assert!(try_iter(&get_symbol_iterator_returns_not_object())
.unwrap()
.is_none());
assert!(try_iter(&get_symbol_iterator_returns_object_without_next())
.unwrap()
.is_none());
}

View File

@@ -0,0 +1,198 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn parse_array() {
let js_array = JSON::parse("[1, 2, 3]").unwrap();
assert!(Array::is_array(&js_array));
let array = Array::from(&js_array);
assert_eq!(array.length(), 3);
assert_eq!(array.pop(), 3);
assert_eq!(array.pop(), 2);
assert_eq!(array.pop(), 1);
}
#[wasm_bindgen_test]
fn parse_object() {
let js_object = JSON::parse("{\"x\": 5, \"y\": true, \"z\": [\"foo\", \"bar\"]}").unwrap();
assert!(js_object.is_object());
let obj = Object::from(js_object);
let keys = Object::keys(&obj);
assert_eq!(keys.length(), 3);
assert_eq!(keys.pop().as_string().unwrap(), "z");
assert_eq!(keys.pop().as_string().unwrap(), "y");
assert_eq!(keys.pop().as_string().unwrap(), "x");
let values = Object::values(&obj);
assert_eq!(values.length(), 3);
let z = values.pop();
assert!(Array::is_array(&z));
let z_array = Array::from(&z);
assert_eq!(z_array.length(), 2);
let y = values.pop();
assert_eq!(y.as_bool(), Some(true));
let x = values.pop();
assert_eq!(x.as_f64().unwrap(), 5.0);
}
#[wasm_bindgen_test]
fn parse_error() {
let js_object = JSON::parse("invalid json");
assert!(js_object.is_err());
let err = js_object.unwrap_err();
assert!(err.is_instance_of::<Error>());
}
#[wasm_bindgen_test]
fn stringify() {
let arr = Array::new();
arr.push(&JsValue::from(1));
arr.push(&JsValue::from(true));
arr.push(&JsValue::from("hello"));
let str1: String = JSON::stringify(&JsValue::from(arr)).unwrap().into();
assert_eq!(str1, "[1,true,\"hello\"]");
let obj = Object::new();
Reflect::set(obj.as_ref(), &JsValue::from("foo"), &JsValue::from("bar")).unwrap();
let str2: String = JSON::stringify(&JsValue::from(obj)).unwrap().into();
assert_eq!(str2, "{\"foo\":\"bar\"}");
}
#[wasm_bindgen_test]
fn stringify_error() {
let func = Function::new_no_args("throw new Error(\"rust really rocks\")");
let obj = Object::new();
Reflect::set(obj.as_ref(), &JsValue::from("toJSON"), func.as_ref()).unwrap();
let result = JSON::stringify(&JsValue::from(obj));
assert!(result.is_err());
let err_obj = result.unwrap_err();
assert!(err_obj.is_instance_of::<Error>());
let err: &Error = err_obj.dyn_ref().unwrap();
let err_msg: String = From::from(err.message());
assert!(err_msg.contains("rust really rocks"));
}
#[wasm_bindgen_test]
fn stringify_with_replacer() {
let obj = Object::new();
Reflect::set(obj.as_ref(), &JsValue::from("foo"), &JsValue::from("bar")).unwrap();
Reflect::set(
obj.as_ref(),
&JsValue::from("hello"),
&JsValue::from("world"),
)
.unwrap();
let replacer_array = Array::new();
replacer_array.push(&JsValue::from("hello"));
let output1: String =
JSON::stringify_with_replacer(&JsValue::from(obj.clone()), &JsValue::from(replacer_array))
.unwrap()
.into();
assert_eq!(output1, "{\"hello\":\"world\"}");
let replacer_func =
Function::new_with_args("key, value", "return key === 'hello' ? undefined : value");
let output2: String =
JSON::stringify_with_replacer(&JsValue::from(obj), &JsValue::from(replacer_func))
.unwrap()
.into();
assert_eq!(output2, "{\"foo\":\"bar\"}");
}
#[wasm_bindgen_test]
fn stringify_with_replacer_error() {
let arr = Array::new();
arr.push(&JsValue::from(1));
arr.push(&JsValue::from(true));
arr.push(&JsValue::from("hello"));
let replacer = Function::new_no_args("throw new Error(\"rust really rocks\")");
let result = JSON::stringify_with_replacer(&JsValue::from(arr), &JsValue::from(replacer));
assert!(result.is_err());
let err_obj = result.unwrap_err();
assert!(err_obj.is_instance_of::<Error>());
let err: &Error = err_obj.dyn_ref().unwrap();
let err_msg: String = From::from(err.message());
assert!(err_msg.contains("rust really rocks"));
}
#[wasm_bindgen_test]
fn stringify_with_replacer_and_space() {
let arr = Array::new();
arr.push(&JsValue::from(1));
arr.push(&JsValue::from(true));
arr.push(&JsValue::from("hello"));
let output1: String = JSON::stringify_with_replacer_and_space(
&JsValue::from(arr),
&JsValue::NULL,
&JsValue::from(4),
)
.unwrap()
.into();
assert_eq!(output1, "[\n 1,\n true,\n \"hello\"\n]");
let obj = Object::new();
Reflect::set(obj.as_ref(), &JsValue::from("foo"), &JsValue::from("bar")).unwrap();
Reflect::set(
obj.as_ref(),
&JsValue::from("hello"),
&JsValue::from("world"),
)
.unwrap();
let replacer_array = Array::new();
replacer_array.push(&JsValue::from("hello"));
let output2: String = JSON::stringify_with_replacer_and_space(
&JsValue::from(obj.clone()),
&JsValue::from(replacer_array),
&JsValue::from(4),
)
.unwrap()
.into();
assert_eq!(output2, "{\n \"hello\": \"world\"\n}");
let replacer_func =
Function::new_with_args("key, value", "return key === 'hello' ? undefined : value");
let output3: String = JSON::stringify_with_replacer_and_space(
&JsValue::from(obj),
&JsValue::from(replacer_func),
&JsValue::from(4),
)
.unwrap()
.into();
assert_eq!(output3, "{\n \"foo\": \"bar\"\n}");
}
#[wasm_bindgen_test]
fn stringify_with_replacer_and_space_error() {
let arr = Array::new();
arr.push(&JsValue::from(1));
arr.push(&JsValue::from(true));
arr.push(&JsValue::from("hello"));
let replacer = Function::new_no_args("throw new Error(\"rust really rocks\")");
let result = JSON::stringify_with_replacer_and_space(
&JsValue::from(arr),
&JsValue::from(replacer),
&JsValue::from(4),
);
assert!(result.is_err());
let err_obj = result.unwrap_err();
assert!(err_obj.is_instance_of::<Error>());
let err: &Error = err_obj.dyn_ref().unwrap();
let err_msg: String = From::from(err.message());
assert!(err_msg.contains("rust really rocks"));
}

View File

@@ -0,0 +1,7 @@
exports.new_string_object = () => new String("hi");
exports.get_replacer_function = function() {
return function upperToHyphenLower(match, offset, string) {
return (offset > 0 ? '-' : '') + match.toLowerCase();
};
};

View File

@@ -0,0 +1,612 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
#[wasm_bindgen(module = "tests/wasm/JsString.js")]
extern "C" {
fn new_string_object() -> JsValue;
fn get_replacer_function() -> Function;
}
#[wasm_bindgen_test]
fn js_string_inheritance() {
let string = new_string_object();
assert!(string.is_instance_of::<JsString>());
assert!(string.is_instance_of::<Object>());
}
#[wasm_bindgen_test]
fn length() {
fn test(s: &str) {
assert_eq!(JsString::from(s).length(), s.len() as u32);
}
test("Mozilla");
test("");
}
#[wasm_bindgen_test]
fn char_at() {
let s = JsString::from("Brave new world");
assert_eq!(JsValue::from(s.char_at(0)), "B");
assert_eq!(JsValue::from(s.char_at(999)), "");
}
#[wasm_bindgen_test]
fn char_code_at() {
let s = "Brave new world";
let js = JsString::from(s);
for (i, b) in s.char_indices() {
assert_eq!(js.char_code_at(i as u32), b as u32 as f64);
}
assert!(js.char_code_at(s.len() as u32).is_nan());
}
#[wasm_bindgen_test]
fn code_point_at() {
assert_eq!(JsString::from("ABC").code_point_at(1), b'B');
assert!(JsString::from("ABC").code_point_at(42).is_undefined());
}
#[wasm_bindgen_test]
fn concat() {
// TODO: Implement ability to receive multiple optional arguments
let s = JsString::from("Hello ").concat(&"World".into());
assert_eq!(JsValue::from(s), "Hello World");
let foo = JsString::from("foo");
assert_eq!(
JsValue::from(foo.concat(&Object::new().into())),
"foo[object Object]"
);
assert_eq!(JsValue::from(foo.concat(&Array::new().into())), "foo");
assert_eq!(JsValue::from(foo.concat(&JsValue::null())), "foonull");
assert_eq!(JsValue::from(foo.concat(&true.into())), "footrue");
assert_eq!(JsValue::from(foo.concat(&1234.into())), "foo1234");
}
#[wasm_bindgen_test]
fn ends_with() {
let s = "To be, or not to be, that is the question.";
let js = JsString::from(s);
// TODO: remove third parameter once we have optional parameters
assert_eq!(js.ends_with("question.", s.len() as i32), true);
assert_eq!(js.ends_with("to be", s.len() as i32), false);
assert_eq!(js.ends_with("to be", 19), true);
}
#[wasm_bindgen_test]
fn from_char_code() {
let s = "½+¾=";
let codes: Vec<u32> = s.chars().map(|char| char as u32).collect();
assert_eq!(JsString::from_char_code1(codes[0]), "½");
assert_eq!(JsString::from_char_code2(codes[0], codes[1]), "½+");
assert_eq!(
JsString::from_char_code3(codes[0], codes[1], codes[2]),
"½+¾"
);
assert_eq!(
JsString::from_char_code4(codes[0], codes[1], codes[2], codes[3]),
"½+¾="
);
let codes_u16: Vec<u16> = codes
.into_iter()
.map(|code| {
assert!(code <= u32::from(u16::max_value()));
code as u16
})
.collect();
assert_eq!(JsString::from_char_code(&codes_u16), "½+¾=");
}
#[wasm_bindgen_test]
fn from_code_point() {
let s = "☃★♲你";
let codes: Vec<u32> = s.chars().map(|char| char as u32).collect();
assert_eq!(JsString::from_code_point1(codes[0]).unwrap(), "");
assert_eq!(
JsString::from_code_point2(codes[0], codes[1]).unwrap(),
"☃★"
);
assert_eq!(
JsString::from_code_point3(codes[0], codes[1], codes[2]).unwrap(),
"☃★♲"
);
assert_eq!(
JsString::from_code_point4(codes[0], codes[1], codes[2], codes[3]).unwrap(),
"☃★♲你"
);
assert_eq!(JsString::from_code_point(&codes).unwrap(), "☃★♲你");
assert!(!JsString::from_code_point1(0x10FFFF).is_err());
assert!(JsString::from_code_point1(0x110000).is_err());
assert!(JsString::from_code_point1(u32::max_value()).is_err());
}
#[wasm_bindgen_test]
fn includes() {
let str = JsString::from("Blue Whale");
// TODO: remove second parameter once we have optional parameters
assert_eq!(str.includes("Blue", 0), true);
assert_eq!(str.includes("Blute", 0), false);
assert_eq!(str.includes("Whale", 0), true);
assert_eq!(str.includes("Whale", 5), true);
assert_eq!(str.includes("Whale", 7), false);
assert_eq!(str.includes("", 0), true);
assert_eq!(str.includes("", 16), true);
}
#[wasm_bindgen_test]
fn index_of() {
let str = JsString::from("Blue Whale");
// TODO: remove second parameter once we have optional parameters
assert_eq!(str.index_of("Blue", 0), 0);
// TODO: remove second parameter once we have optional parameters
assert_eq!(str.index_of("Blute", 0), -1);
assert_eq!(str.index_of("Whale", 0), 5);
assert_eq!(str.index_of("Whale", 5), 5);
assert_eq!(str.index_of("Whale", 7), -1);
// TODO: remove second parameter once we have optional parameters
assert_eq!(str.index_of("", 0), 0);
assert_eq!(str.index_of("", 9), 9);
assert_eq!(str.index_of("", 10), 10);
assert_eq!(str.index_of("", 11), 10);
}
#[wasm_bindgen_test]
fn last_index_of() {
let js = JsString::from("canal");
let len = js.length() as i32;
// TODO: remove second parameter once we have optional parameters
assert_eq!(js.last_index_of("a", len), 3);
assert_eq!(js.last_index_of("a", 2), 1);
assert_eq!(js.last_index_of("a", 0), -1);
// TODO: remove second parameter once we have optional parameters
assert_eq!(js.last_index_of("x", len), -1);
assert_eq!(js.last_index_of("c", -5), 0);
assert_eq!(js.last_index_of("c", 0), 0);
// TODO: remove second parameter once we have optional parameters
assert_eq!(js.last_index_of("", len), 5);
assert_eq!(js.last_index_of("", 2), 2);
}
#[wasm_bindgen_test]
fn match_() {
let s = "The quick brown fox jumped over the lazy dog. It barked.";
let re = RegExp::new("[A-Z]", "g");
let result = JsString::from(s).match_(&re);
let obj = result.unwrap();
assert_eq!(Reflect::get(obj.as_ref(), &"0".into()).unwrap(), "T");
assert_eq!(Reflect::get(obj.as_ref(), &"1".into()).unwrap(), "I");
let re = RegExp::new("[A-Z]([a-z]*)", "g");
let result = JsString::from(s).match_(&re);
let obj = result.unwrap();
assert_eq!(Reflect::get(obj.as_ref(), &"0".into()).unwrap(), "The");
assert_eq!(Reflect::get(obj.as_ref(), &"1".into()).unwrap(), "It");
let result = JsString::from("foo").match_(&re);
assert!(result.is_none());
let s = "For more information, see Chapter 3.4.5.1";
let re = RegExp::new("see (chapter \\d+(\\.\\d)*)", "i");
let result = JsString::from(s).match_(&re);
let obj = result.unwrap();
assert_eq!(
Reflect::get(obj.as_ref(), &"0".into()).unwrap(),
"see Chapter 3.4.5.1"
);
assert_eq!(
Reflect::get(obj.as_ref(), &"1".into()).unwrap(),
"Chapter 3.4.5.1"
);
assert_eq!(Reflect::get(obj.as_ref(), &"2".into()).unwrap(), ".1");
assert_eq!(Reflect::get(obj.as_ref(), &"index".into()).unwrap(), 22);
assert_eq!(Reflect::get(obj.as_ref(), &"input".into()).unwrap(), s);
}
#[wasm_bindgen_test]
fn match_all() {
let s = "The quick brown fox jumped over the lazy dog. It barked.";
let re = RegExp::new("[A-Z]([a-z]*)", "g");
let result: Vec<_> = JsString::from(s)
.match_all(&re)
.into_iter()
.collect::<Result<_, _>>()
.unwrap();
let obj = &result[0];
assert_eq!(Reflect::get(obj.as_ref(), &"0".into()).unwrap(), "The");
assert_eq!(Reflect::get(obj.as_ref(), &"1".into()).unwrap(), "he");
let obj = &result[1];
assert_eq!(Reflect::get(obj.as_ref(), &"0".into()).unwrap(), "It");
assert_eq!(Reflect::get(obj.as_ref(), &"1".into()).unwrap(), "t");
let result: Vec<_> = JsString::from("foo")
.match_all(&re)
.into_iter()
.collect::<Result<_, _>>()
.unwrap();
assert_eq!(result.len(), 0);
let s = "For more information, see Chapter 3.4.5.1. Also see Chapter 3.1.4";
let re = RegExp::new("see (chapter \\d+(\\.\\d)*)", "gi");
let result: Vec<_> = JsString::from(s)
.match_all(&re)
.into_iter()
.collect::<Result<_, _>>()
.unwrap();
let obj = &result[0];
assert_eq!(
Reflect::get(obj.as_ref(), &"0".into()).unwrap(),
"see Chapter 3.4.5.1"
);
assert_eq!(
Reflect::get(obj.as_ref(), &"1".into()).unwrap(),
"Chapter 3.4.5.1"
);
assert_eq!(Reflect::get(obj.as_ref(), &"2".into()).unwrap(), ".1");
assert_eq!(Reflect::get(obj.as_ref(), &"index".into()).unwrap(), 22);
assert_eq!(Reflect::get(obj.as_ref(), &"input".into()).unwrap(), s);
let obj = &result[1];
assert_eq!(
Reflect::get(obj.as_ref(), &"0".into()).unwrap(),
"see Chapter 3.1.4"
);
assert_eq!(
Reflect::get(obj.as_ref(), &"1".into()).unwrap(),
"Chapter 3.1.4"
);
assert_eq!(Reflect::get(obj.as_ref(), &"2".into()).unwrap(), ".4");
assert_eq!(Reflect::get(obj.as_ref(), &"index".into()).unwrap(), 48);
assert_eq!(Reflect::get(obj.as_ref(), &"input".into()).unwrap(), s);
}
#[wasm_bindgen_test]
fn normalize() {
let js = JsString::from("\u{1E9B}\u{0323}");
// TODO: Handle undefined
assert_eq!(JsValue::from(js.normalize("NFC")), "\u{1E9B}\u{0323}");
assert_eq!(
JsValue::from(js.normalize("NFD")),
"\u{017F}\u{0323}\u{0307}"
);
assert_eq!(JsValue::from(js.normalize("NFKC")), "\u{1E69}");
assert_eq!(
JsValue::from(js.normalize("NFKD")),
"\u{0073}\u{0323}\u{0307}"
);
}
#[wasm_bindgen_test]
fn pad_end() {
let js = JsString::from("abc");
// TODO: remove second parameter once we have optional parameters
assert_eq!(JsValue::from(js.pad_end(10, " ")), "abc ");
// TODO: remove second parameter once we have optional parameters
assert_eq!(JsValue::from(js.pad_end(10, " ")), "abc ");
assert_eq!(JsValue::from(js.pad_end(10, "foo")), "abcfoofoof");
assert_eq!(JsValue::from(js.pad_end(6, "123456")), "abc123");
// TODO: remove second parameter once we have optional parameters
assert_eq!(JsValue::from(js.pad_end(1, " ")), "abc");
}
#[wasm_bindgen_test]
fn pad_start() {
let js = JsString::from("abc");
// TODO: remove second parameter once we have optional parameters
assert_eq!(js.pad_start(10, " "), " abc");
assert_eq!(js.pad_start(10, "foo"), "foofoofabc");
assert_eq!(js.pad_start(6, "123465"), "123abc");
assert_eq!(js.pad_start(8, "0"), "00000abc");
// TODO: remove second parameter once we have optional parameters
assert_eq!(js.pad_start(1, " "), "abc");
}
#[wasm_bindgen_test]
fn repeat() {
assert_eq!(JsString::from("test").repeat(3), "testtesttest");
}
#[wasm_bindgen_test]
fn replace() {
let js = JsString::from(
"The quick brown fox jumped over the lazy dog. If the dog reacted, was it really lazy?",
);
let result = js.replace("dog", "ferret");
assert_eq!(
result,
"The quick brown fox jumped over the lazy ferret. If the dog reacted, was it really lazy?"
);
let js = JsString::from("borderTop");
let result = js.replace_with_function("T", &get_replacer_function());
assert_eq!(result, "border-top");
let js = JsString::from(
"The quick brown fox jumped over the lazy dog. If the dog reacted, was it really lazy?",
);
let re = RegExp::new("dog", "g");
let result = js.replace_by_pattern(&re, "ferret");
assert_eq!(result, "The quick brown fox jumped over the lazy ferret. If the ferret reacted, was it really lazy?");
let js = JsString::from("borderTop");
let re = RegExp::new("[A-Z]", "g");
let result = js.replace_by_pattern_with_function(&re, &get_replacer_function());
assert_eq!(result, "border-top");
}
#[wasm_bindgen_test]
fn replace_all() {
let js = JsString::from(
"The quick brown fox jumped over the lazy dog. If the dog reacted, was it really lazy?",
);
let result = js.replace_all("dog", "ferret");
assert_eq!(
result,
"The quick brown fox jumped over the lazy ferret. If the ferret reacted, was it really lazy?"
);
let js = JsString::from("borderTopTest");
let result = js.replace_all_with_function("T", &get_replacer_function());
assert_eq!(result, "border-top-test");
let js = JsString::from(
"The quick brown fox jumped over the lazy dog. If the dog reacted, was it really lazy?",
);
let re = RegExp::new("dog", "g");
let result = js.replace_all_by_pattern(&re, "ferret");
assert_eq!(result, "The quick brown fox jumped over the lazy ferret. If the ferret reacted, was it really lazy?");
let js = JsString::from("borderTopTest");
let re = RegExp::new("[A-Z]", "g");
let result = js.replace_all_by_pattern_with_function(&re, &get_replacer_function());
assert_eq!(result, "border-top-test");
}
#[wasm_bindgen_test]
fn search() {
let js = JsString::from(
"The quick brown fox jumped over the lazy dog. If the dog reacted, was it really lazy?",
);
let re = RegExp::new("[^\\w\\s]", "g");
assert_eq!(js.search(&re), 44);
let js = JsString::from("hey JudE");
let re1 = RegExp::new("[A-Z]", "g");
let re2 = RegExp::new("[.]", "g");
assert_eq!(js.search(&re1), 4);
assert_eq!(js.search(&re2), -1);
}
#[wasm_bindgen_test]
fn slice() {
let characters = JsString::from("acxn18");
assert_eq!(characters.slice(1, 3), "cx");
}
#[wasm_bindgen_test]
fn split() {
let js = JsString::from("Oh brave new world");
let result = js.split(" ");
let mut v = Vec::with_capacity(result.length() as usize);
result.for_each(&mut |x, _, _| v.push(x));
assert_eq!(v[0], "Oh");
assert_eq!(v[1], "brave");
assert_eq!(v[2], "new");
assert_eq!(v[3], "world");
let js = JsString::from("Oct,Nov,Dec");
let result = js.split(",");
let mut v = Vec::with_capacity(result.length() as usize);
result.for_each(&mut |x, _, _| v.push(x));
assert_eq!(v[0], "Oct");
assert_eq!(v[1], "Nov");
assert_eq!(v[2], "Dec");
let result = js.split_limit(",", 2);
let mut v = Vec::with_capacity(result.length() as usize);
result.for_each(&mut |x, _, _| v.push(x));
assert_eq!(result.length(), 2);
assert_eq!(v[0], "Oct");
assert_eq!(v[1], "Nov");
let js = JsString::from("Oh brave new world");
let re = RegExp::new("\\s", "g");
let result = js.split_by_pattern(&re);
let mut v = Vec::with_capacity(result.length() as usize);
result.for_each(&mut |x, _, _| v.push(x));
assert_eq!(v[0], "Oh");
assert_eq!(v[1], "brave");
assert_eq!(v[2], "new");
assert_eq!(v[3], "world");
let result = js.split_by_pattern_limit(&re, 2);
let mut v = Vec::with_capacity(result.length() as usize);
result.for_each(&mut |x, _, _| v.push(x));
assert_eq!(result.length(), 2);
assert_eq!(v[0], "Oh");
assert_eq!(v[1], "brave");
}
#[wasm_bindgen_test]
fn starts_with() {
let js = JsString::from("To be, or not to be, that is the question.");
// TODO: remove second parameter for both assertions once we have optional parameters
assert!(js.starts_with("To be", 0));
assert!(!js.starts_with("not to be", 0));
assert!(js.starts_with("not to be", 10));
}
#[wasm_bindgen_test]
fn substring() {
let js = JsString::from("Mozilla");
assert_eq!(js.substring(0, 1), "M");
assert_eq!(js.substring(1, 0), "M");
assert_eq!(js.substring(0, 6), "Mozill");
// TODO: Add test once we have optional parameters
// assert_eq!(js.substring(4), "lla");
assert_eq!(js.substring(4, 7), "lla");
assert_eq!(js.substring(7, 4), "lla");
assert_eq!(js.substring(0, 7), "Mozilla");
assert_eq!(js.substring(0, 10), "Mozilla");
}
#[wasm_bindgen_test]
fn substr() {
let js = JsString::from("Mozilla");
assert_eq!(js.substr(0, 1), "M");
assert_eq!(js.substr(1, 0), "");
assert_eq!(js.substr(-1, 1), "a");
assert_eq!(js.substr(1, -1), "");
// TODO: Uncomment and test these assertions, once we have support for optional parameters
// assert_eq!(js.substr(-3), "lla");
// assert_eq!(js.substr(1), "ozilla");
assert_eq!(js.substr(-20, 2), "Mo");
assert_eq!(js.substr(20, 2), "");
}
#[wasm_bindgen_test]
fn to_locale_lower_case() {
let js = JsString::from("Mozilla");
assert_eq!(js.to_locale_lower_case(None), "mozilla");
let s = JsString::from("\u{0130}");
assert_eq!(s.to_locale_lower_case(Some("tr".into())), "i");
assert_ne!(s.to_locale_lower_case(Some("en-US".into())), "i");
}
#[wasm_bindgen_test]
fn to_locale_upper_case() {
let js = JsString::from("mozilla");
assert_eq!(js.to_locale_upper_case(None), "MOZILLA");
let s = JsString::from("i\u{0307}");
assert_eq!(s.to_locale_upper_case(Some("lt".into())), "I");
assert_ne!(s.to_locale_upper_case(Some("en-US".into())), "I");
}
#[wasm_bindgen_test]
fn to_lower_case() {
assert_eq!(JsString::from("Mozilla").to_lower_case(), "mozilla");
}
#[wasm_bindgen_test]
fn to_string() {
assert_eq!(JsString::from("foo").to_string(), "foo");
}
#[wasm_bindgen_test]
fn to_upper_case() {
assert_eq!(JsString::from("Mozilla").to_upper_case(), "MOZILLA");
}
#[wasm_bindgen_test]
fn trim() {
assert_eq!(JsString::from(" foo ").trim(), "foo");
// Another example of .trim() removing whitespace from just one side.
assert_eq!(JsString::from("foo ").trim(), "foo");
}
#[wasm_bindgen_test]
fn trim_end_and_trim_right() {
let greeting = JsString::from(" Hello world! ");
let trimmed = " Hello world!";
assert_eq!(greeting.trim_end(), trimmed);
assert_eq!(greeting.trim_right(), trimmed);
}
#[wasm_bindgen_test]
fn trim_start_and_trim_left() {
let greeting = JsString::from(" Hello world! ");
let trimmed = "Hello world! ";
assert_eq!(greeting.trim_start(), trimmed);
assert_eq!(greeting.trim_left(), trimmed);
}
#[wasm_bindgen_test]
fn value_of() {
let greeting = JsString::from("Hello world!");
assert_eq!(greeting.value_of(), "Hello world!");
}
#[wasm_bindgen_test]
fn raw() {
let call_site = Object::new();
let raw = Array::of3(&"foo".into(), &"bar".into(), &"123".into());
Reflect::set(&call_site.as_ref(), &"raw".into(), &raw.into()).unwrap();
assert_eq!(
JsString::raw_2(&call_site, "5", "JavaScript").unwrap(),
"foo5barJavaScript123"
);
let substitutions = Array::of2(&"5".into(), &"JavaScript".into());
assert_eq!(
JsString::raw(&call_site, &substitutions).unwrap(),
"foo5barJavaScript123"
);
assert!(JsString::raw_0(&JsValue::null().unchecked_into()).is_err());
}
#[wasm_bindgen_test]
fn is_valid_utf16() {
assert!(JsString::from("a").is_valid_utf16());
assert!(JsString::from("").is_valid_utf16());
assert!(JsString::from("🥑").is_valid_utf16());
assert!(JsString::from("Why hello there this, 🥑, is 🥑 and is 🥑").is_valid_utf16());
assert!(JsString::from_char_code1(0x00).is_valid_utf16());
assert!(!JsString::from_char_code1(0xd800).is_valid_utf16());
assert!(!JsString::from_char_code1(0xdc00).is_valid_utf16());
}
#[wasm_bindgen_test]
fn as_char() {
assert_eq!(JsString::from('a').as_char(), Some('a'));
assert_eq!(JsString::from('🥑').as_char(), Some('🥑'));
assert_eq!(JsString::from("").as_char(), None);
assert_eq!(JsString::from("ab").as_char(), None);
assert_eq!(JsString::from_char_code1(0xd800).as_char(), None);
assert_eq!(JsString::from_char_code1(0xdc00).as_char(), None);
assert_eq!(JsString::from_char_code1(0xdfff).as_char(), None);
}

View File

@@ -0,0 +1,97 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn clear() {
let map = Map::new();
map.set(&"foo".into(), &"bar".into());
map.set(&"bar".into(), &"baz".into());
assert_eq!(map.size(), 2);
map.clear();
assert_eq!(map.size(), 0);
map.clear();
assert_eq!(map.size(), 0);
}
#[wasm_bindgen_test]
fn delete() {
let map = Map::new();
map.set(&"foo".into(), &"bar".into());
assert_eq!(map.size(), 1);
assert_eq!(map.delete(&"foo".into()), true);
assert_eq!(map.delete(&"bar".into()), false);
assert_eq!(map.size(), 0);
}
#[wasm_bindgen_test]
fn for_each() {
let map = Map::new();
map.set(&1.into(), &true.into());
map.set(&2.into(), &false.into());
map.set(&3.into(), &"awoo".into());
map.set(&4.into(), &100.into());
map.set(&5.into(), &Array::new().into());
map.set(&6.into(), &Object::new().into());
let mut res = Vec::new();
map.for_each(&mut |value, key| {
if value.as_bool().is_some() {
res.push((key, value));
}
});
assert_eq!(map.size(), 6);
assert_eq!(res.len(), 2);
assert_eq!(res[0].0, 1);
assert_eq!(res[0].1, true);
assert_eq!(res[1].0, 2);
assert_eq!(res[1].1, false);
}
#[wasm_bindgen_test]
fn get() {
let map = Map::new();
map.set(&"foo".into(), &"bar".into());
map.set(&1.into(), &2.into());
assert_eq!(map.get(&"foo".into()), "bar");
assert_eq!(map.get(&1.into()), 2);
assert!(map.get(&2.into()).is_undefined());
}
#[wasm_bindgen_test]
fn has() {
let map = Map::new();
map.set(&"foo".into(), &"bar".into());
assert_eq!(map.has(&"foo".into()), true);
assert_eq!(map.has(&"bar".into()), false);
}
#[wasm_bindgen_test]
fn new() {
assert_eq!(Map::new().size(), 0);
}
#[wasm_bindgen_test]
fn set() {
let map = Map::new();
let new = map.set(&"foo".into(), &"bar".into());
assert_eq!(map.has(&"foo".into()), true);
assert_eq!(new.has(&"foo".into()), true);
}
#[wasm_bindgen_test]
fn size() {
let map = Map::new();
map.set(&"foo".into(), &"bar".into());
map.set(&"bar".into(), &"baz".into());
assert_eq!(map.size(), 2);
}
#[wasm_bindgen_test]
fn map_inheritance() {
let map = Map::new();
assert!(map.is_instance_of::<Map>());
assert!(map.is_instance_of::<Object>());
let _: &Object = map.as_ref();
}

View File

@@ -0,0 +1,52 @@
use js_sys::*;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn entries() {
let map = Map::new();
map.set(&"uno".into(), &1.into());
let entries = map.entries();
let next = entries.next().unwrap();
assert_eq!(next.done(), false);
assert!(next.value().is_object());
assert_eq!(Reflect::get(&next.value(), &0.into()).unwrap(), "uno");
assert_eq!(Reflect::get(&next.value(), &1.into()).unwrap(), 1);
let next = entries.next().unwrap();
assert!(next.done());
assert!(next.value().is_undefined());
}
#[wasm_bindgen_test]
fn keys() {
let map = Map::new();
map.set(&"uno".into(), &1.into());
let keys = map.keys();
let next = keys.next().unwrap();
assert_eq!(next.done(), false);
assert_eq!(next.value(), "uno");
let next = keys.next().unwrap();
assert!(next.done());
assert!(next.value().is_undefined());
}
#[wasm_bindgen_test]
fn values() {
let map = Map::new();
map.set(&"uno".into(), &1.into());
let values = map.values();
let next = values.next().unwrap();
assert_eq!(next.done(), false);
assert_eq!(next.value(), 1);
let next = values.next().unwrap();
assert!(next.done());
assert!(next.value().is_undefined());
}

View File

@@ -0,0 +1,271 @@
use std::f64::consts::PI;
use std::f64::{NAN, NEG_INFINITY};
use js_sys::*;
use wasm_bindgen_test::*;
macro_rules! assert_eq {
($a:expr, $b:expr) => {{
let (a, b) = (&$a, &$b);
if f64::is_infinite(*a) && f64::is_infinite(*b) {
assert!(a == b);
} else {
assert!(
(*a - *b).abs() < 1.0e-6,
"not approximately equal {:?} ?= {:?}",
a,
b
);
}
}};
}
#[wasm_bindgen_test]
fn abs() {
assert_eq!(Math::abs(-32.), 32.);
assert_eq!(Math::abs(-32.), 32.);
assert_eq!(Math::abs(-4.7), 4.7);
}
#[wasm_bindgen_test]
fn acos() {
assert_eq!(Math::acos(-1.), PI);
assert_eq!(Math::acos(0.5), 1.0471975511965979);
assert!(Math::acos(2.).is_nan());
}
#[wasm_bindgen_test]
fn acosh() {
assert_eq!(Math::acosh(1.), 0.);
assert_eq!(Math::acosh(2.), 2.0f64.acosh());
assert!(Math::acosh(0.5).is_nan());
}
#[wasm_bindgen_test]
fn asin() {
assert_eq!(Math::asin(1.), 1.0f64.asin());
assert_eq!(Math::asin(0.5), 0.5f64.asin());
assert!(Math::asin(2.).is_nan());
}
#[wasm_bindgen_test]
fn asinh() {
assert_eq!(Math::asinh(1.0), 1f64.asinh());
assert_eq!(Math::asinh(0.5), 0.5f64.asinh());
}
#[wasm_bindgen_test]
fn atan() {
assert_eq!(Math::atan(1.0), 1f64.atan());
assert_eq!(Math::atan(0.5), 0.5f64.atan());
}
#[wasm_bindgen_test]
fn atan2() {
assert_eq!(Math::atan2(1.0, 2.0), 1f64.atan2(2.));
assert_eq!(Math::atan2(0.7, 3.8), 0.7f64.atan2(3.8f64));
}
#[wasm_bindgen_test]
fn atanh() {
assert_eq!(Math::atanh(1.), 1f64.atanh());
assert_eq!(Math::atanh(0.5), 0.5f64.atanh());
assert!(Math::atanh(2.).is_nan());
}
#[wasm_bindgen_test]
fn cbrt() {
assert_eq!(Math::cbrt(27.), 3.);
assert_eq!(Math::cbrt(12.3), 12.3f64.cbrt());
}
#[wasm_bindgen_test]
fn ceil() {
assert_eq!(Math::ceil(1.1), 2.);
assert_eq!(Math::ceil(-1.1), -1.);
}
#[wasm_bindgen_test]
fn clz32() {
assert!(Math::clz32(1) == 31);
assert!(Math::clz32(1000) == 22);
}
#[wasm_bindgen_test]
fn cos() {
assert_eq!(Math::cos(0.0), 1.);
assert_eq!(Math::cos(1.5), 1.5f64.cos());
}
#[wasm_bindgen_test]
fn cosh() {
assert_eq!(Math::cosh(0.), 1.);
assert_eq!(Math::cosh(2.), 3.7621956910836314);
}
#[wasm_bindgen_test]
fn exp() {
assert_eq!(Math::exp(0.), 1.);
assert_eq!(Math::exp(-1.), 0.36787944117144233);
assert_eq!(Math::exp(2.), 7.38905609893065);
}
#[wasm_bindgen_test]
fn expm1() {
assert_eq!(Math::expm1(0.), 0.);
assert_eq!(Math::expm1(1.), 1.718281828459045);
assert_eq!(Math::expm1(-1.), -0.6321205588285577);
assert_eq!(Math::expm1(2.), 6.38905609893065);
}
#[wasm_bindgen_test]
fn floor() {
assert_eq!(Math::floor(5.95), 5.);
assert_eq!(Math::floor(-5.05), -6.);
}
#[wasm_bindgen_test]
fn fround() {
assert!(Math::fround(5.5) == 5.5);
assert!(Math::fround(5.05) == 5.050000190734863);
assert!(Math::fround(5.) == 5.);
assert!(Math::fround(-5.05) == -5.050000190734863);
}
#[wasm_bindgen_test]
fn hypot() {
assert!(Math::hypot(3., 4.) == 5.);
assert!(Math::hypot(3.9, 5.2) == 6.5);
assert!(Math::hypot(6., 8.) == 10.);
assert!(Math::hypot(7., 24.) == 25.);
}
#[wasm_bindgen_test]
fn imul() {
assert!(Math::imul(3, 4) == 12);
assert!(Math::imul(-5, 12) == -60);
assert!(Math::imul(0xffffffffu32 as i32, 5) == 0xffffffffu32.wrapping_mul(5) as i32);
}
#[wasm_bindgen_test]
fn log() {
assert_eq!(Math::log(8.) / Math::log(2.), 3.);
assert_eq!(Math::log(625.) / Math::log(5.), 4.);
}
#[wasm_bindgen_test]
fn log10() {
assert_eq!(Math::log10(100000.), 5.);
assert_eq!(Math::log10(1.), 0.);
assert_eq!(Math::log10(2.), 0.3010299956639812);
}
#[wasm_bindgen_test]
fn log1p() {
assert_eq!(Math::log1p(1.), 0.6931471805599453);
assert_eq!(Math::log1p(0.), 0.);
assert_eq!(Math::log1p(-1.), NEG_INFINITY);
assert!(Math::log1p(-2.).is_nan());
}
#[wasm_bindgen_test]
fn log2() {
assert_eq!(Math::log2(3.), 1.584962500721156);
assert_eq!(Math::log2(2.), 1.);
assert_eq!(Math::log2(1.), 0.);
assert_eq!(Math::log2(0.), NEG_INFINITY);
}
#[wasm_bindgen_test]
fn max() {
assert_eq!(Math::max(3., 1.), 3.);
assert_eq!(Math::max(-3., 1.), 1.);
assert_eq!(Math::max(9913., 43.4), 9913.);
assert_eq!(Math::max(-27., -43.), -27.);
assert_eq!(Math::max(-423.27, -43.1), -43.1);
}
#[wasm_bindgen_test]
fn min() {
assert_eq!(Math::min(3., 1.), 1.);
assert_eq!(Math::min(-3., 1.), -3.);
assert_eq!(Math::min(9913., 43.4), 43.4);
assert_eq!(Math::min(-27., -43.), -43.);
assert_eq!(Math::min(-423.27, -43.1), -423.27);
}
#[wasm_bindgen_test]
fn pow() {
assert_eq!(Math::pow(7., 2.), 49.);
assert_eq!(Math::pow(3.8, 0.5), 3.8f64.powf(0.5f64));
assert!(Math::pow(-2., 0.5).is_nan());
}
#[wasm_bindgen_test]
fn random() {
assert!(Math::random() < 1.);
assert!(Math::random() >= 0.);
}
#[wasm_bindgen_test]
fn round() {
assert_eq!(Math::round(20.49), 20.);
assert_eq!(Math::round(20.5), 21.);
assert_eq!(Math::round(42.), 42.);
assert_eq!(Math::round(-20.5), -20.);
assert_eq!(Math::round(-20.51), -21.);
}
#[wasm_bindgen_test]
fn sign() {
assert_eq!(Math::sign(3.), 1.);
assert_eq!(Math::sign(-3.), -1.);
assert_eq!(Math::sign(2.3), 1.);
assert_eq!(Math::sign(0.), 0.);
assert!(Math::sign(NAN).is_nan());
}
#[wasm_bindgen_test]
fn sin() {
assert_eq!(Math::sin(0.), 0.);
assert_eq!(Math::sin(1.), 1f64.sin());
assert_eq!(Math::sin(PI / 2.), 1.);
}
#[wasm_bindgen_test]
fn sinh() {
assert_eq!(Math::sinh(0.), 0.);
assert_eq!(Math::sinh(1.), 1f64.sinh());
assert_eq!(Math::sinh(2.3), 2.3f64.sinh());
}
#[wasm_bindgen_test]
fn sqrt() {
assert_eq!(Math::sqrt(9.), 3.);
assert_eq!(Math::sqrt(2.), 2f64.sqrt());
assert_eq!(Math::sqrt(42.42), 42.42f64.sqrt());
assert_eq!(Math::sqrt(1.), 1.);
assert!(Math::sqrt(-1.).is_nan());
}
#[wasm_bindgen_test]
fn tan() {
assert_eq!(Math::tan(0.), 0.);
assert_eq!(Math::tan(1.), 1f64.tan());
assert_eq!(Math::tan(0.5), 0.5f64.tan());
}
#[wasm_bindgen_test]
fn tanh() {
assert_eq!(Math::tanh(0.), 0.);
assert_eq!(Math::tanh(1.), 1f64.tanh());
assert_eq!(Math::tanh(0.5), 0.5f64.tanh());
}
#[wasm_bindgen_test]
fn trunc() {
assert_eq!(Math::trunc(13.37), 13.);
assert_eq!(Math::trunc(42.84), 42.);
assert_eq!(Math::trunc(0.123), 0.);
assert_eq!(Math::trunc(-0.123), 0.);
}

View File

@@ -0,0 +1,22 @@
exports.const_epsilon = function() {
return Number.EPSILON;
};
exports.const_max_safe_integer = function() {
return Number.MAX_SAFE_INTEGER;
};
exports.const_max_value = function() {
return Number.MAX_VALUE;
};
exports.const_min_safe_integer = function() {
return Number.MIN_SAFE_INTEGER;
};
exports.const_min_value = function() {
return Number.MIN_VALUE;
};
exports.const_negative_infinity = function() {
return Number.NEGATIVE_INFINITY;
};
exports.const_positive_infinity = function() {
return Number.POSITIVE_INFINITY;
};

View File

@@ -0,0 +1,158 @@
use std::f64::{INFINITY, NAN};
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
#[wasm_bindgen(module = "tests/wasm/Number.js")]
extern "C" {
fn const_epsilon() -> f64;
fn const_max_safe_integer() -> f64;
fn const_max_value() -> f64;
fn const_min_safe_integer() -> f64;
fn const_min_value() -> f64;
fn const_negative_infinity() -> f64;
fn const_positive_infinity() -> f64;
}
#[wasm_bindgen_test]
fn is_finite() {
assert!(Number::is_finite(&42.into()));
assert!(Number::is_finite(&42.1.into()));
assert!(!Number::is_finite(&"42".into()));
assert!(!Number::is_finite(&NAN.into()));
assert!(!Number::is_finite(&INFINITY.into()));
}
#[wasm_bindgen_test]
fn is_integer() {
assert!(Number::is_integer(&42.into()));
assert!(!Number::is_integer(&42.1.into()));
}
#[wasm_bindgen_test]
fn is_nan() {
assert!(Number::is_nan(&NAN.into()));
assert!(!Number::is_nan(&JsValue::TRUE));
assert!(!Number::is_nan(&JsValue::NULL));
assert!(!Number::is_nan(&37.into()));
assert!(!Number::is_nan(&"37".into()));
assert!(!Number::is_nan(&"37.37".into()));
assert!(!Number::is_nan(&"".into()));
assert!(!Number::is_nan(&" ".into()));
// These would all return true with the global isNaN()
assert!(!Number::is_nan(&"NaN".into()));
assert!(!Number::is_nan(&JsValue::UNDEFINED));
assert!(!Number::is_nan(&"blabla".into()));
}
#[wasm_bindgen_test]
fn is_safe_integer() {
assert_eq!(Number::is_safe_integer(&42.into()), true);
assert_eq!(
Number::is_safe_integer(&(Math::pow(2., 53.) - 1.).into()),
true
);
assert_eq!(Number::is_safe_integer(&Math::pow(2., 53.).into()), false);
assert_eq!(Number::is_safe_integer(&"42".into()), false);
assert_eq!(Number::is_safe_integer(&42.1.into()), false);
assert_eq!(Number::is_safe_integer(&NAN.into()), false);
assert_eq!(Number::is_safe_integer(&INFINITY.into()), false);
}
#[allow(deprecated)]
#[wasm_bindgen_test]
fn new() {
let n = Number::new(&JsValue::from(42));
let v = JsValue::from(n);
assert!(v.is_object());
assert_eq!(Number::from(v).value_of(), 42.);
}
#[wasm_bindgen_test]
fn parse_int_float() {
assert_eq!(Number::parse_int("42", 10), 42.);
assert_eq!(Number::parse_int("42", 16), 66.); // 0x42 == 66
assert!(Number::parse_int("invalid int", 10).is_nan());
assert_eq!(Number::parse_float("123456.789"), 123456.789);
assert!(Number::parse_float("invalid float").is_nan());
}
#[wasm_bindgen_test]
fn to_locale_string() {
let number = Number::from(1234.45);
assert_eq!(number.to_locale_string("en-US"), "1,234.45");
// TODO: these tests seems to be system dependent, disable for now
// assert_eq!(wasm.to_locale_string(number, "de-DE"), "1,234.45");
// assert_eq!(wasm.to_locale_string(number, "zh-Hans-CN-u-nu-hanidec"), "1,234.45");
}
#[wasm_bindgen_test]
fn to_precision() {
assert_eq!(Number::from(0.1).to_precision(3).unwrap(), "0.100");
assert!(Number::from(10).to_precision(101).is_err());
}
#[wasm_bindgen_test]
fn to_string() {
assert_eq!(Number::from(42).to_string(10).unwrap(), "42");
assert_eq!(Number::from(233).to_string(16).unwrap(), "e9");
assert!(Number::from(100).to_string(100).is_err());
}
#[wasm_bindgen_test]
fn value_of() {
assert_eq!(Number::from(42).value_of(), 42.);
}
#[wasm_bindgen_test]
fn to_fixed() {
assert_eq!(Number::from(123.456).to_fixed(2).unwrap(), "123.46");
assert!(Number::from(10).to_fixed(101).is_err());
}
#[wasm_bindgen_test]
fn to_exponential() {
assert_eq!(Number::from(123456).to_exponential(2).unwrap(), "1.23e+5");
assert!(Number::from(10).to_exponential(101).is_err());
}
#[allow(deprecated)]
#[wasm_bindgen_test]
fn number_inheritance() {
let n = Number::new(&JsValue::from(42));
assert!(n.is_instance_of::<Number>());
assert!(n.is_instance_of::<Object>());
let _: &Object = n.as_ref();
}
#[wasm_bindgen_test]
fn consts() {
assert_eq!(const_epsilon(), Number::EPSILON, "EPSILON");
assert_eq!(
const_max_safe_integer(),
Number::MAX_SAFE_INTEGER,
"MAX_SAFE_INTEGER"
);
assert_eq!(const_max_value(), Number::MAX_VALUE, "MAX_VALUE");
assert_eq!(
const_min_safe_integer(),
Number::MIN_SAFE_INTEGER,
"MIN_SAFE_INTEGER"
);
assert_eq!(const_min_value(), Number::MIN_VALUE, "MIN_VALUE");
assert_eq!(
const_negative_infinity(),
Number::NEGATIVE_INFINITY,
"NEGATIVE_INFINITY"
);
assert_eq!(
const_positive_infinity(),
Number::POSITIVE_INFINITY,
"POSITIVE_INFINITY"
);
}

View File

@@ -0,0 +1,11 @@
const symbol_key = Symbol();
exports.map_with_symbol_key = function() {
return { [symbol_key]: 42 };
};
exports.symbol_key = function() {
return symbol_key;
};
exports.Foo = class {};
exports.Bar = class {};

View File

@@ -0,0 +1,304 @@
use js_sys::*;
use std::f64::NAN;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
#[wasm_bindgen]
extern "C" {
type Foo42;
#[wasm_bindgen(method, setter, structural)]
fn set_foo(this: &Foo42, val: JsValue);
#[wasm_bindgen(js_name = prototype, js_namespace = Object)]
static OBJECT_PROTOTYPE: JsValue;
#[wasm_bindgen(js_name = prototype, js_namespace = Array)]
static ARRAY_PROTOTYPE: JsValue;
type DefinePropertyAttrs;
#[wasm_bindgen(method, setter, structural)]
fn set_value(this: &DefinePropertyAttrs, val: &JsValue);
type PropertyDescriptor;
#[wasm_bindgen(method, getter, structural)]
fn value(this: &PropertyDescriptor) -> JsValue;
}
#[wasm_bindgen(module = "tests/wasm/Object.js")]
extern "C" {
fn map_with_symbol_key() -> Object;
fn symbol_key() -> JsValue;
type Foo;
#[wasm_bindgen(constructor)]
fn new() -> Foo;
#[wasm_bindgen(js_name = prototype, js_namespace = Foo)]
static FOO_PROTOTYPE: Object;
#[wasm_bindgen(js_name = prototype, js_namespace = Bar)]
static BAR_PROTOTYPE: Object;
}
fn foo_42() -> Object {
let foo = Foo42::from(JsValue::from(Object::new()));
foo.set_foo(42.into());
JsValue::from(foo).into()
}
#[wasm_bindgen_test]
fn new() {
assert!(JsValue::from(Object::new()).is_object());
}
#[wasm_bindgen_test]
fn assign() {
let a = JsValue::from("a");
let b = JsValue::from("b");
let c = JsValue::from("c");
let target = Object::new();
Reflect::set(target.as_ref(), a.as_ref(), a.as_ref()).unwrap();
let src1 = Object::new();
Reflect::set(src1.as_ref(), &a, &c).unwrap();
let src2 = Object::new();
Reflect::set(src2.as_ref(), &b, &b).unwrap();
let src3 = Object::new();
Reflect::set(src3.as_ref(), &c, &c).unwrap();
let res = Object::assign3(&target, &src1, &src2, &src3);
assert!(Object::is(target.as_ref(), res.as_ref()));
assert_eq!(Reflect::get(target.as_ref(), &a).unwrap(), c);
assert_eq!(Reflect::get(target.as_ref(), &b).unwrap(), b);
assert_eq!(Reflect::get(target.as_ref(), &c).unwrap(), c);
}
#[wasm_bindgen_test]
fn create() {
let array_proto = eval("Array.prototype")
.unwrap()
.dyn_into::<Object>()
.unwrap();
let my_array = Object::create(&array_proto);
assert!(my_array.is_instance_of::<Array>());
}
#[wasm_bindgen_test]
fn define_property() {
let value = DefinePropertyAttrs::from(JsValue::from(Object::new()));
value.set_value(&43.into());
let descriptor = Object::from(JsValue::from(value));
let foo = foo_42();
let foo = Object::define_property(&foo, &"bar".into(), &descriptor);
assert!(foo.has_own_property(&"bar".into()));
}
#[wasm_bindgen_test]
fn define_properties() {
let props = Object::new();
let descriptor = DefinePropertyAttrs::from(JsValue::from(Object::new()));
descriptor.set_value(&42.into());
let descriptor = JsValue::from(descriptor);
Reflect::set(props.as_ref(), &JsValue::from("bar"), &descriptor).unwrap();
Reflect::set(props.as_ref(), &JsValue::from("car"), &descriptor).unwrap();
let foo = foo_42();
let foo = Object::define_properties(&foo, &props);
assert!(foo.has_own_property(&"bar".into()));
assert!(foo.has_own_property(&"car".into()));
}
#[wasm_bindgen_test]
fn entries() {
let entries = Object::entries(&foo_42());
assert_eq!(entries.length(), 1);
entries.for_each(&mut |x, _, _| {
assert!(x.is_object());
let array: Array = x.into();
assert_eq!(array.shift(), "foo");
assert_eq!(array.shift(), 42);
assert_eq!(array.length(), 0);
});
}
#[wasm_bindgen_test]
fn from_entries() {
let array = Array::new();
let entry_one = Array::new();
let entry_two = Array::new();
entry_one.push(&"foo".into());
entry_one.push(&"bar".into());
entry_two.push(&"baz".into());
entry_two.push(&42.into());
array.push(&entry_one);
array.push(&entry_two);
let object = Object::from_entries(&array).unwrap();
assert_eq!(Reflect::get(object.as_ref(), &"foo".into()).unwrap(), "bar");
assert_eq!(Reflect::get(object.as_ref(), &"baz".into()).unwrap(), 42);
let not_iterable = Object::new();
let error = Object::from_entries(&not_iterable).unwrap_err();
assert!(error.is_instance_of::<TypeError>());
}
#[wasm_bindgen_test]
fn get_own_property_descriptor() {
let foo = foo_42();
let desc = Object::get_own_property_descriptor(&foo, &"foo".into());
assert_eq!(PropertyDescriptor::from(desc).value(), 42);
let desc = Object::get_own_property_descriptor(&foo, &"bar".into());
assert!(desc.is_undefined());
}
#[wasm_bindgen_test]
fn get_own_property_descriptors() {
let foo = foo_42();
let descriptors = Object::get_own_property_descriptors(&foo);
let foo_desc = Reflect::get(&descriptors, &"foo".into()).unwrap();
assert_eq!(PropertyDescriptor::from(foo_desc).value(), 42);
}
#[wasm_bindgen_test]
fn get_own_property_names() {
let names = Object::get_own_property_names(&foo_42());
assert_eq!(names.length(), 1);
names.for_each(&mut |x, _, _| {
assert_eq!(x, "foo");
});
}
#[wasm_bindgen_test]
fn get_own_property_symbols() {
let symbols = Object::get_own_property_symbols(&map_with_symbol_key());
assert_eq!(symbols.length(), 1);
}
#[wasm_bindgen_test]
fn get_prototype_of() {
let proto = JsValue::from(Object::get_prototype_of(&Object::new().into()));
assert_eq!(proto, *OBJECT_PROTOTYPE);
let proto = JsValue::from(Object::get_prototype_of(&Array::new().into()));
assert_eq!(proto, *ARRAY_PROTOTYPE);
}
#[wasm_bindgen_test]
fn has_own_property() {
assert!(foo_42().has_own_property(&"foo".into()));
assert!(!foo_42().has_own_property(&"bar".into()));
assert!(map_with_symbol_key().has_own_property(&symbol_key()));
}
#[wasm_bindgen_test]
fn has_own() {
assert!(Object::has_own(&foo_42(), &"foo".into()));
assert!(!Object::has_own(&foo_42(), &"bar".into()));
assert!(Object::has_own(&map_with_symbol_key(), &symbol_key()));
}
#[wasm_bindgen_test]
fn to_string() {
assert_eq!(Object::new().to_string(), "[object Object]");
assert_eq!(foo_42().to_string(), "[object Object]");
}
#[wasm_bindgen_test]
fn is() {
let object = JsValue::from(Object::new());
assert!(Object::is(&object, &object));
assert!(Object::is(&JsValue::undefined(), &JsValue::undefined()));
assert!(Object::is(&JsValue::null(), &JsValue::null()));
assert!(Object::is(&JsValue::TRUE, &JsValue::TRUE));
assert!(Object::is(&JsValue::FALSE, &JsValue::FALSE));
assert!(Object::is(&"foo".into(), &"foo".into()));
assert!(Object::is(&JsValue::from(42), &JsValue::from(42)));
assert!(Object::is(&JsValue::from(NAN), &JsValue::from(NAN)));
let another_object = JsValue::from(Object::new());
assert!(!Object::is(&object, &another_object));
assert!(!Object::is(&JsValue::TRUE, &JsValue::FALSE));
assert!(!Object::is(&"foo".into(), &"bar".into()));
assert!(!Object::is(&JsValue::from(23), &JsValue::from(42)));
}
#[wasm_bindgen_test]
fn is_extensible() {
let object = Object::new();
assert!(Object::is_extensible(&object));
Object::prevent_extensions(&object);
assert!(!Object::is_extensible(&object));
}
#[wasm_bindgen_test]
fn is_frozen() {
let object = Object::new();
assert!(!Object::is_frozen(&object));
Object::freeze(&object);
assert!(Object::is_frozen(&object));
}
#[wasm_bindgen_test]
fn is_sealed() {
let object = Object::new();
assert!(!Object::is_sealed(&object));
Object::seal(&object);
assert!(Object::is_sealed(&object));
}
#[wasm_bindgen_test]
fn is_prototype_of() {
let foo = JsValue::from(Foo::new());
assert!(FOO_PROTOTYPE.is_prototype_of(&foo));
assert!(!BAR_PROTOTYPE.is_prototype_of(&foo));
}
#[wasm_bindgen_test]
fn keys() {
let keys = Object::keys(&foo_42());
assert_eq!(keys.length(), 1);
keys.for_each(&mut |x, _, _| {
assert_eq!(x, "foo");
});
}
#[wasm_bindgen_test]
fn values() {
let values = Object::values(&foo_42());
assert_eq!(values.length(), 1);
values.for_each(&mut |x, _, _| {
assert_eq!(x, 42);
});
}
#[wasm_bindgen_test]
fn property_is_enumerable() {
assert!(foo_42().property_is_enumerable(&"foo".into()));
assert!(!foo_42().property_is_enumerable(&42.into()));
assert!(!Object::new().property_is_enumerable(&"foo".into()));
}
#[wasm_bindgen_test]
fn set_prototype_of() {
let a = foo_42();
let b = foo_42();
Object::set_prototype_of(&a, &b);
assert!(b.is_prototype_of(&a.into()));
}
#[wasm_bindgen_test]
fn to_locale_string() {
assert_eq!(Object::new().to_locale_string(), "[object Object]");
}
#[wasm_bindgen_test]
fn value_of() {
let a = JsValue::from(foo_42());
let b = JsValue::from(foo_42());
let a2 = JsValue::from(Object::from(a.clone()).value_of());
assert_eq!(a, a);
assert_eq!(a, a2);
assert_ne!(a, b);
assert_ne!(a2, b);
}

View File

@@ -0,0 +1,11 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn promise_inheritance() {
let promise = Promise::new(&mut |_, _| ());
assert!(promise.is_instance_of::<Promise>());
assert!(promise.is_instance_of::<Object>());
let _: &Object = promise.as_ref();
}

View File

@@ -0,0 +1,11 @@
exports.proxy_target = function() {
return { a: 100 };
};
exports.proxy_handler = function() {
return {
get: function(obj, prop) {
return prop in obj ? obj[prop] : 37;
}
};
};

View File

@@ -0,0 +1,45 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
#[wasm_bindgen(module = "tests/wasm/Proxy.js")]
extern "C" {
fn proxy_target() -> JsValue;
fn proxy_handler() -> Object;
type Custom;
#[wasm_bindgen(method, getter, structural, catch)]
fn a(this: &Custom) -> Result<u32, JsValue>;
#[wasm_bindgen(method, getter, structural, catch)]
fn b(this: &Custom) -> Result<u32, JsValue>;
type RevocableResult;
#[wasm_bindgen(method, getter, structural)]
fn proxy(this: &RevocableResult) -> JsValue;
#[wasm_bindgen(method, getter, structural)]
fn revoke(this: &RevocableResult) -> Function;
}
#[wasm_bindgen_test]
fn new() {
let proxy = Proxy::new(&proxy_target(), &proxy_handler());
let proxy = Custom::from(JsValue::from(proxy));
assert_eq!(proxy.a().unwrap(), 100);
assert_eq!(proxy.b().unwrap(), 37);
}
#[wasm_bindgen_test]
fn revocable() {
let result = Proxy::revocable(&proxy_target(), &proxy_handler());
let result = RevocableResult::from(JsValue::from(result));
let proxy = result.proxy();
let revoke = result.revoke();
let obj = Custom::from(proxy);
assert_eq!(obj.a().unwrap(), 100);
assert_eq!(obj.b().unwrap(), 37);
revoke.apply(&JsValue::undefined(), &Array::new()).unwrap();
assert!(obj.a().is_err());
assert!(obj.b().is_err());
assert!(JsValue::from(obj).is_object());
}

View File

@@ -0,0 +1,17 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn range_error() {
let error = RangeError::new("out of range yo");
assert!(error.is_instance_of::<RangeError>());
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Error = error.as_ref();
let _: &Object = error.as_ref();
let base: &Error = error.as_ref();
assert_eq!(JsValue::from(base.message()), "out of range yo");
}

View File

@@ -0,0 +1,17 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn reference_error() {
let error = ReferenceError::new("bad reference, fool");
assert!(error.is_instance_of::<ReferenceError>());
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Error = error.as_ref();
let _: &Object = error.as_ref();
let base: &Error = error.as_ref();
assert_eq!(JsValue::from(base.message()), "bad reference, fool");
}

View File

@@ -0,0 +1,41 @@
exports.get_char_at = function() {
return "foo".charAt;
};
exports.Rectangle = class {
constructor(x, y){
this.x = x,
this.y = y
}
static eq(x, y) {
return x === y;
}
};
exports.Rectangle2 = class {
constructor(x, y){
this.x = x,
this.y = y
}
static eq(x, y) {
return x === y;
}
};
exports.throw_all_the_time = () => new Proxy({}, {
getPrototypeOf() { throw new Error("nope"); },
setPrototypeOf() { throw new Error("nope"); },
isExtensible() { throw new Error("nope"); },
preventExtensions() { throw new Error("nope"); },
getOwnPropertyDescriptor() { throw new Error("nope"); },
defineProperty() { throw new Error("nope"); },
has() { throw new Error("nope"); },
get() { throw new Error("nope"); },
set() { throw new Error("nope"); },
deleteProperty() { throw new Error("nope"); },
ownKeys() { throw new Error("nope"); },
apply() { throw new Error("nope"); },
construct() { throw new Error("nope"); },
});

View File

@@ -0,0 +1,263 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
#[wasm_bindgen(module = "tests/wasm/Reflect.js")]
extern "C" {
fn get_char_at() -> Function;
#[wasm_bindgen(js_name = Rectangle)]
static RECTANGLE_CLASS: Function;
#[wasm_bindgen(js_name = Rectangle2)]
static RECTANGLE2_CLASS: Function;
#[derive(Clone)]
type Rectangle;
#[wasm_bindgen(constructor)]
fn new() -> Rectangle;
#[wasm_bindgen(method, getter, structural)]
fn x(this: &Rectangle) -> u32;
#[wasm_bindgen(method, getter, structural, js_name = x)]
fn x_jsval(this: &Rectangle) -> JsValue;
#[wasm_bindgen(method, setter, structural)]
fn set_x(this: &Rectangle, x: u32);
fn throw_all_the_time() -> Object;
}
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_name = prototype, js_namespace = Object)]
static OBJECT_PROTOTYPE: JsValue;
#[wasm_bindgen(js_name = prototype, js_namespace = Array)]
static ARRAY_PROTOTYPE: JsValue;
type DefinePropertyAttrs;
#[wasm_bindgen(method, setter, structural)]
fn set_value(this: &DefinePropertyAttrs, val: &JsValue);
type PropertyDescriptor;
#[wasm_bindgen(method, getter, structural)]
fn value(this: &PropertyDescriptor) -> JsValue;
}
#[wasm_bindgen_test]
fn apply() {
let args = Array::new();
args.push(&3.into());
assert_eq!(
Reflect::apply(&get_char_at(), &"ponies".into(), &args).unwrap(),
"i"
);
}
#[wasm_bindgen_test]
fn construct() {
let args = Array::new();
args.push(&10.into());
args.push(&10.into());
let instance = Reflect::construct(&RECTANGLE_CLASS, &args).unwrap();
assert_eq!(Rectangle::from(instance).x(), 10);
}
#[wasm_bindgen_test]
fn construct_with_new_target() {
let args = Array::new();
args.push(&10.into());
args.push(&10.into());
let instance =
Reflect::construct_with_new_target(&RECTANGLE_CLASS, &args, &RECTANGLE2_CLASS).unwrap();
assert_eq!(Rectangle::from(instance).x(), 10);
}
#[wasm_bindgen_test]
fn define_property() {
let value = DefinePropertyAttrs::from(JsValue::from(Object::new()));
value.set_value(&42.into());
let obj = Object::from(JsValue::from(value));
assert!(Reflect::define_property(&obj, &"key".into(), &obj).unwrap());
}
#[wasm_bindgen_test]
fn delete_property() {
let r = Rectangle::new();
r.set_x(10);
let obj = Object::from(JsValue::from(r.clone()));
Reflect::delete_property(&obj, &"x".into()).unwrap();
assert!(r.x_jsval().is_undefined());
let array = Array::new();
array.push(&1.into());
let obj = Object::from(JsValue::from(array));
Reflect::delete_property(&obj, &0.into()).unwrap();
let array = Array::from(&JsValue::from(obj));
assert!(array.length() == 1);
array.for_each(&mut |x, _, _| assert!(x.is_undefined()));
}
#[wasm_bindgen_test]
fn get() {
let r = Rectangle::new();
r.set_x(10);
let obj = JsValue::from(r.clone());
assert_eq!(Reflect::get(&obj, &"x".into()).unwrap(), 10);
}
#[wasm_bindgen_test]
fn get_f64() {
let a = Array::new();
assert_eq!(Reflect::get_f64(&a, 0.0).unwrap(), JsValue::UNDEFINED);
assert_eq!(a.push(&JsValue::from_str("Hi!")), 1);
assert_eq!(Reflect::get_f64(&a, 0.0).unwrap(), JsValue::from_str("Hi!"));
}
#[wasm_bindgen_test]
fn get_u32() {
let a = Array::new();
assert_eq!(Reflect::get_u32(&a, 0).unwrap(), JsValue::UNDEFINED);
assert_eq!(a.push(&JsValue::from_str("Hi!")), 1);
assert_eq!(Reflect::get_u32(&a, 0).unwrap(), JsValue::from_str("Hi!"));
}
#[wasm_bindgen_test]
fn get_own_property_descriptor() {
let r = Rectangle::new();
r.set_x(10);
let obj = Object::from(JsValue::from(r.clone()));
let desc = Reflect::get_own_property_descriptor(&obj, &"x".into()).unwrap();
assert_eq!(PropertyDescriptor::from(desc).value(), 10);
let desc = Reflect::get_own_property_descriptor(&obj, &"foo".into()).unwrap();
assert!(desc.is_undefined());
}
#[wasm_bindgen_test]
fn get_prototype_of() {
let proto = JsValue::from(Reflect::get_prototype_of(&Object::new().into()).unwrap());
assert_eq!(proto, *OBJECT_PROTOTYPE);
let proto = JsValue::from(Reflect::get_prototype_of(&Array::new().into()).unwrap());
assert_eq!(proto, *ARRAY_PROTOTYPE);
}
#[wasm_bindgen_test]
fn has() {
let obj = JsValue::from(Rectangle::new());
assert!(Reflect::has(&obj, &"x".into()).unwrap());
assert!(!Reflect::has(&obj, &"foo".into()).unwrap());
}
#[wasm_bindgen_test]
fn is_extensible() {
let obj = Object::from(JsValue::from(Rectangle::new()));
assert!(Reflect::is_extensible(&obj).unwrap());
Reflect::prevent_extensions(&obj).unwrap();
assert!(!Reflect::is_extensible(&obj).unwrap());
let obj = Object::seal(&Object::new());
assert!(!Reflect::is_extensible(&obj).unwrap());
}
#[wasm_bindgen_test]
fn own_keys() {
let obj = JsValue::from(Rectangle::new());
let keys = Reflect::own_keys(&obj).unwrap();
assert!(keys.length() == 2);
keys.for_each(&mut |k, _, _| {
assert!(k == "x" || k == "y");
});
}
#[wasm_bindgen_test]
fn prevent_extensions() {
let obj = Object::new();
Reflect::prevent_extensions(&obj).unwrap();
assert!(!Reflect::is_extensible(&obj).unwrap());
}
#[wasm_bindgen_test]
fn set() {
let obj = JsValue::from(Object::new());
assert!(Reflect::set(&obj, &"key".into(), &"value".into()).unwrap());
assert_eq!(Reflect::get(&obj, &"key".into()).unwrap(), "value");
}
#[wasm_bindgen_test]
fn set_f64() {
let a = Array::new();
a.push(&JsValue::from_str("Hi!"));
assert_eq!(Reflect::get_f64(&a, 0.0).unwrap(), JsValue::from_str("Hi!"));
Reflect::set_f64(&a, 0.0, &JsValue::from_str("Bye!")).unwrap();
assert_eq!(
Reflect::get_f64(&a, 0.0).unwrap(),
JsValue::from_str("Bye!")
);
}
#[wasm_bindgen_test]
fn set_u32() {
let a = Array::new();
a.push(&JsValue::from_str("Hi!"));
assert_eq!(Reflect::get_u32(&a, 0).unwrap(), JsValue::from_str("Hi!"));
Reflect::set_u32(&a, 0, &JsValue::from_str("Bye!")).unwrap();
assert_eq!(Reflect::get_u32(&a, 0).unwrap(), JsValue::from_str("Bye!"));
}
#[wasm_bindgen_test]
fn set_with_receiver() {
let obj1 = JsValue::from(Object::new());
let obj2 = JsValue::from(Object::new());
assert!(Reflect::set_with_receiver(&obj2, &"key".into(), &"value".into(), &obj2).unwrap());
assert!(Reflect::get(&obj1, &"key".into()).unwrap().is_undefined());
assert_eq!(Reflect::get(&obj2, &"key".into()).unwrap(), "value");
}
#[wasm_bindgen_test]
fn set_prototype_of() {
let obj = Object::new();
assert!(Reflect::set_prototype_of(&obj, &JsValue::null()).unwrap());
let obj = JsValue::from(obj);
assert_eq!(
JsValue::from(Reflect::get_prototype_of(&obj).unwrap()),
JsValue::null()
);
}
#[wasm_bindgen_test]
fn reflect_bindings_handle_proxies_that_just_throw_for_everything() {
let p = throw_all_the_time();
let desc = Object::new();
Reflect::set(desc.as_ref(), &"value".into(), &1.into()).unwrap();
assert!(Reflect::define_property(&p, &"a".into(), &desc).is_err());
assert!(Reflect::delete_property(&p, &"a".into()).is_err());
assert!(Reflect::get(p.as_ref(), &"a".into()).is_err());
assert!(Reflect::get_f64(p.as_ref(), 0.0).is_err());
assert!(Reflect::get_u32(p.as_ref(), 0).is_err());
assert!(Reflect::get_own_property_descriptor(&p, &"a".into()).is_err());
assert!(Reflect::get_prototype_of(p.as_ref()).is_err());
assert!(Reflect::has(p.as_ref(), &"a".into()).is_err());
assert!(Reflect::is_extensible(&p).is_err());
assert!(Reflect::own_keys(p.as_ref()).is_err());
assert!(Reflect::prevent_extensions(&p).is_err());
assert!(Reflect::set(p.as_ref(), &"a".into(), &1.into()).is_err());
assert!(Reflect::set_f64(p.as_ref(), 0.0, &1.into()).is_err());
assert!(Reflect::set_u32(p.as_ref(), 0, &1.into()).is_err());
assert!(Reflect::set_prototype_of(&p, Object::new().as_ref()).is_err());
}

View File

@@ -0,0 +1,160 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn regexp_inheritance() {
let re = RegExp::new(".", "");
assert!(re.is_instance_of::<RegExp>());
assert!(re.is_instance_of::<Object>());
let _: &Object = re.as_ref();
}
#[wasm_bindgen_test]
fn exec() {
let re = RegExp::new("quick\\s(brown).+?(jumps)", "ig");
let result = re.exec("The Quick Brown Fox Jumps Over The Lazy Dog");
let mut v = vec![];
result.unwrap().for_each(&mut |x, _, _| v.push(x));
assert_eq!(v[0], "Quick Brown Fox Jumps");
assert_eq!(v[1], "Brown");
assert_eq!(v[2], "Jumps");
let result = re.exec("foo");
assert!(result.is_none());
}
#[wasm_bindgen_test]
fn flags() {
let re = RegExp::new("foo", "ig");
assert_eq!(re.flags(), "gi");
}
#[wasm_bindgen_test]
fn global() {
let re = RegExp::new("foo", "g");
assert!(re.global());
let re = RegExp::new("bar", "i");
assert!(!re.global());
}
#[wasm_bindgen_test]
fn ignore_case() {
let re = RegExp::new("foo", "");
assert!(!re.ignore_case());
let re = RegExp::new("foo", "i");
assert!(re.ignore_case());
}
#[wasm_bindgen_test]
fn input() {
let re = RegExp::new("hi", "g");
re.test("hi there!");
assert_eq!(RegExp::input(), "hi there!");
}
#[wasm_bindgen_test]
fn last_index() {
let re = RegExp::new("hi", "g");
assert_eq!(re.last_index(), 0);
re.set_last_index(42);
assert_eq!(re.last_index(), 42);
}
#[wasm_bindgen_test]
fn last_match() {
let re = RegExp::new("hi", "g");
re.test("hi there!");
assert_eq!(RegExp::last_match(), "hi");
}
#[wasm_bindgen_test]
fn last_paren() {
let re = RegExp::new("(hi)", "g");
re.test("hi there!");
assert_eq!(RegExp::last_paren(), "hi");
}
#[wasm_bindgen_test]
fn left_context() {
let re = RegExp::new("world", "g");
re.test("hello world!");
assert_eq!(RegExp::left_context(), "hello ");
}
#[wasm_bindgen_test]
fn multiline() {
let re = RegExp::new("foo", "m");
assert!(re.multiline());
}
#[wasm_bindgen_test]
fn n1_to_n9() {
let re = RegExp::new(
r"(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)\s(\w+)",
"",
);
re.test("The Quick Brown Fox Jumps Over The Lazy Dog");
assert_eq!(RegExp::n1(), "The");
assert_eq!(RegExp::n2(), "Quick");
assert_eq!(RegExp::n3(), "Brown");
assert_eq!(RegExp::n4(), "Fox");
assert_eq!(RegExp::n5(), "Jumps");
assert_eq!(RegExp::n6(), "Over");
assert_eq!(RegExp::n7(), "The");
assert_eq!(RegExp::n8(), "Lazy");
assert_eq!(RegExp::n9(), "Dog");
}
#[wasm_bindgen_test]
fn new() {
let re = RegExp::new("foo", "");
let re = RegExp::new_regexp(&re, "g");
assert_eq!(re.to_string(), "/foo/g");
}
#[wasm_bindgen_test]
fn right_context() {
let re = RegExp::new("hello", "g");
re.test("hello world!");
assert_eq!(RegExp::right_context(), " world!");
}
#[wasm_bindgen_test]
fn source() {
let re = RegExp::new("fooBar", "ig");
assert_eq!(re.source(), "fooBar");
let re = RegExp::new("", "ig");
assert_eq!(re.source(), "(?:)");
}
#[wasm_bindgen_test]
fn sticky() {
let re = RegExp::new("foo", "y");
assert!(re.sticky());
}
#[wasm_bindgen_test]
fn test() {
let re = RegExp::new("foo", "");
assert!(re.test("football"));
assert!(!re.test("bar"));
}
#[wasm_bindgen_test]
fn to_string() {
let re = RegExp::new("a+b+c", "g");
assert_eq!(re.to_string(), "/a+b+c/g");
}
#[wasm_bindgen_test]
fn unicode() {
let re = RegExp::new("\u{61}", "u");
assert!(re.unicode());
}

View File

@@ -0,0 +1,127 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
fn set2vec(s: &Set) -> Vec<JsValue> {
let mut result = Vec::new();
s.for_each(&mut |x, _, _| result.push(x));
return result;
}
#[wasm_bindgen_test]
fn add() {
let set = Set::new(&JsValue::undefined());
set.add(&100.into());
assert_eq!(set.size(), 1);
assert_eq!(set2vec(&set)[0], 100);
}
#[wasm_bindgen_test]
fn clear() {
let set = Set::new(&JsValue::undefined());
set.add(&1.into());
set.add(&2.into());
set.add(&3.into());
assert_eq!(set.size(), 3);
set.clear();
assert_eq!(set.size(), 0);
}
#[wasm_bindgen_test]
fn delete() {
let set = Set::new(&JsValue::undefined());
set.add(&1.into());
set.add(&2.into());
set.add(&3.into());
assert!(set.delete(&3.into()));
assert!(!set.delete(&3.into()));
assert!(!set.delete(&4.into()));
}
#[wasm_bindgen_test]
fn for_each() {
let set = Set::new(&JsValue::undefined());
set.add(&1.into());
set.add(&2.into());
set.add(&3.into());
let v = set2vec(&set);
assert_eq!(v.len(), 3);
assert!(v.iter().any(|v| *v == 1));
assert!(v.iter().any(|v| *v == 2));
assert!(v.iter().any(|v| *v == 3));
}
#[wasm_bindgen_test]
fn has() {
let set = Set::new(&JsValue::undefined());
set.add(&1.into());
set.add(&2.into());
set.add(&3.into());
assert!(set.has(&1.into()));
assert!(!set.has(&1.3.into()));
}
#[wasm_bindgen_test]
fn new() {
assert_eq!(Set::new(&JsValue::undefined()).size(), 0);
}
#[wasm_bindgen_test]
fn size() {
let set = Set::new(&JsValue::undefined());
assert_eq!(set.size(), 0);
set.add(&1.into());
assert_eq!(set.size(), 1);
set.add(&2.into());
assert_eq!(set.size(), 2);
set.add(&3.into());
assert_eq!(set.size(), 3);
}
#[wasm_bindgen_test]
fn set_inheritance() {
let set = Set::new(&JsValue::undefined());
assert!(set.is_instance_of::<Set>());
assert!(set.is_instance_of::<Object>());
let _: &Object = set.as_ref();
}
#[wasm_bindgen_test]
fn keys() {
let set = Set::new(&JsValue::undefined());
set.add(&1.into());
set.add(&2.into());
set.add(&3.into());
let list = set
.keys()
.into_iter()
.map(|e| e.unwrap())
.collect::<Vec<_>>();
assert_eq!(list.len(), 3);
assert!(list.iter().any(|l| *l == 1));
assert!(list.iter().any(|l| *l == 2));
assert!(list.iter().any(|l| *l == 3));
}
#[wasm_bindgen_test]
fn values() {
let set = Set::new(&JsValue::undefined());
set.add(&1.into());
set.add(&2.into());
set.add(&3.into());
let list = set
.values()
.into_iter()
.map(|e| e.unwrap())
.collect::<Vec<_>>();
assert_eq!(list.len(), 3);
assert!(list.iter().any(|l| *l == 1));
assert!(list.iter().any(|l| *l == 2));
assert!(list.iter().any(|l| *l == 3));
}

View File

@@ -0,0 +1,41 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn entries() {
let s = Set::new(&JsValue::undefined());
s.add(&1.into());
let iter = s.entries();
let obj = iter.next().unwrap();
assert!(!obj.done());
let array = Array::from(&obj.value());
assert_eq!(array.length(), 2);
array.for_each(&mut |a, _, _| {
assert_eq!(a, 1);
});
assert!(iter.next().unwrap().done());
}
#[wasm_bindgen_test]
fn keys() {
let s = Set::new(&JsValue::undefined());
s.add(&1.into());
let iter = s.keys();
let obj = iter.next().unwrap();
assert!(!obj.done());
assert_eq!(obj.value(), 1);
assert!(iter.next().unwrap().done());
}
#[wasm_bindgen_test]
fn values() {
let s = Set::new(&JsValue::undefined());
s.add(&1.into());
let iter = s.values();
let obj = iter.next().unwrap();
assert!(!obj.done());
assert_eq!(obj.value(), 1);
assert!(iter.next().unwrap().done());
}

View File

@@ -0,0 +1,3 @@
exports.is_shared_array_buffer_supported = function () {
return typeof SharedArrayBuffer === 'function';
};

View File

@@ -0,0 +1,59 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
#[wasm_bindgen(module = "tests/wasm/SharedArrayBuffer.js")]
extern "C" {
fn is_shared_array_buffer_supported() -> bool;
}
#[wasm_bindgen_test]
fn new() {
if !is_shared_array_buffer_supported() {
return;
}
let x = SharedArrayBuffer::new(42);
let y: JsValue = x.into();
assert!(y.is_object());
}
#[wasm_bindgen_test]
fn byte_length() {
if !is_shared_array_buffer_supported() {
return;
}
let buf = SharedArrayBuffer::new(42);
assert_eq!(buf.byte_length(), 42);
}
#[wasm_bindgen_test]
fn slice() {
if !is_shared_array_buffer_supported() {
return;
}
let buf = SharedArrayBuffer::new(4);
let slice = buf.slice(2);
assert!(JsValue::from(slice).is_object());
}
#[wasm_bindgen_test]
fn slice_with_end() {
if !is_shared_array_buffer_supported() {
return;
}
let buf = SharedArrayBuffer::new(4);
let slice = buf.slice_with_end(1, 2);
assert!(JsValue::from(slice).is_object());
}
#[wasm_bindgen_test]
fn sharedarraybuffer_inheritance() {
if !is_shared_array_buffer_supported() {
return;
}
let buf = SharedArrayBuffer::new(4);
assert!(buf.is_instance_of::<SharedArrayBuffer>());
assert!(buf.is_instance_of::<Object>());
let _: &Object = buf.as_ref();
}

View File

@@ -0,0 +1,162 @@
const assert = require('assert');
exports.test_has_instance = function(sym) {
class Array1 {
static [sym](instance) {
return Array.isArray(instance);
}
}
assert.equal(typeof sym, "symbol");
assert.ok([] instanceof Array1);
};
exports.test_is_concat_spreadable = function(sym) {
const alpha = ['a', 'b', 'c'];
const numeric = [1, 2, 3];
let alphaNumeric = alpha.concat(numeric);
assert.deepEqual(alphaNumeric, ["a", "b", "c", 1, 2, 3]);
numeric[sym] = false;
alphaNumeric = alpha.concat(numeric);
assert.deepEqual(alphaNumeric, ["a", "b", "c", numeric]);
};
exports.test_iterator = function(sym) {
const iterable1 = new Object();
iterable1[sym] = function* () {
yield 1;
yield 2;
yield 3;
};
assert.deepEqual([...iterable1], [1, 2, 3]);
};
exports.test_async_iterator = async function(sym) {
const iterable1 = new Object();
iterable1[sym] = function () {
let done = false;
return {
next() {
if (done) {
return Promise.resolve({
done: true,
value: 1
});
} else {
done = true;
return Promise.resolve({
done: false,
value: 0
});
}
}
};
};
const values = [];
for await (let value of iterable1) {
values.push(value);
}
assert.deepEqual(values, [0]);
};
exports.test_match = function(sym) {
const regexp1 = /foo/;
assert.throws(() => '/foo/'.startsWith(regexp1));
regexp1[sym] = false;
assert.ok('/foo/'.startsWith(regexp1));
assert.equal('/baz/'.endsWith(regexp1), false);
};
exports.test_replace = function(sym) {
class Replace1 {
constructor(value) {
this.value = value;
}
[sym](string) {
return `s/${string}/${this.value}/g`;
}
}
assert.equal('foo'.replace(new Replace1('bar')), 's/foo/bar/g');
};
exports.test_search = function(sym) {
class Search1 {
constructor(value) {
this.value = value;
}
[sym](string) {
return string.indexOf(this.value);
}
}
assert.equal('foobar'.search(new Search1('bar')), 3);
};
exports.test_species = function(sym) {
class Array1 extends Array {
static get [sym]() { return Array; }
}
const a = new Array1(1, 2, 3);
const mapped = a.map(x => x * x);
assert.equal(mapped instanceof Array1, false);
assert.ok(mapped instanceof Array);
};
exports.test_split = function(sym) {
class Split1 {
constructor(value) {
this.value = value;
}
[sym](string) {
var index = string.indexOf(this.value);
return this.value + string.substr(0, index) + "/"
+ string.substr(index + this.value.length);
}
}
assert.equal('foobar'.split(new Split1('foo')), 'foo/bar');
};
exports.test_to_primitive = function(sym) {
const object1 = {
[sym](hint) {
if (hint == 'number') {
return 42;
}
return null;
}
};
assert.equal(+object1, 42);
};
exports.test_to_string_tag = function(sym) {
class ValidatorClass {
get [sym]() {
return 'Validator';
}
}
assert.equal(Object.prototype.toString.call(new ValidatorClass()), '[object Validator]');
};

View File

@@ -0,0 +1,130 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use wasm_bindgen_test::*;
#[wasm_bindgen(module = "tests/wasm/Symbol.js")]
extern "C" {
fn test_has_instance(sym: &Symbol);
fn test_is_concat_spreadable(sym: &Symbol);
fn test_iterator(sym: &Symbol);
fn test_async_iterator(sym: &Symbol) -> Promise;
fn test_match(sym: &Symbol);
fn test_replace(sym: &Symbol);
fn test_search(sym: &Symbol);
fn test_species(sym: &Symbol);
fn test_split(sym: &Symbol);
fn test_to_primitive(sym: &Symbol);
fn test_to_string_tag(sym: &Symbol);
}
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_name = Symbol)]
fn gensym(val: JsValue) -> Symbol;
}
#[wasm_bindgen_test]
fn has_instance() {
test_has_instance(&Symbol::has_instance());
}
#[wasm_bindgen_test]
fn is_concat_spreadable() {
test_is_concat_spreadable(&Symbol::is_concat_spreadable());
}
#[wasm_bindgen_test]
fn iterator() {
test_iterator(&Symbol::iterator());
}
#[wasm_bindgen_test]
async fn async_iterator() {
JsFuture::from(test_async_iterator(&Symbol::async_iterator()))
.await
.unwrap_throw();
}
#[wasm_bindgen_test]
fn match_() {
test_match(&Symbol::match_());
}
#[wasm_bindgen_test]
fn replace() {
test_replace(&Symbol::replace());
}
#[wasm_bindgen_test]
fn search() {
test_search(&Symbol::search());
}
#[wasm_bindgen_test]
fn species() {
test_species(&Symbol::species());
}
#[wasm_bindgen_test]
fn split() {
test_split(&Symbol::split());
}
#[wasm_bindgen_test]
fn to_primitive() {
test_to_primitive(&Symbol::to_primitive());
}
#[wasm_bindgen_test]
fn to_string_tag() {
test_to_string_tag(&Symbol::to_string_tag());
}
#[wasm_bindgen_test]
fn for_() {
let foo = JsValue::from(Symbol::for_("foo"));
let bar = JsValue::from(Symbol::for_("bar"));
assert_eq!(foo, foo);
assert_eq!(bar, bar);
assert_ne!(foo, bar);
assert_ne!(bar, foo);
assert_eq!(Symbol::for_("mario").to_string(), "Symbol(mario)");
}
#[wasm_bindgen_test]
fn key_for() {
let sym = Symbol::for_("foo");
assert_eq!(Symbol::key_for(&sym), "foo");
assert!(Symbol::key_for(&Symbol::iterator()).is_undefined());
assert!(Symbol::key_for(&Symbol::async_iterator()).is_undefined());
assert!(Symbol::key_for(&gensym(JsValue::undefined())).is_undefined());
}
#[wasm_bindgen_test]
fn to_string() {
assert_eq!(Symbol::iterator().to_string(), "Symbol(Symbol.iterator)");
assert_eq!(
Symbol::async_iterator().to_string(),
"Symbol(Symbol.asyncIterator)"
);
assert_eq!(Symbol::for_("foo").to_string(), "Symbol(foo)");
assert_eq!(gensym("desc".into()).to_string(), "Symbol(desc)");
}
#[wasm_bindgen_test]
fn unscopables() {
assert_eq!(
Symbol::unscopables().to_string(),
"Symbol(Symbol.unscopables)"
);
}
#[wasm_bindgen_test]
fn value_of() {
let a = Symbol::for_("foo");
assert_eq!(JsValue::from(a.value_of()), JsValue::from(a));
let a = gensym(JsValue::undefined());
assert_eq!(JsValue::from(a.value_of()), JsValue::from(a));
}

View File

@@ -0,0 +1,17 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn syntax_error() {
let error = SyntaxError::new("msg");
assert!(error.is_instance_of::<SyntaxError>());
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Error = error.as_ref();
let _: &Object = error.as_ref();
let base: &Error = error.as_ref();
assert_eq!(JsValue::from(base.message()), "msg");
}

View File

@@ -0,0 +1,3 @@
exports.is_temporal_supported = function () {
return typeof Temporal === 'object';
};

View File

@@ -0,0 +1,81 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
#[wasm_bindgen(module = "tests/wasm/Temporal.js")]
extern "C" {
fn is_temporal_supported() -> bool;
}
#[wasm_bindgen_test]
fn now() {
if !is_temporal_supported() {
return;
}
let x = Temporal::Now::plain_date("iso8086");
let y: JsValue = x.into();
assert!(y.is_object());
}
#[wasm_bindgen_test]
fn duration() {
if !is_temporal_supported() {
return;
}
let x = Temporal::Duration::from(&"PT1.00001S".into());
assert_eq!(x.years(), 0);
assert_eq!(x.microseconds(), 10);
}
#[wasm_bindgen_test]
fn zoned_date_time() {
if !is_temporal_supported() {
return;
}
let zdt = Temporal::ZonedDateTime::from(&"2020-03-09T00:00-07:00[America/Los_Angeles]".into());
let earlier_day = zdt.subtract(
&Temporal::Duration::from(&"P1D".into()),
&JsValue::UNDEFINED,
);
let earlier_hours = zdt.subtract(
&Temporal::Duration::from(&"PT24H".into()),
&JsValue::UNDEFINED,
);
assert_eq!(earlier_day.hour(), 0);
assert_eq!(earlier_hours.hour(), 23);
}
#[wasm_bindgen_test]
fn plain_time() {
if !is_temporal_supported() {
return;
}
let time = Temporal::PlainTime::from(&"19:39:09.068346205".into());
assert_eq!(time.microsecond(), 346);
assert_eq!(time.round(&"hour".into()).hour(), 20);
}
#[wasm_bindgen_test]
fn plain_date() {
if !is_temporal_supported() {
return;
}
let x = Temporal::PlainDate::new(2022, 2, 2).with_calendar("persian");
let y = Temporal::PlainDate::new(2022, 2, 5);
let z = Temporal::PlainDate::from(&"-002022-02-02[u-ca=gregory]".into());
assert_eq!(Temporal::PlainDate::compare(&x, &y), -1);
assert_eq!(x.year(), 1400);
assert_eq!(x.month(), 11);
assert_eq!(x.month_code(), "M11");
assert_eq!(x.day(), 13);
assert_eq!(x.era(), "ap");
assert_eq!(y.era(), JsValue::UNDEFINED);
assert_eq!(z.era_year(), 2023i32);
assert_eq!(y.day_of_week(), 6);
assert_eq!(
Reflect::get(&x.get_iso_fields(), &"isoYear".into()).unwrap(),
2022i32
);
assert_eq!(x.in_leap_year(), false);
}

View File

@@ -0,0 +1,17 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn type_error() {
let error = TypeError::new("msg");
assert!(error.is_instance_of::<TypeError>());
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Error = error.as_ref();
let _: &Object = error.as_ref();
let base: &Error = error.as_ref();
assert_eq!(JsValue::from(base.message()), "msg");
}

View File

@@ -0,0 +1,175 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
macro_rules! each {
($m:ident) => {
$m!(Uint8Array);
$m!(Uint8ClampedArray);
$m!(Uint16Array);
$m!(Uint32Array);
$m!(Int8Array);
$m!(Int16Array);
$m!(Int32Array);
$m!(Float32Array);
$m!(Float64Array);
};
}
macro_rules! test_inheritence {
($arr:ident) => {{
let arr = $arr::new(&JsValue::undefined());
assert!(arr.is_instance_of::<$arr>());
let _: &Object = arr.as_ref();
assert!(arr.is_instance_of::<Object>());
}};
}
#[wasm_bindgen_test]
fn inheritence() {
each!(test_inheritence);
}
macro_rules! test_undefined {
($arr:ident) => {{
let arr = $arr::new(&JsValue::undefined());
assert_eq!(arr.length(), 0);
assert_eq!(arr.byte_length(), 0);
assert_eq!(arr.byte_offset(), 0);
assert!(JsValue::from(arr.buffer()).is_object());
}};
}
#[wasm_bindgen_test]
fn new_undefined() {
each!(test_undefined);
}
macro_rules! test_length {
($arr:ident) => {{
let arr = $arr::new(&4.into());
assert_eq!(arr.length(), 4);
assert!(arr.byte_length() != 0);
assert_eq!(arr.byte_offset(), 0);
assert!(JsValue::from(arr.buffer()).is_object());
}};
}
#[wasm_bindgen_test]
fn new_length() {
each!(test_length);
}
macro_rules! test_subarray {
($arr:ident) => {{
assert_eq!($arr::new(&4.into()).subarray(0, 1).length(), 1);
}};
}
#[wasm_bindgen_test]
fn new_subarray() {
each!(test_subarray);
}
macro_rules! test_fill {
($arr:ident) => {{
let arr = $arr::new(&4.into());
arr.for_each(&mut |x, _, _| {
assert_eq!(x as f64, 0.0);
});
arr.fill(2 as _, 0, 2);
arr.for_each(&mut |x, i, _| {
if i < 2 {
assert_eq!(x as f64, 2.0);
} else {
assert_eq!(x as f64, 0.0);
}
});
}};
}
#[wasm_bindgen_test]
fn new_fill() {
each!(test_fill);
}
macro_rules! test_at {
($arr:ident) => {{
let arr = $arr::new(&2.into());
arr.set_index(1, 1 as _);
assert_eq!(arr.at(-1).unwrap() as f64, 1 as f64);
}};
}
#[wasm_bindgen_test]
fn new_at() {
each!(test_at);
}
macro_rules! test_get_set {
($arr:ident) => {{
let arr = $arr::new(&1.into());
assert_eq!(arr.get_index(0) as f64, 0 as f64);
arr.set_index(0, 1 as _);
assert_eq!(arr.get_index(0) as f64, 1 as f64);
}};
}
#[wasm_bindgen_test]
fn new_get_set() {
each!(test_get_set);
}
macro_rules! test_slice {
($arr:ident) => {{
let arr = $arr::new(&4.into());
assert_eq!(arr.length(), 4);
assert_eq!(arr.slice(1, 2).length(), 1);
}};
}
#[wasm_bindgen_test]
fn new_slice() {
each!(test_slice);
}
#[wasm_bindgen_test]
fn view() {
let x = [1, 2, 3];
let array = unsafe { Int32Array::view(&x) };
assert_eq!(array.length(), 3);
array.for_each(&mut |x, i, _| {
assert_eq!(x, (i + 1) as i32);
});
}
#[wasm_bindgen_test]
fn from() {
let x: Vec<i32> = vec![1, 2, 3];
let array = Int32Array::from(x.as_slice());
assert_eq!(array.length(), 3);
array.for_each(&mut |x, i, _| {
assert_eq!(x, (i + 1) as i32);
});
}
#[wasm_bindgen_test]
fn copy_to() {
let mut x = [0; 10];
let array = Int32Array::new(&10.into());
array.fill(5, 0, 10);
array.copy_to(&mut x);
for i in x.iter() {
assert_eq!(*i, 5);
}
}
#[wasm_bindgen_test]
fn copy_from() {
let x = [1, 2, 3];
let array = Int32Array::new(&3.into());
array.copy_from(&x);
array.for_each(&mut |x, i, _| {
assert_eq!(x, (i + 1) as i32);
});
}
#[wasm_bindgen_test]
fn to_vec() {
let array = Int32Array::new(&10.into());
array.fill(5, 0, 10);
assert_eq!(array.to_vec(), vec![5, 5, 5, 5, 5, 5, 5, 5, 5, 5]);
}

View File

@@ -0,0 +1,17 @@
use js_sys::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn uri_error() {
let error = UriError::new("msg");
assert!(error.is_instance_of::<UriError>());
assert!(error.is_instance_of::<Error>());
assert!(error.is_instance_of::<Object>());
let _: &Error = error.as_ref();
let _: &Object = error.as_ref();
let base: &Error = error.as_ref();
assert_eq!(JsValue::from(base.message()), "msg");
}

View File

@@ -0,0 +1,61 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
#[wasm_bindgen]
extern "C" {
type SomeKey;
#[wasm_bindgen(method, setter, structural)]
fn set_some(this: &SomeKey, val: JsValue);
}
fn some_key() -> Object {
let key = SomeKey::from(JsValue::from(Object::new()));
key.set_some("key".into());
Object::from(JsValue::from(key))
}
#[wasm_bindgen_test]
fn new() {
assert!(JsValue::from(WeakMap::new()).is_object());
}
#[wasm_bindgen_test]
fn get_and_set() {
let map = WeakMap::new();
let key = some_key();
map.set(&key, &"value".into());
assert_eq!(map.get(&key), "value");
assert_eq!(map.get(&Object::new()), JsValue::undefined());
assert_eq!(map.get(&some_key()), JsValue::undefined());
}
#[wasm_bindgen_test]
fn has() {
let map = WeakMap::new();
let key = some_key();
map.set(&key, &"value".into());
assert!(map.has(&key));
assert!(!map.has(&Object::new()));
assert!(!map.has(&some_key()));
}
#[wasm_bindgen_test]
fn delete() {
let map = WeakMap::new();
let key = some_key();
assert!(!map.has(&key));
map.set(&key, &"value".into());
assert!(map.has(&key));
map.delete(&key);
assert!(!map.has(&key));
}
#[wasm_bindgen_test]
fn weakmap_inheritance() {
let map = WeakMap::new();
assert!(map.is_instance_of::<WeakMap>());
assert!(map.is_instance_of::<Object>());
let _: &Object = map.as_ref();
}

View File

@@ -0,0 +1,51 @@
use js_sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
#[wasm_bindgen]
extern "C" {
type SomeValue;
#[wasm_bindgen(method, setter, structural)]
fn set_some(this: &SomeValue, val: JsValue);
}
fn some_value() -> Object {
let value = SomeValue::from(JsValue::from(Object::new()));
value.set_some("value".into());
Object::from(JsValue::from(value))
}
#[wasm_bindgen_test]
fn new() {
assert!(JsValue::from(WeakSet::new()).is_object())
}
#[wasm_bindgen_test]
fn has() {
let set = WeakSet::new();
let value = some_value();
assert!(!set.has(&value));
set.add(&value);
assert!(set.has(&value));
assert!(!set.has(&some_value()));
}
#[wasm_bindgen_test]
fn delete() {
let set = WeakSet::new();
let value = some_value();
set.add(&value);
assert!(set.has(&value));
assert!(set.delete(&value));
assert!(!set.has(&value));
assert!(!set.delete(&value));
}
#[wasm_bindgen_test]
fn weakset_inheritance() {
let set = WeakSet::new();
assert!(set.is_instance_of::<WeakSet>());
assert!(set.is_instance_of::<Object>());
let _: &Object = set.as_ref();
}

View File

@@ -0,0 +1,45 @@
const { TextEncoder } = require("util");
const data =
"\u0000asm\u0001\u0000\u0000\u0000\u0001\b\u0002`\u0001\u007f\u0000`\u0000" +
"\u0000\u0002\u0019\u0001\u0007imports\rimported_func\u0000\u0000\u0003" +
"\u0002\u0001\u0001\u0007\u0011\u0001\rexported_func\u0000\u0001\n\b\u0001" +
"\u0006\u0000A*\u0010\u0000\u000b";
const encoder = new TextEncoder();
const wasmArray = encoder.encode(data);
function getWasmArray() {
return wasmArray;
}
function getTableObject() {
return { element: "anyfunc", initial: 1 }
}
function getInvalidTableObject() {
return { element: "anyfunc", initial: 1, maximum: 0 }
}
function getImports() {
return {
imports: {
imported_func: function () {
return 1;
}
}
};
}
// Polyfill `WebAssembly.instantiateStreaming` for node.
if (!global.WebAssembly.instantiateStreaming) {
global.WebAssembly.instantiateStreaming =
(response, imports) => response.then(buf => WebAssembly.instantiate(buf, imports));
}
module.exports = {
getInvalidTableObject,
getTableObject,
getWasmArray,
getImports,
};

View File

@@ -0,0 +1,205 @@
use js_sys::*;
use wasm_bindgen::{prelude::*, JsCast};
use wasm_bindgen_futures::JsFuture;
use wasm_bindgen_test::*;
use web_sys::{Headers, Response, ResponseInit};
#[wasm_bindgen(module = "tests/wasm/WebAssembly.js")]
extern "C" {
#[wasm_bindgen(js_name = getWasmArray)]
fn get_wasm_array() -> Uint8Array;
#[wasm_bindgen(js_name = getTableObject)]
fn get_table_object() -> Object;
#[wasm_bindgen(js_name = getInvalidTableObject)]
fn get_invalid_table_object() -> Object;
#[wasm_bindgen(js_name = getImports)]
fn get_imports() -> Object;
}
fn get_invalid_wasm() -> JsValue {
ArrayBuffer::new(42).into()
}
fn get_bad_type_wasm() -> JsValue {
2.into()
}
fn get_valid_wasm() -> JsValue {
get_wasm_array().into()
}
#[wasm_bindgen_test]
fn validate() {
assert!(!WebAssembly::validate(&get_invalid_wasm()).unwrap());
assert!(WebAssembly::validate(&get_bad_type_wasm()).is_err());
}
#[wasm_bindgen_test]
async fn compile_compile_error() {
let p = WebAssembly::compile(&get_invalid_wasm());
let e = JsFuture::from(p).await.unwrap_err();
assert!(e.is_instance_of::<WebAssembly::CompileError>());
}
#[wasm_bindgen_test]
async fn compile_type_error() {
let p = WebAssembly::compile(&get_bad_type_wasm());
let e = JsFuture::from(p).await.unwrap_err();
assert!(e.is_instance_of::<TypeError>());
}
#[wasm_bindgen_test]
async fn compile_valid() {
let p = WebAssembly::compile(&get_valid_wasm());
let module = JsFuture::from(p).await.unwrap();
assert!(module.is_instance_of::<WebAssembly::Module>());
}
#[wasm_bindgen_test]
fn module_inheritance() {
let module = WebAssembly::Module::new(&get_valid_wasm()).unwrap();
assert!(module.is_instance_of::<WebAssembly::Module>());
assert!(module.is_instance_of::<Object>());
let _: &Object = module.as_ref();
}
#[wasm_bindgen_test]
fn module_error() {
let error = WebAssembly::Module::new(&get_invalid_wasm()).err().unwrap();
assert!(error.is_instance_of::<WebAssembly::CompileError>());
let error = WebAssembly::Module::new(&get_bad_type_wasm())
.err()
.unwrap();
assert!(error.is_instance_of::<TypeError>());
}
#[wasm_bindgen_test]
fn module_custom_sections() {
let module = WebAssembly::Module::new(&get_valid_wasm()).unwrap();
let cust_sec = WebAssembly::Module::custom_sections(&module, "abcd");
assert_eq!(cust_sec.length(), 0);
}
#[wasm_bindgen_test]
fn module_exports() {
let module = WebAssembly::Module::new(&get_valid_wasm()).unwrap();
let exports = WebAssembly::Module::exports(&module);
assert_eq!(exports.length(), 1);
}
#[wasm_bindgen_test]
fn module_imports() {
let module = WebAssembly::Module::new(&get_valid_wasm()).unwrap();
let imports = WebAssembly::Module::imports(&module);
assert_eq!(imports.length(), 1);
}
#[wasm_bindgen_test]
fn table_inheritance() {
let table = WebAssembly::Table::new(&get_table_object().into()).unwrap();
assert!(table.is_instance_of::<WebAssembly::Table>());
assert!(table.is_instance_of::<Object>());
let _: &Object = table.as_ref();
}
#[wasm_bindgen_test]
fn table_error() {
let error = WebAssembly::Table::new(&get_invalid_table_object())
.err()
.unwrap();
assert!(error.is_instance_of::<RangeError>());
}
#[wasm_bindgen_test]
fn table() {
let table = WebAssembly::Table::new(&get_table_object().into()).unwrap();
assert_eq!(table.length(), 1);
assert!(table.get(0).is_ok());
assert!(table.get(999).is_err());
table.grow(1).unwrap();
assert_eq!(table.length(), 2);
let f = table.get(0).unwrap();
table.set(1, &f).unwrap();
}
#[wasm_bindgen_test]
fn compile_error_inheritance() {
let error = WebAssembly::CompileError::new("");
assert!(error.is_instance_of::<WebAssembly::CompileError>());
assert!(error.is_instance_of::<Error>());
let _: &Error = error.as_ref();
}
#[wasm_bindgen_test]
fn link_error_inheritance() {
let error = WebAssembly::LinkError::new("");
assert!(error.is_instance_of::<WebAssembly::LinkError>());
assert!(error.is_instance_of::<Error>());
let _: &Error = error.as_ref();
}
#[wasm_bindgen_test]
fn runtime_error_inheritance() {
let error = WebAssembly::RuntimeError::new("");
assert!(error.is_instance_of::<WebAssembly::RuntimeError>());
assert!(error.is_instance_of::<Error>());
let _: &Error = error.as_ref();
}
#[wasm_bindgen_test]
fn webassembly_instance() {
let module = WebAssembly::Module::new(&get_valid_wasm()).unwrap();
let imports = get_imports();
let instance = WebAssembly::Instance::new(&module, &imports).unwrap();
// Inheritance chain is correct.
assert!(instance.is_instance_of::<WebAssembly::Instance>());
assert!(instance.is_instance_of::<Object>());
let _: &Object = instance.as_ref();
// Has expected exports.
let exports = instance.exports();
assert!(Reflect::has(exports.as_ref(), &"exported_func".into()).unwrap());
}
#[wasm_bindgen_test]
async fn instantiate_module() {
let module = WebAssembly::Module::new(&get_valid_wasm()).unwrap();
let imports = get_imports();
let p = WebAssembly::instantiate_module(&module, &imports);
let inst = JsFuture::from(p).await.unwrap();
assert!(inst.is_instance_of::<WebAssembly::Instance>());
}
#[wasm_bindgen_test]
fn memory_works() {
let obj = Object::new();
Reflect::set(obj.as_ref(), &"initial".into(), &1.into()).unwrap();
let mem = WebAssembly::Memory::new(&obj).unwrap();
assert!(mem.is_instance_of::<WebAssembly::Memory>());
assert!(mem.is_instance_of::<Object>());
assert!(mem.buffer().is_instance_of::<ArrayBuffer>());
assert_eq!(mem.grow(1), 1);
assert_eq!(mem.grow(2), 2);
assert_eq!(mem.grow(3), 4);
assert_eq!(
mem.buffer()
.dyn_into::<ArrayBuffer>()
.unwrap()
.byte_length(),
7 * 64 * 1024,
);
}

View File

@@ -0,0 +1,90 @@
use std::f64::{INFINITY, NAN};
use js_sys::*;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn test_decode_uri() {
let x = decode_uri("https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B")
.ok()
.expect("should decode URI OK");
assert_eq!(String::from(x), "https://mozilla.org/?x=шеллы");
assert!(decode_uri("%E0%A4%A").is_err());
}
#[wasm_bindgen_test]
fn test_decode_uri_component() {
let x = decode_uri_component("%3Fx%3Dtest")
.ok()
.expect("should decode URI OK");
assert_eq!(String::from(x), "?x=test");
assert!(decode_uri_component("%E0%A4%A").is_err());
}
#[wasm_bindgen_test]
fn test_encode_uri() {
let x = encode_uri("ABC abc 123");
assert_eq!(String::from(x), "ABC%20abc%20123");
}
#[wasm_bindgen_test]
fn test_encode_uri_component() {
let x = encode_uri_component("?x=шеллы");
assert_eq!(String::from(x), "%3Fx%3D%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
}
#[wasm_bindgen_test]
fn test_eval() {
let x = eval("42").ok().expect("should eval OK");
assert_eq!(x.as_f64().unwrap(), 42.0);
let err = eval("(function () { throw 42; }())")
.err()
.expect("eval should throw");
assert_eq!(err.as_f64().unwrap(), 42.0);
}
#[wasm_bindgen_test]
fn test_is_finite() {
assert!(is_finite(&42.into()));
assert!(is_finite(&42.1.into()));
assert!(is_finite(&"42".into()));
assert!(!is_finite(&NAN.into()));
assert!(!is_finite(&INFINITY.into()));
}
#[wasm_bindgen_test]
fn test_parse_int_float() {
let i = parse_int("42", 10);
assert_eq!(i as i64, 42);
let i = parse_int("42", 16);
assert_eq!(i as i64, 66); // 0x42 == 66
let i = parse_int("invalid int", 10);
assert!(i.is_nan());
let f = parse_float("123456.789");
assert_eq!(f, 123456.789);
let f = parse_float("invalid float");
assert!(f.is_nan());
}
#[wasm_bindgen_test]
fn test_escape() {
assert_eq!(String::from(escape("test")), "test");
assert_eq!(String::from(escape("äöü")), "%E4%F6%FC");
assert_eq!(String::from(escape("ć")), "%u0107");
assert_eq!(String::from(escape("@*_+-./")), "@*_+-./");
}
#[wasm_bindgen_test]
fn test_unescape() {
assert_eq!(String::from(unescape("abc123")), "abc123");
assert_eq!(String::from(unescape("%E4%F6%FC")), "äöü");
assert_eq!(String::from(unescape("%u0107")), "ć");
assert_eq!(String::from(unescape("@*_+-./")), "@*_+-./");
}

View File

@@ -0,0 +1,43 @@
#![cfg(target_arch = "wasm32")]
#![allow(non_snake_case)]
pub mod Array;
pub mod ArrayBuffer;
pub mod ArrayIterator;
pub mod BigInt;
pub mod Boolean;
pub mod DataView;
pub mod Date;
pub mod Error;
pub mod EvalError;
pub mod Function;
pub mod Generator;
pub mod Intl;
pub mod Iterator;
pub mod JSON;
pub mod JsString;
pub mod Map;
pub mod MapIterator;
pub mod Math;
pub mod Number;
pub mod Object;
pub mod Promise;
pub mod Proxy;
pub mod RangeError;
pub mod ReferenceError;
pub mod Reflect;
pub mod RegExp;
pub mod Set;
pub mod SetIterator;
pub mod SharedArrayBuffer;
pub mod Symbol;
pub mod SyntaxError;
#[cfg(js_sys_unstable_apis)]
pub mod Temporal;
pub mod TypeError;
pub mod TypedArray;
pub mod UriError;
pub mod WeakMap;
pub mod WeakSet;
pub mod WebAssembly;
pub mod global_fns;