Browse Source

Enable more linting rules (#486)

pull/490/head
Gabe Gorelick 7 years ago committed by Sergi Almacellas Abellana
parent
commit
6c3cdc2130
  1. 40
      .eslintrc.js
  2. 2
      Gruntfile.js
  3. 79
      papaparse.js
  4. 16
      tests/node-tests.js
  5. 38
      tests/test-cases.js
  6. 4
      tests/test.js

40
.eslintrc.js

@ -20,8 +20,8 @@ module.exports = {
"arrow-body-style": "error", "arrow-body-style": "error",
"arrow-parens": "error", "arrow-parens": "error",
"arrow-spacing": "error", "arrow-spacing": "error",
"block-scoped-var": "off", "block-scoped-var": "error",
"block-spacing": "off", "block-spacing": "error",
"brace-style": "off", "brace-style": "off",
"callback-return": "error", "callback-return": "error",
"camelcase": ["error", {"properties": "never"}], "camelcase": ["error", {"properties": "never"}],
@ -44,8 +44,8 @@ module.exports = {
"default-case": "error", "default-case": "error",
"dot-location": "error", "dot-location": "error",
"dot-notation": "error", "dot-notation": "error",
"eol-last": "off", "eol-last": "error",
"eqeqeq": "off", "eqeqeq": "error",
"for-direction": "error", "for-direction": "error",
"func-call-spacing": "error", "func-call-spacing": "error",
"func-name-matching": "error", "func-name-matching": "error",
@ -64,11 +64,14 @@ module.exports = {
"id-length": "off", "id-length": "off",
"id-match": "error", "id-match": "error",
"implicit-arrow-linebreak": "error", "implicit-arrow-linebreak": "error",
"indent": ["error", "tab"], "indent": [
"error",
"tab"
],
"indent-legacy": "off", "indent-legacy": "off",
"init-declarations": "off", "init-declarations": "off",
"jsx-quotes": "error", "jsx-quotes": "error",
"key-spacing": "off", "key-spacing": "error",
"keyword-spacing": "off", "keyword-spacing": "off",
"line-comment-position": "off", "line-comment-position": "off",
"linebreak-style": [ "linebreak-style": [
@ -90,11 +93,11 @@ module.exports = {
"error", "error",
"always-multiline" "always-multiline"
], ],
"new-parens": "off", "new-parens": "error",
"newline-after-var": "off", "newline-after-var": "off",
"newline-before-return": "off", "newline-before-return": "off",
"newline-per-chained-call": "off", "newline-per-chained-call": "off",
"no-alert": "off", "no-alert": "error",
"no-array-constructor": "error", "no-array-constructor": "error",
"no-await-in-loop": "error", "no-await-in-loop": "error",
"no-bitwise": "error", "no-bitwise": "error",
@ -163,11 +166,11 @@ module.exports = {
"no-restricted-modules": "error", "no-restricted-modules": "error",
"no-restricted-properties": "error", "no-restricted-properties": "error",
"no-restricted-syntax": "error", "no-restricted-syntax": "error",
"no-return-assign": "off", "no-return-assign": "error",
"no-return-await": "error", "no-return-await": "error",
"no-script-url": "error", "no-script-url": "error",
"no-self-compare": "error", "no-self-compare": "error",
"no-sequences": "off", "no-sequences": "error",
"no-shadow": "off", "no-shadow": "off",
"no-shadow-restricted-names": "error", "no-shadow-restricted-names": "error",
"no-spaced-func": "error", "no-spaced-func": "error",
@ -192,7 +195,7 @@ module.exports = {
"no-useless-rename": "error", "no-useless-rename": "error",
"no-useless-return": "off", "no-useless-return": "off",
"no-var": "off", "no-var": "off",
"no-void": "off", "no-void": "error",
"no-warning-comments": "error", "no-warning-comments": "error",
"no-whitespace-before-property": "error", "no-whitespace-before-property": "error",
"no-with": "error", "no-with": "error",
@ -200,7 +203,7 @@ module.exports = {
"error", "error",
"any" "any"
], ],
"object-curly-newline": "off", "object-curly-newline": ["error", {"consistent": true}],
"object-curly-spacing": "off", "object-curly-spacing": "off",
"object-shorthand": "off", "object-shorthand": "off",
"one-var": "off", "one-var": "off",
@ -230,8 +233,8 @@ module.exports = {
"require-await": "error", "require-await": "error",
"require-jsdoc": "off", "require-jsdoc": "off",
"rest-spread-spacing": "error", "rest-spread-spacing": "error",
"semi": "off", "semi": "error",
"semi-spacing": "off", "semi-spacing": "error",
"semi-style": [ "semi-style": [
"error", "error",
"last" "last"
@ -239,13 +242,16 @@ module.exports = {
"sort-imports": "error", "sort-imports": "error",
"sort-keys": "off", "sort-keys": "off",
"sort-vars": "off", "sort-vars": "off",
"space-before-blocks": "off", "space-before-blocks": "error",
"space-before-function-paren": "off", "space-before-function-paren": [
"error",
"never"
],
"space-in-parens": [ "space-in-parens": [
"error", "error",
"never" "never"
], ],
"space-infix-ops": "off", "space-infix-ops": "error",
"space-unary-ops": [ "space-unary-ops": [
"error", "error",
{ {

2
Gruntfile.js

@ -18,4 +18,4 @@ module.exports = function(grunt) {
grunt.registerTask('build', ['uglify']); grunt.registerTask('build', ['uglify']);
grunt.registerTask('default', ['uglify']); grunt.registerTask('default', ['uglify']);
} };

79
papaparse.js

@ -28,7 +28,7 @@
{ {
'use strict'; 'use strict';
var global = (function () { var global = (function() {
// alternative method, similar to `Function('return this')()` // alternative method, similar to `Function('return this')()`
// but without using `eval` (which is disabled when // but without using `eval` (which is disabled when
// using Content Security Policy). // using Content Security Policy).
@ -163,7 +163,7 @@
queue.splice(0, 1); queue.splice(0, 1);
parseNextFile(); parseNextFile();
} }
} };
} }
@ -183,7 +183,7 @@
} }
else else
{ {
document.addEventListener('DOMContentLoaded', function () { document.addEventListener('DOMContentLoaded', function() {
LOADED_SYNC = true; LOADED_SYNC = true;
}, true); }, true);
} }
@ -399,7 +399,7 @@
if (typeof str === 'undefined' || str === null) if (typeof str === 'undefined' || str === null)
return ''; return '';
str = str.toString().replace(quoteCharRegex, _quoteChar+_quoteChar); str = str.toString().replace(quoteCharRegex, _quoteChar + _quoteChar);
var needsQuotes = (typeof _quotes === 'boolean' && _quotes) var needsQuotes = (typeof _quotes === 'boolean' && _quotes)
|| (_quotes instanceof Array && _quotes[col]) || (_quotes instanceof Array && _quotes[col])
@ -602,7 +602,7 @@
if (this._config.chunkSize) if (this._config.chunkSize)
{ {
var end = this._start + this._config.chunkSize - 1; // minus one because byte range is inclusive var end = this._start + this._config.chunkSize - 1; // minus one because byte range is inclusive
xhr.setRequestHeader('Range', 'bytes='+this._start+'-'+end); xhr.setRequestHeader('Range', 'bytes=' + this._start + '-' + end);
xhr.setRequestHeader('If-None-Match', 'webkit-no-cache'); // https://bugs.webkit.org/show_bug.cgi?id=82672 xhr.setRequestHeader('If-None-Match', 'webkit-no-cache'); // https://bugs.webkit.org/show_bug.cgi?id=82672
} }
@ -617,11 +617,11 @@
this._chunkError(); this._chunkError();
else else
this._start += this._config.chunkSize; this._start += this._config.chunkSize;
} };
this._chunkLoaded = function() this._chunkLoaded = function()
{ {
if (xhr.readyState != 4) if (xhr.readyState !== 4)
return; return;
if (xhr.status < 200 || xhr.status >= 400) if (xhr.status < 200 || xhr.status >= 400)
@ -632,13 +632,13 @@
this._finished = !this._config.chunkSize || this._start > getFileSize(xhr); this._finished = !this._config.chunkSize || this._start > getFileSize(xhr);
this.parseChunk(xhr.responseText); this.parseChunk(xhr.responseText);
} };
this._chunkError = function(errorMessage) this._chunkError = function(errorMessage)
{ {
var errorText = xhr.statusText || errorMessage; var errorText = xhr.statusText || errorMessage;
this._sendError(new Error(errorText)); this._sendError(new Error(errorText));
} };
function getFileSize(xhr) function getFileSize(xhr)
{ {
@ -687,7 +687,7 @@
{ {
if (!this._finished && (!this._config.preview || this._rowCount < this._config.preview)) if (!this._finished && (!this._config.preview || this._rowCount < this._config.preview))
this._readChunk(); this._readChunk();
} };
this._readChunk = function() this._readChunk = function()
{ {
@ -700,7 +700,7 @@
var txt = reader.readAsText(input, this._config.encoding); var txt = reader.readAsText(input, this._config.encoding);
if (!usingAsyncReader) if (!usingAsyncReader)
this._chunkLoaded({ target: { result: txt } }); // mimic the async signature this._chunkLoaded({ target: { result: txt } }); // mimic the async signature
} };
this._chunkLoaded = function(event) this._chunkLoaded = function(event)
{ {
@ -708,12 +708,12 @@
this._start += this._config.chunkSize; this._start += this._config.chunkSize;
this._finished = !this._config.chunkSize || this._start >= this._input.size; this._finished = !this._config.chunkSize || this._start >= this._input.size;
this.parseChunk(event.target.result); this.parseChunk(event.target.result);
} };
this._chunkError = function() this._chunkError = function()
{ {
this._sendError(reader.error); this._sendError(reader.error);
} };
} }
FileStreamer.prototype = Object.create(ChunkStreamer.prototype); FileStreamer.prototype = Object.create(ChunkStreamer.prototype);
@ -730,7 +730,7 @@
{ {
remaining = s; remaining = s;
return this._nextChunk(); return this._nextChunk();
} };
this._nextChunk = function() this._nextChunk = function()
{ {
if (this._finished) return; if (this._finished) return;
@ -739,7 +739,7 @@
remaining = size ? remaining.substr(size) : ''; remaining = size ? remaining.substr(size) : '';
this._finished = !remaining; this._finished = !remaining;
return this.parseChunk(chunk); return this.parseChunk(chunk);
} };
} }
StringStreamer.prototype = Object.create(StringStreamer.prototype); StringStreamer.prototype = Object.create(StringStreamer.prototype);
StringStreamer.prototype.constructor = StringStreamer; StringStreamer.prototype.constructor = StringStreamer;
@ -761,7 +761,7 @@
this._input.on('data', this._streamData); this._input.on('data', this._streamData);
this._input.on('end', this._streamEnd); this._input.on('end', this._streamEnd);
this._input.on('error', this._streamError); this._input.on('error', this._streamError);
} };
this._nextChunk = function() this._nextChunk = function()
{ {
@ -773,7 +773,7 @@
{ {
parseOnData = true; parseOnData = true;
} }
} };
this._streamData = bindFunction(function(chunk) this._streamData = bindFunction(function(chunk)
{ {
@ -921,7 +921,7 @@
self.streamer.parseChunk(_input, true); self.streamer.parseChunk(_input, true);
}; };
this.aborted = function () this.aborted = function()
{ {
return _aborted; return _aborted;
}; };
@ -940,7 +940,7 @@
{ {
if (_results && _delimiterError) if (_results && _delimiterError)
{ {
addError('Delimiter', 'UndetectableDelimiter', 'Unable to auto-detect delimiting character; defaulted to \''+Papa.DefaultDelimiter+'\''); addError('Delimiter', 'UndetectableDelimiter', 'Unable to auto-detect delimiting character; defaulted to \'' + Papa.DefaultDelimiter + '\'');
_delimiterError = false; _delimiterError = false;
} }
@ -977,7 +977,7 @@
if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) { if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) {
_config.dynamicTyping[field] = _config.dynamicTypingFunction(field); _config.dynamicTyping[field] = _config.dynamicTypingFunction(field);
} }
return (_config.dynamicTyping[field] || _config.dynamicTyping) === true return (_config.dynamicTyping[field] || _config.dynamicTyping) === true;
} }
function parseDynamic(field, value) function parseDynamic(field, value)
@ -1007,7 +1007,8 @@
{ {
var row = _config.header ? {} : []; var row = _config.header ? {} : [];
for (var j = 0; j < _results.data[i].length; j++) var j;
for (j = 0; j < _results.data[i].length; j++)
{ {
var field = j; var field = j;
var value = _results.data[i][j]; var value = _results.data[i][j];
@ -1062,8 +1063,8 @@
for (var j = 0; j < preview.data.length; j++) for (var j = 0; j < preview.data.length; j++)
{ {
if (skipEmptyLines && preview.data[j].length === 1 && preview.data[j][0].length === 0) { if (skipEmptyLines && preview.data[j].length === 1 && preview.data[j][0].length === 0) {
emptyLinesCount++ emptyLinesCount++;
continue continue;
} }
var fieldCount = preview.data[j].length; var fieldCount = preview.data[j].length;
avgFieldCount += fieldCount; avgFieldCount += fieldCount;
@ -1096,12 +1097,12 @@
return { return {
successful: !!bestDelim, successful: !!bestDelim,
bestDelimiter: bestDelim bestDelimiter: bestDelim
} };
} }
function guessLineEndings(input) function guessLineEndings(input)
{ {
input = input.substr(0, 1024*1024); // max length 1 MB input = input.substr(0, 1024 * 1024); // max length 1 MB
var r = input.split('\r'); var r = input.split('\r');
@ -1150,13 +1151,13 @@
var fastMode = config.fastMode; var fastMode = config.fastMode;
var quoteChar; var quoteChar;
/** Allows for no quoteChar by setting quoteChar to undefined in config */ /** Allows for no quoteChar by setting quoteChar to undefined in config */
if (config.quoteChar === undefined){ if (config.quoteChar === undefined) {
quoteChar = '"'; quoteChar = '"';
} else { } else {
quoteChar = config.quoteChar; quoteChar = config.quoteChar;
} }
var escapeChar = quoteChar; var escapeChar = quoteChar;
if (config.escapeChar !== undefined){ if (config.escapeChar !== undefined) {
escapeChar = config.escapeChar; escapeChar = config.escapeChar;
} }
@ -1175,7 +1176,7 @@
comments = false; comments = false;
// Newline must be valid: \r, \n, or \r\n // Newline must be valid: \r, \n, or \r\n
if (newline != '\n' && newline != '\r' && newline != '\r\n') if (newline !== '\n' && newline !== '\r' && newline !== '\r\n')
newline = '\n'; newline = '\n';
// We're gonna need these at the Parser scope // We're gonna need these at the Parser scope
@ -1237,7 +1238,8 @@
var nextDelim = input.indexOf(delim, cursor); var nextDelim = input.indexOf(delim, cursor);
var nextNewline = input.indexOf(newline, cursor); var nextNewline = input.indexOf(newline, cursor);
var quoteCharRegex = new RegExp(escapeChar.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&')+quoteChar, 'g'); var quoteCharRegex = new RegExp(escapeChar.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&') + quoteChar, 'g');
var quoteSearch;
// Parser loop // Parser loop
for (;;) for (;;)
@ -1246,7 +1248,7 @@
if (input[cursor] === quoteChar) if (input[cursor] === quoteChar)
{ {
// Start our search for the closing quote where the cursor is // Start our search for the closing quote where the cursor is
var quoteSearch = cursor; quoteSearch = cursor;
// Skip the opening quote // Skip the opening quote
cursor++; cursor++;
@ -1254,7 +1256,7 @@
for (;;) for (;;)
{ {
// Find closing quote // Find closing quote
quoteSearch = input.indexOf(quoteChar, quoteSearch+1); quoteSearch = input.indexOf(quoteChar, quoteSearch + 1);
//No other quotes are found - no other delimiters //No other quotes are found - no other delimiters
if (quoteSearch === -1) if (quoteSearch === -1)
@ -1273,7 +1275,7 @@
} }
// Closing quote at EOF // Closing quote at EOF
if (quoteSearch === inputLen-1) if (quoteSearch === inputLen - 1)
{ {
var value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar); var value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar);
return finish(value); return finish(value);
@ -1281,14 +1283,14 @@
// If this quote is escaped, it's part of the data; skip it // If this quote is escaped, it's part of the data; skip it
// If the quote character is the escape character, then check if the next character is the escape character // If the quote character is the escape character, then check if the next character is the escape character
if (quoteChar === escapeChar && input[quoteSearch+1] === escapeChar) if (quoteChar === escapeChar && input[quoteSearch + 1] === escapeChar)
{ {
quoteSearch++; quoteSearch++;
continue; continue;
} }
// If the quote character is not the escape character, then check if the previous character was the escape character // If the quote character is not the escape character, then check if the previous character was the escape character
if (quoteChar !== escapeChar && quoteSearch !== 0 && input[quoteSearch-1] === escapeChar) if (quoteChar !== escapeChar && quoteSearch !== 0 && input[quoteSearch - 1] === escapeChar)
{ {
continue; continue;
} }
@ -1296,7 +1298,7 @@
var spacesBetweenQuoteAndDelimiter = extraSpaces(nextDelim); var spacesBetweenQuoteAndDelimiter = extraSpaces(nextDelim);
// Closing quote followed by delimiter or 'unnecessary steps + delimiter' // Closing quote followed by delimiter or 'unnecessary steps + delimiter'
if (input[quoteSearch+1+spacesBetweenQuoteAndDelimiter] === delim) if (input[quoteSearch + 1 + spacesBetweenQuoteAndDelimiter] === delim)
{ {
row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));
cursor = quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen; cursor = quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen;
@ -1308,7 +1310,7 @@
var spacesBetweenQuoteAndNewLine = extraSpaces(nextNewline); var spacesBetweenQuoteAndNewLine = extraSpaces(nextNewline);
// Closing quote followed by newline or 'unnecessary spaces + newLine' // Closing quote followed by newline or 'unnecessary spaces + newLine'
if (input.substr(quoteSearch+1+spacesBetweenQuoteAndNewLine, newlineLen) === newline) if (input.substr(quoteSearch + 1 + spacesBetweenQuoteAndNewLine, newlineLen) === newline)
{ {
row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));
saveRow(quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen); saveRow(quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen);
@ -1405,7 +1407,7 @@
var spaceLength = 0; var spaceLength = 0;
if (index !== -1) { if (index !== -1) {
var textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index); var textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index);
if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() == '') { if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') {
spaceLength = textBetweenClosingQuoteAndIndex.length; spaceLength = textBetweenClosingQuoteAndIndex.length;
} }
} }
@ -1464,7 +1466,8 @@
function doStep() function doStep()
{ {
step(returnable()); step(returnable());
data = [], errors = []; data = [];
errors = [];
} }
}; };

16
tests/node-tests.js

@ -7,7 +7,7 @@ var assert = require('assert');
var longSampleRawCsv = fs.readFileSync(__dirname + '/long-sample.csv', 'utf8'); var longSampleRawCsv = fs.readFileSync(__dirname + '/long-sample.csv', 'utf8');
function assertLongSampleParsedCorrectly(parsedCsv) { function assertLongSampleParsedCorrectly(parsedCsv) {
assert.equal(8, parsedCsv.data.length) assert.equal(8, parsedCsv.data.length);
assert.deepEqual(parsedCsv.data[0], [ assert.deepEqual(parsedCsv.data[0], [
'Grant', 'Grant',
'Dyer', 'Dyer',
@ -16,7 +16,7 @@ function assertLongSampleParsedCorrectly(parsedCsv) {
'2014-05-31T01:06:56-07:00', '2014-05-31T01:06:56-07:00',
'Magna Ut Associates', 'Magna Ut Associates',
'ljenkins' 'ljenkins'
]) ]);
assert.deepEqual(parsedCsv.data[7], [ assert.deepEqual(parsedCsv.data[7], [
'Talon', 'Talon',
'Salinas', 'Salinas',
@ -27,13 +27,13 @@ function assertLongSampleParsedCorrectly(parsedCsv) {
'Phasellus@Quisquetincidunt.example' 'Phasellus@Quisquetincidunt.example'
]); ]);
assert.deepEqual(parsedCsv.meta, { assert.deepEqual(parsedCsv.meta, {
"delimiter":",", "delimiter": ",",
"linebreak":"\n", "linebreak": "\n",
"aborted":false, "aborted": false,
"truncated":false, "truncated": false,
"cursor":1209 "cursor": 1209
}); });
assert.equal(parsedCsv.errors.length, 0) assert.equal(parsedCsv.errors.length, 0);
} }
describe('PapaParse', function() { describe('PapaParse', function() {

38
tests/test-cases.js

@ -1,6 +1,8 @@
var chai;
var Papa;
if (typeof module !== 'undefined' && module.exports) { if (typeof module !== 'undefined' && module.exports) {
var chai = require('chai'); chai = require('chai');
var Papa = require('../papaparse.js'); Papa = require('../papaparse.js');
} }
var assert = chai.assert; var assert = chai.assert;
@ -206,7 +208,7 @@ var CORE_PARSER_TESTS = [
"code": "InvalidQuotes", "code": "InvalidQuotes",
"message": "Trailing quote on quoted field is malformed", "message": "Trailing quote on quoted field is malformed",
"row": 0, "row": 0,
"index":1 "index": 1
}] }]
} }
}, },
@ -731,7 +733,7 @@ var PARSE_TESTS = [
}, },
{ {
description: "ASCII 30 delimiter", description: "ASCII 30 delimiter",
input: 'a'+RECORD_SEP+'b'+RECORD_SEP+'c\r\nd'+RECORD_SEP+'e'+RECORD_SEP+'f', input: 'a' + RECORD_SEP + 'b' + RECORD_SEP + 'c\r\nd' + RECORD_SEP + 'e' + RECORD_SEP + 'f',
config: { delimiter: RECORD_SEP }, config: { delimiter: RECORD_SEP },
expected: { expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']], data: [['a', 'b', 'c'], ['d', 'e', 'f']],
@ -740,7 +742,7 @@ var PARSE_TESTS = [
}, },
{ {
description: "ASCII 31 delimiter", description: "ASCII 31 delimiter",
input: 'a'+UNIT_SEP+'b'+UNIT_SEP+'c\r\nd'+UNIT_SEP+'e'+UNIT_SEP+'f', input: 'a' + UNIT_SEP + 'b' + UNIT_SEP + 'c\r\nd' + UNIT_SEP + 'e' + UNIT_SEP + 'f',
config: { delimiter: UNIT_SEP }, config: { delimiter: UNIT_SEP },
expected: { expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']], data: [['a', 'b', 'c'], ['d', 'e', 'f']],
@ -1083,7 +1085,7 @@ var PARSE_TESTS = [
description: "Single quote as quote character", description: "Single quote as quote character",
notes: "Must parse correctly when single quote is specified as a quote character", notes: "Must parse correctly when single quote is specified as a quote character",
input: "a,b,'c,d'", input: "a,b,'c,d'",
config: { quoteChar: "'"}, config: { quoteChar: "'" },
expected: { expected: {
data: [['a', 'b', 'c,d']], data: [['a', 'b', 'c,d']],
errors: [] errors: []
@ -1093,7 +1095,7 @@ var PARSE_TESTS = [
description: "Custom escape character in the middle", description: "Custom escape character in the middle",
notes: "Must parse correctly if the backslash sign (\\) is configured as a custom escape character", notes: "Must parse correctly if the backslash sign (\\) is configured as a custom escape character",
input: 'a,b,"c\\"d\\"f"', input: 'a,b,"c\\"d\\"f"',
config: { escapeChar:'\\'}, config: { escapeChar: '\\' },
expected: { expected: {
data: [['a', 'b', 'c"d"f']], data: [['a', 'b', 'c"d"f']],
errors: [] errors: []
@ -1103,7 +1105,7 @@ var PARSE_TESTS = [
description: "Custom escape character at the end", description: "Custom escape character at the end",
notes: "Must parse correctly if the backslash sign (\\) is configured as a custom escape character and the escaped quote character appears at the end of the column", notes: "Must parse correctly if the backslash sign (\\) is configured as a custom escape character and the escaped quote character appears at the end of the column",
input: 'a,b,"c\\"d\\""', input: 'a,b,"c\\"d\\""',
config: { escapeChar:'\\'}, config: { escapeChar: '\\' },
expected: { expected: {
data: [['a', 'b', 'c"d"']], data: [['a', 'b', 'c"d"']],
errors: [] errors: []
@ -1113,7 +1115,7 @@ var PARSE_TESTS = [
description: "Custom escape character not used for escaping", description: "Custom escape character not used for escaping",
notes: "Must parse correctly if the backslash sign (\\) is configured as a custom escape character and appears as regular character in the text", notes: "Must parse correctly if the backslash sign (\\) is configured as a custom escape character and appears as regular character in the text",
input: 'a,b,"c\\d"', input: 'a,b,"c\\d"',
config: { escapeChar:'\\'}, config: { escapeChar: '\\' },
expected: { expected: {
data: [['a', 'b', 'c\\d']], data: [['a', 'b', 'c\\d']],
errors: [] errors: []
@ -1123,7 +1125,7 @@ var PARSE_TESTS = [
description: "Header row with preceding comment", description: "Header row with preceding comment",
notes: "Must parse correctly headers if they are preceded by comments", notes: "Must parse correctly headers if they are preceded by comments",
input: '#Comment\na,b\nc,d\n', input: '#Comment\na,b\nc,d\n',
config: { header: true, comments: '#', skipEmptyLines: true, delimiter: ','}, config: { header: true, comments: '#', skipEmptyLines: true, delimiter: ',' },
expected: { expected: {
data: [{'a': 'c', 'b': 'd'}], data: [{'a': 'c', 'b': 'd'}],
errors: [] errors: []
@ -1314,7 +1316,7 @@ var UNPARSE_TESTS = [
description: "Custom delimiter (ASCII 30)", description: "Custom delimiter (ASCII 30)",
input: [['a', 'b', 'c'], ['d', 'e', 'f']], input: [['a', 'b', 'c'], ['d', 'e', 'f']],
config: { delimiter: RECORD_SEP }, config: { delimiter: RECORD_SEP },
expected: 'a'+RECORD_SEP+'b'+RECORD_SEP+'c\r\nd'+RECORD_SEP+'e'+RECORD_SEP+'f' expected: 'a' + RECORD_SEP + 'b' + RECORD_SEP + 'c\r\nd' + RECORD_SEP + 'e' + RECORD_SEP + 'f'
}, },
{ {
description: "Bad delimiter (\\n)", description: "Bad delimiter (\\n)",
@ -1708,7 +1710,7 @@ var CUSTOM_TESTS = [
handle.abort(); handle.abort();
}, },
chunkSize: 6, chunkSize: 6,
complete: function (response) { complete: function(response) {
callback(response.meta.aborted); callback(response.meta.aborted);
} }
}); });
@ -1828,19 +1830,19 @@ var CUSTOM_TESTS = [
'?x=1&papaworker&y=1', '?x=1&papaworker&y=1',
'?x=1&papaworker=1' '?x=1&papaworker=1'
]; ];
var results = searchStrings.map(function () { return false; }); var results = searchStrings.map(function() { return false; });
var workers = []; var workers = [];
// Give it .5s to do something // Give it .5s to do something
setTimeout(function () { setTimeout(function() {
workers.forEach(function (w) { w.terminate(); }); workers.forEach(function(w) { w.terminate(); });
callback(results); callback(results);
}, 500); }, 500);
searchStrings.forEach(function (searchString, idx) { searchStrings.forEach(function(searchString, idx) {
var w = new Worker('../papaparse.js' + searchString); var w = new Worker('../papaparse.js' + searchString);
workers.push(w); workers.push(w);
w.addEventListener('message', function () { w.addEventListener('message', function() {
results[idx] = true; results[idx] = true;
}); });
w.postMessage({input: 'a,b,c\n1,2,3'}); w.postMessage({input: 'a,b,c\n1,2,3'});
@ -1853,7 +1855,7 @@ var CUSTOM_TESTS = [
describe('Custom Tests', function() { describe('Custom Tests', function() {
function generateTest(test) { function generateTest(test) {
(test.disabled ? it.skip : it)(test.description, function(done) { (test.disabled ? it.skip : it)(test.description, function(done) {
test.run(function (actual) { test.run(function(actual) {
assert.deepEqual(JSON.stringify(actual), JSON.stringify(test.expected)); assert.deepEqual(JSON.stringify(actual), JSON.stringify(test.expected));
done(); done();
}); });

4
tests/test.js

@ -4,11 +4,11 @@ var open = require('open');
var path = require('path'); var path = require('path');
var childProcess = require('child_process'); var childProcess = require('child_process');
var server = connect().use(serveStatic(path.join(__dirname, '/..'))).listen(8071, function () { var server = connect().use(serveStatic(path.join(__dirname, '/..'))).listen(8071, function() {
if (process.argv.indexOf('--phantomjs') !== -1) { if (process.argv.indexOf('--phantomjs') !== -1) {
childProcess.spawn('node_modules/.bin/mocha-phantomjs', ['http://localhost:8071/tests/tests.html'], { childProcess.spawn('node_modules/.bin/mocha-phantomjs', ['http://localhost:8071/tests/tests.html'], {
stdio: 'inherit' stdio: 'inherit'
}).on('exit', function () { }).on('exit', function() {
server.close(); server.close();
}); });

Loading…
Cancel
Save