X-Git-Url: https://adrianiainlam.tk/git/?a=blobdiff_plain;f=auto_tests%2Ftests%2FUtil.js;h=53a83f8130515a86bfc8264c3eb609e65d706d7d;hb=378194819965ebefef3b6c93e180cf343dcff997;hp=2b308b36df08b6e0a017ec6ff64410488367f240;hpb=20bb4e9d1e3da5bedaee7584a9e91aefd9e3a6d4;p=dygraphs.git diff --git a/auto_tests/tests/Util.js b/auto_tests/tests/Util.js index 2b308b3..53a83f8 100644 --- a/auto_tests/tests/Util.js +++ b/auto_tests/tests/Util.js @@ -79,3 +79,57 @@ Util.makeNumbers = function(ary) { } return ret; }; + + +/** + * Sample a pixel from the canvas. + * Returns an [r, g, b, a] tuple where each values is in [0, 255]. + */ +Util.samplePixel = function(canvas, x, y) { + var ctx = canvas.getContext("2d"); // bypasses Proxy if applied. + + // TODO(danvk): Any performance issues with this? + var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); + + var scale = Dygraph.getContextPixelRatio(ctx); + + var i = 4 * (x * scale + imageData.width * y * scale); + var d = imageData.data; + return [d[i], d[i+1], d[i+2], d[i+3]]; +}; + +/** + * Overrides the browser's built-in XMLHttpRequest with a mock. + * Usage: + * + * var mockXhr = Util.overrideXMLHttpRequest(your_data); + * ... call code that does an XHR ... + * mockXhr.respond(); // restores default behavior. + * ... do your assertions ... + */ +Util.overrideXMLHttpRequest = function(data) { + var originalXMLHttpRequest = XMLHttpRequest; + + var requests = []; + var FakeXMLHttpRequest = function () { + requests.push(this); + }; + FakeXMLHttpRequest.prototype.open = function () {}; + FakeXMLHttpRequest.prototype.send = function () { + this.readyState = 4; + this.status = 200; + this.responseText = data; + }; + FakeXMLHttpRequest.restore = function() { + XMLHttpRequest = originalXMLHttpRequest; + }; + FakeXMLHttpRequest.respond = function() { + for (var i = 0; i < requests.length; i++) { + requests[i].onreadystatechange(); + } + FakeXMLHttpRequest.restore(); + }; + XMLHttpRequest = FakeXMLHttpRequest; + return FakeXMLHttpRequest; +}; +