mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-03-29 18:12:06 -07:00
* chore(backlog): add mining workflow milestone and tasks
* refactor: split character dictionary runtime modules
* refactor: split shared type entrypoints
* refactor: use bun serve for stats server
* feat: add repo-local subminer workflow plugin
* fix: add stats server node fallback
* refactor: split immersion tracker query modules
* chore: update backlog task records
* refactor: migrate shared type imports
* refactor: compose startup and setup window wiring
* Add backlog tasks and launcher time helper tests
- Track follow-up cleanup work in Backlog.md
- Replace Date.now usage with shared nowMs helper
- Add launcher args/parser and core regression tests
* test: increase launcher test timeout for CI stability
* fix: address CodeRabbit review feedback
* refactor(main): extract remaining inline runtime logic from main
* chore(backlog): update task notes and changelog fragment
* refactor: split main boot phases
* test: stabilize bun coverage reporting
* Switch plausible endpoint and harden coverage lane parsing
- update docs-site tracking to use the Plausible capture endpoint
- tighten coverage lane argument and LCOV parsing checks
- make script entrypoint use CommonJS main guard
* Restrict docs analytics and build coverage input
- limit Plausible init to docs.subminer.moe
- build Yomitan before src coverage lane
* fix(ci): normalize Windows shortcut paths for cross-platform tests
* Fix verification and immersion-tracker grouping
- isolate verifier artifacts and lease handling
- switch weekly/monthly tracker cutoffs to calendar boundaries
- tighten boot lifecycle and zip writer tests
* fix: resolve CI type failures in boot and immersion query tests
* fix: remove strict spread usage in Date mocks
* fix: use explicit super args for MockDate constructors
* Factor out mock date helper in tracker tests
- reuse a shared `withMockDate` helper for date-sensitive query tests
- make monthly rollup assertions key off `videoId` instead of row order
* fix: use variadic array type for MockDate constructor args
TS2367: fixed-length tuple made args.length === 0 unreachable.
* refactor: remove unused createMainBootRuntimes/Handlers aggregate functions
These functions were never called by production code — main.ts imports
the individual composeBoot* re-exports directly.
* refactor: remove boot re-export alias layer
main.ts now imports directly from the runtime/composers and runtime/domains
modules, eliminating the intermediate boot/ indirection.
* refactor: consolidate 3 near-identical setup window factories
Extract shared createSetupWindowHandler with a config parameter.
Public API unchanged.
* refactor: parameterize duplicated getAffected*Ids query helpers
Four structurally identical functions collapsed into two parameterized
helpers while preserving the existing public API.
* refactor: inline identity composers (stats-startup, overlay-window)
composeStatsStartupRuntime was a no-op that returned its input.
composeOverlayWindowHandlers was a 1-line delegation.
Both removed in favor of direct usage.
* chore: remove unused token/queue file path constants from main.ts
* fix: replace any types in boot services with proper signatures
* refactor: deduplicate ensureDir into shared/fs-utils
5 copies of mkdir-p-if-not-exists consolidated into one shared module
with ensureDir (directory path) and ensureDirForFile (file path) variants.
* fix: tighten type safety in boot services
- Add AppLifecycleShape and OverlayModalInputStateShape constraints
so TAppLifecycleApp and TOverlayModalInputState generics are bounded
- Remove unsafe `as { handleModalInputStateChange? }` cast — now
directly callable via the constraint
- Use `satisfies AppLifecycleShape` for structural validation on the
appLifecycleApp object literal
- Document Electron App.on incompatibility with simple signatures
* refactor: inline subtitle-prefetch-runtime-composer
The composer was a pure pass-through that destructured an object and
reassembled it with the same fields. Inlined at the call site.
* chore: consolidate duplicate import paths in main.ts
* test: extract mpv composer test fixture factory to reduce duplication
* test: add behavioral assertions to composer tests
Upgrade 8 composer test files from shape-only typeof checks to behavioral
assertions that invoke returned handlers and verify injected dependencies are
actually called, following the mpv-runtime-composer pattern.
* refactor: normalize import extensions in query modules
* refactor: consolidate toDbMs into query-shared.ts
* refactor: remove Node.js fallback from stats-server, use Bun only
* Fix monthly rollup test expectations
- Preserve multi-arg Date construction in mock helper
- Align rollup assertions with the correct videoId
* fix: address PR 36 CodeRabbit follow-ups
* fix: harden coverage lane cleanup
* fix(stats): fallback to node server when Bun.serve unavailable
* fix(ci): restore coverage lane compatibility
* chore(backlog): close TASK-242
* fix: address latest CodeRabbit review round
* fix: guard disabled immersion retention windows
* fix: migrate discord rpc wrapper
* fix(ci): add changelog fragment for PR 36
* fix: stabilize macOS visible overlay toggle
* fix: pin installed mpv plugin to current binary
* fix: strip inline subtitle markup from sidebar cues
* fix(renderer): restore subtitle sidebar mpv passthrough
* feat(discord): add configurable presence style presets
Replace the hardcoded "Mining and crafting (Anki cards)" meme message
with a preset system. New `discordPresence.presenceStyle` option
supports four presets: "default" (clean bilingual), "meme" (the OG
Minecraft joke), "japanese" (fully JP), and "minimal". The default
preset shows "Sentence Mining" with 日本語学習中 as the small image
tooltip. Existing users can set presenceStyle to "meme" to keep the
old behavior.
* fix: finalize v0.10.0 release prep
* docs: add subtitle sidebar guide and release note
* chore(backlog): mark docs task done
* fix: lazily resolve youtube playback socket path
* chore(release): build v0.10.0 changelog
* Revert "chore(release): build v0.10.0 changelog"
This reverts commit 9741c0f020.
516 lines
16 KiB
TypeScript
516 lines
16 KiB
TypeScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import os from 'node:os';
|
|
import net from 'node:net';
|
|
import { EventEmitter } from 'node:events';
|
|
import type { Args } from './types';
|
|
import {
|
|
cleanupPlaybackSession,
|
|
findAppBinary,
|
|
launchAppCommandDetached,
|
|
launchTexthookerOnly,
|
|
parseMpvArgString,
|
|
runAppCommandCaptureOutput,
|
|
shouldResolveAniSkipMetadata,
|
|
stopOverlay,
|
|
startOverlay,
|
|
state,
|
|
waitForUnixSocketReady,
|
|
} from './mpv';
|
|
import * as mpvModule from './mpv';
|
|
|
|
class ExitSignal extends Error {
|
|
code: number;
|
|
|
|
constructor(code: number) {
|
|
super(`exit:${code}`);
|
|
this.code = code;
|
|
}
|
|
}
|
|
|
|
function withProcessExitIntercept(callback: () => void): ExitSignal {
|
|
const originalExit = process.exit;
|
|
try {
|
|
process.exit = ((code?: number) => {
|
|
throw new ExitSignal(code ?? 0);
|
|
}) as typeof process.exit;
|
|
callback();
|
|
} catch (error) {
|
|
if (error instanceof ExitSignal) {
|
|
return error;
|
|
}
|
|
throw error;
|
|
} finally {
|
|
process.exit = originalExit;
|
|
}
|
|
|
|
throw new Error('expected process.exit');
|
|
}
|
|
|
|
function createTempSocketPath(): { dir: string; socketPath: string } {
|
|
const baseDir = path.join(process.cwd(), '.tmp', 'launcher-mpv-tests');
|
|
fs.mkdirSync(baseDir, { recursive: true });
|
|
const dir = fs.mkdtempSync(path.join(baseDir, 'case-'));
|
|
return { dir, socketPath: path.join(dir, 'mpv.sock') };
|
|
}
|
|
|
|
test('mpv module exposes only canonical socket readiness helper', () => {
|
|
assert.equal('waitForSocket' in mpvModule, false);
|
|
});
|
|
|
|
test('runAppCommandCaptureOutput captures status and stdio', () => {
|
|
const result = runAppCommandCaptureOutput(process.execPath, [
|
|
'-e',
|
|
'process.stdout.write("stdout-line"); process.stderr.write("stderr-line");',
|
|
]);
|
|
|
|
assert.equal(result.status, 0);
|
|
assert.equal(result.stdout, 'stdout-line');
|
|
assert.equal(result.stderr, 'stderr-line');
|
|
assert.equal(result.error, undefined);
|
|
});
|
|
|
|
test('runAppCommandCaptureOutput strips ELECTRON_RUN_AS_NODE from app child env', () => {
|
|
const original = process.env.ELECTRON_RUN_AS_NODE;
|
|
try {
|
|
process.env.ELECTRON_RUN_AS_NODE = '1';
|
|
const result = runAppCommandCaptureOutput(process.execPath, [
|
|
'-e',
|
|
'process.stdout.write(String(process.env.ELECTRON_RUN_AS_NODE ?? ""));',
|
|
]);
|
|
|
|
assert.equal(result.status, 0);
|
|
assert.equal(result.stdout, '');
|
|
} finally {
|
|
if (original === undefined) {
|
|
delete process.env.ELECTRON_RUN_AS_NODE;
|
|
} else {
|
|
process.env.ELECTRON_RUN_AS_NODE = original;
|
|
}
|
|
}
|
|
});
|
|
|
|
test('parseMpvArgString preserves empty quoted tokens', () => {
|
|
assert.deepEqual(parseMpvArgString('--title "" --force-media-title \'\' --pause'), [
|
|
'--title',
|
|
'',
|
|
'--force-media-title',
|
|
'',
|
|
'--pause',
|
|
]);
|
|
});
|
|
|
|
test('launchTexthookerOnly exits non-zero when app binary cannot be spawned', () => {
|
|
const error = withProcessExitIntercept(() => {
|
|
launchTexthookerOnly('/definitely-missing-subminer-binary', makeArgs());
|
|
});
|
|
|
|
assert.equal(error.code, 1);
|
|
});
|
|
|
|
test('launchAppCommandDetached handles child process spawn errors', async () => {
|
|
let uncaughtError: Error | null = null;
|
|
const onUncaughtException = (error: Error) => {
|
|
uncaughtError = error;
|
|
};
|
|
process.once('uncaughtException', onUncaughtException);
|
|
try {
|
|
launchAppCommandDetached(
|
|
'/definitely-missing-subminer-binary',
|
|
[],
|
|
makeArgs({ logLevel: 'warn' }).logLevel,
|
|
'test',
|
|
);
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
assert.equal(uncaughtError, null);
|
|
} finally {
|
|
process.removeListener('uncaughtException', onUncaughtException);
|
|
}
|
|
});
|
|
|
|
test('stopOverlay logs a warning when stop command cannot be spawned', () => {
|
|
const originalWrite = process.stdout.write;
|
|
const writes: string[] = [];
|
|
const overlayProc = {
|
|
killed: false,
|
|
kill: () => true,
|
|
} as unknown as NonNullable<typeof state.overlayProc>;
|
|
|
|
try {
|
|
process.stdout.write = ((chunk: string | Uint8Array) => {
|
|
writes.push(Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk));
|
|
return true;
|
|
}) as typeof process.stdout.write;
|
|
state.stopRequested = false;
|
|
state.overlayManagedByLauncher = true;
|
|
state.appPath = '/definitely-missing-subminer-binary';
|
|
state.overlayProc = overlayProc;
|
|
|
|
stopOverlay(makeArgs({ logLevel: 'warn' }));
|
|
|
|
assert.ok(writes.some((text) => text.includes('Failed to stop SubMiner overlay')));
|
|
} finally {
|
|
process.stdout.write = originalWrite;
|
|
state.stopRequested = false;
|
|
state.overlayManagedByLauncher = false;
|
|
state.appPath = '';
|
|
state.overlayProc = null;
|
|
}
|
|
});
|
|
|
|
test('waitForUnixSocketReady returns false when socket never appears', async () => {
|
|
const { dir, socketPath } = createTempSocketPath();
|
|
try {
|
|
const ready = await waitForUnixSocketReady(socketPath, 120);
|
|
assert.equal(ready, false);
|
|
} finally {
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('waitForUnixSocketReady returns false when path exists but is not socket', async () => {
|
|
const { dir, socketPath } = createTempSocketPath();
|
|
try {
|
|
fs.writeFileSync(socketPath, 'not-a-socket');
|
|
const ready = await waitForUnixSocketReady(socketPath, 200);
|
|
assert.equal(ready, false);
|
|
} finally {
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('waitForUnixSocketReady returns true when socket becomes connectable before timeout', async () => {
|
|
const { dir, socketPath } = createTempSocketPath();
|
|
fs.writeFileSync(socketPath, '');
|
|
const originalCreateConnection = net.createConnection;
|
|
try {
|
|
net.createConnection = (() => {
|
|
const socket = new EventEmitter() as net.Socket;
|
|
socket.destroy = (() => socket) as net.Socket['destroy'];
|
|
socket.setTimeout = (() => socket) as net.Socket['setTimeout'];
|
|
setTimeout(() => socket.emit('connect'), 25);
|
|
return socket;
|
|
}) as typeof net.createConnection;
|
|
|
|
const ready = await waitForUnixSocketReady(socketPath, 400);
|
|
assert.equal(ready, true);
|
|
} finally {
|
|
net.createConnection = originalCreateConnection;
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('shouldResolveAniSkipMetadata skips URL and YouTube-preloaded playback', () => {
|
|
assert.equal(shouldResolveAniSkipMetadata('/media/show.mkv', 'file'), true);
|
|
assert.equal(
|
|
shouldResolveAniSkipMetadata('https://www.youtube.com/watch?v=test123', 'url'),
|
|
false,
|
|
);
|
|
assert.equal(
|
|
shouldResolveAniSkipMetadata('/tmp/video123.webm', 'file', {
|
|
primaryPath: '/tmp/video123.ja.srt',
|
|
}),
|
|
false,
|
|
);
|
|
});
|
|
|
|
function makeArgs(overrides: Partial<Args> = {}): Args {
|
|
return {
|
|
backend: 'x11',
|
|
directory: '.',
|
|
recursive: false,
|
|
profile: '',
|
|
startOverlay: false,
|
|
whisperBin: '',
|
|
whisperModel: '',
|
|
whisperVadModel: '',
|
|
whisperThreads: 4,
|
|
youtubeSubgenOutDir: '',
|
|
youtubeSubgenAudioFormat: 'wav',
|
|
youtubeSubgenKeepTemp: false,
|
|
youtubeFixWithAi: false,
|
|
youtubePrimarySubLangs: [],
|
|
youtubeSecondarySubLangs: [],
|
|
youtubeAudioLangs: [],
|
|
youtubeWhisperSourceLanguage: 'ja',
|
|
aiConfig: {},
|
|
useTexthooker: false,
|
|
autoStartOverlay: false,
|
|
texthookerOnly: false,
|
|
useRofi: false,
|
|
logLevel: 'error',
|
|
passwordStore: '',
|
|
target: '',
|
|
targetKind: '',
|
|
jimakuApiKey: '',
|
|
jimakuApiKeyCommand: '',
|
|
jimakuApiBaseUrl: '',
|
|
jimakuLanguagePreference: 'none',
|
|
jimakuMaxEntryResults: 10,
|
|
jellyfin: false,
|
|
jellyfinLogin: false,
|
|
jellyfinLogout: false,
|
|
jellyfinPlay: false,
|
|
jellyfinDiscovery: false,
|
|
dictionary: false,
|
|
stats: false,
|
|
doctor: false,
|
|
doctorRefreshKnownWords: false,
|
|
configPath: false,
|
|
configShow: false,
|
|
mpvIdle: false,
|
|
mpvSocket: false,
|
|
mpvStatus: false,
|
|
mpvArgs: '',
|
|
appPassthrough: false,
|
|
appArgs: [],
|
|
jellyfinServer: '',
|
|
jellyfinUsername: '',
|
|
jellyfinPassword: '',
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
test('startOverlay resolves without fixed 2s sleep when readiness signals arrive quickly', async () => {
|
|
const { dir, socketPath } = createTempSocketPath();
|
|
const appPath = path.join(dir, 'fake-subminer.sh');
|
|
fs.writeFileSync(appPath, '#!/bin/sh\nexit 0\n');
|
|
fs.chmodSync(appPath, 0o755);
|
|
fs.writeFileSync(socketPath, '');
|
|
const originalCreateConnection = net.createConnection;
|
|
try {
|
|
net.createConnection = (() => {
|
|
const socket = new EventEmitter() as net.Socket;
|
|
socket.destroy = (() => socket) as net.Socket['destroy'];
|
|
socket.setTimeout = (() => socket) as net.Socket['setTimeout'];
|
|
setTimeout(() => socket.emit('connect'), 10);
|
|
return socket;
|
|
}) as typeof net.createConnection;
|
|
|
|
const startedAt = Date.now();
|
|
await startOverlay(appPath, makeArgs(), socketPath);
|
|
const elapsedMs = Date.now() - startedAt;
|
|
|
|
assert.ok(elapsedMs < 1200, `expected startOverlay <1200ms, got ${elapsedMs}ms`);
|
|
} finally {
|
|
net.createConnection = originalCreateConnection;
|
|
state.overlayProc = null;
|
|
state.overlayManagedByLauncher = false;
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('startOverlay captures app stdout and stderr into app log', async () => {
|
|
const { dir, socketPath } = createTempSocketPath();
|
|
const appPath = path.join(dir, 'fake-subminer.sh');
|
|
const appLogPath = path.join(dir, 'app.log');
|
|
const originalAppLog = process.env.SUBMINER_APP_LOG;
|
|
fs.writeFileSync(
|
|
appPath,
|
|
'#!/bin/sh\nprintf "hello from stdout\\n"\nprintf "hello from stderr\\n" >&2\nexit 0\n',
|
|
);
|
|
fs.chmodSync(appPath, 0o755);
|
|
fs.writeFileSync(socketPath, '');
|
|
const originalCreateConnection = net.createConnection;
|
|
try {
|
|
process.env.SUBMINER_APP_LOG = appLogPath;
|
|
net.createConnection = (() => {
|
|
const socket = new EventEmitter() as net.Socket;
|
|
socket.destroy = (() => socket) as net.Socket['destroy'];
|
|
socket.setTimeout = (() => socket) as net.Socket['setTimeout'];
|
|
setTimeout(() => socket.emit('connect'), 10);
|
|
return socket;
|
|
}) as typeof net.createConnection;
|
|
|
|
await startOverlay(appPath, makeArgs(), socketPath);
|
|
|
|
const logText = fs.readFileSync(appLogPath, 'utf8');
|
|
assert.match(logText, /\[STDOUT\] hello from stdout/);
|
|
assert.match(logText, /\[STDERR\] hello from stderr/);
|
|
} finally {
|
|
net.createConnection = originalCreateConnection;
|
|
state.overlayProc = null;
|
|
state.overlayManagedByLauncher = false;
|
|
if (originalAppLog === undefined) {
|
|
delete process.env.SUBMINER_APP_LOG;
|
|
} else {
|
|
process.env.SUBMINER_APP_LOG = originalAppLog;
|
|
}
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('cleanupPlaybackSession stops launcher-managed overlay app and mpv-owned children', async () => {
|
|
const { dir } = createTempSocketPath();
|
|
const appPath = path.join(dir, 'fake-subminer.sh');
|
|
const appInvocationsPath = path.join(dir, 'app-invocations.log');
|
|
fs.writeFileSync(
|
|
appPath,
|
|
`#!/bin/sh\necho \"$@\" >> ${JSON.stringify(appInvocationsPath)}\nexit 0\n`,
|
|
);
|
|
fs.chmodSync(appPath, 0o755);
|
|
|
|
const calls: string[] = [];
|
|
const overlayProc = {
|
|
killed: false,
|
|
kill: () => {
|
|
calls.push('overlay-kill');
|
|
return true;
|
|
},
|
|
} as unknown as NonNullable<typeof state.overlayProc>;
|
|
const mpvProc = {
|
|
killed: false,
|
|
kill: () => {
|
|
calls.push('mpv-kill');
|
|
return true;
|
|
},
|
|
} as unknown as NonNullable<typeof state.mpvProc>;
|
|
const helperProc = {
|
|
killed: false,
|
|
kill: () => {
|
|
calls.push('helper-kill');
|
|
return true;
|
|
},
|
|
} as unknown as NonNullable<typeof state.overlayProc>;
|
|
|
|
state.stopRequested = false;
|
|
state.appPath = appPath;
|
|
state.overlayManagedByLauncher = true;
|
|
state.overlayProc = overlayProc;
|
|
state.mpvProc = mpvProc;
|
|
state.youtubeSubgenChildren.add(helperProc);
|
|
|
|
try {
|
|
await cleanupPlaybackSession(makeArgs());
|
|
|
|
assert.deepEqual(calls, ['overlay-kill', 'mpv-kill', 'helper-kill']);
|
|
assert.match(fs.readFileSync(appInvocationsPath, 'utf8'), /--stop/);
|
|
} finally {
|
|
state.overlayProc = null;
|
|
state.mpvProc = null;
|
|
state.youtubeSubgenChildren.clear();
|
|
state.overlayManagedByLauncher = false;
|
|
state.appPath = '';
|
|
state.stopRequested = false;
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
// ── findAppBinary: Linux packaged path discovery ──────────────────────────────
|
|
|
|
function makeExecutable(filePath: string): void {
|
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
fs.writeFileSync(filePath, '#!/bin/sh\nexit 0\n');
|
|
fs.chmodSync(filePath, 0o755);
|
|
}
|
|
|
|
function withFindAppBinaryEnvSandbox(run: () => void): void {
|
|
const originalAppImagePath = process.env.SUBMINER_APPIMAGE_PATH;
|
|
const originalBinaryPath = process.env.SUBMINER_BINARY_PATH;
|
|
try {
|
|
delete process.env.SUBMINER_APPIMAGE_PATH;
|
|
delete process.env.SUBMINER_BINARY_PATH;
|
|
run();
|
|
} finally {
|
|
if (originalAppImagePath === undefined) {
|
|
delete process.env.SUBMINER_APPIMAGE_PATH;
|
|
} else {
|
|
process.env.SUBMINER_APPIMAGE_PATH = originalAppImagePath;
|
|
}
|
|
if (originalBinaryPath === undefined) {
|
|
delete process.env.SUBMINER_BINARY_PATH;
|
|
} else {
|
|
process.env.SUBMINER_BINARY_PATH = originalBinaryPath;
|
|
}
|
|
}
|
|
}
|
|
|
|
function withAccessSyncStub(
|
|
isExecutablePath: (filePath: string) => boolean,
|
|
run: () => void,
|
|
): void {
|
|
const originalAccessSync = fs.accessSync;
|
|
try {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
(fs as any).accessSync = (filePath: string): void => {
|
|
if (isExecutablePath(filePath)) {
|
|
return;
|
|
}
|
|
throw Object.assign(new Error(`EACCES: ${filePath}`), { code: 'EACCES' });
|
|
};
|
|
run();
|
|
} finally {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
(fs as any).accessSync = originalAccessSync;
|
|
}
|
|
}
|
|
|
|
test('findAppBinary resolves ~/.local/bin/SubMiner.AppImage when it exists', () => {
|
|
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-test-home-'));
|
|
const originalHomedir = os.homedir;
|
|
try {
|
|
os.homedir = () => baseDir;
|
|
const appImage = path.join(baseDir, '.local/bin/SubMiner.AppImage');
|
|
makeExecutable(appImage);
|
|
|
|
withFindAppBinaryEnvSandbox(() => {
|
|
const result = findAppBinary('/some/other/path/subminer');
|
|
assert.equal(result, appImage);
|
|
});
|
|
} finally {
|
|
os.homedir = originalHomedir;
|
|
fs.rmSync(baseDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('findAppBinary resolves /opt/SubMiner/SubMiner.AppImage when ~/.local/bin candidate does not exist', () => {
|
|
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-test-home-'));
|
|
const originalHomedir = os.homedir;
|
|
try {
|
|
os.homedir = () => baseDir;
|
|
withFindAppBinaryEnvSandbox(() => {
|
|
withAccessSyncStub(
|
|
(filePath) => filePath === '/opt/SubMiner/SubMiner.AppImage',
|
|
() => {
|
|
const result = findAppBinary('/some/other/path/subminer');
|
|
assert.equal(result, '/opt/SubMiner/SubMiner.AppImage');
|
|
},
|
|
);
|
|
});
|
|
} finally {
|
|
os.homedir = originalHomedir;
|
|
fs.rmSync(baseDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('findAppBinary finds subminer on PATH when AppImage candidates do not exist', () => {
|
|
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-test-path-'));
|
|
const originalHomedir = os.homedir;
|
|
const originalPath = process.env.PATH;
|
|
try {
|
|
os.homedir = () => baseDir;
|
|
// No AppImage candidates in empty home dir; place subminer wrapper on PATH
|
|
const binDir = path.join(baseDir, 'bin');
|
|
const wrapperPath = path.join(binDir, 'subminer');
|
|
makeExecutable(wrapperPath);
|
|
process.env.PATH = `${binDir}${path.delimiter}${originalPath ?? ''}`;
|
|
|
|
withFindAppBinaryEnvSandbox(() => {
|
|
withAccessSyncStub(
|
|
(filePath) => filePath === wrapperPath,
|
|
() => {
|
|
// selfPath must differ from wrapperPath so the self-check does not exclude it
|
|
const result = findAppBinary(path.join(baseDir, 'launcher', 'subminer'));
|
|
assert.equal(result, wrapperPath);
|
|
},
|
|
);
|
|
});
|
|
} finally {
|
|
os.homedir = originalHomedir;
|
|
process.env.PATH = originalPath;
|
|
fs.rmSync(baseDir, { recursive: true, force: true });
|
|
}
|
|
});
|