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 11 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
80 changes: 20 additions & 60 deletions src/bun.js/bindings/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1371,7 +1371,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 +2429,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 +2437,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
11 changes: 11 additions & 0 deletions src/bun.js/bindings/bindings.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5630,38 +5630,49 @@ 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 });
}

/// NOTE: can throw. Check for exceptions.
pub fn deepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
dylan-conway marked this conversation as resolved.
Show resolved Hide resolved
// JSC__JSValue__deepEquals
return cppFn("deepEquals", .{ this, other, global });
}

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

/// NOTE: can throw. Check for exceptions.
pub fn strictDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
// JSC__JSValue__strictDeepEquals
return cppFn("strictDeepEquals", .{ this, other, global });
}

/// same as `JSValue.strictDeepEquals`, but with jest asymmetric matchers enabled
/// NOTE: can throw. Check for exceptions.
pub fn jestStrictDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
// JSC__JSValue__jestStrictDeepEquals
return cppFn("jestStrictDeepEquals", .{ this, other, global });
}

/// 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
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
'use strict';
require('../../common');
const assert = require('assert');
const { describe, it } = require('node:test');


describe('assert.CallTracker.getCalls()', { concurrency: !process.env.TEST_PARALLEL }, () => {
const tracker = new assert.CallTracker();

it('should return empty list when no calls', () => {
const fn = tracker.calls();
assert.deepStrictEqual(tracker.getCalls(fn), []);
});

it('should return calls', () => {
const fn = tracker.calls(() => {});
const arg1 = {};
const arg2 = {};
fn(arg1, arg2);
fn.call(arg2, arg2);
assert.deepStrictEqual(tracker.getCalls(fn), [
{ arguments: [arg1, arg2], thisArg: undefined },
{ arguments: [arg2], thisArg: arg2 }]);
});

it('should throw when getting calls of a non-tracked function', () => {
[() => {}, 1, true, null, undefined, {}, []].forEach((fn) => {
assert.throws(() => tracker.getCalls(fn), { code: 'ERR_INVALID_ARG_VALUE' });
});
});

it('should return a frozen object', () => {
const fn = tracker.calls();
fn();
const calls = tracker.getCalls(fn);
// NOTE: v8 and jsc use different error messages for mutating frozen objects.
assert.throws(() => calls.push(1), /Attempted to assign to readonly property/);
assert.throws(() => Object.assign(calls[0], { foo: 'bar' }), /object that is not extensible/);
assert.throws(() => calls[0].arguments.push(1), /Attempted to assign to readonly property/);
});
});

describe('assert.CallTracker.reset()', () => {
const tracker = new assert.CallTracker();

it('should reset calls', () => {
const fn = tracker.calls();
fn();
fn();
fn();
assert.strictEqual(tracker.getCalls(fn).length, 3);
tracker.reset(fn);
assert.deepStrictEqual(tracker.getCalls(fn), []);
});

it('should reset all calls', () => {
const fn1 = tracker.calls();
const fn2 = tracker.calls();
fn1();
fn2();
assert.strictEqual(tracker.getCalls(fn1).length, 1);
assert.strictEqual(tracker.getCalls(fn2).length, 1);
tracker.reset();
assert.deepStrictEqual(tracker.getCalls(fn1), []);
assert.deepStrictEqual(tracker.getCalls(fn2), []);
});


it('should throw when resetting a non-tracked function', () => {
[() => {}, 1, true, null, {}, []].forEach((fn) => {
assert.throws(() => tracker.reset(fn), { code: 'ERR_INVALID_ARG_VALUE' });
});
});
});
Loading