How to use until method in elementium

Best Python code snippet using elementium_python

webdriverwait_tests.py

Source:webdriverwait_tests.py Github

copy

Full Screen

...38 def testShouldExplicitlyWaitForASingleElement(self):39 self._loadPage("dynamic")40 add = self.driver.find_element_by_id("adder")41 add.click();42 WebDriverWait(self.driver, 3).until(EC.presence_of_element_located((By.ID, "box0"))) # All is well if this doesn't throw.43 def testShouldStillFailToFindAnElementWithExplicitWait(self):44 self._loadPage("dynamic")45 try:46 WebDriverWait(self.driver, 0.7).until(EC.presence_of_element_located((By.ID, "box0")))47 self.fail("Expected TimeoutException to have been thrown")48 except TimeoutException as e:49 pass50 except Exception as e:51 self.fail("Expected TimeoutException but got " + str(e))52 def testShouldExplicitlyWaituntilAtLeastOneElementIsFoundWhenSearchingForMany(self):53 self._loadPage("dynamic")54 add = self.driver.find_element_by_id("adder")55 add.click();56 add.click();57 elements = WebDriverWait(self.driver, 2).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "redbox")))58 self.assertTrue(len(elements) >= 1)59 def testShouldFailToFindElementsWhenExplicitWaiting(self):60 self._loadPage("dynamic")61 try:62 elements = WebDriverWait(self.driver, 0.7).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "redbox")))63 except TimeoutException as e:64 pass # we should get a timeout65 except Exception as e:66 self.fail("Expected TimeoutException but got " + str(e))67 def testShouldWaitOnlyAsLongAsTimeoutSpecifiedWhenImplicitWaitsAreSet(self):68 self._loadPage("dynamic")69 self.driver.implicitly_wait(0.5)70 try:71 start = time.time()72 try:73 WebDriverWait(self.driver, 1).until(EC.presence_of_element_located((By.ID, "box0")))74 self.fail("Expected TimeoutException to have been thrown")75 except TimeoutException as e:76 pass77 self.assertTrue(time.time() - start < 1.5, 78 "Expected to take just over 1 second to execute, but took %f" % 79 (time.time() - start))80 finally:81 self.driver.implicitly_wait(0)82 def testShouldWaitAtLeastOnce(self):83 self._loadPage("simpleTest")84 elements_exists = lambda driver: driver.find_elements_by_tag_name('h1')85 elements = WebDriverWait(self.driver, 0).until(elements_exists)86 self.assertTrue(len(elements) >= 1)87 def testWaitUntilNotReturnsIfEvaluatesToFalse(self):88 falsum = lambda driver: False89 self.assertFalse(WebDriverWait(self.driver, 1).until_not(falsum))90 def testWaitShouldStillFailIfProduceIgnoredException(self):91 ignored = (InvalidElementStateException, StaleElementReferenceException)92 try:93 WebDriverWait(self.driver, 1, 0.7, ignored_exceptions=ignored).until(throwSERE)94 self.fail("Expected TimeoutException to have been thrown")95 except TimeoutException as e:96 pass97 def testWaitShouldStillFailIfProduceChildOfIgnoredException(self):98 ignored = (WebDriverException)99 try:100 WebDriverWait(self.driver, 1, 0.7, ignored_exceptions=ignored).until(throwSERE)101 self.fail("Expected TimeoutException to have been thrown")102 except TimeoutException as e:103 pass104 def testWaitUntilNotShouldNotFailIfProduceIgnoredException(self):105 ignored = (InvalidElementStateException, StaleElementReferenceException)106 self.assertTrue(WebDriverWait(self.driver, 1, 0.7, ignored_exceptions=ignored).until_not(throwSERE))107 def testExpectedConditionTitleIs(self):108 self._loadPage("blank")109 WebDriverWait(self.driver, 1).until(EC.title_is("blank"))110 self.driver.execute_script("setTimeout(function(){document.title='not blank'}, 200)")111 WebDriverWait(self.driver, 1).until(EC.title_is("not blank"))112 self.assertEqual(self.driver.title, 'not blank')113 try:114 WebDriverWait(self.driver, 0.7).until(EC.title_is("blank"))115 self.fail("Expected TimeoutException to have been thrown")116 except TimeoutException as e:117 pass118 def testExpectedConditionTitleContains(self):119 self._loadPage("blank")120 self.driver.execute_script("setTimeout(function(){document.title='not blank'}, 200)")121 WebDriverWait(self.driver, 1).until(EC.title_contains("not"))122 self.assertEqual(self.driver.title, 'not blank')123 try:124 WebDriverWait(self.driver, 0.7).until(EC.title_contains("blanket"))125 self.fail("Expected TimeoutException to have been thrown")126 except TimeoutException as e:127 pass128 129 def testExpectedConditionVisibilityOfElementLocated(self):130 self._loadPage("javascriptPage")131 try:132 WebDriverWait(self.driver, 0.7).until(EC.visibility_of_element_located((By.ID, 'clickToHide')))133 self.fail("Expected TimeoutException to have been thrown")134 except TimeoutException as e:135 pass136 self.driver.find_element_by_id('clickToShow').click()137 element = WebDriverWait(self.driver, 5).until(EC.visibility_of_element_located((By.ID, 'clickToHide')))138 self.assertTrue(element.is_displayed())139 def testExpectedConditionVisibilityOf(self):140 self._loadPage("javascriptPage")141 hidden = self.driver.find_element_by_id('clickToHide')142 try:143 WebDriverWait(self.driver, 0.7).until(EC.visibility_of(hidden))144 self.fail("Expected TimeoutException to have been thrown")145 except TimeoutException as e:146 pass147 self.driver.find_element_by_id('clickToShow').click()148 element = WebDriverWait(self.driver, 5).until(EC.visibility_of(hidden))149 self.assertTrue(element.is_displayed())150 151 def testExpectedConditionTextToBePresentInElement(self):152 self._loadPage('booleanAttributes')153 try:154 WebDriverWait(self.driver, 0.7).until(EC.text_to_be_present_in_element((By.ID, 'unwrappable'), 'Expected'))155 self.fail("Expected TimeoutException to have been thrown")156 except TimeoutException as e:157 pass158 self.driver.execute_script("setTimeout(function(){var el = document.getElementById('unwrappable'); el.textContent = el.innerText = 'Unwrappable Expected text'}, 200)")159 WebDriverWait(self.driver, 1).until(EC.text_to_be_present_in_element((By.ID, 'unwrappable'), 'Expected'))160 self.assertEqual('Unwrappable Expected text', self.driver.find_element_by_id('unwrappable').text)161 162 def testExpectedConditionTextToBePresentInElementValue(self):163 self._loadPage('booleanAttributes')164 try:165 WebDriverWait(self.driver, 1).until(EC.text_to_be_present_in_element_value((By.ID, 'inputRequired'), 'Expected'))166 self.fail("Expected TimeoutException to have been thrown")167 except TimeoutException as e:168 pass169 self.driver.execute_script("setTimeout(function(){document.getElementById('inputRequired').value = 'Example Expected text'}, 200)")170 WebDriverWait(self.driver, 1).until(EC.text_to_be_present_in_element_value((By.ID, 'inputRequired'), 'Expected'))171 self.assertEqual('Example Expected text', self.driver.find_element_by_id('inputRequired').get_attribute('value'))172 173 def testExpectedConditionFrameToBeAvailableAndSwitchTo(self):174 self._loadPage("blank")175 try:176 WebDriverWait(self.driver, 1).until(EC.frame_to_be_available_and_switch_to_it('myFrame'))177 self.fail("Expected TimeoutException to have been thrown")178 except TimeoutException as e:179 pass180 self.driver.execute_script("setTimeout(function(){var f = document.createElement('iframe'); f.id='myFrame'; f.src = '"+self._pageURL('iframeWithAlert')+"'; document.body.appendChild(f)}, 200)")181 WebDriverWait(self.driver, 1).until(EC.frame_to_be_available_and_switch_to_it('myFrame'))182 self.assertEqual('click me', self.driver.find_element_by_id('alertInFrame').text)183 184 def testExpectedConditionInvisiblityOfElementLocated(self):185 self._loadPage("javascriptPage")186 self.driver.execute_script("delayedShowHide(0, true)")187 try:188 WebDriverWait(self.driver, 0.7).until(EC.invisibility_of_element_located((By.ID, 'clickToHide')))189 self.fail("Expected TimeoutException to have been thrown")190 except TimeoutException as e:191 pass192 self.driver.execute_script("delayedShowHide(200, false)")193 WebDriverWait(self.driver, 0.7).until(EC.invisibility_of_element_located((By.ID, 'clickToHide')))194 self.assertFalse(self.driver.find_element_by_id('clickToHide').is_displayed())195 196 def testExpectedConditionElementToBeClickable(self):197 self._loadPage("javascriptPage")198 try:199 WebDriverWait(self.driver, 0.7).until(EC.element_to_be_clickable((By.ID, 'clickToHide')))200 self.fail("Expected TimeoutException to have been thrown")201 except TimeoutException as e:202 pass203 self.driver.execute_script("delayedShowHide(200, true)")204 WebDriverWait(self.driver, 0.7).until(EC.element_to_be_clickable((By.ID, 'clickToHide')))205 element = self.driver.find_element_by_id('clickToHide')206 element.click()207 WebDriverWait(self.driver, 3.5).until(EC.invisibility_of_element_located((By.ID, 'clickToHide')))208 self.assertFalse(element.is_displayed())209 210 def testExpectedConditionStalenessOf(self):211 self._loadPage('dynamicallyModifiedPage')212 element = self.driver.find_element_by_id('element-to-remove')213 try:214 WebDriverWait(self.driver, 0.7).until(EC.staleness_of(element))215 self.fail("Expected TimeoutException to have been thrown")216 except TimeoutException as e:217 pass218 self.driver.find_element_by_id('buttonDelete').click()219 self.assertEqual('element', element.text)220 WebDriverWait(self.driver, 0.7).until(EC.staleness_of(element))221 try:222 element.text223 self.fail("Expected StaleReferenceException to have been thrown")224 except StaleElementReferenceException as e:225 pass226 227 def testExpectedConditionElementToBeSelected(self):228 self._loadPage("formPage")229 element = self.driver.find_element_by_id('checky')230 try:231 WebDriverWait(self.driver, 0.7).until(EC.element_to_be_selected(element))232 self.fail("Expected TimeoutException to have been thrown")233 except TimeoutException as e:234 pass235 self.driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)")236 WebDriverWait(self.driver, 0.7).until(EC.element_to_be_selected(element))237 self.assertTrue(element.is_selected())238 239 def testExpectedConditionElementLocatedToBeSelected(self):240 self._loadPage("formPage")241 element = self.driver.find_element_by_id('checky')242 try:243 WebDriverWait(self.driver, 0.7).until(EC.element_located_to_be_selected((By.ID, 'checky')))244 self.fail("Expected TimeoutException to have been thrown")245 except TimeoutException as e:246 pass247 self.driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)")248 WebDriverWait(self.driver, 0.7).until(EC.element_located_to_be_selected((By.ID, 'checky')))249 self.assertTrue(element.is_selected())250 251 def testExpectedConditionElementSelectionStateToBe(self):252 self._loadPage("formPage")253 element = self.driver.find_element_by_id('checky')254 WebDriverWait(self.driver, 0.7).until(EC.element_selection_state_to_be(element, False))255 self.assertFalse(element.is_selected())256 try:257 WebDriverWait(self.driver, 0.7).until(EC.element_selection_state_to_be(element, True))258 self.fail("Expected TimeoutException to have been thrown")259 except TimeoutException as e:260 pass261 self.driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)")262 WebDriverWait(self.driver, 0.7).until(EC.element_selection_state_to_be(element, True))263 self.assertTrue(element.is_selected())264 265 def testExpectedConditionElementLocatedSelectionStateToBe(self):266 self._loadPage("formPage")267 element = self.driver.find_element_by_id('checky')268 WebDriverWait(self.driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), False))269 self.assertFalse(element.is_selected())270 try:271 WebDriverWait(self.driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), True))272 self.fail("Expected TimeoutException to have been thrown")273 except TimeoutException as e:274 pass275 self.driver.execute_script("setTimeout(function(){document.getElementById('checky').checked = true}, 200)")276 WebDriverWait(self.driver, 0.7).until(EC.element_located_selection_state_to_be((By.ID, 'checky'), True))277 self.assertTrue(element.is_selected())278 279 def testExpectedConditionAlertIsPresent(self):280 self._loadPage('blank')281 try:282 WebDriverWait(self.driver, 0.7).until(EC.alert_is_present())283 self.fail("Expected TimeoutException to have been thrown")284 except TimeoutException as e:285 pass286 self.driver.execute_script("setTimeout(function(){alert('alerty')}, 200)")287 WebDriverWait(self.driver, 0.7).until(EC.alert_is_present())288 alert = self.driver.switch_to_alert()289 self.assertEqual('alerty', alert.text)290 alert.dismiss()291 def _pageURL(self, name):292 return "http://localhost:%d/%s.html" % (self.webserver.port, name)293 def _loadSimplePage(self):294 self._loadPage("simpleTest")295 def _loadPage(self, name):...

Full Screen

Full Screen

climate.py

Source:climate.py Github

copy

Full Screen

1"""Support for Climate devices of (EMEA/EU-based) Honeywell TCC systems."""2from __future__ import annotations3from datetime import datetime as dt4import logging5from homeassistant.components.climate import ClimateEntity6from homeassistant.components.climate.const import (7 HVAC_MODE_AUTO,8 HVAC_MODE_HEAT,9 HVAC_MODE_OFF,10 PRESET_AWAY,11 PRESET_ECO,12 PRESET_HOME,13 PRESET_NONE,14 SUPPORT_PRESET_MODE,15 SUPPORT_TARGET_TEMPERATURE,16)17from homeassistant.const import PRECISION_TENTHS18from homeassistant.core import HomeAssistant19from homeassistant.helpers.entity_platform import AddEntitiesCallback20from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType21import homeassistant.util.dt as dt_util22from . import (23 ATTR_DURATION_DAYS,24 ATTR_DURATION_HOURS,25 ATTR_DURATION_UNTIL,26 ATTR_SYSTEM_MODE,27 ATTR_ZONE_TEMP,28 CONF_LOCATION_IDX,29 SVC_RESET_ZONE_OVERRIDE,30 SVC_SET_SYSTEM_MODE,31 EvoChild,32 EvoDevice,33)34from .const import (35 DOMAIN,36 EVO_AUTO,37 EVO_AUTOECO,38 EVO_AWAY,39 EVO_CUSTOM,40 EVO_DAYOFF,41 EVO_FOLLOW,42 EVO_HEATOFF,43 EVO_PERMOVER,44 EVO_RESET,45 EVO_TEMPOVER,46)47_LOGGER = logging.getLogger(__name__)48PRESET_RESET = "Reset" # reset all child zones to EVO_FOLLOW49PRESET_CUSTOM = "Custom"50HA_HVAC_TO_TCS = {HVAC_MODE_OFF: EVO_HEATOFF, HVAC_MODE_HEAT: EVO_AUTO}51TCS_PRESET_TO_HA = {52 EVO_AWAY: PRESET_AWAY,53 EVO_CUSTOM: PRESET_CUSTOM,54 EVO_AUTOECO: PRESET_ECO,55 EVO_DAYOFF: PRESET_HOME,56 EVO_RESET: PRESET_RESET,57} # EVO_AUTO: None,58HA_PRESET_TO_TCS = {v: k for k, v in TCS_PRESET_TO_HA.items()}59EVO_PRESET_TO_HA = {60 EVO_FOLLOW: PRESET_NONE,61 EVO_TEMPOVER: "temporary",62 EVO_PERMOVER: "permanent",63}64HA_PRESET_TO_EVO = {v: k for k, v in EVO_PRESET_TO_HA.items()}65STATE_ATTRS_TCS = ["systemId", "activeFaults", "systemModeStatus"]66STATE_ATTRS_ZONES = ["zoneId", "activeFaults", "setpointStatus", "temperatureStatus"]67async def async_setup_platform(68 hass: HomeAssistant,69 config: ConfigType,70 async_add_entities: AddEntitiesCallback,71 discovery_info: DiscoveryInfoType | None = None,72) -> None:73 """Create the evohome Controller, and its Zones, if any."""74 if discovery_info is None:75 return76 broker = hass.data[DOMAIN]["broker"]77 _LOGGER.debug(78 "Found the Location/Controller (%s), id=%s, name=%s (location_idx=%s)",79 broker.tcs.modelType,80 broker.tcs.systemId,81 broker.tcs.location.name,82 broker.params[CONF_LOCATION_IDX],83 )84 controller = EvoController(broker, broker.tcs)85 zones = []86 for zone in broker.tcs.zones.values():87 if zone.modelType == "HeatingZone" or zone.zoneType == "Thermostat":88 _LOGGER.debug(89 "Adding: %s (%s), id=%s, name=%s",90 zone.zoneType,91 zone.modelType,92 zone.zoneId,93 zone.name,94 )95 new_entity = EvoZone(broker, zone)96 zones.append(new_entity)97 else:98 _LOGGER.warning(99 "Ignoring: %s (%s), id=%s, name=%s: unknown/invalid zone type, "100 "report as an issue if you feel this zone type should be supported",101 zone.zoneType,102 zone.modelType,103 zone.zoneId,104 zone.name,105 )106 async_add_entities([controller] + zones, update_before_add=True)107class EvoClimateEntity(EvoDevice, ClimateEntity):108 """Base for an evohome Climate device."""109 def __init__(self, evo_broker, evo_device) -> None:110 """Initialize a Climate device."""111 super().__init__(evo_broker, evo_device)112 self._preset_modes = None113 @property114 def hvac_modes(self) -> list[str]:115 """Return a list of available hvac operation modes."""116 return list(HA_HVAC_TO_TCS)117 @property118 def preset_modes(self) -> list[str] | None:119 """Return a list of available preset modes."""120 return self._preset_modes121class EvoZone(EvoChild, EvoClimateEntity):122 """Base for a Honeywell TCC Zone."""123 def __init__(self, evo_broker, evo_device) -> None:124 """Initialize a Honeywell TCC Zone."""125 super().__init__(evo_broker, evo_device)126 if evo_device.modelType.startswith("VisionProWifi"):127 # this system does not have a distinct ID for the zone128 self._unique_id = f"{evo_device.zoneId}z"129 else:130 self._unique_id = evo_device.zoneId131 self._name = evo_device.name132 self._icon = "mdi:radiator"133 if evo_broker.client_v1:134 self._precision = PRECISION_TENTHS135 else:136 self._precision = self._evo_device.setpointCapabilities["valueResolution"]137 self._preset_modes = list(HA_PRESET_TO_EVO)138 self._supported_features = SUPPORT_PRESET_MODE | SUPPORT_TARGET_TEMPERATURE139 async def async_zone_svc_request(self, service: dict, data: dict) -> None:140 """Process a service request (setpoint override) for a zone."""141 if service == SVC_RESET_ZONE_OVERRIDE:142 await self._evo_broker.call_client_api(143 self._evo_device.cancel_temp_override()144 )145 return146 # otherwise it is SVC_SET_ZONE_OVERRIDE147 temperature = max(min(data[ATTR_ZONE_TEMP], self.max_temp), self.min_temp)148 if ATTR_DURATION_UNTIL in data:149 duration = data[ATTR_DURATION_UNTIL]150 if duration.total_seconds() == 0:151 await self._update_schedule()152 until = dt_util.parse_datetime(self.setpoints.get("next_sp_from", ""))153 else:154 until = dt_util.now() + data[ATTR_DURATION_UNTIL]155 else:156 until = None # indefinitely157 until = dt_util.as_utc(until) if until else None158 await self._evo_broker.call_client_api(159 self._evo_device.set_temperature(temperature, until=until)160 )161 @property162 def hvac_mode(self) -> str:163 """Return the current operating mode of a Zone."""164 if self._evo_tcs.systemModeStatus["mode"] in (EVO_AWAY, EVO_HEATOFF):165 return HVAC_MODE_AUTO166 is_off = self.target_temperature <= self.min_temp167 return HVAC_MODE_OFF if is_off else HVAC_MODE_HEAT168 @property169 def target_temperature(self) -> float:170 """Return the target temperature of a Zone."""171 return self._evo_device.setpointStatus["targetHeatTemperature"]172 @property173 def preset_mode(self) -> str | None:174 """Return the current preset mode, e.g., home, away, temp."""175 if self._evo_tcs.systemModeStatus["mode"] in (EVO_AWAY, EVO_HEATOFF):176 return TCS_PRESET_TO_HA.get(self._evo_tcs.systemModeStatus["mode"])177 return EVO_PRESET_TO_HA.get(self._evo_device.setpointStatus["setpointMode"])178 @property179 def min_temp(self) -> float:180 """Return the minimum target temperature of a Zone.181 The default is 5, but is user-configurable within 5-35 (in Celsius).182 """183 return self._evo_device.setpointCapabilities["minHeatSetpoint"]184 @property185 def max_temp(self) -> float:186 """Return the maximum target temperature of a Zone.187 The default is 35, but is user-configurable within 5-35 (in Celsius).188 """189 return self._evo_device.setpointCapabilities["maxHeatSetpoint"]190 async def async_set_temperature(self, **kwargs) -> None:191 """Set a new target temperature."""192 temperature = kwargs["temperature"]193 if (until := kwargs.get("until")) is None:194 if self._evo_device.setpointStatus["setpointMode"] == EVO_FOLLOW:195 await self._update_schedule()196 until = dt_util.parse_datetime(self.setpoints.get("next_sp_from", ""))197 elif self._evo_device.setpointStatus["setpointMode"] == EVO_TEMPOVER:198 until = dt_util.parse_datetime(self._evo_device.setpointStatus["until"])199 until = dt_util.as_utc(until) if until else None200 await self._evo_broker.call_client_api(201 self._evo_device.set_temperature(temperature, until=until)202 )203 async def async_set_hvac_mode(self, hvac_mode: str) -> None:204 """Set a Zone to one of its native EVO_* operating modes.205 Zones inherit their _effective_ operating mode from their Controller.206 Usually, Zones are in 'FollowSchedule' mode, where their setpoints are a207 function of their own schedule and the Controller's operating mode, e.g.208 'AutoWithEco' mode means their setpoint is (by default) 3C less than scheduled.209 However, Zones can _override_ these setpoints, either indefinitely,210 'PermanentOverride' mode, or for a set period of time, 'TemporaryOverride' mode211 (after which they will revert back to 'FollowSchedule' mode).212 Finally, some of the Controller's operating modes are _forced_ upon the Zones,213 regardless of any override mode, e.g. 'HeatingOff', Zones to (by default) 5C,214 and 'Away', Zones to (by default) 12C.215 """216 if hvac_mode == HVAC_MODE_OFF:217 await self._evo_broker.call_client_api(218 self._evo_device.set_temperature(self.min_temp, until=None)219 )220 else: # HVAC_MODE_HEAT221 await self._evo_broker.call_client_api(222 self._evo_device.cancel_temp_override()223 )224 async def async_set_preset_mode(self, preset_mode: str | None) -> None:225 """Set the preset mode; if None, then revert to following the schedule."""226 evo_preset_mode = HA_PRESET_TO_EVO.get(preset_mode, EVO_FOLLOW)227 if evo_preset_mode == EVO_FOLLOW:228 await self._evo_broker.call_client_api(229 self._evo_device.cancel_temp_override()230 )231 return232 temperature = self._evo_device.setpointStatus["targetHeatTemperature"]233 if evo_preset_mode == EVO_TEMPOVER:234 await self._update_schedule()235 until = dt_util.parse_datetime(self.setpoints.get("next_sp_from", ""))236 else: # EVO_PERMOVER237 until = None238 until = dt_util.as_utc(until) if until else None239 await self._evo_broker.call_client_api(240 self._evo_device.set_temperature(temperature, until=until)241 )242 async def async_update(self) -> None:243 """Get the latest state data for a Zone."""244 await super().async_update()245 for attr in STATE_ATTRS_ZONES:246 self._device_state_attrs[attr] = getattr(self._evo_device, attr)247class EvoController(EvoClimateEntity):248 """Base for a Honeywell TCC Controller/Location.249 The Controller (aka TCS, temperature control system) is the parent of all the child250 (CH/DHW) devices. It is implemented as a Climate entity to expose the controller's251 operating modes to HA.252 It is assumed there is only one TCS per location, and they are thus synonymous.253 """254 def __init__(self, evo_broker, evo_device) -> None:255 """Initialize a Honeywell TCC Controller/Location."""256 super().__init__(evo_broker, evo_device)257 self._unique_id = evo_device.systemId258 self._name = evo_device.location.name259 self._icon = "mdi:thermostat"260 self._precision = PRECISION_TENTHS261 modes = [m["systemMode"] for m in evo_broker.config["allowedSystemModes"]]262 self._preset_modes = [263 TCS_PRESET_TO_HA[m] for m in modes if m in list(TCS_PRESET_TO_HA)264 ]265 self._supported_features = SUPPORT_PRESET_MODE if self._preset_modes else 0266 async def async_tcs_svc_request(self, service: dict, data: dict) -> None:267 """Process a service request (system mode) for a controller.268 Data validation is not required, it will have been done upstream.269 """270 if service == SVC_SET_SYSTEM_MODE:271 mode = data[ATTR_SYSTEM_MODE]272 else: # otherwise it is SVC_RESET_SYSTEM273 mode = EVO_RESET274 if ATTR_DURATION_DAYS in data:275 until = dt_util.start_of_local_day()276 until += data[ATTR_DURATION_DAYS]277 elif ATTR_DURATION_HOURS in data:278 until = dt_util.now() + data[ATTR_DURATION_HOURS]279 else:280 until = None281 await self._set_tcs_mode(mode, until=until)282 async def _set_tcs_mode(self, mode: str, until: dt | None = None) -> None:283 """Set a Controller to any of its native EVO_* operating modes."""284 until = dt_util.as_utc(until) if until else None285 await self._evo_broker.call_client_api(286 self._evo_tcs.set_status(mode, until=until)287 )288 @property289 def hvac_mode(self) -> str:290 """Return the current operating mode of a Controller."""291 tcs_mode = self._evo_tcs.systemModeStatus["mode"]292 return HVAC_MODE_OFF if tcs_mode == EVO_HEATOFF else HVAC_MODE_HEAT293 @property294 def current_temperature(self) -> float | None:295 """Return the average current temperature of the heating Zones.296 Controllers do not have a current temp, but one is expected by HA.297 """298 temps = [299 z.temperatureStatus["temperature"]300 for z in self._evo_tcs.zones.values()301 if z.temperatureStatus["isAvailable"]302 ]303 return round(sum(temps) / len(temps), 1) if temps else None304 @property305 def preset_mode(self) -> str | None:306 """Return the current preset mode, e.g., home, away, temp."""307 return TCS_PRESET_TO_HA.get(self._evo_tcs.systemModeStatus["mode"])308 @property309 def min_temp(self) -> float:310 """Return None as Controllers don't have a target temperature."""311 return None312 @property313 def max_temp(self) -> float:314 """Return None as Controllers don't have a target temperature."""315 return None316 async def async_set_temperature(self, **kwargs) -> None:317 """Raise exception as Controllers don't have a target temperature."""318 raise NotImplementedError("Evohome Controllers don't have target temperatures.")319 async def async_set_hvac_mode(self, hvac_mode: str) -> None:320 """Set an operating mode for a Controller."""321 await self._set_tcs_mode(HA_HVAC_TO_TCS.get(hvac_mode))322 async def async_set_preset_mode(self, preset_mode: str | None) -> None:323 """Set the preset mode; if None, then revert to 'Auto' mode."""324 await self._set_tcs_mode(HA_PRESET_TO_TCS.get(preset_mode, EVO_AUTO))325 async def async_update(self) -> None:326 """Get the latest state data for a Controller."""327 self._device_state_attrs = {}328 attrs = self._device_state_attrs329 for attr in STATE_ATTRS_TCS:330 if attr == "activeFaults":331 attrs["activeSystemFaults"] = getattr(self._evo_tcs, attr)332 else:...

Full Screen

Full Screen

capability_service_pb.py

Source:capability_service_pb.py Github

copy

Full Screen

1#!/usr/bin/env python2#3# Copyright 2007 Google Inc.4#5# Licensed under the Apache License, Version 2.0 (the "License");6# you may not use this file except in compliance with the License.7# You may obtain a copy of 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,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16#17from google.net.proto import ProtocolBuffer18import array19import dummy_thread as thread20__pychecker__ = """maxreturns=0 maxbranches=0 no-callinit21 unusednames=printElemNumber,debug_strs no-special"""22if hasattr(ProtocolBuffer, 'ExtendableProtocolMessage'):23 _extension_runtime = True24 _ExtendableProtocolMessage = ProtocolBuffer.ExtendableProtocolMessage25else:26 _extension_runtime = False27 _ExtendableProtocolMessage = ProtocolBuffer.ProtocolMessage28from google.appengine.base.capabilities_pb import *29import google.appengine.base.capabilities_pb30class IsEnabledRequest(ProtocolBuffer.ProtocolMessage):31 has_package_ = 032 package_ = ""33 def __init__(self, contents=None):34 self.capability_ = []35 self.call_ = []36 if contents is not None: self.MergeFromString(contents)37 def package(self): return self.package_38 def set_package(self, x):39 self.has_package_ = 140 self.package_ = x41 def clear_package(self):42 if self.has_package_:43 self.has_package_ = 044 self.package_ = ""45 def has_package(self): return self.has_package_46 def capability_size(self): return len(self.capability_)47 def capability_list(self): return self.capability_48 def capability(self, i):49 return self.capability_[i]50 def set_capability(self, i, x):51 self.capability_[i] = x52 def add_capability(self, x):53 self.capability_.append(x)54 def clear_capability(self):55 self.capability_ = []56 def call_size(self): return len(self.call_)57 def call_list(self): return self.call_58 def call(self, i):59 return self.call_[i]60 def set_call(self, i, x):61 self.call_[i] = x62 def add_call(self, x):63 self.call_.append(x)64 def clear_call(self):65 self.call_ = []66 def MergeFrom(self, x):67 assert x is not self68 if (x.has_package()): self.set_package(x.package())69 for i in xrange(x.capability_size()): self.add_capability(x.capability(i))70 for i in xrange(x.call_size()): self.add_call(x.call(i))71 def Equals(self, x):72 if x is self: return 173 if self.has_package_ != x.has_package_: return 074 if self.has_package_ and self.package_ != x.package_: return 075 if len(self.capability_) != len(x.capability_): return 076 for e1, e2 in zip(self.capability_, x.capability_):77 if e1 != e2: return 078 if len(self.call_) != len(x.call_): return 079 for e1, e2 in zip(self.call_, x.call_):80 if e1 != e2: return 081 return 182 def IsInitialized(self, debug_strs=None):83 initialized = 184 if (not self.has_package_):85 initialized = 086 if debug_strs is not None:87 debug_strs.append('Required field: package not set.')88 return initialized89 def ByteSize(self):90 n = 091 n += self.lengthString(len(self.package_))92 n += 1 * len(self.capability_)93 for i in xrange(len(self.capability_)): n += self.lengthString(len(self.capability_[i]))94 n += 1 * len(self.call_)95 for i in xrange(len(self.call_)): n += self.lengthString(len(self.call_[i]))96 return n + 197 def ByteSizePartial(self):98 n = 099 if (self.has_package_):100 n += 1101 n += self.lengthString(len(self.package_))102 n += 1 * len(self.capability_)103 for i in xrange(len(self.capability_)): n += self.lengthString(len(self.capability_[i]))104 n += 1 * len(self.call_)105 for i in xrange(len(self.call_)): n += self.lengthString(len(self.call_[i]))106 return n107 def Clear(self):108 self.clear_package()109 self.clear_capability()110 self.clear_call()111 def OutputUnchecked(self, out):112 out.putVarInt32(10)113 out.putPrefixedString(self.package_)114 for i in xrange(len(self.capability_)):115 out.putVarInt32(18)116 out.putPrefixedString(self.capability_[i])117 for i in xrange(len(self.call_)):118 out.putVarInt32(26)119 out.putPrefixedString(self.call_[i])120 def OutputPartial(self, out):121 if (self.has_package_):122 out.putVarInt32(10)123 out.putPrefixedString(self.package_)124 for i in xrange(len(self.capability_)):125 out.putVarInt32(18)126 out.putPrefixedString(self.capability_[i])127 for i in xrange(len(self.call_)):128 out.putVarInt32(26)129 out.putPrefixedString(self.call_[i])130 def TryMerge(self, d):131 while d.avail() > 0:132 tt = d.getVarInt32()133 if tt == 10:134 self.set_package(d.getPrefixedString())135 continue136 if tt == 18:137 self.add_capability(d.getPrefixedString())138 continue139 if tt == 26:140 self.add_call(d.getPrefixedString())141 continue142 if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError143 d.skipData(tt)144 def __str__(self, prefix="", printElemNumber=0):145 res=""146 if self.has_package_: res+=prefix+("package: %s\n" % self.DebugFormatString(self.package_))147 cnt=0148 for e in self.capability_:149 elm=""150 if printElemNumber: elm="(%d)" % cnt151 res+=prefix+("capability%s: %s\n" % (elm, self.DebugFormatString(e)))152 cnt+=1153 cnt=0154 for e in self.call_:155 elm=""156 if printElemNumber: elm="(%d)" % cnt157 res+=prefix+("call%s: %s\n" % (elm, self.DebugFormatString(e)))158 cnt+=1159 return res160 def _BuildTagLookupTable(sparse, maxtag, default=None):161 return tuple([sparse.get(i, default) for i in xrange(0, 1+maxtag)])162 kpackage = 1163 kcapability = 2164 kcall = 3165 _TEXT = _BuildTagLookupTable({166 0: "ErrorCode",167 1: "package",168 2: "capability",169 3: "call",170 }, 3)171 _TYPES = _BuildTagLookupTable({172 0: ProtocolBuffer.Encoder.NUMERIC,173 1: ProtocolBuffer.Encoder.STRING,174 2: ProtocolBuffer.Encoder.STRING,175 3: ProtocolBuffer.Encoder.STRING,176 }, 3, ProtocolBuffer.Encoder.MAX_TYPE)177 _STYLE = """"""178 _STYLE_CONTENT_TYPE = """"""179 _PROTO_DESCRIPTOR_NAME = 'apphosting.IsEnabledRequest'180class IsEnabledResponse(ProtocolBuffer.ProtocolMessage):181 DEFAULT = 0182 ENABLED = 1183 SCHEDULED_FUTURE = 2184 SCHEDULED_NOW = 3185 DISABLED = 4186 UNKNOWN = 5187 _SummaryStatus_NAMES = {188 0: "DEFAULT",189 1: "ENABLED",190 2: "SCHEDULED_FUTURE",191 3: "SCHEDULED_NOW",192 4: "DISABLED",193 5: "UNKNOWN",194 }195 def SummaryStatus_Name(cls, x): return cls._SummaryStatus_NAMES.get(x, "")196 SummaryStatus_Name = classmethod(SummaryStatus_Name)197 has_summary_status_ = 0198 summary_status_ = 0199 has_time_until_scheduled_ = 0200 time_until_scheduled_ = 0201 def __init__(self, contents=None):202 self.config_ = []203 if contents is not None: self.MergeFromString(contents)204 def summary_status(self): return self.summary_status_205 def set_summary_status(self, x):206 self.has_summary_status_ = 1207 self.summary_status_ = x208 def clear_summary_status(self):209 if self.has_summary_status_:210 self.has_summary_status_ = 0211 self.summary_status_ = 0212 def has_summary_status(self): return self.has_summary_status_213 def time_until_scheduled(self): return self.time_until_scheduled_214 def set_time_until_scheduled(self, x):215 self.has_time_until_scheduled_ = 1216 self.time_until_scheduled_ = x217 def clear_time_until_scheduled(self):218 if self.has_time_until_scheduled_:219 self.has_time_until_scheduled_ = 0220 self.time_until_scheduled_ = 0221 def has_time_until_scheduled(self): return self.has_time_until_scheduled_222 def config_size(self): return len(self.config_)223 def config_list(self): return self.config_224 def config(self, i):225 return self.config_[i]226 def mutable_config(self, i):227 return self.config_[i]228 def add_config(self):229 x = CapabilityConfig()230 self.config_.append(x)231 return x232 def clear_config(self):233 self.config_ = []234 def MergeFrom(self, x):235 assert x is not self236 if (x.has_summary_status()): self.set_summary_status(x.summary_status())237 if (x.has_time_until_scheduled()): self.set_time_until_scheduled(x.time_until_scheduled())238 for i in xrange(x.config_size()): self.add_config().CopyFrom(x.config(i))239 def Equals(self, x):240 if x is self: return 1241 if self.has_summary_status_ != x.has_summary_status_: return 0242 if self.has_summary_status_ and self.summary_status_ != x.summary_status_: return 0243 if self.has_time_until_scheduled_ != x.has_time_until_scheduled_: return 0244 if self.has_time_until_scheduled_ and self.time_until_scheduled_ != x.time_until_scheduled_: return 0245 if len(self.config_) != len(x.config_): return 0246 for e1, e2 in zip(self.config_, x.config_):247 if e1 != e2: return 0248 return 1249 def IsInitialized(self, debug_strs=None):250 initialized = 1251 for p in self.config_:252 if not p.IsInitialized(debug_strs): initialized=0253 return initialized254 def ByteSize(self):255 n = 0256 if (self.has_summary_status_): n += 1 + self.lengthVarInt64(self.summary_status_)257 if (self.has_time_until_scheduled_): n += 1 + self.lengthVarInt64(self.time_until_scheduled_)258 n += 1 * len(self.config_)259 for i in xrange(len(self.config_)): n += self.lengthString(self.config_[i].ByteSize())260 return n261 def ByteSizePartial(self):262 n = 0263 if (self.has_summary_status_): n += 1 + self.lengthVarInt64(self.summary_status_)264 if (self.has_time_until_scheduled_): n += 1 + self.lengthVarInt64(self.time_until_scheduled_)265 n += 1 * len(self.config_)266 for i in xrange(len(self.config_)): n += self.lengthString(self.config_[i].ByteSizePartial())267 return n268 def Clear(self):269 self.clear_summary_status()270 self.clear_time_until_scheduled()271 self.clear_config()272 def OutputUnchecked(self, out):273 if (self.has_summary_status_):274 out.putVarInt32(8)275 out.putVarInt32(self.summary_status_)276 if (self.has_time_until_scheduled_):277 out.putVarInt32(16)278 out.putVarInt64(self.time_until_scheduled_)279 for i in xrange(len(self.config_)):280 out.putVarInt32(26)281 out.putVarInt32(self.config_[i].ByteSize())282 self.config_[i].OutputUnchecked(out)283 def OutputPartial(self, out):284 if (self.has_summary_status_):285 out.putVarInt32(8)286 out.putVarInt32(self.summary_status_)287 if (self.has_time_until_scheduled_):288 out.putVarInt32(16)289 out.putVarInt64(self.time_until_scheduled_)290 for i in xrange(len(self.config_)):291 out.putVarInt32(26)292 out.putVarInt32(self.config_[i].ByteSizePartial())293 self.config_[i].OutputPartial(out)294 def TryMerge(self, d):295 while d.avail() > 0:296 tt = d.getVarInt32()297 if tt == 8:298 self.set_summary_status(d.getVarInt32())299 continue300 if tt == 16:301 self.set_time_until_scheduled(d.getVarInt64())302 continue303 if tt == 26:304 length = d.getVarInt32()305 tmp = ProtocolBuffer.Decoder(d.buffer(), d.pos(), d.pos() + length)306 d.skip(length)307 self.add_config().TryMerge(tmp)308 continue309 if (tt == 0): raise ProtocolBuffer.ProtocolBufferDecodeError310 d.skipData(tt)311 def __str__(self, prefix="", printElemNumber=0):312 res=""313 if self.has_summary_status_: res+=prefix+("summary_status: %s\n" % self.DebugFormatInt32(self.summary_status_))314 if self.has_time_until_scheduled_: res+=prefix+("time_until_scheduled: %s\n" % self.DebugFormatInt64(self.time_until_scheduled_))315 cnt=0316 for e in self.config_:317 elm=""318 if printElemNumber: elm="(%d)" % cnt319 res+=prefix+("config%s <\n" % elm)320 res+=e.__str__(prefix + " ", printElemNumber)321 res+=prefix+">\n"322 cnt+=1323 return res324 def _BuildTagLookupTable(sparse, maxtag, default=None):325 return tuple([sparse.get(i, default) for i in xrange(0, 1+maxtag)])326 ksummary_status = 1327 ktime_until_scheduled = 2328 kconfig = 3329 _TEXT = _BuildTagLookupTable({330 0: "ErrorCode",331 1: "summary_status",332 2: "time_until_scheduled",333 3: "config",334 }, 3)335 _TYPES = _BuildTagLookupTable({336 0: ProtocolBuffer.Encoder.NUMERIC,337 1: ProtocolBuffer.Encoder.NUMERIC,338 2: ProtocolBuffer.Encoder.NUMERIC,339 3: ProtocolBuffer.Encoder.STRING,340 }, 3, ProtocolBuffer.Encoder.MAX_TYPE)341 _STYLE = """"""342 _STYLE_CONTENT_TYPE = """"""343 _PROTO_DESCRIPTOR_NAME = 'apphosting.IsEnabledResponse'344if _extension_runtime:345 pass...

Full Screen

Full Screen

extract_function.py

Source:extract_function.py Github

copy

Full Screen

1# -------------------------------------------------- in-module-02global_var = 33def x():4 foo = 3.15 #? 11 text {'new_name': 'bar'}6 x = int(foo + 1 + global_var)7# ++++++++++++++++++++++++++++++++++++++++++++++++++8global_var = 39def bar(foo):10 return int(foo + 1 + global_var)11def x():12 foo = 3.113 #? 11 text {'new_name': 'bar'}14 x = bar(foo)15# -------------------------------------------------- in-module-116glob = 317#? 11 text {'new_name': 'a'}18test(100, (glob.a + b, c) + 1)19# ++++++++++++++++++++++++++++++++++++++++++++++++++20glob = 321#? 11 text {'new_name': 'a'}22def a(b):23 return glob.a + b24test(100, (a(b), c) + 1)25# -------------------------------------------------- in-module-226#? 0 text {'new_name': 'ab'}27100 + 1 * 228# ++++++++++++++++++++++++++++++++++++++++++++++++++29#? 0 text {'new_name': 'ab'}30def ab():31 return 100 + 1 * 232ab()33# -------------------------------------------------- in-function-134def f(x):35#? 11 text {'new_name': 'ab'}36 return x + 1 * 237# ++++++++++++++++++++++++++++++++++++++++++++++++++38def ab(x):39 return x + 1 * 240def f(x):41#? 11 text {'new_name': 'ab'}42 return ab(x)43# -------------------------------------------------- in-function-with-dec44@classmethod45def f(x):46#? 11 text {'new_name': 'ab'}47 return x + 1 * 248# ++++++++++++++++++++++++++++++++++++++++++++++++++49def ab(x):50 return x + 1 * 251@classmethod52def f(x):53#? 11 text {'new_name': 'ab'}54 return ab(x)55# -------------------------------------------------- in-method-156class X:57 def z(self): pass58 def f(x, b):59 #? 11 text {'new_name': 'ab'}60 return x + b * 261# ++++++++++++++++++++++++++++++++++++++++++++++++++62class X:63 def z(self): pass64 def ab(x, b):65 return x + b * 266 def f(x, b):67 #? 11 text {'new_name': 'ab'}68 return x.ab(b)69# -------------------------------------------------- in-method-270glob1 = 171class X:72 def g(self): pass73 def f(self, b, c):74 #? 11 text {'new_name': 'ab'}75 return self.g() or self.f(b) ^ glob1 & b76# ++++++++++++++++++++++++++++++++++++++++++++++++++77glob1 = 178class X:79 def g(self): pass80 def ab(self, b):81 return self.g() or self.f(b) ^ glob1 & b82 def f(self, b, c):83 #? 11 text {'new_name': 'ab'}84 return self.ab(b)85# -------------------------------------------------- in-method-order86class X:87 def f(self, b, c):88 #? 18 text {'new_name': 'b'}89 return b | self.a90# ++++++++++++++++++++++++++++++++++++++++++++++++++91class X:92 def b(self, b):93 return b | self.a94 def f(self, b, c):95 #? 18 text {'new_name': 'b'}96 return self.b(b)97# -------------------------------------------------- in-classmethod-198class X:99 @classmethod100 def f(x):101 #? 16 text {'new_name': 'ab'}102 return 25103# ++++++++++++++++++++++++++++++++++++++++++++++++++104class X:105 @classmethod106 def ab(x):107 return 25108 @classmethod109 def f(x):110 #? 16 text {'new_name': 'ab'}111 return x.ab()112# -------------------------------------------------- in-staticmethod-1113class X(int):114 @staticmethod115 def f(x):116 #? 16 text {'new_name': 'ab'}117 return 25 | 3118# ++++++++++++++++++++++++++++++++++++++++++++++++++119def ab():120 return 25 | 3121class X(int):122 @staticmethod123 def f(x):124 #? 16 text {'new_name': 'ab'}125 return ab()126# -------------------------------------------------- in-class-1127class Ya():128 a = 3129 #? 11 text {'new_name': 'f'}130 c = a + 2131# ++++++++++++++++++++++++++++++++++++++++++++++++++132def f(a):133 return a + 2134class Ya():135 a = 3136 #? 11 text {'new_name': 'f'}137 c = f(a)138# -------------------------------------------------- in-closure139def x(z):140 def y(x):141 #? 15 text {'new_name': 'f'}142 return -x * z143# ++++++++++++++++++++++++++++++++++++++++++++++++++144def f(x, z):145 return -x * z146def x(z):147 def y(x):148 #? 15 text {'new_name': 'f'}149 return f(x, z)150# -------------------------------------------------- with-range-1151#? 0 text {'new_name': 'a', 'until_line': 4}152v1 = 3153v2 = 2154x = test(v1 + v2 * v3)155# ++++++++++++++++++++++++++++++++++++++++++++++++++156#? 0 text {'new_name': 'a', 'until_line': 4}157def a(test, v3):158 v1 = 3159 v2 = 2160 x = test(v1 + v2 * v3)161 return x162x = a(test, v3)163# -------------------------------------------------- with-range-2164#? 2 text {'new_name': 'a', 'until_line': 6, 'until_column': 4}165#foo166v1 = 3167v2 = 2168x, y = test(v1 + v2 * v3)169#raaaa170y171# ++++++++++++++++++++++++++++++++++++++++++++++++++172#? 2 text {'new_name': 'a', 'until_line': 6, 'until_column': 4}173def a(test, v3):174 #foo175 v1 = 3176 v2 = 2177 x, y = test(v1 + v2 * v3)178 #raaaa179 return y180y = a(test, v3)181y182# -------------------------------------------------- with-range-3183#foo184#? 2 text {'new_name': 'a', 'until_line': 5, 'until_column': 4}185v1 = 3186v2 = 2187x, y = test(v1 + v2 * v3)188#raaaa189y190# ++++++++++++++++++++++++++++++++++++++++++++++++++191#foo192#? 2 text {'new_name': 'a', 'until_line': 5, 'until_column': 4}193def a(test, v3):194 v1 = 3195 v2 = 2196 x, y = test(v1 + v2 * v3)197 return y198y = a(test, v3)199#raaaa200y201# -------------------------------------------------- with-range-func-1202import os203# comment1204@dec205# comment2206def x(v1):207 #foo208 #? 2 text {'new_name': 'a', 'until_line': 9, 'until_column': 5}209 v2 = 2210 if 1:211 x, y = os.listdir(v1 + v2 * v3)212 #bar213 return x, y214# ++++++++++++++++++++++++++++++++++++++++++++++++++215import os216# comment1217def a(v1, v3):218 v2 = 2219 if 1:220 x, y = os.listdir(v1 + v2 * v3)221 return x, y222@dec223# comment2224def x(v1):225 #foo226 #? 2 text {'new_name': 'a', 'until_line': 9, 'until_column': 5}227 x, y = a(v1, v3)228 #bar229 return x, y230# -------------------------------------------------- with-range-func-2231import os232# comment1233# comment2234def x(v1):235 #? 2 text {'new_name': 'a', 'until_line': 10, 'until_column': 0}236 #foo237 v2 = 2238 if 1:239 x, y = os.listdir(v1 + v2 * v3)240 #bar241 return y242x243# ++++++++++++++++++++++++++++++++++++++++++++++++++244import os245# comment1246# comment2247def a(v1, v3):248 #foo249 v2 = 2250 if 1:251 x, y = os.listdir(v1 + v2 * v3)252 #bar253 return y254def x(v1):255 #? 2 text {'new_name': 'a', 'until_line': 10, 'until_column': 0}256 y = a(v1, v3)257 return y258x259# -------------------------------------------------- with-range-func-3260def x(v1):261 #? 2 text {'new_name': 'func', 'until_line': 6, 'until_column': 4}262 #foo263 v2 = 2264 x = v1 * 2265 y = 3266 #bar267 return x268x269# ++++++++++++++++++++++++++++++++++++++++++++++++++270def func(v1):271 #foo272 v2 = 2273 x = v1 * 2274 return x275def x(v1):276 #? 2 text {'new_name': 'func', 'until_line': 6, 'until_column': 4}277 x = func(v1)278 y = 3279 #bar280 return x281x282# -------------------------------------------------- in-class-range-1283class X1:284 #? 9 text {'new_name': 'f', 'until_line': 4}285 a = 3286 c = a + 2287# ++++++++++++++++++++++++++++++++++++++++++++++++++288def f():289 a = 3290 c = a + 2291 return c292class X1:293 #? 9 text {'new_name': 'f', 'until_line': 4}294 c = f()295# -------------------------------------------------- in-method-range-1296glob1 = 1297class X:298 # ha299 def g(self): pass300 # haha301 def f(self, b, c):302 #? 11 text {'new_name': 'ab', 'until_line': 12, 'until_column': 28}303 #foo304 local1 = 3305 local2 = 4306 x= self.g() or self.f(b) ^ glob1 & b is local1307 # bar308# ++++++++++++++++++++++++++++++++++++++++++++++++++309glob1 = 1310class X:311 # ha312 def g(self): pass313 # haha314 def ab(self, b):315 #foo316 local1 = 3317 local2 = 4318 x= self.g() or self.f(b) ^ glob1 & b is local1319 return x320 def f(self, b, c):321 #? 11 text {'new_name': 'ab', 'until_line': 12, 'until_column': 28}322 x = self.ab(b)323 # bar324# -------------------------------------------------- in-method-range-2325glob1 = 1326class X:327 # comment328 def f(self, b, c):329 #? 11 text {'new_name': 'ab', 'until_line': 11, 'until_column': 10}330 #foo331 local1 = 3332 local2 = 4333 return local1 * glob1 * b334 # bar335# ++++++++++++++++++++++++++++++++++++++++++++++++++336glob1 = 1337class X:338 # comment339 def ab(self, b):340 #foo341 local1 = 3342 local2 = 4343 return local1 * glob1 * b344 # bar345 def f(self, b, c):346 #? 11 text {'new_name': 'ab', 'until_line': 11, 'until_column': 10}347 return self.ab(b)348# -------------------------------------------------- in-method-range-3349glob1 = 1350class X:351 def f(self, b, c):352 local1, local2 = 3, 4353 #foo354 #? 11 text {'new_name': 'ab', 'until_line': 7, 'until_column': 29}355 return local1 & glob1 & b356 # bar357 local2358# ++++++++++++++++++++++++++++++++++++++++++++++++++359glob1 = 1360class X:361 def ab(self, local1, b):362 return local1 & glob1 & b363 def f(self, b, c):364 local1, local2 = 3, 4365 #foo366 #? 11 text {'new_name': 'ab', 'until_line': 7, 'until_column': 29}367 return self.ab(local1, b)368 # bar369 local2370# -------------------------------------------------- in-method-no-param371glob1 = 1372class X:373 def f():374 #? 11 text {'new_name': 'ab', 'until_line': 5, 'until_column': 22}375 return glob1 + 2376# ++++++++++++++++++++++++++++++++++++++++++++++++++377glob1 = 1378class X:379 def ab():380 return glob1 + 2381 def f():382 #? 11 text {'new_name': 'ab', 'until_line': 5, 'until_column': 22}383 return ab()384# -------------------------------------------------- random-return-1385def x():386 #? 0 error {'new_name': 'ab', 'until_line': 5, 'until_column': 10}387 if x:388 return 1389 return 1390# ++++++++++++++++++++++++++++++++++++++++++++++++++391Can only extract return statements if they are at the end.392# -------------------------------------------------- random-return-2393def x():394 #? 0 error {'new_name': 'ab', 'until_line': 5, 'until_column': 10}395 #396 return397 pass398# ++++++++++++++++++++++++++++++++++++++++++++++++++399Can only extract return statements if they are at the end.400# -------------------------------------------------- random-yield-1401def x():402 #? 0 error {'new_name': 'ab', 'until_line': 5, 'until_column': 10}403 #404 if (yield 1):405 return406 pass407# ++++++++++++++++++++++++++++++++++++++++++++++++++408Cannot extract yield statements.409# -------------------------------------------------- random-yield-2410def x():411 #? 0 error {'new_name': 'ab', 'until_line': 4, 'until_column': 10}412 #413 try:414 yield415 finally:416 pass417# ++++++++++++++++++++++++++++++++++++++++++++++++++...

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run elementium 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