Skip to content

Commit

Permalink
Updating tests
Browse files Browse the repository at this point in the history
  • Loading branch information
pastuxso committed Dec 18, 2024
1 parent 2e89fe9 commit fc62003
Show file tree
Hide file tree
Showing 4 changed files with 93 additions and 101 deletions.
8 changes: 0 additions & 8 deletions src/extension/cell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -540,14 +540,6 @@ export class NotebookCellOutputManager {
const isSignedIn = features.isOnInContextState(FeatureName.SignedIn)
const isForceLogin = features.isOnInContextState(FeatureName.ForceLogin)

// const isAutoSaveOn = ContextState.getKey<boolean>(NOTEBOOK_AUTOSAVE_ON)

// if (!isSignedIn) {
// return Promise.resolve()
// } else if (!isSignedIn && isForceLogin) {
// return Promise.resolve()
// }

if (!isSignedIn && isForceLogin) {
return Promise.resolve()
}
Expand Down
164 changes: 83 additions & 81 deletions src/extension/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import {
RUNME_FRONTMATTER_PARSED,
VSCODE_LANGUAGEID_MAP,
} from '../constants'
import { ServerLifecycleIdentity, getSessionOutputs } from '../utils/configuration'
import { ServerLifecycleIdentity } from '../utils/configuration'

import {
DeserializeRequest,
Expand All @@ -57,6 +57,7 @@ import { IProcessInfoState } from './terminal/terminalState'
import ContextState from './contextState'
import * as ghost from './ai/ghost'
import getLogger from './logger'
import features from './features'

declare var globalThis: any
const DEFAULT_LANG_ID = 'text'
Expand Down Expand Up @@ -404,6 +405,74 @@ export abstract class SerializerBase implements NotebookSerializer, Disposable {
}
}

export class WasmSerializer extends SerializerBase {
protected readonly ready: ReadyPromise

constructor(
protected context: ExtensionContext,
kernel: Kernel,
) {
super(context, kernel)
const wasmUri = Uri.joinPath(this.context.extensionUri, 'wasm', 'runme.wasm')
this.ready = initWasm(wasmUri)
}

protected async saveNotebook(
data: NotebookData,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
token: CancellationToken,
): Promise<Uint8Array> {
const { Runme } = globalThis as Serializer.Wasm

const notebook = JSON.stringify(data)
const markdown = await Runme.serialize(notebook)

const encoder = new TextEncoder()
return encoder.encode(markdown)
}

protected async reviveNotebook(
content: Uint8Array,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
token: CancellationToken,
): Promise<Serializer.Notebook> {
const { Runme } = globalThis as Serializer.Wasm

const markdown = Buffer.from(content).toString('utf8')
const notebook = await Runme.deserialize(markdown)

if (!notebook) {
return this.printCell('⚠️ __Error__: no cells found!')
}
return notebook
}

protected async saveNotebookOutputsByCacheId(_cacheId: string): Promise<number> {
console.error('saveNotebookOutputsByCacheId not implemented for WasmSerializer')
return -1
}

public async saveNotebookOutputs(_uri: Uri): Promise<number> {
console.error('saveNotebookOutputs not implemented for WasmSerializer')
return -1
}

public getMaskedCache(): Promise<Uint8Array> | undefined {
console.error('getMaskedCache not implemented for WasmSerializer')
return Promise.resolve(new Uint8Array())
}

public getPlainCache(): Promise<Uint8Array> | undefined {
console.error('getPlainCache not implemented for WasmSerializer')
return Promise.resolve(new Uint8Array())
}

public getNotebookDataCache(): NotebookData | undefined {
console.error('getNotebookDataCache not implemented for WasmSerializer')
return {} as NotebookData
}
}

export class GrpcSerializer extends SerializerBase {
private client?: ParserServiceClient
protected ready: ReadyPromise
Expand Down Expand Up @@ -502,11 +571,9 @@ export class GrpcSerializer extends SerializerBase {
return -1
}

const sessionOutputsPreview = ContextState.getKey<boolean>(NOTEBOOK_PREVIEW_OUTPUTS)
const isAutosaveOn = ContextState.getKey<boolean>(NOTEBOOK_AUTOSAVE_ON)
if (sessionOutputsPreview && !isAutosaveOn) {
if (GrpcSerializer.shouldDisablePreviewOutputs()) {
await ContextState.addKey(NOTEBOOK_PREVIEW_OUTPUTS, false)
} else if (!sessionOutputsPreview && this.kernel.isFeatureOn(FeatureName.SignedIn)) {
} else if (GrpcSerializer.shouldSkipOutputSave()) {
return bytes.length
}

Expand All @@ -519,6 +586,17 @@ export class GrpcSerializer extends SerializerBase {
return bytes.length
}

static shouldDisablePreviewOutputs(): boolean {
const sessionOutputsPreview = ContextState.getKey<boolean>(NOTEBOOK_PREVIEW_OUTPUTS)
const isAutosaveOn = ContextState.getKey<boolean>(NOTEBOOK_AUTOSAVE_ON)
return sessionOutputsPreview && !isAutosaveOn
}

static shouldSkipOutputSave(): boolean {
const sessionOutputsPreview = ContextState.getKey<boolean>(NOTEBOOK_PREVIEW_OUTPUTS)
return !sessionOutputsPreview && features.isOnInContextState(FeatureName.SignedIn)
}

public async saveNotebookOutputs(uri: Uri): Promise<number> {
let cacheId: string | undefined
this.cacheDocUriMapping.forEach((docUri, cid) => {
Expand Down Expand Up @@ -687,14 +765,6 @@ export class GrpcSerializer extends SerializerBase {
return result
}

static sessionOutputsEnabled() {
// const isAutoSaveOn = ContextState.getKey<boolean>(NOTEBOOK_AUTOSAVE_ON)
// const isSessionOutputs = getSessionOutputs()

// return isSessionOutputs && isAutoSaveOn
return getSessionOutputs()
}

private async cacheNotebookOutputs(
notebook: Notebook,
cacheId: string | undefined,
Expand Down Expand Up @@ -940,71 +1010,3 @@ export class GrpcSerializer extends SerializerBase {
return this.notebookDataCache.get(cacheId)
}
}

export class WasmSerializer extends SerializerBase {
protected readonly ready: ReadyPromise

constructor(
protected context: ExtensionContext,
kernel: Kernel,
) {
super(context, kernel)
const wasmUri = Uri.joinPath(this.context.extensionUri, 'wasm', 'runme.wasm')
this.ready = initWasm(wasmUri)
}

protected async saveNotebook(
data: NotebookData,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
token: CancellationToken,
): Promise<Uint8Array> {
const { Runme } = globalThis as Serializer.Wasm

const notebook = JSON.stringify(data)
const markdown = await Runme.serialize(notebook)

const encoder = new TextEncoder()
return encoder.encode(markdown)
}

protected async reviveNotebook(
content: Uint8Array,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
token: CancellationToken,
): Promise<Serializer.Notebook> {
const { Runme } = globalThis as Serializer.Wasm

const markdown = Buffer.from(content).toString('utf8')
const notebook = await Runme.deserialize(markdown)

if (!notebook) {
return this.printCell('⚠️ __Error__: no cells found!')
}
return notebook
}

protected async saveNotebookOutputsByCacheId(_cacheId: string): Promise<number> {
console.error('saveNotebookOutputsByCacheId not implemented for WasmSerializer')
return -1
}

public async saveNotebookOutputs(_uri: Uri): Promise<number> {
console.error('saveNotebookOutputs not implemented for WasmSerializer')
return -1
}

public getMaskedCache(): Promise<Uint8Array> | undefined {
console.error('getMaskedCache not implemented for WasmSerializer')
return Promise.resolve(new Uint8Array())
}

public getPlainCache(): Promise<Uint8Array> | undefined {
console.error('getPlainCache not implemented for WasmSerializer')
return Promise.resolve(new Uint8Array())
}

public getNotebookDataCache(): NotebookData | undefined {
console.error('getNotebookDataCache not implemented for WasmSerializer')
return {} as NotebookData
}
}
2 changes: 2 additions & 0 deletions tests/extension/provider/sessionOutputs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ vi.mock('../../../src/extension/utils', () => ({

vi.mock('../../../src/extension/runner', () => ({}))
vi.mock('../../../src/extension/grpc/runner/v1', () => ({}))

const contextFake: ExtensionContext = {
extensionUri: Uri.parse('file:///Users/fakeUser/projects/vscode-runme'),
secrets: {
Expand All @@ -37,6 +38,7 @@ const contextFake: ExtensionContext = {
} as any

StatefulAuthProvider.initialize(contextFake)

describe('Preview Outputs Cell Status Bar provider', () => {
const kernel = new Kernel({} as any)
it('should register commands when initializing', () => {
Expand Down
20 changes: 8 additions & 12 deletions tests/extension/serializer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -530,17 +530,15 @@ describe('GrpcSerializer', () => {

describe('#saveNotebookOutputs', () => {
beforeEach(() => {
const sessionOutputsEnabled = vi.fn().mockReturnValue(true)
GrpcSerializer.sessionOutputsEnabled = sessionOutputsEnabled
const shouldDisablePreviewOutputs = vi.fn().mockReturnValue(true)
GrpcSerializer.shouldDisablePreviewOutputs = shouldDisablePreviewOutputs
})
const fakeCachedBytes = new Uint8Array([1, 2, 3, 4])
const serializer: any = new GrpcSerializer(context, new Server(), new Kernel())
const togglePreviewButton = vi.fn()
serializer.togglePreviewButton = togglePreviewButton

it('skips if session outputs are disabled', async () => {
const sessionOutputsEnabled = vi.fn().mockReturnValue(false)
GrpcSerializer.sessionOutputsEnabled = sessionOutputsEnabled
it('skips if preview outputs are disabled', async () => {
const fixture = deepCopyFixture()
serializer.plainCache.set(
fixture.metadata['runme.dev/frontmatterParsed'].runme.id,
Expand All @@ -551,7 +549,7 @@ describe('GrpcSerializer', () => {
metadata: fixture.metadata,
})

expect(togglePreviewButton).toBeCalledWith(false)
expect(workspace.fs.writeFile).toHaveBeenCalledTimes(0)
})

it('skips if notebook has zero bytes', async () => {
Expand All @@ -565,7 +563,7 @@ describe('GrpcSerializer', () => {
metadata: fixture.metadata,
})

expect(togglePreviewButton).toBeCalledWith(false)
expect(workspace.fs.writeFile).toHaveBeenCalledTimes(0)
})

it('skips if uri mapping to cacheId is unknown', async () => {
Expand All @@ -579,7 +577,7 @@ describe('GrpcSerializer', () => {
metadata: fixture.metadata,
})

expect(togglePreviewButton).toBeCalledWith(false)
expect(workspace.fs.writeFile).toHaveBeenCalledTimes(0)
})

it('skips if session file mapping is unknown', async () => {
Expand All @@ -598,7 +596,7 @@ describe('GrpcSerializer', () => {
metadata: fixture.metadata,
})

expect(togglePreviewButton).toBeCalledWith(false)
expect(workspace.fs.writeFile).toHaveBeenCalledTimes(0)
})

it('skips if runner env session in unknown', async () => {
Expand All @@ -619,7 +617,7 @@ describe('GrpcSerializer', () => {
metadata: fixture.metadata,
})

expect(togglePreviewButton).toBeCalledWith(false)
expect(workspace.fs.writeFile).toHaveBeenCalledTimes(0)
})

it('writes cached bytes to session file on serialization and save', async () => {
Expand All @@ -630,7 +628,6 @@ describe('GrpcSerializer', () => {
}
writeableSer.cacheDocUriMapping.set(fixture.metadata['runme.dev/cacheId'], fakeSrcDocUri)
ContextState.getKey = vi.fn().mockImplementation(() => true)
GrpcSerializer.sessionOutputsEnabled = vi.fn().mockReturnValue(true)
GrpcSerializer.getOutputsUri = vi.fn().mockImplementation(() => fakeSrcDocUri)

const result = await writeableSer.serializeNotebook(
Expand Down Expand Up @@ -694,7 +691,6 @@ describe('GrpcSerializer', () => {
const ser = new GrpcSerializer(context, new Server(), new Kernel())
;(ser as any).cacheDocUriMapping = { get: vi.fn().mockReturnValue(fakeSrcDocUri) }
;(ser as any).client = { serialize }
GrpcSerializer.sessionOutputsEnabled = vi.fn().mockReturnValue(true)

await (ser as any).cacheNotebookOutputs(fixture, 'irrelevant')

Expand Down

0 comments on commit fc62003

Please sign in to comment.