-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluetooth.service.spec.ts
294 lines (235 loc) · 9.48 KB
/
bluetooth.service.spec.ts
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
const mockExec = jest.fn();
const mockNoble = {
state: 'poweredOn',
on: jest.fn(),
startScanningAsync: jest.fn(),
stopScanning: jest.fn(),
};
jest.mock(
'@abandonware/noble',
() => {
return mockNoble;
},
{ virtual: true }
);
import { Test, TestingModule } from '@nestjs/testing';
import { BluetoothService } from './bluetooth.service';
import { ConfigModule } from '../../config/config.module';
import { BluetoothHealthIndicator } from './bluetooth.health';
jest.mock('util', () => ({
...jest.requireActual('util'),
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
promisify: () => mockExec,
}));
jest.useFakeTimers();
describe('BluetoothService', () => {
let service: BluetoothService;
const healthIndicator = {
reportError: jest.fn(),
reportSuccess: jest.fn(),
};
beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
imports: [ConfigModule],
providers: [BluetoothService, BluetoothHealthIndicator],
})
.overrideProvider(BluetoothHealthIndicator)
.useValue(healthIndicator)
.compile();
service = module.get<BluetoothService>(BluetoothService);
});
describe('Bluetooth Classic', () => {
it('should return measured RSSI value from command output', async () => {
mockExec.mockResolvedValue({ stdout: 'RSSI return value: -4' });
const address = '77:50:fb:4d:ab:70';
expect(await service.inquireClassicRssi(1, address)).toBe(-4);
expect(mockExec).toHaveBeenCalledWith(
`hcitool -i hci1 cc \"${address}\" && hcitool -i hci1 rssi \"${address}\"`,
expect.anything()
);
});
it('should return undefined if no RSSI could be determined', async () => {
mockExec.mockResolvedValue({
stdout: "Can't create connection: Input/output error",
stderr: 'Not connected.',
});
expect(
await service.inquireClassicRssi(0, '08:05:90:ed:3b:60')
).toBeUndefined();
});
it('should return undefined if the command failed', async () => {
mockExec.mockRejectedValue({ message: 'Command failed' });
expect(
await service.inquireClassicRssi(0, '08:05:90:ed:3b:60')
).toBeUndefined();
});
it('should throw an exception if an inquiry is requested for a locked adapter', async () => {
await service.lockAdapter(1);
await expect(
service.inquireClassicRssi(1, '77:50:fb:4d:ab:71')
).rejects.toThrow();
});
it('should reset the HCI device if the query took too long', async () => {
mockExec.mockRejectedValue({ signal: 'SIGKILL' });
const result = await service.inquireClassicRssi(1, '08:05:90:ed:3b:60');
expect(result).toBeUndefined();
expect(mockExec).toHaveBeenCalledWith('hciconfig hci1 reset');
});
it('should stop scanning on an adapter while performing an inquiry', async () => {
service.onLowEnergyDiscovery(() => undefined);
const stateChangeHandler = mockNoble.on.mock.calls[0][1];
await stateChangeHandler('poweredOn');
expect(mockNoble.startScanningAsync).toHaveBeenCalledTimes(1);
let execResolve;
const execPromise = new Promise((r) => (execResolve = r));
mockExec.mockReturnValue(execPromise);
const inquirePromise = service.inquireClassicRssi(0, 'x').then(() => {
expect(mockNoble.startScanningAsync).toHaveBeenCalledTimes(2);
});
expect(mockNoble.stopScanning).toHaveBeenCalledTimes(1);
execResolve({ stdout: '-1' });
return inquirePromise;
});
it('should start scanning again even after encountering an exception', async () => {
service.onLowEnergyDiscovery(() => undefined);
const stateChangeHandler = mockNoble.on.mock.calls[0][1];
stateChangeHandler('poweredOn');
mockExec.mockRejectedValue({ stderr: 'error' });
await service.inquireClassicRssi(0, 'x');
expect(mockNoble.startScanningAsync).toHaveBeenCalledTimes(2);
});
it('should stop scanning on an adapter while getting Classic device info', async () => {
service.onLowEnergyDiscovery(() => undefined);
const stateChangeHandler = mockNoble.on.mock.calls[0][1];
await stateChangeHandler('poweredOn');
expect(mockNoble.startScanningAsync).toHaveBeenCalledTimes(1);
let execResolve;
const execPromise = new Promise((r) => (execResolve = r));
mockExec.mockReturnValue(execPromise);
const inquirePromise = service
.inquireClassicDeviceInfo(0, 'x')
.then(() => {
expect(mockNoble.startScanningAsync).toHaveBeenCalledTimes(2);
});
expect(mockNoble.stopScanning).toHaveBeenCalledTimes(1);
execResolve({ stdout: '' });
return inquirePromise;
});
it('should return device information based on parsed output', async () => {
mockExec.mockResolvedValue({
stdout: `
Requesting information ...
\tBD Address: F0:99:B6:12:34:AB
\tOUI Company: Apple, Inc. (F0-99-B6)
\tDevice Name: Test iPhone
\tLMP Version: 5.0 (0x9) LMP Subversion: 0x4307
\tManufacturer: Broadcom Corporation (15)
\tFeatures page 0:
\tFeatures page 1:
\tFeatures page 2:
`,
});
expect(
await service.inquireClassicDeviceInfo(0, 'F0:99:B6:12:34:AB')
).toStrictEqual({
address: 'F0:99:B6:12:34:AB',
name: 'Test iPhone',
manufacturer: 'Apple, Inc.',
});
});
it('should return the address as device name if none was found', async () => {
mockExec.mockResolvedValue({
stdout: 'IO error',
});
expect(
await service.inquireClassicDeviceInfo(0, 'F0:99:B6:12:34:AB')
).toStrictEqual({
address: 'F0:99:B6:12:34:AB',
name: 'F0:99:B6:12:34:AB',
manufacturer: undefined,
});
});
it('should return barebones information if request fails', async () => {
mockExec.mockRejectedValue({ stderr: 'I/O Error' });
expect(
await service.inquireClassicDeviceInfo(0, 'F0:99:B6:12:34:CD')
).toStrictEqual({
address: 'F0:99:B6:12:34:CD',
name: 'F0:99:B6:12:34:CD',
});
});
it('should report success to the health indicator when queries are successful', async () => {
mockExec.mockResolvedValue({ stdout: 'RSSI return value: -4' });
await service.inquireClassicRssi(0, '');
expect(healthIndicator.reportSuccess).toHaveBeenCalledTimes(1);
});
it('should report an error to the health indicator when queries are unsuccessful', async () => {
mockExec.mockRejectedValue({ message: 'critical error' });
await service.inquireClassicRssi(0, '');
expect(healthIndicator.reportError).toHaveBeenCalledTimes(1);
});
it('should not report anything to the health indicator if the device was not reachable', async () => {
mockExec.mockRejectedValue({
message: 'Could not connect: Input/output error',
});
await service.inquireClassicRssi(0, '');
expect(healthIndicator.reportSuccess).not.toHaveBeenCalled();
expect(healthIndicator.reportError).not.toHaveBeenCalled();
});
it('should not report an error if the scan was stopped due to low time limits', async () => {
mockExec.mockRejectedValue({
message: 'killed',
signal: 'SIGKILL',
});
await service.inquireClassicRssi(0, '');
expect(healthIndicator.reportError).not.toHaveBeenCalled();
});
});
describe('Bluetooth Low Energy', () => {
it('should setup noble listeners on the first subscriber', () => {
const callback = () => undefined;
service.onLowEnergyDiscovery(callback);
expect(mockNoble.on).toHaveBeenCalledWith(
'stateChange',
expect.any(Function)
);
expect(mockNoble.on).toHaveBeenCalledWith('discover', callback);
});
it('should only setup noble listeners once', () => {
service.onLowEnergyDiscovery(() => undefined);
service.onLowEnergyDiscovery(() => undefined);
expect(mockNoble.on).toHaveBeenCalledTimes(4);
});
it('should enable scanning when the adapter is inactive', () => {
service.onLowEnergyDiscovery(() => undefined);
const stateChangeHandler = mockNoble.on.mock.calls[0][1];
stateChangeHandler('poweredOn');
expect(mockNoble.startScanningAsync).toHaveBeenCalledTimes(1);
});
it('should not enable scanning when the adapter is performing a Classic inquiry', () => {
service.onLowEnergyDiscovery(() => undefined);
const stateChangeHandler = mockNoble.on.mock.calls[0][1];
let execResolve;
const execPromise = new Promise((r) => (execResolve = r));
mockExec.mockReturnValue(execPromise);
const inquirePromise = service.inquireClassicRssi(0, 'x').then(() => {
expect(mockNoble.startScanningAsync).toHaveBeenCalledTimes(1);
});
stateChangeHandler('poweredOn');
expect(mockNoble.startScanningAsync).not.toHaveBeenCalled();
execResolve({ stdout: '-1' });
return inquirePromise;
});
it('should continue scanning if Classic inquiries are performed on another adapter', async () => {
service.onLowEnergyDiscovery(() => undefined);
const stateChangeHandler = mockNoble.on.mock.calls[0][1];
stateChangeHandler('poweredOn');
const execPromise = Promise.resolve({ stdout: '-1' });
mockExec.mockReturnValue(execPromise);
await service.inquireClassicRssi(1, 'x');
expect(mockNoble.startScanningAsync).toHaveBeenCalledTimes(1);
expect(mockNoble.stopScanning).not.toHaveBeenCalled();
});
});
});