Skip to content

Commit

Permalink
chore: add unit tests and change scope for tested methods
Browse files Browse the repository at this point in the history
  • Loading branch information
mingxuanzhangsfdx committed Mar 25, 2024
1 parent f3c10e6 commit 4b35861
Show file tree
Hide file tree
Showing 9 changed files with 256 additions and 4 deletions.
1 change: 1 addition & 0 deletions hello
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
world
2 changes: 1 addition & 1 deletion src/streaming/streamingClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ export class StreamingClient {
return null;
}

private async getCompletedTestRun(
public async getCompletedTestRun(
testRunId: string
): Promise<ApexTestQueueItem> {
const queryApexTestQueueItem = `SELECT Id, Status, ApexClassId, TestRunResultId FROM ApexTestQueueItem WHERE ParentJobId = '${testRunId}'`;
Expand Down
4 changes: 2 additions & 2 deletions src/tests/codeCoverage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ export class CodeCoverage {
}

@elapsedTime()
private async queryPerClassCodeCov(
public async queryPerClassCodeCov(
apexTestClassSet: Set<string>
): Promise<ApexCodeCoverage[]> {
const perClassCodeCovQuery =
Expand All @@ -188,7 +188,7 @@ export class CodeCoverage {
}

@elapsedTime()
private async queryAggregateCodeCov(
public async queryAggregateCodeCov(
apexClassIdSet: Set<string>
): Promise<ApexCodeCoverageAggregate[]> {
const codeCoverageQuery =
Expand Down
26 changes: 26 additions & 0 deletions test-result-123-junit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
<testsuite name="force.apex" timestamp="123" hostname="123" tests="1" failures="0" errors="0" time="0.00">
<properties>
<property name="failRate" value="123"/>
<property name="testsRan" value="1"/>
<property name="orgId" value="123"/>
<property name="outcome" value="123"/>
<property name="passing" value="1"/>
<property name="failing" value="0"/>
<property name="skipped" value="0"/>
<property name="passRate" value="123"/>
<property name="testStartTime" value="Fri Jan 01 0123 12:00:00 AM"/>
<property name="testExecutionTime" value="0.00 s"/>
<property name="testTotalTime" value="0.00 s"/>
<property name="commandTime" value="0.00 s"/>
<property name="hostname" value="123"/>
<property name="username" value="123"/>
<property name="testRunId" value="123"/>
<property name="userId" value="123"/>
</properties>
<testcase name="method" classname="apexClass" time="0.00">
<failure message="123"><![CDATA[123]]></failure>
</testcase>
</testsuite>
</testsuites>
1 change: 1 addition & 0 deletions test-run-id.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
123
31 changes: 31 additions & 0 deletions test/streaming/streamingClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -548,3 +548,34 @@ describe('Streaming API Client', () => {
assert.calledOnce(clearIntervalStub);
});
});

describe('getCompletedTestRun', () => {
const $$ = new TestContext();

beforeEach(async () => {
sandboxStub = createSandbox();
// Stub retrieveMaxApiVersion to get over "Domain Not Found: The org cannot be found" error
sandboxStub
.stub(Connection.prototype, 'retrieveMaxApiVersion')
.resolves('50.0');
await $$.stubAuths(testData);
mockConnection = await testData.getConnection();
});

afterEach(() => {
sandboxStub.restore();
});

it('should return largeTestResultErr if query fails', () => {
const mockToolingQuery = sandboxStub.stub(mockConnection.tooling, 'query');
const errorMessage = '123';
mockToolingQuery.rejects(new Error(errorMessage));
const streamClient = new StreamingClient(mockConnection);
try {
streamClient.getCompletedTestRun('testRunId');
} catch (error) {
expect(error.message).to.include('ApexTestQueueItem');
expect(error.message).to.include(errorMessage);
}
});
});
32 changes: 32 additions & 0 deletions test/tests/asyncTests.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,23 @@ describe('Run Apex tests asynchronously', () => {
expect(result.length).to.eql(1);
});

it('should throw error when queryPromises fail in getAsyncTestResults', async () => {
sandboxStub
.stub(mockConnection.tooling, 'query')
.resolves({ done: true, totalSize: 1, records: [] });
const errorMessage = '123';
sandboxStub.stub(utils, 'queryAll').rejects(new Error(errorMessage));
const asyncTestSrv = new AsyncTests(mockConnection);
try {
await asyncTestSrv.getAsyncTestResults(pollResponse);
fail('should throw an error');
} catch (e) {
expect(e.message).to.include(
nls.localize('largeTestResultErr', ['ApexTestResult[]', errorMessage])
);
}
});

it('should format multiple queries correctly', async () => {
const queryOneIds = queryIds.slice(0, QUERY_RECORD_LIMIT).join("','");
const queryOne = `${queryStart}('${queryOneIds}')`;
Expand Down Expand Up @@ -1405,6 +1422,21 @@ describe('Run Apex tests asynchronously', () => {
expect(handlerStub.calledOnce).to.be.true;
});
});

it('should throw error when query fails in checkRunStatus', async () => {
const asyncTestSrv = new AsyncTests(mockConnection);
const mockToolingQuery = sandboxStub.stub(mockConnection.tooling, 'query');
const errorMessage = '123';
mockToolingQuery.onFirstCall().rejects(new Error(errorMessage));
try {
await asyncTestSrv.checkRunStatus(testRunId);
fail('should throw an error');
} catch (e) {
expect(e.message).to.include(
nls.localize('largeTestResultErr', ['ApexTestRunResult', errorMessage])
);
}
});
});

describe('elapsedTime', () => {
Expand Down
67 changes: 67 additions & 0 deletions test/tests/codeCoverage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
ApexCodeCoverageAggregateRecord
} from '../../src/tests/types';
import { QUERY_RECORD_LIMIT } from '../../src/tests/constants';
import { nls } from '../../src/i18n';

let mockConnection: Connection;
let sandboxStub: SinonSandbox;
Expand Down Expand Up @@ -158,6 +159,72 @@ describe('Get code coverage results', () => {
expect(coveredLines).to.equal(0);
});

it('should throw error when queryPerClassCodeCov fail', async () => {
const errorMessage = '123';
const codeCov = new CodeCoverage(mockConnection);
sandboxStub
.stub(codeCov, 'queryPerClassCodeCov')
.rejects(new Error(errorMessage));
try {
await codeCov.getPerClassCodeCoverage(
new Set<string>(['0001x05958', '0001x05959', '0001x05951'])
);
} catch (e) {
expect(e.message).to.be.include(
nls.localize('largeTestResultErr', ['ApexCodeCoverage[]', errorMessage])
);
}
});

it('should throw error when queryAggregateCodeCov fail', async () => {
const codeCoverageQueryResult = [
{
ApexClassOrTrigger: { Id: '0001x05958', Name: 'ApexTrigger1' },
NumLinesCovered: 5,
NumLinesUncovered: 1,
Coverage: { coveredLines: [1, 2, 3, 4, 5], uncoveredLines: [6] }
},
{
ApexClassOrTrigger: { Id: '0001x05959', Name: 'ApexTrigger2' },
NumLinesCovered: 6,
NumLinesUncovered: 2,
Coverage: { coveredLines: [1, 2, 3, 4, 5, 6], uncoveredLines: [7, 8] }
},
{
ApexClassOrTrigger: { Id: '0001x05951', Name: 'ApexTrigger3' },
NumLinesCovered: 7,
NumLinesUncovered: 3,
Coverage: {
coveredLines: [1, 2, 3, 4, 5, 6, 7],
uncoveredLines: [8, 9, 10]
}
}
];

toolingQueryStub.resolves({
done: true,
totalSize: 3,
records: codeCoverageQueryResult
} as ApexCodeCoverageAggregate);
const errorMessage = '123';
const codeCov = new CodeCoverage(mockConnection);
sandboxStub
.stub(codeCov, 'queryAggregateCodeCov')
.rejects(new Error(errorMessage));
try {
await codeCov.getPerClassCodeCoverage(
new Set<string>(['0001x05958', '0001x05959', '0001x05951'])
);
} catch (e) {
expect(e.message).to.be.include(
nls.localize('largeTestResultErr', [
'ApexCodeCoverageAggregate[]',
errorMessage
])
);
}
});

it('should return per class code coverage for multiple test classes', async () => {
const perClassCodeCovResult = [
{
Expand Down
96 changes: 95 additions & 1 deletion test/tests/testService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import { AuthInfo, Connection } from '@salesforce/core';
import { MockTestOrgData, TestContext } from '@salesforce/core/lib/testSetup';
import { fail } from 'assert';
import { expect } from 'chai';
import * as u from '../../src/tests/utils';
import { createSandbox, SinonSandbox, SinonStub, spy } from 'sinon';
import { TestService } from '../../src';
import { ApexTestResultData, ResultFormat, TestService } from '../../src';
import { nls } from '../../src/i18n';

let mockConnection: Connection;
let sandboxStub: SinonSandbox;
Expand Down Expand Up @@ -288,3 +290,95 @@ describe('Apex Test Suites', async () => {
});
});
});

describe('WriteResultFiles', async () => {
const $$ = new TestContext();
beforeEach(async () => {
sandboxStub = createSandbox();
await $$.stubAuths(testData);
// Stub retrieveMaxApiVersion to get over "Domain Not Found: The org cannot be found" error
sandboxStub
.stub(Connection.prototype, 'retrieveMaxApiVersion')
.resolves('50.0');
mockConnection = await Connection.create({
authInfo: await AuthInfo.create({
username: testData.username
})
});

toolingQueryStub = sandboxStub.stub(mockConnection.tooling, 'query');
toolingCreateStub = sandboxStub.stub(mockConnection.tooling, 'create');
});

afterEach(async () => {
sandboxStub.restore();
});

it('should throw error when stringify fail', async () => {
toolingQueryStub.resolves({ records: [{ Id: 'xxxxxxx243' }] });
const errorMessage = '123';
sandboxStub.stub(u, 'stringify').throws(new Error(errorMessage));
const mockResult = {
summary: {
failRate: '123',
testsRan: 1,
orgId: '123',
outcome: '123',
passing: 1,
failing: 0,
skipped: 0,
passRate: '123',
skipRate: '123',
testStartTime: '123',
testExecutionTimeInMs: 1,
testTotalTimeInMs: 1,
commandTimeInMs: 1,
hostname: '123',
username: '123',
testRunId: '123',
userId: '123'
},
tests: [
{
id: '123',
queueItemId: '123',
stackTrace: '123',
message: '123',
asyncApexJobId: '123',
methodName: 'method',
outcome: 'CompileFail',
apexLogId: '123',
apexClass: {
id: '123',
name: 'apex',
namespacePrefix: 'a',
fullName: 'apexClass'
},
runTime: 1,
testTimestamp: '123',
fullName: 'mockApexTestResultData'
} as ApexTestResultData
]
};

const outputDirConfig = {
dirPath: './',
resultFormats: [ResultFormat.json],
fileInfos: [
{
filename: 'hello',
content: 'world'
}
]
};
const testService = new TestService(mockConnection);
try {
await testService.writeResultFiles(mockResult, outputDirConfig, false);
fail('Should throw an error');
} catch (e) {
expect(e.message).to.include(
nls.localize('jsonStringifyErr', [ResultFormat.json, errorMessage])
);
}
});
});

0 comments on commit 4b35861

Please sign in to comment.