Best Python code snippet using lisa_python
colorsensor.py
Source:colorsensor.py
...142 return self._delete(url=self.__sub_url)143class CapabilitiesAPI(HTTPRequester):144 __sub_url = "sensor/capabilities"145 @lru_cache()146 def _get_capabilities(self):147 return self._get(url=self.__sub_url)148 def get_output_pin_count(self):149 return self._get_capabilities()["output_pin_count"]150 def get_trigger_sources(self):151 return self._get_capabilities()["trigger_sources"]152 def get_maximum_sample_rate(self):153 return self._get_capabilities()["maximum_sample_rate"]154 def get_maximum_detectables_count(self):155 return self._get_capabilities()["maximum_detectables_count"]156 def get_maximum_matchers_count(self):157 return self._get_capabilities()["maximum_matchers_count"]158 def get_switching_output_drivers(self):159 return self._get_capabilities()["output_drivers"]160 def get_supported_tolerance_shapes(self):161 return {item["shape"] for item in self._get_capabilities()["tolerances"]}162 def get_supported_colorspaces(self):163 return {item["space_id"] for item in self._get_capabilities()["colorspaces"]}164class DetectionProfilesAPI(HTTPRequester):165 __sub_url = "sensor/detection-profiles"166 def get_detection_profiles(self):167 return self._get(url=self.__sub_url)168 def get_current_detection_profile(self):169 return self._get(url=(self.__sub_url, "current"))170 def get_detection_profile(self, any_id):171 return self._get(url=(self.__sub_url, str(any_id)))172 # for backwards compatibility173 get_detection_profile_by_uuid = get_detection_profile174 def post_detection_profile(self, data):175 return self._post(url=self.__sub_url, data=data)176 def change_detection_profile(self, any_id, data):177 return self._put(url=(self.__sub_url, str(any_id)), data=data)...
test_security.py
Source:test_security.py
1# Copyright (c) 2018 Intel Corporation2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14from unittest.mock import patch15from wca.config import ValidationError16import pytest17import wca.security18@patch('wca.security.LIBC.capget', return_value=-1)19@patch('os.geteuid', return_value=1000)20def test_privileges_failed_capget(mock_geteuid, mock_capget):21 with pytest.raises(wca.security.GettingCapabilitiesFailed):22 wca.security.are_privileges_sufficient()23@patch('wca.security.log.error')24@patch('os.geteuid', return_value=1000)25@patch('wca.security._get_capabilities', return_value=wca.security.UserCapDataStruct(0, 0, 0))26@patch('wca.security._get_securebits', return_value=0)27@patch('wca.security._read_paranoid', return_value=1)28@pytest.mark.parametrize(29 'use_cgroup, use_resctrl, use_perf, expected_log', [30 (True, True, True,31 'Insufficient privileges! For unprivileged user '32 'it is needed to have: CAP_DAC_OVERRIDE set. CAP_SETUID and SECBIT_NO_SETUID_FIXUP '33 'set. "/proc/sys/kernel/perf_event_paranoid" set to (0 or -1).'),34 (False, True, True,35 'Insufficient privileges! For unprivileged user '36 'it is needed to have: CAP_SETUID and SECBIT_NO_SETUID_FIXUP set.'37 ' "/proc/sys/kernel/perf_event_paranoid" set to (0 or -1).'),38 (True, False, True,39 'Insufficient privileges! For unprivileged user '40 'it is needed to have: CAP_DAC_OVERRIDE set.'41 ' "/proc/sys/kernel/perf_event_paranoid" set to (0 or -1).'),42 (True, True, False,43 'Insufficient privileges! For unprivileged user '44 'it is needed to have: CAP_DAC_OVERRIDE set. CAP_SETUID and SECBIT_NO_SETUID_FIXUP '45 'set.'),46 ])47def test_privileges_failed(mock_read_paranoid, mock_get_securebits, mock_get_capabilities,48 mock_getuid, mock_log, use_cgroup, use_resctrl, use_perf, expected_log):49 assert not wca.security.are_privileges_sufficient(use_cgroup, use_resctrl, use_perf)50 mock_log.assert_called_with(expected_log)51@patch('wca.security.log.error')52@patch('os.geteuid', return_value=1000)53@patch('wca.security._get_capabilities', return_value=wca.security.UserCapDataStruct(130, 0, 0))54@patch('wca.security._get_securebits', return_value=12)55@patch('wca.security._read_paranoid', return_value=-1)56@pytest.mark.parametrize(57 'use_cgroup, use_resctrl, use_perf', [58 (True, True, True),59 (False, True, True),60 (True, False, True),61 (True, True, False),62 ])63def test_privileges_successful(mock_read_paranoid, mock_get_securebits, mock_get_capabilities,64 mock_getuid, mock_log, use_cgroup, use_resctrl, use_perf):65 assert wca.security.are_privileges_sufficient(use_cgroup, use_resctrl, use_perf)66 mock_log.assert_not_called()67@patch('wca.security.log.error')68@patch('os.geteuid', return_value=1000)69@patch('wca.security._get_capabilities', return_value=wca.security.UserCapDataStruct(128, 0, 0))70@patch('wca.security._get_securebits', return_value=12)71@patch('wca.security._read_paranoid', return_value=-1)72def test_privileges_failed_no_cap_dac_override(mock_read_paranoid, mock_get_securebits,73 mock_get_capabilities, mock_getuid, mock_log):74 assert not wca.security.are_privileges_sufficient(True, True, True)75 mock_log.assert_called_with(76 'Insufficient privileges! For unprivileged user '77 'it is needed to have: CAP_DAC_OVERRIDE set.')78@patch('wca.security.log.error')79@patch('os.geteuid', return_value=1000)80@patch('wca.security._get_capabilities', return_value=wca.security.UserCapDataStruct(2, 0, 0))81@patch('wca.security._get_securebits', return_value=4)82@patch('wca.security._read_paranoid', return_value=-1)83def test_privileges_failed_no_cap_setuid_fixup_bit(mock_read_paranoid, mock_get_securebits,84 mock_get_capabilities, mock_getuid, mock_log):85 assert not wca.security.are_privileges_sufficient(True, True, True)86 mock_log.assert_called_with(87 'Insufficient privileges! For unprivileged user '88 'it is needed to have: CAP_SETUID and SECBIT_NO_SETUID_FIXUP set.')89@patch('wca.security.log.error')90@patch('os.geteuid', return_value=1000)91@patch('wca.security._get_capabilities', return_value=wca.security.UserCapDataStruct(130, 0, 0))92@patch('wca.security._get_securebits', return_value=0)93@patch('wca.security._read_paranoid', return_value=-1)94def test_privileges_failed_cap_setuid_no_fixup_bit(mock_read_paranoid, mock_get_securebits,95 mock_get_capabilities, mock_getuid, mock_log):96 assert not wca.security.are_privileges_sufficient(True, True, True)97 mock_log.assert_called_with(98 'Insufficient privileges! For unprivileged user '99 'it is needed to have: CAP_SETUID and SECBIT_NO_SETUID_FIXUP set.')100@patch('wca.security.log.error')101@patch('os.geteuid', return_value=1000)102@patch('wca.security._get_capabilities', return_value=wca.security.UserCapDataStruct(130, 0, 0))103@patch('wca.security._get_securebits', return_value=4)104@patch('wca.security._read_paranoid', return_value=2)105def test_privileges_failed_perf_event_paranoid_set(mock_read_paranoid, mock_get_securebits,106 mock_get_capabilities, mock_getuid, mock_log):107 assert not wca.security.are_privileges_sufficient(True, True, True)108 mock_log.assert_called_with(109 'Insufficient privileges! For unprivileged user '110 'it is needed to have: "/proc/sys/kernel/perf_event_paranoid" set to (0 or -1).')111def test_privileges_return_true_no_permissions_needed():112 assert wca.security.are_privileges_sufficient(False, False, False)113def test_ssl_error_only_client_key():114 """Tests that SSL throws ValidationError when only client key path is provided."""115 with pytest.raises(ValidationError):116 wca.security.SSL(client_key_path='/key')117def test_ssl_accept_single_file():118 """Tests that SSL accepts single file with client certificate and key."""119 wca.security.SSL(client_cert_path='/cert.pem')120def test_ssl_get_client_certs_single_file():121 """Tests that get_client_certs() returns file path with client certificate and key."""122 ssl = wca.security.SSL(client_cert_path='/cert.pem')123 assert ssl.client_key_path is None124 assert ssl.get_client_certs() == '/cert.pem'125def test_ssl_get_client_certs_tuple():126 """Tests that get_client_certs() returns tuple with client certificate and key paths."""127 ssl = wca.security.SSL(client_cert_path='/cert', client_key_path='/key')...
compute_capabilities_filter.py
Source:compute_capabilities_filter.py
...21class ComputeCapabilitiesFilter(filters.BaseHostFilter):22 """HostFilter hard-coded to work with InstanceType records."""23 # Instance type and host capabilities do not change within a request24 run_filter_once_per_request = True25 def _get_capabilities(self, host_state, scope):26 cap = host_state27 for index in range(0, len(scope)):28 try:29 if isinstance(cap, six.string_types):30 try:31 cap = jsonutils.loads(cap)32 except ValueError as e:33 LOG.debug("%(host_state)s fails. The capabilities "34 "'%(cap)s' couldn't be loaded from JSON: "35 "%(error)s",36 {'host_state': host_state, 'cap': cap,37 'error': e})38 return None39 if not isinstance(cap, dict):40 if getattr(cap, scope[index], None) is None:41 # If can't find, check stats dict42 cap = cap.stats.get(scope[index], None)43 else:44 cap = getattr(cap, scope[index], None)45 else:46 cap = cap.get(scope[index], None)47 except AttributeError as e:48 LOG.debug("%(host_state)s fails. The capabilities couldn't "49 "be retrieved: %(error)s.",50 {'host_state': host_state, 'error': e})51 return None52 if cap is None:53 LOG.debug("%(host_state)s fails. There are no capabilities "54 "to retrieve.",55 {'host_state': host_state})56 return None57 return cap58 def _satisfies_extra_specs(self, host_state, instance_type):59 """Check that the host_state provided by the compute service60 satisfies the extra specs associated with the instance type.61 """62 if 'extra_specs' not in instance_type:63 return True64 for key, req in six.iteritems(instance_type.extra_specs):65 # Either not scope format, or in capabilities scope66 scope = key.split(':')67 if len(scope) > 1:68 if scope[0] != "capabilities":69 continue70 else:71 del scope[0]72 cap = self._get_capabilities(host_state, scope)73 if cap is None:74 return False75 if not extra_specs_ops.match(str(cap), req):76 LOG.debug("%(host_state)s fails extra_spec requirements. "77 "'%(req)s' does not match '%(cap)s'",78 {'host_state': host_state, 'req': req,79 'cap': cap})80 return False81 return True82 def host_passes(self, host_state, spec_obj):83 """Return a list of hosts that can create instance_type."""84 instance_type = spec_obj.flavor85 if not self._satisfies_extra_specs(host_state,86 instance_type):...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!