<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2016 Zhipeng Jia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

'use strict'

var test = require('tap').test

var snappy = require('snappy')
var snappyjs = require('./index')

var fs = require('fs')
var textrandomInputString = fs.readFileSync('snappy_compressor.js', 'utf8')

function bufferToUint8Array (buffer) {
  return new Uint8Array(buffer)
}

function bufferToArrayBuffer (buffer) {
  var arrayBuffer = new ArrayBuffer(buffer.length)
  var view = new Uint8Array(arrayBuffer)
  var i
  for (i = 0; i < buffer.length; i++) {
    view[i] = buffer[i]
  }
  return arrayBuffer
}

function uint8ArrayToBuffer (uint8Array) {
  var buffer = Buffer.alloc(uint8Array.length)
  var i
  for (i = 0; i < uint8Array.length; i++) {
    buffer[i] = uint8Array[i]
  }
  return buffer
}

function arrayBufferToBuffer (arrayBuffer) {
  var view = new Uint8Array(arrayBuffer)
  var buffer = Buffer.alloc(view.length)
  var i
  for (i = 0; i < view.length; i++) {
    buffer[i] = view[i]
  }
  return buffer
}

function stringToUint8Array (source) {
  var arrayBuffer = new ArrayBuffer(source.length * 2)
  var view = new Uint16Array(arrayBuffer)
  var i
  for (i = 0; i < source.length; i++) {
    view[i] = source.charCodeAt(i)
  }
  return new Uint8Array(arrayBuffer)
}

function stringToArrayBuffer (source) {
  var arrayBuffer = new ArrayBuffer(source.length * 2)
  var view = new Uint16Array(arrayBuffer)
  var i
  for (i = 0; i < source.length; i++) {
    view[i] = source.charCodeAt(i)
  }
  return arrayBuffer
}

function uint8ArrayToString (uint8Array) {
  var view = new Uint16Array(uint8Array.buffer)
  var result = ''
  var i
  for (i = 0; i < view.length; i++) {
    result += String.fromCharCode(view[i])
  }
  return result
}

function arrayBufferToString (arrayBuffer) {
  var view = new Uint16Array(arrayBuffer)
  var result = ''
  var i
  for (i = 0; i < view.length; i++) {
    result += String.fromCharCode(view[i])
  }
  return result
}

function randomString (length) {
  var result = ''
  var i, code
  for (i = 0; i < length; i++) {
    code = Math.floor(Math.random() * 256)
    result += String.fromCharCode(code)
  }
  return result
}

test('compress() normal text using Uint8Array', function (t) {
  var compressed = snappyjs.compress(stringToUint8Array(textrandomInputString))
  compressed = arrayBufferToBuffer(compressed)
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, textrandomInputString)
  t.end()
})

test('compress() normal text using ArrayBuffer', function (t) {
  var compressed = snappyjs.compress(stringToArrayBuffer(textrandomInputString))
  compressed = arrayBufferToBuffer(compressed)
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, textrandomInputString)
  t.end()
})

test('compress() normal text using Buffer', function (t) {
  var compressed = snappyjs.compress(arrayBufferToBuffer(stringToArrayBuffer(textrandomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, textrandomInputString)
  t.end()
})

test('uncompress() normal text using Uint8Array', function (t) {
  var compressed = snappy.compressSync(arrayBufferToBuffer(stringToArrayBuffer(textrandomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  compressed = bufferToUint8Array(compressed)
  var uncompressed = snappyjs.uncompress(compressed)
  var uncompressedString = uint8ArrayToString(uncompressed)
  t.equal(uncompressedString, textrandomInputString)
  t.end()
})

test('uncompress() normal text using ArrayBuffer', function (t) {
  var compressed = snappy.compressSync(arrayBufferToBuffer(stringToArrayBuffer(textrandomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  compressed = bufferToArrayBuffer(compressed)
  var uncompressed = snappyjs.uncompress(compressed)
  var uncompressedString = arrayBufferToString(uncompressed)
  t.equal(uncompressedString, textrandomInputString)
  t.end()
})

test('uncompress() normal text using Buffer', function (t) {
  var compressed = snappy.compressSync(arrayBufferToBuffer(stringToArrayBuffer(textrandomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappyjs.uncompress(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, textrandomInputString)
  t.end()
})

test('compress() random string of length 100000 using Uint8Array', function (t) {
  var randomInputString = randomString(100000)
  var compressed = snappyjs.compress(stringToUint8Array(randomInputString))
  compressed = uint8ArrayToBuffer(compressed)
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('compress() random string of length 100000 using ArrayBuffer', function (t) {
  var randomInputString = randomString(100000)
  var compressed = snappyjs.compress(stringToArrayBuffer(randomInputString))
  compressed = arrayBufferToBuffer(compressed)
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('compress() random string of length 100000 using Buffer', function (t) {
  var randomInputString = randomString(100000)
  var compressed = snappyjs.compress(arrayBufferToBuffer(stringToArrayBuffer(randomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('compress() random string of length 100 using Uint8Array', function (t) {
  var randomInputString = randomString(100)
  var compressed = snappyjs.compress(stringToUint8Array(randomInputString))
  compressed = uint8ArrayToBuffer(compressed)
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('compress() random string of length 100 using ArrayBuffer', function (t) {
  var randomInputString = randomString(100)
  var compressed = snappyjs.compress(stringToArrayBuffer(randomInputString))
  compressed = arrayBufferToBuffer(compressed)
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('compress() random string of length 100 using Buffer', function (t) {
  var randomInputString = randomString(100)
  var compressed = snappyjs.compress(arrayBufferToBuffer(stringToArrayBuffer(randomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('uncompress() random string of length 100000 using Uint8Array', function (t) {
  var randomInputString = randomString(100000)
  var compressed = snappy.compressSync(arrayBufferToBuffer(stringToArrayBuffer(randomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  compressed = bufferToUint8Array(compressed)
  var uncompressed = snappyjs.uncompress(compressed)
  var uncompressedString = uint8ArrayToString(uncompressed)
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('uncompress() random string of length 100000 using ArrayBuffer', function (t) {
  var randomInputString = randomString(100000)
  var compressed = snappy.compressSync(arrayBufferToBuffer(stringToArrayBuffer(randomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  compressed = bufferToArrayBuffer(compressed)
  var uncompressed = snappyjs.uncompress(compressed)
  var uncompressedString = arrayBufferToString(uncompressed)
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('uncompress() random string of length 100000 using Buffer', function (t) {
  var randomInputString = randomString(100000)
  var compressed = snappy.compressSync(arrayBufferToBuffer(stringToArrayBuffer(randomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappyjs.uncompress(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})
<commit_msg>add unit test for maxLength param<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2016 Zhipeng Jia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

'use strict'

var test = require('tap').test

var snappy = require('snappy')
var snappyjs = require('./index')

var fs = require('fs')
var textrandomInputString = fs.readFileSync('snappy_compressor.js', 'utf8')

function bufferToUint8Array (buffer) {
  return new Uint8Array(buffer)
}

function bufferToArrayBuffer (buffer) {
  var arrayBuffer = new ArrayBuffer(buffer.length)
  var view = new Uint8Array(arrayBuffer)
  var i
  for (i = 0; i < buffer.length; i++) {
    view[i] = buffer[i]
  }
  return arrayBuffer
}

function uint8ArrayToBuffer (uint8Array) {
  var buffer = Buffer.alloc(uint8Array.length)
  var i
  for (i = 0; i < uint8Array.length; i++) {
    buffer[i] = uint8Array[i]
  }
  return buffer
}

function arrayBufferToBuffer (arrayBuffer) {
  var view = new Uint8Array(arrayBuffer)
  var buffer = Buffer.alloc(view.length)
  var i
  for (i = 0; i < view.length; i++) {
    buffer[i] = view[i]
  }
  return buffer
}

function stringToUint8Array (source) {
  var arrayBuffer = new ArrayBuffer(source.length * 2)
  var view = new Uint16Array(arrayBuffer)
  var i
  for (i = 0; i < source.length; i++) {
    view[i] = source.charCodeAt(i)
  }
  return new Uint8Array(arrayBuffer)
}

function stringToArrayBuffer (source) {
  var arrayBuffer = new ArrayBuffer(source.length * 2)
  var view = new Uint16Array(arrayBuffer)
  var i
  for (i = 0; i < source.length; i++) {
    view[i] = source.charCodeAt(i)
  }
  return arrayBuffer
}

function uint8ArrayToString (uint8Array) {
  var view = new Uint16Array(uint8Array.buffer)
  var result = ''
  var i
  for (i = 0; i < view.length; i++) {
    result += String.fromCharCode(view[i])
  }
  return result
}

function arrayBufferToString (arrayBuffer) {
  var view = new Uint16Array(arrayBuffer)
  var result = ''
  var i
  for (i = 0; i < view.length; i++) {
    result += String.fromCharCode(view[i])
  }
  return result
}

function randomString (length) {
  var result = ''
  var i, code
  for (i = 0; i < length; i++) {
    code = Math.floor(Math.random() * 256)
    result += String.fromCharCode(code)
  }
  return result
}

test('compress() normal text using Uint8Array', function (t) {
  var compressed = snappyjs.compress(stringToUint8Array(textrandomInputString))
  compressed = arrayBufferToBuffer(compressed)
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, textrandomInputString)
  t.end()
})

test('compress() normal text using ArrayBuffer', function (t) {
  var compressed = snappyjs.compress(stringToArrayBuffer(textrandomInputString))
  compressed = arrayBufferToBuffer(compressed)
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, textrandomInputString)
  t.end()
})

test('compress() normal text using Buffer', function (t) {
  var compressed = snappyjs.compress(arrayBufferToBuffer(stringToArrayBuffer(textrandomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, textrandomInputString)
  t.end()
})

test('uncompress() normal text using Uint8Array', function (t) {
  var compressed = snappy.compressSync(arrayBufferToBuffer(stringToArrayBuffer(textrandomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  compressed = bufferToUint8Array(compressed)
  var uncompressed = snappyjs.uncompress(compressed)
  var uncompressedString = uint8ArrayToString(uncompressed)
  t.equal(uncompressedString, textrandomInputString)
  t.end()
})

test('uncompress() normal text using ArrayBuffer', function (t) {
  var compressed = snappy.compressSync(arrayBufferToBuffer(stringToArrayBuffer(textrandomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  compressed = bufferToArrayBuffer(compressed)
  var uncompressed = snappyjs.uncompress(compressed)
  var uncompressedString = arrayBufferToString(uncompressed)
  t.equal(uncompressedString, textrandomInputString)
  t.end()
})

test('uncompress() normal text using Buffer', function (t) {
  var compressed = snappy.compressSync(arrayBufferToBuffer(stringToArrayBuffer(textrandomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappyjs.uncompress(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, textrandomInputString)
  t.end()
})

test('compress() random string of length 100000 using Uint8Array', function (t) {
  var randomInputString = randomString(100000)
  var compressed = snappyjs.compress(stringToUint8Array(randomInputString))
  compressed = uint8ArrayToBuffer(compressed)
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('compress() random string of length 100000 using ArrayBuffer', function (t) {
  var randomInputString = randomString(100000)
  var compressed = snappyjs.compress(stringToArrayBuffer(randomInputString))
  compressed = arrayBufferToBuffer(compressed)
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('compress() random string of length 100000 using Buffer', function (t) {
  var randomInputString = randomString(100000)
  var compressed = snappyjs.compress(arrayBufferToBuffer(stringToArrayBuffer(randomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('compress() random string of length 100 using Uint8Array', function (t) {
  var randomInputString = randomString(100)
  var compressed = snappyjs.compress(stringToUint8Array(randomInputString))
  compressed = uint8ArrayToBuffer(compressed)
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('compress() random string of length 100 using ArrayBuffer', function (t) {
  var randomInputString = randomString(100)
  var compressed = snappyjs.compress(stringToArrayBuffer(randomInputString))
  compressed = arrayBufferToBuffer(compressed)
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('compress() random string of length 100 using Buffer', function (t) {
  var randomInputString = randomString(100)
  var compressed = snappyjs.compress(arrayBufferToBuffer(stringToArrayBuffer(randomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappy.uncompressSync(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('uncompress() random string of length 100000 using Uint8Array', function (t) {
  var randomInputString = randomString(100000)
  var compressed = snappy.compressSync(arrayBufferToBuffer(stringToArrayBuffer(randomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  compressed = bufferToUint8Array(compressed)
  var uncompressed = snappyjs.uncompress(compressed)
  var uncompressedString = uint8ArrayToString(uncompressed)
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('uncompress() random string of length 100000 using ArrayBuffer', function (t) {
  var randomInputString = randomString(100000)
  var compressed = snappy.compressSync(arrayBufferToBuffer(stringToArrayBuffer(randomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  compressed = bufferToArrayBuffer(compressed)
  var uncompressed = snappyjs.uncompress(compressed)
  var uncompressedString = arrayBufferToString(uncompressed)
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('uncompress() random string of length 100000 using Buffer', function (t) {
  var randomInputString = randomString(100000)
  var compressed = snappy.compressSync(arrayBufferToBuffer(stringToArrayBuffer(randomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  var uncompressed = snappyjs.uncompress(compressed)
  var uncompressedString = arrayBufferToString(bufferToArrayBuffer(uncompressed))
  t.equal(uncompressedString, randomInputString)
  t.end()
})

test('uncompress() maxLength', function (t) {
  var randomInputString = randomString(100000)
  var compressed = snappy.compressSync(arrayBufferToBuffer(stringToArrayBuffer(randomInputString)))
  t.equal(snappy.isValidCompressedSync(compressed), true)
  compressed = bufferToUint8Array(compressed)
  t.throws(function () { snappyjs.uncompress(compressed, 99999) }, new Error('The uncompressed length of 200000 is too big, expect at most 99999'))//

  t.end()
})
<|endoftext|>


<commit_before>import test from 'ava';

const objc = require('./src/index.js');

test('string creation', t => {
  const NSString = objc.NSString;
  const string = NSString.stringWithString_('Hello World');
  t.is(String(string), 'Hello World');
});

test('primitive return values', t => {
  const NSString = objc.NSString;
  const string = NSString.stringWithString_('I am the doctor');
  const length = string.length();
  t.is(length, 15);
  t.is(typeof length, 'number');
});

test('load constant directly from `objc` module', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.NSFontAttributeName;

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/out bundle', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.constant('NSFontAttributeName');

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/ bundle', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.constant('NSFontAttributeName', 'AppKit');

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/ full bundle name', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.constant('NSFontAttributeName', 'com.apple.AppKit');

  t.is(NSFontAttributeName, 'NSFont');
});

test('get username using NSProcessInfo, convert to javascript string and compare the value to the username given by `os.userInfo()`', t => {
  const NSProcessInfo = objc.NSProcessInfo;
  const os = require('os');

  const processInfo = NSProcessInfo.processInfo();
  const username = processInfo.userName();

  t.is(String(username), os.userInfo().username);
});

test('primitive argument types', t => {
  const NSNumber = objc.NSNumber;

  const number = NSNumber.numberWithInt_(5);

  t.is(Number(number), 5);
});

test('inout parameters 1 (^@)', t => {
  const NSFileManager = objc.NSFileManager;
  const fm = NSFileManager.defaultManager();

  const filepath = '/Library/Caches/randomfilenamethatsurelydoesntexust.hey';
  fm.createFileAtPath_contents_attributes_(filepath, null, null);

  const error1 = objc.ref(null);
  const success1 = fm.removeItemAtPath_error_(filepath, error1);

  t.is(success1, true);
  t.is(typeof objc.deref(error1), 'undefined');

  const error2 = objc.ref(null);
  const success2 = fm.removeItemAtPath_error_(filepath, error2);

  t.is(success2, false);
  t.is(typeof objc.deref(error2), 'object');
});

test('inout parameters 2 (^@)', t => {
  const NSDictionary = objc.NSDictionary;
  const NSAppleScript = objc.NSAppleScript;
  const source = 'telll application "Safari" to get URL of current tab of window 1';

  const script = NSAppleScript.alloc().initWithSource_(source);

  const error = objc.ref(null);
  const success = script.compileAndReturnError_(error);

  t.is(success, false);
  t.is(objc.deref(error).isKindOfClass_(NSDictionary), true);
});

test('Automatic array conversion (JS array -> NSArray)', t => {
  const NSArray = objc.NSArray;

  const inputArray = ['I', 'am', 'the', 'doctor'];
  const array = NSArray.arrayWithArray_(inputArray);

  inputArray.forEach((object, index) => {
    const str1 = String(object);
    const str2 = String(array.objectAtIndex_(index));
    t.is(str1, str2);
  });
});

test('Iterate over a NSArray', t => {
  const NSArray = objc.NSArray;

  const inputArray = ['hey', 'missy', 'you', 'so', 'fine'];
  const array = NSArray.arrayWithArray_(inputArray);

  for (const element of array) {
    const index = inputArray.indexOf(String(element));
    inputArray.splice(index, 1);
  }

  t.is(inputArray.length, 0);
});

test('Test calling methods that contain underscores', t => {
  const NSDate = objc.NSDate;

  const now = NSDate.date();
  const web_RFC1123DateString = now._web_RFC1123DateString(); // eslint-disable-line camelcase

  t.is(typeof web_RFC1123DateString, 'object'); // eslint-disable-line camelcase
  t.is(web_RFC1123DateString.isKindOfClass_('NSString'), true); // eslint-disable-line camelcase
});

test('Test possible selectors for 0 underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = ['date'];

  possibleSelectors('date').forEach((_, index) => {
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for 1 underscore', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    'performAction:',
    'performAction_'
  ];

  possibleSelectors('performAction_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for 2 underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    'performAction_withObject_',
    'performAction:withObject_',
    'performAction_withObject:',
    'performAction:withObject:'
  ];

  possibleSelectors('performAction_withObject_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for 3 underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    'performAction:withObject_afterDelay:',
    'performAction:withObject_afterDelay_',
    'performAction:withObject:afterDelay_',
    'performAction_withObject:afterDelay:',
    'performAction_withObject:afterDelay_',
    'performAction_withObject_afterDelay:',
    'performAction:withObject:afterDelay:',
    'performAction_withObject_afterDelay_'
  ];

  possibleSelectors('performAction_withObject_afterDelay_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for method with leading underscore and no other underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    '_dateString',
    '_dateString'
  ];

  possibleSelectors('_dateString').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for method with leading underscore and other underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    '_dateStringForTimeZone_',
    '_dateStringForTimeZone:',
    ':dateStringForTimeZone_',
    ':dateStringForTimeZone:'
  ];

  possibleSelectors('_dateStringForTimeZone_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('description of class proxy', t => {
  const util = require('util');
  const NSDate = objc.NSDate;

  const description = util.inspect(NSDate);

  t.is(description, '[objc.ClassProxy NSDate]');
});

test('description of instance proxy', t => {
  const util = require('util');
  const string = objc.NSString.stringWithString_('the north remembers');

  const description = util.inspect(string);

  t.is(description, '[objc.InstanceProxy the north remembers]');
});

test('description of method proxy', t => {
  const util = require('util');
  const NSDate = objc.NSDate;

  const dateMethod = NSDate.date;
  const description = util.inspect(dateMethod);

  t.is(description, '[objc.MethodProxy for date]');
});

test('Class class methods', t => {
  const NSString = objc.NSString;

  const classMethods = NSString.__classMethods;

  t.is(Array.isArray(classMethods), true);

  // Includes methods inherited from NSObject
  t.true(classMethods.includes('load'));
  t.true(classMethods.includes('init'));

  // Includes NSString-specific methods
  t.true(classMethods.includes('stringWithCString:'));
  t.true(classMethods.includes('stringWithFormat:'));
  t.true(classMethods.includes('stringEncodingForData:encodingOptions:convertedString:usedLossyConversion:'));
});

test('Class instance methods', t => {
  const NSString = objc.NSString;

  const classMethods = NSString.__instanceMethods;

  t.is(Array.isArray(classMethods), true);

  // Includes methods inherited from NSObject
  t.true(classMethods.includes('copy'));
  t.true(classMethods.includes('description'));

  // Includes NSString-specific methods
  t.true(classMethods.includes('length'));
  t.true(classMethods.includes('cStringUsingEncoding:'));
  t.true(classMethods.includes('compare:options:range:locale:'));
  t.true(classMethods.includes('getBytes:maxLength:usedLength:encoding:options:range:remainingRange:'));
});

test('Type conversion JS -> ObjC: String', t => {
  const NSString = objc.NSString;

  const input = 'trust me. i am the doctor';
  const asNSString = objc.ns(input);

  t.true(asNSString.isKindOfClass_(NSString));
});

test('Type conversion JS -> ObjC: Number', t => {
  const NSNumber = objc.NSNumber;

  const input = 42;
  const asNSNumber = objc.ns(input);

  t.true(asNSNumber.isKindOfClass_(NSNumber));
});

test('Type conversion JS -> ObjC: Array', t => {
  const NSArray = objc.NSArray;

  const input = ['time', 'and', 'relative', 'dimensions', 'in', 'space'];
  const asNSArray = objc.ns(input);

  t.true(asNSArray.isKindOfClass_(NSArray));
});

test('Type conversion JS -> ObjC: Date', t => {
  const NSDate = objc.NSDate;

  const input = new Date('1963-11-23T17:16:20');
  const asNSDate = objc.ns(input);

  t.true(asNSDate.isKindOfClass_(NSDate));
});

test('Type conversion JS -> ObjC: Unknown', t => {
  const input = {firstName: 'Lukas', lastName: 'Kollmer'};
  const objcValue = objc.ns(input);

  t.is(objcValue, input);
});

test('Type conversion ObjC -> JS: String', t => {
  const NSString = objc.NSString;

  const input = NSString.stringWithString_('trust me. i am the doctor');
  const asString = objc.js(input);

  t.is(asString, 'trust me. i am the doctor');
});

test('Type conversion ObjC -> JS: Number', t => {
  const NSNumber = objc.NSNumber;

  const input = NSNumber.numberWithInt_(42);
  const asNumber = objc.js(input);

  t.is(asNumber, 42);
});

test('Type conversion ObjC -> JS: Array', t => {
  const NSArray = objc.NSArray;

  const input = NSArray.arrayWithArray_(['time', 'and', 'relative', 'dimensions', 'in', 'space']);
  const asArray = objc.js(input);

  t.is(asArray.length, 6);
});

test('Type conversion ObjC -> JS: Date', t => {
  const NSDate = objc.NSDate;

  const input = NSDate.date();
  const asDate = objc.js(input);

  t.true(asDate instanceof Date);
});

test('Type conversion ObjC -> JS: Unknown', t => {
  const NSProcessInfo = objc.NSProcessInfo;

  const input = NSProcessInfo.processInfo();
  const jsValue = objc.js(input);

  t.is(input, jsValue);
});

test('class exists', t => {
  t.true(objc.classExists('NSString'));
  t.false(objc.classExists('ClassThatDoesntExist'));
});

<commit_msg>added a trailing underscore test case<commit_after>import test from 'ava';

const objc = require('./src/index.js');

test('string creation', t => {
  const NSString = objc.NSString;
  const string = NSString.stringWithString_('Hello World');
  t.is(String(string), 'Hello World');
});

test('primitive return values', t => {
  const NSString = objc.NSString;
  const string = NSString.stringWithString_('I am the doctor');
  const length = string.length();
  t.is(length, 15);
  t.is(typeof length, 'number');
});

test('load constant directly from `objc` module', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.NSFontAttributeName;

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/out bundle', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.constant('NSFontAttributeName');

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/ bundle', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.constant('NSFontAttributeName', 'AppKit');

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/ full bundle name', t => {
  objc.import('AppKit');
  const NSFontAttributeName = objc.constant('NSFontAttributeName', 'com.apple.AppKit');

  t.is(NSFontAttributeName, 'NSFont');
});

test('get username using NSProcessInfo, convert to javascript string and compare the value to the username given by `os.userInfo()`', t => {
  const NSProcessInfo = objc.NSProcessInfo;
  const os = require('os');

  const processInfo = NSProcessInfo.processInfo();
  const username = processInfo.userName();

  t.is(String(username), os.userInfo().username);
});

test('primitive argument types', t => {
  const NSNumber = objc.NSNumber;

  const number = NSNumber.numberWithInt_(5);

  t.is(Number(number), 5);
});

test('inout parameters 1 (^@)', t => {
  const NSFileManager = objc.NSFileManager;
  const fm = NSFileManager.defaultManager();

  const filepath = '/Library/Caches/randomfilenamethatsurelydoesntexust.hey';
  fm.createFileAtPath_contents_attributes_(filepath, null, null);

  const error1 = objc.ref(null);
  const success1 = fm.removeItemAtPath_error_(filepath, error1);

  t.is(success1, true);
  t.is(typeof objc.deref(error1), 'undefined');

  const error2 = objc.ref(null);
  const success2 = fm.removeItemAtPath_error_(filepath, error2);

  t.is(success2, false);
  t.is(typeof objc.deref(error2), 'object');
});

test('inout parameters 2 (^@)', t => {
  const NSDictionary = objc.NSDictionary;
  const NSAppleScript = objc.NSAppleScript;
  const source = 'telll application "Safari" to get URL of current tab of window 1';

  const script = NSAppleScript.alloc().initWithSource_(source);

  const error = objc.ref(null);
  const success = script.compileAndReturnError_(error);

  t.is(success, false);
  t.is(objc.deref(error).isKindOfClass_(NSDictionary), true);
});

test('Automatic array conversion (JS array -> NSArray)', t => {
  const NSArray = objc.NSArray;

  const inputArray = ['I', 'am', 'the', 'doctor'];
  const array = NSArray.arrayWithArray_(inputArray);

  inputArray.forEach((object, index) => {
    const str1 = String(object);
    const str2 = String(array.objectAtIndex_(index));
    t.is(str1, str2);
  });
});

test('Iterate over a NSArray', t => {
  const NSArray = objc.NSArray;

  const inputArray = ['hey', 'missy', 'you', 'so', 'fine'];
  const array = NSArray.arrayWithArray_(inputArray);

  for (const element of array) {
    const index = inputArray.indexOf(String(element));
    inputArray.splice(index, 1);
  }

  t.is(inputArray.length, 0);
});

test('Test calling methods that contain underscores', t => {
  const NSDate = objc.NSDate;

  const now = NSDate.date();
  const web_RFC1123DateString = now._web_RFC1123DateString(); // eslint-disable-line camelcase

  t.is(typeof web_RFC1123DateString, 'object'); // eslint-disable-line camelcase
  t.is(web_RFC1123DateString.isKindOfClass_('NSString'), true); // eslint-disable-line camelcase
});

test('Test possible selectors for 0 underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = ['date'];

  possibleSelectors('date').forEach((_, index) => {
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for 1 underscore', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    'performAction:',
    'performAction_'
  ];

  possibleSelectors('performAction_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for 2 underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    'performAction_withObject_',
    'performAction:withObject_',
    'performAction_withObject:',
    'performAction:withObject:'
  ];

  possibleSelectors('performAction_withObject_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for 3 underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    'performAction:withObject_afterDelay:',
    'performAction:withObject_afterDelay_',
    'performAction:withObject:afterDelay_',
    'performAction_withObject:afterDelay:',
    'performAction_withObject:afterDelay_',
    'performAction_withObject_afterDelay:',
    'performAction:withObject:afterDelay:',
    'performAction_withObject_afterDelay_'
  ];

  possibleSelectors('performAction_withObject_afterDelay_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for method with leading underscore and no other underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    '_dateString',
    '_dateString'
  ];

  possibleSelectors('_dateString').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('Test possible selectors for method with leading underscore and other underscores', t => {
  const possibleSelectors = require('./src/possible-selectors');

  const selectors = [
    '_dateStringForTimeZone_',
    '_dateStringForTimeZone:',
    ':dateStringForTimeZone_',
    ':dateStringForTimeZone:'
  ];

  possibleSelectors('_dateStringForTimeZone_').forEach(sel => {
    const index = selectors.indexOf(sel);
    selectors.splice(index, 1);
  });

  t.is(selectors.length, 0);
});

test('description of class proxy', t => {
  const util = require('util');
  const NSDate = objc.NSDate;

  const description = util.inspect(NSDate);

  t.is(description, '[objc.ClassProxy NSDate]');
});

test('description of instance proxy', t => {
  const util = require('util');
  const string = objc.NSString.stringWithString_('the north remembers');

  const description = util.inspect(string);

  t.is(description, '[objc.InstanceProxy the north remembers]');
});

test('description of method proxy', t => {
  const util = require('util');
  const NSDate = objc.NSDate;

  const dateMethod = NSDate.date;
  const description = util.inspect(dateMethod);

  t.is(description, '[objc.MethodProxy for date]');
});

test('Class class methods', t => {
  const NSString = objc.NSString;

  const classMethods = NSString.__classMethods;

  t.is(Array.isArray(classMethods), true);

  // Includes methods inherited from NSObject
  t.true(classMethods.includes('load'));
  t.true(classMethods.includes('init'));

  // Includes NSString-specific methods
  t.true(classMethods.includes('stringWithCString:'));
  t.true(classMethods.includes('stringWithFormat:'));
  t.true(classMethods.includes('stringEncodingForData:encodingOptions:convertedString:usedLossyConversion:'));
});

test('Class instance methods', t => {
  const NSString = objc.NSString;

  const classMethods = NSString.__instanceMethods;

  t.is(Array.isArray(classMethods), true);

  // Includes methods inherited from NSObject
  t.true(classMethods.includes('copy'));
  t.true(classMethods.includes('description'));

  // Includes NSString-specific methods
  t.true(classMethods.includes('length'));
  t.true(classMethods.includes('cStringUsingEncoding:'));
  t.true(classMethods.includes('compare:options:range:locale:'));
  t.true(classMethods.includes('getBytes:maxLength:usedLength:encoding:options:range:remainingRange:'));
});

test('Type conversion JS -> ObjC: String', t => {
  const NSString = objc.NSString;

  const input = 'trust me. i am the doctor';
  const asNSString = objc.ns(input);

  t.true(asNSString.isKindOfClass_(NSString));
});

test('Type conversion JS -> ObjC: Number', t => {
  const NSNumber = objc.NSNumber;

  const input = 42;
  const asNSNumber = objc.ns(input);

  t.true(asNSNumber.isKindOfClass_(NSNumber));
});

test('Type conversion JS -> ObjC: Array', t => {
  const NSArray = objc.NSArray;

  const input = ['time', 'and', 'relative', 'dimensions', 'in', 'space'];
  const asNSArray = objc.ns(input);

  t.true(asNSArray.isKindOfClass_(NSArray));
});

test('Type conversion JS -> ObjC: Date', t => {
  const NSDate = objc.NSDate;

  const input = new Date('1963-11-23T17:16:20');
  const asNSDate = objc.ns(input);

  t.true(asNSDate.isKindOfClass_(NSDate));
});

test('Type conversion JS -> ObjC: Unknown', t => {
  const input = {firstName: 'Lukas', lastName: 'Kollmer'};
  const objcValue = objc.ns(input);

  t.is(objcValue, input);
});

test('Type conversion ObjC -> JS: String', t => {
  const NSString = objc.NSString;

  const input = NSString.stringWithString_('trust me. i am the doctor');
  const asString = objc.js(input);

  t.is(asString, 'trust me. i am the doctor');
});

test('Type conversion ObjC -> JS: Number', t => {
  const NSNumber = objc.NSNumber;

  const input = NSNumber.numberWithInt_(42);
  const asNumber = objc.js(input);

  t.is(asNumber, 42);
});

test('Type conversion ObjC -> JS: Array', t => {
  const NSArray = objc.NSArray;

  const input = NSArray.arrayWithArray_(['time', 'and', 'relative', 'dimensions', 'in', 'space']);
  const asArray = objc.js(input);

  t.is(asArray.length, 6);
});

test('Type conversion ObjC -> JS: Date', t => {
  const NSDate = objc.NSDate;

  const input = NSDate.date();
  const asDate = objc.js(input);

  t.true(asDate instanceof Date);
});

test('Type conversion ObjC -> JS: Unknown', t => {
  const NSProcessInfo = objc.NSProcessInfo;

  const input = NSProcessInfo.processInfo();
  const jsValue = objc.js(input);

  t.is(input, jsValue);
});

test('class exists', t => {
  t.true(objc.classExists('NSString'));
  t.false(objc.classExists('ClassThatDoesntExist'));
});

test('Trailing underscores in method names can be omitted', t => {
  const NSString = objc.NSString;

  const str1 = NSString.stringWithString_('Hello World');
  const str2 = NSString.stringWithString('Hello World');

  t.is(String(str1), String(str2));
});
<|endoftext|>


<commit_before>/*!
 * is-match <https://github.com/jonschlinkert/is-match>
 *
 * Copyright (c) 2015 Jon Schlinkert, contributors.
 * Licensed under the MIT License
 */

'use strict';

/* deps: mocha */
var should = require('should');
var matcher = require('./');

it('should throw if not array, string, regexp, object or function', function () {
  function fixture () {
    matcher(1234)
  }
  should.throws(fixture, TypeError)
  should.throws(fixture, /expects a string, array, regex, object or function/)
})

describe('should return a matching function:', function () {
  it('from an object:', function () {
    var isMatch = matcher({a: 'b'});

    isMatch({a: 'b'}).should.be.true;
    isMatch({a: 'b', c: 'd'}).should.be.false;
    isMatch({e: 'f', c: 'd'}).should.be.false;
  });

  it('from a string:', function () {
    var isMatch = matcher('a');

    isMatch('a').should.be.true;
    isMatch('b').should.be.false;
    matcher('a')('abc').should.be.true;
    matcher('a')('def').should.be.false;
  });

  it('from a string glob pattern:', function () {
    matcher('*')('a').should.be.true;
    matcher('!b')('a').should.be.true;
    matcher('!b')('b').should.be.false;
  });

  it('from a string non-glob pattern:', function () {
    matcher('abc')('foo abc bar').should.be.false;
    matcher('abc')('abc').should.be.true;
    matcher('abc')(['foo', 'abc']).should.be.true;
    matcher('abc')(['foo abc bar', 'baz']).should.be.true;
  });

  it('from an array of glob patterns:', function () {
    matcher(['a'])('a').should.be.false;
    matcher(['b'])('a').should.be.false;
    matcher(['b', 'a'])(['a', 'b']).should.be.false;
    matcher(['b', 'a'])(['b', 'a']).should.be.true;
    matcher(['b', 'c', '*'])(['b', 'c', '*']).should.be.true;
    matcher(['*-koaip', '!foo-koa'])('x-koaip').should.be.true;
    matcher(['*-koaip', '!foo-koa'])(['foo-koa', 'bar-koa']).should.be.false;
  });

  it('from a regex:', function () {
    var isMatch = matcher(/a/);
    isMatch('a').should.be.true;
    isMatch('b').should.be.false;
  });

  it('from a function:', function () {
    var isMatch = matcher(function  (val) {
      return val === 'a';
    });
    isMatch('a').should.be.true;
    isMatch('b').should.be.false;
  });
});
<commit_msg>add more tests, ref #4<commit_after>/*!
 * is-match <https://github.com/jonschlinkert/is-match>
 *
 * Copyright (c) 2015 Jon Schlinkert, contributors.
 * Licensed under the MIT License
 */

'use strict';

/* deps: mocha */
var should = require('should');
var matcher = require('./');

it('should throw if not array, string, regexp, object or function', function () {
  function fixture () {
    matcher(1234)
  }
  should.throws(fixture, TypeError)
  should.throws(fixture, /expects a string, array, regex, object or function/)
})

describe('should return a matching function:', function () {
  it('from an object', function () {
    var isMatch = matcher({a: 'b'});

    isMatch({a: 'b'}).should.be.true;
    isMatch({a: 'b', c: 'd'}).should.be.false;
    isMatch({e: 'f', c: 'd'}).should.be.false;
  });

  it('from a string', function () {
    var isMatch = matcher('a');

    isMatch('a').should.be.true;
    isMatch('b').should.be.false;
    matcher('a')('abc').should.be.true;
    matcher('a')('def').should.be.false;
  });

  it('from a string glob pattern on single value', function () {
    matcher('*')('a').should.be.true;
    matcher('!b')('a').should.be.true;
    matcher('!b')('b').should.be.false;
  });

  it('from a string glob pattern on multiple values', function () {
    matcher('*')(['a', 'b']).should.be.true;
    matcher('{(b|[A-Z]),!([C-F])}.js')(['E.js', 'a.js']).should.be.false;
    matcher('{(b|[A-Z]),!([C-F])}.js')(['E.js', 'B.js']).should.be.true;
  });

  it('from a string non-glob pattern on single value', function () {
    matcher('abc')('foo abc bar').should.be.false;
    matcher('abc')('abc').should.be.true;
  })

  it('from a string non-glob pattern on multiple values', function () {
    matcher('abc')(['foo', 'abc']).should.be.true;
    matcher('abc')(['foo abc bar', 'baz']).should.be.true;
  });

  it('from an array of glob patterns on single value', function () {
    matcher(['a', 'b'])('a').should.be.true;
    matcher(['a', 'b'])('c').should.be.false;
    matcher(['*-koaip', '!foo-koa'])('x-koaip').should.be.true;
  });

  it('from an array of glob patterns on multiple values', function () {
    matcher(['a', 'b'])(['a', 'c']).should.be.true;
    matcher(['a', 'b'])(['e', 'f', 'g']).should.be.false;
    matcher(['*-koaip', '!foo-koa'])(['x-koaip', 'bar-koa']).should.be.true;
    matcher(['*-koaip', '!foo-koa'])(['foo-koa', 'bar-koa']).should.be.false;
  });

  it('from a regex', function () {
    var isMatch = matcher(/a/);
    isMatch('a').should.be.true;
    isMatch('b').should.be.false;
  });

  it('from a function', function () {
    var isMatch = matcher(function  (val) {
      return val === 'a';
    });
    isMatch('a').should.be.true;
    isMatch('b').should.be.false;
  });
});
<|endoftext|>


<commit_before>import fs from 'fs';
import test from 'ava';
import linkReplacer from './';

var basicInput = 'http://www.google.com';
var testImageUrl = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
var basicOutput = '"[Google](' + basicInput + ')", *google.com*';
var fourSpaces = '    ';

test.cb('Basic link replacement', function (t) {
  linkReplacer.replacePlainLinks(basicInput, function (newMarkdown) {
    t.is(newMarkdown, basicOutput);
    t.end();
  });
});

test.cb('Basic link replacement in parentheses', function (t) {
  linkReplacer.replacePlainLinks('(' + basicInput + ')', function (newMarkdown) {
    t.is(newMarkdown, '(' + basicOutput + ')');
    t.end();
  });
});

test.cb('Basic link replacement with trailing spaces', function (t) {
  linkReplacer.replacePlainLinks(basicInput + fourSpaces, function (newMarkdown) {
    t.is(newMarkdown, basicOutput + fourSpaces);
    t.end();
  });
});

test.cb('Will not replace image links', function (t) {
  linkReplacer.replacePlainLinks(testImageUrl, function (newMarkdown) {
    t.is(newMarkdown, testImageUrl);
    t.end();
  });
});

test.cb('Basic link replacement with the same link appearing twice', function (t) {
  linkReplacer.replacePlainLinks(basicInput + ' ' + basicInput, function (newMarkdown) {
    t.is(newMarkdown, basicOutput + ' ' + basicOutput);
    t.end();
  });
});

test.cb('A 404 title shouldn\t be replaced', function (t) {
  var fourOhFourUrl = 'http://www.google.com/aaa';
  linkReplacer.replacePlainLinks(fourOhFourUrl, function (newMarkdown) {
    t.is(newMarkdown, fourOhFourUrl);
    t.end();
  });
});

test.cb('Can handle a typical list of wikia urls at end of article', function (t) {
  fs.readFile('/fixtures/wikialistsample.md', function (inputErr, sampleInput) {
    fs.readFile('/fixtures/wikialistsample-output.md', function (outputErr, targetOutput) {
      linkReplacer.replacePlainLinks(sampleInput, function (newMarkdown) {
        t.is(newMarkdown, targetOutput);
        t.end();
      });
    });
  });
});
<commit_msg>More tests for coverage.<commit_after>import fs from 'fs';
import test from 'ava';
import linkReplacer from './';

var basicInput = 'http://www.google.com';
var testImageUrl = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
var basicOutput = '"[Google](' + basicInput + ')", *google.com*';
var fourSpaces = '    ';
var endOfFileReference = '[1]: http://en.wikipedia.org/wiki/Branch_predictor';
test.cb('Basic link replacement', function (t) {
  linkReplacer.replacePlainLinks(basicInput, function (newMarkdown) {
    t.is(newMarkdown, basicOutput);
    t.end();
  });
});

test.cb('Basic link replacement in parentheses', function (t) {
  linkReplacer.replacePlainLinks('(' + basicInput + ')', function (newMarkdown) {
    t.is(newMarkdown, '(' + basicOutput + ')');
    t.end();
  });
});

test.cb('Basic link replacement with trailing spaces', function (t) {
  linkReplacer.replacePlainLinks(basicInput + fourSpaces, function (newMarkdown) {
    t.is(newMarkdown, basicOutput + fourSpaces);
    t.end();
  });
});

test.cb('A link that is part of existing markdown link should not be replaced', function (t) {
  linkReplacer.replacePlainLinks(basicOutput, function (newMarkdown) {
    t.is(newMarkdown, basicOutput);
    t.end();
  });
});

test.cb('A link that is part of the reference list at the end of markdown, should not be replaced', function (t) {
  linkReplacer.replacePlainLinks(endOfFileReference, function (newMarkdown) {
    t.is(newMarkdown, endOfFileReference);
    t.end();
  });
});

test.cb('Only links that are not part of existing links should be textified, even if there is another link with the same url', function (t) {
  linkReplacer.replacePlainLinks(basicOutput + ' ' + basicInput, function (newMarkdown) {
    t.is(newMarkdown, basicOutput + ' ' + basicOutput);
    t.end();
  });
});

test.cb('Will not replace image links', function (t) {
  linkReplacer.replacePlainLinks(testImageUrl, function (newMarkdown) {
    t.is(newMarkdown, testImageUrl);
    t.end();
  });
});

test.cb('Basic link replacement with the same link appearing twice', function (t) {
  linkReplacer.replacePlainLinks(basicInput + ' ' + basicInput, function (newMarkdown) {
    t.is(newMarkdown, basicOutput + ' ' + basicOutput);
    t.end();
  });
});

test.cb('A 404 title shouldn\t be replaced', function (t) {
  var fourOhFourUrl = 'http://www.google.com/aaa';
  linkReplacer.replacePlainLinks(fourOhFourUrl, function (newMarkdown) {
    t.is(newMarkdown, fourOhFourUrl);
    t.end();
  });
});

test.cb('Can handle a typical list of wikia urls at end of article', function (t) {
  fs.readFile('/fixtures/wikialistsample.md', function (inputErr, sampleInput) {
    fs.readFile('/fixtures/wikialistsample-output.md', function (outputErr, targetOutput) {
      linkReplacer.replacePlainLinks(sampleInput, function (newMarkdown) {
        t.is(newMarkdown, targetOutput);
        t.end();
      });
    });
  });
});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-17 11:07:31<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict'

const test = require('tape')
const isPromise = require('is-promise')
const isStream = require('is-stream')
const isRoughlyEqual = require('is-roughly-equal')
const floor = require('floordate')
const client = require('./index')

const hour = 60 * 60 * 1000
const when = new Date(floor(new Date()) + 10 * hour)
const validWhen = isRoughlyEqual(2 * hour, +when)

const isHalleschesTor = (s) => s
	&& s.id === 9012103
	&& s.name === 'U Hallesches Tor'
	&& isRoughlyEqual(.00001, s.latitude, 52.497776)
	&& isRoughlyEqual(.00001, s.longitude, 13.391766)

const isKottbusserTor = (s) => s
	&& s.id === 9013102
	&& s.name === 'U Kottbusser Tor'
	&& isRoughlyEqual(.00001, s.latitude, 52.499044)
	&& isRoughlyEqual(.00001, s.longitude, 13.417748)

const isM17 = (l) => l
	&& l.id === 533
	&& l.name === 'M17'
	&& l.type === 'tram'
	&& l.agencyId === 'BVT'

test('stations() with completion', (t) => {
	t.plan(4)
	const s = client.stations({query: 'hallesc', completion: true})
	t.ok(isPromise(s))
	s.catch((err) => t.fail(err.message))
	.then((data) => {
		t.ok(Array.isArray(data))
		const s = data.find((s) => s.id === 9012103)
		t.equal(s.id, 9012103)
		t.equal(s.name, 'U Hallesches Tor')
	})
})

test('stations() without completion', (t) => {
	t.plan(4)
	const s = client.stations({query: 'hallesches tor'})
	t.ok(isStream(s))
	s.on('error', (err) => t.fail(err.message))
	.on('data', (s) => {
		if (s.id !== 9012103) return
		t.equal(s.id, 9012103)
		t.equal(s.name, 'U Hallesches Tor')
	})
	.on('end', () => t.pass('end event'))
})

test('nearby()', (t) => {
	const latitudeValid = isRoughlyEqual(.3, 52.5137344)
	const longitudeValid = isRoughlyEqual(.3, 13.4744798)
	t.plan(3 + 4 * 8)

	const s = client.nearby({
		latitude: 52.5137344,
		longitude: 13.4744798,
		results: 4,
		distance: 1000
	})
	t.ok(isPromise(s))
	s.catch((err) => t.fail(err.message))
	.then((data) => {
		t.ok(Array.isArray(data))
		t.equal(data.length, 4)
		for (let l of data) {
			t.ok(l)
			t.equal(l.type, 'station')
			t.equal(typeof l.id, 'number')
			t.equal(typeof l.latitude, 'number')
			t.ok(latitudeValid(l.latitude))
			t.equal(typeof l.longitude, 'number')
			t.ok(longitudeValid(l.longitude))
			t.ok(l.distance <= 1000)
		}
	})
})

test('station()', (t) => {
	t.plan(4 + 1 * 4)

	t.throws(() => client.station())
	t.throws(() => client.station('foo'))
	t.throws(() => client.station({}))

	const s = client.station(9012103)
	t.ok(isPromise(s))
	s.catch((err) => t.fail(err.message))
	.then((s) => {
		t.ok(isHalleschesTor(s))
		t.equal(typeof s.weight, 'number')
		t.ok(s.weight > 0)
		t.ok(Array.isArray(s.lines))
	})
})

test('departures()', (t) => {
	t.plan(5 + 7 * 3)

	t.throws(() => client.departures())
	t.throws(() => client.departures('foo'))
	t.throws(() => client.departures({}))

	const s = client.departures(9012103, {when, duration: 3})
	t.ok(isPromise(s))
	s.catch((err) => t.fail(err.message))
	.then((data) => {
		t.ok(Array.isArray(data))
		for (let dep of data) {
			t.ok(isHalleschesTor(dep.station))
			t.ok(validWhen(dep.when))
			t.ok(dep.product)
		}
	})
})

test('lines()', (t) => {
	t.plan(2 + 1 * 2)
	const s = client.lines({variants: true, name: 'M17'})
	t.ok(isStream(s))
	s.on('error', (err) => t.fail(err.message))
	.on('data', (l) => {
		t.ok(isM17(l))
		t.ok(Array.isArray(l.variants))
	})
	.on('end', () => t.pass('end event'))
})

test('line()', (t) => {
	t.plan(4 + 1 * 2)

	t.throws(() => client.line())
	t.throws(() => client.line('foo'))
	t.throws(() => client.line({}))

	const s = client.line(533)
	t.ok(isPromise(s))
	s.catch((err) => t.fail(err.message))
	.then((l) => {
		t.ok(isM17(l))
		t.ok(Array.isArray(l.variants))
	})
})

test('routes()', (t) => {
	t.plan(6 + 1 * 6)

	t.throws(() => client.routes())
	t.throws(() => client.routes('foo'))
	t.throws(() => client.routes({}))
	t.throws(() => client.routes(123))
	t.throws(() => client.routes(123, 'foo'))
	t.throws(() => client.routes(123, {}))

	const s = client.routes(9012103, 9013102, {when, results: 1})
	s.catch((err) => t.fail(err.message))
	.then((r) => {
		t.ok(Array.isArray(r))
		t.equal(r.length, 1)
		r = r[0]
		t.ok(validWhen(r.start))
		t.ok(isHalleschesTor(r.from))
		t.ok(validWhen(r.end))
		t.ok(isKottbusserTor(r.to))
	})
})

test('map()', (t) => {
	t.plan(5)

	t.throws(() => client.map())
	t.throws(() => client.map(123))
	t.throws(() => client.map({}))

	const s = client.map('bvg-night')
	t.ok(isStream(s))
	s.on('error', (err) => t.fail(err.message))
	.on('data', () => {})
	.on('end', () => t.pass('end event'))
})
<commit_msg>fix tests, part 5<commit_after>#!/usr/bin/env node
'use strict'

const test = require('tape')
const isPromise = require('is-promise')
const isStream = require('is-stream')
const isRoughlyEqual = require('is-roughly-equal')
const floor = require('floordate')
const client = require('./index')

const hour = 60 * 60 * 1000
const when = new Date(+floor(new Date(), 'day') + 10 * hour)
const validWhen = isRoughlyEqual(2 * hour, +when)

const isHalleschesTor = (s) => s
	&& s.id === 9012103
	&& s.name === 'U Hallesches Tor'
	&& isRoughlyEqual(.00001, s.latitude, 52.497776)
	&& isRoughlyEqual(.00001, s.longitude, 13.391766)

const isKottbusserTor = (s) => s
	&& s.id === 9013102
	&& s.name === 'U Kottbusser Tor'
	&& isRoughlyEqual(.00001, s.latitude, 52.499044)
	&& isRoughlyEqual(.00001, s.longitude, 13.417748)

const isM17 = (l) => l
	&& l.id === 533
	&& l.name === 'M17'
	&& l.type === 'tram'
	&& l.agencyId === 'BVT'

test('stations() with completion', (t) => {
	t.plan(4)
	const s = client.stations({query: 'hallesc', completion: true})
	t.ok(isPromise(s))
	s.catch((err) => t.fail(err.message))
	.then((data) => {
		t.ok(Array.isArray(data))
		const s = data.find((s) => s.id === 9012103)
		t.equal(s.id, 9012103)
		t.equal(s.name, 'U Hallesches Tor')
	})
})

test('stations() without completion', (t) => {
	t.plan(4)
	const s = client.stations({query: 'hallesches tor'})
	t.ok(isStream(s))
	s.on('error', (err) => t.fail(err.message))
	.on('data', (s) => {
		if (s.id !== 9012103) return
		t.equal(s.id, 9012103)
		t.equal(s.name, 'U Hallesches Tor')
	})
	.on('end', () => t.pass('end event'))
})

test('nearby()', (t) => {
	const latitudeValid = isRoughlyEqual(.3, 52.5137344)
	const longitudeValid = isRoughlyEqual(.3, 13.4744798)
	t.plan(3 + 4 * 8)

	const s = client.nearby({
		latitude: 52.5137344,
		longitude: 13.4744798,
		results: 4,
		distance: 1000
	})
	t.ok(isPromise(s))
	s.catch((err) => t.fail(err.message))
	.then((data) => {
		t.ok(Array.isArray(data))
		t.equal(data.length, 4)
		for (let l of data) {
			t.ok(l)
			t.equal(l.type, 'station')
			t.equal(typeof l.id, 'number')
			t.equal(typeof l.latitude, 'number')
			t.ok(latitudeValid(l.latitude))
			t.equal(typeof l.longitude, 'number')
			t.ok(longitudeValid(l.longitude))
			t.ok(l.distance <= 1000)
		}
	})
})

test('station()', (t) => {
	t.plan(4 + 1 * 4)

	t.throws(() => client.station())
	t.throws(() => client.station('foo'))
	t.throws(() => client.station({}))

	const s = client.station(9012103)
	t.ok(isPromise(s))
	s.catch((err) => t.fail(err.message))
	.then((s) => {
		t.ok(isHalleschesTor(s))
		t.equal(typeof s.weight, 'number')
		t.ok(s.weight > 0)
		t.ok(Array.isArray(s.lines))
	})
})

test('departures()', (t) => {
	t.plan(5 + 4 * 3)

	t.throws(() => client.departures())
	t.throws(() => client.departures('foo'))
	t.throws(() => client.departures({}))

	const s = client.departures(9012103, {when, duration: 3})
	t.ok(isPromise(s))
	s.catch((err) => t.fail(err.message))
	.then((data) => {
		t.ok(Array.isArray(data))
		for (let dep of data) {
			t.ok(isHalleschesTor(dep.station))
			t.ok(validWhen(dep.when))
			t.ok(dep.product)
		}
	})
})

test('lines()', (t) => {
	t.plan(2 + 1 * 2)
	const s = client.lines({variants: true, name: 'M17'})
	t.ok(isStream(s))
	s.on('error', (err) => t.fail(err.message))
	.on('data', (l) => {
		t.ok(isM17(l))
		t.ok(Array.isArray(l.variants))
	})
	.on('end', () => t.pass('end event'))
})

test('line()', (t) => {
	t.plan(4 + 1 * 2)

	t.throws(() => client.line())
	t.throws(() => client.line('foo'))
	t.throws(() => client.line({}))

	const s = client.line(533)
	t.ok(isPromise(s))
	s.catch((err) => t.fail(err.message))
	.then((l) => {
		t.ok(isM17(l))
		t.ok(Array.isArray(l.variants))
	})
})

test('routes()', (t) => {
	t.plan(6 + 1 * 6)

	t.throws(() => client.routes())
	t.throws(() => client.routes('foo'))
	t.throws(() => client.routes({}))
	t.throws(() => client.routes(123))
	t.throws(() => client.routes(123, 'foo'))
	t.throws(() => client.routes(123, {}))

	const s = client.routes(9012103, 9013102, {when, results: 1})
	s.catch((err) => t.fail(err.message))
	.then((r) => {
		t.ok(Array.isArray(r))
		t.equal(r.length, 1)
		r = r[0]
		t.ok(validWhen(r.start))
		t.ok(isHalleschesTor(r.from))
		t.ok(validWhen(r.end))
		t.ok(isKottbusserTor(r.to))
	})
})

test('map()', (t) => {
	t.plan(5)

	t.throws(() => client.map())
	t.throws(() => client.map(123))
	t.throws(() => client.map({}))

	const s = client.map('bvg-night')
	t.ok(isStream(s))
	s.on('error', (err) => t.fail(err.message))
	.on('data', () => {})
	.on('end', () => t.pass('end event'))
})
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-17 11:47:28<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var boxpack = require('./'),
    blocks = [
        { width: 200, height: 200 },
        { width: 100, height: 100 },
        { width: 100, height: 100 },
        { width: 100, height: 200 },
        { width: 50, height: 50 },
        { width: 10, height: 10 }
    ];

console.log(boxpack(blocks, {maxWidth: 200}));
<commit_msg>removed useless test.js<commit_after><|endoftext|>


<commit_before>var dropdown;

function setup() {
  dropdown = createSelect(); // or create dropdown?
  dropdown.option('apple','1');
  dropdown.option('orange','2');
  //dropdown.option('pear', 'pear');
  dropdown.option('pear');

  dropdown.value('2');

  dropdown.changed(mySelectEvent);
}

function mousePressed() {
  println(dropdown.value());
}

function draw() {
  background(0);
  if (dropdown.value() === 'pear') {
    background(0, 255, 0);
  }
}

function mySelectEvent() {
  var selected = this.selected();
  if (selected === 'pear') {
    console.log("it's a pear!");
  }
}

<commit_msg>dropdown test<commit_after>var dropdown;

function setup() {
  dropdown = createSelect(); // or create dropdown?

  // just mucking around
  dropdown.option('apple','1');
  dropdown.option('orange','2');
  dropdown.option('pear');

  // Set what it starts as
  dropdown.value('2');

  dropdown.changed(mySelectEvent);
}

function draw() {
  background(0);
  if (dropdown.selected() === '1') {
    background(255, 0, 0);
  }
}

function mySelectEvent() {
  var selected = this.selected();
  if (selected === 'pear') {
    console.log("it's a pear!");
  }
}

<|endoftext|>


<commit_before>odoo.define('im_livechat.im_livechat', function (require) {
"use strict";

var bus = require('bus.bus').bus;
var config = require('web.config');
var core = require('web.core');
var session = require('web.session');
var time = require('web.time');
var utils = require('web.utils');
var Widget = require('web.Widget');

var ChatWindow = require('mail.ChatWindow');

var _t = core._t;
var QWeb = core.qweb;

var LivechatButton = Widget.extend({
    className:"openerp o_livechat_button hidden-print",

    events: {
        "click": "open_chat"
    },

    init: function (parent, server_url, options) {
        this._super(parent);
        this.options = _.defaults(options || {}, {
            input_placeholder: _t('Ask something ...'),
            default_username: _t("Visitor"),
            button_text: _t("Chat with one of our collaborators"),
            default_message: _t("How may I help you?"),
        });
        this.channel = null;
        this.chat_window = null;
        this.messages = [];
        this.server_url = server_url;
    },

    willStart: function () {
        var self = this;
        var cookie = utils.get_cookie('im_livechat_session');
        var ready;
        if (!cookie) {
            ready = session.rpc("/im_livechat/init", {channel_id: this.options.channel_id}).then(function (result) {
                if (!result.available_for_me) {
                    return $.Deferred().reject();
                }
                self.rule = result.rule;
            });
        } else {
            var channel = JSON.parse(cookie);
            ready = session.rpc("/mail/chat_history", {uuid: channel.uuid, limit: 100}).then(function (history) {
                self.history = history;
            });
        }
        return ready.then(this.load_qweb_template.bind(this));
    },

    start: function () {
        this.$el.text(this.options.button_text);
        var small_screen = config.device.size_class === config.device.SIZES.XS;
        if (this.history) {
            _.each(this.history.reverse(), this.add_message.bind(this));
            this.open_chat();
        } else if (!small_screen && this.rule.action === 'auto_popup') {
            var auto_popup_cookie = utils.get_cookie('im_livechat_auto_popup');
            if (!auto_popup_cookie || JSON.parse(auto_popup_cookie)) {
                this.auto_popup_timeout = setTimeout(this.open_chat.bind(this), this.rule.auto_popup_timer*1000);
            }
        }
        bus.on('notification', this, function (notifications) {
            var self = this;
            _.each(notifications, function (notification) {
                if (self.channel && (notification[0] === self.channel.uuid)) {
                    self.add_message(notification[1]);
                    self.render_messages();
                    if (self.chat_window.folded || !self.chat_window.thread.is_at_bottom()) {
                        self.chat_window.update_unread(self.chat_window.unread_msgs+1);
                    }
                }
            });
        });
        return this._super();
    },

    load_qweb_template: function(){
        var xml_files = ['/mail/static/src/xml/chat_window.xml',
                         '/mail/static/src/xml/thread.xml',
                         '/im_livechat/static/src/xml/im_livechat.xml'];
        var defs = _.map(xml_files, function (tmpl) {
            return session.rpc('/web/proxy/load', {path: tmpl}).then(function (xml) {
                QWeb.add_template(xml);
            });
        });
        return $.when.apply($, defs);
    },

    open_chat: _.debounce(function () {
        if (this.opening_chat) {
            return;
        }
        var self = this;
        var cookie = utils.get_cookie('im_livechat_session');
        var def;
        this.opening_chat = true;
        clearTimeout(this.auto_popup_timeout);
        if (cookie) {
            def = $.when(JSON.parse(cookie));
        } else {
            this.messages = []; // re-initialize messages cache
            def = session.rpc('/im_livechat/get_session', {
                channel_id : this.options.channel_id,
                anonymous_name : this.options.default_username,
            }, {shadow: true});
        }
        def.then(function (channel) {
            if (!channel || !channel.operator_pid) {
                alert(_t("None of our collaborators seems to be available, please try again later."));
            } else {
                self.channel = channel;
                self.open_chat_window(channel);
                self.send_welcome_message();
                self.render_messages();

                bus.add_channel(channel.uuid);
                bus.start_polling();

                utils.set_cookie('im_livechat_session', JSON.stringify(channel), 60*60);
                utils.set_cookie('im_livechat_auto_popup', JSON.stringify(false), 60*60);
            }
        }).always(function () {
            self.opening_chat = false;
        });
    }, 200, true),

    open_chat_window: function (channel) {
        var self = this;
        var options = {
            display_stars: false,
            placeholder: this.options.input_placeholder || "",
        };
        var is_folded = (channel.state === 'folded');
        this.chat_window = new ChatWindow(this, channel.id, channel.name, is_folded, channel.message_unread_counter, options);
        this.chat_window.appendTo($('body')).then(function () {
            self.chat_window.$el.css({right: 0, bottom: 0});
            self.$el.hide();
        });
        this.chat_window.on("close_chat_session", this, function () {
            var input_disabled = this.chat_window.$(".o_chat_composer input").prop('disabled');
            var ask_fb = !input_disabled && _.find(this.messages, function (msg) {
                return msg.id !== '_welcome';
            });
            if (ask_fb) {
                this.chat_window.toggle_fold(false);
                this.ask_feedback();
            } else {
                this.close_chat();
            }
        });
        this.chat_window.on("post_message", this, function (message) {
            self.send_message(message).fail(function (error, e) {
                e.preventDefault();
                return self.send_message(message); // try again just in case
            });
        });
        this.chat_window.on("fold_channel", this, function () {
            this.channel.state = (this.channel.state === 'open') ? 'folded' : 'open';
            utils.set_cookie('im_livechat_session', JSON.stringify(this.channel), 60*60);
        });
        this.chat_window.thread.$el.on("scroll", null, _.debounce(function () {
            if (self.chat_window.thread.is_at_bottom()) {
                self.chat_window.update_unread(0);
            }
        }, 100));
    },

    close_chat: function () {
        this.chat_window.destroy();
        utils.set_cookie('im_livechat_session', "", -1); // remove cookie
    },

    send_message: function (message) {
        var self = this;
        return session
            .rpc("/mail/chat_post", {uuid: this.channel.uuid, message_content: message.content})
            .then(function () {
                self.chat_window.thread.scroll_to();
            });
    },

    add_message: function (data, options) {
        var msg = {
            id: data.id,
            attachment_ids: data.attachment_ids,
            author_id: data.author_id,
            body: data.body,
            date: moment(time.str_to_datetime(data.date)),
            is_needaction: false,
            is_note: data.is_note,
            customer_email_data: []
        };

        // Compute displayed author name or email
        msg.displayed_author = msg.author_id && msg.author_id[1] ||
                               this.options.default_username;

        // Compute the avatar_url
        msg.avatar_src = this.server_url;
        if (msg.author_id && msg.author_id[0]) {
            msg.avatar_src += "/web/image/res.partner/" + msg.author_id[0] + "/image_small";
        } else {
            msg.avatar_src += "/mail/static/src/img/smiley/avatar.jpg";
        }

        if (options && options.prepend) {
            this.messages.unshift(msg);
        } else {
            this.messages.push(msg);
        }
    },

    render_messages: function () {
        var should_scroll = !this.chat_window.folded && this.chat_window.thread.is_at_bottom();
        this.chat_window.render(this.messages);
        if (should_scroll) {
            this.chat_window.thread.scroll_to();
        }
    },

    send_welcome_message: function () {
        if (this.options.default_message) {
            this.add_message({
                id: '_welcome',
                attachment_ids: [],
                author_id: this.channel.operator_pid,
                body: this.options.default_message,
                channel_ids: [this.channel.id],
                date: time.datetime_to_str(new Date()),
                tracking_value_ids: [],
            }, {prepend: true});
        }
    },

    ask_feedback: function () {
        this.chat_window.$(".o_chat_composer input").prop('disabled', true);

        var feedback = new Feedback(this, this.channel.uuid);
        feedback.replace(this.chat_window.thread.$el);

        feedback.on("send_message", this, this.send_message);
        feedback.on("feedback_sent", this, this.close_chat);
    }
});

/*
 * Rating for Livechat
 *
 * This widget displays the 3 rating smileys, and a textarea to add a reason
 * (only for red smiley), and sends the user feedback to the server.
 */
var Feedback = Widget.extend({
    template: "im_livechat.FeedBack",

    events: {
        'click .o_livechat_rating_choices img': 'on_click_smiley',
        'click .o_livechat_no_feedback em': 'on_click_no_feedback',
        'click .o_rating_submit_button': 'on_click_send',
    },

    init: function (parent, channel_uuid) {
        this._super(parent);
        this.channel_uuid = channel_uuid;
        this.server_origin = session.origin;
        this.rating = undefined;
    },

    on_click_smiley: function (ev) {
        this.rating = parseInt($(ev.currentTarget).data('value'));
        this.$('.o_livechat_rating_choices img').removeClass('selected');
        this.$('.o_livechat_rating_choices img[data-value="'+this.rating+'"]').addClass('selected');

        // only display textearea if bad smiley selected
        var close_chat = false;
        if (this.rating === 0) {
            this.$('.o_livechat_rating_reason').show();
        } else {
            this.$('.o_livechat_rating_reason').hide();
            close_chat = true;
        }
        this._send_feedback({close: close_chat});
    },

    on_click_no_feedback: function () {
        this.trigger("feedback_sent"); // will close the chat
    },

    on_click_send: function () {
        if (_.isNumber(this.rating)) {
            this._send_feedback({ reason: this.$('textarea').val(), close: true });
        }
    },

    _send_feedback: function (options) {
        var self = this;
        var args = {
            uuid: this.channel_uuid,
            rate: this.rating,
            reason : options.reason
        };
        return session.rpc('/im_livechat/feedback', args).then(function () {
            if (options.close) {
                var content = _.str.sprintf(_t("Rating: :rating_%d"), self.rating);
                if (options.reason) {
                    content += " \n" + options.reason;
                }
                self.trigger("send_message", {content: content});
                self.trigger("feedback_sent"); // will close the chat
            }
        });
    }
});

return {
    LivechatButton: LivechatButton,
    Feedback: Feedback,
};

});
<commit_msg>[FIX] im_livechat: bad rating=1 not 0 w/ 75d3121c<commit_after>odoo.define('im_livechat.im_livechat', function (require) {
"use strict";

var bus = require('bus.bus').bus;
var config = require('web.config');
var core = require('web.core');
var session = require('web.session');
var time = require('web.time');
var utils = require('web.utils');
var Widget = require('web.Widget');

var ChatWindow = require('mail.ChatWindow');

var _t = core._t;
var QWeb = core.qweb;

var LivechatButton = Widget.extend({
    className:"openerp o_livechat_button hidden-print",

    events: {
        "click": "open_chat"
    },

    init: function (parent, server_url, options) {
        this._super(parent);
        this.options = _.defaults(options || {}, {
            input_placeholder: _t('Ask something ...'),
            default_username: _t("Visitor"),
            button_text: _t("Chat with one of our collaborators"),
            default_message: _t("How may I help you?"),
        });
        this.channel = null;
        this.chat_window = null;
        this.messages = [];
        this.server_url = server_url;
    },

    willStart: function () {
        var self = this;
        var cookie = utils.get_cookie('im_livechat_session');
        var ready;
        if (!cookie) {
            ready = session.rpc("/im_livechat/init", {channel_id: this.options.channel_id}).then(function (result) {
                if (!result.available_for_me) {
                    return $.Deferred().reject();
                }
                self.rule = result.rule;
            });
        } else {
            var channel = JSON.parse(cookie);
            ready = session.rpc("/mail/chat_history", {uuid: channel.uuid, limit: 100}).then(function (history) {
                self.history = history;
            });
        }
        return ready.then(this.load_qweb_template.bind(this));
    },

    start: function () {
        this.$el.text(this.options.button_text);
        var small_screen = config.device.size_class === config.device.SIZES.XS;
        if (this.history) {
            _.each(this.history.reverse(), this.add_message.bind(this));
            this.open_chat();
        } else if (!small_screen && this.rule.action === 'auto_popup') {
            var auto_popup_cookie = utils.get_cookie('im_livechat_auto_popup');
            if (!auto_popup_cookie || JSON.parse(auto_popup_cookie)) {
                this.auto_popup_timeout = setTimeout(this.open_chat.bind(this), this.rule.auto_popup_timer*1000);
            }
        }
        bus.on('notification', this, function (notifications) {
            var self = this;
            _.each(notifications, function (notification) {
                if (self.channel && (notification[0] === self.channel.uuid)) {
                    self.add_message(notification[1]);
                    self.render_messages();
                    if (self.chat_window.folded || !self.chat_window.thread.is_at_bottom()) {
                        self.chat_window.update_unread(self.chat_window.unread_msgs+1);
                    }
                }
            });
        });
        return this._super();
    },

    load_qweb_template: function(){
        var xml_files = ['/mail/static/src/xml/chat_window.xml',
                         '/mail/static/src/xml/thread.xml',
                         '/im_livechat/static/src/xml/im_livechat.xml'];
        var defs = _.map(xml_files, function (tmpl) {
            return session.rpc('/web/proxy/load', {path: tmpl}).then(function (xml) {
                QWeb.add_template(xml);
            });
        });
        return $.when.apply($, defs);
    },

    open_chat: _.debounce(function () {
        if (this.opening_chat) {
            return;
        }
        var self = this;
        var cookie = utils.get_cookie('im_livechat_session');
        var def;
        this.opening_chat = true;
        clearTimeout(this.auto_popup_timeout);
        if (cookie) {
            def = $.when(JSON.parse(cookie));
        } else {
            this.messages = []; // re-initialize messages cache
            def = session.rpc('/im_livechat/get_session', {
                channel_id : this.options.channel_id,
                anonymous_name : this.options.default_username,
            }, {shadow: true});
        }
        def.then(function (channel) {
            if (!channel || !channel.operator_pid) {
                alert(_t("None of our collaborators seems to be available, please try again later."));
            } else {
                self.channel = channel;
                self.open_chat_window(channel);
                self.send_welcome_message();
                self.render_messages();

                bus.add_channel(channel.uuid);
                bus.start_polling();

                utils.set_cookie('im_livechat_session', JSON.stringify(channel), 60*60);
                utils.set_cookie('im_livechat_auto_popup', JSON.stringify(false), 60*60);
            }
        }).always(function () {
            self.opening_chat = false;
        });
    }, 200, true),

    open_chat_window: function (channel) {
        var self = this;
        var options = {
            display_stars: false,
            placeholder: this.options.input_placeholder || "",
        };
        var is_folded = (channel.state === 'folded');
        this.chat_window = new ChatWindow(this, channel.id, channel.name, is_folded, channel.message_unread_counter, options);
        this.chat_window.appendTo($('body')).then(function () {
            self.chat_window.$el.css({right: 0, bottom: 0});
            self.$el.hide();
        });
        this.chat_window.on("close_chat_session", this, function () {
            var input_disabled = this.chat_window.$(".o_chat_composer input").prop('disabled');
            var ask_fb = !input_disabled && _.find(this.messages, function (msg) {
                return msg.id !== '_welcome';
            });
            if (ask_fb) {
                this.chat_window.toggle_fold(false);
                this.ask_feedback();
            } else {
                this.close_chat();
            }
        });
        this.chat_window.on("post_message", this, function (message) {
            self.send_message(message).fail(function (error, e) {
                e.preventDefault();
                return self.send_message(message); // try again just in case
            });
        });
        this.chat_window.on("fold_channel", this, function () {
            this.channel.state = (this.channel.state === 'open') ? 'folded' : 'open';
            utils.set_cookie('im_livechat_session', JSON.stringify(this.channel), 60*60);
        });
        this.chat_window.thread.$el.on("scroll", null, _.debounce(function () {
            if (self.chat_window.thread.is_at_bottom()) {
                self.chat_window.update_unread(0);
            }
        }, 100));
    },

    close_chat: function () {
        this.chat_window.destroy();
        utils.set_cookie('im_livechat_session', "", -1); // remove cookie
    },

    send_message: function (message) {
        var self = this;
        return session
            .rpc("/mail/chat_post", {uuid: this.channel.uuid, message_content: message.content})
            .then(function () {
                self.chat_window.thread.scroll_to();
            });
    },

    add_message: function (data, options) {
        var msg = {
            id: data.id,
            attachment_ids: data.attachment_ids,
            author_id: data.author_id,
            body: data.body,
            date: moment(time.str_to_datetime(data.date)),
            is_needaction: false,
            is_note: data.is_note,
            customer_email_data: []
        };

        // Compute displayed author name or email
        msg.displayed_author = msg.author_id && msg.author_id[1] ||
                               this.options.default_username;

        // Compute the avatar_url
        msg.avatar_src = this.server_url;
        if (msg.author_id && msg.author_id[0]) {
            msg.avatar_src += "/web/image/res.partner/" + msg.author_id[0] + "/image_small";
        } else {
            msg.avatar_src += "/mail/static/src/img/smiley/avatar.jpg";
        }

        if (options && options.prepend) {
            this.messages.unshift(msg);
        } else {
            this.messages.push(msg);
        }
    },

    render_messages: function () {
        var should_scroll = !this.chat_window.folded && this.chat_window.thread.is_at_bottom();
        this.chat_window.render(this.messages);
        if (should_scroll) {
            this.chat_window.thread.scroll_to();
        }
    },

    send_welcome_message: function () {
        if (this.options.default_message) {
            this.add_message({
                id: '_welcome',
                attachment_ids: [],
                author_id: this.channel.operator_pid,
                body: this.options.default_message,
                channel_ids: [this.channel.id],
                date: time.datetime_to_str(new Date()),
                tracking_value_ids: [],
            }, {prepend: true});
        }
    },

    ask_feedback: function () {
        this.chat_window.$(".o_chat_composer input").prop('disabled', true);

        var feedback = new Feedback(this, this.channel.uuid);
        feedback.replace(this.chat_window.thread.$el);

        feedback.on("send_message", this, this.send_message);
        feedback.on("feedback_sent", this, this.close_chat);
    }
});

/*
 * Rating for Livechat
 *
 * This widget displays the 3 rating smileys, and a textarea to add a reason
 * (only for red smiley), and sends the user feedback to the server.
 */
var Feedback = Widget.extend({
    template: "im_livechat.FeedBack",

    events: {
        'click .o_livechat_rating_choices img': 'on_click_smiley',
        'click .o_livechat_no_feedback em': 'on_click_no_feedback',
        'click .o_rating_submit_button': 'on_click_send',
    },

    init: function (parent, channel_uuid) {
        this._super(parent);
        this.channel_uuid = channel_uuid;
        this.server_origin = session.origin;
        this.rating = undefined;
    },

    on_click_smiley: function (ev) {
        this.rating = parseInt($(ev.currentTarget).data('value'));
        this.$('.o_livechat_rating_choices img').removeClass('selected');
        this.$('.o_livechat_rating_choices img[data-value="'+this.rating+'"]').addClass('selected');

        // only display textearea if bad smiley selected
        var close_chat = false;
        if (this.rating === 1) {
            this.$('.o_livechat_rating_reason').show();
        } else {
            this.$('.o_livechat_rating_reason').hide();
            close_chat = true;
        }
        this._send_feedback({close: close_chat});
    },

    on_click_no_feedback: function () {
        this.trigger("feedback_sent"); // will close the chat
    },

    on_click_send: function () {
        if (_.isNumber(this.rating)) {
            this._send_feedback({ reason: this.$('textarea').val(), close: true });
        }
    },

    _send_feedback: function (options) {
        var self = this;
        var args = {
            uuid: this.channel_uuid,
            rate: this.rating,
            reason : options.reason
        };
        return session.rpc('/im_livechat/feedback', args).then(function () {
            if (options.close) {
                var content = _.str.sprintf(_t("Rating: :rating_%d"), self.rating);
                if (options.reason) {
                    content += " \n" + options.reason;
                }
                self.trigger("send_message", {content: content});
                self.trigger("feedback_sent"); // will close the chat
            }
        });
    }
});

return {
    LivechatButton: LivechatButton,
    Feedback: Feedback,
};

});
<|endoftext|>


<commit_before>$("#inputBox").on("paste", function() {
  setTimeout(function() {
    input(1);
  }, 0);
});

$("#inputBox").on("focus", function() {
  $(this).attr("placeholder", "(End your search with \\ for Quick Search, add 'l' for lyric videos)");
  setTimeout(function() {
    $("#inputBox").attr("placeholder", placeholder);
  }, 4000);

  if ($(window).width() <= 600) {
    $("footer").css("display", "none");
  }
});

$("#inputBox").on("blur", function() {
  if ($(window).width() <= 600) {
    $("footer").css("display", "block");
  }
});

$("#playlistNameBox").on("blur", function() {
  input(2);
});

window.addEventListener("keydown", function(e) {
  if ((!$("#inputBox").is(":focus")
       || $("#inputBox").val() == ""
       || $("#inputBox").val() == " ")
      && !$("#playlistNameBox").is(":focus")) {
    switch (e.code) {
      case "ArrowLeft":
      case "MediaTrackPrevious":
        e.preventDefault();
        backVideo();
        break;
      case "ArrowRight":
      case "MediaTrackNext":
        e.preventDefault();
        forwardVideo();
        break;
      case "Space":
      case "MediaPlayPause":
        e.preventDefault();
        if ($("#inputBox").val() === " ") {
          $("#inputBox").val("");
        }
        if (videoPaused) {
          player.playVideo();
        }
        else {
          player.pauseVideo();
        }
        break;
    }
  }
  if ($("#inputBox").is(":focus")) {
    switch (e.code) {
      case "Backslash":
        e.preventDefault();
        if (e.key !== "|") {
          var query = $("#inputBox").val();
          query = query.replace("\\", "");
          if (query.slice(-2) === " l") {
            query = query + "yric";
          }
          quickSearch(query);
        }
        else {
          //added for | hotkey for popup (now search) thing requested
          hotkeySearchClose = true;
          toggleSearchClose();
          input(0);
        }
        break;
      case "Enter":
        input(0);
        break;
    }
  }
  if (!$("#inputBox").is(":focus") && !$("#playlistNameBox").is(":focus")) {
    switch (e.code) {
      case "KeyR":
        e.preventDefault();
        playlistFeatures.autoplay();
        break;
      case "KeyZ":
        e.preventDefault();
        toggleZen();
        break;
    }
  }
});

$("#youtubeContainer").click(function() {
  if (stationRemote) {
    if ($("#remotePauseIcon").hasClass("fa-play")) {
      $("#remotePauseIcon").removeClass("fa-play").addClass("fa-pause");
      sendStation("videofunctionsplay");
    }
    else {
      $("#remotePauseIcon").removeClass("fa-pause").addClass("fa-play");
      sendStation("videofunctionspause");
    }
  }
});

// * These are the event listeners for stuff that's dragged and dropped

document.addEventListener("drop", function(event) {
  event.preventDefault();
  var data = event.dataTransfer.getData("URL");

  $("#inputBox").val(data);
  input(1);
});
document.addEventListener("dragover", function(event) {
  event.preventDefault();
});
<commit_msg>Update events.js<commit_after>/**
  Copyright 2018 LNFWebsite
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
**/

$("#inputBox").on("paste", function() {
  setTimeout(function() {
    input(1);
  }, 0);
});

$("#inputBox").on("focus", function() {
  $(this).attr("placeholder", "(End your search with \\ for Quick Search, add 'l' for lyric videos)");
  setTimeout(function() {
    $("#inputBox").attr("placeholder", placeholder);
  }, 4000);

  if ($(window).width() <= 600) {
    $("footer").css("display", "none");
  }
});

$("#inputBox").on("blur", function() {
  if ($(window).width() <= 600) {
    $("footer").css("display", "block");
  }
});

$("#playlistNameBox").on("blur", function() {
  input(2);
});

window.addEventListener("keydown", function(e) {
  if ((!$("#inputBox").is(":focus")
       || $("#inputBox").val() == ""
       || $("#inputBox").val() == " ")
      && !$("#playlistNameBox").is(":focus")) {
    switch (e.code) {
      case "ArrowLeft":
      case "MediaTrackPrevious":
        e.preventDefault();
        backVideo();
        break;
      case "ArrowRight":
      case "MediaTrackNext":
        e.preventDefault();
        forwardVideo();
        break;
      case "Space":
      case "MediaPlayPause":
        e.preventDefault();
        if ($("#inputBox").val() === " ") {
          $("#inputBox").val("");
        }
        if (videoPaused) {
          player.playVideo();
        }
        else {
          player.pauseVideo();
        }
        break;
    }
  }
  if ($("#inputBox").is(":focus")) {
    switch (e.code) {
      case "Backslash":
        e.preventDefault();
        if (e.key !== "|") {
          var query = $("#inputBox").val();
          query = query.replace("\\", "");
          if (query.slice(-2) === " l") {
            query = query + "yric";
          }
          quickSearch(query);
        }
        else {
          //added for | hotkey for popup (now search) thing requested
          hotkeySearchClose = true;
          toggleSearchClose();
          input(0);
        }
        break;
      case "Enter":
        input(0);
        break;
    }
  }
  if (!$("#inputBox").is(":focus") && !$("#playlistNameBox").is(":focus")) {
    switch (e.code) {
      case "KeyR":
        e.preventDefault();
        playlistFeatures.autoplay();
        break;
      case "KeyZ":
        e.preventDefault();
        toggleZen();
        break;
    }
  }
});

$("#youtubeContainer").click(function() {
  if (stationRemote) {
    if ($("#remotePauseIcon").hasClass("fa-play")) {
      $("#remotePauseIcon").removeClass("fa-play").addClass("fa-pause");
      sendStation("videofunctionsplay");
    }
    else {
      $("#remotePauseIcon").removeClass("fa-pause").addClass("fa-play");
      sendStation("videofunctionspause");
    }
  }
});

// * These are the event listeners for stuff that's dragged and dropped

document.addEventListener("drop", function(event) {
  event.preventDefault();
  var data = event.dataTransfer.getData("URL");

  $("#inputBox").val(data);
  input(1);
});
document.addEventListener("dragover", function(event) {
  event.preventDefault();
});
<|endoftext|>