Best Python code snippet using ATX
barriers.js
Source:barriers.js  
...65        y: this.y + this.image_size66      };67    push();68    imageMode(CENTER);69    image(this.left_image_1, barrier_left_1.x, barrier_left_1.y, this.image_size, this.image_size);70    image(this.left_image_2, barrier_left_2.x, barrier_left_2.y, this.image_size, this.image_size);71    image(this.left_image_3, barrier_left_3.x, barrier_left_3.y, this.image_size, this.image_size);72    image(this.right_image_1, barrier_right_1.x, barrier_right_1.y, this.image_size, this.image_size);73    image(this.right_image_2, barrier_right_2.x, barrier_right_2.y, this.image_size, this.image_size);74    image(this.right_image_3, barrier_right_3.x, barrier_right_3.y, this.image_size, this.image_size);75    image(this.middle_image_1, barrier_midle_1.x, barrier_midle_1.y, this.image_size, this.image_size);76    image(this.middle_image_2, barrier_midle_2.x, barrier_midle_2.y, this.image_size, this.image_size);77    if (this.down_damaged == 0 && this.up_damaged != this.middle_damage_max) {78      image(image_barrier_bottom_edge, barrier_midle_3.x, barrier_midle_3.y, this.image_size, this.image_size);79    }80    pop();81  }82  update() {83    if(this.left_up_damaged + this.left_down_damaged >= this.left_damage_max){//Prevent damage beyond the limit.84      this.left_up_damaged = this.left_damage_max;85      this.left_down_damaged = 0;86    }87    if(this.right_up_damaged + this.right_down_damaged >= this.right_damage_max){88      this.right_up_damaged = this.right_damage_max;89      this.right_down_damaged = 0;90    }91    if(this.up_damaged + this.down_damaged >= this.middle_damage_max){92      this.up_damaged = this.middle_damage_max;...api-native-image-spec.js
Source:api-native-image-spec.js  
1'use strict'2/* eslint-disable no-unused-expressions */3const {expect} = require('chai')4const {nativeImage} = require('electron')5const path = require('path')6describe('nativeImage module', () => {7  const ImageFormat = {8    PNG: 'png',9    JPEG: 'jpeg'10  }11  const images = [12    {13      filename: 'logo.png',14      format: ImageFormat.PNG,15      hasAlphaChannel: true,16      hasDataUrl: false,17      width: 538,18      height: 19019    },20    {21      dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYlWNgAAIAAAUAAdafFs0AAAAASUVORK5CYII=',22      filename: '1x1.png',23      format: ImageFormat.PNG,24      hasAlphaChannel: true,25      hasDataUrl: true,26      height: 1,27      width: 128    },29    {30      dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVQYlWP8//8/AwMDEwMDAwMDAwAkBgMBBMzldwAAAABJRU5ErkJggg==',31      filename: '2x2.jpg',32      format: ImageFormat.JPEG,33      hasAlphaChannel: false,34      hasDataUrl: true,35      height: 2,36      width: 237    },38    {39      dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAYAAABWKLW/AAAADElEQVQYlWNgIAoAAAAnAAGZWEMnAAAAAElFTkSuQmCC',40      filename: '3x3.png',41      format: ImageFormat.PNG,42      hasAlphaChannel: true,43      hasDataUrl: true,44      height: 3,45      width: 346    }47  ]48  /**49   * @param {?string} filename50   * @returns {?string} Full path.51   */52  const getImagePathFromFilename = (filename) => {53    return (filename === null) ? null54        : path.join(__dirname, 'fixtures', 'assets', filename)55  }56  /**57   * @param {!Object} image58   * @param {Object} filters59   * @returns {boolean}60   */61  const imageMatchesTheFilters = (image, filters = null) => {62    if (filters === null) {63      return true64    }65    return Object.entries(filters)66        .every(([key, value]) => image[key] === value)67  }68  /**69   * @param {!Object} filters70   * @returns {!Array} A matching images list.71   */72  const getImages = (filters) => {73    const matchingImages = images74        .filter(i => imageMatchesTheFilters(i, filters))75    // Add `.path` property to every image.76    matchingImages77        .forEach(i => { i.path = getImagePathFromFilename(i.filename) })78    return matchingImages79  }80  /**81   * @param {!Object} filters82   * @returns {Object} A matching image if any.83   */84  const getImage = (filters) => {85    const matchingImages = getImages(filters)86    let matchingImage = null87    if (matchingImages.length > 0) {88      matchingImage = matchingImages[0]89    }90    return matchingImage91  }92  describe('createEmpty()', () => {93    it('returns an empty image', () => {94      const empty = nativeImage.createEmpty()95      expect(empty.isEmpty())96      expect(empty.getAspectRatio()).to.equal(1)97      expect(empty.toDataURL()).to.equal('data:image/png;base64,')98      expect(empty.toDataURL({scaleFactor: 2.0})).to.equal('data:image/png;base64,')99      expect(empty.getSize()).to.deep.equal({width: 0, height: 0})100      expect(empty.getBitmap()).to.be.empty101      expect(empty.getBitmap({scaleFactor: 2.0})).to.be.empty102      expect(empty.toBitmap()).to.be.empty103      expect(empty.toBitmap({scaleFactor: 2.0})).to.be.empty104      expect(empty.toJPEG(100)).to.be.empty105      expect(empty.toPNG()).to.be.empty106      expect(empty.toPNG({scaleFactor: 2.0})).to.be.empty107      if (process.platform === 'darwin') {108        expect(empty.getNativeHandle()).to.be.empty109      }110    })111  })112  describe('createFromBuffer(buffer, scaleFactor)', () => {113    it('returns an empty image when the buffer is empty', () => {114      expect(nativeImage.createFromBuffer(Buffer.from([])).isEmpty())115    })116    it('returns an image created from the given buffer', () => {117      const imageA = nativeImage.createFromPath(path.join(__dirname, 'fixtures', 'assets', 'logo.png'))118      const imageB = nativeImage.createFromBuffer(imageA.toPNG())119      expect(imageB.getSize()).to.deep.equal({width: 538, height: 190})120      expect(imageA.toBitmap().equals(imageB.toBitmap())).to.be.true121      const imageC = nativeImage.createFromBuffer(imageA.toJPEG(100))122      expect(imageC.getSize()).to.deep.equal({width: 538, height: 190})123      const imageD = nativeImage.createFromBuffer(imageA.toBitmap(),124        {width: 538, height: 190})125      expect(imageD.getSize()).to.deep.equal({width: 538, height: 190})126      const imageE = nativeImage.createFromBuffer(imageA.toBitmap(),127        {width: 100, height: 200})128      expect(imageE.getSize()).to.deep.equal({width: 100, height: 200})129      const imageF = nativeImage.createFromBuffer(imageA.toBitmap())130      expect(imageF.isEmpty())131      const imageG = nativeImage.createFromBuffer(imageA.toPNG(),132        {width: 100, height: 200})133      expect(imageG.getSize()).to.deep.equal({width: 538, height: 190})134      const imageH = nativeImage.createFromBuffer(imageA.toJPEG(100),135        {width: 100, height: 200})136      expect(imageH.getSize()).to.deep.equal({width: 538, height: 190})137      const imageI = nativeImage.createFromBuffer(imageA.toBitmap(),138        {width: 538, height: 190, scaleFactor: 2.0})139      expect(imageI.getSize()).to.deep.equal({width: 269, height: 95})140    })141  })142  describe('createFromDataURL(dataURL)', () => {143    it('returns an empty image from the empty string', () => {144      expect(nativeImage.createFromDataURL('').isEmpty())145    })146    it('returns an image created from the given string', () => {147      const imagesData = getImages({hasDataUrl: true})148      for (const imageData of imagesData) {149        const imageFromPath = nativeImage.createFromPath(imageData.path)150        const imageFromDataUrl = nativeImage.createFromDataURL(imageData.dataUrl)151        expect(imageFromDataUrl.isEmpty())152        expect(imageFromDataUrl.getSize()).to.deep.equal(imageFromPath.getSize())153        expect(imageFromDataUrl.toBitmap()).to.satisfy(154            bitmap => imageFromPath.toBitmap().equals(bitmap))155        expect(imageFromDataUrl.toDataURL()).to.equal(imageFromPath.toDataURL())156      }157    })158  })159  describe('toDataURL()', () => {160    it('returns a PNG data URL', () => {161      const imagesData = getImages({hasDataUrl: true})162      for (const imageData of imagesData) {163        const imageFromPath = nativeImage.createFromPath(imageData.path)164        const scaleFactors = [1.0, 2.0]165        for (const scaleFactor of scaleFactors) {166          expect(imageFromPath.toDataURL({scaleFactor})).to.equal(imageData.dataUrl)167        }168      }169    })170    it('returns a data URL at 1x scale factor by default', () => {171      const imageData = getImage({filename: 'logo.png'})172      const image = nativeImage.createFromPath(imageData.path)173      const imageOne = nativeImage.createFromBuffer(image.toPNG(), {174        width: image.getSize().width,175        height: image.getSize().height,176        scaleFactor: 2.0177      })178      expect(imageOne.getSize()).to.deep.equal(179          {width: imageData.width / 2, height: imageData.height / 2})180      const imageTwo = nativeImage.createFromDataURL(imageOne.toDataURL())181      expect(imageTwo.getSize()).to.deep.equal(182          {width: imageData.width, height: imageData.height})183      expect(imageOne.toBitmap().equals(imageTwo.toBitmap())).to.be.true184    })185    it('supports a scale factor', () => {186      const imageData = getImage({filename: 'logo.png'})187      const image = nativeImage.createFromPath(imageData.path)188      const expectedSize = {width: imageData.width, height: imageData.height}189      const imageFromDataUrlOne = nativeImage.createFromDataURL(190          image.toDataURL({scaleFactor: 1.0}))191      expect(imageFromDataUrlOne.getSize()).to.deep.equal(expectedSize)192      const imageFromDataUrlTwo = nativeImage.createFromDataURL(193          image.toDataURL({scaleFactor: 2.0}))194      expect(imageFromDataUrlTwo.getSize()).to.deep.equal(expectedSize)195    })196  })197  describe('toPNG()', () => {198    it('returns a buffer at 1x scale factor by default', () => {199      const imageData = getImage({filename: 'logo.png'})200      const imageA = nativeImage.createFromPath(imageData.path)201      const imageB = nativeImage.createFromBuffer(imageA.toPNG(), {202        width: imageA.getSize().width,203        height: imageA.getSize().height,204        scaleFactor: 2.0205      })206      expect(imageB.getSize()).to.deep.equal(207          {width: imageData.width / 2, height: imageData.height / 2})208      const imageC = nativeImage.createFromBuffer(imageB.toPNG())209      expect(imageC.getSize()).to.deep.equal(210          {width: imageData.width, height: imageData.height})211      expect(imageB.toBitmap().equals(imageC.toBitmap())).to.be.true212    })213    it('supports a scale factor', () => {214      const imageData = getImage({filename: 'logo.png'})215      const image = nativeImage.createFromPath(imageData.path)216      const imageFromBufferOne = nativeImage.createFromBuffer(217          image.toPNG({scaleFactor: 1.0}))218      expect(imageFromBufferOne.getSize()).to.deep.equal(219          {width: imageData.width, height: imageData.height})220      const imageFromBufferTwo = nativeImage.createFromBuffer(221          image.toPNG({scaleFactor: 2.0}), {scaleFactor: 2.0})222      expect(imageFromBufferTwo.getSize()).to.deep.equal(223          {width: imageData.width / 2, height: imageData.height / 2})224    })225  })226  describe('createFromPath(path)', () => {227    it('returns an empty image for invalid paths', () => {228      expect(nativeImage.createFromPath('').isEmpty())229      expect(nativeImage.createFromPath('does-not-exist.png').isEmpty())230      expect(nativeImage.createFromPath('does-not-exist.ico').isEmpty())231      expect(nativeImage.createFromPath(__dirname).isEmpty())232      expect(nativeImage.createFromPath(__filename).isEmpty())233    })234    it('loads images from paths relative to the current working directory', () => {235      const imagePath = `.${path.sep}${path.join('spec', 'fixtures', 'assets', 'logo.png')}`236      const image = nativeImage.createFromPath(imagePath)237      expect(image.isEmpty()).to.be.false238      expect(image.getSize()).to.deep.equal({width: 538, height: 190})239    })240    it('loads images from paths with `.` segments', () => {241      const imagePath = `${path.join(__dirname, 'fixtures')}${path.sep}.${path.sep}${path.join('assets', 'logo.png')}`242      const image = nativeImage.createFromPath(imagePath)243      expect(image.isEmpty()).to.be.false244      expect(image.getSize()).to.deep.equal({width: 538, height: 190})245    })246    it('loads images from paths with `..` segments', () => {247      const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`248      const image = nativeImage.createFromPath(imagePath)249      expect(image.isEmpty()).to.be.false250      expect(image.getSize()).to.deep.equal({width: 538, height: 190})251    })252    it('Gets an NSImage pointer on macOS', function () {253      if (process.platform !== 'darwin') {254        // FIXME(alexeykuzmin): Skip the test.255        // this.skip()256        return257      }258      const imagePath = `${path.join(__dirname, 'fixtures', 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`259      const image = nativeImage.createFromPath(imagePath)260      const nsimage = image.getNativeHandle()261      expect(nsimage).to.have.lengthOf(8)262      // If all bytes are null, that's Bad263      const allBytesAreNotNull = nsimage.reduce((acc, x) => acc || (x !== 0), false)264      expect(allBytesAreNotNull)265    })266    it('loads images from .ico files on Windows', function () {267      if (process.platform !== 'win32') {268        // FIXME(alexeykuzmin): Skip the test.269        // this.skip()270        return271      }272      const imagePath = path.join(__dirname, 'fixtures', 'assets', 'icon.ico')273      const image = nativeImage.createFromPath(imagePath)274      expect(image.isEmpty()).to.be.false275      expect(image.getSize()).to.deep.equal({width: 256, height: 256})276    })277  })278  describe('createFromNamedImage(name)', () => {279    it('returns empty for invalid options', () => {280      const image = nativeImage.createFromNamedImage('totally_not_real')281      expect(image.isEmpty())282    })283    it('returns empty on non-darwin platforms', function () {284      if (process.platform === 'darwin') {285        // FIXME(alexeykuzmin): Skip the test.286        // this.skip()287        return288      }289      const image = nativeImage.createFromNamedImage('NSActionTemplate')290      expect(image.isEmpty())291    })292    it('returns a valid image on darwin', function () {293      if (process.platform !== 'darwin') {294        // FIXME(alexeykuzmin): Skip the test.295        // this.skip()296        return297      }298      const image = nativeImage.createFromNamedImage('NSActionTemplate')299      expect(image.isEmpty()).to.be.false300    })301    it('returns allows an HSL shift for a valid image on darwin', function () {302      if (process.platform !== 'darwin') {303        // FIXME(alexeykuzmin): Skip the test.304        // this.skip()305        return306      }307      const image = nativeImage.createFromNamedImage('NSActionTemplate', [0.5, 0.2, 0.8])308      expect(image.isEmpty()).to.be.false309    })310  })311  describe('resize(options)', () => {312    it('returns a resized image', () => {313      const image = nativeImage.createFromPath(path.join(__dirname, 'fixtures', 'assets', 'logo.png'))314      for (const [resizeTo, expectedSize] of new Map([315        [{}, {width: 538, height: 190}],316        [{width: 269}, {width: 269, height: 95}],317        [{width: 600}, {width: 600, height: 212}],318        [{height: 95}, {width: 269, height: 95}],319        [{height: 200}, {width: 566, height: 200}],320        [{width: 80, height: 65}, {width: 80, height: 65}],321        [{width: 600, height: 200}, {width: 600, height: 200}],322        [{width: 0, height: 0}, {width: 0, height: 0}],323        [{width: -1, height: -1}, {width: 0, height: 0}]324      ])) {325        const actualSize = image.resize(resizeTo).getSize()326        expect(actualSize).to.deep.equal(expectedSize)327      }328    })329    it('returns an empty image when called on an empty image', () => {330      expect(nativeImage.createEmpty().resize({width: 1, height: 1}).isEmpty())331      expect(nativeImage.createEmpty().resize({width: 0, height: 0}).isEmpty())332    })333    it('supports a quality option', () => {334      const image = nativeImage.createFromPath(path.join(__dirname, 'fixtures', 'assets', 'logo.png'))335      const good = image.resize({width: 100, height: 100, quality: 'good'})336      const better = image.resize({width: 100, height: 100, quality: 'better'})337      const best = image.resize({width: 100, height: 100, quality: 'best'})338      expect(good.toPNG()).to.have.lengthOf.at.most(better.toPNG().length)339      expect(better.toPNG()).to.have.lengthOf.below(best.toPNG().length)340    })341  })342  describe('crop(bounds)', () => {343    it('returns an empty image when called on an empty image', () => {344      expect(nativeImage.createEmpty().crop({width: 1, height: 2, x: 0, y: 0}).isEmpty())345      expect(nativeImage.createEmpty().crop({width: 0, height: 0, x: 0, y: 0}).isEmpty())346    })347    it('returns an empty image when the bounds are invalid', () => {348      const image = nativeImage.createFromPath(path.join(__dirname, 'fixtures', 'assets', 'logo.png'))349      expect(image.crop({width: 0, height: 0, x: 0, y: 0}).isEmpty())350      expect(image.crop({width: -1, height: 10, x: 0, y: 0}).isEmpty())351      expect(image.crop({width: 10, height: -35, x: 0, y: 0}).isEmpty())352      expect(image.crop({width: 100, height: 100, x: 1000, y: 1000}).isEmpty())353    })354    it('returns a cropped image', () => {355      const image = nativeImage.createFromPath(path.join(__dirname, 'fixtures', 'assets', 'logo.png'))356      const cropA = image.crop({width: 25, height: 64, x: 0, y: 0})357      const cropB = image.crop({width: 25, height: 64, x: 30, y: 40})358      expect(cropA.getSize()).to.deep.equal({width: 25, height: 64})359      expect(cropB.getSize()).to.deep.equal({width: 25, height: 64})360      expect(cropA.toPNG().equals(cropB.toPNG())).to.be.false361    })362  })363  describe('getAspectRatio()', () => {364    it('returns an aspect ratio of an empty image', () => {365      expect(nativeImage.createEmpty().getAspectRatio()).to.equal(1.0)366    })367    it('returns an aspect ratio of an image', () => {368      const imageData = getImage({filename: 'logo.png'})369      // imageData.width / imageData.height = 2.831578947368421370      const expectedAspectRatio = 2.8315789699554443371      const image = nativeImage.createFromPath(imageData.path)372      expect(image.getAspectRatio()).to.equal(expectedAspectRatio)373    })374  })375  describe('addRepresentation()', () => {376    it('supports adding a buffer representation for a scale factor', () => {377      const image = nativeImage.createEmpty()378      const imageDataOne = getImage({width: 1, height: 1})379      image.addRepresentation({380        scaleFactor: 1.0,381        buffer: nativeImage.createFromPath(imageDataOne.path).toPNG()382      })383      const imageDataTwo = getImage({width: 2, height: 2})384      image.addRepresentation({385        scaleFactor: 2.0,386        buffer: nativeImage.createFromPath(imageDataTwo.path).toPNG()387      })388      const imageDataThree = getImage({width: 3, height: 3})389      image.addRepresentation({390        scaleFactor: 3.0,391        buffer: nativeImage.createFromPath(imageDataThree.path).toPNG()392      })393      image.addRepresentation({394        scaleFactor: 4.0,395        buffer: 'invalid'396      })397      expect(image.isEmpty()).to.be.false398      expect(image.getSize()).to.deep.equal({width: 1, height: 1})399      expect(image.toDataURL({scaleFactor: 1.0})).to.equal(imageDataOne.dataUrl)400      expect(image.toDataURL({scaleFactor: 2.0})).to.equal(imageDataTwo.dataUrl)401      expect(image.toDataURL({scaleFactor: 3.0})).to.equal(imageDataThree.dataUrl)402      expect(image.toDataURL({scaleFactor: 4.0})).to.equal(imageDataThree.dataUrl)403    })404    it('supports adding a data URL representation for a scale factor', () => {405      const image = nativeImage.createEmpty()406      const imageDataOne = getImage({width: 1, height: 1})407      image.addRepresentation({408        scaleFactor: 1.0,409        dataURL: imageDataOne.dataUrl410      })411      const imageDataTwo = getImage({width: 2, height: 2})412      image.addRepresentation({413        scaleFactor: 2.0,414        dataURL: imageDataTwo.dataUrl415      })416      const imageDataThree = getImage({width: 3, height: 3})417      image.addRepresentation({418        scaleFactor: 3.0,419        dataURL: imageDataThree.dataUrl420      })421      image.addRepresentation({422        scaleFactor: 4.0,423        dataURL: 'invalid'424      })425      expect(image.isEmpty()).to.be.false426      expect(image.getSize()).to.deep.equal({width: 1, height: 1})427      expect(image.toDataURL({scaleFactor: 1.0})).to.equal(imageDataOne.dataUrl)428      expect(image.toDataURL({scaleFactor: 2.0})).to.equal(imageDataTwo.dataUrl)429      expect(image.toDataURL({scaleFactor: 3.0})).to.equal(imageDataThree.dataUrl)430      expect(image.toDataURL({scaleFactor: 4.0})).to.equal(imageDataThree.dataUrl)431    })432    it('supports adding a representation to an existing image', () => {433      const imageDataOne = getImage({width: 1, height: 1})434      const image = nativeImage.createFromPath(imageDataOne.path)435      const imageDataTwo = getImage({width: 2, height: 2})436      image.addRepresentation({437        scaleFactor: 2.0,438        dataURL: imageDataTwo.dataUrl439      })440      const imageDataThree = getImage({width: 3, height: 3})441      image.addRepresentation({442        scaleFactor: 2.0,443        dataURL: imageDataThree.dataUrl444      })445      expect(image.toDataURL({scaleFactor: 1.0})).to.equal(imageDataOne.dataUrl)446      expect(image.toDataURL({scaleFactor: 2.0})).to.equal(imageDataTwo.dataUrl)447    })448  })...test_images.py
Source:test_images.py  
1import unittest2import tkinter3from test import support4from tkinter.test.support import AbstractTkTest, AbstractDefaultRootTest, requires_tcl5support.requires('gui')6class MiscTest(AbstractTkTest, unittest.TestCase):7    def test_image_types(self):8        image_types = self.root.image_types()9        self.assertIsInstance(image_types, tuple)10        self.assertIn('photo', image_types)11        self.assertIn('bitmap', image_types)12    def test_image_names(self):13        image_names = self.root.image_names()14        self.assertIsInstance(image_names, tuple)15class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase):16    def test_image_types(self):17        self.assertRaises(RuntimeError, tkinter.image_types)18        root = tkinter.Tk()19        image_types = tkinter.image_types()20        self.assertIsInstance(image_types, tuple)21        self.assertIn('photo', image_types)22        self.assertIn('bitmap', image_types)23        root.destroy()24        tkinter.NoDefaultRoot()25        self.assertRaises(RuntimeError, tkinter.image_types)26    def test_image_names(self):27        self.assertRaises(RuntimeError, tkinter.image_names)28        root = tkinter.Tk()29        image_names = tkinter.image_names()30        self.assertIsInstance(image_names, tuple)31        root.destroy()32        tkinter.NoDefaultRoot()33        self.assertRaises(RuntimeError, tkinter.image_names)34    def test_image_create_bitmap(self):35        self.assertRaises(RuntimeError, tkinter.BitmapImage)36        root = tkinter.Tk()37        image = tkinter.BitmapImage()38        self.assertIn(image.name, tkinter.image_names())39        root.destroy()40        tkinter.NoDefaultRoot()41        self.assertRaises(RuntimeError, tkinter.BitmapImage)42    def test_image_create_photo(self):43        self.assertRaises(RuntimeError, tkinter.PhotoImage)44        root = tkinter.Tk()45        image = tkinter.PhotoImage()46        self.assertIn(image.name, tkinter.image_names())47        root.destroy()48        tkinter.NoDefaultRoot()49        self.assertRaises(RuntimeError, tkinter.PhotoImage)50class BitmapImageTest(AbstractTkTest, unittest.TestCase):51    @classmethod52    def setUpClass(cls):53        AbstractTkTest.setUpClass.__func__(cls)54        cls.testfile = support.findfile('python.xbm', subdir='imghdrdata')55    def test_create_from_file(self):56        image = tkinter.BitmapImage('::img::test', master=self.root,57                                    foreground='yellow', background='blue',58                                    file=self.testfile)59        self.assertEqual(str(image), '::img::test')60        self.assertEqual(image.type(), 'bitmap')61        self.assertEqual(image.width(), 16)62        self.assertEqual(image.height(), 16)63        self.assertIn('::img::test', self.root.image_names())64        del image65        self.assertNotIn('::img::test', self.root.image_names())66    def test_create_from_data(self):67        with open(self.testfile, 'rb') as f:68            data = f.read()69        image = tkinter.BitmapImage('::img::test', master=self.root,70                                    foreground='yellow', background='blue',71                                    data=data)72        self.assertEqual(str(image), '::img::test')73        self.assertEqual(image.type(), 'bitmap')74        self.assertEqual(image.width(), 16)75        self.assertEqual(image.height(), 16)76        self.assertIn('::img::test', self.root.image_names())77        del image78        self.assertNotIn('::img::test', self.root.image_names())79    def assertEqualStrList(self, actual, expected):80        self.assertIsInstance(actual, str)81        self.assertEqual(self.root.splitlist(actual), expected)82    def test_configure_data(self):83        image = tkinter.BitmapImage('::img::test', master=self.root)84        self.assertEqual(image['data'], '-data {} {} {} {}')85        with open(self.testfile, 'rb') as f:86            data = f.read()87        image.configure(data=data)88        self.assertEqualStrList(image['data'],89                                ('-data', '', '', '', data.decode('ascii')))90        self.assertEqual(image.width(), 16)91        self.assertEqual(image.height(), 16)92        self.assertEqual(image['maskdata'], '-maskdata {} {} {} {}')93        image.configure(maskdata=data)94        self.assertEqualStrList(image['maskdata'],95                                ('-maskdata', '', '', '', data.decode('ascii')))96    def test_configure_file(self):97        image = tkinter.BitmapImage('::img::test', master=self.root)98        self.assertEqual(image['file'], '-file {} {} {} {}')99        image.configure(file=self.testfile)100        self.assertEqualStrList(image['file'],101                                ('-file', '', '', '',self.testfile))102        self.assertEqual(image.width(), 16)103        self.assertEqual(image.height(), 16)104        self.assertEqual(image['maskfile'], '-maskfile {} {} {} {}')105        image.configure(maskfile=self.testfile)106        self.assertEqualStrList(image['maskfile'],107                                ('-maskfile', '', '', '', self.testfile))108    def test_configure_background(self):109        image = tkinter.BitmapImage('::img::test', master=self.root)110        self.assertEqual(image['background'], '-background {} {} {} {}')111        image.configure(background='blue')112        self.assertEqual(image['background'], '-background {} {} {} blue')113    def test_configure_foreground(self):114        image = tkinter.BitmapImage('::img::test', master=self.root)115        self.assertEqual(image['foreground'],116                         '-foreground {} {} #000000 #000000')117        image.configure(foreground='yellow')118        self.assertEqual(image['foreground'],119                         '-foreground {} {} #000000 yellow')120class PhotoImageTest(AbstractTkTest, unittest.TestCase):121    @classmethod122    def setUpClass(cls):123        AbstractTkTest.setUpClass.__func__(cls)124        cls.testfile = support.findfile('python.gif', subdir='imghdrdata')125    def create(self):126        return tkinter.PhotoImage('::img::test', master=self.root,127                                  file=self.testfile)128    def colorlist(self, *args):129        if tkinter.TkVersion >= 8.6 and self.wantobjects:130            return args131        else:132            return tkinter._join(args)133    def check_create_from_file(self, ext):134        testfile = support.findfile('python.' + ext, subdir='imghdrdata')135        image = tkinter.PhotoImage('::img::test', master=self.root,136                                   file=testfile)137        self.assertEqual(str(image), '::img::test')138        self.assertEqual(image.type(), 'photo')139        self.assertEqual(image.width(), 16)140        self.assertEqual(image.height(), 16)141        self.assertEqual(image['data'], '')142        self.assertEqual(image['file'], testfile)143        self.assertIn('::img::test', self.root.image_names())144        del image145        self.assertNotIn('::img::test', self.root.image_names())146    def check_create_from_data(self, ext):147        testfile = support.findfile('python.' + ext, subdir='imghdrdata')148        with open(testfile, 'rb') as f:149            data = f.read()150        image = tkinter.PhotoImage('::img::test', master=self.root,151                                   data=data)152        self.assertEqual(str(image), '::img::test')153        self.assertEqual(image.type(), 'photo')154        self.assertEqual(image.width(), 16)155        self.assertEqual(image.height(), 16)156        self.assertEqual(image['data'], data if self.wantobjects157                                        else data.decode('latin1'))158        self.assertEqual(image['file'], '')159        self.assertIn('::img::test', self.root.image_names())160        del image161        self.assertNotIn('::img::test', self.root.image_names())162    def test_create_from_ppm_file(self):163        self.check_create_from_file('ppm')164    def test_create_from_ppm_data(self):165        self.check_create_from_data('ppm')166    def test_create_from_pgm_file(self):167        self.check_create_from_file('pgm')168    def test_create_from_pgm_data(self):169        self.check_create_from_data('pgm')170    def test_create_from_gif_file(self):171        self.check_create_from_file('gif')172    def test_create_from_gif_data(self):173        self.check_create_from_data('gif')174    @requires_tcl(8, 6)175    def test_create_from_png_file(self):176        self.check_create_from_file('png')177    @requires_tcl(8, 6)178    def test_create_from_png_data(self):179        self.check_create_from_data('png')180    def test_configure_data(self):181        image = tkinter.PhotoImage('::img::test', master=self.root)182        self.assertEqual(image['data'], '')183        with open(self.testfile, 'rb') as f:184            data = f.read()185        image.configure(data=data)186        self.assertEqual(image['data'], data if self.wantobjects187                                        else data.decode('latin1'))188        self.assertEqual(image.width(), 16)189        self.assertEqual(image.height(), 16)190    def test_configure_format(self):191        image = tkinter.PhotoImage('::img::test', master=self.root)192        self.assertEqual(image['format'], '')193        image.configure(file=self.testfile, format='gif')194        self.assertEqual(image['format'], ('gif',) if self.wantobjects195                                          else 'gif')196        self.assertEqual(image.width(), 16)197        self.assertEqual(image.height(), 16)198    def test_configure_file(self):199        image = tkinter.PhotoImage('::img::test', master=self.root)200        self.assertEqual(image['file'], '')201        image.configure(file=self.testfile)202        self.assertEqual(image['file'], self.testfile)203        self.assertEqual(image.width(), 16)204        self.assertEqual(image.height(), 16)205    def test_configure_gamma(self):206        image = tkinter.PhotoImage('::img::test', master=self.root)207        self.assertEqual(image['gamma'], '1.0')208        image.configure(gamma=2.0)209        self.assertEqual(image['gamma'], '2.0')210    def test_configure_width_height(self):211        image = tkinter.PhotoImage('::img::test', master=self.root)212        self.assertEqual(image['width'], '0')213        self.assertEqual(image['height'], '0')214        image.configure(width=20)215        image.configure(height=10)216        self.assertEqual(image['width'], '20')217        self.assertEqual(image['height'], '10')218        self.assertEqual(image.width(), 20)219        self.assertEqual(image.height(), 10)220    def test_configure_palette(self):221        image = tkinter.PhotoImage('::img::test', master=self.root)222        self.assertEqual(image['palette'], '')223        image.configure(palette=256)224        self.assertEqual(image['palette'], '256')225        image.configure(palette='3/4/2')226        self.assertEqual(image['palette'], '3/4/2')227    def test_blank(self):228        image = self.create()229        image.blank()230        self.assertEqual(image.width(), 16)231        self.assertEqual(image.height(), 16)232        self.assertEqual(image.get(4, 6), self.colorlist(0, 0, 0))233    def test_copy(self):234        image = self.create()235        image2 = image.copy()236        self.assertEqual(image2.width(), 16)237        self.assertEqual(image2.height(), 16)238        self.assertEqual(image.get(4, 6), image.get(4, 6))239    def test_subsample(self):240        image = self.create()241        image2 = image.subsample(2, 3)242        self.assertEqual(image2.width(), 8)243        self.assertEqual(image2.height(), 6)244        self.assertEqual(image2.get(2, 2), image.get(4, 6))245        image2 = image.subsample(2)246        self.assertEqual(image2.width(), 8)247        self.assertEqual(image2.height(), 8)248        self.assertEqual(image2.get(2, 3), image.get(4, 6))249    def test_zoom(self):250        image = self.create()251        image2 = image.zoom(2, 3)252        self.assertEqual(image2.width(), 32)253        self.assertEqual(image2.height(), 48)254        self.assertEqual(image2.get(8, 18), image.get(4, 6))255        self.assertEqual(image2.get(9, 20), image.get(4, 6))256        image2 = image.zoom(2)257        self.assertEqual(image2.width(), 32)258        self.assertEqual(image2.height(), 32)259        self.assertEqual(image2.get(8, 12), image.get(4, 6))260        self.assertEqual(image2.get(9, 13), image.get(4, 6))261    def test_put(self):262        image = self.create()263        image.put('{red green} {blue yellow}', to=(4, 6))264        self.assertEqual(image.get(4, 6), self.colorlist(255, 0, 0))265        self.assertEqual(image.get(5, 6),266                         self.colorlist(0, 128 if tkinter.TkVersion >= 8.6267                                           else 255, 0))268        self.assertEqual(image.get(4, 7), self.colorlist(0, 0, 255))269        self.assertEqual(image.get(5, 7), self.colorlist(255, 255, 0))270        image.put((('#f00', '#00ff00'), ('#000000fff', '#ffffffff0000')))271        self.assertEqual(image.get(0, 0), self.colorlist(255, 0, 0))272        self.assertEqual(image.get(1, 0), self.colorlist(0, 255, 0))273        self.assertEqual(image.get(0, 1), self.colorlist(0, 0, 255))274        self.assertEqual(image.get(1, 1), self.colorlist(255, 255, 0))275    def test_get(self):276        image = self.create()277        self.assertEqual(image.get(4, 6), self.colorlist(62, 116, 162))278        self.assertEqual(image.get(0, 0), self.colorlist(0, 0, 0))279        self.assertEqual(image.get(15, 15), self.colorlist(0, 0, 0))280        self.assertRaises(tkinter.TclError, image.get, -1, 0)281        self.assertRaises(tkinter.TclError, image.get, 0, -1)282        self.assertRaises(tkinter.TclError, image.get, 16, 15)283        self.assertRaises(tkinter.TclError, image.get, 15, 16)284    def test_write(self):285        image = self.create()286        self.addCleanup(support.unlink, support.TESTFN)287        image.write(support.TESTFN)288        image2 = tkinter.PhotoImage('::img::test2', master=self.root,289                                    format='ppm',290                                    file=support.TESTFN)291        self.assertEqual(str(image2), '::img::test2')292        self.assertEqual(image2.type(), 'photo')293        self.assertEqual(image2.width(), 16)294        self.assertEqual(image2.height(), 16)295        self.assertEqual(image2.get(0, 0), image.get(0, 0))296        self.assertEqual(image2.get(15, 8), image.get(15, 8))297        image.write(support.TESTFN, format='gif', from_coords=(4, 6, 6, 9))298        image3 = tkinter.PhotoImage('::img::test3', master=self.root,299                                    format='gif',300                                    file=support.TESTFN)301        self.assertEqual(str(image3), '::img::test3')302        self.assertEqual(image3.type(), 'photo')303        self.assertEqual(image3.width(), 2)304        self.assertEqual(image3.height(), 3)305        self.assertEqual(image3.get(0, 0), image.get(4, 6))306        self.assertEqual(image3.get(1, 2), image.get(5, 8))307    def test_transparency(self):308        image = self.create()309        self.assertEqual(image.transparency_get(0, 0), True)310        self.assertEqual(image.transparency_get(4, 6), False)311        image.transparency_set(4, 6, True)312        self.assertEqual(image.transparency_get(4, 6), True)313        image.transparency_set(4, 6, False)314        self.assertEqual(image.transparency_get(4, 6), False)315tests_gui = (MiscTest, DefaultRootTest, BitmapImageTest, PhotoImageTest,)316if __name__ == "__main__":...ImageDiffSpec.js
Source:ImageDiffSpec.js  
1var2  //TODO can roll isNode up into a function if checks get longer3  isNode    = typeof module !== 'undefined',4  Canvas    = isNode && require('canvas'),5  imagediff = imagediff || require('../js/imagediff.js');6describe('ImageUtils', function() {7  var8    OBJECT            = 'object',9    TYPE_CANVAS       = isNode ? '[object Canvas]' : '[object HTMLCanvasElement]',10    E_TYPE            = { name : 'ImageTypeError', message : 'Submitted object was not an image.' };11  function getContext () {12    var13      canvas = imagediff.createCanvas(),14      context = canvas.getContext('2d');15    return context;16  }17  function newImage () {18    return isNode ? new Canvas.Image() : new Image();19  }20  function toImageDiffEqual (expected) {21    var22      expectedData = expected.data,23      actualData = this.actual.data;24    this.message = function () {25      var26        length = Math.min(expectedData.length, actualData.length),27        examples = '',28        count = 0,29        i;30      for (i = 0; i < length; i++) {31        if (expectedData[i] !== actualData[i]) {32          count++;33          if (count < 10) {34            examples += (examples ? ', ' : '') + 'Expected '+expectedData[i]+' to equal '+actualData[i]+' at '+i;35          }36        }37      }38      return 'Differed in ' + count + ' places. ' + examples;39    }40    return imagediff.equal(this.actual, expected);41  }42  // Creation Testing43  describe('Creation', function () {44    it('should create a canvas', function () {45      var46        canvas = imagediff.createCanvas();47      expect(typeof canvas).toEqual(OBJECT);48      expect(Object.prototype.toString.apply(canvas)).toEqual(TYPE_CANVAS);49    });50    it('should create a canvas with dimensions', function () {51      var52        canvas = imagediff.createCanvas(10, 20);53      expect(typeof canvas).toEqual(OBJECT);54      expect(Object.prototype.toString.apply(canvas)).toEqual(TYPE_CANVAS);55      expect(canvas.width).toEqual(10);56      expect(canvas.height).toEqual(20);57    });58    it('should create an imagedata object', function () {59      var60        imageData = imagediff.createImageData(10, 10);61      expect(typeof imageData).toEqual(OBJECT);62      expect(imageData.width).toBeDefined();63      expect(imageData.height).toBeDefined();64      expect(imageData.data).toBeDefined();65    });66  });67  // Types Testing68  describe('Types', function () {69    // Checking70    describe('Checking', function () {71      var72        image = newImage(),73        canvas = imagediff.createCanvas(),74        context = canvas.getContext('2d'),75        imageData = context.createImageData(30, 30);76      function testType (type, object) {77        return function () {78          expect(imagediff[type](null)).toEqual(false);79          expect(imagediff[type]('')).toEqual(false);80          expect(imagediff[type]({})).toEqual(false);81          expect(imagediff[type](object)).toEqual(true);82        };83      }84      it('should check Image type',     testType('isImage', image));85      it('should check Canvas type',    testType('isCanvas', canvas));86      it('should check 2DContext type', testType('isContext', context));87      it('should check ImageData type', testType('isImageData', imageData));88      it('should check for any of the image types', function () {89        expect(imagediff.isImageType(null)).toEqual(false);90        expect(imagediff.isImageType('')).toEqual(false);91        expect(imagediff.isImageType({})).toEqual(false);92        expect(imagediff.isImageType(image)).toEqual(true);93        expect(imagediff.isImageType(canvas)).toEqual(true);94        expect(imagediff.isImageType(context)).toEqual(true);95        expect(imagediff.isImageType(imageData)).toEqual(true);96      });97    });98    // Conversion99    describe('Conversion', function () {100      var101        image = newImage(),102        imageData;103      beforeEach(function () {104        this.addMatchers({105          toBeImageData : function () {106            return imagediff.isImageData(this.actual);107          },108          toImageDiffEqual : toImageDiffEqual109        });110      });111      it('should convert Image to ImageData', function () {112        var113          result;114        image.src = 'images/checkmark.png';115        waitsFor(function () {116          return image.complete;117        }, 'image not loaded.', 1000);118        runs(function () {119          var120            canvas = imagediff.createCanvas(image.width, image.height),121            context = canvas.getContext('2d');122          context.drawImage(image, 0, 0);123          imageData = context.getImageData(0, 0, image.width, image.height);124          result = imagediff.toImageData(image);125          expect(result).toBeImageData();126          expect(result).toImageDiffEqual(imageData);127        });128      });129      it('should convert Canvas to ImageData', function () {130        var131          canvas = imagediff.createCanvas(),132          context = canvas.getContext('2d'),133          result;134        canvas.height = image.height;135        canvas.width = image.width;136        context.drawImage(image, 0, 0);137        result = imagediff.toImageData(canvas);138        expect(result).toBeImageData();139        expect(result).toImageDiffEqual(imageData);140      });141      it('should convert Context to ImageData', function () {142        var143          canvas = imagediff.createCanvas(),144          context = canvas.getContext('2d'),145          result = imagediff.toImageData(context);146        expect(result).toBeImageData();147      });148      it('should copy ImageData to new ImageData', function () {149        result = imagediff.toImageData(imageData);150        expect(result).toBeImageData();151        expect(result).toImageDiffEqual(imageData);152        expect(imageData !== result).toBeTruthy();153      });154      it('should fail on non-ImageType', function () {155        expect(function () { imagediff.toImageData() }).toThrow(E_TYPE);156        expect(function () { imagediff.toImageData('') }).toThrow(E_TYPE);157        expect(function () { imagediff.toImageData({}) }).toThrow(E_TYPE);158      });159    });160  });161  // Equals Testing162  describe('Equals', function () {163    var context, a, b;164    beforeEach(function () {165      context = getContext();166      a = context.createImageData(2, 2);167    });168    it('should not be equal for equal ImageData', function () {169      b = context.createImageData(2, 2);170      expect(imagediff.equal(a, b)).toEqual(true);171    });172    it('should not be equal when one ImageData is of different width', function () {173      b = context.createImageData(3, 2);174      expect(imagediff.equal(a, b)).toEqual(false);175      expect(imagediff.equal(b, a)).toEqual(false);176    });177    it('should not be equal when one ImageData is of different height', function () {178      b = context.createImageData(2, 3);179      expect(imagediff.equal(a, b)).toEqual(false);180      expect(imagediff.equal(b, a)).toEqual(false);181    });182    it('should not be equal when one ImageData data array differs', function () {183      b = context.createImageData(2, 2);184      b.data[0] = 100;185      expect(imagediff.equal(a, b)).toEqual(false);186    });187    it('should be equal within optional tolerance', function () {188      b = context.createImageData(2, 2);189      b.data[0] = 100;190      expect(imagediff.equal(a, b, 101)).toEqual(true);191    });192    it('should be equal optional tolerance', function () {193      b = context.createImageData(2, 2);194      b.data[0] = 100;195      expect(imagediff.equal(a, b, 100)).toEqual(true);196    });197    it('should not be equal outside tolerance', function () {198      b = context.createImageData(2, 2);199      b.data[0] = 100;200      expect(imagediff.equal(a, b, 5)).toEqual(false);201    });202  });203  // Diff Testing204  describe('Diff', function () {205    var a, b, c, d;206    beforeEach(function () {207      this.addMatchers({208        toImageDiffEqual : toImageDiffEqual209      });210    });211    describe('Geometry', function () {212      it('should be square, 1x1', function () {213        a = imagediff.createImageData(1, 1),214        b = imagediff.createImageData(1, 1),215        c = imagediff.diff(a, b);216        expect(c.width).toEqual(1);217        expect(c.height).toEqual(1);218      });219      it('should be square, 2x2', function () {220        a = imagediff.createImageData(1, 2),221        b = imagediff.createImageData(2, 1),222        c = imagediff.diff(a, b);223        expect(c.width).toEqual(2);224        expect(c.height).toEqual(2);225      });226      it('should be rectangular, 1x2', function () {227        a = imagediff.createImageData(1, 2),228        b = imagediff.createImageData(1, 1),229        c = imagediff.diff(a, b);230        expect(c.width).toEqual(1);231        expect(c.height).toEqual(2);232      });233      it('should be rectangular, 2x1', function () {234        a = imagediff.createImageData(2, 1),235        b = imagediff.createImageData(1, 1),236        c = imagediff.diff(a, b);237        expect(c.width).toEqual(2);238        expect(c.height).toEqual(1);239      });240    });241    describe('Difference', function () {242      it('should be black', function () {243        a = imagediff.createImageData(1, 1),244        b = imagediff.createImageData(1, 1),245        c = imagediff.diff(a, b);246        d = imagediff.createImageData(1, 1);247        d.data[3] = 255;248        expect(c).toImageDiffEqual(d);249      });250      it('should calculate difference', function () {251        a = imagediff.createImageData(1, 1),252        a.data[1] = 200;253        b = imagediff.createImageData(1, 1),254        b.data[1] = 158;255        c = imagediff.diff(a, b);256        d = imagediff.createImageData(1, 1);257        d.data[1] = 42;258        d.data[3] = 255;259        expect(c).toImageDiffEqual(d);260      });261      it('should center images of unequal size', function () {262        a = imagediff.createImageData(3, 3),263        b = imagediff.createImageData(1, 1),264        b.data[1] = 21;265        c = imagediff.diff(a, b);266        d = imagediff.createImageData(3, 3);267        // 4 * (rowPos * imageWidth + columnPos) + rgbPos268        d.data[4 * (1 * 3 + 1) + 1] = 21;269        // set alpha270        Array.prototype.forEach.call(d.data, function (value, i) {271          if (i % 4 === 3) {272            d.data[i] = 255;273          }274        });275        expect(c).toImageDiffEqual(d);276      });277      it('should optionally align images top left for unequal size', function () {278        a = imagediff.createImageData(3, 3),279        b = imagediff.createImageData(1, 1),280        b.data[1] = 21;281        c = imagediff.diff(a, b, {align: 'top'});282        d = imagediff.createImageData(3, 3);283        d.data[1] = 21;284        // set alpha285        Array.prototype.forEach.call(d.data, function (value, i) {286          if (i % 4 === 3) {287            d.data[i] = 255;288          }289        });290        expect(c).toImageDiffEqual(d);291      });292    });293    /*294    var295      a = imagediff.createImageData(1, 3),296      b = imagediff.createImageData(3, 1),297      c, d;298    a.data[0] = 255;299    a.data[3] = 255;300    a.data[4] = 255;301    a.data[7] = 255;302    a.data[8] = 255;303    a.data[11] = 255;304    b.data[0] = 255;305    b.data[3] = 255;306    b.data[4] = 255;307    b.data[7] = 255;308    b.data[8] = 255;309    b.data[11] = 255;310    */311  });312  // Jasmine Matcher Testing313  describe("jasmine.Matchers", function() {314    var315      imageA = newImage(),316      imageB = newImage(),317      imageC = newImage(),318      env, spec;319    imageA.src = 'images/xmark.png';320    imageB.src = 'images/xmark.png';321    imageC.src = 'images/checkmark.png';322    beforeEach(function() {323      env = new jasmine.Env();324      env.updateInterval = 0;325      var suite = env.describe("suite", function() {326        spec = env.it("spec", function() {327        });328      });329      spyOn(spec, 'addMatcherResult');330      spec.addMatchers(imagediff.jasmine);331      this.addMatchers({332        toPass: function() {333          return lastResult().passed();334        },335        toFail: function() {336          return !lastResult().passed();337        }338      });339    });340    function match(value) {341      return spec.expect(value);342    }343    function lastResult() {344      return spec.addMatcherResult.mostRecentCall.args[0];345    }346    it('toBeImageData', function () {347      var a = imagediff.createImageData(1, 1),348          b = {};349      expect(match(a).toBeImageData()).toPass();350      expect(match(b).toBeImageData()).toFail();351    });352    it('toImageDiffEqual with images', function () {353      waitsFor(function () {354        return imageA.complete && imageB.complete && imageC.complete;355      }, 'image not loaded.', 2000);356      runs(function () {357        expect(match(imageA).toImageDiffEqual(imageB)).toPass();358        expect(match(imageA).toImageDiffEqual(imageC)).toFail();359        expect(function () {360          match(imageA).toImageDiffEqual({});361        }).toThrow(E_TYPE);362      });363    });364    it('toImageDiffEqual with contexts (not a DOM element)', function () {365      var366        a = imagediff.createCanvas(imageA.width, imageA.height).getContext('2d'),367        b = imagediff.createCanvas(imageB.width, imageB.height).getContext('2d'),368        c = imagediff.createCanvas(imageC.width, imageC.height).getContext('2d');369      a.drawImage(imageA, 0, 0);370      b.drawImage(imageB, 0, 0);371      c.drawImage(imageC, 0, 0);372      expect(match(a).toImageDiffEqual(b)).toPass();373      expect(match(a).toImageDiffEqual(c)).toFail();374      expect(function () {375        match(a).toImageDiffEqual({});376      }).toThrow(E_TYPE);377    });378  });379  // Image Output380  describe('Image Output', function () {381    if (!isNode) { return; }382    var383      output = 'images/spec_output.png';384    beforeEach(function () {385      this.addMatchers(imagediff.jasmine)386    });387    afterEach(function () {388      require('fs').unlink(output);389    });390    it('saves an image as a PNG', function () {391      var392        image = newImage(),393        canvas = imagediff.createCanvas(10, 10),394        context = canvas.getContext('2d'),395        a, b;396      context.moveTo(0, 0);397      context.lineTo(10, 10);398      context.strokeStyle = 'rgba(150, 150, 150, .5)';399      context.stroke();400      a = context.getImageData(0, 0, 10, 10);401      imagediff.imageDataToPNG(a, output, function () {402        image.src = output;403      });404      waitsFor(function () {405        return image.complete;406      }, 'image not loaded.', 2000);407      runs(function () {408        b = imagediff.toImageData(image);409        expect(b).toBeImageData();410        expect(canvas).toImageDiffEqual(b, 10);411      });412    });413  });414  // Compatibility Testing415  describe('Compatibility', function () {416    var417      fn = Function,418      global = (fn('return this;')()), // Get the global object419      that = imagediff,420      reference;421    afterEach(function () {422      global.imagediff = that;423    });424    it('should remove imagediff from global space', function () {425      imagediff.noConflict();426      if (!isNode) {427        expect(imagediff === that).toEqual(false);428        expect(global.imagediff === that).toEqual(false);429      }430    });431    it('should return imagediff', function () {432      reference = imagediff.noConflict();433      expect(reference === that).toEqual(true);434    });435  });...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
