import fs from 'fs'; import http from 'http'; import { AddressInfo } from 'net'; import os from 'os'; import path from 'path'; import { checkForUpdate } from './checkForUpdate'; import { showBorderedMessage } from './showBorderedMessage'; import { getLastVersion } from './state/lastVersion'; import { version } from '../../package.json'; // NON-MOCKED against the real npm-registry-fetch: a local HTTP server stands in // for the registry so the request that actually goes out can be inspected. jest.mock('./log'); jest.mock('./showBorderedMessage'); jest.mock('./state/lastVersion'); describe('checkForUpdate against a local registry', () => { const originalEnv = process.env; const originalCwd = process.cwd(); let dir: string; let server: http.Server; let requests: http.IncomingMessage[]; let respond: (res: http.ServerResponse) => void; let consoleError: jest.SpyInstance; const registryUrl = () => `http://127.0.0.1:${ (server.address() as AddressInfo).port }/api/npm/npm-remote/`; const npmrc = (file: string, contents: string) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, contents); }; beforeEach(async () => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'alks-registry-')); process.env = { ...originalEnv }; delete process.env.npm_config_registry; process.env.npm_config_userconfig = path.join(dir, 'user.npmrc'); process.env.npm_config_globalconfig = path.join(dir, 'global.npmrc'); // A proxy in the test machine's environment must not capture 127.0.0.1 process.env.NO_PROXY = '127.0.0.1'; process.env.no_proxy = '127.0.0.1'; requests = []; respond = (res) => { res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ version: '999.0.0' })); }; server = http.createServer((req, res) => { requests.push(req); respond(res); }); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve) ); consoleError = jest.spyOn(console, 'error').mockImplementation(() => {}); (getLastVersion as jest.Mock).mockResolvedValue(version); }); afterEach(async () => { process.chdir(originalCwd); process.env = originalEnv; consoleError.mockRestore(); await new Promise((resolve) => server.close(resolve)); fs.rmSync(dir, { recursive: true, force: true }); jest.resetAllMocks(); }); it('asks the configured registry, with the login stored for it, and announces the update', async () => { const registry = registryUrl(); const hostAndPath = registry.replace(/^http:/, ''); npmrc( path.join(dir, 'user.npmrc'), `registry=${registry}\n${hostAndPath}:_authToken=abc123\n` ); await checkForUpdate(); expect(requests).toHaveLength(1); expect(requests[0].url).toBe('/api/npm/npm-remote/alks/latest'); expect(requests[0].headers.authorization).toBe('Bearer abc123'); expect(showBorderedMessage).toHaveBeenCalledWith( 40, expect.stringContaining('999.0.0') ); expect(consoleError).not.toHaveBeenCalled(); }); it('follows a registry set by environment variable', async () => { process.env.npm_config_registry = registryUrl(); await checkForUpdate(); expect(requests[0].url).toBe('/api/npm/npm-remote/alks/latest'); expect(showBorderedMessage).toHaveBeenCalled(); }); it('ignores a .npmrc in the directory the command runs from', async () => { npmrc(path.join(dir, 'user.npmrc'), `registry=${registryUrl()}\n`); const project = path.join(dir, 'project'); npmrc( path.join(project, '.npmrc'), 'registry=http://127.0.0.1:1/\n//127.0.0.1:1/:_authToken=stolen\n' ); process.chdir(project); await checkForUpdate(); expect(requests).toHaveLength(1); expect(requests[0].headers.authorization).toBeUndefined(); expect(consoleError).not.toHaveBeenCalled(); }); it('announces an update from a registry that answers within the time limit', async () => { process.env.npm_config_registry = registryUrl(); respond = (res) => { setTimeout(() => { res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ version: '999.0.0' })); }, 1500); }; await checkForUpdate(); expect(showBorderedMessage).toHaveBeenCalled(); expect(consoleError).not.toHaveBeenCalled(); }); it.each([401, 403])( 'warns that the login was rejected on a %i', async (status) => { process.env.npm_config_registry = registryUrl(); respond = (res) => { res.statusCode = status; res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ error: 'nope' })); }; await expect(checkForUpdate()).resolves.toBeUndefined(); expect(consoleError).toHaveBeenCalledTimes(1); const warning = consoleError.mock.calls[0][0]; expect(warning).toContain('rejected the login'); expect(warning).toContain(`HTTP ${status}`); expect(warning).not.toContain('NODE_EXTRA_CA_CERTS'); } ); it('warns, and does not hang, when the connection is refused', async () => { process.env.npm_config_registry = 'http://127.0.0.1:1/'; await expect(checkForUpdate()).resolves.toBeUndefined(); expect(consoleError).toHaveBeenCalledTimes(1); expect(consoleError.mock.calls[0][0]).toContain( 'WARNING: update check failed' ); }); it('only logs, and returns within 3 seconds, when the registry never answers', async () => { process.env.npm_config_registry = registryUrl(); // Never ends the response; the server is closed once the test is done respond = () => {}; const started = Date.now(); await checkForUpdate(); expect(Date.now() - started).toBeLessThan(3500); expect(consoleError).not.toHaveBeenCalled(); expect(showBorderedMessage).not.toHaveBeenCalled(); }, 10000); });