Skip to content

Commit

Permalink
Unit tests use only exported functions (#4358)
Browse files Browse the repository at this point in the history
* Core modules have no test-only exported functions

* Queue has no test-only exports

* All tests run only on exported functions

* Fix initializing test error
  • Loading branch information
James-Yu committed Sep 1, 2024
1 parent da45fa3 commit 14700e1
Show file tree
Hide file tree
Showing 15 changed files with 794 additions and 809 deletions.
5 changes: 1 addition & 4 deletions src/compile/queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,5 @@ export const queue = {
clear,
isLastStep,
getStep,
getStepString,
_test: {
getQueue: () => stepQueue
}
getStepString
}
35 changes: 13 additions & 22 deletions src/compile/recipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,19 @@ import { queue } from './queue'

const logger = lw.log('Build', 'Recipe')

const state: {
let state: {
prevRecipe: Recipe | undefined,
prevLangId: string,
isMikTeX: boolean | undefined
} = {
prevRecipe: undefined,
prevLangId: '',
isMikTeX: undefined
}

initialize()
export function initialize() {
state = {
prevRecipe: undefined,
prevLangId: '',
isMikTeX: undefined
}
}

setDockerImage()
Expand Down Expand Up @@ -306,8 +311,8 @@ function findRecipe(rootFile: string, langId: string, recipeName?: string): Reci
candidates = recipes.filter(candidate => candidate.name.toLowerCase().match('pnw|pweave'))
}
if (candidates.length < 1) {
logger.log(`Failed to resolve build recipe: ${recipeName}.`)
void logger.showErrorMessage(`Failed to resolve build recipe: ${recipeName}.`)
logger.log(`Cannot find any recipe for langID \`${langId}\`.`)
void logger.showErrorMessage(`[Builder] Cannot find any recipe for langID \`${langId}\`: ${recipeName}.`)
}
recipe = candidates[0]
}
Expand Down Expand Up @@ -360,7 +365,7 @@ function populateTools(rootFile: string, buildTools: Tool[]): Tool[] {
tool.args.includes('--lualatex') ||
tool.args.includes('--pdflua') ||
tool.args.includes('--pdflualatex')
if (isMikTeX() && ((tool.command === 'latexmk' && !isLuaLatex) || tool.command === 'pdflatex')) {
if (((tool.command === 'latexmk' && !isLuaLatex) || tool.command === 'pdflatex') && isMikTeX()) {
tool.args.unshift('--max-print-line=' + lw.constant.MAX_PRINT_LINE)
}
}
Expand Down Expand Up @@ -390,17 +395,3 @@ function isMikTeX(): boolean {
}
return state.isMikTeX
}

export const _test = {
setDockerImage,
setDockerPath,
createOutputSubFolders,
findMagicComments,
createBuildMagic,
findRecipe,
state,
populateTools,
isMikTeX,
createBuildTools,
build
}
13 changes: 4 additions & 9 deletions src/core/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,7 @@ export const cache = {
reset,
refreshCache,
refreshCacheAggressive,
loadFlsFile,
_test: {
caches,
canCache,
isExcluded,
updateAST
}
loadFlsFile
}

// Listener for file changes: refreshes the cache if the file can be cached.
Expand All @@ -59,7 +53,7 @@ lw.watcher.src.onChange((filePath: string) => {

// Listener for file deletions: removes the file from the cache if it exists.
lw.watcher.src.onDelete((filePath: string) => {
if (get(filePath) === undefined) {
if (get(filePath) !== undefined) {
caches.delete(filePath)
logger.log(`Removed ${filePath} .`)
}
Expand Down Expand Up @@ -236,10 +230,11 @@ let cachingFilesCount: number = 0
*/
async function refreshCache(filePath: string, rootPath?: string): Promise<Promise<void> | undefined> {
if (isExcluded(filePath)) {
logger.log(`Ignored ${filePath} .`)
logger.log(`File is excluded from caching: ${filePath} .`)
return
}
if (!canCache(filePath)) {
logger.log(`File cannot be cached: ${filePath} .`)
return
}
logger.log(`Caching ${filePath} .`)
Expand Down
12 changes: 7 additions & 5 deletions src/core/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { lw } from '../lw'
const logger = lw.log('File')

export const file = {
tmpDirPath: createTmpDir(),
tmpDirPath: '',
getOutDir,
getLangId,
getJobname,
Expand All @@ -23,10 +23,12 @@ export const file = {
setTeXDirs,
exists,
read,
kpsewhich,
_test: {
createTmpDir
}
kpsewhich
}

initialize()
export function initialize() {
file.tmpDirPath = createTmpDir()
}

/**
Expand Down
15 changes: 5 additions & 10 deletions src/core/root.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,7 @@ export const root = {
langId: undefined as string | undefined,
},
find,
getWorkspace,
_test: {
getIndicator,
getWorkspace,
findFromMagic,
findFromActive,
findFromRoot,
findInWorkspace
}
getWorkspace
}

lw.watcher.src.onDelete(filePath => {
Expand Down Expand Up @@ -163,6 +155,7 @@ async function findFromMagic(): Promise<string | undefined> {
return
}

logger.log('Try finding root from magic comment.')
const regex = /^(?:%\s*!\s*T[Ee]X\sroot\s*=\s*(.*\.(?:tex|[jrsRS]nw|[rR]tex|jtexw))$)/m
const fileStack: string[] = []
let content: string | undefined = vscode.window.activeTextEditor.document.getText()
Expand Down Expand Up @@ -212,6 +205,7 @@ function findFromRoot(): string | undefined {
logger.log(`The active document cannot be used as the root file: ${vscode.window.activeTextEditor.document.uri.toString(true)}`)
return
}
logger.log('Try finding root from current root.')
if (lw.cache.getIncludedTeX().includes(vscode.window.activeTextEditor.document.fileName)) {
return root.file.path
}
Expand All @@ -235,6 +229,7 @@ function findFromActive(): string | undefined {
logger.log(`The active document cannot be used as the root file: ${vscode.window.activeTextEditor.document.uri.toString(true)}`)
return
}
logger.log('Try finding root from active editor.')
const content = utils.stripCommentsAndVerbatim(vscode.window.activeTextEditor.document.getText())
const result = content.match(getIndicator())
if (result) {
Expand Down Expand Up @@ -288,7 +283,7 @@ function findSubfiles(content: string): string | undefined {
*/
async function findInWorkspace(): Promise<string | undefined> {
const workspace = getWorkspace()
logger.log(`Current workspaceRootDir: ${workspace ? workspace.toString(true) : ''} .`)
logger.log(`Try finding root from current workspaceRootDir: ${workspace ? workspace.toString(true) : ''} .`)

if (!workspace) {
return
Expand Down
31 changes: 16 additions & 15 deletions src/core/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,38 +9,39 @@ class Watcher {
* Map of folder paths to watcher information. Each folder has its own
* watcher to save resources.
*/
private readonly watchers: {[folder: string]: {watcher: vscode.FileSystemWatcher, files: Set<string>}} = {}
private get watchers() {
return this._watchers
}
private readonly _watchers: {[folder: string]: {watcher: vscode.FileSystemWatcher, files: Set<string>}} = {}

/**
* Set of handlers to be called when a file is created.
*/
private readonly onCreateHandlers: Set<(filePath: string) => void> = new Set()
private get onCreateHandlers() {
return this._onCreateHandlers
}
private readonly _onCreateHandlers: Set<(filePath: string) => void> = new Set()
/**
* Set of handlers to be called when a file is changed.
*/
private readonly onChangeHandlers: Set<(filePath: string) => void> = new Set()
private get onChangeHandlers() {
return this._onChangeHandlers
}
private readonly _onChangeHandlers: Set<(filePath: string) => void> = new Set()
/**
* Set of handlers to be called when a file is deleted.
*/
private readonly onDeleteHandlers: Set<(filePath: string) => void> = new Set()
private get onDeleteHandlers() {
return this._onDeleteHandlers
}
private readonly _onDeleteHandlers: Set<(filePath: string) => void> = new Set()
/**
* Map of file paths to polling information. This may be of particular use
* when large binary files are progressively write to disk, and multiple
* 'change' events are therefore emitted in a short period of time.
*/
private readonly polling: {[filePath: string]: {time: number, size: number}} = {}

readonly _test = {
handlers: {
onCreateHandlers: this.onCreateHandlers,
onChangeHandlers: this.onChangeHandlers,
onDeleteHandlers: this.onDeleteHandlers,
},
getWatchers: () => this.watchers,
onDidChange: (...args: Parameters<Watcher['onDidChange']>) => this.onDidChange(...args),
onDidDelete: (...args: Parameters<Watcher['onDidDelete']>) => this.onDidDelete(...args)
}

/**
* Creates a new Watcher instance.
*
Expand Down
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ lw.cache = cache
import { root } from './core/root'
lw.root = root
import { parser } from './parse'
void parser.parse.reset()
lw.parser = parser
void lw.parser.parse.reset()
import { compile } from './compile'
lw.compile = compile
import { preview, server, viewer } from './preview'
Expand Down
15 changes: 9 additions & 6 deletions test/units/01_core_file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as path from 'path'
import * as sinon from 'sinon'
import { assert, get, mock, set } from './utils'
import { lw } from '../../src/lw'
import { initialize } from '../../src/core/file'

describe(path.basename(__filename).split('.')[0] + ':', () => {
const fixture = path.basename(__filename).split('.')[0]
Expand All @@ -18,11 +19,14 @@ describe(path.basename(__filename).split('.')[0] + ':', () => {

describe('lw.file.createTmpDir', () => {
it('should create temporary directories', () => {
assert.ok(lw.file._test.createTmpDir())
assert.ok(path.isAbsolute(lw.file.tmpDirPath), lw.file.tmpDirPath)
})

it('should create different temporary directories', () => {
assert.notStrictEqual(lw.file._test.createTmpDir(), lw.file._test.createTmpDir())
const tmpDir1 = lw.file.tmpDirPath
initialize()

assert.notStrictEqual(tmpDir1, lw.file.tmpDirPath)
})

function forbiddenTemp(chars: string[ ]) {
Expand All @@ -31,7 +35,7 @@ describe(path.basename(__filename).split('.')[0] + ':', () => {
chars.forEach(char => {
tmpNames.forEach(envvar => process.env[envvar] = (process.env[envvar] === undefined ? undefined : ('\\Test ' + char)))
try {
lw.file._test.createTmpDir()
initialize()
assert.fail('Expected an error to be thrown')
} catch {
assert.ok(true)
Expand Down Expand Up @@ -487,10 +491,9 @@ describe(path.basename(__filename).split('.')[0] + ':', () => {
})

it('should handle non-file URIs', async () => {
const oldStat = lw.external.stat
lw.external.stat = () => { return Promise.resolve({type: 0, ctime: 0, mtime: 0, size: 0}) }
const stub = sinon.stub(lw.external, 'stat').resolves({type: 0, ctime: 0, mtime: 0, size: 0})
const result = await lw.file.exists(vscode.Uri.parse('https://code.visualstudio.com/'))
lw.external.stat = oldStat
stub.restore()
assert.ok(result)
})

Expand Down
Loading

0 comments on commit 14700e1

Please sign in to comment.