Skip to content

Commit

Permalink
fix: inline mockdate and fix negative thread time (#972)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Mar 17, 2022
1 parent 0e9b92d commit aa239bf
Show file tree
Hide file tree
Showing 8 changed files with 105 additions and 46 deletions.
5 changes: 4 additions & 1 deletion packages/vite-node/src/server.ts
Expand Up @@ -6,6 +6,9 @@ import { toFilePath, withInlineSourcemap } from './utils'

export * from './externalize'

// store the original reference to avoid it been mocked
const RealDate = Date

export class ViteNodeServer {
private fetchPromiseMap = new Map<string, Promise<FetchResult>>()
private transformPromiseMap = new Map<string, Promise<TransformResult | null | undefined>>()
Expand Down Expand Up @@ -78,7 +81,7 @@ export class ViteNodeServer {
const filePath = toFilePath(id, this.server.config.root)

const module = this.server.moduleGraph.getModuleById(id)
const timestamp = module?.lastHMRTimestamp || Date.now()
const timestamp = module?.lastHMRTimestamp || RealDate.now()
const cache = this.fetchCache.get(filePath)
if (timestamp && cache && cache.timestamp >= timestamp)
return cache.result
Expand Down
29 changes: 0 additions & 29 deletions packages/vitest/LICENSE.md
Expand Up @@ -1231,35 +1231,6 @@ Repository: unjs/mlly
---------------------------------------

## mockdate
License: MIT
By: Bob Lauer
Repository: https://github.com/boblauer/MockDate.git

> The MIT License (MIT)
>
> Copyright (c) 2014 Bob Lauer
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in all
> copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
> SOFTWARE.
---------------------------------------

## natural-compare
License: MIT
By: Lauri Rooden
Expand Down
1 change: 0 additions & 1 deletion packages/vitest/package.json
Expand Up @@ -118,7 +118,6 @@
"magic-string": "^0.26.1",
"micromatch": "^4.0.4",
"mlly": "^0.4.3",
"mockdate": "^3.0.5",
"natural-compare": "^1.4.0",
"pathe": "^0.2.0",
"picocolors": "^1.0.0",
Expand Down
91 changes: 91 additions & 0 deletions packages/vitest/src/integrations/mockdate.ts
@@ -0,0 +1,91 @@
/* Ported from https://github.com/boblauer/MockDate/blob/master/src/mockdate.ts */
/*
The MIT License (MIT)
Copyright (c) 2014 Bob Lauer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

export const RealDate = Date

let now: null | number = null

class MockDate extends RealDate {
constructor()
constructor(value: number | string)
constructor(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number)
constructor(y?: number | string, m?: number, d?: number, h?: number, M?: number, s?: number, ms?: number) {
super()

let date: any
switch (arguments.length) {
case 0:
if (now !== null)
date = new RealDate(now.valueOf())
else
date = new RealDate()
break
case 1:
date = new RealDate(y!)
break
default:
d = typeof d === 'undefined' ? 1 : d
h = h || 0
M = M || 0
s = s || 0
ms = ms || 0
date = new RealDate(y as number, m!, d, h, M, s, ms)
break
}

return date
}
}

// MockDate.prototype = RealDate.prototype

MockDate.UTC = RealDate.UTC

MockDate.now = function() {
return new MockDate().valueOf()
}

MockDate.parse = function(dateString) {
return RealDate.parse(dateString)
}

MockDate.toString = function() {
return RealDate.toString()
}

export function mockDate(date: string | number | Date): void {
const dateObj = new RealDate(date.valueOf())
if (isNaN(dateObj.getTime()))
throw new TypeError(`mockdate: The time set is an invalid date: ${date}`)

// @ts-expect-error global
globalThis.Date = MockDate

now = dateObj.valueOf()
}

export function resetDate(): void {
globalThis.Date = RealDate
}
8 changes: 4 additions & 4 deletions packages/vitest/src/integrations/timers.ts
Expand Up @@ -12,15 +12,15 @@ import type {
import {
withGlobal,
} from '@sinonjs/fake-timers'
import MockDate from 'mockdate'
import { RealDate, mockDate, resetDate } from './mockdate'

export class FakeTimers {
private _clock!: InstalledClock
private _fakingTime: boolean
private _fakingDate: boolean
private _fakeTimers: FakeTimerWithContext
private _maxLoops: number
private _now = Date.now
private _now = RealDate.now

constructor({
global,
Expand Down Expand Up @@ -83,7 +83,7 @@ export class FakeTimers {

useRealTimers(): void {
if (this._fakingDate) {
MockDate.reset()
resetDate()
this._fakingDate = false
}

Expand Down Expand Up @@ -127,7 +127,7 @@ export class FakeTimers {
this._clock.setSystemTime(now)
}
else {
MockDate.set(now ?? this.getRealSystemTime())
mockDate(now ?? this.getRealSystemTime())
this._fakingDate = true
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/node/reporters/base.ts
Expand Up @@ -135,7 +135,7 @@ export abstract class BaseReporter implements Reporter {
}

const executionTime = this.end - this.start
const threadTime = files.reduce((acc, test) => acc + (test.result?.duration || 0) + (test.collectDuration || 0), 0)
const threadTime = files.reduce((acc, test) => acc + Math.max(0, test.result?.duration || 0) + Math.max(0, test.collectDuration || 0), 0)

const padTitle = (str: string) => c.dim(`${str.padStart(10)} `)
const time = (time: number) => {
Expand Down
9 changes: 5 additions & 4 deletions packages/vitest/src/runtime/setup.ts
Expand Up @@ -5,6 +5,7 @@ import type { ResolvedConfig } from '../types'
import { getWorkerState, toArray } from '../utils'
import * as VitestIndex from '../index'
import { resetRunOnceCounter } from '../integrations/run-once'
import { RealDate } from '../integrations/mockdate'
import { rpc } from './rpc'

let globalSetup = false
Expand Down Expand Up @@ -63,7 +64,7 @@ export function setupConsoleLogSpy() {
type: 'stdout',
content: stdoutBuffer.map(i => String(i)).join(''),
taskId: getWorkerState().current?.id,
time: stdoutTime || Date.now(),
time: stdoutTime || RealDate.now(),
})
}
stdoutBuffer.length = 0
Expand All @@ -75,7 +76,7 @@ export function setupConsoleLogSpy() {
type: 'stderr',
content: stderrBuffer.map(i => String(i)).join(''),
taskId: getWorkerState().current?.id,
time: stderrTime || Date.now(),
time: stderrTime || RealDate.now(),
})
}
stderrBuffer.length = 0
Expand All @@ -84,15 +85,15 @@ export function setupConsoleLogSpy() {

const stdout = new Writable({
write(data, encoding, callback) {
stdoutTime = stdoutTime || Date.now()
stdoutTime = stdoutTime || RealDate.now()
stdoutBuffer.push(data)
schedule()
callback()
},
})
const stderr = new Writable({
write(data, encoding, callback) {
stderrTime = stderrTime || Date.now()
stderrTime = stderrTime || RealDate.now()
stderrBuffer.push(data)
schedule()
callback()
Expand Down
6 changes: 0 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit aa239bf

Please sign in to comment.