[Pkg-javascript-commits] [node-expat] 341/371: use standard JavaScript style and improvements
Jonas Smedegaard
dr at jones.dk
Sun Feb 28 10:00:31 UTC 2016
This is an automated email from the git hooks/post-receive script.
js pushed a commit to branch master
in repository node-expat.
commit 27d078c4ab9476dd57a03f5e0519e574d2466127
Author: Sonny Piers <sonny at fastmail.net>
Date: Sun Oct 25 18:21:39 2015 +0100
use standard JavaScript style and improvements
---
.editorconfig | 11 +
.gitignore | 12 +-
.npmignore | 8 +
.travis.yml | 11 +-
README.md | 9 +-
bench.js | 101 ++++----
lib/node-expat.js | 99 +++----
package.json | 5 +-
test/index.js | 755 +++++++++++++++++++++++++++---------------------------
9 files changed, 517 insertions(+), 494 deletions(-)
diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000..a996a2d
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,11 @@
+# EditorConfig is awesome: http://EditorConfig.org
+
+root = true
+
+[*]
+end_of_line = lf
+insert_final_newline = true
+charset = utf-8
+trim_trailing_whitespace = true
+indent_style = space
+indent_size = 2
diff --git a/.gitignore b/.gitignore
index b457b0c..1ea4900 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,7 @@
-.lock-wscript
-node_modules
-build
-*.swp
-npm-debug.log
+build/
+node_modules/
+
+!.editorconfig
+!.gitignore
+!.npmignore
+!.travis.yml
diff --git a/.npmignore b/.npmignore
new file mode 100644
index 0000000..142832a
--- /dev/null
+++ b/.npmignore
@@ -0,0 +1,8 @@
+test/
+
+.editorconfig
+.gitignore
+.npmignore
+.travis.yml
+
+bench.js
diff --git a/.travis.yml b/.travis.yml
index 4ea46d1..723effb 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -6,13 +6,12 @@ env:
- CXX="g++-4.8"
node_js:
- - '0.8'
- '0.10'
- '0.12'
- - 'iojs'
- - 'iojs-v1'
- - 'iojs-v2'
- '4.0'
+ - '4.1'
+ - '4.2'
+ - 'stable'
addons:
apt:
@@ -22,6 +21,4 @@ addons:
- g++-4.8
- gcc-4.8
-before_install:
- # npm shipped with Node.js 0.8 doesn't support carret so let's update it
- - if [ "$TRAVIS_NODE_VERSION" == "0.8" ]; then npm install -g npm; fi
+before_script: npm install -g standard
diff --git a/README.md b/README.md
index 61400b3..514f88a 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,11 @@
# node-expat
-[![Build Status](https://travis-ci.org/node-xmpp/node-expat.png)](https://travis-ci.org/node-xmpp/node-expat)
+[![build status](https://img.shields.io/travis/node-xmpp/node-expat/master.svg?style=flat-square)](https://travis-ci.org/node-xmpp/node-expat/branches)
+[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](http://standardjs.com/)
## Motivation
-You use [node.js](http://github.com/ry/node) for speed? You process
+You use [Node.js](https://nodejs.org) for speed? You process
XML streams? Then you want the fastest XML parser: [libexpat](http://expat.sourceforge.net/)!
## Manual
@@ -13,10 +14,8 @@ Please see the [node-expat manual](http://node-xmpp.org/doc/expat.html)
## Install
-Install node-expat:
-
```
- npm i node-expat
+npm install node-expat
```
## Testing
diff --git a/bench.js b/bench.js
index 14825a8..2bf7a0e 100644
--- a/bench.js
+++ b/bench.js
@@ -1,62 +1,61 @@
-'use strict';
+'use strict'
-var util = require('util');
-var node_xml = require("node-xml");
-var libxml = require("libxmljs");
-var expat = require('./');
-var sax = require('sax');
+var node_xml = require('node-xml')
+var libxml = require('libxmljs')
+var expat = require('./')
+var sax = require('sax')
-function NodeXmlParser() {
- var parser = new node_xml.SaxParser(function(cb) { });
- this.parse = function(s) {
- parser.parseString(s);
- };
+function NodeXmlParser () { // eslint-disable-line
+ var parser = new node_xml.SaxParser(function (cb) {})
+ this.parse = function (s) {
+ parser.parseString(s)
+ }
}
-function LibXmlJsParser() {
- var parser = new libxml.SaxPushParser(function(cb) { });
- this.parse = function(s) {
- parser.push(s, false);
- };
+function LibXmlJsParser () { // eslint-disable-line
+ var parser = new libxml.SaxPushParser(function (cb) {})
+ this.parse = function (s) {
+ parser.push(s, false)
+ }
}
-function SaxParser() {
- var parser = sax.parser();
- this.parse = function(s) {
- parser.write(s).close();
- }
+function SaxParser () { // eslint-disable-line
+ var parser = sax.parser()
+ this.parse = function (s) {
+ parser.write(s).close()
+ }
}
-function ExpatParser() {
- var parser = new expat.Parser();
- this.parse = function(s) {
- parser.parse(s, false);
- };
+function ExpatParser () {
+ var parser = new expat.Parser()
+ this.parse = function (s) {
+ parser.parse(s, false)
+ }
}
-// var p = new NodeXmlParser();
-// var p = new LibXmlJsParser();
-// var p = new SaxParser();
-var p = new ExpatParser();
-p.parse("<r>");
-var nEl = 0;
-function d() {
- p.parse("<foo bar='baz'>quux</foo>");
- nEl++;
- setTimeout(d, 0);
+// var p = new NodeXmlParser()
+// var p = new LibXmlJsParser()
+// var p = new SaxParser()
+var p = new ExpatParser()
+p.parse('<r>')
+var nEl = 0
+function d () {
+ p.parse("<foo bar='baz'>quux</foo>")
+ nEl++
+ setTimeout(d, 0)
}
-d();
+d()
-var its =[];
-setInterval(function() {
- console.log(nEl + " el/s");
- its.push(nEl);
- nEl = 0;
-}, 1000);
+var its = []
+setInterval(function () {
+ console.log(nEl + ' el/s')
+ its.push(nEl)
+ nEl = 0
+}, 1000)
process.on('SIGINT', function () {
- var average = 0;
- its.forEach(function (v){
- average += v;
- });
- average /= its.length;
- console.log("Average: " + average + " el/s");
- process.exit(0);
-});
+ var average = 0
+ its.forEach(function (v) {
+ average += v
+ })
+ average /= its.length
+ console.log('Average: ' + average + ' el/s')
+ process.exit(0)
+})
diff --git a/lib/node-expat.js b/lib/node-expat.js
index 078c62f..f9de2e7 100644
--- a/lib/node-expat.js
+++ b/lib/node-expat.js
@@ -1,11 +1,10 @@
'use strict'
-var EventEmitter = require('events').EventEmitter
var util = require('util')
var expat = require('bindings')('node_expat')
var Stream = require('stream').Stream
-var Parser = function(encoding) {
+var Parser = function (encoding) {
this.encoding = encoding
this._getNewParser()
this.parser.emit = this.emit.bind(this)
@@ -16,98 +15,100 @@ var Parser = function(encoding) {
}
util.inherits(Parser, Stream)
-Parser.prototype._getNewParser = function() {
- this.parser = new expat.Parser(this.encoding)
+Parser.prototype._getNewParser = function () {
+ this.parser = new expat.Parser(this.encoding)
}
-Parser.prototype.parse = function(buf, isFinal) {
+Parser.prototype.parse = function (buf, isFinal) {
return this.parser.parse(buf, isFinal)
}
-Parser.prototype.setEncoding = function(encoding) {
+Parser.prototype.setEncoding = function (encoding) {
this.encoding = encoding
return this.parser.setEncoding(this.encoding)
}
-Parser.prototype.setUnknownEncoding = function(map, convert) {
+Parser.prototype.setUnknownEncoding = function (map, convert) {
return this.parser.setUnknownEncoding(map, convert)
}
-Parser.prototype.getError = function() {
+Parser.prototype.getError = function () {
return this.parser.getError()
}
-Parser.prototype.stop = function() {
+Parser.prototype.stop = function () {
return this.parser.stop()
}
-Parser.prototype.pause = function() {
+Parser.prototype.pause = function () {
return this.stop()
}
-Parser.prototype.resume = function() {
+Parser.prototype.resume = function () {
return this.parser.resume()
}
-Parser.prototype.destroy = function() {
+Parser.prototype.destroy = function () {
this.parser.stop()
this.end()
}
-Parser.prototype.destroySoon = function() {
+Parser.prototype.destroySoon = function () {
this.destroy()
}
-Parser.prototype.write = function(data) {
- var error, result
- try {
- result = this.parse(data)
- if (!result)
- error = this.getError()
- } catch (e) {
- error = e
- }
- if (error) {
- this.emit('error', error)
- this.emit('close')
+Parser.prototype.write = function (data) {
+ var error, result
+ try {
+ result = this.parse(data)
+ if (!result) {
+ error = this.getError()
}
- return result
+ } catch (e) {
+ error = e
+ }
+ if (error) {
+ this.emit('error', error)
+ this.emit('close')
+ }
+ return result
}
-Parser.prototype.end = function(data) {
- var error, result
- try {
- result = this.parse(data || '', true)
- if (!result)
+Parser.prototype.end = function (data) {
+ var error, result
+ try {
+ result = this.parse(data || '', true)
+ if (!result) {
error = this.getError()
- } catch (e) {
- error = e
}
+ } catch (e) {
+ error = e
+ }
- if (!error) {
- this.emit('end')
- } else {
- this.emit('error', error)
- }
- this.emit('close')
+ if (!error) {
+ this.emit('end')
+ } else {
+ this.emit('error', error)
+ }
+ this.emit('close')
}
-Parser.prototype.reset = function() {
- return this.parser.reset()
+Parser.prototype.reset = function () {
+ return this.parser.reset()
}
-Parser.prototype.getCurrentLineNumber = function() {
- return this.parser.getCurrentLineNumber()
+Parser.prototype.getCurrentLineNumber = function () {
+ return this.parser.getCurrentLineNumber()
}
-Parser.prototype.getCurrentColumnNumber = function() {
- return this.parser.getCurrentColumnNumber()
+Parser.prototype.getCurrentColumnNumber = function () {
+ return this.parser.getCurrentColumnNumber()
}
-Parser.prototype.getCurrentByteIndex = function() {
- return this.parser.getCurrentByteIndex()
+Parser.prototype.getCurrentByteIndex = function () {
+ return this.parser.getCurrentByteIndex()
}
exports.Parser = Parser
-exports.createParser = function(cb) {
+exports.createParser = function (cb) {
var parser = new Parser()
if (cb) {
- parser.on('startElement', cb)
+ parser.on('startElement', cb)
}
return parser
}
diff --git a/package.json b/package.json
index f92e636..dbf0743 100644
--- a/package.json
+++ b/package.json
@@ -12,7 +12,10 @@
"parsing"
],
"scripts": {
- "test": "vows --spec ./test/**/*.js"
+ "preversion": "npm test",
+ "lint": "standard",
+ "unit": "vows --spec ./test/**/*.js",
+ "test": "npm run unit && npm run lint"
},
"dependencies": {
"bindings": "^1.2.1",
diff --git a/test/index.js b/test/index.js
index 0cb3357..0c939c9 100644
--- a/test/index.js
+++ b/test/index.js
@@ -1,419 +1,422 @@
-'use strict';
+'use strict'
var expat = require('../lib/node-expat')
- , Iconv = require('iconv').Iconv
- , Buffer = require('buffer').Buffer
- , vows = require('vows')
- , assert = require('assert')
- , fs = require('fs')
- , log = require('debug')('test/index')
+var Iconv = require('iconv').Iconv
+var Buffer = require('buffer').Buffer
+var vows = require('vows')
+var assert = require('assert')
+var fs = require('fs')
+var log = require('debug')('test/index')
-function collapseTexts(evs) {
- var r = []
- var t = ''
- evs.forEach(function(ev) {
- if (ev[0] == 'text') {
- t += ev[1]
- } else {
- if (t != '')
- r.push([ 'text', t ])
- t = ''
- r.push(ev)
- }
- })
- if (t != '') {
- r.push([ 'text', t ])
+function collapseTexts (evs) {
+ var r = []
+ var t = ''
+ evs.forEach(function (ev) {
+ if (ev[0] === 'text') {
+ t += ev[1]
+ } else {
+ if (t !== '') {
+ r.push([ 'text', t ])
+ }
+ t = ''
+ r.push(ev)
}
- return r
+ })
+ if (t !== '') {
+ r.push([ 'text', t ])
+ }
+ return r
}
-function expect(s, evs_expected) {
+function expect (s, evs_expected) {
for (var step = s.length; step > 0; step--) {
expectWithParserAndStep(s, evs_expected, new expat.Parser(), step)
}
}
-function expectWithParserAndStep(s, evs_expected, p, step) {
- var evs_received = [];
- p.addListener('startElement', function(name, attrs) {
- evs_received.push(['startElement', name, attrs]);
- });
- p.addListener('endElement', function(name) {
- evs_received.push(['endElement', name]);
- });
- p.addListener('text', function(s) {
- evs_received.push(['text', s]);
- });
- p.addListener('processingInstruction', function(target, data) {
- evs_received.push(['processingInstruction', target, data]);
- });
- p.addListener('comment', function(s) {
- evs_received.push(['comment', s]);
- });
- p.addListener('xmlDecl', function(version, encoding, standalone) {
- evs_received.push(['xmlDecl', version, encoding, standalone]);
- });
- p.addListener('startCdata', function() {
- evs_received.push(['startCdata']);
- });
- p.addListener('endCdata', function() {
- evs_received.push(['endCdata']);
- });
- p.addListener('entityDecl', function(entityName, isParameterEntity, value, base, systemId, publicId, notationName) {
- evs_received.push(['entityDecl', entityName, isParameterEntity, value, base, systemId, publicId, notationName]);
- });
- p.addListener('error', function(e) {
- evs_received.push(['error', e]);
- });
- for(var l = 0; l < s.length; l += step)
- {
- var end = l + step;
- if (end > s.length)
- end = s.length;
+function expectWithParserAndStep (s, evs_expected, p, step) {
+ var evs_received = []
+ p.addListener('startElement', function (name, attrs) {
+ evs_received.push(['startElement', name, attrs])
+ })
+ p.addListener('endElement', function (name) {
+ evs_received.push(['endElement', name])
+ })
+ p.addListener('text', function (s) {
+ evs_received.push(['text', s])
+ })
+ p.addListener('processingInstruction', function (target, data) {
+ evs_received.push(['processingInstruction', target, data])
+ })
+ p.addListener('comment', function (s) {
+ evs_received.push(['comment', s])
+ })
+ p.addListener('xmlDecl', function (version, encoding, standalone) {
+ evs_received.push(['xmlDecl', version, encoding, standalone])
+ })
+ p.addListener('startCdata', function () {
+ evs_received.push(['startCdata'])
+ })
+ p.addListener('endCdata', function () {
+ evs_received.push(['endCdata'])
+ })
+ p.addListener('entityDecl', function (entityName, isParameterEntity, value, base, systemId, publicId, notationName) {
+ evs_received.push(['entityDecl', entityName, isParameterEntity, value, base, systemId, publicId, notationName])
+ })
+ p.addListener('error', function (e) {
+ evs_received.push(['error', e])
+ })
+ for (var l = 0; l < s.length; l += step) {
+ var end = l + step
+ if (end > s.length) {
+ end = s.length
+ }
- p.write(s.slice(l, end));
- }
+ p.write(s.slice(l, end))
+ }
- var expected = JSON.stringify(evs_expected);
- var received = JSON.stringify(collapseTexts(evs_received));
- assert.equal(received, expected);
+ var expected = JSON.stringify(evs_expected)
+ var received = JSON.stringify(collapseTexts(evs_received))
+ assert.equal(received, expected)
}
vows.describe('node-expat').addBatch({
- 'single element': {
- 'simple': function() {
- expect("<r/>",
- [['startElement', 'r', {}],
- ['endElement', 'r']]);
- },
- 'single element with attribute': function() {
- expect("<r foo='bar'/>",
- [['startElement', 'r', {foo: 'bar'}],
- ['endElement', 'r']]);
- },
- 'single elemeht with differently quoted attributes': function() {
- expect("<r foo='bar' baz=\"quux\" test=\"tset\"/>",
- [['startElement', 'r', {foo: 'bar', baz: 'quux', test: 'tset'}],
- ['endElement', 'r']]);
- },
- 'single element with namespaces': function() {
- expect("<r xmlns='http://localhost/' xmlns:x=\"http://example.com/\"></r>",
- [['startElement', 'r', {xmlns: 'http://localhost/', 'xmlns:x': 'http://example.com/'}],
- ['endElement', 'r']]);
- },
- 'single element with text content': function() {
- expect("<r>foo</r>",
- [['startElement', 'r', {}],
- ['text', "foo"],
- ['endElement', 'r']]);
- },
- 'single element with text content and line break': function() {
- expect("<r>foo\nbar</r>",
- [['startElement', 'r', {}],
- ['text', "foo\nbar"],
- ['endElement', 'r']]);
- },
- 'single element with CDATA content': function() {
- expect("<r><![CDATA[<greeting>Hello, world!</greeting>]]></r>",
- [['startElement', 'r', {}],
- ['startCdata'],
- ['text', "<greeting>Hello, world!</greeting>"],
- ['endCdata'],
- ['endElement', 'r']]);
- },
- 'single element with entity text': function() {
- expect("<r>foo&bar</r>",
- [['startElement', 'r', {}],
- ['text', "foo&bar"],
- ['endElement', 'r']]);
- },
- 'single element with umlaut text': function() {
- expect("<r>ß</r>",
- [['startElement', 'r', {}],
- ['text', "ß"],
- ['endElement', 'r']]);
- },
- 'from buffer': function() {
- expect(new Buffer('<foo>bar</foo>'),
- [['startElement', 'foo', {}],
- ['text', 'bar'],
- ['endElement', 'foo']]);
- }
+ 'single element': {
+ 'simple': function () {
+ expect('<r/>',
+ [['startElement', 'r', {}],
+ ['endElement', 'r']])
},
- 'entity declaration': {
- 'a billion laughs': function() {
- expect('<!DOCTYPE b [<!ELEMENT b (#PCDATA)>' +
- '<!ENTITY l0 "ha"><!ENTITY l1 "&l0;&l0;"><!ENTITY l2 "&l1;&l1;">' +
- ']><b>&l2;</b>',
- [["entityDecl","l0",false,"ha",null,null,null,null],
- ["entityDecl","l1",false,"&l0;&l0;",null,null,null,null],
- ["entityDecl","l2",false,"&l1;&l1;",null,null,null,null],
- ["startElement","b",{}],["text","hahahaha"],["endElement","b"]]);
- }
+ 'single element with attribute': function () {
+ expect("<r foo='bar'/>",
+ [['startElement', 'r', {foo: 'bar'}],
+ ['endElement', 'r']])
},
- 'processing instruction': {
- 'with parameters': function() {
- expect("<?i like xml?>",
- [['processingInstruction', 'i', 'like xml']]);
- },
- 'simple': function() {
- expect("<?dragons?>",
- [['processingInstruction', 'dragons', '']]);
- },
- 'XML declaration with encoding': function() {
- expect("<?xml version='1.0' encoding='UTF-8'?>",
- [['xmlDecl', '1.0', 'UTF-8', true]]);
- },
- 'XML declaration': function() {
- expect("<?xml version='1.0'?>",
- [['xmlDecl', '1.0', null, true]]);
- }
+ 'single elemeht with differently quoted attributes': function () {
+ expect('<r foo=\'bar\' baz="quux" test="tset"/>',
+ [['startElement', 'r', {foo: 'bar', baz: 'quux', test: 'tset'}],
+ ['endElement', 'r']])
},
- 'comment': {
- 'simple': function() {
- expect("<!-- no comment -->",
- [['comment', ' no comment ']]);
- }
+ 'single element with namespaces': function () {
+ expect('<r xmlns=\'http://localhost/\' xmlns:x="http://example.com/"></r>',
+ [['startElement', 'r', {xmlns: 'http://localhost/', 'xmlns:x': 'http://example.com/'}],
+ ['endElement', 'r']])
},
- 'unknownEncoding with single-byte map': {
- 'Windows-1252': function() {
- var p = new expat.Parser();
- var encodingName;
- p.addListener('unknownEncoding', function(name) {
- encodingName = name;
- var map = [];
- for(var i = 0; i < 256; i++)
- map[i] = i;
- map[165] = 0x00A5; // ¥
- map[128] = 0x20AC; // €
- map[ 36] = 0x0024; // $
- p.setUnknownEncoding(map);
- });
- var text = "";
- p.addListener('text', function(s) {
- text += s;
- });
- p.addListener('error', function(e) {
- assert.fail(e);
- });
- p.parse("<?xml version='1.0' encoding='Windows-1252'?><r>");
- p.parse(new Buffer([165, 128, 36]));
- p.parse("</r>");
- assert.equal(encodingName, "Windows-1252");
- assert.equal(text, "¥€$");
- }
+ 'single element with text content': function () {
+ expect('<r>foo</r>',
+ [['startElement', 'r', {}],
+ ['text', 'foo'],
+ ['endElement', 'r']])
},
- 'unknownEncoding with single-byte map using iconv': {
- 'Windows-1252': function() {
- var p = new expat.Parser();
- var encodingName;
- p.addListener('unknownEncoding', function(name) {
- encodingName = name;
- var iconv = new Iconv(encodingName + '//TRANSLIT//IGNORE', 'UTF-8');
- var map = [];
-
- for(var i = 0; i < 256; i++) {
- try {
- var d = iconv.convert(new Buffer([i])).toString();
- } catch (e) {
- d = '\b';
- }
- map[i] = d.charCodeAt(0);
- }
- p.setUnknownEncoding(map);
- });
- var text = '';
- p.addListener('text', function(s) {
- text += s;
- });
- p.addListener('error', function(e) {
- assert.fail(e);
- });
- p.parse("<?xml version='1.0' encoding='Windows-1252'?><r>");
- p.parse(new Buffer([165, 128, 36]));
- p.parse("</r>");
- assert.equal(encodingName, "Windows-1252");
- assert.equal("¥€$", text);
- }
+ 'single element with text content and line break': function () {
+ expect('<r>foo\nbar</r>',
+ [['startElement', 'r', {}],
+ ['text', 'foo\nbar'],
+ ['endElement', 'r']])
},
- 'error': {
- 'tag name starting with ampersand': function() {
- expect("<&", [['error', "not well-formed (invalid token)"]]);
- }
+ 'single element with CDATA content': function () {
+ expect('<r><![CDATA[<greeting>Hello, world!</greeting>]]></r>',
+ [['startElement', 'r', {}],
+ ['startCdata'],
+ ['text', '<greeting>Hello, world!</greeting>'],
+ ['endCdata'],
+ ['endElement', 'r']])
},
-
- 'reset': {
- 'complete doc without error': function() {
- var p = new expat.Parser("UTF-8");
- expectWithParserAndStep("<start><first /><second>text</second></start>", [['startElement', 'start', {}], ['startElement', 'first', {}], ['endElement', 'first'], ['startElement', 'second', {}], ['text', "text"], ['endElement', 'second'], ['endElement', 'start']], p, 1000);
- p.reset();
- expectWithParserAndStep("<restart><third>moretext</third><fourth /></restart>", [['startElement', 'restart', {}], ['startElement', 'third', {}], ['text', "moretext"], ['endElement', 'third'], ['startElement', 'fourth', {}], ['endElement', 'fourth'], ['endElement', 'restart']], p, 1000);
+ 'single element with entity text': function () {
+ expect('<r>foo&bar</r>',
+ [['startElement', 'r', {}],
+ ['text', 'foo&bar'],
+ ['endElement', 'r']])
+ },
+ 'single element with umlaut text': function () {
+ expect('<r>ß</r>',
+ [['startElement', 'r', {}],
+ ['text', 'ß'],
+ ['endElement', 'r']])
+ },
+ 'from buffer': function () {
+ expect(new Buffer('<foo>bar</foo>'),
+ [['startElement', 'foo', {}],
+ ['text', 'bar'],
+ ['endElement', 'foo']])
+ }
},
- 'incomplete doc without error': function() {
- var p = new expat.Parser("UTF-8");
- expectWithParserAndStep("<start><first /><second>text</second>", [['startElement', 'start', {}], ['startElement', 'first', {}], ['endElement', 'first'], ['startElement', 'second', {}], ['text', "text"], ['endElement', 'second']], p, 1000);
- p.reset();
- expectWithParserAndStep("<restart><third>moretext</third><fourth /></restart>", [['startElement', 'restart', {}], ['startElement', 'third', {}], ['text', "moretext"], ['endElement', 'third'], ['startElement', 'fourth', {}], ['endElement', 'fourth'], ['endElement', 'restart']], p, 1000);
+ 'entity declaration': {
+ 'a billion laughs': function () {
+ expect('<!DOCTYPE b [<!ELEMENT b (#PCDATA)>' +
+ '<!ENTITY l0 "ha"><!ENTITY l1 "&l0;&l0;"><!ENTITY l2 "&l1;&l1;">' +
+ ']><b>&l2;</b>',
+ [['entityDecl', 'l0', false, 'ha', null, null, null, null],
+ ['entityDecl', 'l1', false, '&l0;&l0;', null, null, null, null],
+ ['entityDecl', 'l2', false, '&l1;&l1;', null, null, null, null],
+ ['startElement', 'b', {}], ['text', 'hahahaha'], ['endElement', 'b']])
+ }
},
- 'with doc error': function() {
- var p = new expat.Parser("UTF-8");
- expectWithParserAndStep("</end>", [["error", "not well-formed (invalid token)"]], p, 1000);
- p.reset();
- expectWithParserAndStep("<restart><third>moretext</third><fourth /></restart>", [['startElement', 'restart', {}], ['startElement', 'third', {}], ['text', "moretext"], ['endElement', 'third'], ['startElement', 'fourth', {}], ['endElement', 'fourth'], ['endElement', 'restart']], p, 1000);
- }
+ 'processing instruction': {
+ 'with parameters': function () {
+ expect('<?i like xml?>',
+ [['processingInstruction', 'i', 'like xml']])
+ },
+ 'simple': function () {
+ expect('<?dragons?>',
+ [['processingInstruction', 'dragons', '']])
},
- 'stop and resume': {
- topic: function() {
- var cb = this.callback;
- var p = new expat.Parser("UTF-8");
+ 'XML declaration with encoding': function () {
+ expect("<?xml version='1.0' encoding='UTF-8'?>",
+ [['xmlDecl', '1.0', 'UTF-8', true]])
+ },
+ 'XML declaration': function () {
+ expect("<?xml version='1.0'?>",
+ [['xmlDecl', '1.0', null, true]])
+ }
+ },
+ 'comment': {
+ 'simple': function () {
+ expect('<!-- no comment -->',
+ [['comment', ' no comment ']])
+ }
+ },
+ 'unknownEncoding with single-byte map': {
+ 'Windows-1252': function () {
+ var p = new expat.Parser()
+ var encodingName
+ p.addListener('unknownEncoding', function (name) {
+ encodingName = name
+ var map = []
+ for (var i = 0; i < 256; i++) {
+ map[i] = i
+ }
+ map[165] = 0x00A5 // ¥
+ map[128] = 0x20AC // €
+ map[36] = 0x0024 // $
+ p.setUnknownEncoding(map)
+ })
+ var text = ''
+ p.addListener('text', function (s) {
+ text += s
+ })
+ p.addListener('error', function (e) {
+ assert.fail(e)
+ })
+ p.parse("<?xml version='1.0' encoding='Windows-1252'?><r>")
+ p.parse(new Buffer([165, 128, 36]))
+ p.parse('</r>')
+ assert.equal(encodingName, 'Windows-1252')
+ assert.equal(text, '¥€$')
+ }
+ },
+ 'unknownEncoding with single-byte map using iconv': {
+ 'Windows-1252': function () {
+ var p = new expat.Parser()
+ var encodingName
+ p.addListener('unknownEncoding', function (name) {
+ encodingName = name
+ var iconv = new Iconv(encodingName + '//TRANSLIT//IGNORE', 'UTF-8')
+ var map = []
- var input = '\
- <wrap> \
- <short /> \
- <short></short> \
- <long /> \
- <short /> \
- <long>foo</long> \
- </wrap>';
+ for (var i = 0; i < 256; i++) {
+ try {
+ var d = iconv.convert(new Buffer([i])).toString()
+ } catch (e) {
+ d = '\b'
+ }
+ map[i] = d.charCodeAt(0)
+ }
+ p.setUnknownEncoding(map)
+ })
+ var text = ''
+ p.addListener('text', function (s) {
+ text += s
+ })
+ p.addListener('error', function (e) {
+ assert.fail(e)
+ })
+ p.parse("<?xml version='1.0' encoding='Windows-1252'?><r>")
+ p.parse(new Buffer([165, 128, 36]))
+ p.parse('</r>')
+ assert.equal(encodingName, 'Windows-1252')
+ assert.equal('¥€$', text)
+ }
+ },
+ 'error': {
+ 'tag name starting with ampersand': function () {
+ expect('<&', [['error', 'not well-formed (invalid token)']])
+ }
+ },
+
+ 'reset': {
+ 'complete doc without error': function () {
+ var p = new expat.Parser('UTF-8')
+ expectWithParserAndStep('<start><first /><second>text</second></start>', [['startElement', 'start', {}], ['startElement', 'first', {}], ['endElement', 'first'], ['startElement', 'second', {}], ['text', 'text'], ['endElement', 'second'], ['endElement', 'start']], p, 1000)
+ p.reset()
+ expectWithParserAndStep('<restart><third>moretext</third><fourth /></restart>', [['startElement', 'restart', {}], ['startElement', 'third', {}], ['text', 'moretext'], ['endElement', 'third'], ['startElement', 'fourth', {}], ['endElement', 'fourth'], ['endElement', 'restart']], p, 1000)
+ },
+ 'incomplete doc without error': function () {
+ var p = new expat.Parser('UTF-8')
+ expectWithParserAndStep('<start><first /><second>text</second>', [['startElement', 'start', {}], ['startElement', 'first', {}], ['endElement', 'first'], ['startElement', 'second', {}], ['text', 'text'], ['endElement', 'second']], p, 1000)
+ p.reset()
+ expectWithParserAndStep('<restart><third>moretext</third><fourth /></restart>', [['startElement', 'restart', {}], ['startElement', 'third', {}], ['text', 'moretext'], ['endElement', 'third'], ['startElement', 'fourth', {}], ['endElement', 'fourth'], ['endElement', 'restart']], p, 1000)
+ },
+ 'with doc error': function () {
+ var p = new expat.Parser('UTF-8')
+ expectWithParserAndStep('</end>', [['error', 'not well-formed (invalid token)']], p, 1000)
+ p.reset()
+ expectWithParserAndStep('<restart><third>moretext</third><fourth /></restart>', [['startElement', 'restart', {}], ['startElement', 'third', {}], ['text', 'moretext'], ['endElement', 'third'], ['startElement', 'fourth', {}], ['endElement', 'fourth'], ['endElement', 'restart']], p, 1000)
+ }
+ },
+ 'stop and resume': {
+ topic: function () {
+ var cb = this.callback
+ var p = new expat.Parser('UTF-8')
- var expected = ['wrap', 'short', 'short', 'long', 'short', 'long'];
- var received = [];
+ var input = [
+ '<wrap>',
+ '<short />',
+ '<short></short>',
+ '<long />',
+ '<short />',
+ '<long>foo</long>',
+ '</wrap>'
+ ].join('')
- var tolerance = 10/100;
- var expectedRuntime = 1000;
- var start = new Date();
+ var expected = ['wrap', 'short', 'short', 'long', 'short', 'long']
+ var received = []
- p.addListener('startElement', function(name, attrs) {
- received.push(name)
+ var tolerance = 10 / 100
+ var expectedRuntime = 1000
+ var start = new Date()
- // suspend parser for 1/2 second
- if (name == 'long') {
- p.stop()
- setTimeout(function() {
- p.resume()
- }, 500)
- }
- });
+ p.addListener('startElement', function (name, attrs) {
+ received.push(name)
- p.addListener('endElement', function(name) {
- // finished parsing
- if(name == 'wrap') {
- // test elements received (count. naming, order)
- assert.equal(JSON.stringify(received), JSON.stringify(expected));
+ // suspend parser for 1/2 second
+ if (name === 'long') {
+ p.stop()
+ setTimeout(function () {
+ p.resume()
+ }, 500)
+ }
+ })
- // test timing (+-5%)
- var now = new Date();
- var diff = now.getTime() - start.getTime();
- var max = expectedRuntime + expectedRuntime * tolerance,
- min = expectedRuntime - expectedRuntime * tolerance;
+ p.addListener('endElement', function (name) {
+ // finished parsing
+ if (name === 'wrap') {
+ // test elements received (count. naming, order)
+ assert.equal(JSON.stringify(received), JSON.stringify(expected))
- assert.ok(diff < max, 'Runtime within maximum expected time');
- assert.ok(diff > min, 'Runtime at least minimum expected time');
+ // test timing (+-5%)
+ var now = new Date()
+ var diff = now.getTime() - start.getTime()
+ var max = expectedRuntime + expectedRuntime * tolerance
+ var min = expectedRuntime - expectedRuntime * tolerance
- return cb(true);
- }
- });
+ assert.ok(diff < max, 'Runtime within maximum expected time')
+ assert.ok(diff > min, 'Runtime at least minimum expected time')
- assert.ok(p.parse(input));
- },
- 'should have worked': function() {
- assert.ok(true, 'start & stop works')
+ return cb(true)
}
+ })
+
+ assert.ok(p.parse(input))
},
- 'corner cases': {
- 'parse empty string': function() {
- var p = new expat.Parser('UTF-8')
- p.parse('')
- assert.ok(true, 'Did not segfault')
- },
- 'Escaping of ampersands': function() {
- expect('<e>foo & bar</e>',
- [['startElement', 'e', {}],
- ['text', 'foo & bar'],
- ['endElement', 'e']])
- },
- 'parsing twice the same document with the same parser instance should be fine': function() {
- var p = new expat.Parser('UTF-8')
- var xml = '<foo>bar</foo>'
- var result = p.parse(xml)
- assert.ok(result)
- assert.isNull(p.getError())
- p.reset()
- var result2 = p.parse(xml)
- assert.isNull(p.getError())
- assert.ok(result2)
- }
+ 'should have worked': function () {
+ assert.ok(true, 'start & stop works')
+ }
+ },
+ 'corner cases': {
+ 'parse empty string': function () {
+ var p = new expat.Parser('UTF-8')
+ p.parse('')
+ assert.ok(true, 'Did not segfault')
+ },
+ 'Escaping of ampersands': function () {
+ expect('<e>foo & bar</e>',
+ [['startElement', 'e', {}],
+ ['text', 'foo & bar'],
+ ['endElement', 'e']])
+ },
+ 'parsing twice the same document with the same parser instance should be fine': function () {
+ var p = new expat.Parser('UTF-8')
+ var xml = '<foo>bar</foo>'
+ var result = p.parse(xml)
+ assert.ok(result)
+ assert.isNull(p.getError())
+ p.reset()
+ var result2 = p.parse(xml)
+ assert.isNull(p.getError())
+ assert.ok(result2)
+ }
+ },
+ 'statistics': {
+ 'line number': function () {
+ var p = new expat.Parser()
+ assert.equal(p.getCurrentLineNumber(), 1)
+ p.parse('\n')
+ assert.equal(p.getCurrentLineNumber(), 2)
+ p.parse('\n')
+ assert.equal(p.getCurrentLineNumber(), 3)
},
- 'statistics': {
- 'line number': function() {
- var p = new expat.Parser()
- assert.equal(p.getCurrentLineNumber(), 1)
- p.parse('\n')
- assert.equal(p.getCurrentLineNumber(), 2)
- p.parse('\n')
- assert.equal(p.getCurrentLineNumber(), 3)
- },
- 'column number': function() {
- var p = new expat.Parser();
- assert.equal(p.getCurrentColumnNumber(), 0)
- p.parse(' ')
- assert.equal(p.getCurrentColumnNumber(), 1)
- p.parse(' ')
- assert.equal(p.getCurrentColumnNumber(), 2)
- p.parse('\n')
- assert.equal(p.getCurrentColumnNumber(), 0)
- },
- 'byte index': function() {
- var p = new expat.Parser()
- assert.equal(p.getCurrentByteIndex(), -1)
- p.parse('')
- assert.equal(p.getCurrentByteIndex(), -1)
- p.parse('\n')
- assert.equal(p.getCurrentByteIndex(), 1)
- p.parse(' ')
- assert.equal(p.getCurrentByteIndex(), 2)
- },
+ 'column number': function () {
+ var p = new expat.Parser()
+ assert.equal(p.getCurrentColumnNumber(), 0)
+ p.parse(' ')
+ assert.equal(p.getCurrentColumnNumber(), 1)
+ p.parse(' ')
+ assert.equal(p.getCurrentColumnNumber(), 2)
+ p.parse('\n')
+ assert.equal(p.getCurrentColumnNumber(), 0)
},
- 'Stream interface': {
- 'read file': {
- topic: function() {
- var p = expat.createParser()
- this.startTags = 0
- p.on('startElement', function(name) {
- log('startElement', name)
- this.startTags++
- }.bind(this))
- this.endTags = 0
- p.on('endElement', function(name) {
- log('endElement', name)
- this.endTags++
- }.bind(this))
- p.on('end', function() {
- this.ended = true
- log('ended')
- }.bind(this))
- p.on('close', function() {
- this.closed = true
- log('closed')
- this.callback()
- }.bind(this))
- p.on('error', function(error) {
- assert.fail('Error', error)
- }.bind(this))
+ 'byte index': function () {
+ var p = new expat.Parser()
+ assert.equal(p.getCurrentByteIndex(), -1)
+ p.parse('')
+ assert.equal(p.getCurrentByteIndex(), -1)
+ p.parse('\n')
+ assert.equal(p.getCurrentByteIndex(), 1)
+ p.parse(' ')
+ assert.equal(p.getCurrentByteIndex(), 2)
+ }
+ },
+ 'Stream interface': {
+ 'read file': {
+ topic: function () {
+ var p = expat.createParser()
+ this.startTags = 0
+ p.on('startElement', function (name) {
+ log('startElement', name)
+ this.startTags++
+ }.bind(this))
+ this.endTags = 0
+ p.on('endElement', function (name) {
+ log('endElement', name)
+ this.endTags++
+ }.bind(this))
+ p.on('end', function () {
+ this.ended = true
+ log('ended')
+ }.bind(this))
+ p.on('close', function () {
+ this.closed = true
+ log('closed')
+ this.callback()
+ }.bind(this))
+ p.on('error', function (error) {
+ assert.fail('Error', error)
+ })
- var mystic = fs.createReadStream(__dirname + '/mystic-library.xml')
- mystic.pipe(p)
- },
- 'startElement and endElement events': function() {
- assert.ok(this.startTags > 0, 'startElement events at all')
- assert.ok(this.startTags == this.endTags, 'equal amount')
- },
- 'end event': function() {
- assert.ok(this.ended, 'emit end event')
- },
- 'close event': function() {
- assert.ok(this.closed, 'emit close event')
- }
- }
+ var mystic = fs.createReadStream(__dirname + '/mystic-library.xml')
+ mystic.pipe(p)
+ },
+ 'startElement and endElement events': function () {
+ assert.ok(this.startTags > 0, 'startElement events at all')
+ assert.ok(this.startTags === this.endTags, 'equal amount')
+ },
+ 'end event': function () {
+ assert.ok(this.ended, 'emit end event')
+ },
+ 'close event': function () {
+ assert.ok(this.closed, 'emit close event')
+ }
}
+ }
}).export(module)
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-expat.git
More information about the Pkg-javascript-commits
mailing list