From 35730c4584ba0f8a97aad28e1378d80a8baf5c13 Mon Sep 17 00:00:00 2001 From: David Goss Date: Thu, 28 Jul 2022 13:22:02 +0100 Subject: [PATCH] fix: ensure durations are integers in json formatter --- src/formatter/helpers/duration_helpers.ts | 7 +++++++ src/formatter/helpers/duration_helpers_spec.ts | 18 ++++++++++++++++++ src/formatter/json_formatter.ts | 6 ++---- 3 files changed, 27 insertions(+), 4 deletions(-) create mode 100644 src/formatter/helpers/duration_helpers.ts create mode 100644 src/formatter/helpers/duration_helpers_spec.ts diff --git a/src/formatter/helpers/duration_helpers.ts b/src/formatter/helpers/duration_helpers.ts new file mode 100644 index 000000000..c3296aedd --- /dev/null +++ b/src/formatter/helpers/duration_helpers.ts @@ -0,0 +1,7 @@ +import { Duration } from '@cucumber/messages' + +const NANOS_IN_SECOND = 1_000_000_000 + +export function durationToNanoseconds(duration: Duration): number { + return Math.floor(duration.seconds * NANOS_IN_SECOND + duration.nanos) +} diff --git a/src/formatter/helpers/duration_helpers_spec.ts b/src/formatter/helpers/duration_helpers_spec.ts new file mode 100644 index 000000000..bfa2ecc41 --- /dev/null +++ b/src/formatter/helpers/duration_helpers_spec.ts @@ -0,0 +1,18 @@ +import { expect } from 'chai' +import { durationToNanoseconds } from './duration_helpers' + +describe('duration helpers', () => { + describe('durationToNanoseconds', () => { + it('should convert under a second', () => { + expect(durationToNanoseconds({ seconds: 0, nanos: 257344166 })).to.eq( + 257344166 + ) + }) + + it('should convert over a second', () => { + expect(durationToNanoseconds({ seconds: 2, nanos: 1043459 })).to.eq( + 2001043459 + ) + }) + }) +}) diff --git a/src/formatter/json_formatter.ts b/src/formatter/json_formatter.ts index 1f758cc05..01544f3d0 100644 --- a/src/formatter/json_formatter.ts +++ b/src/formatter/json_formatter.ts @@ -8,6 +8,7 @@ import { import { ITestCaseAttempt } from './helpers/event_data_collector' import { doesHaveValue, doesNotHaveValue } from '../value_checker' import { parseStepArgument } from '../step_arguments' +import { durationToNanoseconds } from './helpers/duration_helpers' const { getGherkinStepMap, getGherkinScenarioMap } = GherkinDocumentParser @@ -280,10 +281,7 @@ export default class JsonFormatter extends Formatter { status: messages.TestStepResultStatus[status].toLowerCase(), } if (doesHaveValue(testStepResult.duration)) { - data.result.duration = - messages.TimeConversion.durationToMilliseconds( - testStepResult.duration - ) * 1000000 + data.result.duration = durationToNanoseconds(testStepResult.duration) } if ( status === messages.TestStepResultStatus.FAILED &&