misc.spec.ts 7.5 KB
Newer Older
1
#!/usr/bin/env ts-node
2
/**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
3
 *   Wechaty - https://github.com/chatie/wechaty
4
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
5
 *   @copyright 2016-2018 Huan LI <zixia@zixia.net>
6 7 8 9 10 11 12 13 14 15 16 17
 *
 *   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.
18 19
 *
 */
20 21
// tslint:disable:no-shadowed-variable
import * as test  from 'blue-tape'
22
import * as sinon from 'sinon'
23
// const sinonTest   = require('sinon-test')(sinon)
24

25
import * as http      from 'http'
26
import * as express   from 'express'
27

28 29 30 31 32 33
import promiseRetry = require('promise-retry')

import Misc     from './misc'
import {
  log,
}               from './config'
34

35
test('stripHtml()', async t => {
36 37 38
  const HTML_BEFORE_STRIP = 'Outer<html>Inner</html>'
  const HTML_AFTER_STRIP  = 'OuterInner'

39
  const strippedHtml = Misc.stripHtml(HTML_BEFORE_STRIP)
40 41 42
  t.is(strippedHtml, HTML_AFTER_STRIP, 'should strip html as expected')
})

43
test('unescapeHtml()', async t => {
44 45 46
  const HTML_BEFORE_UNESCAPE  = '&apos;|&quot;|&gt;|&lt;|&amp;'
  const HTML_AFTER_UNESCAPE   = `'|"|>|<|&`

47
  const unescapedHtml = Misc.unescapeHtml(HTML_BEFORE_UNESCAPE)
48 49 50
  t.is(unescapedHtml, HTML_AFTER_UNESCAPE, 'should unescape html as expected')
})

51
test('plainText()', async t => {
52 53 54
  const PLAIN_BEFORE  = '&amp;<html>&amp;</html>&amp;<img class="emoji emoji1f4a4" text="[流汗]_web" src="/zh_CN/htmledition/v2/images/spacer.gif" />'
  const PLAIN_AFTER   = '&&&[流汗]'

55
  const plainText = Misc.plainText(PLAIN_BEFORE)
56 57 58 59
  t.is(plainText, PLAIN_AFTER, 'should convert plain text as expected')

})

60
test('digestEmoji()', async t => {
61
  const EMOJI_XML = [
L
lijiarui 已提交
62
    '<img class="emoji emoji1f4a4" text="[流汗]_web" src="/zh_CN/htmledition/v2/images/spacer.gif" />',
63 64
    '<img class="qqemoji qqemoji13" text="[呲牙]_web" src="/zh_CN/htmledition/v2/images/spacer.gif" />',
    '<img class="emoji emoji1f44d" text="_web" src="/zh_CN/htmledition/v2/images/spacer.gif" />',
L
lijiarui 已提交
65
    '<span class="emoji emoji1f334"></span>',
66 67
  ]
  const EMOJI_AFTER_DIGEST  = [
L
lijiarui 已提交
68
    '[流汗]',
69 70
    '[呲牙]',
    '',
L
lijiarui 已提交
71
    '[emoji1f334]',
72
  ]
73

74
  for (let i = 0; i < EMOJI_XML.length; i++) {
75
    const emojiDigest = Misc.digestEmoji(EMOJI_XML[i])
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
76
    t.is(emojiDigest, EMOJI_AFTER_DIGEST[i], 'should digest emoji string ' + i + ' as expected')
77
  }
78 79
})

80
test('unifyEmoji()', async t => {
81 82 83
  const ORIGNAL_XML_LIST: [string[], string][] = [
    [
      [
L
lijiarui 已提交
84 85 86 87 88
        '<img class="emoji emoji1f602" text="_web" src="/zh_CN/htmledition/v2/images/spacer.gif" />',
        '<span class=\"emoji emoji1f602\"></span>',
      ],
        '<emoji code="emoji1f602"/>',
    ],
89
  ]
90

91 92
  ORIGNAL_XML_LIST.forEach(([xmlList, expectedEmojiXml]) => {
    xmlList.forEach(xml => {
93
      const unifiedXml = Misc.unifyEmoji(xml)
94 95 96
      t.is(unifiedXml, expectedEmojiXml, 'should convert the emoji xml to the expected unified xml')
    })
  })
97
})
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
98

99
test('stripEmoji()', async t => {
100 101
  const EMOJI_STR = [
    [
L
lijiarui 已提交
102 103 104 105 106 107 108
      'ABC<img class="emoji emoji1f4a4" text="[流汗]_web" src="/zh_CN/htmledition/v2/images/spacer.gif" />DEF',
      'ABCDEF',
    ],
    [
      'UVW<span class="emoji emoji1f334"></span>XYZ',
      'UVWXYZ',
    ],
109 110 111
  ]

  EMOJI_STR.forEach(([emojiStr, expectResult]) => {
112
    const result = Misc.stripEmoji(emojiStr)
113 114 115
    t.is(result, expectResult, 'should strip to the expected str')
  })

116
  const empty = Misc.stripEmoji(undefined)
117 118 119
  t.is(empty, '', 'should return empty string for `undefined`')
})

120
test('downloadStream() for media', async t => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
121
  const app = express()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
122 123 124
  app.use(require('cookie-parser')())
  app.get('/ding', function(req, res) {
    // console.log(req.cookies)
125
    t.ok(req.cookies, 'should has cookies in req')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
126
    t.is(req.cookies.life, '42', 'should has a cookie named life value 42')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
127 128 129
    res.end('dong')
  })

130
  const server = http.createServer(app)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
131
  server.on('clientError', (err, socket) => {
132
    t.fail('server on clientError' + err)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
133 134
    socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
  })
135
  server.listen(65534)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
136

137
  try {
138
    const s = await Misc.urlStream('http://127.0.0.1:65534/ding', [{name: 'life', value: 42}])
139 140 141 142 143 144 145 146 147 148 149 150
    await new Promise((resolve, reject) => {
      s.on('data', (chunk) => {
        // console.log(`BODY: ${chunk}`)
        t.is(chunk.toString(), 'dong', 'should success download dong from downloadStream()')
        server.close()
        resolve()
      })
      s.on('error', reject)
    })
  } catch (e) {
    t.fail('downloadStream() exception: ' + e.message)
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
151
})
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
152

153
test('getPort() for an available socket port', async t => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
154 155
  const PORT = 8788

156
  let port = await Misc.getPort(PORT)
157 158
  t.not(port, PORT, 'should not be same port even it is available(to provent conflict between concurrency tests in AVA)')

Huan (李卓桓)'s avatar
linting  
Huan (李卓桓) 已提交
159
  let ttl = 17
160 161 162 163
  while (ttl-- > 0) {
    try {
      const app = express()
      const server = app.listen(PORT)
164
      port = await Misc.getPort(PORT)
165 166 167 168 169
      server.close()
    } catch (e) {
      t.fail('should not exception: ' + e.message + ', ' + e.stack)
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
170
  t.pass('should has no exception after loop test')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
171
})
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211

test('promiseRetry()', async t => {
  const EXPECTED_RESOLVE = 'Okey'
  const EXPECTED_REJECT  = 'NotTheTime'

  function delayedFactory(timeout: number) {
    const startTime = Date.now()
    return function() {
      const nowTime = Date.now()
      log.silly('MiscTest', 'promiseRetry() delayedFactory(' + timeout + '): ' + (nowTime - startTime))
      if (nowTime - startTime > timeout) {
        return Promise.resolve(EXPECTED_RESOLVE)
      }
      return Promise.reject(EXPECTED_REJECT)
    }
  }

  const thenSpy = sinon.spy()

  const delay500 = delayedFactory(500)
  await promiseRetry(
    {
      minTimeout : 1,
      retries    : 1,
    },
    function(retry) {
      return delay500().catch(retry)
    },
  ).catch((e: any) => {
    thenSpy(e)
  })
  t.true(thenSpy.withArgs(EXPECTED_REJECT).calledOnce, 'should got EXPECTED_REJECT when wait not enough')

  thenSpy.resetHistory()
  const anotherDelay50 = delayedFactory(50)
  await promiseRetry(
    {
      minTimeout: 1,
      retries: 100,
    },
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    function(retry, attempt) {
      log.silly('MiscTest', 'promiseRetry() attempt = %d', attempt)
      return anotherDelay50().catch(retry)
    },
  )
  .then((r: string) => {
    thenSpy(r)
  })
  t.true(thenSpy.withArgs(EXPECTED_RESOLVE).calledOnce, 'should got EXPECTED_RESOLVE when wait enough')
})

test('retry()', async t => {
  const EXPECTED_RESOLVE = 'Okey'
  const EXPECTED_REJECT  = 'NotTheTime'

  function delayedFactory(timeout: number) {
    const startTime = Date.now()
    return function() {
      const nowTime = Date.now()
      log.silly('MiscTest', 'promiseRetry() delayedFactory(' + timeout + '): ' + (nowTime - startTime))
      if (nowTime - startTime > timeout) {
        return Promise.resolve(EXPECTED_RESOLVE)
      }
      return Promise.reject(EXPECTED_REJECT)
    }
  }

  const thenSpy = sinon.spy()

  const anotherDelay50 = delayedFactory(50)
  await Misc.retry(
    function(retry, attempt) {
      log.silly('MiscTest', 'promiseRetry() attempt = %d', attempt)
245 246 247 248 249 250 251 252
      return anotherDelay50().catch(retry)
    },
  )
  .then((r: string) => {
    thenSpy(r)
  })
  t.true(thenSpy.withArgs(EXPECTED_RESOLVE).calledOnce, 'should got EXPECTED_RESOLVE when wait enough')
})