How to use scan method in ng-mocks

Best JavaScript code snippet using ng-mocks

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

scanNodes.js

Source:scanNodes.js Github

copy

Full Screen

1const scanNodes = {2 'Seq Scan': {3 text: `This is the simplest way of fetching data from a table: it scans through every page of data sequentially. Like most other scans, this can apply a filter while reading data, but it needs to read the data first and then discard it. A sequential scan has no way to zero in on just the data you want: it always reads everything in the table. This is generally inefficient unless you need a large proportion of the table to answer your query, but is always available and sometimes may be the only option.`,4 link: 'https://pganalyze.com/docs/explain/scan-nodes/sequential-scan',5 color: '#FF5722',6 },7 'Index Scan': {8 link: 'https://pganalyze.com/docs/explain/scan-nodes/index-scan',9 text: `An index scan uses an index to find either a specific row, or all rows matching a predicate. An index scan will either look up a single row at a time (for a query like WHERE id = 1234, or as the inner table in a nested loop, looking up the row matching the current outer row), or scan through a section of the table in order. An index scan must first look up each row in the index, and then check the actual table data for that index entry. The table data must be checked to ensure that the row it found is actually visible to the current transaction, and also to fetch any columns included in the query that are not present in the index. Because of this, an index scan actually has higher per-row overhead than a sequential scan: its real advantage is that it allows you to read only some of the rows in a table. If your query predicate is not very selective (that is, if few rows are filtered out), a sequential scan may still be more efficient than an index scan.10 If your query predicate matches the index exactly, the scan will retrieve just the matching rows. If you have an additional predicate in your query, the index scan can filter rows as it’s reading them, just like a sequential scan.`,11 },12 'Index Only Scan': {13 link: 'https://pganalyze.com/docs/explain/scan-nodes/index-only-scan',14 text: `This is very similar to an Index Scan, but the data comes directly from the index and the visibility check is handled specially, so it can avoid looking at the table data entirely. An index-only scan is faster, but it’s not always available as an alternative to a regular index scan. It has two restrictions: the index type must support Index-Only Scans (the common btree index type always does) and (somewhat obviously) the query must only project columns included in the index. If you have a SELECT * query but don’t actually need all columns, you may be able to use an index-only scan just by changing the column list.`,15 },16 'Bitmap Heap Scan': {17 link: 'https://pganalyze.com/docs/explain/scan-nodes/bitmap-heap-scan',18 text: `A bitmap heap scan takes a row location bitmap generated by a Bitmap Index Scan (either directly, or through a series of bitmap set operations via BitmapAnd and BitmapOr nodes) and looks up the relevant data. Each chunk of a bitmap can either be exact (pointing directly to rows) or lossy (pointing to a page containing at least one row matching the predicate).19 Postgres prefers using exact blocks, but if limited work_mem is an issue, it will start using lossy blocks as well. The blocks are actually produced as lossy or exact by children of the bitmap heap scan, but that status is more relevant when the blocks are processed to fetch rows, so it is reflected in the Bitmap Heap Scan. If a bitmap block is lossy, the node will need to fetch the entire page, and re-check the specified index condition (since it doesn’t know which rows on the page are needed).`,20 },21 'Bitmap Index Scan': {22 link: 'https://pganalyze.com/docs/explain/scan-nodes/bitmap-index-scan',23 text: `You can think of a bitmap index scan as a middle ground between a sequential scan and an index scan. Like an index scan, it scans an index to determine exactly what data it needs to fetch, but like a sequential scan, it takes advantage of data being easier to read in bulk.24 The bitmap index scan actually operates in tandem with a Bitmap Heap Scan: it does not fetch the data itself. Instead of producing the rows directly, the bitmap index scan constructs a bitmap of potential row locations. It feeds this data to a parent Bitmap Heap Scan, which can decode the bitmap to fetch the underlying data, grabbing data page by page.25 26 A Bitmap Heap Scan is the most common parent node of a Bitmap Index Scan, but a plan may also combine several different Bitmap Index Scans with BitmapAnd or BitmapOr nodes before actually fetching the underlying data. This allows Postgres to use two different indexes at once to execute a query.`,27 },28 'CTE Scan': {29 link: 'https://pganalyze.com/docs/explain/scan-nodes/cte-scan',30 text: `Scan the result of a common table expression. Note that until Postgres 12, common table expressions are an optimization fence; the CTE result is materialized, and is essentially treated as a temporary table and not optimized as part of the query. If you depend on this behavior, be aware performance of your queries may change when you upgrade.`,31 },32 'Custom Scan': {33 link: 'https://pganalyze.com/docs/explain/scan-nodes/custom-scan',34 text: `Scan using a custom scan implementation, which can be added as a separate module and plug into standard Postgres query planning and execution.`,35 },36 'Foreign Scan': {37 link: 'https://pganalyze.com/docs/explain/scan-nodes/foreign-scan',38 text: `Scan on a Foreign Table.`,39 },40 'Function Scan': {41 link: 'https://pganalyze.com/docs/explain/scan-nodes/function-scan',42 text: `Scans the result of a set-returning function (like unnest or regexp_split_to_table).`,43 },44 'Subquery Scan': {45 text: `A Subquery Scan is for scanning the output of a sub-query in the range table. We often need an extra plan node above the sub-query's plan to perform expression evaluations (which we can't push into the sub-query without risking changing its semantics).`,46 link: 'https://pganalyze.com/docs/explain/scan-nodes/subquery-scan'47 },48 'Table Sample Scan': {49 link: 'https://pganalyze.com/docs/explain/scan-nodes/table-sample-scan',50 text: `Scan a table when the TABLESAMPLE feature is used. Note that this clause does change the semantics of your query, but if you’re looking to gather some statistics about data in a large table, it can be a lot more efficient than a full sequential scan.`,51 },52 'Tid Scan': {53 link: 'https://pganalyze.com/docs/explain/scan-nodes/tid-scan',54 text: `Similar to an Index Scan, but one that can only look up rows using the internal and unstable ctid identifier. You are unlikely to use this type of scan in your queries.`,55 },56 'Values Scan': {57 link: 'https://pganalyze.com/docs/explain/scan-nodes/values-scan',58 text: `Scan the literal VALUES clause.`,59 },60 'Work Table Scan': {61 link: 'https://pganalyze.com/docs/explain/scan-nodes/work-table-scan',62 text: `Scans the work table used in evaluating a recursive common table expression.`,63 },64};...

Full Screen

Full Screen

croc_scan_test.py

Source:croc_scan_test.py Github

copy

Full Screen

1#!/usr/bin/env python2# Copyright (c) 2011 The Chromium Authors. All rights reserved.3# Use of this source code is governed by a BSD-style license that can be4# found in the LICENSE file.5"""Unit tests for croc_scan.py."""6import re7import unittest8import croc_scan9class TestScanner(unittest.TestCase):10 """Tests for croc_scan.Scanner."""11 def testInit(self):12 """Test __init()__."""13 s = croc_scan.Scanner()14 self.assertEqual(s.re_token.pattern, '#')15 self.assertEqual(s.comment_to_eol, ['#'])16 self.assertEqual(s.comment_start, None)17 self.assertEqual(s.comment_end, None)18 def testScanLines(self):19 """Test ScanLines()."""20 s = croc_scan.Scanner()21 # Set up imaginary language:22 # ':' = comment to EOL23 # '"' = string start/end24 # '(' = comment start25 # ')' = comment end26 s.re_token = re.compile(r'([\:\"\(\)])')27 s.comment_to_eol = [':']28 s.comment_start = '('29 s.comment_end = ')'30 # No input file = no output lines31 self.assertEqual(s.ScanLines([]), [])32 # Empty lines and lines with only whitespace are ignored33 self.assertEqual(s.ScanLines([34 '', # 135 'line', # 2 exe36 ' \t ', # 337 ]), [2])38 # Comments to EOL are stripped, but not inside strings39 self.assertEqual(s.ScanLines([40 'test', # 1 exe41 ' : A comment', # 242 '"a : in a string"', # 3 exe43 'test2 : with comment to EOL', # 4 exe44 'foo = "a multiline string with an empty line', # 5 exe45 '', # 6 exe46 ': and a comment-to-EOL character"', # 7 exe47 ': done', # 848 ]), [1, 3, 4, 5, 6, 7])49 # Test Comment start/stop detection50 self.assertEqual(s.ScanLines([51 '( a comment on one line)', # 152 'text (with a comment)', # 2 exe53 '( a comment with a : in the middle)', # 354 '( a multi-line', # 455 ' comment)', # 556 'a string "with a ( in it"', # 6 exe57 'not in a multi-line comment', # 7 exe58 '(a comment with a " in it)', # 859 ': not in a string, so this gets stripped', # 960 'more text "with an uninteresting string"', # 10 exe61 ]), [2, 6, 7, 10])62 # TODO: Test Scan(). Low priority, since it just wraps ScanLines().63class TestPythonScanner(unittest.TestCase):64 """Tests for croc_scan.PythonScanner."""65 def testScanLines(self):66 """Test ScanLines()."""67 s = croc_scan.PythonScanner()68 # No input file = no output lines69 self.assertEqual(s.ScanLines([]), [])70 self.assertEqual(s.ScanLines([71 '# a comment', # 172 '', # 273 '"""multi-line string', # 3 exe74 '# not a comment', # 4 exe75 'end of multi-line string"""', # 5 exe76 ' ', # 677 '"single string with #comment"', # 7 exe78 '', # 879 '\'\'\'multi-line string, single-quote', # 9 exe80 '# not a comment', # 10 exe81 'end of multi-line string\'\'\'', # 11 exe82 '', # 1283 '"string with embedded \\" is handled"', # 13 exe84 '# quoted "', # 1485 '"\\""', # 15 exe86 '# quoted backslash', # 1687 '"\\\\"', # 17 exe88 'main()', # 18 exe89 '# end', # 1990 ]), [3, 4, 5, 7, 9, 10, 11, 13, 15, 17, 18])91class TestCppScanner(unittest.TestCase):92 """Tests for croc_scan.CppScanner."""93 def testScanLines(self):94 """Test ScanLines()."""95 s = croc_scan.CppScanner()96 # No input file = no output lines97 self.assertEqual(s.ScanLines([]), [])98 self.assertEqual(s.ScanLines([99 '// a comment', # 1100 '# a preprocessor define', # 2101 '', # 3102 '\'#\', \'"\'', # 4 exe103 '', # 5104 '/* a multi-line comment', # 6105 'with a " in it', # 7106 '*/', # 8107 '', # 9108 '"a string with /* and \' in it"', # 10 exe109 '', # 11110 '"a multi-line string\\', # 12 exe111 '// not a comment\\', # 13 exe112 'ending here"', # 14 exe113 '', # 15114 '"string with embedded \\" is handled"', # 16 exe115 '', # 17116 'main()', # 18 exe117 '// end', # 19118 ]), [4, 10, 12, 13, 14, 16, 18])119class TestScanFile(unittest.TestCase):120 """Tests for croc_scan.ScanFile()."""121 class MockScanner(object):122 """Mock scanner."""123 def __init__(self, language):124 """Constructor."""125 self.language = language126 def Scan(self, filename):127 """Mock Scan() method."""128 return 'scan %s %s' % (self.language, filename)129 def MockPythonScanner(self):130 return self.MockScanner('py')131 def MockCppScanner(self):132 return self.MockScanner('cpp')133 def setUp(self):134 """Per-test setup."""135 # Hook scanners136 self.old_python_scanner = croc_scan.PythonScanner137 self.old_cpp_scanner = croc_scan.CppScanner138 croc_scan.PythonScanner = self.MockPythonScanner139 croc_scan.CppScanner = self.MockCppScanner140 def tearDown(self):141 """Per-test cleanup."""142 croc_scan.PythonScanner = self.old_python_scanner143 croc_scan.CppScanner = self.old_cpp_scanner144 def testScanFile(self):145 """Test ScanFile()."""146 self.assertEqual(croc_scan.ScanFile('foo', 'python'), 'scan py foo')147 self.assertEqual(croc_scan.ScanFile('bar1', 'C'), 'scan cpp bar1')148 self.assertEqual(croc_scan.ScanFile('bar2', 'C++'), 'scan cpp bar2')149 self.assertEqual(croc_scan.ScanFile('bar3', 'ObjC'), 'scan cpp bar3')150 self.assertEqual(croc_scan.ScanFile('bar4', 'ObjC++'), 'scan cpp bar4')151 self.assertEqual(croc_scan.ScanFile('bar', 'fortran'), [])152if __name__ == '__main__':...

Full Screen

Full Screen

test_schedule_graph.py

Source:test_schedule_graph.py Github

copy

Full Screen

1import tvm2def test_scan():3 m = tvm.var("m")4 n = tvm.var("n")5 x = tvm.compute((m, n), lambda i, j: tvm.const(1, "float32"), name="x")6 s_state = tvm.placeholder((m, n))7 s_init = tvm.compute((1, n), lambda _, i: x[0, i], name="s_init")8 x_trans = tvm.compute((m, n), lambda i, j: x[i, j] + 1, name="x_trans")9 s_up1 = tvm.compute((m, n), lambda t, i: s_state[t - 1, i] + 1, name="up1")10 s_update = tvm.compute((m, n), lambda t, i: s_up1[t, i] + x_trans[t, i], name="update")11 s_scan = tvm.scan(s_init, s_update, s_state)12 def test_getbody():13 body = tvm.schedule.ScanGetBody(s_scan.op)14 assert set(body) == set([s_scan.op, s_update.op, s_up1.op])15 def test_attach_path():16 s = tvm.create_schedule(s_scan.op)17 s[x_trans].compute_at(s[s_update], s_update.op.axis[0])18 apath = tvm.schedule.CreateAttachPath(s)19 assert(tuple(apath[s_update.op]) == tuple([s_scan.op.scan_axis]))20 assert(tuple(apath[x_trans.op]) == tuple([s_update.op.axis[0], s_scan.op.scan_axis]))21 def test_fix_pt():22 body = tvm.schedule.ScanGetBody(s_scan.op)23 fxpt = tvm.schedule.ScanFixPointAnalysis(s_scan.op, body)24 assert(fxpt[s_scan.spatial_axis_[0]].value != 0)25def test_scan_fix_point():26 m = tvm.var("m")27 n = tvm.var("n")28 l = tvm.var("l")29 x = tvm.compute((l, m, n), lambda *i: tvm.const(1, "float32"), name="x")30 s_state = tvm.placeholder((l, m, n))31 s_init = tvm.compute((1, m, n), lambda _, i, j: x[0, i, j], name="s_init")32 def test_scan0():33 s_update = tvm.compute((l, m, n),34 lambda t, i, j: x[t, j, i] + s_state[t-1, i, j], name="update")35 s_scan = tvm.scan(s_init, s_update, s_state)36 body = tvm.schedule.ScanGetBody(s_scan.op)37 fxpt = tvm.schedule.ScanFixPointAnalysis(s_scan.op, body)38 assert(fxpt[s_scan.op.spatial_axis_[0]].value == 1)39 assert(fxpt[s_scan.op.spatial_axis_[1]].value == 1)40 def test_scan1():41 s_update = tvm.compute((l, m, n),42 lambda t, i, j: x[t, j, i] + s_state[t-1, j, i], name="update")43 s_scan = tvm.scan(s_init, s_update, s_state)44 body = tvm.schedule.ScanGetBody(s_scan.op)45 fxpt = tvm.schedule.ScanFixPointAnalysis(s_scan.op, body)46 assert(fxpt[s_scan.op.spatial_axis_[0]].value == 0)47 assert(fxpt[s_scan.op.spatial_axis_[1]].value == 0)48 def test_scan3_not_exact_reach():49 s_h1 = tvm.compute((l, n, m), lambda t, j, i: s_state[t-1, i, j], name="h1")50 s_h2 = tvm.compute((l, m, n), lambda t, i, j: s_state[t-1, i, 10] * 2, name="h1")51 s_update = tvm.compute((l, m, n), lambda t, i, j: s_h1[t, j, i] + s_h2[t, i, j], name="update")52 s_scan = tvm.scan(s_init, s_update, s_state)53 body = tvm.schedule.ScanGetBody(s_scan.op)54 fxpt = tvm.schedule.ScanFixPointAnalysis(s_scan.op)55 assert(fxpt[s_scan.op.spatial_axis_[0]].value == 1)56 assert(fxpt[s_scan.op.spatial_axis_[1]].value == 0)57 def test_scan4_reach_other():58 s_h1 = tvm.compute((l, n, m), lambda t, j, i: s_state[t-1, j, j], name="h1")59 s_h2 = tvm.compute((l, m, n), lambda t, i, j: s_state[t-1, i, j] * 2, name="h1")60 s_update = tvm.compute((l, m, n),61 lambda t, i, j: s_h1[t, j, i] + s_h2[t, i, j], name="update")62 s_scan = tvm.scan(s_init, s_update, s_state)63 fxpt = tvm.schedule.ScanFixPointAnalysis(s_scan.op)64 assert(fxpt[s_scan.op.spatial_axis_[0]].value == 0)65 assert(fxpt[s_scan.op.spatial_axis_[1]].value == 0)66 def test_scan5_multi_output():67 m = tvm.var("m")68 n = tvm.var("n")69 x1 = tvm.placeholder((m, n))70 s1 = tvm.placeholder((m, n))71 x2 = tvm.placeholder((m, n))72 s2 = tvm.placeholder((m, n))73 s1_init = tvm.compute((1, n), lambda _, i: x1[0, i])74 s2_init = tvm.compute((1, n), lambda _, i: x2[0, i])75 s1_update = tvm.compute((m, n), lambda t, i: s1[t-1, i] + x1[t, i])76 s2_update = tvm.compute((m, n), lambda t, i: x2[t, i] + s2[t-1,i])77 r0, r1 = tvm.scan([s1_init, s2_init],78 [s1_update, s2_update],79 [s1, s2])80 body = tvm.schedule.ScanGetBody(r0.op)81 fxpt = tvm.schedule.ScanFixPointAnalysis(r0.op)82 assert(fxpt[r1.op.spatial_axis_[0]].value == 1)83 test_scan0()84 test_scan1()85 test_scan3_not_exact_reach()86 test_scan4_reach_other()87 test_scan5_multi_output()88def test_create_read_graph():89 m = tvm.var('m')90 l = tvm.var('l')91 A = tvm.placeholder((m, l), name='A')92 A1 = tvm.compute((m, l), lambda i, j: A[i, j])93 A2 = tvm.compute((m, l), lambda i, j: A1[i, j] + 3)94 g = tvm.schedule.CreateReadGraph([A2.op])95 assert g[A2.op][0] == A196 assert g[A1.op][0] == A97 post_order = tvm.schedule.PostDFSOrder([A2.op], g)98 assert(post_order[0] == A.op)99 assert(post_order[1] == A1.op)100if __name__ == "__main__":101 test_scan()102 test_create_read_graph()...

Full Screen

Full Screen

tag.js

Source:tag.js Github

copy

Full Screen

1jest.mock(`apollo-server-express`)2const { PubSub } = require(`apollo-server-express`)3const { createTestDb, deleteTestDb } = require('../../test/db')4const {5 User,6 Tag,7 ScanClass,8 Device,9 Service,10 MqttSource,11} = require('../relations')12const fromUnixTime = require('date-fns/fromUnixTime')13const dbFilename = `test-tag-spread-edge.db`14const pubsub = new PubSub()15let db = undefined16beforeAll(async () => {17 db = await createTestDb().catch((error) => {18 throw error19 })20})21afterAll(async () => {22 await deleteTestDb(db).catch((error) => {23 throw error24 })25})26afterEach(() => {27 jest.clearAllMocks()28})29test(`Tag: initialize initializes ScanClass to.`, async () => {30 await Tag.initialize(db, pubsub)31 expect(ScanClass.initialized).toBe(true)32})33jest.useFakeTimers()34describe(`ScanClass:`, () => {35 test(`create creates a new ScanClass with the appropriate fields.`, async () => {36 await User.initialize(db, pubsub)37 const user = User.instances[0]38 const name = 'default'39 const description = 'Default Scan Class'40 const rate = 100041 const scanClass = await ScanClass.create(name, description, rate, user.id)42 expect(ScanClass.instances.length).toBe(1)43 expect(scanClass.id).toEqual(expect.any(Number))44 expect(scanClass.name).toBe(name)45 expect(scanClass.description).toBe(description)46 expect(scanClass.rate).toBe(rate)47 expect(scanClass.createdBy.id).toBe(user.id)48 })49 test(`stopScan doesn't clear an interval if there is isn't one.`, () => {50 const scanClass = ScanClass.instances[0]51 scanClass.stopScan()52 expect(clearInterval).toHaveBeenCalledTimes(0)53 })54 test(`startScan creates an interval`, () => {55 const scanClass = ScanClass.instances[0]56 scanClass.startScan()57 expect(setInterval).toHaveBeenCalledTimes(1)58 expect(setInterval).toHaveBeenCalledWith(59 expect.any(Function),60 scanClass.rate61 )62 })63 test(`stopScan clears an interval if there is one.`, () => {64 const scanClass = ScanClass.instances[0]65 scanClass.stopScan()66 expect(clearInterval).toHaveBeenCalledTimes(1)67 })68 test69 test(`Getters all return their underscore values`, () => {70 const scanClass = ScanClass.instances[0]71 expect(scanClass.rate).toBe(scanClass._rate)72 expect(scanClass.createdBy.id).toBe(scanClass._createdBy)73 expect(scanClass.createdOn).toStrictEqual(74 fromUnixTime(scanClass._createdOn)75 )76 })77 test(`Setters all set the values appropriately`, async () => {78 const scanClass = ScanClass.instances[0]79 const rate = 123480 await scanClass.setRate(rate)81 expect(scanClass.rate).toBe(rate)82 })83})84let tag = null85describe('Tag:', () => {86 test(`create creates a new Tag with the appropriate fields.`, async () => {87 const name = `testTag`88 const description = `Test Tag`89 const value = 12390 const scanClass = ScanClass.instances[0].id91 const createdBy = User.instances[0].id92 const datatype = `INT32`93 tag = await Tag.create(94 name,95 description,96 value,97 scanClass,98 createdBy,99 datatype100 )101 expect(tag.createdBy.id).toBe(createdBy)102 expect(tag.datatype).toBe(datatype)103 })104 test(`check that init sets the appropriate underscore fields.`, async () => {105 Tag.instances = []106 const uninitTag = new Tag(tag.id)107 await uninitTag.init()108 expect(uninitTag._name).toBe(tag._name)109 expect(uninitTag._description).toBe(tag._description)110 expect(uninitTag._value).toBe(tag._value)111 expect(uninitTag._scanClass).toBe(tag._scanClass)112 expect(uninitTag._createdBy).toBe(tag._createdBy)113 expect(uninitTag._CreatedOn).toBe(tag._CreatedOn)114 expect(uninitTag._datatype).toBe(tag._datatype)115 await Tag.getAll()116 })117 test(`Getters all return their underscore values`, () => {118 expect(tag.name).toBe(tag._name)119 expect(tag.description).toBe(tag._description)120 expect(tag.value).toBe(parseInt(tag._value))121 expect(tag.scanClass.id).toBe(tag._scanClass)122 expect(tag.createdBy.id).toBe(tag._createdBy)123 expect(tag.createdOn).toStrictEqual(fromUnixTime(tag._createdOn))124 expect(tag.datatype).toBe(tag._datatype)125 })126 test(`Setters all set the values appropriately`, async () => {127 const name = `newName`128 const description = `New description`129 const value = 321130 const datatype = `FLOAT`131 await tag.setName(name)132 await tag.setDescription(description)133 await tag.setValue(value)134 await tag.setDatatype(datatype)135 expect(tag.name).toBe(name)136 expect(tag.description).toBe(description)137 expect(tag.value).toBe(value)138 expect(tag.datatype).toBe(datatype)139 })140 test(`setScanClass with invalid scan class id throws error`, async () => {141 expect(await tag.setScanClass(12345).catch((e) => e)).toMatchInlineSnapshot(142 `[Error: Scan Class with 12345 does not exist.]`143 )144 })145})146test(`ScanClass: tags returns the tags we've assigned this scan class to.`, () => {147 const scanClass = ScanClass.instances[0]148 expect(scanClass.tags.length).toBe(1)149 expect(scanClass.tags[0].id).toBe(Tag.instances[0].id)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { scan } from 'ng-mocks';2import { MyComponent } from './my.component';3import { MyModule } from './my.module';4describe('MyComponent', () => {5 it('should render', () => {6 const fixture = MockRender(MyComponent, MyModule);7 const myComponent = scan(fixture.nativeElement).query(MyComponent);8 expect(myComponent).not.toBeNull();9 });10});11import { Component } from '@angular/core';12@Component({13})14export class MyComponent {}15import { NgModule } from '@angular/core';16import { CommonModule } from '@angular/common';17import { MyComponent } from './my.component';18@NgModule({19 imports: [CommonModule],20})21export class MyModule {}22{23 "compilerOptions": {24 "importHelpers": true,25 },26}27{28 "scripts": {29 },30 "dependencies": {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { scan } from 'ng-mocks';2const fixture = TestBed.createComponent(TestComponent);3const debugElement = fixture.debugElement;4const input = scan(debugElement, 'input');5const label = scan(debugElement, 'label');6import { find } from 'ng-mocks';7const fixture = TestBed.createComponent(TestComponent);8const debugElement = fixture.debugElement;9const input = find(debugElement, 'input');10const label = find(debugElement, 'label');11import { find } from 'ng-mocks';12const fixture = TestBed.createComponent(TestComponent);13const debugElement = fixture.debugElement;14const input = find(debugElement, 'input');15const label = find(debugElement, 'label');16import { find } from 'ng-mocks';17const fixture = TestBed.createComponent(TestComponent);18const debugElement = fixture.debugElement;19const input = find(debugElement, 'input');20const label = find(debugElement, 'label');21import { find } from 'ng-mocks';22const fixture = TestBed.createComponent(TestComponent);23const debugElement = fixture.debugElement;24const input = find(debugElement, 'input');25const label = find(debugElement, 'label');26import { find } from 'ng-mocks';27const fixture = TestBed.createComponent(TestComponent);28const debugElement = fixture.debugElement;29const input = find(debugElement, 'input');30const label = find(debugElement, 'label');31import { find } from 'ng-mocks';32const fixture = TestBed.createComponent(TestComponent);33const debugElement = fixture.debugElement;34const input = find(debugElement, 'input');

Full Screen

Using AI Code Generation

copy

Full Screen

1const el = ngMocks.find('my-id');2const el = ngMocks.find('my-id');3const el = ngMocks.find('my-id');4const el = ngMocks.find('my-id');5const el = ngMocks.find('my-id');6const el = ngMocks.find('my-id');7const el = ngMocks.find('my-id');8const el = ngMocks.find('my-id');9const el = ngMocks.find('my-id');10const el = ngMocks.find('my-id');11const el = ngMocks.find('my-id');12const el = ngMocks.find('my-id');13const el = ngMocks.find('my-id');14const el = ngMocks.find('my-id');

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 ng-mocks 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