-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy path1-box.js
786 lines (695 loc) · 24.3 KB
/
1-box.js
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
'use strict';
/* global describe it before after */
const expect = require('chai').expect,
{ db: { connect, mongoose }, Box, Measurement } = require('../../index'),
dbConnectionString = require('../helpers/dbConnectionString'),
senseBox = require('../helpers/senseBox'),
moment = require('moment'),
parseISO8601 = require('../helpers/iso8601'),
shouldBeABox = require('../helpers/shouldBeABox'),
shouldBeABoxWithSecrets = require('../helpers/shouldBeABoxWithSecrets'),
checkBoxLocation = require('../helpers/checkBoxLocation'),
initBoxWithMeasurements = require('../helpers/initBoxWithMeasurements'),
ensureIndexes = require('../helpers/ensureIndexes'),
fs = require('fs');
const shouldNotHappenThenner = function (err) {
/* eslint-disable no-console */
console.log(err);
/* eslint-enable no-console */
expect(false).true;
};
describe('Box model', function () {
const testBoxes = {};
before(function () {
return connect(dbConnectionString({ db: 'boxTest' }))
.then(() => ensureIndexes());
});
after(function () {
mongoose.disconnect();
});
describe('Box creation', function () {
it('should allow to create a box', function () {
return Box.initNew(senseBox())
.then(shouldBeABox)
.then(function (box) {
return Box.findById(box._id);
})
.then(shouldBeABoxWithSecrets)
.then(function (box) {
expect(box.name).equal('testSensebox');
expect(box.grouptag).to.be.an('array').that.is.empty;
expect(box.model).equal('homeEthernet');
expect(box.integrations.mqtt.enabled).false;
expect(box.locations).an('array');
for (const loc of box.locations) {
checkBoxLocation(loc);
}
testBoxes[box._id] = box;
});
});
it('should allow creation of gsm integration with homeV2GSM model', function () {
const box = senseBox({
model: 'homeV2GSM',
gsm: {
imsi: '973498573498563456873',
secret_code: 'superSecretCodeForTesting'
}
});
return Box.initNew(box)
.then(shouldBeABoxWithSecrets)
.then(function (box) {
return Box.findById(box._id);
})
.then(shouldBeABox)
.then(function ({ integrations }) {
expect(integrations.gsm.imsi).equal('973498573498563456873');
expect(integrations.gsm.secret_code).equal('superSecretCodeForTesting');
});
});
it('should persist integrations and other properties upon creation', function () {
const box = senseBox({
name: 'integrationsbox',
grouptag: ['grouptagTest'],
exposure: 'outdoor',
ttn: {
dev_id: 'test_devid',
app_id: 'test_appid',
port: 55,
profile: 'lora-serialization',
decodeOptions: []
},
mqtt: {
enabled: true,
url: 'mqtt://testbroker',
topic: 'some/test/topic',
connectionOptions: '{}',
decodeOptions: '{}',
messageFormat: 'csv'
}
});
return Box.initNew(box)
.then(shouldBeABoxWithSecrets)
.then(function (box) {
return Box.findById(box._id);
})
.then(shouldBeABox)
.then(function ({ integrations, name, grouptag, exposure }) {
expect(name).equal('integrationsbox');
// expect(grouptag).equal(['grouptagTest']);
expect(grouptag).to.be.an('array').that.include('grouptagTest');
expect(exposure).equal('outdoor');
expect(integrations).an('object');
expect(integrations).not.empty;
expect(integrations.ttn).an('object');
expect(integrations.ttn).not.empty;
expect(integrations.ttn.dev_id).equal('test_devid');
expect(integrations.ttn.app_id).equal('test_appid');
expect(integrations.ttn.port).equal(55);
expect(integrations.ttn.profile).equal('lora-serialization');
expect(integrations.ttn.decodeOptions).an('array');
expect(integrations.ttn.decodeOptions).lengthOf(0);
expect(integrations.mqtt).an('object');
expect(integrations.mqtt).not.empty;
expect(integrations.mqtt.enabled).true;
expect(integrations.mqtt.url).equal('mqtt://testbroker');
expect(integrations.mqtt.topic).equal('some/test/topic');
expect(integrations.mqtt.connectionOptions).equal('{}');
expect(integrations.mqtt.decodeOptions).equal('{}');
expect(integrations.mqtt.messageFormat).equal('csv');
testBoxes[box._id] = box;
});
});
it('should allow to create a custom senseBox with custom sensors', function () {
const box = senseBox({
sensors: [
{
title: 'customSensor0',
unit: 'customUnit0',
sensorType: 'customSensorType0'
},
{
title: 'customSensor1',
unit: 'customUnit1',
sensorType: 'customSensorType1'
},
{
title: 'customSensor2',
unit: 'customUnit2',
sensorType: 'customSensorType2'
},
{
title: 'customSensor3',
unit: 'customUnit3',
sensorType: 'customSensorType3'
},
{
title: 'customSensor4',
unit: 'customUnit4',
sensorType: 'customSensorType4',
icon: 'icon!'
}
]
});
return Box.initNew(box)
.then(shouldBeABoxWithSecrets)
.then(function (box) {
return Box.findById(box._id);
})
.then(shouldBeABox)
.then(function ({ sensors, model }) {
expect(model).equal('custom');
expect(sensors).an('array');
expect(sensors).not.empty;
for (const [
index,
{ title, unit, sensorType, icon }
] of sensors.entries()) {
expect(title.includes('customSensor')).true;
expect(title.endsWith(index.toString(10))).true;
expect(unit.includes('customUnit')).true;
expect(unit.endsWith(index.toString(10))).true;
expect(sensorType.includes('customSensorType')).true;
expect(sensorType.endsWith(index.toString(10))).true;
if (index === sensors.length - 1) {
expect(icon).equal('icon!');
}
}
testBoxes[box._id] = box;
});
});
it('should not allow to specify sensors and model at the same time', function () {
const box = senseBox({
sensors: [{ title: 'sensor', unit: '%', sensorType: 'dummy' }]
});
box.model = 'homeEthernet';
return Box.initNew(box).then(shouldNotHappenThenner)
.catch(function (err) {
expect(err.name).equal('ModelError');
expect(err.message).equal(
'Parameters model and sensors cannot be specified at the same time.'
);
});
});
it('should not allow creation of homeV2GSM without gsm credentials', function () {
return Box.initNew(senseBox({ model: 'homeV2GSM' }))
.then(shouldNotHappenThenner)
.catch(function (err) {
expect(err.name).equal('ModelError');
expect(err.message).equal('homeV2GSM can not be created without imsi or secret code');
});
});
it('should not allow to specify unknown model', function () {
return Box.initNew(senseBox({ model: 'fancyNewModel' }))
.then(shouldNotHappenThenner)
.catch(function (err) {
expect(err.name).equal('ValidationError');
expect(err.message).equal(
'Box validation failed: model: `fancyNewModel` is not a valid enum value for path `model`., sensors: sensors are required if model is invalid or missing.'
);
});
});
it('should not be possible to create a box with empty array for sensors', function () {
const box = senseBox();
box.model = 'custom';
box.sensors = [];
return Box.initNew(box).then(shouldNotHappenThenner)
.catch(function (err) {
expect(err.name).equal('ModelError');
expect(err.message).equal(
'Parameters model and sensors cannot be specified at the same time.'
);
});
});
});
describe('findBoxById', function () {
it('should return the public properties', function () {
const boxId = Object.keys(testBoxes)[0];
return (
Box.findBoxById(boxId)
// .then(shouldBeABox)
.then(function (box) {
expect(box.loc).an('array');
expect(box.loc).lengthOf(1);
expect(box.loc[0].type).equal('Feature');
checkBoxLocation(box.loc[0].geometry);
})
);
});
it('should allow to include secrets', function () {
const boxId = Object.keys(testBoxes)[0];
return Box.findBoxById(boxId, { includeSecrets: true })
.then(shouldBeABoxWithSecrets)
.then(function (box) {
expect(box.loc).an('array');
expect(box.loc).lengthOf(1);
expect(box.loc[0].type).equal('Feature');
checkBoxLocation(box.loc[0].geometry);
});
});
it('should allow to show only last measurements', function () {
const boxId = Object.keys(testBoxes)[0];
const measurements = Measurement.decodeMeasurements(
testBoxes[boxId].sensors.map(s => {
return { sensor_id: s._id.toString(), value: 2 };
})
);
return Box.findById(boxId)
.then(function (box) {
return measurements.then(function (ms) {
return box.saveMeasurementsArray(ms);
});
})
.then(function () {
return Box.findBoxById(boxId, { onlyLastMeasurements: true });
})
.then(function (lastMeasurements) {
expect(Object.keys(lastMeasurements)).members(['_id', 'sensors']);
for (const { lastMeasurement } of lastMeasurements.sensors) {
expect(lastMeasurement).an('object');
expect(Object.keys(lastMeasurement)).members([
'value',
'createdAt'
]);
expect(parseISO8601(lastMeasurement.createdAt).isValid()).true;
}
});
});
it('should allow to show only locations', function () {
const boxId = Object.keys(testBoxes)[0];
return Box.findBoxById(boxId, { onlyLocations: true }).then(function (
locations
) {
expect(Object.keys(locations)).members(['_id', 'locations']);
expect(locations.locations).an('array');
for (const loc of locations.locations) {
checkBoxLocation(loc);
}
});
});
it('should allow to disable population and specify own projection', function () {
const boxId = Object.keys(testBoxes)[0];
return Box.findBoxById(boxId, {
populate: false,
projection: { name: 1, integrations: 1, exposure: 1, _id: 0 }
}).then(function (result) {
expect(Object.keys(result)).members([
'name',
'integrations',
'exposure'
]);
});
});
});
describe('findBoxesMinimal()', function () {
it('should return all boxes with minimal subset of attributes', function () {
return Box.findBoxesMinimal().then(function (queryCursor) {
queryCursor.on('data', (box) => {
expect(Object.keys(box)).to.include.members([
'_id',
'currentLocation',
'exposure',
'name',
]);
expect(Object.keys(box))
.to.not.include('loc')
.and.to.not.include('locations')
.and.not.include('weblink')
.and.not.include('image')
.and.not.include('description')
.and.not.include('model')
.and.not.include('sensors');
});
queryCursor.on('end', () => {
expect(true).to.be.true;
});
});
});
});
describe('JSON serialization', function () {
it('should only serialize public properties', function () {
const boxId = Object.keys(testBoxes)[0];
return Box.findById(boxId).then(function (box) {
const json = box.toJSON();
expect(Object.keys(json)).members([
'createdAt',
'exposure',
'model',
'grouptag',
'image',
'name',
'updatedAt',
'currentLocation',
'sensors',
'description',
'weblink',
'_id',
'loc',
'lastMeasurementAt'
]);
});
});
});
describe('Updating properties of a box', function () {
it('should allow to delete multiple sensors in one request', function () {
let sensorsToDelete;
return initBoxWithMeasurements()
.then(function (box) {
sensorsToDelete = box.sensors.map(function (sensor) {
return { deleted: true, _id: sensor._id };
});
sensorsToDelete = sensorsToDelete.slice(0, -1);
return box.updateBox({ sensors: sensorsToDelete });
})
.then(function (box) {
return Box.findById(box._id);
})
.then(function ({ sensors }) {
expect(sensors).lengthOf(1);
for (const { _id } of sensors) {
expect(sensorsToDelete.findIndex(s => _id.equals(s._id))).equal(-1);
}
return Measurement.count({
sensor_id: { $in: sensorsToDelete.map(s => s._id) }
});
})
.then(function (count) {
expect(count).equal(0);
});
});
it('should allow to add a sensor to a box through updateBox', function () {
const newSensor = {
title: 'newPhenomenon',
unit: 'newUnit',
icon: 'newIcon',
sensorType: 'newSensorType',
new: true,
edited: true
};
let numberOfSensors;
return Box.initNew(senseBox())
.then(shouldBeABoxWithSecrets)
.then(function (box) {
numberOfSensors = box.sensors.length;
return box.updateBox({ sensors: [newSensor] });
})
.then(function (box) {
return Box.findById(box._id);
})
.then(function (box) {
expect(box.sensors).lengthOf(numberOfSensors + 1);
const addedSensor = box.sensors[box.sensors.length - 1];
expect(addedSensor.title).equal(newSensor.title);
expect(addedSensor.unit).equal(newSensor.unit);
expect(addedSensor.sensorType).equal(newSensor.sensorType);
expect(addedSensor.icon).equal(newSensor.icon);
});
});
it('should allow to edit a sensor', function () {
let sensorToEdit;
return Box.initNew(senseBox())
.then(shouldBeABoxWithSecrets)
.then(function (box) {
sensorToEdit = box.sensors[2];
sensorToEdit.edited = true;
sensorToEdit.title = 'new Title';
sensorToEdit.unit = 'new Unit';
sensorToEdit.sensorType = 'new sensorType';
return box.updateBox({ sensors: [sensorToEdit] });
})
.then(function (box) {
return Box.findById(box._id);
})
.then(function (box) {
const updatedSensor = box.sensors[2];
expect(updatedSensor.title).equal(sensorToEdit.title);
expect(updatedSensor.unit).equal(sensorToEdit.unit);
expect(updatedSensor.sensorType).equal(sensorToEdit.sensorType);
expect(updatedSensor.icon).equal(sensorToEdit.icon);
});
});
it('should not allow to delete all sensors of a box at once', function () {
let sensorsToDelete;
return Box.initNew(senseBox())
.then(shouldBeABoxWithSecrets)
.then(function (box) {
sensorsToDelete = box.sensors.map(function (sensor) {
return { deleted: true, _id: sensor._id };
});
return box.updateBox({ sensors: sensorsToDelete });
})
.then(shouldNotHappenThenner)
.catch(function (err) {
expect(err.name).equal('ModelError');
expect(err.message).equal(
'Unable to delete sensor(s). A box needs at least one sensor.'
);
});
});
it('should not allow to delete all sensors of a box one by one', function () {
return Box.initNew(senseBox())
.then(shouldBeABoxWithSecrets)
.then(function (box) {
return box.updateBox({
sensors: [{ deleted: true, _id: box.sensors[0]._id }]
});
})
.then(function (box) {
return box.updateBox({
sensors: [{ deleted: true, _id: box.sensors[0]._id }]
});
})
.then(function (box) {
return box.updateBox({
sensors: [{ deleted: true, _id: box.sensors[0]._id }]
});
})
.then(function (box) {
return box.updateBox({
sensors: [{ deleted: true, _id: box.sensors[0]._id }]
});
})
.then(function (box) {
return box.updateBox({
sensors: [{ deleted: true, _id: box.sensors[0]._id }]
});
})
.then(shouldNotHappenThenner)
.catch(function (err) {
expect(err.name).equal('ModelError');
expect(err.message).equal(
'Unable to delete sensor(s). A box needs at least one sensor.'
);
});
});
let boxid;
it('should allow to change name the basic string properties of a box', function () {
const updatePayload = {
name: 'new Name',
exposure: 'outdoor',
grouptag: 'new Grouptag',
weblink: 'http://www.opensensemap.org',
image: {
type: 'png',
data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQYV2NgYAAAAAMAAWgmWQ0AAAAASUVORK5CYII='
},
description: 'this is the new description',
model: 'homeWifi'
};
return Box.initNew(senseBox())
.then(shouldBeABoxWithSecrets)
.then(function (box) {
return box.updateBox(updatePayload);
})
.then(function (box) {
boxid = box._id;
return Box.findById(box._id);
})
.then(function ({
name,
exposure,
grouptag,
weblink,
image,
description,
model
}) {
expect(name).equal(updatePayload.name);
expect(exposure).equal(updatePayload.exposure);
expect(grouptag).to.be.an('array').that.include(updatePayload.grouptag);
expect(weblink).equal(updatePayload.weblink);
expect(description).equal(updatePayload.description);
expect(model).equal(updatePayload.model);
expect(
moment().diff(
moment(parseInt(image.split('_')[1].slice(0, -4), 36) * 1000)
)
).to.be.below(1000);
expect(fs.existsSync(`/userimages/${image}`)).true;
});
});
it('should allow to delete the image of a box', async function () {
let box = await Box.findById(boxid);
expect(box.image).not.empty;
expect(fs.existsSync(`/userimages/${box.image}`)).true;
await box.updateBox({ image: 'deleteImage' });
box = await Box.findById(boxid);
expect(box.image).not.exist;
expect(fs.existsSync(`/userimages/${box.image}`)).false;
});
it('should not allow to change name of a box to empty string', function () {
const updatePayload = { name: '' };
return Box.initNew(senseBox())
.then(shouldBeABoxWithSecrets)
.then(function (box) {
return box.updateBox(updatePayload);
})
.then(shouldNotHappenThenner)
.catch(function (err) {
expect(err.name).equal('ValidationError');
expect(err.message).equal(
'Box validation failed: name: Path `name` is required.'
);
});
});
it('should allow to unset grouptag, description and weblink of a box', function () {
const updatePayload = {
grouptag: 'new Grouptag',
weblink: 'http://www.opensensemap.org',
description: 'this is the new description'
};
return Box.initNew(senseBox())
.then(shouldBeABoxWithSecrets)
.then(function (box) {
return box.updateBox(updatePayload);
})
.then(function (box) {
return Box.findById(box._id);
})
.then(function (box) {
expect(box.grouptag).to.be.an('array').that.include(updatePayload.grouptag);
expect(box.weblink).equal(updatePayload.weblink);
expect(box.description).equal(updatePayload.description);
updatePayload.grouptag = [];
updatePayload.weblink = '';
updatePayload.description = '';
return box.updateBox(updatePayload);
})
.then(function (box) {
return Box.findById(box._id);
})
.then(function ({ grouptag, weblink, description }) {
expect(grouptag).to.be.an('array').that.is.empty;
expect(weblink).not.exist;
expect(description).not.exist;
});
});
it('should allow to set ttn settings', function () {
const updatePayload = {
ttn: {
app_id: 'some_app_id',
dev_id: 'some_dev_id',
profile: 'sensebox/home'
}
};
return Box.initNew(senseBox())
.then(shouldBeABoxWithSecrets)
.then(function (box) {
return box.updateBox(updatePayload);
})
.then(function (box) {
return Box.findById(box._id);
})
.then(function ({ integrations: { ttn: { app_id, dev_id, profile } } }) {
expect(app_id).equal(updatePayload.ttn.app_id);
expect(dev_id).equal(updatePayload.ttn.dev_id);
expect(profile).equal(updatePayload.ttn.profile);
});
});
it('should allow to set mqtt settings', function () {
const updatePayload = {
mqtt: {
enabled: true,
url: 'mqtt://somebroker',
topic: 'some/topic',
connectionOptions: '',
decodeOptions: '',
messageFormat: 'csv'
}
};
return Box.initNew(senseBox())
.then(shouldBeABoxWithSecrets)
.then(function (box) {
return box.updateBox(updatePayload);
})
.then(function (box) {
return Box.findById(box._id);
})
.then(function ({
integrations: {
mqtt: {
enabled,
url,
topic,
decodeOptions,
connectionOptions,
messageFormat
}
}
}) {
expect(enabled).equal(updatePayload.mqtt.enabled);
expect(url).equal(updatePayload.mqtt.url);
expect(topic).equal(updatePayload.mqtt.topic);
expect(decodeOptions).equal(updatePayload.mqtt.decodeOptions);
expect(connectionOptions).equal(updatePayload.mqtt.connectionOptions);
expect(messageFormat).equal(updatePayload.mqtt.messageFormat);
});
});
it('should allow to add feinstaub addon to box', function () {
const updatePayload = { addons: { add: 'feinstaub' } };
return Box.initNew(senseBox())
.then(shouldBeABoxWithSecrets)
.then(function (box) {
return box.updateBox(updatePayload);
})
.then(function (box) {
return Box.findById(box._id);
})
.then(function ({ model, sensors }) {
expect(
sensors.some(function ({ unit, sensorType, title }) {
return (
unit === 'µg/m³' && sensorType === 'SDS 011' && title === 'PM10'
);
})
).true;
expect(
sensors.some(function ({ unit, sensorType, title }) {
return (
unit === 'µg/m³' &&
sensorType === 'SDS 011' &&
title === 'PM2.5'
);
})
).true;
expect(model.includes('Feinstaub')).true;
});
});
});
describe('Box deletion', function () {
it('should allow to delete a box', function () {
let boxId;
return Box.initNew(senseBox())
.then(shouldBeABoxWithSecrets)
.then(function (box) {
boxId = box._id;
return box.removeSelfAndMeasurements();
})
.then(function () {
return Box.findById(boxId);
})
.then(function (box) {
expect(box).not.exist;
});
});
});
});