From 16de485dbe76aa4db774b2cce468d26326dbb2e9 Mon Sep 17 00:00:00 2001 From: Ben Francis Date: Thu, 26 Nov 2026 12:35:50 +0000 Subject: [PATCH] Implement DataSchema - closes #37 --- package-lock.json | 73 ++++++++++++++++++++++++++------ package.json | 1 + src/action-affordance.js | 63 ++++++++++++++++++++++----- src/data-schema.js | 51 ++++++++++++++++++++++ src/property-affordance.js | 44 +++++++++++++++---- src/thing.js | 5 ++- src/types.js | 38 ++++++++--------- test/action-affordance.test.js | 43 +++++++++++++++++++ test/data-schema.test.js | 42 ++++++++++++++++++ test/property-affordance.test.js | 21 +++++++++ test/thing.test.js | 8 ++++ 11 files changed, 337 insertions(+), 52 deletions(-) create mode 100644 src/data-schema.js create mode 100644 test/data-schema.test.js diff --git a/package-lock.json b/package-lock.json index 24a24d5..02cc3e7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "0.1.0", "license": "MPL-2.0", "dependencies": { + "ajv": "^8.20.0", "express": "^5.1.0" }, "devDependencies": { @@ -358,16 +359,15 @@ } }, "node_modules/ajv": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", - "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", - "dev": true, + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", "license": "MIT", "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" }, "funding": { "type": "github", @@ -728,6 +728,30 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/eslint/node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/eslint/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, "node_modules/espree": { "version": "11.2.0", "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz", @@ -847,7 +871,6 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, "license": "MIT" }, "node_modules/fast-json-stable-stringify": { @@ -864,6 +887,22 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/file-entry-cache": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", @@ -1178,10 +1217,9 @@ "license": "MIT" }, "node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "license": "MIT" }, "node_modules/json-stable-stringify-without-jsonify": { @@ -1546,6 +1584,15 @@ "url": "https://opencollective.com/express" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/router": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", diff --git a/package.json b/package.json index 29f4857..620e25d 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ }, "homepage": "https://github.com/benfrancis/webthing-node-2#readme", "dependencies": { + "ajv": "^8.20.0", "express": "^5.1.0" }, "devDependencies": { diff --git a/src/action-affordance.js b/src/action-affordance.js index d796c87..4246026 100644 --- a/src/action-affordance.js +++ b/src/action-affordance.js @@ -1,8 +1,9 @@ import InteractionAffordance from './interaction-affordance.js'; import ValidationError from './validation-error.js'; import { randomUUID } from 'node:crypto'; +import DataSchema from './data-schema.js'; -/** @import {DataSchema, PartialActionDescription, ActionDescription, Form, +/** @import {DataSchemaDescription, PartialActionDescription, ActionDescription, Form, * ActionStatus} from "./types.js" */ @@ -16,12 +17,12 @@ import { randomUUID } from 'node:crypto'; */ class ActionAffordance extends InteractionAffordance { /** - * @type {DataSchema|undefined} + * @type {DataSchemaDescription|undefined} */ input; /** - * @type {DataSchema|undefined} + * @type {DataSchemaDescription|undefined} */ output; @@ -50,6 +51,16 @@ class ActionAffordance extends InteractionAffordance { */ #actionRequests = new Map(); + /** + * @type {DataSchema} + */ + inputSchema; + + /** + * @type {DataSchema} + */ + outputSchema; + /** * Create a new Action. * @@ -101,12 +112,18 @@ class ActionAffordance extends InteractionAffordance { if (validationError.validationErrors.length > 0) { throw validationError; } + + this.inputSchema = new DataSchema(this.input, `actions.${this.name}.input`); + this.outputSchema = new DataSchema( + this.output, + `actions.${this.name}.output`, + ); } /** * Parse input member. * - * @param {DataSchema|undefined} input + * @param {DataSchemaDescription|undefined} input */ #parseInputMember(input) { if (!(input === undefined || typeof input === 'object')) { @@ -117,13 +134,12 @@ class ActionAffordance extends InteractionAffordance { }, ]); } - // TODO: Validate DataSchema this.input = input; } /** * Parse output member. - * @param {DataSchema|undefined} output + * @param {DataSchemaDescription|undefined} output */ #parseOutputMember(output) { if (!(output === undefined || typeof output === 'object')) { @@ -134,7 +150,6 @@ class ActionAffordance extends InteractionAffordance { }, ]); } - // TODO: Validate DataSchema this.output = output; } @@ -224,15 +239,40 @@ class ActionAffordance extends InteractionAffordance { * schema. * @returns {Promise} A Promise which resolves with the output of the * action (if any), conforming to the output data schema. + * @throws {Error} Throws InternalError if handler is missing. * */ async invoke(input) { - // TODO: Validate input against data schema if (!this.invokeHandler) { console.error(`No invoke handler set for action ${this.name}`); throw new Error('InternalError'); } - return this.invokeHandler(input); + this.#validateInput(input); + const output = await this.invokeHandler(input); + this.#validateOutput(output); + return output; + } + + /** + * @param {any} input + * @throws {Error} Throws BadRequest on invalid input. + */ + #validateInput(input) { + if (!this.inputSchema.validate(input)) { + console.error(`Tried to invoke action ${this.name} with invalid input`); + throw new Error('BadRequest'); + } + } + + /** + * @param {any} output + * @throws {Error} Throws InternalError on invalid output. + */ + #validateOutput(output) { + if (!this.outputSchema.validate(output)) { + console.error(`Action ${this.name} returned invalid output`); + throw new Error('InternalError'); + } } /** @@ -240,8 +280,10 @@ class ActionAffordance extends InteractionAffordance { * * @param {any} input The action input. * @returns {ActionStatus & {href: string}} The initial status of the action request. + * @throws {Error} Throws InternalError if handler is missing. */ invokeAsync(input) { + this.#validateInput(input); if (!this.invokeHandler) { console.error(`No invoke handler set for action ${this.name}`); throw new Error('InternalError'); @@ -269,6 +311,7 @@ class ActionAffordance extends InteractionAffordance { input, request.controller.signal, ); + this.#validateOutput(output); if (this.#actionRequests.get(actionID) !== request) { return; } @@ -325,7 +368,7 @@ class ActionAffordance extends InteractionAffordance { * @throws {Error} Throws NotFoundError if the request does not exist, * or ConflictError if it has already completed or failed. */ - cancelAction(actionID) { + cancel(actionID) { const request = this.#actionRequests.get(actionID); if (!request) { throw new Error('NotFoundError'); diff --git a/src/data-schema.js b/src/data-schema.js new file mode 100644 index 0000000..1046ea8 --- /dev/null +++ b/src/data-schema.js @@ -0,0 +1,51 @@ +import { Ajv } from 'ajv'; +import ValidationError from './validation-error.js'; + +/** + * Data Schema + * + * Represents a DataSchema from the WoT Thing Description 1.1 specification. + * https://www.w3.org/TR/wot-thing-description/#dataschema + */ +class DataSchema { + /** + * @type {import('ajv').ValidateFunction|undefined} + */ + #validator; + + /** + * @param {object|undefined} schema A raw data schema from a + * Thing Description. + * @param {string|undefined} [field] The Thing Description field the schema + * came from, following the dot-separated format from validationErrors in WoT Discovery. + */ + constructor(schema, field = undefined) { + if (schema === undefined) { + return; + } + + try { + const ajv = new Ajv({ allErrors: true, strict: false }); + this.#validator = ajv.compile(schema); + } catch (error) { + throw new ValidationError([ + { + field, + description: `Invalid data schema${error instanceof Error ? `: ${error.message}` : ''}`, + }, + ]); + } + } + + /** + * Check whether a value conforms to this data schema. + * + * @param {any} value + * @returns {boolean} + */ + validate(value) { + return this.#validator ? this.#validator(value) : true; + } +} + +export default DataSchema; diff --git a/src/property-affordance.js b/src/property-affordance.js index 1049751..c68cb3e 100644 --- a/src/property-affordance.js +++ b/src/property-affordance.js @@ -1,7 +1,8 @@ import InteractionAffordance from './interaction-affordance.js'; import ValidationError from './validation-error.js'; +import DataSchema from './data-schema.js'; -/** @import {DataSchema, PartialPropertyDescription, PropertyDescription, Form} from "./types.js" */ +/** @import {DataSchemaDescription, PartialPropertyDescription, PropertyDescription, Form} from "./types.js" */ /** * Property Affordance @@ -10,9 +11,7 @@ import ValidationError from './validation-error.js'; * specification https://www.w3.org/TR/wot-thing-description/#propertyaffordance */ class PropertyAffordance extends InteractionAffordance { - // *** DataSchema ***/ - // TODO: Consider making this a mixin or use @implements InteractionAffordance - // and @implements DataSchema + /* Start of property data schema */ /** * @type {any} @@ -30,7 +29,7 @@ class PropertyAffordance extends InteractionAffordance { unit; /** - * @type {Array|undefined} + * @type {Array|undefined} */ oneOf; @@ -59,13 +58,18 @@ class PropertyAffordance extends InteractionAffordance { */ type; - // *** End of DataSchema *** + /* End of property data schema */ /** * @type {boolean|undefined} */ observeable; + /** + * @type {DataSchema} + */ + valueSchema; + /** * Create a new Property. * @@ -116,6 +120,10 @@ class PropertyAffordance extends InteractionAffordance { if (validationError.validationErrors.length > 0) { throw validationError; } + + // Note that metadata contains other property metadata alongside + // the data schema, but the data schema validation will ignore it. + this.valueSchema = new DataSchema(metadata, `properties.${this.name}`); } /** @@ -227,14 +235,34 @@ class PropertyAffordance extends InteractionAffordance { this.writeHandler = handler; } + /** + * Validate a value against the data schema before writing it. + * + * @param {any} value + * @throws {Error} Throws BadRequest if value is invalid. + */ + validateWrite(value) { + if (!this.valueSchema.validate(value)) { + console.error(`Tried to write invalid value for property ${this.name}`); + throw new Error('BadRequest'); + } + } + /** * Read the property. * * @returns {Promise} The current value of the property. + * @throws {Error} Throws InternalError for invalid value or missing handler. */ async read() { if (this.readHandler) { - return this.readHandler(); + const value = await this.readHandler(); + // Validate the read value against the data schema + if (!this.valueSchema.validate(value)) { + console.error(`Read invalid value for property ${this.name}`); + throw new Error('InternalError'); + } + return value; } else { console.error(`No read handler set for property ${this.name}`); throw new Error('InternalError'); @@ -248,8 +276,8 @@ class PropertyAffordance extends InteractionAffordance { * @returns {Promise} A Promise. */ async write(value) { - // TODO: Validate value against data schema if (this.writeHandler) { + this.validateWrite(value); return this.writeHandler(value); } else { console.error(`No write handler set for property ${this.name}`); diff --git a/src/thing.js b/src/thing.js index b30d603..cf3690f 100644 --- a/src/thing.js +++ b/src/thing.js @@ -480,7 +480,7 @@ class Thing { } const entries = Object.entries(values); - for (const [name] of entries) { + for (const [name, value] of entries) { const property = this.properties.get(name); if (!property) { console.error(`No property called ${name} could be found`); @@ -489,6 +489,7 @@ class Thing { if (property.readOnly === true) { throw new Error('BadRequest'); } + property.validateWrite(value); } for (const [name, value] of entries) { @@ -559,7 +560,7 @@ class Thing { if (!action) { throw new Error('NotFoundError'); } - action.cancelAction(actionID); + action.cancel(actionID); } /** diff --git a/src/types.js b/src/types.js index 6457562..bdde562 100644 --- a/src/types.js +++ b/src/types.js @@ -29,7 +29,7 @@ */ /** - * Data Schema + * Data Schema Description * * @typedef {{ * '@type'?: string|Array, @@ -42,16 +42,16 @@ * unit?: string, * minimum?: number, * maximum?: number, - * properties?: Record, + * properties?: Record, * required?: Array, - * items?: DataSchema, - * oneOf?: Array, + * items?: DataSchemaDescription, + * oneOf?: Array, * enum?: Array, * readOnly?: boolean, * writeOnly?: boolean, * format?: string, * type?: 'object'|'array'|'string'|'number'|'integer'|'boolean'|'null' - * }} DataSchema + * }} DataSchemaDescription */ /** @@ -82,7 +82,7 @@ /** * Property Description * - * @typedef {InteractionDescription & DataSchema & { + * @typedef {InteractionDescription & DataSchemaDescription & { * forms: Array
, * observeable?: boolean|undefined * }} PropertyDescription @@ -93,7 +93,7 @@ * * Same as PropertyDescription but forms is optional * - * @typedef {InteractionDescription & DataSchema & { + * @typedef {InteractionDescription & DataSchemaDescription & { * forms?: Array, * observeable?: boolean|undefined * }} PartialPropertyDescription @@ -104,8 +104,8 @@ * * @typedef { InteractionDescription & { * forms: Array, - * input?: DataSchema, - * output?: DataSchema, + * input?: DataSchemaDescription, + * output?: DataSchemaDescription, * safe?: boolean, * idempotent?: boolean, * synchronous?: boolean, @@ -119,8 +119,8 @@ * * @typedef { InteractionDescription & { * forms?: Array, - * input?: DataSchema, - * output?: DataSchema, + * input?: DataSchemaDescription, + * output?: DataSchemaDescription, * safe?: boolean, * idempotent?: boolean, * synchronous?: boolean, @@ -132,10 +132,10 @@ * * @typedef {InteractionDescription & { * forms: Array, - * subscription?: DataSchema, - * data?: DataSchema, - * dataResponse?: DataSchema, - * cancellation?: DataSchema, + * subscription?: DataSchemaDescription, + * data?: DataSchemaDescription, + * dataResponse?: DataSchemaDescription, + * cancellation?: DataSchemaDescription, * }} EventDescription */ @@ -144,10 +144,10 @@ * * @typedef {InteractionDescription & { * forms?: Array, - * subscription?: DataSchema, - * data?: DataSchema, - * dataResponse?: DataSchema, - * cancellation?: DataSchema, + * subscription?: DataSchemaDescription, + * data?: DataSchemaDescription, + * dataResponse?: DataSchemaDescription, + * cancellation?: DataSchemaDescription, * }} PartialEventDescription */ diff --git a/test/action-affordance.test.js b/test/action-affordance.test.js index 99c5c20..ccc0ab3 100644 --- a/test/action-affordance.test.js +++ b/test/action-affordance.test.js @@ -1,6 +1,7 @@ import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import ActionAffordance from '../src/action-affordance.js'; +import DataSchema from '../src/data-schema.js'; import ValidationError from '../src/validation-error.js'; describe('ActionAffordance', () => { @@ -20,6 +21,10 @@ describe('ActionAffordance', () => { assert.equal(action.title, 'Toggle'); assert.deepEqual(action.input, { type: 'boolean' }); assert.deepEqual(action.output, { type: 'boolean' }); + assert.ok(action.inputSchema instanceof DataSchema); + assert.ok(action.outputSchema instanceof DataSchema); + assert.equal(action.inputSchema.validate(true), true); + assert.equal(action.outputSchema.validate(false), true); assert.equal(action.safe, true); assert.equal(action.idempotent, true); assert.equal(action.synchronous, false); @@ -31,6 +36,8 @@ describe('ActionAffordance', () => { assert.equal(action.safe, false); assert.equal(action.idempotent, false); assert.equal(action.synchronous, undefined); + assert.ok(action.inputSchema instanceof DataSchema); + assert.ok(action.outputSchema instanceof DataSchema); }); it('should reject invalid member types', () => { @@ -97,6 +104,42 @@ describe('ActionAffordance', () => { assert.deepEqual(result, { value: 'red' }); }); + it('should validate action input and output against their schemas', async () => { + const action = new ActionAffordance('setLevel', { + input: { + type: 'object', + properties: { level: { type: 'integer', minimum: 0 } }, + required: ['level'], + }, + output: { type: 'string', enum: ['ok', 'failed'] }, + }); + let invoked = false; + action.setInvokeHandler(async () => { + invoked = true; + return 'unexpected'; + }); + + await assert.rejects(() => action.invoke({}), /BadRequest/); + assert.equal(invoked, false); + await assert.rejects(() => action.invoke({ level: 1 }), /InternalError/); + }); + + it('should fail asynchronous actions when their output violates the schema', async () => { + const action = new ActionAffordance('getLevel', { + output: { type: 'integer' }, + }); + action.setInvokeHandler(async () => 'not an integer'); + + const { href } = action.invokeAsync(undefined); + await new Promise((resolve) => setImmediate(resolve)); + + assert.equal(action.query(href.split('/').at(-1)).status, 'failed'); + assert.equal( + action.query(href.split('/').at(-1)).error.detail, + 'InternalError', + ); + }); + it('should reject when no invoke handler has been registered', async () => { const action = new ActionAffordance('setColor', { input: { type: 'string' }, diff --git a/test/data-schema.test.js b/test/data-schema.test.js new file mode 100644 index 0000000..10cf63d --- /dev/null +++ b/test/data-schema.test.js @@ -0,0 +1,42 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import DataSchema from '../src/data-schema.js'; +import ValidationError from '../src/validation-error.js'; + +describe('DataSchema', () => { + it('should validate values against the provided schema', () => { + const schema = new DataSchema({ type: 'integer', minimum: 0 }); + + assert.equal(schema.validate(1), true); + assert.equal(schema.validate(-1), false); + assert.equal(schema.validate('1'), false); + }); + + it('should accept values when no schema is provided', () => { + const schema = new DataSchema(undefined); + + assert.equal(schema.validate({ any: 'value' }), true); + }); + + it('should report invalid schemas with their Thing Description field', () => { + assert.throws( + () => new DataSchema({ type: 'invalid' }, 'properties.level'), + (error) => { + assert.ok(error instanceof ValidationError); + assert.equal(error.validationErrors[0].field, 'properties.level'); + return true; + }, + ); + }); + + it('should leave the validation error field undefined when omitted', () => { + assert.throws( + () => new DataSchema({ type: 'invalid' }), + (error) => { + assert.ok(error instanceof ValidationError); + assert.equal(error.validationErrors[0].field, undefined); + return true; + }, + ); + }); +}); diff --git a/test/property-affordance.test.js b/test/property-affordance.test.js index 92527ec..0441c9b 100644 --- a/test/property-affordance.test.js +++ b/test/property-affordance.test.js @@ -1,6 +1,7 @@ import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import PropertyAffordance from '../src/property-affordance.js'; +import DataSchema from '../src/data-schema.js'; import ValidationError from '../src/validation-error.js'; describe('PropertyAffordance', () => { @@ -18,6 +19,8 @@ describe('PropertyAffordance', () => { assert.equal(property.type, 'boolean'); assert.equal(property.readOnly, true); assert.equal(property.writeOnly, false); + assert.ok(property.valueSchema instanceof DataSchema); + assert.equal(property.valueSchema.validate(true), true); }); it('should default readOnly and writeOnly to false when omitted', () => { @@ -26,6 +29,7 @@ describe('PropertyAffordance', () => { assert.equal(property.readOnly, false); assert.equal(property.writeOnly, false); assert.equal(property.type, 'string'); + assert.ok(property.valueSchema instanceof DataSchema); }); it('should reject invalid member types', () => { @@ -139,6 +143,23 @@ describe('PropertyAffordance', () => { assert.equal(await property.write(7), 7); }); + it('should reject writes and reads that do not match the data schema', async () => { + const property = new PropertyAffordance('level', { + type: 'integer', + minimum: 0, + maximum: 100, + }); + let written; + property.setWriteHandler(async (value) => { + written = value; + }); + property.setReadHandler(async () => 101); + + await assert.rejects(() => property.write(101), /BadRequest/); + assert.equal(written, undefined); + await assert.rejects(() => property.read(), /InternalError/); + }); + it('should reject when no read or write handler is registered', async () => { const property = new PropertyAffordance('level', { type: 'number' }); diff --git a/test/thing.test.js b/test/thing.test.js index 63b18bc..e8e2fce 100644 --- a/test/thing.test.js +++ b/test/thing.test.js @@ -193,6 +193,7 @@ describe('Thing', () => { title: 'Writable Thing', properties: { on: { type: 'boolean' }, + level: { type: 'number' }, locked: { type: 'boolean', readOnly: true }, }, }); @@ -200,6 +201,9 @@ describe('Thing', () => { thing.setPropertyWriteHandler('on', async () => { written = true; }); + thing.setPropertyWriteHandler('level', async () => { + written = true; + }); await assert.rejects( () => thing.writeMultipleProperties({ on: true, locked: true }), @@ -209,6 +213,10 @@ describe('Thing', () => { () => thing.writeMultipleProperties({ on: true, missing: true }), /NotFoundError/, ); + await assert.rejects( + () => thing.writeMultipleProperties({ on: false, level: 'invalid' }), + /BadRequest/, + ); await assert.rejects( () => thing.writeMultipleProperties(null), /BadRequest/,