@homebridge-plugins/homebridge-tuya 2.7.2-beta.5 → 2.7.2-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADVANCED_OPTIONS.md +73 -0
- package/CHANGELOG.md +9 -0
- package/SUPPORTED_DEVICES.md +1 -1
- package/config.schema.json +70 -0
- package/dist/accessory/AccessoryFactory.js +3 -0
- package/dist/accessory/AccessoryFactory.js.map +1 -1
- package/dist/accessory/BaseAccessory.js +2 -0
- package/dist/accessory/BaseAccessory.js.map +1 -1
- package/dist/accessory/ET72GWAccessory.js +182 -0
- package/dist/accessory/ET72GWAccessory.js.map +1 -0
- package/dist/accessory/GarageDoorAccessory.js +107 -4
- package/dist/accessory/GarageDoorAccessory.js.map +1 -1
- package/dist/accessory/LockAccessory.js +119 -0
- package/dist/accessory/LockAccessory.js.map +1 -1
- package/dist/config.js.map +1 -1
- package/dist/core/TuyaOpenAPI.js +129 -1
- package/dist/core/TuyaOpenAPI.js.map +1 -1
- package/dist/device/ET72GWMeasurements.js +305 -0
- package/dist/device/ET72GWMeasurements.js.map +1 -0
- package/dist/device/TuyaCustomDeviceManager.js +1 -1
- package/dist/device/TuyaCustomDeviceManager.js.map +1 -1
- package/dist/device/TuyaDeviceManager.js +4 -1
- package/dist/device/TuyaDeviceManager.js.map +1 -1
- package/dist/device/TuyaHomeDeviceManager.js +1 -1
- package/dist/device/TuyaHomeDeviceManager.js.map +1 -1
- package/dist/platform.js +6 -0
- package/dist/platform.js.map +1 -1
- package/package.json +1 -1
- package/test/accessory/et72gwAccessory.test.ts +489 -0
- package/test/accessory/timedState.test.ts +372 -0
- package/test/et72gw-floor-temperature.test.ts +248 -0
- package/test/et72gw-heating-state.test.ts +140 -0
- package/test/skipSchema.test.ts +54 -0
- package/test/tuya-shadow.test.ts +159 -0
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { jest } from '@jest/globals';
|
|
2
|
+
import { ET72GWMeasurements } from '../src/device/ET72GWMeasurements';
|
|
3
|
+
import { ShadowReadError } from '../src/core/TuyaOpenAPI';
|
|
4
|
+
|
|
5
|
+
const now = 1800000000000;
|
|
6
|
+
const options = { pollIntervalSeconds: 300, maxCacheAgeSeconds: 900, maxReportAgeSeconds: 0, maxHeatingReportAgeSeconds: 0 };
|
|
7
|
+
const payload = (active = true, powered = true, time = now - 240000) => ({ properties: [
|
|
8
|
+
{ code: 'FloorTemper', dpId: 106, value: 820, time },
|
|
9
|
+
{ code: 'TemperUnitChange', dpId: 107, value: true, time: time - 1000000 },
|
|
10
|
+
{ code: 'work_status', dpId: 118, value: active, time },
|
|
11
|
+
{ code: 'power1', dpId: 101, value: powered, time: time - 1000000 },
|
|
12
|
+
] });
|
|
13
|
+
|
|
14
|
+
describe('ET-72GW relay/power cache on the single shadow response', () => {
|
|
15
|
+
let adapter: ET72GWMeasurements;
|
|
16
|
+
let read: jest.Mock<() => Promise<unknown>>;
|
|
17
|
+
let changed: jest.Mock;
|
|
18
|
+
let online: boolean;
|
|
19
|
+
beforeEach(() => {
|
|
20
|
+
jest.useFakeTimers({ now }); online = true;
|
|
21
|
+
read = jest.fn<() => Promise<unknown>>().mockResolvedValue(payload()); changed = jest.fn();
|
|
22
|
+
adapter = new ET72GWMeasurements(read, options, changed, () => online);
|
|
23
|
+
});
|
|
24
|
+
afterEach(() => { adapter.stop(); jest.restoreAllMocks(); jest.useRealTimers(); });
|
|
25
|
+
test.each([[true,true,true],[false,true,false],[true,false,false],[false,false,false]])(
|
|
26
|
+
'relay=%s power=%s reports heating=%s', async (relay,power,expected) => {
|
|
27
|
+
read.mockResolvedValue(payload(relay,power)); await adapter.refresh();
|
|
28
|
+
expect(adapter.currentHeating()).toMatchObject({ heating: expected, relayActive: relay, powered: power, measuredAt: now - 240000 });
|
|
29
|
+
expect(adapter.currentFloor()?.celsius).toBeCloseTo(27.7778);
|
|
30
|
+
expect(read).toHaveBeenCalledTimes(1);
|
|
31
|
+
});
|
|
32
|
+
test('not available before a valid report or while offline', async () => {
|
|
33
|
+
expect(adapter.currentHeating()).toBeUndefined(); await adapter.refresh(); online = false;
|
|
34
|
+
expect(adapter.currentHeating()).toBeUndefined();
|
|
35
|
+
});
|
|
36
|
+
test.each([
|
|
37
|
+
['missing relay', (p: any[]) => p.filter(x => x.dpId!==118)],
|
|
38
|
+
['missing power', (p: any[]) => p.filter(x => x.dpId!==101)],
|
|
39
|
+
['string relay', (p: any[]) => p.map(x => x.dpId===118 ? {...x,value:'true'} : x)],
|
|
40
|
+
['numeric power', (p: any[]) => p.map(x => x.dpId===101 ? {...x,value:0} : x)],
|
|
41
|
+
['null relay', (p: any[]) => p.map(x => x.dpId===118 ? {...x,value:null} : x)],
|
|
42
|
+
['duplicate relay', (p: any[]) => [...p,p.find(x => x.dpId===118)]],
|
|
43
|
+
['wrong code', (p: any[]) => p.map(x => x.dpId===118 ? {...x,code:'other'} : x)],
|
|
44
|
+
['conflicting ID', (p: any[]) => p.map(x => x.dpId===118 ? {...x,dp_id:101} : x)],
|
|
45
|
+
['invalid time', (p: any[]) => p.map(x => x.dpId===118 ? {...x,time:0} : x)],
|
|
46
|
+
['future time', (p: any[]) => p.map(x => x.dpId===118 ? {...x,time:Date.now()+60001} : x)],
|
|
47
|
+
])('rejects %s without losing a valid floor measurement', async (_name, corrupt) => {
|
|
48
|
+
await adapter.refresh(); await jest.advanceTimersByTimeAsync(300000);
|
|
49
|
+
read.mockResolvedValue({properties:corrupt(payload().properties)}); await adapter.refresh();
|
|
50
|
+
expect(adapter.currentHeating()).toBeUndefined(); expect(adapter.currentFloor()).toBeDefined();
|
|
51
|
+
});
|
|
52
|
+
test('valid relay/power still available when floor data is missing', async () => {
|
|
53
|
+
read.mockResolvedValue({properties:payload().properties.filter(p=>p.dpId!==106)}); await adapter.refresh();
|
|
54
|
+
expect(adapter.currentFloor()).toBeUndefined(); expect(adapter.currentHeating()?.heating).toBe(true);
|
|
55
|
+
});
|
|
56
|
+
test('idle-active-idle transitions retain original timestamps and notify once per retrieval', async () => {
|
|
57
|
+
for (const [index,active] of [false,true,false].entries()) {
|
|
58
|
+
if (index) { await jest.advanceTimersByTimeAsync(300000); }
|
|
59
|
+
read.mockResolvedValue(payload(active,true,Date.now())); await adapter.refresh();
|
|
60
|
+
expect(adapter.currentHeating()?.heating).toBe(active);
|
|
61
|
+
expect(adapter.currentHeating()?.measuredAt).toBe(Date.now());
|
|
62
|
+
}
|
|
63
|
+
expect(read).toHaveBeenCalledTimes(3); expect(changed).toHaveBeenCalledTimes(3);
|
|
64
|
+
});
|
|
65
|
+
test('cache expires even if the last relay was active, with a notification', async () => {
|
|
66
|
+
await adapter.refresh(); await jest.advanceTimersByTimeAsync(900000);
|
|
67
|
+
expect(adapter.currentHeating()).toBeUndefined(); expect(changed).toHaveBeenCalledTimes(2);
|
|
68
|
+
});
|
|
69
|
+
test('unchanged old relay timestamp is permitted by default, but report-age policy can reject it', async () => {
|
|
70
|
+
read.mockResolvedValue(payload(false,true,now-86400000)); await adapter.refresh();
|
|
71
|
+
expect(adapter.currentHeating()?.heating).toBe(false);
|
|
72
|
+
adapter.stop();
|
|
73
|
+
adapter=new ET72GWMeasurements(read,{...options,maxHeatingReportAgeSeconds:600},changed,()=>online);
|
|
74
|
+
await adapter.refresh(); expect(adapter.currentHeating()).toBeUndefined(); expect(adapter.currentFloor()).toBeDefined();
|
|
75
|
+
});
|
|
76
|
+
test('strict relay age expires independently of floor and ignores old power-setting time', async () => {
|
|
77
|
+
adapter=new ET72GWMeasurements(read,{...options,maxHeatingReportAgeSeconds:300},changed,()=>online);
|
|
78
|
+
await adapter.refresh(); await jest.advanceTimersByTimeAsync(60000);
|
|
79
|
+
expect(adapter.currentHeating()).toBeUndefined(); expect(adapter.currentFloor()).toBeDefined();
|
|
80
|
+
expect(changed).toHaveBeenCalledTimes(2);
|
|
81
|
+
});
|
|
82
|
+
test.each([118,101])('rejects DP %s regression and conflicting values, preserving independent history',async id=>{
|
|
83
|
+
await adapter.refresh();
|
|
84
|
+
await jest.advanceTimersByTimeAsync(300000);
|
|
85
|
+
const older=payload().properties.map(p=>p.dpId===id?{...p,time:p.time-1}:p);
|
|
86
|
+
read.mockResolvedValue({properties:older});await adapter.refresh();expect(adapter.currentHeating()).toBeUndefined();
|
|
87
|
+
await jest.advanceTimersByTimeAsync(300000);
|
|
88
|
+
const conflict=payload().properties.map(p=>p.dpId===id?{...p,value:false}:p);
|
|
89
|
+
read.mockResolvedValue({properties:conflict});await adapter.refresh();expect(adapter.currentHeating()).toBeUndefined();
|
|
90
|
+
});
|
|
91
|
+
test('independent power/relay timestamps are valid; power off dominates and regressions remain invalid',async()=>{
|
|
92
|
+
const off=payload(true,false,now-1);off.properties=off.properties.map(p=>p.dpId===101?{...p,time:now}:p);
|
|
93
|
+
read.mockResolvedValue(off);await adapter.refresh();expect(adapter.currentHeating()?.heating).toBe(false);
|
|
94
|
+
await jest.advanceTimersByTimeAsync(300000);
|
|
95
|
+
const on=payload(true,true,now-1);on.properties=on.properties.map(p=>p.dpId===101?{...p,time:now+1}:p);
|
|
96
|
+
read.mockResolvedValue(on);await adapter.refresh();expect(adapter.currentHeating()?.heating).toBe(true);
|
|
97
|
+
await jest.advanceTimersByTimeAsync(300000);
|
|
98
|
+
read.mockResolvedValue(off);await adapter.refresh();expect(adapter.currentHeating()).toBeUndefined();
|
|
99
|
+
await jest.advanceTimersByTimeAsync(300000);
|
|
100
|
+
const consistent=payload(true,true,Date.now());consistent.properties=consistent.properties.map(p=>p.dpId===101?{...p,time:now+1}:p);
|
|
101
|
+
read.mockResolvedValue(consistent);await adapter.refresh();expect(adapter.currentHeating()?.heating).toBe(true);
|
|
102
|
+
});
|
|
103
|
+
test.each([true, false])('a newer true power timestamp does not invalidate unchanged relay=%s', async active => {
|
|
104
|
+
read.mockResolvedValue(payload(active)); await adapter.refresh();
|
|
105
|
+
const oldTime = adapter.currentHeating()!.measuredAt;
|
|
106
|
+
await jest.advanceTimersByTimeAsync(300000);
|
|
107
|
+
read.mockResolvedValue({ properties: payload(active).properties.map(p => p.dpId === 101 ? { ...p, time: Date.now() } : p) });
|
|
108
|
+
await adapter.refresh();
|
|
109
|
+
expect(adapter.currentHeating()).toMatchObject({ heating: active, measuredAt: oldTime, powerMeasuredAt: Date.now() });
|
|
110
|
+
expect(read).toHaveBeenCalledTimes(2);
|
|
111
|
+
await jest.advanceTimersByTimeAsync(900000);
|
|
112
|
+
expect(adapter.currentHeating()).toBeUndefined();
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test.each(['transport','authorization'] as const)('handles %s using the common lifecycle without extra requests',async kind=>{
|
|
116
|
+
await adapter.refresh();await jest.advanceTimersByTimeAsync(300000);
|
|
117
|
+
read.mockRejectedValue(new ShadowReadError(kind));await adapter.refresh();
|
|
118
|
+
expect(Boolean(adapter.currentHeating())).toBe(kind==='transport');
|
|
119
|
+
await jest.advanceTimersByTimeAsync(600000);expect(adapter.currentHeating()).toBeUndefined();
|
|
120
|
+
expect(read).toHaveBeenCalledTimes(2);
|
|
121
|
+
});
|
|
122
|
+
test('slightly early timer is rescheduled for the remaining cooldown instead of skipping a poll',async()=>{
|
|
123
|
+
const timer=jest.spyOn(global,'setTimeout');adapter.start();await jest.advanceTimersByTimeAsync(0);
|
|
124
|
+
const index=timer.mock.calls.findIndex(args=>args[1]===300000);
|
|
125
|
+
const callback=timer.mock.calls[index][0] as ()=>void;
|
|
126
|
+
clearTimeout(timer.mock.results[index].value as ReturnType<typeof setTimeout>);
|
|
127
|
+
await jest.advanceTimersByTimeAsync(299998);callback();await Promise.resolve();
|
|
128
|
+
expect(read).toHaveBeenCalledTimes(1);
|
|
129
|
+
await jest.advanceTimersByTimeAsync(2);expect(read).toHaveBeenCalledTimes(2);
|
|
130
|
+
await jest.advanceTimersByTimeAsync(300000);expect(read).toHaveBeenCalledTimes(3);
|
|
131
|
+
});
|
|
132
|
+
test('a delayed host timer runs one request, without catch-up or duplicate requests',async()=>{
|
|
133
|
+
const timer=jest.spyOn(global,'setTimeout');adapter.start();await jest.advanceTimersByTimeAsync(0);
|
|
134
|
+
const index=timer.mock.calls.findIndex(args=>args[1]===300000);
|
|
135
|
+
const callback=timer.mock.calls[index][0] as ()=>void;
|
|
136
|
+
clearTimeout(timer.mock.results[index].value as ReturnType<typeof setTimeout>);
|
|
137
|
+
await jest.advanceTimersByTimeAsync(1800000);callback();await jest.advanceTimersByTimeAsync(0);
|
|
138
|
+
expect(read).toHaveBeenCalledTimes(2);await adapter.refresh();expect(read).toHaveBeenCalledTimes(2);
|
|
139
|
+
});
|
|
140
|
+
});
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { describe, expect, test } from '@jest/globals';
|
|
2
|
+
|
|
3
|
+
import TuyaOpenAPI from '../src/core/TuyaOpenAPI';
|
|
4
|
+
import TuyaHomeDeviceManager from '../src/device/TuyaHomeDeviceManager';
|
|
5
|
+
|
|
6
|
+
// A stand-in for the Tuya cloud: two devices in one home, and a spec for each.
|
|
7
|
+
function fakeApi(calls: string[]) {
|
|
8
|
+
return {
|
|
9
|
+
get: async (path: string) => {
|
|
10
|
+
calls.push(path);
|
|
11
|
+
if (path === '/v1.0/homes/1/devices') {
|
|
12
|
+
return {
|
|
13
|
+
success: true,
|
|
14
|
+
result: [
|
|
15
|
+
{ id: 'light1', name: 'Light', category: 'dj', status: [] },
|
|
16
|
+
{ id: 'hub1', name: 'Zigbee Hub', category: 'wg2', status: [] },
|
|
17
|
+
],
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
if (path.endsWith('/specifications')) {
|
|
21
|
+
return {
|
|
22
|
+
success: true,
|
|
23
|
+
result: {
|
|
24
|
+
status: [{ code: 'switch_led', type: 'Boolean', values: '{}' }],
|
|
25
|
+
functions: [{ code: 'switch_led', type: 'Boolean', values: '{}' }],
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
return { success: false, code: 404, msg: 'unexpected' };
|
|
30
|
+
},
|
|
31
|
+
} as unknown as TuyaOpenAPI;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
describe('skipSchema', () => {
|
|
35
|
+
test('every device gets its specification by default', async () => {
|
|
36
|
+
const calls: string[] = [];
|
|
37
|
+
const manager = new TuyaHomeDeviceManager(fakeApi(calls));
|
|
38
|
+
const devices = await manager.updateDevices([1]);
|
|
39
|
+
expect(calls).toContain('/v1.0/devices/light1/specifications');
|
|
40
|
+
expect(calls).toContain('/v1.0/devices/hub1/specifications');
|
|
41
|
+
expect(devices.every(device => device.schema.length === 1)).toBe(true);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test('skipped devices are not looked up and get an empty schema', async () => {
|
|
45
|
+
const calls: string[] = [];
|
|
46
|
+
const manager = new TuyaHomeDeviceManager(fakeApi(calls));
|
|
47
|
+
manager.skipSchema = (device) => device.id === 'hub1';
|
|
48
|
+
const devices = await manager.updateDevices([1]);
|
|
49
|
+
expect(calls).toContain('/v1.0/devices/light1/specifications');
|
|
50
|
+
expect(calls).not.toContain('/v1.0/devices/hub1/specifications');
|
|
51
|
+
expect(devices.find(device => device.id === 'light1')!.schema).toHaveLength(1);
|
|
52
|
+
expect(devices.find(device => device.id === 'hub1')!.schema).toEqual([]);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { jest } from '@jest/globals';
|
|
2
|
+
import https from 'https';
|
|
3
|
+
import { EventEmitter } from 'events';
|
|
4
|
+
import TuyaOpenAPI, { ShadowReadError } from '../src/core/TuyaOpenAPI';
|
|
5
|
+
import { initLogger } from '../src/util/Logger';
|
|
6
|
+
|
|
7
|
+
// Every transport is intercepted before invoking the client. This suite cannot reach Tuya.
|
|
8
|
+
describe('bounded current-session shadow GET', () => {
|
|
9
|
+
let api: TuyaOpenAPI;
|
|
10
|
+
let request: any;
|
|
11
|
+
let req: any;
|
|
12
|
+
let res: any;
|
|
13
|
+
let reply: () => void;
|
|
14
|
+
const logs = { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() };
|
|
15
|
+
beforeEach(() => {
|
|
16
|
+
jest.useFakeTimers({ now: 1800000000000 });
|
|
17
|
+
initLogger(logs);
|
|
18
|
+
api = new TuyaOpenAPI(TuyaOpenAPI.Endpoints.AMERICA, 'dummy-client', 'dummy-secret', 'en', true);
|
|
19
|
+
api.tokenInfo = { access_token: 'dummy-token', refresh_token: 'dummy-refresh', uid: 'dummy-user', expire: Date.now() + 3600000 };
|
|
20
|
+
req = new EventEmitter(); req.destroy = jest.fn();
|
|
21
|
+
res = new EventEmitter(); res.statusCode = 200; res.headers = {}; res.destroy = jest.fn();
|
|
22
|
+
reply = () => { res.emit('data', Buffer.from(JSON.stringify({ success: true, result: { properties: [] } }))); res.emit('end'); };
|
|
23
|
+
request = jest.spyOn(https, 'request').mockImplementation(((_options: any, callback: any) => {
|
|
24
|
+
req.end = jest.fn(() => { callback(res); reply(); });
|
|
25
|
+
return req;
|
|
26
|
+
}) as any);
|
|
27
|
+
jest.spyOn(api, 'request').mockRejectedValue(new Error('Forbidden normal request'));
|
|
28
|
+
jest.spyOn(api, 'homeLogin').mockRejectedValue(new Error('Forbidden login'));
|
|
29
|
+
jest.spyOn(api, 'getToken').mockRejectedValue(new Error('Forbidden token'));
|
|
30
|
+
jest.spyOn(api, '_refreshAccessTokenIfNeed').mockRejectedValue(new Error('Forbidden refresh'));
|
|
31
|
+
Object.values(logs).forEach(log => log.mockClear());
|
|
32
|
+
});
|
|
33
|
+
afterEach(() => {
|
|
34
|
+
expect(api.request).not.toHaveBeenCalled();
|
|
35
|
+
expect(api.homeLogin).not.toHaveBeenCalled();
|
|
36
|
+
expect(api.getToken).not.toHaveBeenCalled();
|
|
37
|
+
expect(api._refreshAccessTokenIfNeed).not.toHaveBeenCalled();
|
|
38
|
+
Object.values(logs).forEach(log => expect(log).not.toHaveBeenCalled());
|
|
39
|
+
jest.restoreAllMocks(); jest.useRealTimers();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test.each(['Smart', 'Manual'] as const)('mode %s uses one bounded POST with no setpoint or reauthentication', async mode => {
|
|
43
|
+
await api.setDeviceControlMode('configured-device', mode);
|
|
44
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
45
|
+
expect(request.mock.calls[0][0]).toMatchObject({ method: 'POST', path: '/v2.0/cloud/thing/configured-device/shadow/properties/issue' });
|
|
46
|
+
expect(JSON.parse(req.end.mock.calls[0][0])).toEqual({ properties: JSON.stringify({ ControlMode: mode }) });
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test('mode command includes power-on only when explicitly needed', async () => {
|
|
50
|
+
await api.setDeviceControlMode('configured-device', 'Manual', true);
|
|
51
|
+
expect(JSON.parse(req.end.mock.calls[0][0])).toEqual({ properties: JSON.stringify({ ControlMode: 'Manual', power1: true }) });
|
|
52
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('invalid mode cannot reach the network', async () => {
|
|
56
|
+
await expect(api.setDeviceControlMode('configured-device', 'Anti_frozen' as any)).rejects.toMatchObject({ kind: 'response' });
|
|
57
|
+
expect(request).not.toHaveBeenCalled();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('mode POST times out once without retry or login', async () => {
|
|
61
|
+
reply = () => {};
|
|
62
|
+
const pending = expect(api.setDeviceControlMode('configured-device', 'Manual')).rejects.toMatchObject({ kind: 'transport' });
|
|
63
|
+
await jest.advanceTimersByTimeAsync(10000); await pending;
|
|
64
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test('mode POST authorization failure is not retried', async () => {
|
|
68
|
+
res.statusCode = 403;
|
|
69
|
+
await expect(api.setDeviceControlMode('configured-device', 'Manual')).rejects.toMatchObject({ kind: 'authorization' });
|
|
70
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test('signs exactly one GET for the selected device with the existing token', async () => {
|
|
74
|
+
await expect(api.getDeviceShadow('configured-device')).resolves.toEqual({ properties: [] });
|
|
75
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
76
|
+
const options = request.mock.calls[0][0];
|
|
77
|
+
expect(options).toMatchObject({ method: 'GET', path: '/v2.0/cloud/thing/configured-device/shadow/properties', hostname: 'openapi.tuyaus.com' });
|
|
78
|
+
const { sign, ...headers } = options.headers;
|
|
79
|
+
expect(sign).toMatch(/^[A-F0-9]{64}$/);
|
|
80
|
+
expect(headers.access_token).toBe('dummy-token');
|
|
81
|
+
expect(api.tokenInfo.refresh_token).toBe('dummy-refresh');
|
|
82
|
+
expect(jest.getTimerCount()).toBe(0);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test.each(['missing', 'expired', 'near-expiry'])('rejects a %s token without any network', async mode => {
|
|
86
|
+
if (mode === 'missing') { api.tokenInfo.access_token = ''; }
|
|
87
|
+
else { api.tokenInfo.expire = Date.now() + (mode === 'expired' ? -1 : 60000); }
|
|
88
|
+
await expect(api.getDeviceShadow('configured-device')).rejects.toMatchObject({ kind: 'session' });
|
|
89
|
+
expect(request).not.toHaveBeenCalled();
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test('rejects path injection before network', async () => {
|
|
93
|
+
await expect(api.getDeviceShadow('../token')).rejects.toBeInstanceOf(ShadowReadError);
|
|
94
|
+
expect(request).not.toHaveBeenCalled();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test.each([401, 403])('treats HTTP %s as authorization failure', async code => {
|
|
98
|
+
res.statusCode = code;
|
|
99
|
+
await expect(api.getDeviceShadow('configured-device')).rejects.toMatchObject({ kind: 'authorization' });
|
|
100
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('handles response errors during rejected-status teardown without losing the authorization result', async () => {
|
|
104
|
+
res.statusCode = 403;
|
|
105
|
+
res.destroy = jest.fn(() => res.emit('error', new Error('private response details')));
|
|
106
|
+
await expect(api.getDeviceShadow('configured-device')).rejects.toMatchObject({ kind: 'authorization' });
|
|
107
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test.each([1004, 1010, 1100, '1106', 1114, 28841101, 28841002])('treats Tuya %s as authorization failure', async code => {
|
|
111
|
+
reply = () => { res.emit('data', Buffer.from(JSON.stringify({ success: false, code }))); res.emit('end'); };
|
|
112
|
+
await expect(api.getDeviceShadow('configured-device')).rejects.toMatchObject({ kind: 'authorization' });
|
|
113
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
test.each([302, 500])('does not follow or retry HTTP %s', async code => {
|
|
117
|
+
res.statusCode = code; res.headers.location = 'https://example.invalid';
|
|
118
|
+
await expect(api.getDeviceShadow('configured-device')).rejects.toMatchObject({ kind: 'response' });
|
|
119
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test.each(['1200', 'garbage', '99999999999999999999999', new Date(1800000000000 + 1200000).toUTCString()])(
|
|
123
|
+
'bounds Retry-After %s', async retry => {
|
|
124
|
+
res.statusCode = 429; res.headers['retry-after'] = retry;
|
|
125
|
+
await expect(api.getDeviceShadow('configured-device')).rejects.toMatchObject({
|
|
126
|
+
kind: 'rate-limit', retryAfterSeconds: retry === 'garbage' ? 0 : retry.startsWith('999') ? 86400 : 1200,
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test.each(['malformed', 'oversized', 'api-error'])('rejects %s payload without retries', async mode => {
|
|
131
|
+
reply = () => {
|
|
132
|
+
res.emit('data', Buffer.from(mode === 'oversized' ? 'x'.repeat(262145) : mode === 'malformed' ? '{' : '{"success":false,"code":999}'));
|
|
133
|
+
res.emit('end');
|
|
134
|
+
};
|
|
135
|
+
await expect(api.getDeviceShadow('configured-device')).rejects.toMatchObject({ kind: 'response' });
|
|
136
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test('total deadline terminates a silent request at ten seconds, without a retry', async () => {
|
|
140
|
+
reply = () => {};
|
|
141
|
+
const pending = expect(api.getDeviceShadow('configured-device')).rejects.toMatchObject({ kind: 'transport' });
|
|
142
|
+
await jest.advanceTimersByTimeAsync(9999);
|
|
143
|
+
expect(req.destroy).not.toHaveBeenCalled();
|
|
144
|
+
await jest.advanceTimersByTimeAsync(1);
|
|
145
|
+
await pending;
|
|
146
|
+
expect(req.destroy).toHaveBeenCalledTimes(1);
|
|
147
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
148
|
+
expect(jest.getTimerCount()).toBe(0);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test.each(['request-error', 'response-error', 'aborted'])('sanitizes %s and does not retry', async mode => {
|
|
152
|
+
reply = () => {
|
|
153
|
+
if (mode === 'request-error') { req.emit('error', new Error('sensitive transport details')); }
|
|
154
|
+
else { res.emit(mode === 'aborted' ? 'aborted' : 'error', new Error('sensitive response details')); }
|
|
155
|
+
};
|
|
156
|
+
await expect(api.getDeviceShadow('configured-device')).rejects.toMatchObject({ message: 'Shadow read failed: transport' });
|
|
157
|
+
expect(request).toHaveBeenCalledTimes(1);
|
|
158
|
+
});
|
|
159
|
+
});
|