Unverified Commit 0756542b authored by Chiranjib Swain's avatar Chiranjib Swain Committed by GitHub
Browse files

Refactor error handling and improve test logging for installers (#989)

* Refactor error handling for version not found cases across multiple installers

* Mock core.error in tests to suppress error logs

* fix(graalvm): improve error messages for EA version not found scenarios

* refactor(tests): update error messages for version not found scenarios

* fix(graalvm): enhance error messages for version not found scenarios

* fix(graalvm): improve error messages for version not found scenarios with updated download URL

* fix(graalvm): improve error handling for EA version not found scenarios with clearer messages
parent 1d018f9b
Loading
Loading
Loading
Loading
+9
Changes for __tests__/cache.test.ts: 9 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -17,6 +17,7 @@ describe('dependency cache', () => {
  let spyWarning: jest.SpyInstance<void, Parameters<typeof core.warning>>;
  let spyDebug: jest.SpyInstance<void, Parameters<typeof core.debug>>;
  let spySaveState: jest.SpyInstance<void, Parameters<typeof core.saveState>>;
  let spyCoreError: jest.SpyInstance;

  beforeEach(() => {
    workspace = mkdtempSync(join(tmpdir(), 'setup-java-cache-'));
@@ -51,6 +52,10 @@ describe('dependency cache', () => {

    spySaveState = jest.spyOn(core, 'saveState');
    spySaveState.mockImplementation(() => null);

    // Mock core.error to suppress error logs
    spyCoreError = jest.spyOn(core, 'error');
    spyCoreError.mockImplementation(() => {});
  });

  afterEach(() => {
@@ -58,6 +63,10 @@ describe('dependency cache', () => {
    process.env['GITHUB_WORKSPACE'] = ORIGINAL_GITHUB_WORKSPACE;
    process.env['RUNNER_OS'] = ORIGINAL_RUNNER_OS;
    resetState();

    jest.resetAllMocks();
    jest.clearAllMocks();
    jest.restoreAllMocks();
  });

  describe('restore', () => {
+13
Changes for __tests__/cleanup-java.test.ts: 13 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -11,19 +11,32 @@ describe('cleanup', () => {
    Parameters<typeof cache.saveCache>
  >;
  let spyJobStatusSuccess: jest.SpyInstance;
  let spyCoreError: jest.SpyInstance;

  beforeEach(() => {
    spyWarning = jest.spyOn(core, 'warning');
    spyWarning.mockImplementation(() => null);

    spyInfo = jest.spyOn(core, 'info');
    spyInfo.mockImplementation(() => null);

    spyCacheSave = jest.spyOn(cache, 'saveCache');

    spyJobStatusSuccess = jest.spyOn(util, 'isJobStatusSuccess');
    spyJobStatusSuccess.mockReturnValue(true);

    // Mock core.error to suppress error logs
    spyCoreError = jest.spyOn(core, 'error');
    spyCoreError.mockImplementation(() => {});

    createStateForSuccessfulRestore();
  });

  afterEach(() => {
    resetState();
    jest.resetAllMocks();
    jest.clearAllMocks();
    jest.restoreAllMocks();
  });

  it('does not fail nor warn even when the save process throws a ReserveCacheError', async () => {
+9 −3
Changes for __tests__/distributors/adopt-installer.test.ts: 9 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -9,9 +9,11 @@ import {JavaInstallerOptions} from '../../src/distributions/base-models';
import os from 'os';

import manifestData from '../data/adopt.json';
import * as core from '@actions/core';

describe('getAvailableVersions', () => {
  let spyHttpClient: jest.SpyInstance;
  let spyCoreError: jest.SpyInstance;

  beforeEach(() => {
    spyHttpClient = jest.spyOn(HttpClient.prototype, 'getJson');
@@ -20,6 +22,10 @@ describe('getAvailableVersions', () => {
      headers: {},
      result: []
    });

    // Mock core.error to suppress error logs
    spyCoreError = jest.spyOn(core, 'error');
    spyCoreError.mockImplementation(() => {});
  });

  afterEach(() => {
@@ -262,7 +268,7 @@ describe('findPackageForDownload', () => {
    distribution['getAvailableVersions'] = async () => manifestData as any;
    await expect(
      distribution['findPackageForDownload']('9.0.8')
    ).rejects.toThrow(/Could not find satisfied version for SemVer */);
    ).rejects.toThrow(/No matching version found for SemVer */);
  });

  it('version is not found', async () => {
@@ -277,7 +283,7 @@ describe('findPackageForDownload', () => {
    );
    distribution['getAvailableVersions'] = async () => manifestData as any;
    await expect(distribution['findPackageForDownload']('7.x')).rejects.toThrow(
      /Could not find satisfied version for SemVer */
      /No matching version found for SemVer */
    );
  });

@@ -293,7 +299,7 @@ describe('findPackageForDownload', () => {
    );
    distribution['getAvailableVersions'] = async () => [];
    await expect(distribution['findPackageForDownload']('11')).rejects.toThrow(
      /Could not find satisfied version for SemVer */
      /No matching version found for SemVer */
    );
  });
});
+100 −7
Changes for __tests__/distributors/base-installer.test.ts: 100 added lines, 7 removed lines.
Original line number Diff line number Diff line
@@ -38,7 +38,7 @@ class EmptyJavaBase extends JavaBase {
  ): Promise<JavaDownloadRelease> {
    const availableVersion = '11.0.9';
    if (!semver.satisfies(availableVersion, range)) {
      throw new Error('Available version not found');
      throw this.createVersionNotFoundError(range, [availableVersion]);
    }

    return {
@@ -248,6 +248,7 @@ describe('setupJava', () => {
  let spyCoreExportVariable: jest.SpyInstance;
  let spyCoreAddPath: jest.SpyInstance;
  let spyCoreSetOutput: jest.SpyInstance;
  let spyCoreError: jest.SpyInstance;

  beforeEach(() => {
    spyGetToolcachePath = jest.spyOn(util, 'getToolcachePath');
@@ -287,6 +288,10 @@ describe('setupJava', () => {
    spyCoreSetOutput = jest.spyOn(core, 'setOutput');
    spyCoreSetOutput.mockImplementation(() => undefined);

    // Mock core.error to suppress error logs
    spyCoreError = jest.spyOn(core, 'error');
    spyCoreError.mockImplementation(() => undefined);

    jest.spyOn(os, 'arch').mockReturnValue('x86' as ReturnType<typeof os.arch>);
  });

@@ -530,19 +535,16 @@ describe('setupJava', () => {
        checkLatest: false
      }
    ]
  ])(
    'should throw an error for Available version not found for %s',
    async input => {
  ])('should throw an error for version not found for %s', async input => {
    mockJavaBase = new EmptyJavaBase(input);
    await expect(mockJavaBase.setupJava()).rejects.toThrow(
        'Available version not found'
      `No matching version found for SemVer '${input.version}'`
    );
    expect(spyTcFindAllVersions).toHaveBeenCalled();
    expect(spyCoreAddPath).not.toHaveBeenCalled();
    expect(spyCoreExportVariable).not.toHaveBeenCalled();
    expect(spyCoreSetOutput).not.toHaveBeenCalled();
    }
  );
  });
});

describe('normalizeVersion', () => {
@@ -570,6 +572,97 @@ describe('normalizeVersion', () => {
  });
});

describe('createVersionNotFoundError', () => {
  it('should include all required fields in error message without available versions', () => {
    const mockJavaBase = new EmptyJavaBase({
      version: '17.0.5',
      architecture: 'x64',
      packageType: 'jdk',
      checkLatest: false
    });

    const error = (mockJavaBase as any).createVersionNotFoundError('17.0.5');

    expect(error.message).toContain(
      "No matching version found for SemVer '17.0.5'"
    );
    expect(error.message).toContain('Distribution: Empty');
    expect(error.message).toContain('Package type: jdk');
    expect(error.message).toContain('Architecture: x64');
  });

  it('should include available versions when provided', () => {
    const mockJavaBase = new EmptyJavaBase({
      version: '17.0.5',
      architecture: 'x64',
      packageType: 'jdk',
      checkLatest: false
    });

    const availableVersions = ['11.0.1', '11.0.2', '17.0.1', '17.0.2'];
    const error = (mockJavaBase as any).createVersionNotFoundError(
      '17.0.5',
      availableVersions
    );

    expect(error.message).toContain(
      "No matching version found for SemVer '17.0.5'"
    );
    expect(error.message).toContain('Distribution: Empty');
    expect(error.message).toContain('Package type: jdk');
    expect(error.message).toContain('Architecture: x64');
    expect(error.message).toContain(
      'Available versions: 11.0.1, 11.0.2, 17.0.1, 17.0.2'
    );
  });

  it('should truncate available versions when there are many', () => {
    const mockJavaBase = new EmptyJavaBase({
      version: '17.0.5',
      architecture: 'x64',
      packageType: 'jdk',
      checkLatest: false
    });

    // Create 60 versions to test truncation
    const availableVersions = Array.from({length: 60}, (_, i) => `11.0.${i}`);
    const error = (mockJavaBase as any).createVersionNotFoundError(
      '17.0.5',
      availableVersions
    );

    expect(error.message).toContain('Available versions:');
    expect(error.message).toContain('...');
    expect(error.message).toContain('(showing first 50 of 60 versions');
  });

  it('should include additional context when provided', () => {
    const mockJavaBase = new EmptyJavaBase({
      version: '17.0.5',
      architecture: 'x64',
      packageType: 'jdk',
      checkLatest: false
    });

    const availableVersions = ['11.0.1', '11.0.2'];
    const additionalContext = 'Platform: linux';
    const error = (mockJavaBase as any).createVersionNotFoundError(
      '17.0.5',
      availableVersions,
      additionalContext
    );

    expect(error.message).toContain(
      "No matching version found for SemVer '17.0.5'"
    );
    expect(error.message).toContain('Distribution: Empty');
    expect(error.message).toContain('Package type: jdk');
    expect(error.message).toContain('Architecture: x64');
    expect(error.message).toContain('Platform: linux');
    expect(error.message).toContain('Available versions: 11.0.1, 11.0.2');
  });
});

describe('getToolcacheVersionName', () => {
  const DummyJavaBase = JavaBase as any;

+7 −2
Changes for __tests__/distributors/corretto-installer.test.ts: 7 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -4,13 +4,14 @@ import {JavaInstallerOptions} from '../../src/distributions/base-models';
import {CorrettoDistribution} from '../../src/distributions/corretto/installer';
import * as util from '../../src/util';
import os from 'os';
import {isGeneratorFunction} from 'util/types';
import * as core from '@actions/core';

import manifestData from '../data/corretto.json';

describe('getAvailableVersions', () => {
  let spyHttpClient: jest.SpyInstance;
  let spyGetDownloadArchiveExtension: jest.SpyInstance;
  let spyCoreError: jest.SpyInstance;

  beforeEach(() => {
    spyHttpClient = jest.spyOn(HttpClient.prototype, 'getJson');
@@ -23,6 +24,10 @@ describe('getAvailableVersions', () => {
      util,
      'getDownloadArchiveExtension'
    );

    // Mock core.error to suppress error logs
    spyCoreError = jest.spyOn(core, 'error');
    spyCoreError.mockImplementation(() => {});
  });

  afterEach(() => {
@@ -198,7 +203,7 @@ describe('getAvailableVersions', () => {

      await expect(
        distribution['findPackageForDownload'](version)
      ).rejects.toThrow("Could not find satisfied version for SemVer '4'");
      ).rejects.toThrow("No matching version found for SemVer '4'");
    });

    it.each([
Loading