forked from ooici/marine-integrations
/
unit_test.py
3351 lines (2755 loc) · 138 KB
/
unit_test.py
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
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
"""
@file coi-services/ion/idk/unit_test.py
@author Bill French
@brief Base classes for instrument driver tests.
"""
from mock import patch
from pyon.core.bootstrap import CFG
import subprocess
import re
import os
import time
import ntplib
import unittest
import datetime
from sets import Set
# Set testing to false because the capability container tries to clear out
# couchdb if we are testing. Since we don't care about couchdb for the most
# part we can ignore this. See initialize_ion_int_tests() for implementation.
# If you DO care about couch content make sure you do a force_clean when needed.
from pyon.core import bootstrap
bootstrap.testing = False
# Import pyon first for monkey patching.
from mi.core.log import get_logger ; log = get_logger()
import gevent
import json
from pprint import PrettyPrinter
from pyon.core.exception import IonException, ExceptionFactory
from mock import Mock
from mi.core.unit_test import MiIntTestCase
from mi.core.unit_test import MiUnitTest
from mi.core.unit_test import ParticleTestMixin
from mi.core.port_agent_simulator import TCPSimulatorServer
from mi.core.instrument.instrument_driver import InstrumentDriver
from mi.core.instrument.instrument_driver import DriverParameter
from mi.core.instrument.instrument_driver import ConfigMetadataKey
from mi.core.instrument.instrument_protocol import InstrumentProtocol
from mi.core.instrument.protocol_param_dict import ProtocolParameterDict
from mi.core.instrument.protocol_param_dict import ParameterDictVisibility
from mi.core.instrument.protocol_param_dict import ParameterDictKey
from mi.core.instrument.protocol_param_dict import ParameterDictType
from mi.core.instrument.protocol_cmd_dict import CommandDictKey
from mi.core.instrument.driver_dict import DriverDictKey
from ion.agents.port.port_agent_process import PortAgentProcessType
from interface.objects import AgentCapability
from interface.objects import CapabilityType
from ion.agents.instrument.driver_process import DriverProcess, DriverProcessType
from interface.objects import AgentCommandResult
from interface.objects import AgentCommand
from mi.idk.util import convert_enum_to_dict
from mi.idk.util import get_dict_value
from mi.idk.comm_config import CommConfig
from mi.idk.comm_config import ConfigTypes
from mi.idk.config import Config
from mi.idk.common import Singleton
from mi.idk.instrument_agent_client import InstrumentAgentClient
from mi.idk.instrument_agent_client import InstrumentAgentDataSubscribers
from mi.idk.instrument_agent_client import InstrumentAgentEventSubscribers
from mi.idk.exceptions import IDKException
from mi.idk.exceptions import TestNotInitialized
from mi.idk.exceptions import TestNoCommConfig
from mi.core.exceptions import InstrumentException
from mi.core.exceptions import InstrumentParameterException
from mi.core.exceptions import InstrumentStateException
from mi.core.instrument.port_agent_client import PortAgentClient
from mi.core.instrument.port_agent_client import PortAgentPacket
from mi.core.instrument.data_particle import CommonDataParticleType
from mi.core.instrument.data_particle import DataParticle
from mi.core.instrument.data_particle import DataParticleKey
from mi.core.instrument.data_particle import DataParticleValue
from mi.core.instrument.data_particle import RawDataParticleKey
from mi.core.instrument.instrument_driver import DriverEvent
from mi.core.instrument.instrument_driver import DriverConnectionState
from mi.core.instrument.instrument_driver import DriverProtocolState
from mi.core.instrument.instrument_driver import DriverAsyncEvent
from mi.core.tcp_client import TcpClient
from mi.core.common import BaseEnum
from mi.core.driver_scheduler import DriverSchedulerConfigKey
from mi.core.driver_scheduler import TriggerType
from ion.agents.instrument.direct_access.direct_access_server import DirectAccessTypes
from ion.agents.port.port_agent_process import PortAgentProcess
from pyon.core.exception import Conflict
from pyon.core.exception import ResourceError, BadRequest, Timeout, ServerError
from pyon.agent.agent import ResourceAgentState
from pyon.agent.agent import ResourceAgentEvent
from ooi.logging import log
# Do not remove this import. It is for package building.
from mi.core.instrument.zmq_driver_process import ZmqDriverProcess
AGENT_DISCOVER_TIMEOUT=900
GO_ACTIVE_TIMEOUT=900
GET_TIMEOUT=900
SET_TIMEOUT=900
EXECUTE_TIMEOUT=900
#AGENT_DISCOVER_TIMEOUT=180
#GO_ACTIVE_TIMEOUT=400
#GET_TIMEOUT=180
#SET_TIMEOUT=180
#EXECUTE_TIMEOUT=180
SAMPLE_RAW_DATA="Iam Apublished Message"
LOCALHOST='localhost'
class DriverStartupConfigKey(BaseEnum):
PARAMETERS = 'parameters'
SCHEDULER = 'scheduler'
class AgentCapabilityType(BaseEnum):
AGENT_COMMAND = 'agent_command'
AGENT_PARAMETER = 'agent_parameter'
RESOURCE_COMMAND = 'resource_command'
RESOURCE_INTERFACE = 'resource_interface'
RESOURCE_PARAMETER = 'resource_parameter'
class ParameterTestConfigKey(BaseEnum):
"""
Defines the dict keys used in the data particle parameter config used in unit tests of data particles
"""
TYPE = 'type'
REQUIRED = 'required'
NAME = 'name'
DIRECT_ACCESS = 'directaccess'
STARTUP = 'startup'
READONLY = 'readonly'
DEFAULT = 'default'
STATES = 'states'
VALUE = 'value'
class InstrumentDriverTestConfig(Singleton):
"""
Singleton driver test config object.
"""
driver_module = None
driver_class = None
working_dir = "/tmp/" # requires trailing / or it messes up the path. should fix.
delimeter = ['<<','>>']
logger_timeout = 15
driver_process_type = DriverProcessType.PYTHON_MODULE
agent_resource_id = None
agent_name = None
agent_module = 'mi.idk.instrument_agent'
agent_class = 'InstrumentAgent'
data_instrument_agent_module = 'mi.idk.instrument_agent'
data_instrument_agent_class = 'PublisherInstrumentAgent'
agent_packet_config = None
agent_stream_encoding = 'ION R2'
agent_stream_definition = None
driver_startup_config = {}
container_deploy_file = 'deploy/r2qual.yml'
publisher_deploy_file = 'deploy/r2pub.yml'
initialized = False
def initialize(self, *args, **kwargs):
self.driver_module = kwargs.get('driver_module')
self.driver_class = kwargs.get('driver_class')
if kwargs.get('working_dir'):
self.working_dir = kwargs.get('working_dir')
if kwargs.get('delimeter'):
self.delimeter = kwargs.get('delimeter')
self.agent_preload_id = get_dict_value(kwargs, ['instrument_agent_preload_id', 'agent_preload_id'])
self.agent_resource_id = get_dict_value(kwargs, ['instrument_agent_resource_id', 'agent_resource_id'], self.agent_resource_id)
self.agent_name = get_dict_value(kwargs, ['instrument_agent_name', 'agent_name'], self.agent_name)
self.agent_packet_config = self._build_packet_config(get_dict_value(kwargs, ['instrument_agent_packet_config','agent_packet_config']))
self.agent_stream_definition = get_dict_value(kwargs, ['instrument_agent_stream_definition', 'agent_stream_definition'])
self.agent_module = get_dict_value(kwargs, ['instrument_agent_module', 'agent_module'], self.agent_module)
self.agent_class = get_dict_value(kwargs, ['instrument_agent_class', 'agent_class'], self.agent_class)
self.agent_stream_encoding = get_dict_value(kwargs, ['instrument_agent_stream_encoding', 'agent_stream_encoding'], self.agent_stream_encoding)
if kwargs.get('container_deploy_file'):
self.container_deploy_file = kwargs.get('container_deploy_file')
if kwargs.get('logger_timeout'):
self.logger_timeout = kwargs.get('logger_timeout')
if kwargs.get('driver_process_type'):
self.driver_process_type = kwargs.get('driver_process_type')
self.driver_startup_config = get_dict_value(kwargs, ['startup_config', 'driver_startup_config'])
log.info("Startup Config: %s", self.driver_startup_config)
log.info("Preload Startup Config: %s", self.config_for_preload(self.driver_startup_config))
self.initialized = True
def config_for_preload(self,adict):
def helper(prefix, dict):
buffer = ""
if dict is None or 0 == len(dict):
return "%s: {}," % ".".join(prefix)
newprefix = prefix[:]
for k, v in dict.iteritems():
if type(v) == type({}):
buffer += helper(newprefix + [k], v)
elif type(v) == type([]):
# can't handle lists
assert 0 == len(v)
buffer += "%s: []," % ".".join(newprefix)
else:
newprefix.append(k)
buffer += "%s: %s," % (".".join(newprefix), v)
return buffer
return helper([], adict)
def _build_packet_config(self, param_config):
"""
Build a packet config from various data types.
@param packet_config: packet config object. Can be enum, dict or list
@return list of stream names to create
"""
params = []
if(isinstance(param_config, list)):
params = param_config
elif(isinstance(param_config, BaseEnum)):
params = param_config.list()
elif(isinstance(param_config, dict)):
params = [ value for (key, value) in param_config.items() ]
else:
log.error("Unknown param_config type")
return []
result = []
for i in params:
if(isinstance(i, tuple)):
log.debug("BLAMMM")
result.append(i[0])
else:
result.append(i)
return result
class DriverTestMixin(MiUnitTest, ParticleTestMixin):
"""
Base class for data particle mixin. Used for data particle validation.
"""
_raw_sample_parameters = {
RawDataParticleKey.PAYLOAD: {'type': unicode, 'value': u'SWFtIEFwdWJsaXNoZWQgTWVzc2FnZQ=='},
RawDataParticleKey.LENGTH: {'type': int, 'value': 22},
RawDataParticleKey.TYPE: {'type': int, 'value': 2},
RawDataParticleKey.CHECKSUM: {'type': int, 'value': 2757}
}
def assert_particle_raw(self, data_particle, verify_values = False):
'''
Verify a raw data particles
@param data_particle SBE26plusTideSampleDataParticle data particle
@param verify_values bool, should we verify parameter values
'''
self.assert_data_particle_header(data_particle, CommonDataParticleType.RAW)
self.assert_data_particle_parameters(data_particle, self._raw_sample_parameters, verify_values)
def assert_data_particle_parameters(self, data_particle, param_dict, verify_values = False):
"""
Verify data partice parameters. Does a quick conversion of the values to a dict
so that common methods can operate on them.
@param data_particle the data particle to examine
@param parameter_dict dict with parameter names and types
@param verify_values bool should ve verify parameter values
"""
sample_dict = self.get_data_particle_values_as_dict(data_particle)
self.assert_parameters(sample_dict, param_dict, verify_values)
def assert_driver_parameter_definition(self, driver, param_dict):
"""
Verify the parameters have been defined as expected in the driver protocol.
parameter_dict_examples:
startup: Verifies the parameter is defined as a startup parameter
directaccess: Verifies the parameter is defined as a direct access parameter
readonly: Verifies the parameter is defined as a readonly parameter
verify: Verifies the default value of the parameter
{
'some_key': {
startup: False
directaccess: False
readonly: False
default: some_value
}
}
@param driver: driver to inspect, must have a protocol defined
@param parameter_dict: dict with parameter names and types
"""
self.assertIsInstance(driver, InstrumentDriver)
self.assertIsInstance(driver._protocol, InstrumentProtocol)
self.assertIsInstance(driver._protocol._param_dict, ProtocolParameterDict)
self.assertIsInstance(param_dict, dict)
pd = driver._protocol._param_dict
for (name, config) in param_dict.items():
log.debug("Verify parameter: %s", name)
self.assertIsInstance(config, dict)
startup = config.get(ParameterTestConfigKey.STARTUP)
da = config.get(ParameterTestConfigKey.DIRECT_ACCESS)
readonly = config.get(ParameterTestConfigKey.READONLY)
default = config.get(ParameterTestConfigKey.DEFAULT)
if(da == True):
self.assertIn(name, pd.get_direct_access_list(), msg="%s not a direct access parameters %s" % (name, pd.get_direct_access_list()))
elif(da == False):
self.assertNotIn(name, pd.get_direct_access_list(), msg="%s is a direct access parameters %s" % (name, pd.get_direct_access_list()))
if(startup == True):
self.assertIn(name, pd.get_startup_list(), msg="%s is not a startup parameter" % name)
elif(startup == False):
self.assertNotIn(name, pd.get_startup_list(), msg="%s is a startup parameter" % name)
if(readonly == True):
ro_params = pd.get_visibility_list(ParameterDictVisibility.READ_ONLY) + \
pd.get_visibility_list(ParameterDictVisibility.IMMUTABLE)
self.assertIn(name, ro_params, msg="%s is not a read only parameter" % name)
elif(readonly == False):
self.assertIn(name, pd.get_visibility_list(ParameterDictVisibility.READ_WRITE), msg="%s is a read only parameter" % name)
if(default):
self.assertEqual(default, pd.get_default_value(name), "%s default value incorrect: %s != %s" % (name, default, pd.get_default_value(name)))
def assert_parameters(self, current_parameters, param_dict, verify_values = False):
"""
Verify the parameters contain all parameters in the parameter enum and verify the
types match those defined in the enum.
parameter_dict_examples:
There is one record for each parameter. with a dict describing the parameter.
type: the data type of the parameter. REQUIRED
required: is the parameter required, False == not required
name: Name of the parameter, used for validation if we use constants when defining keys
value: value of the parameter being validated. This is useful for unit tests where
parameters are known.
Following only used for driver parameter verification
startup: Verifies the parameter is defined as a startup parameter
directaccess: Verifies the parameter is defined as a direct access parameter
readonly: Verifies the parameter is defined as a readonly parameter
verify: Verifies the default value of the parameter
{
'some_key': {
type: float,
required: False,
name: 'some_key',
value: 1.1
startup: False
directaccess: False
readonly: False
default: some_value
}
}
required defaults to True
name: defaults to None
As a short cut you can define the dict with just the type. The other fields will default
{
'some_key': float
}
This will verify the type is a float, it is required and we will not validate the key.
@param current_parameters: list of parameters to examine
@param parameter_dict: dict with parameter names and types
@param verify_values: bool should ve verify parameter values
"""
self.assertIsInstance(current_parameters, dict)
self.assertIsInstance(param_dict, dict)
self.assert_parameter_names(param_dict)
self.assert_parameter_set(current_parameters, param_dict)
self.assert_parameter_types(current_parameters, param_dict)
if(verify_values):
self.assert_parameter_value(current_parameters, param_dict)
def assert_parameter_names(self, param_dict):
"""
Verify that the names of the parameter dictionary keys match the parameter value 'name'. This
is useful when the parameter dict is built using constants. If name is none then ignore.
param_dict:
{
'some_key': {
type: float,
required: False,
name: 'some_key'
}
}
@param param_dict: dictionary containing data particle parameter validation values
"""
for key, param_def in param_dict.items():
if(isinstance(param_def, dict)):
name = param_def.get(ParameterTestConfigKey.NAME)
if(name != None):
self.assertEqual(key, name)
def assert_parameter_set(self, sample_values, param_dict):
"""
Verify all required parameters appear in sample_dict as described in param_dict. Also verify
that there are no extra values in the sample dict that are not listed as optional in the
param_dict
@param sample_values: parsed data particle to inspect
@param param_dict: dictionary containing parameter validation information
"""
self.assertIsInstance(sample_values, dict)
self.assertIsInstance(param_dict, dict)
required_keys = []
optional_keys = []
# get all the sample parameter names
sample_keys = sample_values.keys()
log.info("Sample Keys: %s", sample_keys)
# split the parameters into optional and required
for key, param in param_dict.items():
if(isinstance(param, dict)):
required = param.get(ParameterTestConfigKey.REQUIRED, True)
if(required):
required_keys.append(key)
else:
optional_keys.append(key)
else:
required_keys.append(key)
log.info("Required Keys: %s", required_keys)
log.info("Optional Keys: %s", optional_keys)
# Lets verify all required parameters are there
for required in required_keys:
self.assertTrue(required in sample_keys, msg="particle missing parameter '%s', a required key" % required)
sample_keys.remove(required)
# Now lets look for optional fields and removed them from the parameter list
for optional in optional_keys:
if(optional in sample_keys):
sample_keys.remove(optional)
log.info("Unknown Keys: %s", sample_keys)
# If there is anything left in the sample keys then it's a problem
self.assertEqual(len(sample_keys), 0)
def assert_parameter_value(self, sample_values, param_dict):
"""
Verify the value in the data particle parameter with the value in the param dict. This test
is useful in unit testing when the values are known.
@param sample_dict: parsed data particle to inspect
@param param_dict: dictionary containing parameter validation information
"""
for (param_name, param_value) in sample_values.items():
# get the parameter type
param_def = param_dict.get(param_name)
log.debug("Particle Def (%s) ", param_def)
self.assertIsNotNone(param_def)
if(isinstance(param_def, dict)):
param_type = param_def.get(ParameterTestConfigKey.TYPE)
self.assertIsNotNone(type)
else:
param_type = param_def
try:
required_value = param_def[ParameterTestConfigKey.VALUE]
# Only test the equality if the parameter has a value. Test for required parameters
# happens in assert_parameter_set
if(param_value != None):
self.assertEqual(param_value, required_value, msg="%s value not equal: %s != %s" % (param_name, repr(param_value), repr(required_value)))
except KeyError:
# Ignore key errors
pass
def assert_parameter_types(self, sample_values, param_dict):
"""
Verify all parameters in the sample_dict are of the same type as described in the param_dict
@param sample_dict: parsed data particle to inspect
@param param_dict: dictionary containing parameter validation information
"""
for (param_name, param_value) in sample_values.items():
log.debug("Data Particle Parameter (%s): %s", param_name, type(param_value))
# get the parameter type
param_def = param_dict.get(param_name)
self.assertIsNotNone(param_def)
if(isinstance(param_def, dict)):
param_type = param_def.get(ParameterTestConfigKey.TYPE)
self.assertIsNotNone(type)
else:
param_type = param_def
# is this a required parameter
if(isinstance(param_def, dict)):
required = param_def.get(ParameterTestConfigKey.REQUIRED, True)
else:
required = param_def
if(required):
self.assertIsNotNone(param_value, msg="%s required field None" % param_name)
if(param_value):
# It looks like one of the interfaces between services converts unicode to string
# and vice versa. So if the type is string it can be promoted to unicode so it
# is still valid.
if (param_type == long and isinstance(param_value, int)):
# we want type Long, but it is a int instance. All good
pass
elif (param_type == unicode and isinstance(param_value, str)):
# we want type unicode, but it is a string instance. All good
pass
else:
self.assertIsInstance(param_value, param_type)
def assert_driver_schema(self, driver, parameters, capabilities, options=None):
"""
Verify that our driver schema returns the correct values. If it does not then there is a
mismatch in the param dict.
@param driver driver object
@param parameters dictionary containing information about driver parameters
@param capabilities dictionary containing information about driver capabilities
@param options dictionary containing information about driver options
"""
# This has to come from the protocol so None is returned until we
# initialize
self.assert_initialize_driver(driver)
config_json = driver.get_config_metadata()
self.assertIsNotNone(config_json)
config = json.loads(config_json)
pp = PrettyPrinter()
log.debug("Config: %s", pp.pformat(config))
self.assert_driver_schema_parameters(config, parameters)
self.assert_driver_schema_capabilities(config, capabilities)
self.assert_driver_schema_options(config, options)
def assert_driver_schema_parameters(self, config, parameters):
"""
verify the parameters returned in the config match the expected parameters passed in.
@param config driver schema dictionary
@param parameters dictionary from test mixin describing expected parameters.
"""
log.debug("Verify driver schema - parameters")
parameter_dict = config.get(ConfigMetadataKey.PARAMETERS)
self.assertIsNotNone(parameter_dict)
self.assertIsInstance(parameters, dict)
self.assert_driver_schema_parameters_keys(parameter_dict, parameters)
for key in parameter_dict.keys():
log.debug("verify driver parameter %s", key)
config_parameter = parameter_dict.get(key)
expected_parameter = parameters.get(key)
self.assertIsNotNone(config_parameter)
self.assertIsNotNone(expected_parameter)
self.assert_schema_parameter_type(key, config_parameter, expected_parameter)
self.assert_schema_parameter_read_only(key, config_parameter, expected_parameter)
self.assert_schema_parameter_metadata(key, config_parameter)
self.assert_schema_value_metadata(key, config_parameter)
def assert_driver_schema_parameters_keys(self, config, parameters):
"""
verify config returned has the same keys as the expected parameters
@param config driver schema dictionary
@param parameters dictionary from test mixin describing expected parameters.
"""
log.debug("Verify driver parameter sets match")
self.assertIsInstance(config, dict)
self.assertIsInstance(parameters, dict)
self.assertEqual(sorted(config.keys()), sorted(parameters.keys()))
def assert_schema_parameter_type(self, name, config_parameter, expected_parameter):
"""
verify config returned describes the type properly
@param config_parameter parameter as returned from the schema
@param expected_parameters dictionary with expected parameter info
"""
log.debug("Verify driver parameter type is defined correctly")
value_dict = config_parameter.get(ParameterDictKey.VALUE)
self.assertIsNotNone(value_dict)
value_type = value_dict.get(ParameterDictKey.TYPE)
self.assertIsNotNone(value_type, 'value type for %s not define' % name)
log.debug("parameter '%s' type: %s", name, value_type)
if(value_type == ParameterDictType.FLOAT):
param_type = float
elif(value_type == ParameterDictType.INT):
param_type = int
elif(value_type == ParameterDictType.LIST):
param_type = list
elif(value_type == ParameterDictType.STRING):
param_type = str
elif(value_type == ParameterDictType.BOOL):
param_type = bool
else:
self.fail("Unknown parameter type: %s" % type)
expected_type = expected_parameter.get(ParameterTestConfigKey.TYPE)
self.assertIsNotNone(expected_type)
self.assertEqual(expected_type, param_type, msg="Type mismatch: %s expected type %s, defined type %s" % (name, expected_type, param_type))
def assert_schema_parameter_read_only(self, name, config_parameter, expected_parameter):
"""
verify config returned describes the read only parameters properly
@param name parameter name
@param config_parameter parameter as returned from the schema
@param expected_parameters dictionary with expected parameter info
"""
param_visibility = config_parameter.get(ParameterDictKey.VISIBILITY)
self.assertIsNotNone(param_visibility)
read_only = expected_parameter.get(ParameterTestConfigKey.READONLY, False)
log.debug("Key: %s, Expected Read-Only: %s, schema visibility: %s", name, read_only, param_visibility)
if(param_visibility == ParameterDictVisibility.READ_ONLY or
param_visibility == ParameterDictVisibility.IMMUTABLE):
self.assertTrue(read_only, "%s is NOT defined as read-only" % name)
else:
self.assertFalse(read_only, "%s is defined as read-only" % name)
def assert_schema_parameter_metadata(self, name, config_parameter):
"""
verify parameter has required metadata
@param name parameter name
@param config_parameter parameter as returned from the schema
@param expected_parameters dictionary with expected parameter info
"""
display_name = config_parameter.get(ParameterDictKey.DISPLAY_NAME)
self.assertIsNotNone(display_name, "%s has no name defined" % name)
def assert_schema_value_metadata(self, name, config_parameter):
"""
verify value has required metadata
@param name parameter name
@param config_parameter parameter as returned from the schema
@param expected_parameters dictionary with expected parameter info
"""
value = config_parameter.get(ParameterDictKey.VALUE)
self.assertIsNotNone(value, "%s has no value dict defined")
self.assertIsInstance(value, dict)
# nothing more to check here at the moment. Type has already been verified
def assert_driver_schema_capabilities(self, config, capabilities):
"""
verify the parameters returned in the config match the expected capabilities passed in.
@param config driver schema dictionary
@param capabilities dictionary from test mixin describing expected capabilities.
"""
log.debug("Verify driver schema - capabilites")
capability_dict = config.get(ConfigMetadataKey.COMMANDS)
self.assertIsNotNone(capability_dict)
self.assertEqual(sorted(capability_dict.keys()), sorted(capabilities.keys()))
for key in capability_dict.keys():
log.debug("verify driver capability %s", key)
capability = capability_dict.get(key)
self.assertIsInstance(capability, dict)
self.assert_driver_schema_capability_metadata(key, capability)
def assert_driver_schema_capability_metadata(self, name, capability):
"""
verify required values exist in the schema
@param name capability name we are checking
@param capability schema record
"""
log.debug("Verify capability metadata - %s", name)
display_name = capability.get(CommandDictKey.DISPLAY_NAME)
self.assertIsNotNone(display_name, "%s display name not defined in the command dict" % name)
timeout = capability.get(CommandDictKey.TIMEOUT)
self.assertIsNotNone(timeout)
self.assertIsInstance(timeout, int)
def assert_driver_schema_options(self, config, options):
"""
verify the parameters returned in the config match the expected options passed in.
@param config driver schema dictionary
@param options dictionary from test mixin describing expected options
"""
log.debug("Verify driver schema - options")
option_dict = config.get(ConfigMetadataKey.DRIVER)
self.assertIsNotNone(option_dict)
vendor_da_support = option_dict.get(DriverDictKey.VENDOR_SW_COMPATIBLE)
self.assertIsNotNone(vendor_da_support, "%s not defined in driver options" % DriverDictKey.VENDOR_SW_COMPATIBLE)
def assert_metadata_generation(self, instrument_params=None, commands=None):
"""
Test that we can generate metadata information for the driver,
commands, and parameters. Needs a driver to exist first. Metadata
can come from any source (file or code).
@param instrumnet_params The list of parameters to compare with the parameter
metadata being generated. Could be from an enum class's list() method.
@param commands The list of commands to compare with the command
metadata being generated. Could be from an enum class's list() method
"""
json_result = self.driver_client.cmd_dvr("get_config_metadata")
self.assert_(json_result != None)
self.assert_(len(json_result) > 100) # just make sure we have something...
result = json.loads(json_result)
log.debug("Metadata JSON response: %s", json_result)
self.assert_(result != None)
self.assert_(isinstance(result, dict))
# simple driver metadata check
self.assertTrue(result[ConfigMetadataKey.DRIVER])
self.assertTrue(result[ConfigMetadataKey.DRIVER][DriverDictKey.VENDOR_SW_COMPATIBLE])
# param metadata check
self.assertTrue(result[ConfigMetadataKey.PARAMETERS])
keys = result[ConfigMetadataKey.PARAMETERS].keys()
keys.append(DriverParameter.ALL) # toss that in there to match up
keys.sort()
enum_list = instrument_params
enum_list.sort()
self.assertEqual(keys, enum_list)
# command metadata check
self.assertTrue(result[ConfigMetadataKey.COMMANDS])
keys = result[ConfigMetadataKey.COMMANDS].keys()
keys.sort()
enum_list = commands
enum_list.sort()
self.assertEqual(keys, enum_list)
class InstrumentDriverTestCase(MiIntTestCase):
"""
Base class for instrument driver tests
"""
# configuration singleton
test_config = InstrumentDriverTestConfig()
@classmethod
def initialize(cls, *args, **kwargs):
"""
Initialize the test_configuration singleton
"""
cls.test_config.initialize(*args,**kwargs)
# Port agent process object.
port_agent = None
def setUp(self):
"""
@brief Setup test cases.
"""
log.debug("*********************************************************************")
log.debug("Starting Test %s", self._testMethodName)
log.debug("*********************************************************************")
log.debug("ID: %s", self.id())
log.debug("InstrumentDriverTestCase setUp")
# Test to ensure we have initialized our test config
if not self.test_config.initialized:
return TestNotInitialized(msg="Tests non initialized. Missing InstrumentDriverTestCase.initalize(...)?")
self.clear_events()
def tearDown(self):
"""
@brief Test teardown
"""
log.debug("InstrumentDriverTestCase tearDown")
def get_ntp_timestamp(self, unix_time=None):
"""
Get an ntp timestamp using the passed in unix_time
or the current time if not passed
@param unix_time: unix timestamp to create
@return: ntp timestamp
"""
if(unix_time == None):
unix_time = time.time()
return ntplib.system_to_ntp_time(time.time())
def clear_events(self):
"""
@brief Clear the event list.
"""
self.events = []
def get_events(self, type=None):
"""
return a list of events received. If a type is passed then the list
will only contain events of that type.
@param type: type of event we are looking for
"""
if(type == None):
return self.events
else:
return [evt for evt in self.events if evt['type']==type]
def get_sample_events(self, type=None):
"""
Get a list of sample events, potentially of a passed in type
@param type: what type of data particle are we looking for
@return: list of data sample events
"""
samples = self.get_events(DriverAsyncEvent.SAMPLE)
if(type == None):
return samples
else:
result = []
for evt in samples:
value = evt.get('value')
particle = json.loads(value)
if(particle and particle.get('stream_name') == type):
result.append(evt)
return result
def event_received(self, evt):
"""
@brief Simple callback to catch events from the driver for verification.
"""
self.events.append(evt)
@classmethod
def comm_config_file(cls):
"""
@brief Return the path the the driver comm config yaml file.
@return if comm_config.yml exists return the full path
"""
repo_dir = Config().get('working_repo')
driver_path = cls.test_config.driver_module
p = re.compile('\.')
driver_path = p.sub('/', driver_path)
abs_path = "%s/%s/%s" % (repo_dir, os.path.dirname(driver_path), CommConfig.config_filename())
log.debug(abs_path)
return abs_path
@classmethod
def get_comm_config(cls):
"""
@brief Create the comm config object by reading the comm_config.yml file.
"""
log.info("get comm config")
config_file = cls.comm_config_file()
log.debug( " -- reading comm config from: %s" % config_file )
if not os.path.exists(config_file):
raise TestNoCommConfig(msg="Missing comm config. Try running start_driver or switch_driver")
return CommConfig.get_config_from_file(config_file)
def port_agent_config(self):
"""
return the port agent configuration
"""
comm_config = self.get_comm_config()
if ConfigTypes.SERIAL == comm_config.method():
config = {
'port_agent_addr': comm_config.host,
'device_os_port': comm_config.device_os_port,
'device_baud': comm_config.device_baud,
'device_data_bits': comm_config.device_data_bits,
'device_stop_bits': comm_config.device_stop_bits,
'device_flow_control': comm_config.device_flow_control,
'device_parity': comm_config.device_parity,
'command_port': comm_config.command_port,
'data_port': comm_config.data_port,
'telnet_sniffer_port': comm_config.sniffer_port,
'process_type': PortAgentProcessType.UNIX,
'log_level': 5,
}
else:
config = {
'port_agent_addr' : comm_config.host,
'device_addr' : comm_config.device_addr,
'command_port': comm_config.command_port,
'data_port': comm_config.data_port,
'telnet_sniffer_port': comm_config.sniffer_port,
'process_type': PortAgentProcessType.UNIX,
'log_level': 5,
}
config['instrument_type'] = comm_config.method()
if ConfigTypes.BOTPT == comm_config.config_type:
config['instrument_type'] = ConfigTypes.BOTPT
config['device_tx_port'] = comm_config.device_tx_port
config['device_rx_port'] = comm_config.device_rx_port
elif ConfigTypes.ETHERNET == comm_config.config_type:
config['device_port'] = comm_config.device_port
if(comm_config.sniffer_prefix): config['telnet_sniffer_prefix'] = comm_config.sniffer_prefix
if(comm_config.sniffer_suffix): config['telnet_sniffer_suffix'] = comm_config.sniffer_suffix
return config
def init_port_agent(self):
"""
@brief Launch the driver process and driver client. This is used in the
integration and qualification tests. The port agent abstracts the physical
interface with the instrument.
@retval return the pid to the logger process
"""
if(self.port_agent):
log.error("Port agent already initialized")
return
log.debug("Startup Port Agent")
config = self.port_agent_config()
log.debug("port agent config: %s", config)
port_agent = PortAgentProcess.launch_process(config, timeout = 60, test_mode = True)
port = port_agent.get_data_port()
pid = port_agent.get_pid()
if(self.get_comm_config().host == LOCALHOST):
log.info('Started port agent pid %s listening at port %s' % (pid, port))
else:
log.info("Connecting to port agent on host: %s, port: %s", self.get_comm_config().host, port)
self.addCleanup(self.stop_port_agent)
self.port_agent = port_agent
return port
def stop_port_agent(self):
"""
Stop the port agent.
"""
log.info("Stop port agent")
if self.port_agent:
log.debug("found port agent, now stop it")
self.port_agent.stop()
self.port_agent = None
def init_driver_process_client(self):
"""
@brief Launch the driver process and driver client
@retval return driver process and driver client object
"""
log.info("Startup Driver Process")
driver_config = {
'dvr_mod' : self.test_config.driver_module,
'dvr_cls' : self.test_config.driver_class,
'workdir' : self.test_config.working_dir,
'comms_config' : self.port_agent_comm_config(),
'process_type' : (self.test_config.driver_process_type,),