tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

ImageTestUtils.sys.mjs (1800B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      4 
      5 /**
      6 * Provides testing functions working with images and image URLs.
      7 */
      8 
      9 import { Assert } from "resource://testing-common/Assert.sys.mjs";
     10 
     11 export const ImageTestUtils = {
     12  /**
     13   * Assert that both provided image URLs are visually identical.
     14   */
     15  async assertEqualImage(win, first, second, msg) {
     16    const firstCanvas = await this.drawImageOnCanvas(win, first);
     17    const secondCanvas = await this.drawImageOnCanvas(win, second);
     18 
     19    Assert.equal(
     20      firstCanvas.width,
     21      secondCanvas.width,
     22      `${msg} - Both images have the same width`
     23    );
     24    Assert.equal(
     25      firstCanvas.height,
     26      secondCanvas.height,
     27      `${msg} - Both images have the same height`
     28    );
     29 
     30    const differences = win.windowUtils.compareCanvases(
     31      firstCanvas,
     32      secondCanvas,
     33      {}
     34    );
     35    Assert.equal(differences, 0, `${msg} - Both images are identical`);
     36  },
     37 
     38  drawImageOnCanvas(win, url) {
     39    return new Promise((resolve, reject) => {
     40      const img = new win.Image();
     41 
     42      img.onload = function () {
     43        // TODO: compareCanvases only works for the HTMLCanvasElement.
     44        const canvas = win.document.createElementNS(
     45          "http://www.w3.org/1999/xhtml",
     46          "canvas"
     47        );
     48        canvas.width = img.naturalWidth;
     49        canvas.height = img.naturalHeight;
     50 
     51        const ctx = canvas.getContext("2d");
     52        ctx.drawImage(img, 0, 0);
     53 
     54        resolve(canvas);
     55      };
     56 
     57      img.onerror = function () {
     58        reject(`error loading image ${url}`);
     59      };
     60 
     61      // Load the src image for drawing
     62      img.src = url;
     63    });
     64  },
     65 };