Skip to content

Commit

Permalink
feat(test-utils): support server.receive
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Sep 8, 2020
1 parent 031293c commit 06c0351
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 4 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"kleur": "^4.1.1",
"latest-version": "^5.1.0",
"mocha": "^8.1.3",
"nock": "^13.0.4",
"open": "^7.2.1",
"ora": "^5.0.0",
"p-map": "^4.0.0",
Expand Down
49 changes: 46 additions & 3 deletions packages/koishi-test-utils/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import { AppOptions, App, Server, Session, AppStatus } from 'koishi-core'
import { assert } from 'chai'
import { Socket } from 'net'
import * as http from 'http'
import * as memory from './memory'

export const BASE_SELF_ID = 514

class MockedAppServer extends Server {
interface MockedResponse {
code: number
body: string
headers: Record<string, any>
}

class MockedServer extends Server {
constructor(app: App) {
super(app)
this.bots.forEach(bot => bot.ready = true)
Expand All @@ -13,17 +21,52 @@ class MockedAppServer extends Server {
_close() {}

async _listen() {}

get(path: string, headers?: Record<string, any>) {
return this.receive('GET', path, headers, '')
}

post(path: string, body: any, headers?: Record<string, any>) {
return this.receive('POST', path, headers, JSON.stringify(body))
}

receive(method: string, path: string, headers: Record<string, any>, content: string) {
const socket = new Socket()
const req = new http.IncomingMessage(socket)
req.url = path
req.method = method
Object.assign(req.headers, headers)
req.headers['content-type'] = 'application/json'
req.headers['content-length'] = '' + content.length
return new Promise<MockedResponse>((resolve) => {
const res = new http.ServerResponse(req)
let body = ''
res.write = (chunk: any) => {
body += chunk
return true
}
res.end = (chunk: any) => {
res.write(chunk)
const code = res.statusCode
const headers = res.getHeaders()
resolve({ code, body, headers })
}
this.server.emit('request', req, res)
req.emit('data', content)
req.emit('end')
})
}
}

Server.types.mock = MockedAppServer
Server.types.mock = MockedServer

interface MockedAppOptions extends AppOptions {
mockStart?: boolean
mockDatabase?: boolean
}

export class MockedApp extends App {
public server: MockedAppServer
public server: MockedServer

constructor(options: MockedAppOptions = {}) {
super({ selfId: BASE_SELF_ID, type: 'mock', ...options })
Expand Down
5 changes: 4 additions & 1 deletion packages/plugin-github/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ export function apply(ctx: Context, config: Config = {}) {

router.get(config.authorize, async (ctx) => {
const targetId = parseInt(ctx.query.state)
if (Number.isNaN(targetId)) throw new Error('Invalid targetId')
if (Number.isNaN(targetId)) {
ctx.body = 'Invalid targetId'
return ctx.status = 400
}
const { code, state } = ctx.query
const data = await github.getTokens({ code, state, redirect_uri: redirect })
await database.setUser(targetId, {
Expand Down
26 changes: 26 additions & 0 deletions packages/plugin-github/tests/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { fn, spyOn } from 'jest-mock'
import { expect } from 'chai'
import { readdirSync } from 'fs-extra'
import { resolve } from 'path'
import nock from 'nock'
import * as github from 'koishi-plugin-github'

const app = new App({
Expand All @@ -16,6 +17,8 @@ app.plugin(github, {
repos: { 'koishijs/koishi': [123] },
})

const session = app.session(123)

// override listen
const listen = spyOn(app.server, 'listen')
listen.mockReturnValue(Promise.resolve())
Expand All @@ -25,6 +28,7 @@ const sendGroupMsg = app.bots[0].sendGroupMsg = fn()

before(async () => {
await app.start()
await app.database.getUser(123, 3)
await app.database.getGroup(123, BASE_SELF_ID)
})

Expand All @@ -46,6 +50,28 @@ function check(file: string) {
}

describe('GitHub Plugin', () => {
it('authorize server', async () => {
const ghAccessToken = Random.uuid()
const ghRefreshToken = Random.uuid()
const interceptor = nock('https://github.com').post('/login/oauth/access_token')
interceptor.reply(200, {
access_token: ghAccessToken,
refresh_token: ghRefreshToken,
})

await expect(app.server.get('/github/authorize')).to.eventually.have.property('code', 400)
await expect(app.server.get('/github/authorize?state=123')).to.eventually.have.property('code', 200)
await expect(app.database.getUser(123)).to.eventually.have.shape({
ghAccessToken,
ghRefreshToken,
})
})

it('github command', async () => {
await session.shouldReply('github', '请输入用户名。')
await session.shouldReply('github satori', /^/)
})

describe('Webhook Events', () => {
const files = readdirSync(resolve(__dirname, 'fixtures'))
files.forEach(file => {
Expand Down

0 comments on commit 06c0351

Please sign in to comment.