Skip to content

Commit

Permalink
feat: implement console.groupCollapsed
Browse files Browse the repository at this point in the history
This implementation of groupCollapsed is intentionally different
from the spec defined by whatwg. See the conversation in #1355
and #1363.
  • Loading branch information
kt3k committed Jan 3, 2019
1 parent 02b6950 commit fd3a409
Show file tree
Hide file tree
Showing 10 changed files with 299 additions and 48 deletions.
73 changes: 61 additions & 12 deletions js/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ type ConsoleOptions = Partial<{
showHidden: boolean;
depth: number;
colors: boolean;
indentLevel: number;
collapsedAt: number | null;
}>;

// Default depth of logging nested objects
Expand Down Expand Up @@ -322,13 +324,26 @@ function stringifyWithQuotes(
}
}

// Returns true when the console is collapsed.
function isCollapsed(
collapsedAt: number | null | undefined,
indentLevel: number | null | undefined
) {
if (collapsedAt == null || indentLevel == null) {
return false;
}

return collapsedAt <= indentLevel;
}

/** TODO Do not expose this from "deno" namespace. */
export function stringifyArgs(
// tslint:disable-next-line:no-any
args: any[],
options: ConsoleOptions = {}
): string {
const out: string[] = [];
const { collapsedAt, indentLevel } = options;
for (const a of args) {
if (typeof a === "string") {
out.push(a);
Expand All @@ -347,7 +362,12 @@ export function stringifyArgs(
}
}
let outstr = out.join(" ");
if (groupIndent.length !== 0) {
if (
!isCollapsed(collapsedAt, indentLevel) &&
indentLevel != null &&
indentLevel > 0
) {
const groupIndent = " ".repeat(indentLevel);
if (outstr.indexOf("\n") !== -1) {
outstr = outstr.replace(/\n/g, `\n${groupIndent}`);
}
Expand All @@ -356,20 +376,30 @@ export function stringifyArgs(
return outstr;
}

type PrintFunc = (x: string, isErr?: boolean) => void;
type PrintFunc = (x: string, isErr?: boolean, printsNewline?: boolean) => void;

const countMap = new Map<string, number>();
const timerMap = new Map<string, number>();

let groupIndent = "";

export class Console {
constructor(private printFunc: PrintFunc) {}
indentLevel: number;
collapsedAt: number | null;
constructor(private printFunc: PrintFunc) {
this.indentLevel = 0;
this.collapsedAt = null;
}

/** Writes the arguments to stdout */
// tslint:disable-next-line:no-any
log = (...args: any[]): void => {
this.printFunc(stringifyArgs(args));
this.printFunc(
stringifyArgs(args, {
indentLevel: this.indentLevel,
collapsedAt: this.collapsedAt
}),
false,
!isCollapsed(this.collapsedAt, this.indentLevel)
);
};

/** Writes the arguments to stdout */
Expand All @@ -380,13 +410,20 @@ export class Console {
/** Writes the properties of the supplied `obj` to stdout */
// tslint:disable-next-line:no-any
dir = (obj: any, options: ConsoleOptions = {}) => {
this.printFunc(stringifyArgs([obj], options));
this.log(stringifyArgs([obj], options));
};

/** Writes the arguments to stdout */
// tslint:disable-next-line:no-any
warn = (...args: any[]): void => {
this.printFunc(stringifyArgs(args), true);
this.printFunc(
stringifyArgs(args, {
indentLevel: this.indentLevel,
collapsedAt: this.collapsedAt
}),
true,
!isCollapsed(this.collapsedAt, this.indentLevel)
);
};

/** Writes the arguments to stdout */
Expand Down Expand Up @@ -482,16 +519,28 @@ export class Console {
this.info(`${label}: ${duration}ms`);
};

// tslint:disable-next-line:no-any
group = (...label: any[]): void => {
groupIndent += " ";
group = (...label: Array<unknown>): void => {
if (label.length > 0) {
this.log(...label);
}
this.indentLevel += 2;
};

groupCollapsed = (...label: Array<unknown>): void => {
if (this.collapsedAt == null) {
this.collapsedAt = this.indentLevel;
}
this.group(...label);
};

groupEnd = (): void => {
groupIndent = groupIndent.slice(0, groupIndent.length - 2);
if (this.indentLevel > 0) {
this.indentLevel -= 2;
}
if (this.collapsedAt != null && this.collapsedAt >= this.indentLevel) {
this.collapsedAt = null;
this.log(); // When the collapsed state ended, outputs a sinle new line.
}
};
}

Expand Down
35 changes: 1 addition & 34 deletions js/console_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ test(function consoleTestStringifyCircular() {
assertEqual(
stringify(console),
// tslint:disable-next-line:max-line-length
"Console { printFunc: [Function], log: [Function], debug: [Function], info: [Function], dir: [Function], warn: [Function], error: [Function], assert: [Function], count: [Function], countReset: [Function], time: [Function], timeLog: [Function], timeEnd: [Function], group: [Function], groupEnd: [Function] }"
"Console { printFunc: [Function], log: [Function], debug: [Function], info: [Function], dir: [Function], warn: [Function], error: [Function], assert: [Function], count: [Function], countReset: [Function], time: [Function], timeLog: [Function], timeEnd: [Function], group: [Function], groupCollapsed: [Function], groupEnd: [Function], indentLevel: 0, collapsedAt: null }"
);
// test inspect is working the same
assertEqual(inspect(nestedObj), nestedObjExpected);
Expand Down Expand Up @@ -145,39 +145,6 @@ test(function consoleTestStringifyWithDepth() {
);
});

test(function consoleStringifyWithGroup() {
const outstrs = [
"This is the outer level",
"Level 2",
"Level 3",
"More of level 3",
"Back to level 2",
"Back to the outer level",
"Still at the outer level"
];
const expectedOut = `${outstrs[0]} ${outstrs[1]} ${outstrs[2]} ${
outstrs[3]
}${outstrs[4]}${outstrs[5]}`;

const expectedErr = ` More of level 3`;
let out = "";
let outErr = "";
out += stringifyArgs([outstrs[0]]);
console.group();
out += stringifyArgs([outstrs[1]]);
console.group();
out += stringifyArgs([outstrs[2]]);
outErr += stringifyArgs([outstrs[3]]);
console.groupEnd();
out += stringifyArgs([outstrs[3]]);
console.groupEnd();
out += stringifyArgs([outstrs[4]]);
console.groupEnd();
out += stringifyArgs([outstrs[5]]);
assertEqual(out, expectedOut);
assertEqual(outErr, expectedErr);
});

test(function consoleTestCallToStringOnLabel() {
const methods = ["count", "countReset", "time", "timeLog", "timeEnd"];

Expand Down
175 changes: 175 additions & 0 deletions js/testing/testing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
/*!
Copyright 2018 Propel http:https://propel.site/. All rights reserved.
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:https://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.
*/

// Do not add imports in this file in order to be compatible with Node.

export function assertEqual(actual: unknown, expected: unknown, msg?: string) {
if (!equal(actual, expected)) {
let actualString: string;
let expectedString: string;
try {
actualString = String(actual);
} catch (e) {
actualString = "[Cannot display]";
}
try {
expectedString = String(expected);
} catch (e) {
expectedString = "[Cannot display]";
}
console.error(
"assertEqual failed. actual =",
actualString,
"expected =",
expectedString
);
if (!msg) {
msg = `actual: ${actualString} expected: ${expectedString}`;
}
throw new Error(msg);
}
}

export function assert(expr: boolean, msg = "") {
if (!expr) {
throw new Error(msg);
}
}

export function equal(c: unknown, d: unknown): boolean {
const seen = new Map();
return (function compare(a: unknown, b: unknown) {
if (Object.is(a, b)) {
return true;
}
if (a && typeof a === "object" && b && typeof b === "object") {
if (seen.get(a) === b) {
return true;
}
if (Object.keys(a || {}).length !== Object.keys(b || {}).length) {
return false;
}
const merged = { ...a, ...b };
for (const key in merged) {
type Key = keyof typeof merged;
if (!compare(a && a[key as Key], b && b[key as Key])) {
return false;
}
}
seen.set(a, b);
return true;
}
return false;
})(c, d);
}

export type TestFunction = () => void | Promise<void>;

export interface TestDefinition {
fn: TestFunction;
name: string;
}

export const exitOnFail = true;

let filterRegExp: RegExp | null;
const tests: TestDefinition[] = [];

let filtered = 0;
const ignored = 0;
const measured = 0;

// Must be called before any test() that needs to be filtered.
export function setFilter(s: string): void {
filterRegExp = new RegExp(s, "i");
}

export function test(t: TestDefinition | TestFunction): void {
const fn: TestFunction = typeof t === "function" ? t : t.fn;
const name: string = t.name;

if (!name) {
throw new Error("Test function may not be anonymous");
}
if (filter(name)) {
tests.push({ fn, name });
} else {
filtered++;
}
}

function filter(name: string): boolean {
if (filterRegExp) {
return filterRegExp.test(name);
} else {
return true;
}
}

const RESET = "\x1b[0m";
const FG_RED = "\x1b[31m";
const FG_GREEN = "\x1b[32m";

function red_failed() {
return FG_RED + "FAILED" + RESET;
}

function green_ok() {
return FG_GREEN + "ok" + RESET;
}

async function runTests() {
let passed = 0;
let failed = 0;

console.log("running", tests.length, "tests");
for (let i = 0; i < tests.length; i++) {
const { fn, name } = tests[i];
let result = green_ok();
console.groupCollapsed(`test ${name} `);
try {
await fn();
passed++;
} catch (e) {
result = red_failed();
console.error((e && e.stack) || e);
failed++;
if (exitOnFail) {
break;
}
}
console.log("...", result);
console.groupEnd();
}

// Attempting to match the output of Rust's test runner.
const result = failed > 0 ? red_failed() : green_ok();
console.log(
`\ntest result: ${result}. ${passed} passed; ${failed} failed; ` +
`${ignored} ignored; ${measured} measured; ${filtered} filtered out\n`
);

if (failed === 0) {
// All good.
} else {
// Use setTimeout to avoid the error being ignored due to unhandled
// promise rejections being swallowed.
setTimeout(() => {
throw new Error(`There were ${failed} test failures.`);
}, 0);
}
}

setTimeout(runTests, 0);
8 changes: 6 additions & 2 deletions libdeno/binding.cc
Original file line number Diff line number Diff line change
Expand Up @@ -191,17 +191,21 @@ void PromiseRejectCallback(v8::PromiseRejectMessage promise_reject_message) {

void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK_GE(args.Length(), 1);
CHECK_LE(args.Length(), 2);
CHECK_LE(args.Length(), 3);
auto* isolate = args.GetIsolate();
DenoIsolate* d = FromIsolate(isolate);
auto context = d->context_.Get(d->isolate_);
v8::HandleScope handle_scope(isolate);
v8::String::Utf8Value str(isolate, args[0]);
bool is_err =
args.Length() >= 2 ? args[1]->BooleanValue(context).ToChecked() : false;
bool prints_newline =
args.Length() >= 3 ? args[2]->BooleanValue(context).ToChecked() : true;
FILE* file = is_err ? stderr : stdout;
fwrite(*str, sizeof(**str), str.length(), file);
fprintf(file, "\n");
if (prints_newline) {
fprintf(file, "\n");
}
fflush(file);
}

Expand Down
2 changes: 2 additions & 0 deletions tests/console_group.test
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
args: tests/console_group.ts --reload
output: tests/console_group.ts.out
Loading

0 comments on commit fd3a409

Please sign in to comment.