Skip to content

Commit

Permalink
Adding missing/unused utils
Browse files Browse the repository at this point in the history
  • Loading branch information
aaroncox committed Oct 12, 2023
1 parent afc6946 commit 43d76ab
Show file tree
Hide file tree
Showing 3 changed files with 179 additions and 0 deletions.
64 changes: 64 additions & 0 deletions test/utils/mock-fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import fetch, { Response } from 'node-fetch'
import { join as joinPath } from 'path'
import { promisify } from 'util'
import { readFile as _readFile, writeFile as _writeFile } from 'fs'
import { Bytes, Checksum160 } from '@wharfkit/session'

const readFile = promisify(_readFile)
const writeFile = promisify(_writeFile)

function getFilename(path: string, params?: unknown) {
const digest = Checksum160.hash(
Bytes.from(path + (params ? JSON.stringify(params) : ''), 'utf8')
).hexString
return joinPath(__dirname, '../data', digest + '.json')
}

async function getExisting(filename: string) {
try {
const data = await readFile(filename)
return JSON.parse(data.toString('utf8'))
} catch (error) {
if ((<any>error).code !== 'ENOENT') {
throw error
}
}
}

export async function mockFetch(path, params) {
const filename = getFilename(path, params)
if (process.env['MOCK'] !== 'overwrite') {
const existing = await getExisting(filename)
if (existing) {
return new Response(existing.text, {
status: existing.status,
headers: existing.headers,
})
}
}
if (process.env['MOCK']) {
const response = await fetch(path, params)
const cloned = response.clone()
const json = await cloned.json()
await writeFile(
filename,
JSON.stringify(
{
request: {
path,
params,
},
headers: Object.fromEntries(response.headers.entries()),
status: response.status,
json,
text: JSON.stringify(json),
},
undefined,
4
)
)
return response
} else {
throw new Error(`No data for ${path}`)
}
}
17 changes: 17 additions & 0 deletions test/utils/mock-storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { SessionStorage } from '@wharfkit/session'

export class MockStorage implements SessionStorage {
data: Record<string, string> = {}
async write(key: string, data: string): Promise<void> {
this.data[key] = data
}
async read(key: string): Promise<string | null> {
return this.data[key]
}
async remove(key: string): Promise<void> {
delete this.data[key]
}
storageKey(key: string) {
return `mock-${key}`
}
}
98 changes: 98 additions & 0 deletions test/utils/mock-ui.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import {
AbstractUserInterface,
cancelable,
Cancelable,
Checksum256,
LoginContext,
LoginOptions,
PermissionLevel,
PromptArgs,
PromptResponse,
UserInterface,
UserInterfaceLoginResponse,
} from '@wharfkit/session'

export class MockUserInterface extends AbstractUserInterface implements UserInterface {
readonly logging = false
public messages: string[] = []

translate(key) {
return key
}

log(message: string) {
this.messages.push(message)
if (this.logging) {
// eslint-disable-next-line no-console
console.info('MockUserInterface', message)
}
}

async login(context: LoginContext): Promise<UserInterfaceLoginResponse> {
let chainId = context.chain?.id
if (!chainId) {
chainId = Checksum256.from(context.chains[0].id)
}
let permissionLevel = context.permissionLevel
if (!permissionLevel) {
permissionLevel = PermissionLevel.from('mock@interface')
}
return {
chainId,
permissionLevel,
walletPluginIndex: 0,
}
}

async onError(error: Error) {
this.log('onError: ' + JSON.stringify(error))
}

async onLogin(options?: LoginOptions) {
this.log('onLogin: ' + JSON.stringify(options))
}

async onLoginComplete() {
this.log('onLoginComplete')
}

async onTransact() {
this.log('onTransact')
}

async onTransactComplete() {
this.log('onTransactComplete')
}

async onSign() {
this.log('onSign')
}

async onSignComplete() {
this.log('onSignComplete')
}

async onBroadcast() {
this.log('onBroadcast')
}

async onBroadcastComplete() {
this.log('onBroadcastComplete')
}

prompt(args: PromptArgs): Cancelable<PromptResponse> {
this.log('prompt' + JSON.stringify(args))
return cancelable(new Promise(() => {}), (canceled) => {
// do things to cancel promise
throw canceled
})
}

status(message: string) {
this.log(`status:('${message}')`)
}

addTranslations(): void {
this.log('addTranslations')
}
}

0 comments on commit 43d76ab

Please sign in to comment.