xref: /aosp_15_r20/external/perfetto/ui/src/base/async_limiter_unittest.ts (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1// Copyright (C) 2024 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import {AsyncLimiter} from './async_limiter';
16
17test('no concurrent callbacks', async () => {
18  const limiter = new AsyncLimiter();
19
20  const mock1 = jest.fn();
21  limiter.schedule(async () => mock1());
22  expect(mock1).toHaveBeenCalled();
23
24  const mock2 = jest.fn();
25  limiter.schedule(async () => mock2());
26  expect(mock2).not.toHaveBeenCalled();
27});
28
29test('queueing', async () => {
30  const limiter = new AsyncLimiter();
31
32  const mock1 = jest.fn();
33  limiter.schedule(async () => mock1());
34
35  const mock2 = jest.fn();
36  await limiter.schedule(async () => mock2());
37
38  expect(mock1).toHaveBeenCalled();
39  expect(mock2).toHaveBeenCalled();
40});
41
42test('multiple queuing', async () => {
43  const limiter = new AsyncLimiter();
44
45  const mock1 = jest.fn();
46  limiter.schedule(async () => mock1());
47
48  const mock2 = jest.fn();
49  limiter.schedule(async () => mock2());
50
51  const mock3 = jest.fn();
52  await limiter.schedule(async () => mock3());
53
54  expect(mock1).toHaveBeenCalled();
55  expect(mock2).not.toHaveBeenCalled();
56  expect(mock3).toHaveBeenCalled();
57});
58
59test('error in callback bubbles up to caller', async () => {
60  const limiter = new AsyncLimiter();
61  const failingCallback = async () => {
62    throw Error();
63  };
64
65  expect(async () => await limiter.schedule(failingCallback)).rejects.toThrow();
66});
67
68test('chain continues even when one callback fails', async () => {
69  const limiter = new AsyncLimiter();
70
71  const failingCallback = async () => {
72    throw Error();
73  };
74  limiter.schedule(failingCallback).catch(() => {});
75
76  const mock = jest.fn();
77  await limiter.schedule(async () => mock());
78
79  expect(mock).toHaveBeenCalled();
80});
81