retry-unit-tests.ts 1.2 KB
Newer Older
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1 2
#!/usr/bin/env ts-node
/**
3
 * https://github.com/wechaty/wechaty/issues/1084
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
4 5 6 7 8 9 10
 * WebDriver / Puppeteer sometimes will fail(i.e. timeout) with no reason.
 * That will cause the unit tests fail randomly.
 * So we need to retry again when unit tests fail,
 * and treat it's really fail after MAX_RETRY_NUM times.
 */
import { spawn } from 'child_process'

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
11
const MAX_RETRY_NUM = 3
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
12

13
async function main (): Promise<number> {
14
  console.info('Safe Test: starting...')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
15 16 17 18

  let round = 0
  let succ = false
  do {
19
    console.info(`Safe Test: running for round #${round}`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
20
    succ = await unitTest()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
21
    if (succ) { // success!
22
      console.info(`Safe Test: successed at round #${round}!`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
23 24 25 26 27 28
      return 0
    }
  } while (round++ < MAX_RETRY_NUM)
  return 1  // fail finally :(
}

29
async function unitTest () {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
30 31 32
  const child = spawn(
    'npm',
    [
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
33 34
      'run',
      'test:unit',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
35 36
    ],
    {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
37
      shell: true,  // https://stackoverflow.com/a/39682805/1123955
38
      stdio: 'inherit',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
39 40 41 42 43 44 45 46 47 48 49
    },
  )
  return new Promise<boolean>((resolve, reject) => {
    child.once('exit', code =>
      code === 0 ? resolve(true) : resolve(false),
    )
    child.once('error', reject)
  })
}

main()
50 51 52 53 54
  .then(process.exit)
  .catch(e => {
    console.error(e)
    process.exit(1)
  })