1/*
2 * Copyright (C) 2023 The Android Open Source Project
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
17import {Timestamp} from 'common/time';
18import {CoarseVersion} from './coarse_version';
19import {CustomQueryParserResultTypeMap, CustomQueryType} from './custom_query';
20import {AbsoluteEntryIndex, EntriesRange} from './index_types';
21import {Parser} from './parser';
22import {TraceType} from './trace_type';
23
24export class ParserMock<T> implements Parser<T> {
25  constructor(
26    private readonly type: TraceType,
27    private readonly timestamps: Timestamp[],
28    private readonly entries: T[],
29    private readonly customQueryResult: Map<CustomQueryType, object>,
30    private readonly descriptors: string[],
31    private readonly noOffsets: boolean,
32  ) {
33    if (timestamps.length !== entries.length) {
34      throw new Error(`Timestamps and entries must have the same length`);
35    }
36  }
37
38  getTraceType(): TraceType {
39    return this.type;
40  }
41
42  getLengthEntries(): number {
43    return this.entries.length;
44  }
45
46  getCoarseVersion(): CoarseVersion {
47    return CoarseVersion.MOCK;
48  }
49
50  createTimestamps() {
51    throw new Error('Not implemented');
52  }
53
54  getRealToMonotonicTimeOffsetNs(): bigint | undefined {
55    return this.noOffsets ? undefined : 0n;
56  }
57
58  getRealToBootTimeOffsetNs(): bigint | undefined {
59    return this.noOffsets ? undefined : 0n;
60  }
61
62  getTimestamps(): Timestamp[] {
63    return this.timestamps;
64  }
65
66  getEntry(index: AbsoluteEntryIndex): Promise<T> {
67    return Promise.resolve(this.entries[index]);
68  }
69
70  customQuery<Q extends CustomQueryType>(
71    type: Q,
72    entriesRange: EntriesRange,
73  ): Promise<CustomQueryParserResultTypeMap[Q]> {
74    let result = this.customQueryResult.get(type);
75    if (result === undefined) {
76      throw new Error(
77        `This mock was not configured to support custom query type '${type}'. Something missing in your test set up?`,
78      );
79    }
80    if (Array.isArray(result)) {
81      result = result.slice(entriesRange.start, entriesRange.end);
82    }
83    return Promise.resolve(result) as Promise<
84      CustomQueryParserResultTypeMap[Q]
85    >;
86  }
87
88  getDescriptors(): string[] {
89    return this.descriptors;
90  }
91}
92