How to use scan method in localstack

Best Python code snippet using localstack_python

BleScanApiTest.py

Source:BleScanApiTest.py Github

copy

Full Screen

1#/usr/bin/env python3.42#3# Copyright (C) 2016 The Android Open Source Project4#5# Licensed under the Apache License, Version 2.0 (the "License"); you may not6# use this file except in compliance with the License. You may obtain a copy of7# the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the14# License for the specific language governing permissions and limitations under15# the License.16"""17Test script to exercise Ble Scan Api's. This exercises all getters and18setters. This is important since there is a builder object that is immutable19after you set all attributes of each object. If this test suite doesn't pass,20then other test suites utilising Ble Scanner will also fail.21"""22from acts.controllers.sl4a_lib import rpc_client23from acts.test_decorators import test_tracker_info24from acts.test_utils.bt.BluetoothBaseTest import BluetoothBaseTest25from acts.test_utils.bt.bt_constants import ble_scan_settings_callback_types26from acts.test_utils.bt.bt_constants import ble_scan_settings_modes27from acts.test_utils.bt.bt_constants import ble_scan_settings_result_types28from acts.test_utils.bt.bt_constants import ble_scan_settings_report_delay_milli_seconds29from acts.test_utils.bt.bt_constants import ble_uuids30class BleScanResultsError(Exception):31 """Error in getting scan results"""32class BleScanVerificationError(Exception):33 """Error in comparing BleScan results"""34class BleSetScanSettingsError(Exception):35 """Error in setting Ble Scan Settings"""36class BleSetScanFilterError(Exception):37 """Error in setting Ble Scan Settings"""38class BleScanApiTest(BluetoothBaseTest):39 def __init__(self, controllers):40 BluetoothBaseTest.__init__(self, controllers)41 self.ad_dut = self.android_devices[0]42 def _format_defaults(self, input):43 """44 Creates a dictionary of default ScanSetting and ScanFilter Values.45 :return: input: dict46 """47 if 'ScanSettings' not in input.keys():48 input['ScanSettings'] = (49 ble_scan_settings_callback_types['all_matches'], 0,50 ble_scan_settings_modes['low_power'],51 ble_scan_settings_result_types['full'])52 if 'ScanFilterManufacturerDataId' not in input.keys():53 input['ScanFilterManufacturerDataId'] = -154 if 'ScanFilterDeviceName' not in input.keys():55 input['ScanFilterDeviceName'] = None56 if 'ScanFilterDeviceAddress' not in input.keys():57 input['ScanFilterDeviceAddress'] = None58 if 'ScanFilterManufacturerData' not in input.keys():59 input['ScanFilterManufacturerData'] = None60 return input61 def validate_scan_settings_helper(self, input, droid):62 """63 Validates each input of the scan settings object that is matches what64 was set or not set such that it matches the defaults.65 :return: False at any point something doesn't match. True if everything66 matches.67 """68 filter_list = droid.bleGenFilterList()69 if 'ScanSettings' in input.keys():70 try:71 droid.bleSetScanSettingsCallbackType(input['ScanSettings'][0])72 droid.bleSetScanSettingsReportDelayMillis(73 input['ScanSettings'][1])74 droid.bleSetScanSettingsScanMode(input['ScanSettings'][2])75 droid.bleSetScanSettingsResultType(input['ScanSettings'][3])76 except rpc_client.Sl4aApiError as error:77 self.log.debug("Set Scan Settings failed with: ".format(error))78 return False79 if 'ScanFilterDeviceName' in input.keys():80 try:81 droid.bleSetScanFilterDeviceName(input['ScanFilterDeviceName'])82 except rpc_client.Sl4aApiError as error:83 self.log.debug("Set Scan Filter Device Name failed with: {}"84 .format(error))85 return False86 if 'ScanFilterDeviceAddress' in input.keys():87 try:88 droid.bleSetScanFilterDeviceAddress(89 input['ScanFilterDeviceAddress'])90 except rpc_client.Sl4aApiError as error:91 self.log.debug("Set Scan Filter Device Address failed with: {}"92 .format(error))93 return False94 if ('ScanFilterManufacturerDataId' in input.keys()95 and 'ScanFilterManufacturerDataMask' in input.keys()):96 try:97 droid.bleSetScanFilterManufacturerData(98 input['ScanFilterManufacturerDataId'],99 input['ScanFilterManufacturerData'],100 input['ScanFilterManufacturerDataMask'])101 except rpc_client.Sl4aApiError as error:102 self.log.debug("Set Scan Filter Manufacturer info with data "103 "mask failed with: {}".format(error))104 return False105 if ('ScanFilterManufacturerDataId' in input.keys()106 and 'ScanFilterManufacturerData' in input.keys()107 and 'ScanFilterManufacturerDataMask' not in input.keys()):108 try:109 droid.bleSetScanFilterManufacturerData(110 input['ScanFilterManufacturerDataId'],111 input['ScanFilterManufacturerData'])112 except rpc_client.Sl4aApiError as error:113 self.log.debug(114 "Set Scan Filter Manufacturer info failed with: "115 "{}".format(error))116 return False117 if ('ScanFilterServiceUuid' in input.keys()118 and 'ScanFilterServiceMask' in input.keys()):119 droid.bleSetScanFilterServiceUuid(input['ScanFilterServiceUuid'],120 input['ScanFilterServiceMask'])121 input = self._format_defaults(input)122 scan_settings_index = droid.bleBuildScanSetting()123 scan_settings = (124 droid.bleGetScanSettingsCallbackType(scan_settings_index),125 droid.bleGetScanSettingsReportDelayMillis(scan_settings_index),126 droid.bleGetScanSettingsScanMode(scan_settings_index),127 droid.bleGetScanSettingsScanResultType(scan_settings_index))128 scan_filter_index = droid.bleBuildScanFilter(filter_list)129 device_name_filter = droid.bleGetScanFilterDeviceName(130 filter_list, scan_filter_index)131 device_address_filter = droid.bleGetScanFilterDeviceAddress(132 filter_list, scan_filter_index)133 manufacturer_id = droid.bleGetScanFilterManufacturerId(134 filter_list, scan_filter_index)135 manufacturer_data = droid.bleGetScanFilterManufacturerData(136 filter_list, scan_filter_index)137 if scan_settings != input['ScanSettings']:138 self.log.debug("Scan Settings did not match. expected: {}, found: "139 "{}".format(input['ScanSettings'], scan_settings))140 return False141 if device_name_filter != input['ScanFilterDeviceName']:142 self.log.debug("Scan Filter device name did not match. expected: "143 "{}, found {}".format(input['ScanFilterDeviceName'],144 device_name_filter))145 return False146 if device_address_filter != input['ScanFilterDeviceAddress']:147 self.log.debug(148 "Scan Filter address name did not match. expected: "149 "{}, found: {}".format(input['ScanFilterDeviceAddress'],150 device_address_filter))151 return False152 if manufacturer_id != input['ScanFilterManufacturerDataId']:153 self.log.debug("Scan Filter manufacturer data id did not match. "154 "expected: {}, found: {}".format(155 input['ScanFilterManufacturerDataId'],156 manufacturer_id))157 return False158 if manufacturer_data != input['ScanFilterManufacturerData']:159 self.log.debug("Scan Filter manufacturer data did not match. "160 "expected: {}, found: {}".format(161 input['ScanFilterManufacturerData'],162 manufacturer_data))163 return False164 if 'ScanFilterManufacturerDataMask' in input.keys():165 manufacturer_data_mask = droid.bleGetScanFilterManufacturerDataMask(166 filter_list, scan_filter_index)167 if manufacturer_data_mask != input['ScanFilterManufacturerDataMask']:168 self.log.debug(169 "Manufacturer data mask did not match. expected:"170 " {}, found: {}".format(171 input['ScanFilterManufacturerDataMask'],172 manufacturer_data_mask))173 return False174 if ('ScanFilterServiceUuid' in input.keys()175 and 'ScanFilterServiceMask' in input.keys()):176 expected_service_uuid = input['ScanFilterServiceUuid']177 expected_service_mask = input['ScanFilterServiceMask']178 service_uuid = droid.bleGetScanFilterServiceUuid(179 filter_list, scan_filter_index)180 service_mask = droid.bleGetScanFilterServiceUuidMask(181 filter_list, scan_filter_index)182 if service_uuid != expected_service_uuid.lower():183 self.log.debug("Service uuid did not match. expected: {}, "184 "found {}".format(expected_service_uuid,185 service_uuid))186 return False187 if service_mask != expected_service_mask.lower():188 self.log.debug("Service mask did not match. expected: {}, "189 "found {}".format(expected_service_mask,190 service_mask))191 return False192 self.scan_settings_index = scan_settings_index193 self.filter_list = filter_list194 self.scan_callback = droid.bleGenScanCallback()195 return True196 @BluetoothBaseTest.bt_test_wrap197 @test_tracker_info(uuid='5ffc9f7b-c261-4bf0-9a6b-7fda182b6c97')198 def test_start_ble_scan_with_default_settings(self):199 """Test LE scan with default settings.200 Test to validate all default scan settings values.201 Steps:202 1. Create LE scan objects.203 2. Start LE scan.204 Expected Result:205 Scan starts successfully and matches expected settings.206 Returns:207 Pass if True208 Fail if False209 TAGS: LE, Scanning210 Priority: 1211 """212 input = {}213 return self.validate_scan_settings_helper(input, self.ad_dut.droid)214 @BluetoothBaseTest.bt_test_wrap215 @test_tracker_info(uuid='88c3b0cb-b4d4-45d1-be25-9855290a6d03')216 def test_stop_ble_scan_default_settings(self):217 """Test stopping an LE scan.218 Test default scan settings on an actual scan. Verify it can also stop219 the scan.220 Steps:221 1. Validate default scan settings.222 2. Start ble scan.223 3. Stop ble scan.224 Expected Result:225 LE scan is stopped successfully.226 Returns:227 Pass if True228 Fail if False229 TAGS: LE, Scanning230 Priority: 0231 """232 input = {}233 test_result = self.validate_scan_settings_helper(234 input, self.ad_dut.droid)235 if not test_result:236 self.log.error("Could not setup ble scanner.")237 return test_result238 self.ad_dut.droid.bleStartBleScan(239 self.filter_list, self.scan_settings_index, self.scan_callback)240 try:241 self.ad_dut.droid.bleStopBleScan(self.scan_callback)242 except BleScanResultsError as error:243 self.log.error(str(error))244 test_result = False245 return test_result246 @BluetoothBaseTest.bt_test_wrap247 @test_tracker_info(uuid='5aa7a4c2-0b7d-4000-a980-f00c9329a7b9')248 def test_scan_settings_callback_type_all_matches(self):249 """Test LE scan settings callback type all matches.250 Test scan settings callback type all matches.251 Steps:252 1. Validate the scan settings callback type with all other settings set253 to their respective defaults.254 Expected Result:255 Expected Scan settings should match found scan settings.256 Returns:257 Pass if True258 Fail if False259 TAGS: LE, Scanning260 Priority: 1261 """262 input = {}263 input["ScanSettings"] = (264 ble_scan_settings_callback_types['all_matches'], 0,265 ble_scan_settings_modes['low_power'],266 ble_scan_settings_result_types['full'])267 return self.validate_scan_settings_helper(input, self.ad_dut.droid)268 @BluetoothBaseTest.bt_test_wrap269 @test_tracker_info(uuid='fd764861-aa76-480e-b2d2-5d55a888d123')270 def test_scan_settings_set_callback_type_first_match(self):271 """Test LE scan settings callback type first match272 Test scan settings callback type first match.273 Steps:274 1. Validate the scan settings callback type with all other settings set275 to their respective defaults.276 Expected Result:277 Expected Scan settings should match found scan settings.278 Returns:279 Pass if True280 Fail if False281 TAGS: LE, Scanning282 Priority: 1283 """284 input = {}285 input["ScanSettings"] = (286 ble_scan_settings_callback_types['first_match'], 0,287 ble_scan_settings_modes['low_power'],288 ble_scan_settings_result_types['full'])289 test_result = self.validate_scan_settings_helper(290 input, self.ad_dut.droid)291 return test_result292 @BluetoothBaseTest.bt_test_wrap293 @test_tracker_info(uuid='52e4626e-199c-4755-b9f1-8b38ecb30896')294 def test_scan_settings_set_callback_type_match_lost(self):295 """Test LE scan settings callback type match lost.296 Test scan settings callback type match lost.297 Steps:298 1. Validate the scan settings callback type with all other settings set299 to their respective defaults.300 Expected Result:301 Expected Scan settings should match found scan settings.302 Returns:303 Pass if True304 Fail if False305 TAGS: LE, Scanning306 Priority: 1307 """308 input = {}309 input["ScanSettings"] = (310 ble_scan_settings_callback_types['match_lost'], 0,311 ble_scan_settings_modes['low_power'],312 ble_scan_settings_result_types['full'])313 test_result = self.validate_scan_settings_helper(314 input, self.ad_dut.droid)315 return test_result316 @BluetoothBaseTest.bt_test_wrap317 @test_tracker_info(uuid='57476b3c-ba7a-4342-86f6-1b56b2c00181')318 def test_scan_settings_set_invalid_callback_type(self):319 """Test LE scan settings invalid callback type.320 Test scan settings invalid callback type -1.321 Steps:322 1. Build a LE ScanSettings object with an invalid callback type.323 Expected Result:324 Api should fail to build object.325 Returns:326 Pass if True327 Fail if False328 TAGS: LE, Scanning329 Priority: 2330 """331 input = {}332 input["ScanSettings"] = (-1, 0, ble_scan_settings_modes['low_power'],333 ble_scan_settings_result_types['full'])334 test_result = self.validate_scan_settings_helper(335 input, self.ad_dut.droid)336 return not test_result337 @BluetoothBaseTest.bt_test_wrap338 @test_tracker_info(uuid='52c80f0c-4f26-4cda-8a6b-291ac52f673a')339 def test_scan_settings_set_scan_mode_low_power(self):340 """Test LE scan settings scan mode low power mode.341 Test scan settings scan mode low power.342 Steps:343 1. Validate the scan settings scan mode with all other settings set to344 their respective defaults.345 Expected Result:346 Expected Scan settings should match found scan settings.347 Returns:348 Pass if True349 Fail if False350 TAGS: LE, Scanning351 Priority: 1352 """353 input = {}354 input["ScanSettings"] = (355 ble_scan_settings_callback_types['all_matches'], 0,356 ble_scan_settings_modes['low_power'],357 ble_scan_settings_result_types['full'])358 test_result = self.validate_scan_settings_helper(359 input, self.ad_dut.droid)360 return test_result361 @BluetoothBaseTest.bt_test_wrap362 @test_tracker_info(uuid='20f4513c-44a7-435d-be4e-03420093297a')363 def test_scan_settings_set_scan_mode_balanced(self):364 """Test LE scan settings scan mode balanced.365 Test scan settings scan mode balanced.366 Steps:367 1. Validate the scan settings scan mode with all other settings set to368 their respective defaults.369 Expected Result:370 Expected Scan settings should match found scan settings.371 Returns:372 Pass if True373 Fail if False374 TAGS: LE, Scanning375 Priority: 1376 """377 input = {}378 input["ScanSettings"] = (379 ble_scan_settings_callback_types['all_matches'], 0,380 ble_scan_settings_modes['balanced'],381 ble_scan_settings_result_types['full'])382 return self.validate_scan_settings_helper(input, self.ad_dut.droid)383 @BluetoothBaseTest.bt_test_wrap384 @test_tracker_info(uuid='bf14e7fd-853b-4833-8fef-8c4bd629374b')385 def test_scan_settings_set_scan_mode_low_latency(self):386 """Test LE scan settings scan mode low latency.387 Test scan settings scan mode low latency.388 Steps:389 1. Validate the scan settings scan mode with all other settings set to390 their respective defaults.391 Expected Result:392 Expected Scan settings should match found scan settings.393 Returns:394 Pass if True395 Fail if False396 TAGS: LE, Scanning397 Priority: 1398 """399 input = {}400 input["ScanSettings"] = (401 ble_scan_settings_callback_types['all_matches'], 0,402 ble_scan_settings_modes['low_latency'],403 ble_scan_settings_result_types['full'])404 return self.validate_scan_settings_helper(input, self.ad_dut.droid)405 @BluetoothBaseTest.bt_test_wrap406 @test_tracker_info(uuid='9f3b2e10-98f8-4d6a-b6b6-e8dee87063f0')407 def test_scan_settings_set_invalid_scan_mode(self):408 """Test LE scan settings scan mode as an invalid value.409 Test scan settings invalid scan mode -2.410 Steps:411 1. Set the scan settings scan mode to -2.412 Expected Result:413 Building the ScanSettings object should fail.414 Returns:415 Pass if True416 Fail if False417 TAGS: LE, Scanning418 Priority: 1419 """420 input = {}421 input["ScanSettings"] = (422 ble_scan_settings_callback_types['all_matches'], 0, -2,423 ble_scan_settings_result_types['full'])424 return not self.validate_scan_settings_helper(input, self.ad_dut.droid)425 @BluetoothBaseTest.bt_test_wrap426 @test_tracker_info(uuid='cb246be7-4fef-4313-964d-5fb6dbe558c8')427 def test_scan_settings_set_report_delay_millis_min(self):428 """Test scan settings report delay millis as min value429 Test scan settings report delay millis min acceptable value.430 Steps:431 1. Validate the scan settings report delay millis with all other432 settings set to their respective defaults.433 Expected Result:434 Expected Scan settings should match found scan settings.435 Returns:436 Pass if True437 Fail if False438 TAGS: LE, Scanning439 Priority: 2440 """441 input = {}442 input["ScanSettings"] = (443 ble_scan_settings_callback_types['all_matches'],444 ble_scan_settings_report_delay_milli_seconds['min'],445 ble_scan_settings_modes['low_power'],446 ble_scan_settings_result_types['full'])447 return self.validate_scan_settings_helper(input, self.ad_dut.droid)448 @BluetoothBaseTest.bt_test_wrap449 @test_tracker_info(uuid='db1ea8f6-503d-4e9a-b61a-01210508c5a2')450 def test_scan_settings_set_report_delay_millis_min_plus_one(self):451 """Test scan settings report delay millis as min value plus one.452 Test scan settings report delay millis as min value plus one.453 Steps:454 1. Validate the scan settings report delay millis with all other455 settings set to their respective defaults.456 Expected Result:457 Expected Scan settings should match found scan settings.458 Returns:459 Pass if True460 Fail if False461 TAGS: LE, Scanning462 Priority: 4463 """464 input = {}465 input["ScanSettings"] = (466 ble_scan_settings_callback_types['all_matches'],467 ble_scan_settings_report_delay_milli_seconds['min'] + 1,468 ble_scan_settings_modes['low_power'],469 ble_scan_settings_result_types['full'])470 return self.validate_scan_settings_helper(input, self.ad_dut.droid)471 @BluetoothBaseTest.bt_test_wrap472 @test_tracker_info(uuid='54e83ff8-92b0-473e-839a-1ff1c7dcea83')473 def test_scan_settings_set_report_delay_millis_max(self):474 """Test scan settings report delay millis as max value.475 Test scan settings report delay millis max value.476 Steps:477 1. Validate the scan settings report delay millis with all other478 settings set to their respective defaults.479 Expected Result:480 Expected Scan settings should match found scan settings.481 Returns:482 Pass if True483 Fail if False484 TAGS: LE, Scanning485 Priority: 3486 """487 input = {}488 input["ScanSettings"] = (489 ble_scan_settings_callback_types['all_matches'],490 ble_scan_settings_report_delay_milli_seconds['max'],491 ble_scan_settings_modes['low_power'],492 ble_scan_settings_result_types['full'])493 return self.validate_scan_settings_helper(input, self.ad_dut.droid)494 @BluetoothBaseTest.bt_test_wrap495 @test_tracker_info(uuid='45d918ec-7e43-463b-8f07-f009f8808903')496 def test_scan_settings_set_report_delay_millis_max_minus_one(self):497 """Test scan settings report delay millis as max value minus one.498 Test scan settings report delay millis max value - 1.499 Steps:500 1. Validate the scan settings report delay millis with all other501 settings set to their respective defaults.502 Expected Result:503 Expected Scan settings should match found scan settings.504 Returns:505 Pass if True506 Fail if False507 TAGS: LE, Scanning508 Priority: 3509 """510 input = {}511 input["ScanSettings"] = (512 ble_scan_settings_callback_types['all_matches'],513 ble_scan_settings_report_delay_milli_seconds['max'] - 1,514 ble_scan_settings_modes['low_power'],515 ble_scan_settings_result_types['full'])516 return self.validate_scan_settings_helper(input, self.ad_dut.droid)517 @BluetoothBaseTest.bt_test_wrap518 @test_tracker_info(uuid='eb94b5ee-f2e7-4322-b3df-7bdd3a250262')519 def test_scan_settings_set_invalid_report_delay_millis_min_minus_one(self):520 """Test scan settings report delay millis as an invalid value.521 Test scan settings invalid report delay millis min value - 1.522 Steps:523 1. Set scan settings report delay millis to min value -1.524 2. Build scan settings object.525 Expected Result:526 Building scan settings object should fail.527 Returns:528 Pass if True529 Fail if False530 TAGS: LE, Scanning531 Priority: 2532 """533 droid = self.ad_dut.droid534 input = {}535 input["ScanSettings"] = (536 ble_scan_settings_callback_types['all_matches'],537 ble_scan_settings_report_delay_milli_seconds['min'] - 1,538 ble_scan_settings_modes['low_power'],539 ble_scan_settings_result_types['full'])540 return not self.validate_scan_settings_helper(input, droid)541 @BluetoothBaseTest.bt_test_wrap542 @test_tracker_info(uuid='8f5a2bd0-6037-4ac6-a962-f11e7fc13920')543 def test_scan_settings_set_scan_result_type_full(self):544 """Test scan settings result type full.545 Test scan settings result type full.546 Steps:547 1. Validate the scan settings result type with all other settings548 set to their respective defaults.549 Expected Result:550 Expected Scan settings should match found scan settings.551 Returns:552 Pass if True553 Fail if False554 TAGS: LE, Scanning555 Priority: 1556 """557 input = {}558 input["ScanSettings"] = (559 ble_scan_settings_callback_types['all_matches'], 0,560 ble_scan_settings_modes['low_power'],561 ble_scan_settings_result_types['full'])562 return self.validate_scan_settings_helper(input, self.ad_dut.droid)563 @BluetoothBaseTest.bt_test_wrap564 @test_tracker_info(uuid='610fe301-600e-443e-a28b-cd722cc8a4c1')565 def test_scan_settings_set_scan_result_type_abbreviated(self):566 """Test scan settings result type abbreviated.567 Test scan settings result type abbreviated.568 Steps:569 1. Validate the scan settings result type with all other settings570 set to their respective defaults.571 Expected Result:572 Expected Scan settings should match found scan settings.573 Returns:574 Pass if True575 Fail if False576 TAGS: LE, Scanning577 Priority: 1578 """579 input = {}580 input["ScanSettings"] = (581 ble_scan_settings_callback_types['all_matches'], 0,582 ble_scan_settings_modes['low_power'],583 ble_scan_settings_result_types['abbreviated'])584 return self.validate_scan_settings_helper(input, self.ad_dut.droid)585 @BluetoothBaseTest.bt_test_wrap586 @test_tracker_info(uuid='ed58430b-8180-472f-a118-64f5fce5e84c')587 def test_scan_settings_set_invalid_scan_result_type(self):588 """Test scan settings result type as an invalid value.589 Test scan settings invalid result type -1.590 Steps:591 1. Set scan settings result type as an invalid value.592 2. Build scan settings object.593 Expected Result:594 Expected Scan settings should match found scan settings.595 Returns:596 Pass if True597 Fail if False598 TAGS: LE, Scanning599 Priority: 2600 """601 input = {}602 input["ScanSettings"] = (603 ble_scan_settings_callback_types['all_matches'], 0,604 ble_scan_settings_modes['low_power'], -1)605 return not self.validate_scan_settings_helper(input, self.ad_dut.droid)606 @BluetoothBaseTest.bt_test_wrap607 @test_tracker_info(uuid='6489665f-313d-4b1b-bd7f-f0fdeeaad335')608 def test_scan_filter_set_device_name(self):609 """Test scan filter set valid device name.610 Test scan filter device name sl4atest.611 Steps:612 1. Validate the scan filter device name with all other settings613 set to their respective defaults.614 Expected Result:615 Expected Scan filter should match found scan settings.616 Returns:617 Pass if True618 Fail if False619 TAGS: LE, Scanning620 Priority: 1621 """622 input = {}623 input['ScanFilterDeviceName'] = "sl4atest"624 return self.validate_scan_settings_helper(input, self.ad_dut.droid)625 @BluetoothBaseTest.bt_test_wrap626 @test_tracker_info(uuid='76021a9a-14ca-4a2f-a908-96ab90db39ce')627 def test_scan_filter_set_device_name_blank(self):628 """Test scan filter set blank device name.629 Test scan filter device name blank.630 Steps:631 1. Validate the scan filter device name with all other settings632 set to their respective defaults.633 Expected Result:634 Expected Scan filter should match found scan filter.635 Returns:636 Pass if True637 Fail if False638 TAGS: LE, Scanning639 Priority: 1640 """641 droid = self.ad_dut.droid642 input = {}643 input['ScanFilterDeviceName'] = ""644 return self.validate_scan_settings_helper(input, droid)645 @BluetoothBaseTest.bt_test_wrap646 @test_tracker_info(uuid='d77c3d81-43a9-4572-a99b-87969117ede5')647 def test_scan_filter_set_device_name_special_chars(self):648 """Test scan filter set device name as special chars.649 Test scan filter device name special characters.650 Steps:651 1. Validate the scan filter device name with all other settings652 set to their respective defaults.653 Expected Result:654 Expected Scan filter should match found scan filter.655 Returns:656 Pass if True657 Fail if False658 TAGS: LE, Scanning659 Priority: 1660 """661 input = {}662 input['ScanFilterDeviceName'] = "!@#$%^&*()\":<>/"663 return self.validate_scan_settings_helper(input, self.ad_dut.droid)664 @BluetoothBaseTest.bt_test_wrap665 @test_tracker_info(uuid='1697004e-76ab-444b-9419-0437e30444ad')666 def test_scan_filter_set_device_address(self):667 """Test scan filter set valid device address.668 Test scan filter device address valid.669 Steps:670 1. Validate the scan filter device address with all other settings671 set to their respective defaults.672 Expected Result:673 Expected Scan filter should match found scan filter.674 Returns:675 Pass if True676 Fail if False677 TAGS: LE, Scanning678 Priority: 1679 """680 input = {}681 input['ScanFilterDeviceAddress'] = "01:02:03:AB:CD:EF"682 return self.validate_scan_settings_helper(input, self.ad_dut.droid)683 @BluetoothBaseTest.bt_test_wrap684 @test_tracker_info(uuid='eab0409c-7fc5-4d1f-8fbe-5ee2bb743f7e')685 def test_scan_filter_set_invalid_device_address_lower_case(self):686 """Test scan filter set invalid device address.687 Test scan filter device address lower case.688 Steps:689 1. Set the scan filter address to an invalid, lowercase mac address690 Expected Result:691 Api to build scan filter should fail.692 Returns:693 Pass if True694 Fail if False695 TAGS: LE, Scanning696 Priority: 2697 """698 input = {}699 input['ScanFilterDeviceAddress'] = "01:02:03:ab:cd:ef"700 return not self.validate_scan_settings_helper(input, self.ad_dut.droid)701 @BluetoothBaseTest.bt_test_wrap702 @test_tracker_info(uuid='0ec491ac-d273-468e-bbfe-e36a290aeb2a')703 def test_scan_filter_set_invalid_device_address_blank(self):704 """Test scan filter set invalid device address.705 Test scan filter invalid device address blank.706 Steps:707 1. Set the scan filter address to an invalid, blank mac address708 Expected Result:709 Api to build scan filter should fail.710 Returns:711 Pass if True712 Fail if False713 TAGS: LE, Scanning714 Priority: 2715 """716 input = {}717 input['ScanFilterDeviceAddress'] = ""718 test_result = self.validate_scan_settings_helper(719 input, self.ad_dut.droid)720 return not test_result721 @BluetoothBaseTest.bt_test_wrap722 @test_tracker_info(uuid='5cebc454-091c-4e46-b200-1e52c8dffbec')723 def test_scan_filter_set_invalid_device_address_bad_format(self):724 """Test scan filter set badly formatted device address.725 Test scan filter badly formatted device address.726 Steps:727 1. Set the scan filter address to an invalid, blank mac address728 Expected Result:729 Api to build scan filter should fail.730 Returns:731 Pass if True732 Fail if False733 TAGS: LE, Scanning734 Priority: 2735 """736 input = {}737 input['ScanFilterDeviceAddress'] = "10.10.10.10.10"738 return not self.validate_scan_settings_helper(input, self.ad_dut.droid)739 @BluetoothBaseTest.bt_test_wrap740 @test_tracker_info(uuid='d5249d10-1486-4c38-a22d-1f1b077926db')741 def test_scan_filter_set_invalid_device_address_bad_address(self):742 """Test scan filter device address as an invalid value.743 Test scan filter invalid device address invalid characters.744 Steps:745 1. Set a scan filter's device address as ZZ:ZZ:ZZ:ZZ:ZZ:ZZ746 Expected Result:747 Api to build the scan filter should fail.748 Returns:749 Pass if True750 Fail if False751 TAGS: LE, Scanning752 Priority: 1753 """754 input = {}755 input['ScanFilterDeviceAddress'] = "ZZ:ZZ:ZZ:ZZ:ZZ:ZZ"756 return not self.validate_scan_settings_helper(input, self.ad_dut.droid)757 @BluetoothBaseTest.bt_test_wrap758 @test_tracker_info(uuid='65c62d50-69f6-4a0b-bd74-2340e0ce32ca')759 def test_scan_filter_set_manufacturer_id_data(self):760 """Test scan filter manufacturer data.761 Test scan filter manufacturer data with a valid input.762 Steps:763 1. Validate the scan filter manufacturer id with all other settings764 set to their respective defaults.765 Expected Result:766 Expected Scan filter should match found scan filter.767 Returns:768 Pass if True769 Fail if False770 TAGS: LE, Scanning771 Priority: 1772 """773 expected_manufacturer_id = 0774 expected_manufacturer_data = [1, 2, 1, 3, 4, 5, 6]775 input = {}776 input['ScanFilterManufacturerDataId'] = expected_manufacturer_id777 input['ScanFilterManufacturerData'] = expected_manufacturer_data778 return self.validate_scan_settings_helper(input, self.ad_dut.droid)779 @BluetoothBaseTest.bt_test_wrap780 @test_tracker_info(uuid='12807021-9f66-4784-b34a-80859cf4a32f')781 def test_scan_filter_set_manufacturer_id_data_mask(self):782 """Test scan filter manufacturer data mask.783 Test scan filter manufacturer data with a valid data mask.784 Steps:785 1. Validate the scan filter manufacturer id with all other settings786 set to their respective defaults.787 Expected Result:788 Expected Scan filter should match found scan filter.789 Returns:790 Pass if True791 Fail if False792 TAGS: LE, Scanning793 Priority: 1794 """795 expected_manufacturer_id = 1796 expected_manufacturer_data = [1]797 expected_manufacturer_data_mask = [1, 2, 1, 3, 4, 5, 6]798 input = {}799 input['ScanFilterManufacturerDataId'] = expected_manufacturer_id800 input['ScanFilterManufacturerData'] = expected_manufacturer_data801 input[802 'ScanFilterManufacturerDataMask'] = expected_manufacturer_data_mask803 return self.validate_scan_settings_helper(input, self.ad_dut.droid)804 @BluetoothBaseTest.bt_test_wrap805 @test_tracker_info(uuid='980e5ab6-5381-4471-8e5b-0b716665a9b8')806 def test_scan_filter_set_manufacturer_max_id(self):807 """Test scan filter manufacturer data id.808 Test scan filter manufacturer data max id.809 Steps:810 1. Validate the scan filter manufacturer id with all other settings811 set to their respective defaults.812 Expected Result:813 Expected Scan filter should match found scan filter.814 Returns:815 Pass if True816 Fail if False817 TAGS: LE, Scanning818 Priority: 2819 """820 expected_manufacturer_id = 2147483647821 expected_manufacturer_data = [1, 2, 1, 3, 4, 5, 6]822 input = {}823 input['ScanFilterManufacturerDataId'] = expected_manufacturer_id824 input['ScanFilterManufacturerData'] = expected_manufacturer_data825 return self.validate_scan_settings_helper(input, self.ad_dut.droid)826 @BluetoothBaseTest.bt_test_wrap827 @test_tracker_info(uuid='cf0efe38-8621-4288-be26-742719da2f6c')828 def test_scan_filter_set_manufacturer_data_empty(self):829 """Test scan filter empty manufacturer data.830 Test scan filter manufacturer data as empty but valid manufacturer data.831 Steps:832 1. Validate the scan filter manufacturer id with all other settings833 set to their respective defaults.834 Expected Result:835 Expected Scan filter should match found scan filter.836 Returns:837 Pass if True838 Fail if False839 TAGS: LE, Scanning840 Priority: 2841 """842 expected_manufacturer_id = 1843 expected_manufacturer_data = []844 input = {}845 input['ScanFilterManufacturerDataId'] = expected_manufacturer_id846 input['ScanFilterManufacturerData'] = expected_manufacturer_data847 return self.validate_scan_settings_helper(input, self.ad_dut.droid)848 @BluetoothBaseTest.bt_test_wrap849 @test_tracker_info(uuid='7ea0e82e-e92a-469c-8432-8f21978508cb')850 def test_scan_filter_set_manufacturer_data_mask_empty(self):851 """Test scan filter empty manufacturer data mask.852 Test scan filter manufacturer mask empty.853 Steps:854 1. Validate the scan filter manufacturer id with all other settings855 set to their respective defaults.856 Expected Result:857 Expected Scan filter should match found scan filter.858 Returns:859 Pass if True860 Fail if False861 TAGS: LE, Scanning862 Priority: 1863 """864 expected_manufacturer_id = 1865 expected_manufacturer_data = [1, 2, 1, 3, 4, 5, 6]866 expected_manufacturer_data_mask = []867 input = {}868 input['ScanFilterManufacturerDataId'] = expected_manufacturer_id869 input['ScanFilterManufacturerData'] = expected_manufacturer_data870 input[871 'ScanFilterManufacturerDataMask'] = expected_manufacturer_data_mask872 return self.validate_scan_settings_helper(input, self.ad_dut.droid)873 @BluetoothBaseTest.bt_test_wrap874 @test_tracker_info(uuid='88e4a9b8-afae-48cb-873a-fd6b4ef84116')875 def test_scan_filter_set_invalid_manufacturer_min_id_minus_one(self):876 """Test scan filter invalid manufacturer data.877 Test scan filter invalid manufacturer id min value - 1.878 Steps:879 1. Set the scan filters manufacturer id to -1.880 2. Build the scan filter.881 Expected Result:882 Api to build the scan filter should fail.883 Returns:884 Pass if True885 Fail if False886 TAGS: LE, Scanning887 Priority: 2888 """889 expected_manufacturer_id = -1890 expected_manufacturer_data = [1, 2, 1, 3, 4, 5, 6]891 input = {}892 input['ScanFilterManufacturerDataId'] = expected_manufacturer_id893 input['ScanFilterManufacturerData'] = expected_manufacturer_data894 return not self.validate_scan_settings_helper(input, self.ad_dut.droid)895 @BluetoothBaseTest.bt_test_wrap896 @test_tracker_info(uuid='2e8438dc-29cd-4f72-8747-4a161974d4d3')897 def test_scan_filter_set_service_uuid(self):898 """Test scan filter set valid service uuid.899 Test scan filter service uuid.900 Steps:901 1. Validate the scan filter service uuid with all other settings902 set to their respective defaults.903 Expected Result:904 Expected Scan filter should match found scan filter.905 Returns:906 Pass if True907 Fail if False908 TAGS: LE, Scanning909 Priority: 1910 """911 expected_service_uuid = "00000000-0000-1000-8000-00805F9B34FB"912 expected_service_mask = "00000000-0000-1000-8000-00805F9B34FB"913 input = {}914 input['ScanFilterServiceUuid'] = expected_service_uuid915 input['ScanFilterServiceMask'] = expected_service_mask916 return self.validate_scan_settings_helper(input, self.ad_dut.droid)917 @BluetoothBaseTest.bt_test_wrap918 @test_tracker_info(uuid='e07b9985-44b6-4dc4-b570-0833b5d2893c')919 def test_scan_filter_service_uuid_p_service(self):920 """Test scan filter service uuid.921 Test scan filter service uuid p service922 Steps:923 1. Validate the scan filter service uuid with all other settings924 set to their respective defaults.925 Expected Result:926 Expected Scan filter should match found scan filter.927 Returns:928 Pass if True929 Fail if False930 TAGS: LE, Scanning931 Priority: 2932 """933 expected_service_uuid = ble_uuids['p_service']934 expected_service_mask = "00000000-0000-1000-8000-00805F9B34FB"935 self.log.debug("Step 1: Setup environment.")936 input = {}937 input['ScanFilterServiceUuid'] = expected_service_uuid938 input['ScanFilterServiceMask'] = expected_service_mask939 return self.validate_scan_settings_helper(input, self.ad_dut.droid)940 @BluetoothBaseTest.bt_test_wrap941 @test_tracker_info(uuid='0467af19-6e9a-4cfe-9e10-878b0c224df2')942 def test_classic_ble_scan_with_service_uuids_p(self):943 """Test classic LE scan with valid service uuid.944 Test classic ble scan with scan filter service uuid p service uuids.945 Steps:946 1. Validate the scan filter service uuid with all other settings947 set to their respective defaults.948 2. Start classic ble scan.949 3. Stop classic ble scan950 Expected Result:951 Expected Scan filter should match found scan filter.952 Returns:953 Pass if True954 Fail if False955 TAGS: LE, Scanning956 Priority: 1957 """958 droid = self.ad_dut.droid959 service_uuid_list = [ble_uuids['p_service']]960 scan_callback = droid.bleGenLeScanCallback()961 return self.verify_classic_ble_scan_with_service_uuids(962 droid, scan_callback, service_uuid_list)963 @BluetoothBaseTest.bt_test_wrap964 @test_tracker_info(uuid='516c295f-a2df-44f6-b2ad-54451af43ce8')965 def test_classic_ble_scan_with_service_uuids_hr(self):966 """Test classic LE scan with valid service uuid.967 Test classic ble scan with scan filter service uuid hr service968 Steps:969 1. Validate the scan filter service uuid with all other settings970 set to their respective defaults.971 2. Start classic ble scan.972 3. Stop classic ble scan973 Expected Result:974 Expected Scan filter should match found scan filter.975 Returns:976 Pass if True977 Fail if False978 TAGS: LE, Scanning979 Priority: 1980 """981 droid = self.ad_dut.droid982 service_uuid_list = [ble_uuids['hr_service']]983 scan_callback = droid.bleGenLeScanCallback()984 return self.verify_classic_ble_scan_with_service_uuids(985 droid, scan_callback, service_uuid_list)986 @BluetoothBaseTest.bt_test_wrap987 @test_tracker_info(uuid='0458b5e0-bb0b-4d6e-ab79-e21169d3256b')988 def test_classic_ble_scan_with_service_uuids_empty_uuid_list(self):989 """Test classic LE scan with empty but valid uuid list.990 Test classic ble scan with service uuids as empty list.991 Steps:992 1. Validate the scan filter service uuid with all other settings993 set to their respective defaults.994 2. Start classic ble scan.995 3. Stop classic ble scan996 Expected Result:997 Expected Scan filter should match found scan filter.998 Returns:999 Pass if True1000 Fail if False1001 TAGS: LE, Scanning1002 Priority: 11003 """1004 droid = self.ad_dut.droid1005 service_uuid_list = []1006 scan_callback = droid.bleGenLeScanCallback()1007 return self.verify_classic_ble_scan_with_service_uuids(1008 droid, scan_callback, service_uuid_list)1009 @BluetoothBaseTest.bt_test_wrap1010 @test_tracker_info(uuid='c0d84a37-c86c-43c4-9dc7-d16959fdbc2a')1011 def test_classic_ble_scan_with_service_uuids_hr_and_p(self):1012 """Test classic LE scan with multiple service uuids.1013 Test classic ble scan with service uuids a list of hr and p service.1014 Steps:1015 1. Validate the scan filter service uuid with all other settings1016 set to their respective defaults.1017 2. Start classic ble scan.1018 3. Stop classic ble scan1019 Expected Result:1020 Expected Scan filter should match found scan filter.1021 Returns:1022 Pass if True1023 Fail if False1024 TAGS: LE, Scanning1025 Priority: 11026 """1027 droid = self.ad_dut.droid1028 service_uuid_list = [ble_uuids['hr_service'], ble_uuids['p_service']]1029 scan_callback = droid.bleGenLeScanCallback()1030 return self.verify_classic_ble_scan_with_service_uuids(1031 droid, scan_callback, service_uuid_list)1032 def verify_classic_ble_scan_with_service_uuids(self, droid, scan_callback,1033 service_uuid_list):1034 test_result = True1035 try:1036 test_result = droid.bleStartClassicBleScanWithServiceUuids(1037 scan_callback, service_uuid_list)1038 except BleScanResultsError as error:1039 self.log.error(str(error))1040 return False1041 droid.bleStopClassicBleScan(scan_callback)1042 if not test_result:1043 self.log.error(1044 "Start classic ble scan with service uuids return false "1045 "boolean value.")1046 return False...

Full Screen

Full Screen

BleOpportunisticScanTest.py

Source:BleOpportunisticScanTest.py Github

copy

Full Screen

1#/usr/bin/env python3.42#3# Copyright (C) 2016 The Android Open Source Project4#5# Licensed under the Apache License, Version 2.0 (the "License"); you may not6# use this file except in compliance with the License. You may obtain a copy of7# the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the14# License for the specific language governing permissions and limitations under15# the License.16"""17This test script exercises different opportunistic scan scenarios.18It is expected that the second AndroidDevice is able to advertise.19This test script was designed with this setup in mind:20Shield box one: Android Device, Android Device21"""22from queue import Empty23from acts import utils24from acts.test_decorators import test_tracker_info25from acts.test_utils.bt.BluetoothBaseTest import BluetoothBaseTest26from acts.test_utils.bt.bt_constants import ble_scan_settings_modes27from acts.test_utils.bt.bt_constants import ble_scan_settings_modes28from acts.test_utils.bt.bt_test_utils import batch_scan_result29from acts.test_utils.bt.bt_test_utils import cleanup_scanners_and_advertisers30from acts.test_utils.bt.bt_test_utils import generate_ble_advertise_objects31from acts.test_utils.bt.bt_test_utils import generate_ble_scan_objects32from acts.test_utils.bt.bt_test_utils import reset_bluetooth33from acts.test_utils.bt.bt_constants import scan_result34class BleOpportunisticScanTest(BluetoothBaseTest):35 default_timeout = 1036 max_scan_instances = 2737 report_delay = 200038 scan_callbacks = []39 adv_callbacks = []40 active_scan_callback_list = []41 active_adv_callback_list = []42 def __init__(self, controllers):43 BluetoothBaseTest.__init__(self, controllers)44 self.scn_ad = self.android_devices[0]45 self.adv_ad = self.android_devices[1]46 def setup_class(self):47 super(BluetoothBaseTest, self).setup_class()48 utils.set_location_service(self.scn_ad, True)49 utils.set_location_service(self.adv_ad, True)50 return True51 def teardown_test(self):52 cleanup_scanners_and_advertisers(53 self.scn_ad, self.active_scan_callback_list, self.adv_ad,54 self.active_adv_callback_list)55 self.active_adv_callback_list = []56 self.active_scan_callback_list = []57 def on_exception(self, test_name, begin_time):58 reset_bluetooth(self.android_devices)59 def _setup_generic_advertisement(self):60 adv_callback, adv_data, adv_settings = generate_ble_advertise_objects(61 self.adv_ad.droid)62 self.adv_ad.droid.bleStartBleAdvertising(adv_callback, adv_data,63 adv_settings)64 self.active_adv_callback_list.append(adv_callback)65 def _verify_no_events_found(self, event_name):66 try:67 event = self.scn_ad.ed.pop_event(event_name, self.default_timeout)68 self.log.error("Found an event when none was expected: {}".format(69 event))70 return False71 except Empty:72 self.log.info("No scan result found as expected.")73 return True74 @BluetoothBaseTest.bt_test_wrap75 @test_tracker_info(uuid='6bccfbea-3734-4504-8ea9-3511ad17a3e0')76 def test_scan_result_no_advertisement(self):77 """Test opportunistic scan with no advertisement.78 Tests opportunistic scan where there are no advertisements. This should79 not find any onScanResults.80 Steps:81 1. Initialize scanner with scan mode set to opportunistic mode.82 2. Start scanning on dut 083 3. Pop onScanResults event on the scanner84 Expected Result:85 Find no advertisements with the opportunistic scan instance.86 Returns:87 Pass if True88 Fail if False89 TAGS: LE, Advertising, Scanning, Opportunistic Scan90 Priority: 191 """92 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[93 'opportunistic'])94 filter_list, scan_settings, scan_callback = generate_ble_scan_objects(95 self.scn_ad.droid)96 self.scn_ad.droid.bleStartBleScan(filter_list, scan_settings,97 scan_callback)98 self.active_scan_callback_list.append(scan_callback)99 if not self._verify_no_events_found(scan_result.format(scan_callback)):100 return False101 self.scn_ad.droid.bleStopBleScan(scan_callback)102 return True103 @BluetoothBaseTest.bt_test_wrap104 @test_tracker_info(uuid='8430bc57-925c-4b70-a62e-cd34df264ca1')105 def test_batch_scan_result_no_advertisement(self):106 """Test batch opportunistic scan without an advertisement.107 Tests opportunistic scan where there are no advertisements. This should108 not find any onBatchScanResult.109 Steps:110 1. Initialize scanner with scan mode set to opportunistic mode.111 2. Set report delay seconds such that onBatchScanResult events are112 expected113 2. Start scanning on dut 0114 3. Pop onBatchScanResult event on the scanner115 Expected Result:116 Find no advertisements with the opportunistic scan instance.117 Returns:118 Pass if True119 Fail if False120 TAGS: LE, Advertising, Scanning, Opportunistic Scan, Batch Scanning121 Priority: 1122 """123 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[124 'opportunistic'])125 self.scn_ad.droid.bleSetScanSettingsReportDelayMillis(126 self.report_delay)127 filter_list, scan_settings, scan_callback = generate_ble_scan_objects(128 self.scn_ad.droid)129 self.scn_ad.droid.bleStartBleScan(filter_list, scan_settings,130 scan_callback)131 self.active_scan_callback_list.append(scan_callback)132 if not self._verify_no_events_found(133 batch_scan_result.format(scan_callback)):134 return False135 self.scn_ad.droid.bleStopBleScan(scan_callback)136 return True137 @BluetoothBaseTest.bt_test_wrap138 @test_tracker_info(uuid='4613cb67-0f54-494e-8a56-2e8ce56fad41')139 def test_scan_result(self):140 """Test opportunistic scan with an advertisement.141 Tests opportunistic scan where it will only report scan results when142 other registered scanners find results.143 Steps:144 1. Initialize advertiser and start advertisement on dut1145 2. Initialize scanner with scan mode set to opportunistic mode on dut0146 and start scanning147 3. Try to find an event, expect none.148 4. Start a second scanner on dut0, with any other mode set149 5. Pop onScanResults event on the second scanner150 6. Pop onScanResults event on the first scanner151 Expected Result:152 Scan result is found on the opportunistic scan instance.153 Returns:154 Pass if True155 Fail if False156 TAGS: LE, Advertising, Scanning, Opportunistic Scan157 Priority: 1158 """159 self._setup_generic_advertisement()160 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[161 'opportunistic'])162 filter_list, scan_settings, scan_callback = generate_ble_scan_objects(163 self.scn_ad.droid)164 self.scn_ad.droid.bleStartBleScan(filter_list, scan_settings,165 scan_callback)166 self.active_scan_callback_list.append(scan_callback)167 if not self._verify_no_events_found(scan_result.format(scan_callback)):168 return False169 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[170 'low_latency'])171 filter_list2, scan_settings2, scan_callback2 = (172 generate_ble_scan_objects(self.scn_ad.droid))173 self.scn_ad.droid.bleStartBleScan(filter_list2, scan_settings2,174 scan_callback2)175 self.active_scan_callback_list.append(scan_callback2)176 try:177 self.scn_ad.ed.pop_event(178 scan_result.format(scan_callback2), self.default_timeout)179 except Empty:180 self.log.error("Non-Opportunistic scan found no scan results.")181 return False182 try:183 self.scn_ad.ed.pop_event(184 scan_result.format(scan_callback), self.default_timeout)185 except Empty:186 self.log.error("Opportunistic scan found no scan results.")187 return False188 return True189 @BluetoothBaseTest.bt_test_wrap190 @test_tracker_info(uuid='5b46fefc-70ef-48a0-acf4-35077cd72202')191 def test_batch_scan_result(self):192 """Test batch opportunistic scan with advertisement.193 Tests opportunistic scan where it will only report scan results when194 other registered scanners find results. Set the report delay millis such195 that an onBatchScanResult is expected.196 Steps:197 1. Initialize advertiser and start advertisement on dut1198 2. Initialize scanner with scan mode set to opportunistic mode and199 set scan settings report delay seconds such that a batch scan is200 expected201 3. Start scanning on dut 0202 4. Try to find an event, expect none.203 5. Start a second scanner on dut0, with any other mode set and set scan204 settings report delay millis such that an onBatchScanResult is expected205 6. Pop onBatchScanResult event on the second scanner206 7. Pop onBatchScanResult event on the first scanner207 Expected Result:208 Find a batch scan result on both opportunistic scan instances.209 Returns:210 Pass if True211 Fail if False212 TAGS: LE, Advertising, Scanning, Opportunistic Scan, Batch Scanning213 Priority: 1214 """215 self._setup_generic_advertisement()216 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[217 'opportunistic'])218 self.scn_ad.droid.bleSetScanSettingsReportDelayMillis(219 self.report_delay)220 filter_list, scan_settings, scan_callback = generate_ble_scan_objects(221 self.scn_ad.droid)222 self.scn_ad.droid.bleStartBleScan(filter_list, scan_settings,223 scan_callback)224 self.active_scan_callback_list.append(scan_callback)225 if not self._verify_no_events_found(226 batch_scan_result.format(scan_callback)):227 return False228 self.scn_ad.droid.bleSetScanSettingsReportDelayMillis(229 self.report_delay)230 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[231 'low_latency'])232 filter_list2, scan_settings2, scan_callback2 = generate_ble_scan_objects(233 self.scn_ad.droid)234 self.scn_ad.droid.bleStartBleScan(filter_list2, scan_settings2,235 scan_callback2)236 self.active_scan_callback_list.append(scan_callback2)237 try:238 self.scn_ad.ed.pop_event(239 batch_scan_result.format(scan_callback2), self.default_timeout)240 except Empty:241 self.log.error("Non-Opportunistic scan found no scan results.")242 return False243 try:244 self.scn_ad.ed.pop_event(245 batch_scan_result.format(scan_callback), self.default_timeout)246 except Empty:247 self.log.error("Opportunistic scan found no scan results.")248 return False249 return True250 @BluetoothBaseTest.bt_test_wrap251 @test_tracker_info(uuid='fd85d95e-dc8c-48c1-8d8a-83c3475755ff')252 def test_batch_scan_result_not_expected(self):253 """Test opportunistic batch scan without expecting an event.254 Tests opportunistic scan where it will only report scan results when255 other registered scanners find results. Set the report delay millis such256 that a batch scan is not expected.257 Steps:258 1. Initialize advertiser and start advertisement on dut1259 2. Initialize scanner with scan mode set to opportunistic mode and260 set scan settings report delay seconds such that a batch scan is261 expected.262 3. Start scanning on dut 0263 4. Try to find an event, expect none.264 5. Start a second scanner on dut0, with any other mode set and set scan265 settings report delay millis to 0 such that an onBatchScanResult is not266 expected.267 6. Pop onScanResults event on the second scanner268 7. Pop onBatchScanResult event on the first scanner269 Expected Result:270 Batch scan result is not expected on opportunistic scan instance.271 Returns:272 Pass if True273 Fail if False274 TAGS: LE, Advertising, Scanning, Opportunistic Scan, Batch Scanning275 Priority: 1276 """277 self._setup_generic_advertisement()278 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[279 'opportunistic'])280 self.scn_ad.droid.bleSetScanSettingsReportDelayMillis(281 self.report_delay)282 filter_list, scan_settings, scan_callback = generate_ble_scan_objects(283 self.scn_ad.droid)284 self.scn_ad.droid.bleStartBleScan(filter_list, scan_settings,285 scan_callback)286 self.active_scan_callback_list.append(scan_callback)287 if not self._verify_no_events_found(288 batch_scan_result.format(scan_callback)):289 return False290 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[291 'low_latency'])292 filter_list2, scan_settings2, scan_callback2 = (293 generate_ble_scan_objects(self.scn_ad.droid))294 self.scn_ad.droid.bleStartBleScan(filter_list2, scan_settings2,295 scan_callback2)296 self.active_scan_callback_list.append(scan_callback2)297 try:298 self.scn_ad.ed.pop_event(299 scan_result.format(scan_callback2), self.default_timeout)300 except Empty:301 self.log.error("Non-Opportunistic scan found no scan results.")302 return False303 return self._verify_no_events_found(304 batch_scan_result.format(scan_callback))305 @BluetoothBaseTest.bt_test_wrap306 @test_tracker_info(uuid='6138592e-8fd5-444f-9a7c-25cd9695644a')307 def test_scan_result_not_expected(self):308 """Test opportunistic scan without expecting an event.309 Tests opportunistic scan where it will only report batch scan results310 when other registered scanners find results.311 Steps:312 1. Initialize advertiser and start advertisement on dut1313 2. Initialize scanner with scan mode set to opportunistic mode.314 3. Start scanning on dut 0315 4. Try to find an event, expect none.316 5. Start a second scanner on dut0, with any other mode set and set scan317 settings318 report delay millis such that an onBatchScanResult is expected319 6. Pop onBatchScanResult event on the second scanner320 7. Pop onScanResults event on the first scanner321 Expected Result:322 Scan result is not expected on opportunistic scan instance.323 Returns:324 Pass if True325 Fail if False326 TAGS: LE, Advertising, Scanning, Opportunistic Scan327 Priority: 1328 """329 self._setup_generic_advertisement()330 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[331 'opportunistic'])332 filter_list, scan_settings, scan_callback = generate_ble_scan_objects(333 self.scn_ad.droid)334 self.scn_ad.droid.bleStartBleScan(filter_list, scan_settings,335 scan_callback)336 self.active_scan_callback_list.append(scan_callback)337 if not self._verify_no_events_found(scan_result.format(scan_callback)):338 return False339 self.scn_ad.droid.bleSetScanSettingsReportDelayMillis(340 self.report_delay)341 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[342 'low_latency'])343 filter_list2, scan_settings2, scan_callback2 = (344 generate_ble_scan_objects(self.scn_ad.droid))345 self.scn_ad.droid.bleStartBleScan(filter_list2, scan_settings2,346 scan_callback2)347 self.active_scan_callback_list.append(scan_callback2)348 try:349 self.scn_ad.ed.pop_event(350 batch_scan_result.format(scan_callback2), self.default_timeout)351 except Empty:352 self.log.error("Non-Opportunistic scan found no scan results.")353 return False354 return self._verify_no_events_found(scan_result.format(scan_callback))355 @BluetoothBaseTest.bt_test_wrap356 @test_tracker_info(uuid='f7aba3d9-d3f7-4b2f-976e-441772705613')357 def test_max_opportunistic_scan_instances(self):358 """Test max number of opportunistic scan instances.359 Tests max instances of opportunistic scans. Each instances should360 find an onScanResults event.361 Steps:362 1. Initialize advertiser and start advertisement on dut1363 2. Set scan settings to opportunistic scan on dut0 scan instance364 3. Start scan scan from step 2365 4. Repeat step two and three until there are max_scan_instances-1 scan366 instances367 5. Start a regular ble scan on dut0 with the last available scan368 instance369 6. Pop onScanResults event on all scan instances370 Expected Result:371 Each opportunistic scan instance finds a advertisement.372 Returns:373 Pass if True374 Fail if False375 TAGS: LE, Advertising, Scanning, Opportunistic Scan376 Priority: 1377 """378 self._setup_generic_advertisement()379 for _ in range(self.max_scan_instances - 1):380 self.scn_ad.droid.bleSetScanSettingsScanMode(381 ble_scan_settings_modes['opportunistic'])382 filter_list, scan_settings, scan_callback = generate_ble_scan_objects(383 self.scn_ad.droid)384 self.scn_ad.droid.bleStartBleScan(filter_list, scan_settings,385 scan_callback)386 self.active_scan_callback_list.append(scan_callback)387 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[388 'low_latency'])389 filter_list2, scan_settings2, scan_callback2 = (390 generate_ble_scan_objects(self.scn_ad.droid))391 self.scn_ad.droid.bleStartBleScan(filter_list2, scan_settings2,392 scan_callback2)393 self.active_scan_callback_list.append(scan_callback2)394 for callback in self.active_scan_callback_list:395 try:396 self.scn_ad.ed.pop_event(397 scan_result.format(callback), self.default_timeout)398 except Empty:399 self.log.error("No scan results found for callback {}".format(400 callback))401 return False402 return True403 @BluetoothBaseTest.bt_test_wrap404 @test_tracker_info(uuid='cf971f08-4d92-4046-bba6-b86a75aa773c')405 def test_max_opportunistic_batch_scan_instances(self):406 """Test max opportunistic batch scan instances.407 Tests max instances of opportunistic batch scans. Each instances should408 find an onBatchScanResult event.409 Steps:410 1. Initialize advertiser and start advertisement on dut1411 2. Set scan settings to opportunistic scan on dut0 scan instance and412 set report delay seconds such that an onBatchScanResult is expected413 3. Start scan scan from step 2414 4. Repeat step two and three until there are max_scan_instances-1 scan415 instances416 5. Start a regular ble scan on dut0 with the last available scan417 instance418 6. Pop onBatchScanResult event on all scan instances419 Expected Result:420 Each opportunistic scan instance finds an advertisement.421 Returns:422 Pass if True423 Fail if False424 TAGS: LE, Advertising, Scanning, Opportunistic Scan, Batch Scanning425 Priority: 1426 """427 self._setup_generic_advertisement()428 for _ in range(self.max_scan_instances - 1):429 self.scn_ad.droid.bleSetScanSettingsScanMode(430 ble_scan_settings_modes['opportunistic'])431 self.scn_ad.droid.bleSetScanSettingsReportDelayMillis(432 self.report_delay)433 filter_list, scan_settings, scan_callback = generate_ble_scan_objects(434 self.scn_ad.droid)435 self.scn_ad.droid.bleStartBleScan(filter_list, scan_settings,436 scan_callback)437 self.active_scan_callback_list.append(scan_callback)438 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[439 'low_latency'])440 self.scn_ad.droid.bleSetScanSettingsReportDelayMillis(441 self.report_delay)442 filter_list2, scan_settings2, scan_callback2 = (443 generate_ble_scan_objects(self.scn_ad.droid))444 self.scn_ad.droid.bleStartBleScan(filter_list2, scan_settings2,445 scan_callback2)446 self.active_scan_callback_list.append(scan_callback2)447 for callback in self.active_scan_callback_list:448 try:449 self.scn_ad.ed.pop_event(450 batch_scan_result.format(callback), self.default_timeout)451 except Empty:452 self.log.error("No scan results found for callback {}".format(453 callback))454 return True455 @BluetoothBaseTest.bt_test_wrap456 @test_tracker_info(uuid='965d84ef-11a7-418a-97e9-2a441c6de776')457 def test_discover_opportunistic_scan_result_off_secondary_scan_filter(458 self):459 """Test opportunistic scan result from secondary scan filter.460 Tests opportunistic scan where the filtered scan instance does not find461 an advertisement and the scan instance with scan mode set to462 opportunistic scan will also not find an advertisement.463 Steps:464 1. Initialize advertiser and start advertisement on dut1 (make sure the465 advertisement is not advertising the device name)466 2. Set scan settings to opportunistic scan on dut0 scan instance467 3. Start scan scan from step 2468 4. Try to find an event, expect none469 5. Start a second scanner on dut0, with any other mode set and set the470 scan filter device name to "opp_test"471 6. Pop onScanResults from the second scanner472 7. Expect no events473 8. Pop onScanResults from the first scanner474 9. Expect no events475 Expected Result:476 Opportunistic scan instance finds an advertisement.477 Returns:478 Pass if True479 Fail if False480 TAGS: LE, Advertising, Scanning, Opportunistic Scan481 Priority: 1482 """483 self._setup_generic_advertisement()484 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[485 'opportunistic'])486 filter_list, scan_settings, scan_callback = generate_ble_scan_objects(487 self.scn_ad.droid)488 self.scn_ad.droid.bleStartBleScan(filter_list, scan_settings,489 scan_callback)490 self.active_scan_callback_list.append(scan_callback)491 if not self._verify_no_events_found(scan_result.format(scan_callback)):492 return False493 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[494 'low_latency'])495 self.scn_ad.droid.bleSetScanFilterDeviceName("opp_test")496 filter_list2, scan_settings2, scan_callback2 = (497 generate_ble_scan_objects(self.scn_ad.droid))498 self.scn_ad.droid.bleBuildScanFilter(filter_list2)499 self.scn_ad.droid.bleStartBleScan(filter_list2, scan_settings2,500 scan_callback2)501 self.active_scan_callback_list.append(scan_callback2)502 if not self._verify_no_events_found(503 scan_result.format(scan_callback2)):504 return False505 if not self._verify_no_events_found(scan_result.format(scan_callback)):506 return False507 return True508 @BluetoothBaseTest.bt_test_wrap509 @test_tracker_info(uuid='13b0a83f-e96e-4d64-84ef-66351ec5054c')510 def test_negative_opportunistic_scan_filter_result_off_secondary_scan_result(511 self):512 """Test opportunistic scan not found scenario.513 Tests opportunistic scan where the secondary scan instance does find an514 advertisement but the scan instance with scan mode set to opportunistic515 scan does not find an advertisement due to mismatched scan filters.516 Steps:517 1. Initialize advertiser and start advertisement on dut1 (make sure the518 advertisement is not advertising the device name)519 2. Set scan settings to opportunistic scan on dut0 scan instance and set520 the scan filter device name to "opp_test"521 3. Start scan scan from step 2522 4. Try to find an event, expect none523 5. Start a second scanner on dut0, with any other mode set524 6. Pop onScanResults from the second scanner525 7. Pop onScanResults from the first scanner526 8. Expect no events527 Expected Result:528 Opportunistic scan instance doesn't find any advertisements.529 Returns:530 Pass if True531 Fail if False532 TAGS: LE, Advertising, Scanning, Opportunistic Scan533 Priority: 1534 """535 self._setup_generic_advertisement()536 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[537 'opportunistic'])538 self.scn_ad.droid.bleSetScanFilterDeviceName("opp_test")539 filter_list, scan_settings, scan_callback = generate_ble_scan_objects(540 self.scn_ad.droid)541 self.scn_ad.droid.bleBuildScanFilter(filter_list)542 self.scn_ad.droid.bleStartBleScan(filter_list, scan_settings,543 scan_callback)544 self.active_scan_callback_list.append(scan_callback)545 if not self._verify_no_events_found(scan_result.format(scan_callback)):546 return False547 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[548 'low_latency'])549 filter_list2, scan_settings2, scan_callback2 = (550 generate_ble_scan_objects(self.scn_ad.droid))551 self.scn_ad.droid.bleStartBleScan(filter_list2, scan_settings2,552 scan_callback2)553 self.active_scan_callback_list.append(scan_callback2)554 try:555 self.scn_ad.ed.pop_event(556 scan_result.format(scan_callback2), self.default_timeout)557 except Empty:558 self.log.error("Non-Opportunistic scan found no scan results.")559 return False560 return self._verify_no_events_found(scan_result.format(scan_callback))561 @BluetoothBaseTest.bt_test_wrap562 @test_tracker_info(uuid='087f60b2-f6a1-4919-b4c5-cdf3debcfeff')563 def test_opportunistic_scan_filter_result_off_secondary_scan_result(self):564 """Test opportunistic scan from a secondary scan result.565 Tests opportunistic scan where the scan filters are the same between the566 first scan instance with opportunistic scan set and the second instance567 with any other mode set.568 Steps:569 1. Initialize advertiser and start advertisement on dut1570 2. On dut0, set the scan settings mode to opportunistic scan and set571 the scan filter device name to the advertiser's device name572 3. Start scan scan from step 2573 4. Try to find an event, expect none574 5. Start a second scanner on dut0, with any other mode set and set the575 scan filter device name to the advertiser's device name576 6. Pop onScanResults from the second scanner577 7. Pop onScanResults from the first scanner578 Expected Result:579 Opportunistic scan instance finds a advertisement.580 Returns:581 Pass if True582 Fail if False583 TAGS: LE, Advertising, Scanning, Opportunistic Scan584 Priority: 1585 """586 self.adv_ad.droid.bleSetAdvertiseDataIncludeDeviceName(True)587 self._setup_generic_advertisement()588 adv_device_name = self.adv_ad.droid.bluetoothGetLocalName()589 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[590 'opportunistic'])591 self.scn_ad.droid.bleSetScanFilterDeviceName(adv_device_name)592 filter_list, scan_settings, scan_callback = generate_ble_scan_objects(593 self.scn_ad.droid)594 self.scn_ad.droid.bleStartBleScan(filter_list, scan_settings,595 scan_callback)596 self.active_scan_callback_list.append(scan_callback)597 if not self._verify_no_events_found(scan_result.format(scan_callback)):598 return False599 self.scn_ad.droid.bleSetScanSettingsScanMode(ble_scan_settings_modes[600 'low_latency'])601 filter_list2, scan_settings2, scan_callback2 = (602 generate_ble_scan_objects(self.scn_ad.droid))603 self.scn_ad.droid.bleSetScanFilterDeviceName(adv_device_name)604 self.scn_ad.droid.bleBuildScanFilter(filter_list2)605 self.scn_ad.droid.bleStartBleScan(filter_list2, scan_settings2,606 scan_callback2)607 self.active_scan_callback_list.append(scan_callback2)608 try:609 self.scn_ad.ed.pop_event(610 scan_result.format(scan_callback2), self.default_timeout)611 except Empty:612 self.log.error("Opportunistic scan found no scan results.")613 return False614 try:615 self.scn_ad.ed.pop_event(616 scan_result.format(scan_callback), self.default_timeout)617 except Empty:618 self.log.error("Non-Opportunistic scan found no scan results.")619 return False...

Full Screen

Full Screen

test_src_scan.py

Source:test_src_scan.py Github

copy

Full Screen

...116 self.assertEqual(mock.call(fname_list[2]),117 mocked.mock_calls[1])118 finally:119 shutil.rmtree(indir)120 def test_scan(self):121 """Test scanning of a driver"""122 fname = os.path.join(OUR_PATH, '..', '..', 'drivers/i2c/tegra_i2c.c')123 buff = tools.ReadFile(fname, False)124 scan = src_scan.Scanner(None, None)125 scan._parse_driver(fname, buff)126 self.assertIn('i2c_tegra', scan._drivers)127 drv = scan._drivers['i2c_tegra']128 self.assertEqual('i2c_tegra', drv.name)129 self.assertEqual('UCLASS_I2C', drv.uclass_id)130 self.assertEqual(131 {'nvidia,tegra114-i2c': 'TYPE_114',132 'nvidia,tegra20-i2c': 'TYPE_STD',133 'nvidia,tegra20-i2c-dvc': 'TYPE_DVC'}, drv.compat)134 self.assertEqual('i2c_bus', drv.priv)135 self.assertEqual(1, len(scan._drivers))136 self.assertEqual({}, scan._warnings)137 def test_normalized_name(self):138 """Test operation of get_normalized_compat_name()"""139 prop = FakeProp()140 prop.name = 'compatible'141 prop.value = 'rockchip,rk3288-grf'142 node = FakeNode()143 node.props = {'compatible': prop}144 # get_normalized_compat_name() uses this to check for root node145 node.parent = FakeNode()146 scan = src_scan.Scanner(None, None)147 with test_util.capture_sys_output() as (stdout, _):148 name, aliases = scan.get_normalized_compat_name(node)149 self.assertEqual('rockchip_rk3288_grf', name)150 self.assertEqual([], aliases)151 self.assertEqual(1, len(scan._missing_drivers))152 self.assertEqual({'rockchip_rk3288_grf'}, scan._missing_drivers)153 self.assertEqual('', stdout.getvalue().strip())154 self.assertEqual(EXPECT_WARN, scan._warnings)155 i2c = 'I2C_UCLASS'156 compat = {'rockchip,rk3288-grf': 'ROCKCHIP_SYSCON_GRF',157 'rockchip,rk3288-srf': None}158 drv = src_scan.Driver('fred', 'fred.c')159 drv.uclass_id = i2c160 drv.compat = compat161 scan._drivers['rockchip_rk3288_grf'] = drv162 scan._driver_aliases['rockchip_rk3288_srf'] = 'rockchip_rk3288_grf'163 with test_util.capture_sys_output() as (stdout, _):164 name, aliases = scan.get_normalized_compat_name(node)165 self.assertEqual('', stdout.getvalue().strip())166 self.assertEqual('rockchip_rk3288_grf', name)167 self.assertEqual([], aliases)168 self.assertEqual(EXPECT_WARN, scan._warnings)169 prop.value = 'rockchip,rk3288-srf'170 with test_util.capture_sys_output() as (stdout, _):171 name, aliases = scan.get_normalized_compat_name(node)172 self.assertEqual('', stdout.getvalue().strip())173 self.assertEqual('rockchip_rk3288_grf', name)174 self.assertEqual(['rockchip_rk3288_srf'], aliases)175 self.assertEqual(EXPECT_WARN, scan._warnings)176 def test_scan_errors(self):177 """Test detection of scanning errors"""178 buff = '''179static const struct udevice_id tegra_i2c_ids2[] = {180 { .compatible = "nvidia,tegra114-i2c", .data = TYPE_114 },181 { }182};183U_BOOT_DRIVER(i2c_tegra) = {184 .name = "i2c_tegra",185 .id = UCLASS_I2C,186 .of_match = tegra_i2c_ids,187};188'''189 scan = src_scan.Scanner(None, None)190 with self.assertRaises(ValueError) as exc:191 scan._parse_driver('file.c', buff)192 self.assertIn(193 "file.c: Unknown compatible var 'tegra_i2c_ids' (found: tegra_i2c_ids2)",194 str(exc.exception))195 def test_of_match(self):196 """Test detection of of_match_ptr() member"""197 buff = '''198static const struct udevice_id tegra_i2c_ids[] = {199 { .compatible = "nvidia,tegra114-i2c", .data = TYPE_114 },200 { }201};202U_BOOT_DRIVER(i2c_tegra) = {203 .name = "i2c_tegra",204 .id = UCLASS_I2C,205 .of_match = of_match_ptr(tegra_i2c_ids),206};207'''208 scan = src_scan.Scanner(None, None)209 scan._parse_driver('file.c', buff)210 self.assertIn('i2c_tegra', scan._drivers)211 drv = scan._drivers['i2c_tegra']212 self.assertEqual('i2c_tegra', drv.name)213 self.assertEqual('', drv.phase)214 self.assertEqual([], drv.headers)215 def test_priv(self):216 """Test collection of struct info from drivers"""217 buff = '''218static const struct udevice_id test_ids[] = {219 { .compatible = "nvidia,tegra114-i2c", .data = TYPE_114 },220 { }221};222U_BOOT_DRIVER(testing) = {223 .name = "testing",224 .id = UCLASS_I2C,225 .of_match = test_ids,226 .priv_auto = sizeof(struct some_priv),227 .plat_auto = sizeof(struct some_plat),228 .per_child_auto = sizeof(struct some_cpriv),229 .per_child_plat_auto = sizeof(struct some_cplat),230 DM_PHASE(tpl)231 DM_HEADER(<i2c.h>)232 DM_HEADER(<asm/clk.h>)233};234'''235 scan = src_scan.Scanner(None, None)236 scan._parse_driver('file.c', buff)237 self.assertIn('testing', scan._drivers)238 drv = scan._drivers['testing']239 self.assertEqual('testing', drv.name)240 self.assertEqual('UCLASS_I2C', drv.uclass_id)241 self.assertEqual(242 {'nvidia,tegra114-i2c': 'TYPE_114'}, drv.compat)243 self.assertEqual('some_priv', drv.priv)244 self.assertEqual('some_plat', drv.plat)245 self.assertEqual('some_cpriv', drv.child_priv)246 self.assertEqual('some_cplat', drv.child_plat)247 self.assertEqual('tpl', drv.phase)248 self.assertEqual(['<i2c.h>', '<asm/clk.h>'], drv.headers)249 self.assertEqual(1, len(scan._drivers))250 def test_uclass_scan(self):251 """Test collection of uclass-driver info"""252 buff = '''253UCLASS_DRIVER(i2c) = {254 .id = UCLASS_I2C,255 .name = "i2c",256 .flags = DM_UC_FLAG_SEQ_ALIAS,257 .priv_auto = sizeof(struct some_priv),258 .per_device_auto = sizeof(struct per_dev_priv),259 .per_device_plat_auto = sizeof(struct per_dev_plat),260 .per_child_auto = sizeof(struct per_child_priv),261 .per_child_plat_auto = sizeof(struct per_child_plat),262 .child_post_bind = i2c_child_post_bind,263};264'''265 scan = src_scan.Scanner(None, None)266 scan._parse_uclass_driver('file.c', buff)267 self.assertIn('UCLASS_I2C', scan._uclass)268 drv = scan._uclass['UCLASS_I2C']269 self.assertEqual('i2c', drv.name)270 self.assertEqual('UCLASS_I2C', drv.uclass_id)271 self.assertEqual('some_priv', drv.priv)272 self.assertEqual('per_dev_priv', drv.per_dev_priv)273 self.assertEqual('per_dev_plat', drv.per_dev_plat)274 self.assertEqual('per_child_priv', drv.per_child_priv)275 self.assertEqual('per_child_plat', drv.per_child_plat)276 self.assertEqual(1, len(scan._uclass))277 drv2 = copy.deepcopy(drv)278 self.assertEqual(drv, drv2)279 drv2.priv = 'other_priv'280 self.assertNotEqual(drv, drv2)281 # The hashes only depend on the uclass ID, so should be equal282 self.assertEqual(drv.__hash__(), drv2.__hash__())283 self.assertEqual("UclassDriver(name='i2c', uclass_id='UCLASS_I2C')",284 str(drv))285 def test_uclass_scan_errors(self):286 """Test detection of uclass scanning errors"""287 buff = '''288UCLASS_DRIVER(i2c) = {289 .name = "i2c",290};291'''292 scan = src_scan.Scanner(None, None)293 with self.assertRaises(ValueError) as exc:294 scan._parse_uclass_driver('file.c', buff)295 self.assertIn("file.c: Cannot parse uclass ID in driver 'i2c'",296 str(exc.exception))297 def test_struct_scan(self):298 """Test collection of struct info"""299 buff = '''300/* some comment */301struct some_struct1 {302 struct i2c_msg *msgs;303 uint nmsgs;304};305'''306 scan = src_scan.Scanner(None, None)307 scan._basedir = os.path.join(OUR_PATH, '..', '..')308 scan._parse_structs('arch/arm/include/asm/file.h', buff)309 self.assertIn('some_struct1', scan._structs)310 struc = scan._structs['some_struct1']311 self.assertEqual('some_struct1', struc.name)...

Full Screen

Full Screen

scan-test.js

Source:scan-test.js Github

copy

Full Screen

1'use strict';2const helper = require('./test-helper');3const Schema = require('../lib/schema');4const Scan = require('../lib/scan');5const _ = require('lodash');6const chai = require('chai');7const Joi = require('joi');8const expect = chai.expect;9chai.should();10const internals = {};11internals.assertScanFilter = (scan, expected) => {12 const conds = _.map(scan.request.ScanFilter, c => c.format());13 if (!_.isArray(expected)) {14 expected = [expected];15 }16 conds.should.eql(expected);17};18describe('Scan', () => {19 let schema;20 let serializer;21 let table;22 beforeEach(() => {23 serializer = helper.mockSerializer();24 table = helper.mockTable();25 table.tableName = () => 'accounts';26 table.docClient = helper.mockDocClient();27 const config = {28 hashKey: 'name',29 rangeKey: 'email',30 schema: {31 name: Joi.string(),32 email: Joi.string(),33 created: Joi.date()34 },35 indexes: [{ hashKey: 'name', rangeKey: 'created', type: 'local', name: 'CreatedIndex' }]36 };37 schema = new Schema(config);38 table.schema = schema;39 });40 describe('#exec', () => {41 it('should call run scan on table', (done) => {42 table.runScan.yields(null, { ConsumedCapacity: { CapacityUnits: 5, TableName: 'accounts' }, Count: 10, ScannedCount: 12 });43 serializer.serializeItem.returns({ name: { S: 'tim' } });44 new Scan(table, serializer).exec((err, results) => {45 results.ConsumedCapacity.should.eql({ CapacityUnits: 5, TableName: 'accounts' });46 results.Count.should.equal(10);47 results.ScannedCount.should.equal(12);48 done();49 });50 });51 it('should return LastEvaluatedKey', (done) => {52 table.runScan.yields(null, { LastEvaluatedKey: { name: 'tim' }, Count: 10, ScannedCount: 12 });53 serializer.serializeItem.returns({ name: { S: 'tim' } });54 new Scan(table, serializer).exec((err, results) => {55 results.Count.should.equal(10);56 results.ScannedCount.should.equal(12);57 results.LastEvaluatedKey.should.eql({ name: 'tim' });58 done();59 });60 });61 it('should return error', (done) => {62 table.runScan.yields(new Error('Fail'));63 new Scan(table, serializer).exec((err, results) => {64 expect(err).to.exist;65 expect(results).to.not.exist;66 done();67 });68 });69 it('should run scan after encountering a retryable exception', (done) => {70 const err = new Error('RetryableException');71 err.retryable = true;72 table.runScan73 .onCall(0).yields(err)74 .onCall(1).yields(err)75 .onCall(2).yields(null, { Items: [{ name: 'foo' }] });76 new Scan(table, serializer).exec((err, data) => {77 expect(err).to.not.exist;78 expect(data).to.exist;79 expect(data.Items).to.have.length(1);80 expect(table.runScan.calledThrice).to.be.true;81 done();82 });83 });84 });85 describe('#limit', () => {86 it('should set the limit', () => {87 const scan = new Scan(table, serializer).limit(10);88 scan.request.Limit.should.equal(10);89 });90 it('should throw when limit is zero', () => {91 const scan = new Scan(table, serializer);92 expect(() => {93 scan.limit(0);94 }).to.throw('Limit must be greater than 0');95 });96 });97 describe('#attributes', () => {98 it('should set array attributes to get', () => {99 const scan = new Scan(table, serializer).attributes(['created', 'email']);100 scan.request.ProjectionExpression.should.eql('#created,#email');101 scan.request.ExpressionAttributeNames.should.eql({ '#created': 'created', '#email': 'email' });102 });103 it('should set single attribute to get', () => {104 const scan = new Scan(table, serializer).attributes('email');105 scan.request.ProjectionExpression.should.eql('#email');106 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });107 });108 });109 describe('#startKey', () => {110 it('should set start Key to hash', () => {111 const key = { name: { S: 'tim' } };112 serializer.buildKey.returns(key);113 const scan = new Scan(table, serializer).startKey('tim');114 scan.request.ExclusiveStartKey.should.eql(key);115 });116 it('should set start Key to hash + range', () => {117 const key = { name: { S: 'tim' }, email: { S: 'foo@example.com' } };118 serializer.buildKey.returns(key);119 const scan = new Scan(table, serializer).startKey({ name: 'tim', email: 'foo@example.com' });120 scan.request.ExclusiveStartKey.should.eql(key);121 });122 });123 describe('#select', () => {124 it('should set select Key', () => {125 const scan = new Scan(table, serializer).select('COUNT');126 scan.request.Select.should.eql('COUNT');127 });128 });129 describe('#ReturnConsumedCapacity', () => {130 it('should set return consumed capacity Key to passed in value', () => {131 const scan = new Scan(table, serializer).returnConsumedCapacity('TOTAL');132 scan.request.ReturnConsumedCapacity.should.eql('TOTAL');133 });134 it('should set return consumed capacity Key', () => {135 const scan = new Scan(table, serializer).returnConsumedCapacity();136 scan.request.ReturnConsumedCapacity.should.eql('TOTAL');137 });138 });139 describe('#segment', () => {140 it('should set both segment and total segments keys', () => {141 const scan = new Scan(table, serializer).segments(0, 4);142 scan.request.Segment.should.eql(0);143 scan.request.TotalSegments.should.eql(4);144 });145 });146 describe('#where', () => {147 let scan;148 beforeEach(() => {149 const config = {150 hashKey: 'name',151 rangeKey: 'email',152 schema: {153 name: Joi.string(),154 email: Joi.string(),155 created: Joi.date(),156 scores: Schema.types.numberSet(),157 data: Joi.object()158 },159 indexes: [{ hashKey: 'name', rangeKey: 'created', type: 'local', name: 'CreatedIndex' }]160 };161 schema = new Schema(config);162 table.schema = schema;163 scan = new Scan(table, serializer);164 });165 it('should have equals clause', () => {166 scan = scan.where('email').equals('foo@example.com');167 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });168 scan.request.ExpressionAttributeValues.should.eql({ ':email': 'foo@example.com' });169 scan.request.FilterExpression.should.eql('(#email = :email)');170 });171 it('should have not equals clause', () => {172 scan = scan.where('email').ne('foo@example.com');173 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });174 scan.request.ExpressionAttributeValues.should.eql({ ':email': 'foo@example.com' });175 scan.request.FilterExpression.should.eql('(#email <> :email)');176 });177 it('should have less than or equal clause', () => {178 scan = scan.where('email').lte('foo@example.com');179 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });180 scan.request.ExpressionAttributeValues.should.eql({ ':email': 'foo@example.com' });181 scan.request.FilterExpression.should.eql('(#email <= :email)');182 });183 it('should have less than clause', () => {184 scan = scan.where('email').lt('foo@example.com');185 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });186 scan.request.ExpressionAttributeValues.should.eql({ ':email': 'foo@example.com' });187 scan.request.FilterExpression.should.eql('(#email < :email)');188 });189 it('should have greater than or equal clause', () => {190 scan = scan.where('email').gte('foo@example.com');191 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });192 scan.request.ExpressionAttributeValues.should.eql({ ':email': 'foo@example.com' });193 scan.request.FilterExpression.should.eql('(#email >= :email)');194 });195 it('should have greater than clause', () => {196 scan = scan.where('email').gt('foo@example.com');197 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });198 scan.request.ExpressionAttributeValues.should.eql({ ':email': 'foo@example.com' });199 scan.request.FilterExpression.should.eql('(#email > :email)');200 });201 it('should have not null clause', () => {202 scan = scan.where('email').notNull();203 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });204 expect(scan.request.ExpressionAttributeValues).to.not.exist;205 scan.request.FilterExpression.should.eql('(attribute_exists(#email))');206 });207 it('should have null clause', () => {208 scan = scan.where('email').null();209 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });210 expect(scan.request.ExpressionAttributeValues).to.not.exist;211 scan.request.FilterExpression.should.eql('(attribute_not_exists(#email))');212 });213 it('should have contains clause', () => {214 scan = scan.where('email').contains('foo@example.com');215 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });216 scan.request.ExpressionAttributeValues.should.eql({ ':email': 'foo@example.com' });217 scan.request.FilterExpression.should.eql('(contains(#email, :email))');218 });219 it('should not pass a number set when making contains call', () => {220 scan = scan.where('scores').contains(2);221 scan.request.ExpressionAttributeNames.should.eql({ '#scores': 'scores' });222 scan.request.ExpressionAttributeValues.should.eql({ ':scores': 2 });223 scan.request.FilterExpression.should.eql('(contains(#scores, :scores))');224 });225 it('should have not contains clause', () => {226 scan = scan.where('email').notContains('foo@example.com');227 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });228 scan.request.ExpressionAttributeValues.should.eql({ ':email': 'foo@example.com' });229 scan.request.FilterExpression.should.eql('(NOT contains(#email, :email))');230 });231 it('should have in clause', () => {232 scan = scan.where('email').in(['foo@example.com', 'test@example.com']);233 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });234 scan.request.ExpressionAttributeValues.should.eql({ ':email': 'foo@example.com', ':email_2': 'test@example.com' });235 scan.request.FilterExpression.should.eql('(#email IN (:email,:email_2))');236 });237 it('should have begins with clause', () => {238 scan = scan.where('email').beginsWith('foo');239 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });240 scan.request.ExpressionAttributeValues.should.eql({ ':email': 'foo' });241 scan.request.FilterExpression.should.eql('(begins_with(#email, :email))');242 });243 it('should have between clause', () => {244 scan = scan.where('email').between('bob@bob.com', 'foo@foo.com');245 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });246 scan.request.ExpressionAttributeValues.should.eql({ ':email': 'bob@bob.com', ':email_2': 'foo@foo.com' });247 scan.request.FilterExpression.should.eql('(#email BETWEEN :email AND :email_2)');248 });249 it('should have multiple filters', () => {250 scan = scan251 .where('name').equals('Tim')252 .where('email').beginsWith('foo');253 scan.request.ExpressionAttributeNames.should.eql({ '#name': 'name', '#email': 'email' });254 scan.request.ExpressionAttributeValues.should.eql({ ':name': 'Tim', ':email': 'foo' });255 scan.request.FilterExpression.should.eql('(#name = :name) AND (begins_with(#email, :email))');256 });257 it('should have multiple filters on the same attribute', () => {258 scan = scan259 .where('email').gt('foo@example.com')260 .where('email').lt('moo@example.com');261 scan.request.ExpressionAttributeNames.should.eql({ '#email': 'email' });262 scan.request.ExpressionAttributeValues.should.eql({ ':email': 'foo@example.com', ':email_2': 'moo@example.com' });263 scan.request.FilterExpression.should.eql('(#email > :email) AND (#email < :email_2)');264 });265 it('should convert date to iso string', () => {266 const d = new Date();267 scan = scan.where('created').equals(d);268 scan.request.ExpressionAttributeNames.should.eql({ '#created': 'created' });269 scan.request.ExpressionAttributeValues.should.eql({ ':created': d.toISOString() });270 scan.request.FilterExpression.should.eql('(#created = :created)');271 });272 it('should support Map.Attr document paths', () => {273 scan = scan.where('data.attr').equals(15);274 scan.request.ExpressionAttributeNames.should.eql({ '#data': 'data', '#attr': 'attr' });275 scan.request.ExpressionAttributeValues.should.eql({ ':data_attr': 15 });276 scan.request.FilterExpression.should.eql('(#data.#attr = :data_attr)');277 });278 });279 describe('#loadAll', () => {280 it('should set load all option to true', () => {281 const scan = new Scan(table, serializer).loadAll();282 scan.options.loadAll.should.be.true;283 });284 });285 describe('#filterExpression', () => {286 it('should set filter expression', () => {287 const scan = new Scan(table, serializer).filterExpression('Postedby = :val');288 scan.request.FilterExpression.should.equal('Postedby = :val');289 });290 });291 describe('#expressionAttributeValues', () => {292 it('should set expression attribute values', () => {293 const scan = new Scan(table, serializer).expressionAttributeValues({ ':val': 'test' });294 scan.request.ExpressionAttributeValues.should.eql({ ':val': 'test' });295 });296 });297 describe('#expressionAttributeNames', () => {298 it('should set expression attribute names', () => {299 const scan = new Scan(table, serializer).expressionAttributeNames({ '#name': 'name' });300 scan.request.ExpressionAttributeNames.should.eql({ '#name': 'name' });301 });302 });303 describe('#projectionExpression', () => {304 it('should set projection expression', () => {305 const scan = new Scan(table, serializer).projectionExpression('#name, #email');306 scan.request.ProjectionExpression.should.eql('#name, #email');307 });308 });...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful