Bug 851044 - Modified stringifyArgs to use the objects toString method if it is not Object.prototype.toString when logging. r=Yoric

This commit is contained in:
Jonathan Laver 2013-04-05 10:29:16 +01:00
parent dc43b6f565
commit e41e419f3a
3 changed files with 81 additions and 2 deletions

View File

@ -103,7 +103,8 @@
}
/**
* Apply JSON.stringify to an argument of type object.
* Returns |arg.toString()| if available, otherwise
* applies JSON.stringify.
* Return itself otherwise.
*
* @param arg An argument to be stringified if possible.
@ -113,7 +114,20 @@
return arg;
}
if (arg && typeof arg === "object") {
return JSON.stringify(arg);
let argToString = arg.toString();
/**
* The only way to detect whether this object has a non-default
* implementation of |toString| is to check whether it returns
* '[object Object]'. Unfortunately, we cannot simply compare |arg.toString|
* and |Object.prototype.toString| as |arg| typically comes from another
* compartment.
*/
if (argToString === "[object Object]") {
return JSON.stringify(arg);
} else {
return argToString;
}
}
return arg;
};

View File

@ -0,0 +1,64 @@
"use strict";
Components.utils.import("resource://gre/modules/osfile.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
/**
* Tests logging by passing OS.Shared.LOG both an object with its own
* toString method, and one with the default.
*/
function run_test() {
do_test_pending();
let messageCount = 0;
// Create a console listener.
let consoleListener = {
observe: function (aMessage) {
++messageCount;
//Ignore unexpected messages.
if (!(aMessage instanceof Components.interfaces.nsIConsoleMessage)) {
return;
}
if (aMessage.message.indexOf("TEST OS") < 0) {
return;
}
if(messageCount == 1) {
do_check_eq(aMessage.message, "TEST OS {\"name\":\"test\"}\n");
}
if(messageCount == 2) {
do_check_eq(aMessage.message, "TEST OS name is test\n");
// This is required, as printing to the |Services.console|
// while in the observe function causes an exception.
do_execute_soon(function() {
toggleConsoleListener(false);
do_test_finished();
});
}
}
};
// Set/Unset the console listener.
function toggleConsoleListener (pref) {
OS.Shared.DEBUG = pref;
OS.Shared.TEST = pref;
Services.console[pref ? "registerListener" : "unregisterListener"](
consoleListener);
}
toggleConsoleListener(true);
let objectDefault = {name: "test"};
let CustomToString = function() {
this.name = "test";
}
CustomToString.prototype.toString = function() {
return "name is " + this.name;
}
let objectCustom = new CustomToString();
OS.Shared.LOG(objectDefault);
OS.Shared.LOG(objectCustom);
// Once both messages are observed OS.Shared.DEBUG, and OS.Shared.TEST
// are reset to false.
}

View File

@ -5,3 +5,4 @@ tail =
[test_path.js]
[test_osfile_async.js]
[test_profiledir.js]
[test_logging.js]