All files / Sources/Testing testUtils.js

93.61% Statements 88/94
65.51% Branches 19/29
89.47% Functions 17/19
93.4% Lines 85/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229      1x     311x 311x 311x       202x 202x 202x 202x 202x 202x 202x 202x   202x 202x                                       93x 93x   93x 89x   4x 4x     93x 93x 93x 93x 93x   93x 93x 109x     93x 109x 109x 109x 109x   109x 109x                         109x 109x 96x 96x 96x 96x 96x 96x         93x 93x                               93x 93x             104x 104x     2666x 2666x       203x 203x         103x 103x 203x 203x       103x 203x       2562x 103x 2664x 2664x     103x 2664x       103x 103x       104x                           11x 11x 11x 11x 11x 11x                       13x     13x 71x 1x     12x       3x 3x 3x     3x 13x       3x                        
import pixelmatch from 'pixelmatch';
import vtkRTAnalyticSource from 'vtk.js/Sources/Filters/Sources/RTAnalyticSource';
 
let REMOVE_DOM_ELEMENTS = true;
 
function createCanvasContext() {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  return { canvas, context };
}
 
function getImageDataFromURI(imageDataURI) {
  return new Promise((resolve, reject) => {
    const { canvas, context } = createCanvasContext();
    const img = new Image();
    img.addEventListener('load', () => {
      canvas.width = img.width;
      canvas.height = img.height;
      context.drawImage(img, 0, 0);
      resolve(context.getImageData(0, 0, img.width, img.height));
    });
    img.addEventListener('error', reject);
    img.src = imageDataURI;
  });
}
 
/**
 * Compares two images
 * @param image the image under test
 * @param baselines an array of baseline images
 * @param tapeContext tape testing context
 * @param opts if number: mismatch tolerance. if object: tolerance and pixel threshold
 */
async function compareImages(
  image,
  baselines,
  testName,
  tapeContext,
  opts,
  nextCallback
) {
  // defaults
  let pixelThreshold = 0.1;
  let mismatchTolerance = 5; // percent
 
  if (typeof opts === 'number') {
    mismatchTolerance = opts;
  } else {
    pixelThreshold = opts?.pixelThreshold ?? pixelThreshold;
    mismatchTolerance = opts?.mismatchTolerance ?? mismatchTolerance;
  }
 
  let minDelta = 100;
  let minRawCount = 0;
  let minDiff = '';
  let minIndex = 0;
  let isSameDimensions = false;
 
  const imageUnderTest = await getImageDataFromURI(image);
  const baselineImages = await Promise.all(
    baselines.map((baseline) => getImageDataFromURI(baseline))
  );
 
  baselineImages.forEach((baseline, idx) => {
    const diff = createCanvasContext();
    const { width, height } = baseline;
    diff.canvas.width = width;
    diff.canvas.height = height;
 
    const diffImage = diff.context.createImageData(width, height);
    const mismatched = pixelmatch(
      imageUnderTest.data,
      baseline.data,
      diffImage.data,
      width,
      height,
      {
        alpha: 0.5,
        includeAA: false,
        threshold: pixelThreshold,
      }
    );
 
    const percentage = (100 * mismatched) / (width * height);
    if (percentage < minDelta) {
      minDelta = percentage;
      minRawCount = mismatched;
      diff.context.putImageData(diffImage, 0, 0);
      minDiff = diff.canvas.toDataURL();
      minIndex = idx;
      isSameDimensions =
        width === imageUnderTest.width && height === imageUnderTest.height;
    }
  });
 
  tapeContext.ok(isSameDimensions, 'Image match resolution');
  tapeContext.ok(
    minDelta < mismatchTolerance,
    `[${testName}]` +
      ` Matching image - delta ${minDelta.toFixed(2)}%` +
      ` (count: ${minRawCount})`,
    {
      operator: 'imagediff',
      actual: {
        outputImage: image,
        expectedImage: baselines[minIndex],
        diffImage: minDiff,
      },
      expected: mismatchTolerance,
    }
  );
 
  if (nextCallback) {
    nextCallback();
  } else E{
    tapeContext.end();
  }
}
 
function createGarbageCollector(testContext) {
  const resources = [];
  const domElements = [];
 
  function registerResource(vtkObj, priority = 0) {
    resources.push({ vtkObj, priority });
    return vtkObj;
  }
 
  function registerDOMElement(el) {
    domElements.push(el);
    return el;
  }
 
  function releaseResources() {
    // DOM Element handling
    if (REMOVE_DOM_ELEMENTS) {
      domElements.forEach((el) => {
        if (el.parentNode) {
          el.parentNode.removeChild(el);
        }
      });
    }
    while (domElements.length) {
      domElements.pop();
    }
 
    // vtkObject handling
    resources.sort((a, b) => b.priority - a.priority);
    resources.forEach(({ vtkObj }) => {
      if (vtkObj) {
        vtkObj.delete();
      }
    });
    while (resources.length) {
      resources.pop();
    }
 
    // Test end handling
    if (testContext) {
      testContext.end();
    }
  }
 
  return {
    registerResource,
    registerDOMElement,
    releaseResources,
  };
}
 
/**
 * Convenience function to construct a test image.
 * @param {Number[]} size Dimensions of the image as an array of size 3.
 * @param {Number[]} spacing image voxel spacing.
 * @returns Constructed image as vtkImageData
 */
function createImage(size, spacing) {
  const source = vtkRTAnalyticSource.newInstance();
  source.setWholeExtent([0, size[0] - 1, 0, size[1] - 1, 0, size[2] - 1]);
  source.update();
  const image = source.getOutputData();
  image.setSpacing(spacing);
  return image;
}
 
function keepDOM() {
  REMOVE_DOM_ELEMENTS = false;
}
 
function removeDOM() {
  REMOVE_DOM_ELEMENTS = true;
}
 
function arrayEquals(a, b) {
  Iif (a.length !== b.length) {
    return false;
  }
  for (let i = 0; i < a.length; ++i) {
    if (a[i] !== b[i]) {
      return false;
    }
  }
  return true;
}
 
function objEquals(a, b) {
  const k1 = Object.keys(a).sort();
  const k2 = Object.keys(b).sort();
  Iif (!arrayEquals(k1, k2)) {
    return false;
  }
  for (let i = 0; i < k1.length; ++i) {
    Iif (a[k1[i]] !== b[k1[i]]) {
      return false;
    }
  }
  return true;
}
 
export default {
  arrayEquals,
  compareImages,
  createGarbageCollector,
  createImage,
  keepDOM,
  objEquals,
  removeDOM,
};