Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(node/assert): port more test cases from node #16895

Merged
merged 24 commits into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .vscode/launch.json

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

4 changes: 2 additions & 2 deletions src/bun.js/bindings/BunObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -489,12 +489,12 @@ JSC_DEFINE_HOST_FUNCTION(functionBunDeepEquals, (JSGlobalObject * globalObject,

JSC::JSValue arg1 = callFrame->uncheckedArgument(0);
JSC::JSValue arg2 = callFrame->uncheckedArgument(1);
JSC::JSValue arg3 = callFrame->argument(2);
JSC::JSValue strict = callFrame->argument(2);

Vector<std::pair<JSValue, JSValue>, 16> stack;
MarkedArgumentBuffer gcBuffer;

if (arg3.isBoolean() && arg3.asBoolean()) {
if (strict.isBoolean() && strict.asBoolean()) {

bool isEqual = Bun__deepEquals<true, false>(globalObject, arg1, arg2, gcBuffer, stack, &scope, true);
RETURN_IF_EXCEPTION(scope, {});
Expand Down
84 changes: 24 additions & 60 deletions src/bun.js/bindings/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,10 @@ template<bool isStrict, bool enableAsymmetricMatchers>
bool Bun__deepEquals(JSC__JSGlobalObject* globalObject, JSValue v1, JSValue v2, MarkedArgumentBuffer& gcBuffer, Vector<std::pair<JSC::JSValue, JSC::JSValue>, 16>& stack, ThrowScope* scope, bool addToStack)
{
VM& vm = globalObject->vm();
if (UNLIKELY(!vm.isSafeToRecurse())) {
throwStackOverflowError(globalObject, *scope);
return false;
}

// need to check this before primitives, asymmetric matchers
// can match against any type of value.
Expand Down Expand Up @@ -1371,7 +1375,11 @@ std::optional<bool> specialObjectsDequal(JSC__JSGlobalObject* globalObject, Mark
compareAsNormalValue:
break;
}

// globalThis is only equal to globalThis
// NOTE: Zig::GlobalObject is tagged as GlobalProxyType
case GlobalObjectType:
case GlobalProxyType:
return c1Type == c2Type;
DonIsaac marked this conversation as resolved.
Show resolved Hide resolved
default: {
break;
}
Expand Down Expand Up @@ -2425,35 +2433,6 @@ size_t JSC__VM__heapSize(JSC__VM* arg0)
return arg0->heap.size();
}

// This is very naive!
JSC__JSInternalPromise* JSC__VM__reloadModule(JSC__VM* vm, JSC__JSGlobalObject* arg1,
ZigString arg2)
{
return nullptr;
// JSC::JSMap *map = JSC::jsDynamicCast<JSC::JSMap *>(
// arg1->vm(), arg1->moduleLoader()->getDirect(
// arg1->vm(), JSC::Identifier::fromString(arg1->vm(), "registry"_s)));

// const JSC::Identifier identifier = Zig::toIdentifier(arg2, arg1);
// JSC::JSValue val = JSC::identifierToJSValue(arg1->vm(), identifier);

// if (!map->has(arg1, val)) return nullptr;

// if (JSC::JSObject *registryEntry =
// JSC::jsDynamicCast<JSC::JSObject *>(arg1-> map->get(arg1, val))) {
// auto moduleIdent = JSC::Identifier::fromString(arg1->vm(), "module");
// if (JSC::JSModuleRecord *record = JSC::jsDynamicCast<JSC::JSModuleRecord *>(
// arg1->vm(), registryEntry->getDirect(arg1->vm(), moduleIdent))) {
// registryEntry->putDirect(arg1->vm(), moduleIdent, JSC::jsUndefined());
// JSC::JSModuleRecord::destroy(static_cast<JSC::JSCell *>(record));
// }
// map->remove(arg1, val);
// return JSC__JSModuleLoader__loadAndEvaluateModule(arg1, arg2);
// }

// return nullptr;
}

bool JSC__JSValue__isSameValue(JSC__JSValue JSValue0, JSC__JSValue JSValue1,
JSC__JSGlobalObject* globalObject)
{
Expand All @@ -2462,52 +2441,37 @@ bool JSC__JSValue__isSameValue(JSC__JSValue JSValue0, JSC__JSValue JSValue1,
return JSC::sameValue(globalObject, left, right);
}

#define IMPL_DEEP_EQUALS_WRAPPER(strict, enableAsymmetricMatchers, globalObject, a, b) \
DonIsaac marked this conversation as resolved.
Show resolved Hide resolved
ASSERT_NO_PENDING_EXCEPTION(globalObject); \
JSValue v1 = JSValue::decode(a); \
JSValue v2 = JSValue::decode(b); \
ThrowScope scope = DECLARE_THROW_SCOPE(globalObject->vm()); \
Vector<std::pair<JSValue, JSValue>, 16> stack; \
MarkedArgumentBuffer args; \
return Bun__deepEquals<strict, enableAsymmetricMatchers>(globalObject, v1, v2, args, stack, &scope, true)

bool JSC__JSValue__deepEquals(JSC__JSValue JSValue0, JSC__JSValue JSValue1, JSC__JSGlobalObject* globalObject)
{
ASSERT_NO_PENDING_EXCEPTION(globalObject);
JSValue v1 = JSValue::decode(JSValue0);
JSValue v2 = JSValue::decode(JSValue1);

ThrowScope scope = DECLARE_THROW_SCOPE(globalObject->vm());
Vector<std::pair<JSValue, JSValue>, 16> stack;
MarkedArgumentBuffer args;
return Bun__deepEquals<false, false>(globalObject, v1, v2, args, stack, &scope, true);
IMPL_DEEP_EQUALS_WRAPPER(false, false, globalObject, JSValue0, JSValue1);
}

bool JSC__JSValue__jestDeepEquals(JSC__JSValue JSValue0, JSC__JSValue JSValue1, JSC__JSGlobalObject* globalObject)
{
JSValue v1 = JSValue::decode(JSValue0);
JSValue v2 = JSValue::decode(JSValue1);

ThrowScope scope = DECLARE_THROW_SCOPE(globalObject->vm());
Vector<std::pair<JSValue, JSValue>, 16> stack;
MarkedArgumentBuffer args;
return Bun__deepEquals<false, true>(globalObject, v1, v2, args, stack, &scope, true);
IMPL_DEEP_EQUALS_WRAPPER(false, true, globalObject, JSValue0, JSValue1);
}

bool JSC__JSValue__strictDeepEquals(JSC__JSValue JSValue0, JSC__JSValue JSValue1, JSC__JSGlobalObject* globalObject)
{
JSValue v1 = JSValue::decode(JSValue0);
JSValue v2 = JSValue::decode(JSValue1);

ThrowScope scope = DECLARE_THROW_SCOPE(globalObject->vm());
Vector<std::pair<JSValue, JSValue>, 16> stack;
MarkedArgumentBuffer args;
return Bun__deepEquals<true, false>(globalObject, v1, v2, args, stack, &scope, true);
IMPL_DEEP_EQUALS_WRAPPER(true, false, globalObject, JSValue0, JSValue1);
}

bool JSC__JSValue__jestStrictDeepEquals(JSC__JSValue JSValue0, JSC__JSValue JSValue1, JSC__JSGlobalObject* globalObject)
{
JSValue v1 = JSValue::decode(JSValue0);
JSValue v2 = JSValue::decode(JSValue1);

ThrowScope scope = DECLARE_THROW_SCOPE(globalObject->vm());
Vector<std::pair<JSValue, JSValue>, 16> stack;
MarkedArgumentBuffer args;

return Bun__deepEquals<true, true>(globalObject, v1, v2, args, stack, &scope, true);
IMPL_DEEP_EQUALS_WRAPPER(true, true, globalObject, JSValue0, JSValue1);
}

#undef IMPL_DEEP_EQUALS_WRAPPER

bool JSC__JSValue__deepMatch(JSC__JSValue JSValue0, JSC__JSValue JSValue1, JSC__JSGlobalObject* globalObject, bool replacePropsWithAsymmetricMatchers)
{
JSValue obj = JSValue::decode(JSValue0);
Expand Down
27 changes: 20 additions & 7 deletions src/bun.js/bindings/bindings.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5630,38 +5630,51 @@ pub const JSValue = enum(i64) {
}

/// Object.is()
///
/// This algorithm differs from the IsStrictlyEqual Algorithm by treating all NaN values as equivalent and by differentiating +0𝔽 from -0𝔽.
/// https://tc39.es/ecma262/#sec-samevalue
pub fn isSameValue(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
return @intFromEnum(this) == @intFromEnum(other) or cppFn("isSameValue", .{ this, other, global });
}

pub fn deepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
return cppFn("deepEquals", .{ this, other, global });
pub fn deepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) JSError!bool {
// JSC__JSValue__deepEquals
const result = cppFn("deepEquals", .{ this, other, global });
if (global.hasException()) return error.JSError;
return result;
}

/// same as `JSValue.deepEquals`, but with jest asymmetric matchers enabled
pub fn jestDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bun.JSError!bool {
pub fn jestDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) JSError!bool {
const result = cppFn("jestDeepEquals", .{ this, other, global });
if (global.hasException()) return error.JSError;
return result;
}

pub fn strictDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
return cppFn("strictDeepEquals", .{ this, other, global });
pub fn strictDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) JSError!bool {
// JSC__JSValue__strictDeepEquals
const result = cppFn("strictDeepEquals", .{ this, other, global });
if (global.hasException()) return error.JSError;
return result;
}

/// same as `JSValue.strictDeepEquals`, but with jest asymmetric matchers enabled
pub fn jestStrictDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
return cppFn("jestStrictDeepEquals", .{ this, other, global });
pub fn jestStrictDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) JSError!bool {
// JSC__JSValue__jestStrictDeepEquals
const result = cppFn("jestStrictDeepEquals", .{ this, other, global });
if (global.hasException()) return error.JSError;
return result;
}

/// NOTE: can throw. Check for exceptions.
pub fn deepMatch(this: JSValue, subset: JSValue, global: *JSGlobalObject, replace_props_with_asymmetric_matchers: bool) bool {
// JSC__JSValue__deepMatch
return cppFn("deepMatch", .{ this, subset, global, replace_props_with_asymmetric_matchers });
}

/// same as `JSValue.deepMatch`, but with jest asymmetric matchers enabled
pub fn jestDeepMatch(this: JSValue, subset: JSValue, global: *JSGlobalObject, replace_props_with_asymmetric_matchers: bool) bool {
// JSC__JSValue__jestDeepMatch
return cppFn("jestDeepMatch", .{ this, subset, global, replace_props_with_asymmetric_matchers });
}

Expand Down
1 change: 1 addition & 0 deletions src/bun.js/bindings/headers-handwritten.h
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ extern "C" size_t Bun__encoding__byteLengthUTF16(const UChar* ptr, size_t len, E
extern "C" int64_t Bun__encoding__constructFromLatin1(void*, const unsigned char* ptr, size_t len, Encoding encoding);
extern "C" int64_t Bun__encoding__constructFromUTF16(void*, const UChar* ptr, size_t len, Encoding encoding);

/// @note throws a JS exception and returns false if a stack overflow occurs
template<bool isStrict, bool enableAsymmetricMatchers>
bool Bun__deepEquals(JSC::JSGlobalObject* globalObject, JSC::JSValue v1, JSC::JSValue v2, JSC::MarkedArgumentBuffer&, Vector<std::pair<JSC::JSValue, JSC::JSValue>, 16>& stack, JSC::ThrowScope* scope, bool addToStack);

Expand Down
6 changes: 3 additions & 3 deletions src/bun.js/test/expect.zig
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ pub const Expect = struct {
}

const signature = comptime getSignature("toBe", "<green>expected<r>", false);
if (left.deepEquals(right, globalThis) or left.strictDeepEquals(right, globalThis)) {
if (try left.deepEquals(right, globalThis) or try left.strictDeepEquals(right, globalThis)) {
const fmt =
(if (!has_custom_label) "\n\n<d>If this test should pass, replace \"toBe\" with \"toEqual\" or \"toStrictEqual\"<r>" else "") ++
"\n\nExpected: <green>{any}<r>\n" ++
Expand Down Expand Up @@ -1629,7 +1629,7 @@ pub const Expect = struct {
const value: JSValue = try this.getValue(globalThis, thisValue, "toStrictEqual", "<green>expected<r>");

const not = this.flags.not;
var pass = value.jestStrictDeepEquals(expected, globalThis);
var pass = try value.jestStrictDeepEquals(expected, globalThis);

if (not) pass = !pass;
if (pass) return .undefined;
Expand Down Expand Up @@ -2351,7 +2351,7 @@ pub const Expect = struct {

if (Expect.isAsymmetricMatcher(expected_value)) {
const signature = comptime getSignature("toThrow", "<green>expected<r>", false);
const is_equal = result.jestStrictDeepEquals(expected_value, globalThis);
const is_equal = try result.jestStrictDeepEquals(expected_value, globalThis);

if (globalThis.hasException()) {
return .zero;
Expand Down
5 changes: 5 additions & 0 deletions src/js/internal/assert/assertion_error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,11 @@ class AssertionError extends Error {
this.operator = operator;
}
ErrorCaptureStackTrace(this, stackStartFn || stackStartFunction);
// JSC::Interpreter::getStackTrace() sometimes short-circuits without creating a .stack property.
// e.g.: https://github.com/oven-sh/WebKit/blob/e32c6356625cfacebff0c61d182f759abf6f508a/Source/JavaScriptCore/interpreter/Interpreter.cpp#L501
if ($isUndefinedOrNull(this.stack)) {
ErrorCaptureStackTrace(this, AssertionError);
}
// Create error message including the error code in the name.
this.stack; // eslint-disable-line no-unused-expressions
// Reset the name.
Expand Down
8 changes: 8 additions & 0 deletions src/js/internal/primordials.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,14 @@ export default {
}
},
),
SafeWeakMap: makeSafe(
DonIsaac marked this conversation as resolved.
Show resolved Hide resolved
WeakMap,
class SafeWeakMap extends WeakMap {
constructor(i) {
super(i);
}
},
),
SetPrototypeGetSize: getGetter(Set, "size"),
String,
TypedArrayPrototypeGetLength: getGetter(Uint8Array, "length"),
Expand Down
2 changes: 1 addition & 1 deletion src/js/node/assert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -672,7 +672,7 @@ function getActual(fn) {
return NO_EXCEPTION_SENTINEL;
}

function checkIsPromise(obj) {
function checkIsPromise(obj): obj is Promise<unknown> {
// Accept native ES6 promises and promises that are implemented in a similar
// way. Do not accept thenables that use a function as `obj` and that have no
// `catch` handler.
Expand Down
41 changes: 41 additions & 0 deletions test/js/bun/test/expect.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,47 @@ describe("expect()", () => {
}
});
};
describe("toBe()", () => {
let obj = {};
it.each([
[0, 0.0],
[+0, +0],
[0, +0],
[-0, -0],
[1, 1],
[1, 1.0],
[NaN, NaN],
[Infinity, Infinity],
[obj, obj],
[Symbol.for("a"), Symbol.for("a")],
])("expect(%p).toBe(%p) == true", (a, b) => {
expect(a).toBe(b);
expect(b).toBe(a);
});
it.each([
[0, false],
[0, ""],
[0, -0],
[+0, -0],
[1, 2],
[1, true],
[1, "1"],
[Infinity, -Infinity],
["foo", "Foo"],
["foo", "bar"],
["", " "],
["", " "],
["", true],
[{}, {}], //
[new Set(), new Set()], //
[function a() {}, function a() {}], //
[Symbol.for("a"), Symbol.for("b")],
[Symbol("a"), Symbol("a")],
])("expect(%p).toBe(%p) == false", (a, b) => {
expect(a).not.toBe(b);
expect(b).not.toBe(a);
});
});

test("rejects", async () => {
await expect(Promise.reject(4)).rejects.toBe(4);
Expand Down
7 changes: 5 additions & 2 deletions test/js/node/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,8 +348,9 @@ if (normalized.includes("node/test/parallel")) {
}
}

function describe(labelOrFn: string | Function, maybeFn?: Function) {
const [label, fn] = typeof labelOrFn == "function" ? [labelOrFn.name, labelOrFn] : [labelOrFn, maybeFn];
function describe(labelOrFn: string | Function, maybeFnOrOptions?: Function, maybeFn?: Function) {
const [label, fn] =
typeof labelOrFn == "function" ? [labelOrFn.name, labelOrFn] : [labelOrFn, maybeFn ?? maybeFnOrOptions];
if (typeof fn !== "function") throw new TypeError("Second argument to describe() must be a function.");

getContext().testStack.push(label);
Expand All @@ -372,7 +373,9 @@ if (normalized.includes("node/test/parallel")) {

return {
test,
it: test,
describe,
suite: describe,
};
}

Expand Down
Loading