File size: 4,687 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import type {
  ConfigFor,
  CurrentScenario,
  Interface,
  Scenario,
} from './index.js'
import compose from './interfaces/compose.js'
import { runScenarios } from './runner.js'

let currentScenarios: Scenario[] | null = null

export function setCurrentScenarios(scenarios: Scenario[] | null): void {
  currentScenarios = scenarios
}

export function describe<P>(
  name: string,
  config: ConfigFor<P>,
  fn: (props: P) => Promise<void>
): void {
  if (currentScenarios === null) {
    const scenarios = (currentScenarios = [])

    Promise.resolve().then(async () => {
      const ifaceNames = process.env.INTERFACE || 'interactive,console'
      const ifaces = []
      for (const ifaceName of ifaceNames.split(',').map((s) => s.trim())) {
        let iface: unknown
        try {
          iface = await import(`./interfaces/${ifaceName}.js`)
        } catch (e) {
          iface = await import(ifaceName)
        }
        iface = (iface && (iface as any).default) || iface
        if (typeof iface === 'function') {
          iface = await iface()
        }
        if (!iface) {
          throw new Error(`Interface ${ifaceName} is not a valid interface`)
        }
        ifaces.push(iface as Interface)
      }
      runScenarios(scenarios, compose(...ifaces))
    })
  }
  const normalizedConfig: Record<string, (string | number | boolean)[]> =
    Object.fromEntries(
      Object.entries(config).map(([key, value]) => [
        key,
        typeof value === 'boolean'
          ? [value, !value]
          : (value as (string | number | boolean)[]),
      ])
    )
  currentScenarios!.push({
    name,
    config: normalizedConfig,
    only: false,
    fn: fn as (
      props: Record<string, string | number | boolean>
    ) => Promise<void>,
  })
}

describe.only = function describeOnly<P>(
  name: string,
  config: ConfigFor<P>,
  fn: (props: P) => Promise<void>
): void {
  describe(name, config, fn)
  currentScenarios![currentScenarios!.length - 1].only = true
}

let currentScenario: CurrentScenario | null = null

export function withCurrent(
  current: CurrentScenario,
  fn: () => Promise<void>
): Promise<void> {
  const prev = currentScenario
  currentScenario = current
  return fn().finally(() => {
    currentScenario = prev
  })
}

export const PREVIOUS = Symbol('previous measurement with that unit')

export async function measureTime(
  name: string,
  options: {
    relativeTo?: string | typeof PREVIOUS
    scenario?: string
    props?: Record<string, string | number | null>
    offset?: number
  } = {}
) {
  const end = Date.now() - (options.offset || 0)
  await reportMeasurement(name, end, 'ms', {
    relativeTo: PREVIOUS,
    ...options,
  })
}

export async function reportMeasurement(
  name: string,
  value: number,
  unit: string,
  options: {
    relativeTo?: string | typeof PREVIOUS
    scenario?: string
    props?: Record<string, string | number | null>
  } = {}
) {
  if (!currentScenario) {
    throw new Error('reportMeasurement() must be called inside of describe()')
  }
  if (typeof name !== 'string') {
    throw new Error(
      'reportMeasurement() must be called with a name that is a string'
    )
  }
  if (typeof value !== 'number') {
    throw new Error(
      'reportMeasurement() must be called with a value that is a number'
    )
  }
  if (isNaN(value)) {
    throw new Error(
      'reportMeasurement() must be called with a value that is not NaN'
    )
  }
  if (!isFinite(value)) {
    throw new Error(
      'reportMeasurement() must be called with a value that is finite'
    )
  }
  if (typeof unit !== 'string') {
    throw new Error(
      'reportMeasurement() must be called with a unit that is a string'
    )
  }
  let { relativeTo, scenario, props } = options
  if (relativeTo === PREVIOUS) {
    relativeTo = 'previous'
    for (const [prevName, prev] of currentScenario.measurements) {
      if (prev.unit === unit) {
        relativeTo = prevName
      }
    }
  }
  currentScenario.measurements.set(name, {
    value,
    unit,
  })
  let reportedValue = value
  if (relativeTo) {
    const prev = currentScenario.measurements.get(relativeTo)
    if (!prev) {
      throw new Error(`No measurement named ${relativeTo} found`)
    }
    if (prev.unit !== unit) {
      throw new Error(
        `Measurement ${relativeTo} is not a "${unit}" measurement`
      )
    }
    reportedValue -= prev.value
  }
  await currentScenario.iface.measurement(
    scenario ?? currentScenario.scenario.scenario.name,
    props
      ? {
          ...currentScenario.scenario.props,
          ...props,
        }
      : currentScenario.scenario.props,
    name,
    reportedValue,
    unit,
    relativeTo
  )
}