Skip to content

Commit 4a1c170

Browse files
authored
Merge pull request #791 from nemtech/fix_unit_test
Fix unit test
2 parents e18100f + d7964b8 commit 4a1c170

File tree

8 files changed

+192
-14
lines changed

8 files changed

+192
-14
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ SDK Core| v1.0.1 | [symbol-sdk](https://www.npmjs.com/package/symbol-sdk)
1313
Catbuffer | v1.0.0 | [catbuffer-typescript](https://www.npmjs.com/package/catbuffer-typescript)
1414
Client Library | v1.0.0 | [symbol-openapi-typescript-fetch-client](https://www.npmjs.com/package/symbol-openapi-typescript-fetch-client)
1515

16-
- Fixed missing `utf-8` dependancy issue.
16+
- Fixed missing `utf-8` dependency issue.
1717
- Fixed `UnhandledPromiseRejection` issue in http repository.
1818

1919
## [1.0.0] - 13-Mar-2021

package-lock.json

Lines changed: 8 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "symbol-sdk",
3-
"version": "1.0.1",
3+
"version": "1.0.2",
44
"description": "Reactive symbol sdk for typescript and javascript",
55
"scripts": {
66
"pretest": "npm run build",

src/model/node/NodeTime.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ export class NodeTime {
2727
/**
2828
* The request send timestamp
2929
*/
30-
public readonly sendTimeStamp?: UInt64,
30+
public readonly sendTimeStamp: UInt64,
3131
/**
3232
* The request received timestamp
3333
*/
34-
public readonly receiveTimeStamp?: UInt64,
34+
public readonly receiveTimeStamp: UInt64,
3535
) {}
3636
}

src/model/transaction/Deadline.ts

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@
1616

1717
import { ChronoUnit, Duration, Instant, LocalDateTime, ZoneId } from '@js-joda/core';
1818
import { UInt64 } from '../UInt64';
19-
19+
export const defaultChronoUnit = ChronoUnit.HOURS;
20+
export const defaultDeadline = 2;
2021
/**
2122
* The deadline of the transaction. The deadline is given as the number of seconds elapsed since the creation of the nemesis block.
2223
* If a transaction does not get included in a block before the deadline is reached, it is deleted.
@@ -34,23 +35,34 @@ export class Deadline {
3435
* @param {ChronoUnit} chronoUnit the crhono unit. e.g ChronoUnit.HOURS
3536
* @returns {Deadline}
3637
*/
37-
public static create(epochAdjustment: number, deadline = 2, chronoUnit: ChronoUnit = ChronoUnit.HOURS): Deadline {
38+
public static create(epochAdjustment: number, deadline = defaultDeadline, chronoUnit: ChronoUnit = defaultChronoUnit): Deadline {
3839
const deadlineDateTime = Instant.now().plus(deadline, chronoUnit);
3940

4041
if (deadline <= 0) {
4142
throw new Error('deadline should be greater than 0');
4243
}
43-
return new Deadline(deadlineDateTime.minusSeconds(Duration.ofSeconds(epochAdjustment).seconds()).toEpochMilli());
44+
return Deadline.createFromAdjustedValue(deadlineDateTime.minusSeconds(epochAdjustment).toEpochMilli());
4445
}
4546

4647
/**
47-
* @internal
48+
*
4849
* Create an empty Deadline object using min local datetime.
49-
* This is method is an internal method to cope with undefined deadline for embedded transactions
50+
* It can be used used for embedded or nemesis transactions
51+
*
5052
* @returns {Deadline}
5153
*/
5254
public static createEmtpy(): Deadline {
53-
return new Deadline(0);
55+
return Deadline.createFromAdjustedValue(0);
56+
}
57+
58+
/**
59+
*
60+
* Create a Deadline where the adjusted values was externally calculated.
61+
*
62+
* @returns {Deadline}
63+
*/
64+
public static createFromAdjustedValue(adjustedValue: number): Deadline {
65+
return new Deadline(adjustedValue);
5466
}
5567

5668
/**

src/service/DeadlineService.ts

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*
2+
* Copyright 2021 NEM
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import { ChronoUnit, Duration, Instant } from '@js-joda/core';
18+
import { RepositoryFactory } from '../infrastructure';
19+
import { Deadline, defaultChronoUnit, defaultDeadline } from '../model/transaction';
20+
21+
/**
22+
* A factory service that allows the client to generate Deadline objects based on different strategies.
23+
*
24+
* The main issue is that sometimes the local computer time is not in sync, the created deadlines may be too old or too in the future and rejected by the server.
25+
*/
26+
export class DeadlineService {
27+
/**
28+
* The difference in milliseconds between the server and the local time. It used to create "server" deadline without asking for the server time every time a new deadline is created.
29+
*/
30+
private localTimeOffset: number;
31+
32+
/**
33+
* Private constructor, use the create static method
34+
*
35+
* @param repositoryFactory the repository factory to call the rest servers.
36+
* @param epochAdjustment the server epochAdjustment
37+
* @param serverTime the latest known server time to calculate the remote and local time difference.
38+
*/
39+
private constructor(
40+
private readonly repositoryFactory: RepositoryFactory,
41+
private readonly epochAdjustment: number,
42+
serverTime: number,
43+
) {
44+
this.localTimeOffset = Instant.now().minusSeconds(epochAdjustment).toEpochMilli() - serverTime;
45+
}
46+
47+
/**
48+
* It creates a deadline by querying the current time to the server each time. This is the most accurate but less efficient way.
49+
*
50+
* @param deadline the deadline value
51+
* @param chronoUnit the unit of the value.
52+
*/
53+
public async createDeadlineUsingServerTime(deadline = defaultDeadline, chronoUnit: ChronoUnit = defaultChronoUnit): Promise<Deadline> {
54+
const serverTime = (await this.repositoryFactory.createNodeRepository().getNodeTime().toPromise()).receiveTimeStamp.compact();
55+
return Deadline.createFromAdjustedValue(Duration.ofMillis(serverTime).plus(deadline, chronoUnit).toMillis());
56+
}
57+
58+
/**
59+
* It creates a deadline using the known difference between the local and server time.
60+
*
61+
* @param deadline the deadline value
62+
* @param chronoUnit the unit of the value.
63+
*/
64+
public createDeadlineUsingOffset(deadline = defaultDeadline, chronoUnit: ChronoUnit = defaultChronoUnit): Deadline {
65+
return Deadline.createFromAdjustedValue(
66+
Instant.now().plus(deadline, chronoUnit).minusMillis(this.localTimeOffset).minusSeconds(this.epochAdjustment).toEpochMilli(),
67+
);
68+
}
69+
70+
/**
71+
* It creates a deadline using the local time. If the local system time is not in sync, the Deadline may be rejected by the server.
72+
*
73+
* @param deadline the deadline value
74+
* @param chronoUnit the unit of the value.
75+
*/
76+
public createDeadlineUsingLocalTime(deadline = defaultDeadline, chronoUnit: ChronoUnit = defaultChronoUnit): Deadline {
77+
return Deadline.create(this.epochAdjustment, deadline, chronoUnit);
78+
}
79+
80+
/**
81+
* Factory method of this object.
82+
*
83+
* @param repositoryFactory the repository factory to call the rest servers.
84+
*/
85+
public static async create(repositoryFactory: RepositoryFactory): Promise<DeadlineService> {
86+
const epochAdjustment = await repositoryFactory.getEpochAdjustment().toPromise();
87+
const serverTime = (await repositoryFactory.createNodeRepository().getNodeTime().toPromise()).receiveTimeStamp.compact();
88+
return new DeadlineService(repositoryFactory, epochAdjustment, serverTime);
89+
}
90+
}

test/infrastructure/SerializeTransactionToJSON.spec.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -291,16 +291,17 @@ describe('SerializeTransactionToJSON', () => {
291291
});
292292

293293
it('should create AggregatedTransaction - Complete', () => {
294+
const deadline = Deadline.create(epochAdjustment);
294295
const transferTransaction = TransferTransaction.create(
295-
Deadline.create(epochAdjustment),
296+
deadline,
296297
Address.createFromRawAddress('VATNE7Q5BITMUTRRN6IB4I7FLSDRDWZA35C4KNQ'),
297298
[],
298299
PlainMessage.create('test-message'),
299300
NetworkType.PRIVATE_TEST,
300301
);
301302

302303
const aggregateTransaction = AggregateTransaction.createComplete(
303-
Deadline.create(epochAdjustment),
304+
deadline,
304305
[transferTransaction.toAggregate(account.publicAccount)],
305306
NetworkType.PRIVATE_TEST,
306307
[],
@@ -313,8 +314,9 @@ describe('SerializeTransactionToJSON', () => {
313314
});
314315

315316
it('should create AggregatedTransaction - Bonded', () => {
317+
const deadline = Deadline.create(epochAdjustment);
316318
const transferTransaction = TransferTransaction.create(
317-
Deadline.create(epochAdjustment),
319+
deadline,
318320
Address.createFromRawAddress('VATNE7Q5BITMUTRRN6IB4I7FLSDRDWZA35C4KNQ'),
319321
[],
320322
PlainMessage.create('test-message'),

test/service/DeadlineService.spec.ts

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
* Copyright 2018 NEM
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
import { ChronoUnit, Instant, ZoneId } from '@js-joda/core';
17+
import { expect } from 'chai';
18+
import { of as observableOf } from 'rxjs';
19+
import { instance, mock, when } from 'ts-mockito';
20+
import { NodeRepository, RepositoryFactory } from '../../src/infrastructure';
21+
import { Deadline, UInt64 } from '../../src/model';
22+
import { NodeTime } from '../../src/model/node';
23+
import { DeadlineService } from '../../src/service/DeadlineService';
24+
25+
describe('DeadlineService', () => {
26+
const realNow = Instant.now;
27+
const currentSystemMillis = Instant.parse('2021-05-31T10:20:21.154Z').toEpochMilli();
28+
const localtimeError = 10 * 1000; // 10 seconds diff
29+
const epochAdjustment = 1616694977;
30+
const currentServerMillis = currentSystemMillis - epochAdjustment * 1000 - localtimeError;
31+
before(() => {
32+
Instant.now = () => Instant.ofEpochMilli(currentSystemMillis);
33+
});
34+
35+
after(() => {
36+
Instant.now = realNow;
37+
});
38+
const createService = () => {
39+
const mockNodeRepository: NodeRepository = mock<NodeRepository>();
40+
when(mockNodeRepository.getNodeTime()).thenReturn(
41+
observableOf(new NodeTime(UInt64.fromUint(currentServerMillis), UInt64.fromUint(currentServerMillis))),
42+
);
43+
const mockRepoFactory = mock<RepositoryFactory>();
44+
when(mockRepoFactory.getEpochAdjustment()).thenReturn(observableOf(epochAdjustment));
45+
when(mockRepoFactory.createNodeRepository()).thenReturn(instance(mockNodeRepository));
46+
const repositoryFactory = instance(mockRepoFactory);
47+
return DeadlineService.create(repositoryFactory);
48+
};
49+
50+
const printDeadline = (deadline: Deadline) => deadline.toLocalDateTimeGivenTimeZone(epochAdjustment, ZoneId.UTC).toString();
51+
52+
it('createDeadlines', async () => {
53+
const service = await createService();
54+
// createDeadlineUsingLocalTime is 10 seconds ahead
55+
expect(printDeadline(service.createDeadlineUsingOffset())).eq('2021-05-31T12:20:11.154');
56+
expect(printDeadline(await service.createDeadlineUsingServerTime())).eq('2021-05-31T12:20:11.154');
57+
expect(printDeadline(service.createDeadlineUsingLocalTime())).eq('2021-05-31T12:20:21.154');
58+
59+
expect(printDeadline(service.createDeadlineUsingOffset(1))).eq('2021-05-31T11:20:11.154');
60+
expect(printDeadline(await service.createDeadlineUsingServerTime(1))).eq('2021-05-31T11:20:11.154');
61+
expect(printDeadline(service.createDeadlineUsingLocalTime(1))).eq('2021-05-31T11:20:21.154');
62+
63+
expect(printDeadline(service.createDeadlineUsingOffset(5, ChronoUnit.MINUTES))).eq('2021-05-31T10:25:11.154');
64+
expect(printDeadline(await service.createDeadlineUsingServerTime(5, ChronoUnit.MINUTES))).eq('2021-05-31T10:25:11.154');
65+
expect(printDeadline(service.createDeadlineUsingLocalTime(5, ChronoUnit.MINUTES))).eq('2021-05-31T10:25:21.154');
66+
});
67+
});

0 commit comments

Comments
 (0)