import { expect } from "chai"; import { DPT10 } from "../src/DPT10" import { BufferLengthError } from "../src/errors/BufferLengthError"; import { InvalidValueError } from "../src/errors/InvalidValueError"; import { compareBuffers } from "./util" let date = new Date(Date.parse('04 Mar 2022 00:12:00 GMT')) let dayOfWeek = date.getDay() let hour = date.getHours() let minute = date.getMinutes() let second = date.getSeconds() let bufferValue = Buffer.from([(dayOfWeek << 5) + hour, minute, second]) let today = new Date() today.setDate(today.getDate() + dayOfWeek - today.getDay()) today.setHours(hour) today.setMinutes(minute) today.setSeconds(second) today.setMilliseconds(0) let bufferEmpty = Buffer.from([]) let bufferBiggerSize = Buffer.from([0xff, 0xff, 0x63, 0xc0]) describe("Test DPT010", (): void => { let dpt = new DPT10(); it("Decode buffer acceptable", async function () { expect(dpt.decoder(bufferValue).getTime()).is.equal(today.getTime()); }); it("Decode empty buffer", async function () { var testFunction = function () { const value = dpt.decoder(bufferEmpty) } expect(testFunction).to.throw(BufferLengthError); }); it("Decode oversized buffer", async function () { var testFunction = function () { const value = dpt.decoder(bufferBiggerSize) } expect(testFunction).to.throw(BufferLengthError); }); it("Decode invalid buffers", async function () { let bufferErrorHour = Buffer.from([(dayOfWeek << 5) + 24, minute, second]) let bufferErrorMinute = Buffer.from([(dayOfWeek << 5) + hour, 70, second]) let bufferErrorSecond = Buffer.from([(dayOfWeek << 5) + hour, minute, 70]) var test_bufferErrorHour = function () { const value = dpt.decoder(bufferErrorHour) } var test_bufferErrorMinute = function () { const value = dpt.decoder(bufferErrorMinute) } var test_bufferErrorSecond = function () { const value = dpt.decoder(bufferErrorSecond) } expect(test_bufferErrorHour).to.throw(InvalidValueError); expect(test_bufferErrorMinute).to.throw(InvalidValueError); expect(test_bufferErrorSecond).to.throw(InvalidValueError); }); /* Encoder tests */ it("encode valid date", async function () { expect(compareBuffers(dpt.encoder(date), bufferValue)).is.true; }); it("encode valid number", async function () { expect(compareBuffers(dpt.encoder(date.getTime()), bufferValue)).is.true; }); it("encode valid string", async function () { let todayTest = new Date() todayTest.setHours(hour) todayTest.setMinutes(minute) todayTest.setSeconds(second) todayTest.setMilliseconds(0) let todayBuffer = dpt.encoder(todayTest) expect(compareBuffers(dpt.encoder(`${hour}:${minute}:${second}`), todayBuffer)).is.true; }); it("encode invalid string", async function () { var testFunction = function () { const value = dpt.encoder("10-10-10") } expect(testFunction).to.throw(InvalidValueError); }); it("encode undefined", async function () { var testFunction = function () { const value = dpt.encoder(undefined) } expect(testFunction).to.throw(InvalidValueError); }); });