From dd228d207bbbc8f363cf3507750bea7b4631853e Mon Sep 17 00:00:00 2001 From: "Zhuohuan LI (CARPE DIEM)" Date: Wed, 26 Oct 2016 16:14:01 +0800 Subject: [PATCH] code clean --- .github/ISSUE_TEMPLATE.md | 3 +- package.json | 4 +- src/brolog-env.ts | 8 ++- src/config.ts | 3 + src/puppet-web/browser-cookie.ts | 31 +++++----- src/puppet-web/browser-driver.ts | 47 ++++++++------- src/puppet-web/browser.ts | 15 ++--- src/puppet-web/event.ts | 4 +- src/puppet-web/puppet-web.ts | 28 +++++---- src/state-monitor.ts | 50 ++++++++++++---- src/wechaty.ts | 6 ++ test/puppet-web/bridge.spec.ts | 95 ++++++++++-------------------- test/puppet-web/browser.spec.ts | 6 +- test/puppet-web/puppet-web.spec.ts | 8 ++- test/webdriver.spec.ts | 36 +++++------ 15 files changed, 180 insertions(+), 164 deletions(-) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 82f59181..aae6de86 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,4 +1,4 @@ -### Please run `npm run doctor` and paste the output here +### Run `npm run doctor` and paste the output here ### Expected behavior @@ -10,3 +10,4 @@ ### Steps to reproduce the behavior (and fixes, if any) +### Paste the full output logs here with `WECHATY_LOG=silly` set diff --git a/package.json b/package.json index 22145e50..7e2c8515 100644 --- a/package.json +++ b/package.json @@ -22,13 +22,13 @@ "lint": "npm run eslint && npm run tslint", "eslint": "eslint \"{bin,example,src,test}/**/*.js\"", "tslint": "tslint \"{bin,example,src,test}/**/*.ts\" && tsc --noEmit", - "sloc": "sloc . --details --format cli-table --keys total,source,comment --exclude \"node_modules|doc\" && sloc . --exclude \"node_modules|doc\"", "pretest": "npm run lint && npm run clean && npm run build", + "sloc": "sloc . --details --format cli-table --keys total,source,comment --exclude \"\\.\\./|dist/|doc/|node_modules/\" && sloc ./ --exclude \"\\.\\./|dist/|doc/|node_modules/\"", "test": "npm run test:chrome", "posttest": "npm run clean && npm run sloc", "test:phantomjs": "cross-env LC_ALL=C WECHATY_LOG=info WECHATY_HEAD=phantomjs ava --timeout=10m \"dist/test/*.spec.js\"", "test:phantomjs.bak": "cross-env LC_ALL=C WECHATY_LOG=info WECHATY_HEAD=phantomjs ava --timeout=10m \"dist/{src,test}/**/*.spec.js\"", - "test:chrome": "cross-env LC_ALL=C WECHATY_LOG=info WECHATY_HEAD=chrome ava --concurrency 2 --ext js --timeout=10m \"dist/{src,test}/**/*.spec.js\"", + "test:chrome": "cross-env LC_ALL=C WECHATY_LOG=verbose WECHATY_HEAD=chrome ava --concurrency 0 --ext js --timeout=10m \"dist/{src,test}/**/*.spec.js\"", "testdev": "cross-env LC_ALL=C WECHATY_LOG=silly ava --ext ts --serial --verbose --fail-fast --timeout=3m", "testdist": "WECHATY_HEAD=phantomjs ava --ext ts --verbose --fail-fast --timeout=3m", "ava": "cross-env LC_ALL=C WECHATY_LOG=verbose ts-node node_modules/.bin/ava \"{src,test}/**/*.spec.js\"", diff --git a/src/brolog-env.ts b/src/brolog-env.ts index d0d60ca5..de322f41 100644 --- a/src/brolog-env.ts +++ b/src/brolog-env.ts @@ -5,15 +5,19 @@ * */ // const log = require('npmlog') -import Brolog from 'brolog' +import { + Brolog +} from 'brolog' const level = process.env['WECHATY_LOG'] + +// use a typescript switch/case/default: never to replace regex const levelRegexStr = 'silly|verbose|info|warn|error|silent' const levelRegex = new RegExp(levelRegexStr, 'i') if (levelRegex.test(level)) { // log.level = level.toLowerCase() Brolog.level(level) - Brolog.verbose('Brolog', 'WECHATY_LOG set level to %s', level) + Brolog.silly('Brolog', 'WECHATY_LOG set level to %s', level) } else if (level) { Brolog.warn('Brolog', 'env WECHATY_LOG(%s) must be one of silly|verbose|info|warn|error|silent', level) diff --git a/src/config.ts b/src/config.ts index 73764f83..c90f31e4 100644 --- a/src/config.ts +++ b/src/config.ts @@ -161,6 +161,9 @@ export type RecommendInfo = { export interface Sayable { say(content: string, replyTo?: any|any[]): Promise } +export interface Sleepable { + sleep(millisecond: number): Promise +} export * from './brolog-env' diff --git a/src/puppet-web/browser-cookie.ts b/src/puppet-web/browser-cookie.ts index 22cffaab..bbf8ce10 100644 --- a/src/puppet-web/browser-cookie.ts +++ b/src/puppet-web/browser-cookie.ts @@ -40,7 +40,7 @@ export class BrowserCookie { public async read(): Promise { // just check cookies, no file operation - log.verbose('PuppetWebBrowserCookie', 'checkSession()') + log.verbose('PuppetWebBrowserCookie', 'read()') // if (this.browser.dead()) { // throw new Error('checkSession() - browser dead') @@ -50,16 +50,16 @@ export class BrowserCookie { try { // `as any as DriverCookie` because selenium-webdriver @types is outdated with 2.x, where we r using 3.0 const cookies = await this.driver.manage().getCookies() as any as CookieType[] - log.silly('PuppetWebBrowserCookie', 'checkSession %s', cookies.map(c => c.name).join(',')) + log.silly('PuppetWebBrowserCookie', 'read() %s', cookies.map(c => c.name).join(',')) return cookies } catch (e) { - log.error('PuppetWebBrowserCookie', 'checkSession() getCookies() exception: %s', e && e.message || e) + log.error('PuppetWebBrowserCookie', 'read() getCookies() exception: %s', e && e.message || e) throw e } } public async clean(): Promise { - log.verbose('PuppetWebBrowserCookie', `cleanSession(${this.storeFile})`) + log.verbose('PuppetWebBrowserCookie', 'clean() file %s', this.storeFile) if (!this.storeFile) { return } @@ -70,7 +70,7 @@ export class BrowserCookie { await new Promise((resolve, reject) => { fs.unlink(filename, err => { if (err && err.code !== 'ENOENT') { - log.silly('PuppetWebBrowserCookie', 'cleanSession() unlink session file %s fail: %s', filename, err.message) + log.silly('PuppetWebBrowserCookie', 'clean() unlink store file %s fail: %s', filename, err.message) } resolve() }) @@ -79,9 +79,9 @@ export class BrowserCookie { } public async save(): Promise { - log.silly('PuppetWebBrowserCookie', `saveSession(${this.storeFile})`) + log.silly('PuppetWebBrowserCookie', 'save() to file %s', this.storeFile) if (!this.storeFile) { - log.verbose('PuppetWebBrowserCookie', 'save() no session store file') + log.verbose('PuppetWebBrowserCookie', 'save() no store file') return } const storeFile = this.storeFile @@ -114,42 +114,41 @@ export class BrowserCookie { // .then(cookies => { // log.silly('PuppetWeb', 'saving %d cookies for session: %s', cookies.length // , util.inspect(cookies.map(c => { return {name: c.name /*, value: c.value, expiresType: typeof c.expires, expires: c.expires*/} }))) - log.silly('PuppetWebBrowserCookie', 'saving %d cookies for session: %s', cookies.length, cookies.map(c => c.name).join(',')) + log.silly('PuppetWebBrowserCookie', 'save() saving %d cookies: %s', cookies.length, cookies.map(c => c.name).join(',')) const jsonStr = JSON.stringify(cookies) await new Promise((resolve, reject) => { fs.writeFile(storeFile, jsonStr, err => { if (err) { - log.error('PuppetWebBrowserCookie', 'saveSession() fail to write file %s: %s', filename, err.errno) + log.error('PuppetWebBrowserCookie', 'save() fail to write file %s: %s', filename, err.errno) reject(err) } - log.silly('PuppetWebBrowserCookie', 'saved session(%d cookies) to %s', cookies.length, filename) + log.silly('PuppetWebBrowserCookie', 'save() %d cookies to %s', cookies.length, filename) resolve(cookies) }) }) } catch (e) { - log.error('PuppetWebBrowserCookie', 'saveSession() getCookies() exception: %s', e.message) + log.error('PuppetWebBrowserCookie', 'save() getCookies() exception: %s', e.message) throw e } } public async load(): Promise { - log.verbose('PuppetWebBrowserCookie', 'loadSession() from %s', this.storeFile ? this.storeFile : '' ) - if (!this.storeFile) { - log.verbose('PuppetWebBrowserCookie', 'load() no session store file') + log.silly('PuppetWebBrowserCookie', 'load() skipped because no session store file') return // } else if (this.browser.dead()) { // throw new Error('loadSession() - browser dead') } const storeFile = this.storeFile + log.verbose('PuppetWebBrowserCookie', 'load() from %s', storeFile) await new Promise((resolve, reject) => { fs.readFile(storeFile, (err, jsonStr) => { if (err) { - if (err) { log.silly('PuppetWebBrowserCookie', 'loadSession(%s) skipped because error code: %s', this.storeFile, err.code) } + if (err) { log.silly('PuppetWebBrowserCookie', 'load(%s) skipped because error code: %s', this.storeFile, err.code) } return reject(new Error('error code:' + err.code)) } const cookies = JSON.parse(jsonStr.toString()) @@ -161,7 +160,7 @@ export class BrowserCookie { resolve(cookies) }) .catch(e => { - log.error('PuppetWebBrowserCookie', 'loadSession() addCookies() exception: %s', e.message) + log.error('PuppetWebBrowserCookie', 'load() add() exception: %s', e.message) reject(e) }) }) diff --git a/src/puppet-web/browser-driver.ts b/src/puppet-web/browser-driver.ts index 0e957258..794b9c08 100644 --- a/src/puppet-web/browser-driver.ts +++ b/src/puppet-web/browser-driver.ts @@ -27,46 +27,48 @@ export class BrowserDriver { } public async init(): Promise { - log.verbose('PuppetWebBrowser', 'initDriver() for head: %s', this.head) + log.verbose('PuppetWebBrowserDriver', 'init() for head: %s', this.head) if (this.driver) { - await this.driver.close() - await this.driver.quit() + try { + await this.driver.close() + await this.driver.quit() + } catch (e) { + log.warn('PuppetWebBrowserDriver', 'init() this.driver.{close,quit}() exception: %s' + , e.message + ) + } } - const head = this.head - - switch (true) { - case !head: // no head default to phantomjs - case /phantomjs/i.test(head): - case /phantom/i.test(head): + switch (this.head) { + case 'phantomjs': this.driver = this.getPhantomJsDriver() break - case /firefox/i.test(head): + case 'firefox': this.driver = new Builder() .setAlertBehavior('ignore') .forBrowser('firefox') .build() break - case /chrome/i.test(head): + case 'chrome': this.driver = this.getChromeDriver() break default: // unsupported browser head - throw new Error('unsupported head: ' + head) + throw new Error('unsupported head: ' + this.head) } - this.driver.manage() - .timeouts() - .setScriptTimeout(10000) + await this.driver.manage() + .timeouts() + .setScriptTimeout(10000) return this } private getChromeDriver(): WebDriver { - log.verbose('PuppetWebBrowser', 'getChromeDriver()') + log.verbose('PuppetWebBrowserDriver', 'getChromeDriver()') /** * http://stackoverflow.com/a/27733960/1123955 @@ -88,6 +90,7 @@ export class BrowserDriver { // , binary: require('chromedriver').path } if (Config.isDocker) { + log.verbose('PuppetWebBrowserDriver', 'getChromeDriver() wechaty in docker confirmed(should not show this in CI)') options['binary'] = Config.CMD_CHROMIUM } @@ -138,8 +141,8 @@ export class BrowserDriver { .set('phantomjs.binary.path', phantomjsExe) .set('phantomjs.cli.args', phantomjsArgs) - log.silly('PuppetWebBrowser', 'phantomjs binary: ' + phantomjsExe) - log.silly('PuppetWebBrowser', 'phantomjs args: ' + phantomjsArgs.join(' ')) + log.silly('PuppetWebBrowserDriver', 'phantomjs binary: ' + phantomjsExe) + log.silly('PuppetWebBrowserDriver', 'phantomjs args: ' + phantomjsArgs.join(' ')) const driver = new Builder() .withCapabilities(customPhantom) @@ -177,7 +180,7 @@ export class BrowserDriver { // public driver1(newDriver?: WebDriver | null): WebDriver | void { // if (newDriver !== undefined) { - // log.verbose('PuppetWebBrowser', 'driver(%s)' + // log.verbose('PuppetWebBrowserDriver', 'driver(%s)' // , newDriver // ? newDriver.constructor.name // : null @@ -199,12 +202,12 @@ export class BrowserDriver { // if (!this.driver) { // const e = new Error('no driver') - // log.warn('PuppetWebBrowser', 'driver() exception: %s', e.message) + // log.warn('PuppetWebBrowserDriver', 'driver() exception: %s', e.message) // throw e // } // // if (!this.driver.getSession()) { // // const e = new Error('no driver session') - // // log.warn('PuppetWebBrowser', 'driver() exception: %s', e.message) + // // log.warn('PuppetWebBrowserDriver', 'driver() exception: %s', e.message) // // this.driver.quit() // // throw e // // } @@ -213,8 +216,8 @@ export class BrowserDriver { // } public close() { return this.driver.close() } - public executeScript() { return this.driver.executeScript.apply(this.driver, arguments) } public executeAsyncScript() { return this.driver.executeAsyncScript.apply(this.driver, arguments) } + public executeScript() { return this.driver.executeScript.apply(this.driver, arguments) } public get(url: string) { return this.driver.get(url) } public getSession() { return this.driver.getSession() } public manage() { return this.driver.manage() } diff --git a/src/puppet-web/browser.ts b/src/puppet-web/browser.ts index de84c0f6..3a6db746 100644 --- a/src/puppet-web/browser.ts +++ b/src/puppet-web/browser.ts @@ -55,7 +55,7 @@ export class Browser extends EventEmitter { public toString() { return `Browser({head:${this.setting.head})` } - public async init(): Promise { + public async init(): Promise { // this.targetState('open') // this.currentState('opening') this.state.target('open') @@ -92,7 +92,7 @@ export class Browser extends EventEmitter { // this.currentState('open') this.state.current('open') - return this + return } catch (e) { log.error('PuppetWebBrowser', 'init() exception: %s', e.message) @@ -116,11 +116,12 @@ export class Browser extends EventEmitter { } } - public async refresh(): Promise { + public async refresh(): Promise { log.verbose('PuppetWebBrowser', 'refresh()') - return await this.driver - .navigate() - .refresh() + await this.driver + .navigate() + .refresh() + return } public async restart(): Promise { @@ -137,7 +138,7 @@ export class Browser extends EventEmitter { await this.init() } - public async quit(): Promise { + public async quit(): Promise { log.verbose('PuppetWebBrowser', 'quit()') // if (this.currentState() === 'closing') { diff --git a/src/puppet-web/event.ts b/src/puppet-web/event.ts index ae1be5cb..5861e936 100644 --- a/src/puppet-web/event.ts +++ b/src/puppet-web/event.ts @@ -90,10 +90,10 @@ async function onBrowserDead(this: PuppetWeb, e): Promise { return } - this.browser = await this.initBrowser() + await this.initBrowser() log.verbose('PuppetWebEvent', 'onBrowserDead() new browser inited') - this.bridge = await this.initBridge() + await this.initBridge() log.verbose('PuppetWebEvent', 'onBrowserDead() bridge re-inited') const dong = await this.ding() diff --git a/src/puppet-web/puppet-web.ts b/src/puppet-web/puppet-web.ts index 3d8815b9..fd02ae45 100644 --- a/src/puppet-web/puppet-web.ts +++ b/src/puppet-web/puppet-web.ts @@ -109,7 +109,7 @@ export class PuppetWeb extends Puppet { } } - public async quit(): Promise { + public async quit(): Promise { log.verbose('PuppetWeb', 'quit()') // this.targetState('dead') @@ -177,11 +177,10 @@ export class PuppetWeb extends Puppet { log.verbose('PuppetWeb', 'quit() done') // this.currentState('dead') this.state.current('dead') - return this // for Chaining // }) } - public async initBrowser(): Promise { + public async initBrowser(): Promise { log.verbose('PuppetWeb', 'initBrowser()') const browser = new Browser({ head: this.setting.head @@ -194,7 +193,7 @@ export class PuppetWeb extends Puppet { // if (this.targetState() !== 'live') { if (this.state.target() !== 'live') { - log.warn('PuppetWeb', 'initBrowser() found targetState != live, no init anymore') + log.warn('PuppetWeb', 'initBrowser() found state.target()) != live, no init anymore') // return Promise.resolve('skipped') return Promise.reject('skipped') } @@ -207,10 +206,10 @@ export class PuppetWeb extends Puppet { log.error('PuppetWeb', 'initBrowser() exception: %s', e.message) throw e } - return browser // follow func name meaning + return } - public initBridge(): Promise { + public async initBridge(): Promise { log.verbose('PuppetWeb', 'initBridge()') const bridge = new Bridge( this // use puppet instead of browser, is because browser might change(die) duaring run time @@ -226,7 +225,7 @@ export class PuppetWeb extends Puppet { return Promise.reject(errMsg) } - return bridge.init() + await bridge.init() .catch(e => { if (!this.browser) { log.warn('PuppetWeb', 'initBridge() without browser?') @@ -237,9 +236,10 @@ export class PuppetWeb extends Puppet { throw e } }) + return } - private initServer(): Promise { + private async initServer(): Promise { log.verbose('PuppetWeb', 'initServer()') const server = new Server(this.port) @@ -264,16 +264,17 @@ export class PuppetWeb extends Puppet { // if (this.targetState() !== 'live') { if (this.state.target() !== 'live') { - const errMsg = 'initServer() found targetState != live, no init anymore' + const errMsg = 'initServer() found state.target() != live, no init anymore' log.warn('PuppetWeb', errMsg) return Promise.reject(errMsg) } - return server.init() + await server.init() .catch(e => { log.error('PuppetWeb', 'initServer() exception: %s', e.message) throw e }) + return } public reset(reason?: string): void { @@ -291,7 +292,7 @@ export class PuppetWeb extends Puppet { * use Message.self() instead */ public self(message: Message): boolean { - log.warn('PuppetWeb', 'self() method deprecated. use Message.self() instead') + log.warn('PuppetWeb', 'DEPRECATED self() method. use Message.self() instead') if (!this.userId) { log.warn('PuppetWeb', 'self() got no this.userId') @@ -358,12 +359,13 @@ export class PuppetWeb extends Puppet { /** * logout from browser, then server will emit `logout` event */ - public logout() { - return this.bridge.logout() + public async logout(): Promise { + await this.bridge.logout() .catch(e => { log.error('PuppetWeb', 'logout() exception: %s', e.message) throw e }) + return } public getContact(id: string): Promise { diff --git a/src/state-monitor.ts b/src/state-monitor.ts index bead9595..ec8c1da8 100644 --- a/src/state-monitor.ts +++ b/src/state-monitor.ts @@ -16,7 +16,6 @@ import { log } from './config' * A - State A * B - State B */ - export class StateMonitor { private _target: A|B private _current: A|B @@ -25,45 +24,70 @@ export class StateMonitor { constructor(private client: string, initState: A|B) { log.verbose('StateMonitor', 'constructor(%s, %s)', client, initState) - this.target(initState) - this.current(initState, true) + this._target = initState + this._current = initState + this._stable = true } + /** + * set/get target state + */ public target(newState?: A|B): A|B { if (newState) { - log.verbose('StateMonitor', 'target(%s) %s state change from %s to %s' - , this.client, newState - , this._target, newState - ) + log.verbose('StateMonitor', '%s.state.target(%s) from %s' + , this.client + , newState + , this._target + ) this._target = newState } else { - log.verbose('StateMonitor', 'target() %s state is %s', this.client, this._target) + log.silly('StateMonitor', '%s.state.target() is %s', this.client, this._target) } return this._target } + /** + * set/get current state + * @param stable boolean true for stable, false for inprocess + */ public current(newState?: A|B, stable = true): A|B { if (newState) { - log.verbose('StateMonitor', 'current(%s, %s) %s state change from %s:%s to %s:%s' - , newState, stable + log.verbose('StateMonitor', '%s.state.current(%s, %s) from (%s, %s)' , this.client - , this._current, this._stable , newState, stable + , this._current, this._stable ) + if (this._current === newState && this._stable === stable + && stable === false // warn for inprocess current state change twice, mostly like a logic bug outside + ) { + log.warn('StateMonitor', '%s.state.current(%s, %s) called but there are already in the same state' + , this.client + , newState, stable + ) + const e = new Error('current unchange') + log.verbose('StateMonitor', e.stack) + } this._current = newState this._stable = stable } else { - log.verbose('StateMonitor', 'current() %s state is %s', this.client, this._current) + log.silly('StateMonitor', '%s.state.current() is %s', this.client, this._current) } return this._current } + /** + * does the current state be stable(not inprocess)? + */ public stable() { - log.verbose('StateMonitor', 'stable() %s state is %s', this.client, this._stable) + log.silly('StateMonitor', '%s.state.stable() is %s', this.client, this._stable) return this._stable } + /** + * does the current state be inprocess(not stable)? + */ public inprocess() { + log.silly('StateMonitor', '%s.state.inprocess() is %s', this.client, !this._stable) return !this._stable } } diff --git a/src/wechaty.ts b/src/wechaty.ts index 0069ecd7..845473e7 100644 --- a/src/wechaty.ts +++ b/src/wechaty.ts @@ -327,6 +327,12 @@ export class Wechaty extends EventEmitter implements Sayable { return } + public sleep(millisecond: number): Promise { + return new Promise(resolve => { + setTimeout(resolve, millisecond) + }) + } + /** * @deprecated */ diff --git a/test/puppet-web/bridge.spec.ts b/test/puppet-web/bridge.spec.ts index c88d5d7e..691ea0b9 100644 --- a/test/puppet-web/bridge.spec.ts +++ b/test/puppet-web/bridge.spec.ts @@ -9,7 +9,7 @@ import { import { spy } from 'sinon' -test('Bridge retry-promise testing', async t => { +test('Bridge retry-promise test', async t => { // co(function* () { const EXPECTED_RESOLVE = 'Okey' const EXPECTED_REJECT = 'NotTheTime' @@ -33,10 +33,10 @@ test('Bridge retry-promise testing', async t => { await retryPromise({ max: 1, backoff: 1 }, function() { return delay500() }) - .then(r => { - thenSpy(r) - // t.fail('should not resolved retry-promise here') - }) + // .then(r => { + // thenSpy(r) + // // t.fail('should not resolved retry-promise here') + // }) .catch(e => { thenSpy(e) // t.is(e, EXPECTED_REJECT, `retry-promise got ${EXPECTED_REJECT} when wait not enough`) @@ -52,22 +52,11 @@ test('Bridge retry-promise testing', async t => { thenSpy(r) // t.is(r, EXPECTED_RESOLVE, `retryPromise got "${EXPECTED_RESOLVE}" when wait enough`) }) - .catch(e => { - thenSpy(e) - // t.fail(`should not be rejected(with ${e}) when there is enough wait`) - }) + // .catch(e => { + // thenSpy(e) + // // t.fail(`should not be rejected(with ${e}) when there is enough wait`) + // }) t.true(thenSpy.withArgs(EXPECTED_RESOLVE).calledOnce, 'should got EXPECTED_RESOLVE when wait enough') - - // }) - // .catch(e => { // REJECTED - // t.fail(e) - // }) - // .then(r => { // FINALLY - // t.end() - // }) - // .catch(e => { // EXCEPTION - // t.fail(e) - // }) }) test('Bridge smoking test', async t => { @@ -80,47 +69,27 @@ test('Bridge smoking test', async t => { const b = new Bridge(mockPuppet as PuppetWeb, PORT) t.truthy(b, 'should instanciated a bridge with mocked puppet') - // co(function* () { - await browser.init() - t.pass('should instanciated a browser') - - await browser.open() - t.pass('should open success') - - await b.inject() - t.pass('should injected WechatyBro') - - const retDing = await b.execute('return WechatyBro.ding()') - t.is(retDing, 'dong', 'should got dong after execute WechatyBro.ding()') - - // @deprecated - // const retReady = await b.execute('return WechatyBro.isReady()') - // t.is(typeof retReady, 'boolean', 'should got a boolean return after execute WechatyBro.isReady()') - - const retCode = await b.proxyWechaty('isLogin') - t.is(typeof retCode, 'boolean', 'should got a boolean after call proxyWechaty(isLogin)') - - await b.quit() - t.pass('b.quit()') - await browser.quit() - t.pass('browser.quit()') - - // }) - // .catch(e => { // Rejected - // t.fail('co promise rejected:' + e) - // }) - // .then(r => { // Finally - // return co(function* () { - // await b.quit() - // t.pass('b.quit()') - // await browser.quit() - // t.pass('browser.quit()') - - // t.end() - // }) - // }) - // .catch(e => { // Exception - // t.fail('Test Exception:' + e) - // t.end() - // }) + await browser.init() + t.pass('should instanciated a browser') + + await browser.open() + t.pass('should open success') + + await b.inject() + t.pass('should injected WechatyBro') + + const retDing = await b.execute('return WechatyBro.ding()') + t.is(retDing, 'dong', 'should got dong after execute WechatyBro.ding()') + + // @deprecated + // const retReady = await b.execute('return WechatyBro.isReady()') + // t.is(typeof retReady, 'boolean', 'should got a boolean return after execute WechatyBro.isReady()') + + const retCode = await b.proxyWechaty('isLogin') + t.is(typeof retCode, 'boolean', 'should got a boolean after call proxyWechaty(isLogin)') + + await b.quit() + t.pass('b.quit()') + await browser.quit() + t.pass('browser.quit()') }) diff --git a/test/puppet-web/browser.spec.ts b/test/puppet-web/browser.spec.ts index f33493dc..ba7f4dbe 100644 --- a/test/puppet-web/browser.spec.ts +++ b/test/puppet-web/browser.spec.ts @@ -13,7 +13,7 @@ import { const PROFILE = Config.DEFAULT_PROFILE + '-' + process.pid + '-' let profileCounter = 1 -test('Browser class cookie smoking tests', async t => { +test('Browser Cookie smoking test', async t => { const b = new Browser() t.truthy(b, 'should instanciate a browser instance') @@ -78,7 +78,7 @@ test('Browser class cookie smoking tests', async t => { await b.quit() }) -test('Browser session save before quit, and load after restart', async t => { +test('Browser Cookie save/load test', async t => { const profileName = PROFILE + profileCounter++ let b = new Browser({ @@ -90,7 +90,7 @@ test('Browser session save before quit, and load after restart', async t => { * use exception to call b.quit() to clean up */ try { - t.truthy(b, 'new Browser') + t.truthy(b, 'should get a new Browser') // b.targetState('open') b.state.target('open') diff --git a/test/puppet-web/puppet-web.spec.ts b/test/puppet-web/puppet-web.spec.ts index c6c06f88..9a183d8b 100644 --- a/test/puppet-web/puppet-web.spec.ts +++ b/test/puppet-web/puppet-web.spec.ts @@ -67,8 +67,12 @@ test.serial('PuppetWeb server/browser communication', async t => { await pw.init() t.pass('should be inited') - const ret = await dingSocket(pw.server) - t.is(ret, EXPECTED_DING_DATA, 'should got EXPECTED_DING_DATA after resolved dingSocket()') + try { + const ret = await dingSocket(pw.server) + t.is(ret, EXPECTED_DING_DATA, 'should got EXPECTED_DING_DATA after resolved dingSocket()') + } catch (e) { + t.fail(e.message) + } await pw.quit() diff --git a/test/webdriver.spec.ts b/test/webdriver.spec.ts index c6d79979..cff4ce55 100644 --- a/test/webdriver.spec.ts +++ b/test/webdriver.spec.ts @@ -18,32 +18,32 @@ import { * if 2 tests run parallel in the same process, * there will have race conditions for the conflict of `getBrowserPids()` */ -test.serial('WebDriver process create & quit test', async t => { - const b = new PuppetWebBrowser() - t.truthy(b, 'should instanciate a browser') +test('WebDriver process create & quit test', async t => { + const b = new PuppetWebBrowser() + t.truthy(b, 'should instanciate a browser') - await b.init() - t.pass('should be inited successful') - await b.open() - t.pass('should open successful') + await b.init() + t.pass('should be inited successful') + await b.open() + t.pass('should open successful') - let pids = await b.getBrowserPids() - t.truthy(pids.length > 0, 'should exist browser process after b.open()') + let pids = await b.getBrowserPids() + t.truthy(pids.length > 0, 'should exist browser process after b.open()') -// console.log(b.driver.getSession()) + // console.log(b.driver.getSession()) - await b.quit() - t.pass('quited') + await b.quit() + t.pass('quited') - const useAva = false - if (!useAva) { // ava will run tests concurency... - pids = await b.getBrowserPids() - t.is(pids.length, 0, 'no driver process after quit') - } + const useAva = false + if (!useAva) { // ava will run tests concurency... + pids = await b.getBrowserPids() + t.is(pids.length, 0, 'no driver process after quit') + } }) -test.serial('WebDriver smoke testing', async t => { +test('WebDriver smoke testing', async t => { const wb = new PuppetWebBrowser() t.truthy(wb, 'Browser instnace') -- GitLab