1 | 'use strict'
|
2 |
|
3 |
|
4 |
|
5 | module.exports = parse
|
6 |
|
7 | const pickup = require('../../')
|
8 | const { debuglog } = require('util')
|
9 |
|
10 | const debug = debuglog('pickup')
|
11 |
|
12 | function defaults (opts) {
|
13 | if (opts.eventMode === undefined) {
|
14 | opts.eventMode = true
|
15 | }
|
16 | if (opts.charset === undefined) {
|
17 | opts.charset = Math.round(Math.random()) > 0.5 ? 'utf8' : null
|
18 | }
|
19 | return opts
|
20 | }
|
21 |
|
22 | function parse (opts, cb) {
|
23 | opts = defaults(opts)
|
24 |
|
25 | const xml = opts.xml
|
26 | const wanted = opts.wanted
|
27 | const t = opts.t
|
28 | const parser = pickup(opts)
|
29 |
|
30 | let e = 0
|
31 |
|
32 | pickup.EVENTS.forEach((ev) => {
|
33 | if (ev === 'readable') return
|
34 |
|
35 | parser.on(ev, (found) => {
|
36 | debug({ wanted: wanted[e], found: [ev, found] })
|
37 |
|
38 | const obj = wanted[e]
|
39 | t.ok(obj, 'should not emit unexpected event: ' + ev)
|
40 |
|
41 | const name = obj[0]
|
42 | t.is(ev, name, 'should be expected event name')
|
43 |
|
44 | const data = obj[1]
|
45 |
|
46 | if (ev === 'error') {
|
47 | t.same(found, data, 'should be expected error')
|
48 | } else if (ev === 'entry') {
|
49 | t.deepEqual(found, pickup.entry(data), 'should be expected entry')
|
50 | } else if (ev === 'feed') {
|
51 | t.deepEqual(found, pickup.feed(data), 'should be expected feed')
|
52 | } else if (ev === 'data' && typeof found === 'string') {
|
53 | const json = JSON.parse(found)
|
54 | t.deepEqual(json, data, 'should be expected data')
|
55 | } else if (ev === 'end') {
|
56 | t.is(e + 1, wanted.length, 'should emit all')
|
57 | t.is(parser.parser, null, 'should release parser')
|
58 | t.is(parser.state, null, 'should release state')
|
59 | cb()
|
60 | } else {
|
61 | t.same(found, data)
|
62 | }
|
63 |
|
64 | e++
|
65 | })
|
66 | })
|
67 |
|
68 | function write () {
|
69 | let start = 0
|
70 | let end = 0
|
71 | let ok = true
|
72 | let slice
|
73 |
|
74 | do {
|
75 | const size = start + Math.ceil(Math.random() * (xml.length - start))
|
76 |
|
77 | end = opts.size || size
|
78 | slice = xml.slice(start, Math.min(end, xml.length))
|
79 | ok = parser.write(slice)
|
80 | } while (ok && (start = end) < xml.length)
|
81 |
|
82 | if (!ok) {
|
83 | parser.once('drain', write)
|
84 | } else {
|
85 | parser.end()
|
86 | }
|
87 | }
|
88 |
|
89 | write()
|
90 | }
|