prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import absolute_import class BadOption(Exception): """ Incorrect HTTP API arguments """ pass class RenderError(Exception): """ Error rendering page """ pass class InternalError(Exception): """ Unhandled internal error """ pass class GlobalTimeoutError(Exception): """ Timeout exceeded rendering page """ pass class UnsupportedContentType(Exception): """ Request Content-Type is not supported """ pass class ExpiredArguments(Exception): """ Arguments stored with ``save_args`` are expired """ pass class ScriptError(BadOption): """ Error happened while executing Lua script """ LUA_INIT_ERROR = 'LUA_INIT_ERROR' # error happened before coroutine starts LUA_ERROR = 'LUA_ERROR' # lua error() is called from the coroutine LUA_CONVERT_ERROR = 'LUA_CONVERT_ERROR' # result can't be converted to Python SPLASH_LUA_ERROR = 'SPLASH_LUA_ERROR' # custom error raised by Splash BAD_MAIN_ERROR = 'BAD_MAIN_ERROR' # main() definition is incorrect MAIN_NOT_FOUND_ERROR = 'MAIN_NOT_FOUND_ERROR' # main() is not found SYNTAX_ERROR = 'SYNTAX_ERROR' # XXX: unused; reported as INIT_ERROR now JS_ERROR = 'JS_ERROR' # error in a wrapped JS function UNKNOWN_ERROR = 'UNKNOWN_ERROR' class JsError(Exception): <|fim_middle|> class OneShotCallbackError(Exception): """ A one shot callback was called more than once. """ pass <|fim▁end|>
""" Error occured in JavaScript code """ pass
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import absolute_import class BadOption(Exception): """ Incorrect HTTP API arguments """ pass class RenderError(Exception): """ Error rendering page """ pass class InternalError(Exception): """ Unhandled internal error """ pass class GlobalTimeoutError(Exception): """ Timeout exceeded rendering page """ pass class UnsupportedContentType(Exception): """ Request Content-Type is not supported """ pass class ExpiredArguments(Exception): """ Arguments stored with ``save_args`` are expired """ pass class ScriptError(BadOption): """ Error happened while executing Lua script """ LUA_INIT_ERROR = 'LUA_INIT_ERROR' # error happened before coroutine starts LUA_ERROR = 'LUA_ERROR' # lua error() is called from the coroutine LUA_CONVERT_ERROR = 'LUA_CONVERT_ERROR' # result can't be converted to Python SPLASH_LUA_ERROR = 'SPLASH_LUA_ERROR' # custom error raised by Splash BAD_MAIN_ERROR = 'BAD_MAIN_ERROR' # main() definition is incorrect MAIN_NOT_FOUND_ERROR = 'MAIN_NOT_FOUND_ERROR' # main() is not found SYNTAX_ERROR = 'SYNTAX_ERROR' # XXX: unused; reported as INIT_ERROR now JS_ERROR = 'JS_ERROR' # error in a wrapped JS function UNKNOWN_ERROR = 'UNKNOWN_ERROR' class JsError(Exception): """ Error occured in JavaScript code """ pass class OneShotCallbackError(Exception): <|fim_middle|> <|fim▁end|>
""" A one shot callback was called more than once. """ pass
<|file_name|>test.py<|end_file_name|><|fim▁begin|><|fim▁hole|>result = subprocess.Popen('sh test.sh', shell=True) text = result.communicate()[0] sys.exit(result.returncode)<|fim▁end|>
import sys import subprocess
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT )<|fim▁hole|> try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True<|fim▁end|>
dev = []
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): "<|fim_middle|> class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
""Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True)
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): "<|fim_middle|> class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
""Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update()
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): "<|fim_middle|> @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
""Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): "<|fim_middle|> @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
""Return the name of the sensor.""" return self._name
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): "<|fim_middle|> @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
""Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2]
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): "<|fim_middle|> @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
""Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): "<|fim_middle|> @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
""Return the unique id of this entity.""" return f"{self._uuid}_{self.type}"
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): "<|fim_middle|> async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
""Return the unit of measurement of this entity.""" return self._unit_of_measurement
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): "<|fim_middle|> class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
""Get the latest data.""" await self.foobot_data.async_update()
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): "<|fim_middle|> <|fim▁end|>
""Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): "<|fim_middle|> @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
""Initialize the data object.""" self._client = client self._uuid = uuid self.data = {}
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): "<|fim_middle|> <|fim▁end|>
""Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": c <|fim_middle|> foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
ontinue
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def a<|fim_middle|>hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
sync_setup_platform(
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def _<|fim_middle|>self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
_init__(
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def n<|fim_middle|>self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
ame(
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def i<|fim_middle|>self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
con(
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def s<|fim_middle|>self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
tate(
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def u<|fim_middle|>self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
nique_id(
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def u<|fim_middle|>self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
nit_of_measurement(
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def a<|fim_middle|>self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
sync_update(
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def _<|fim_middle|>self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
_init__(
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for the Foobot indoor air quality monitor.""" import asyncio from datetime import timedelta import logging import aiohttp from foobot_async import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = "humidity" ATTR_PM2_5 = "PM2.5" ATTR_CARBON_DIOXIDE = "CO2" ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC" ATTR_FOOBOT_INDEX = "index" SENSOR_TYPES = { "time": [ATTR_TIME, "s"], "pm": [ATTR_PM2_5, "µg/m3", "mdi:cloud"], "tmp": [ATTR_TEMPERATURE, TEMP_CELSIUS, "mdi:thermometer"], "hum": [ATTR_HUMIDITY, "%", "mdi:water-percent"], "co2": [ATTR_CARBON_DIOXIDE, "ppm", "mdi:periodic-table-co2"], "voc": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, "ppb", "mdi:cloud"], "allpollu": [ATTR_FOOBOT_INDEX, "%", "mdi:percent"], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the devices associated with the account.""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug("The following devices were found: %s", devices) for device in devices: foobot_data = FoobotData(client, device["uuid"]) for sensor_type in SENSOR_TYPES: if sensor_type == "time": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception("Failed to connect to foobot servers.") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error("Failed to fetch data from foobot servers.") return async_add_entities(dev, True) class FoobotSensor(Entity): """Implementation of a Foobot sensor.""" def __init__(self, data, device, sensor_type): """Initialize the sensor.""" self._uuid = device["uuid"] self.foobot_data = data self._name = "Foobot {} {}".format(device["name"], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def icon(self): """Icon to use in the frontend.""" return SENSOR_TYPES[self.type][2] @property def state(self): """Return the state of the device.""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """Return the unique id of this entity.""" return f"{self._uuid}_{self.type}" @property def unit_of_measurement(self): """Return the unit of measurement of this entity.""" return self._unit_of_measurement async def async_update(self): """Get the latest data.""" await self.foobot_data.async_update() class FoobotData(Entity): """Get data from Foobot API.""" def __init__(self, client, uuid): """Initialize the data object.""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def a<|fim_middle|>self): """Get the data from Foobot API.""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug("Couldn't fetch data") return False _LOGGER.debug("The data response is: %s", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True <|fim▁end|>
sync_update(
<|file_name|>json_error_response.py<|end_file_name|><|fim▁begin|><|fim▁hole|>#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class JsonErrorResponse(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ Swagger model :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'status': 'str', 'message': 'str' } self.attribute_map = { 'status': 'status', 'message': 'message' } # Status: \&quot;ok\&quot; or \&quot;error\&quot; self.status = None # str # Error message self.message = None # str def __repr__(self): properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))<|fim▁end|>
<|file_name|>json_error_response.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class JsonErrorResponse(object): <|fim_middle|> <|fim▁end|>
""" NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ Swagger model :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'status': 'str', 'message': 'str' } self.attribute_map = { 'status': 'status', 'message': 'message' } # Status: \&quot;ok\&quot; or \&quot;error\&quot; self.status = None # str # Error message self.message = None # str def __repr__(self): properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))
<|file_name|>json_error_response.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class JsonErrorResponse(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): <|fim_middle|> def __repr__(self): properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) <|fim▁end|>
""" Swagger model :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'status': 'str', 'message': 'str' } self.attribute_map = { 'status': 'status', 'message': 'message' } # Status: \&quot;ok\&quot; or \&quot;error\&quot; self.status = None # str # Error message self.message = None # str
<|file_name|>json_error_response.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class JsonErrorResponse(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ Swagger model :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'status': 'str', 'message': 'str' } self.attribute_map = { 'status': 'status', 'message': 'message' } # Status: \&quot;ok\&quot; or \&quot;error\&quot; self.status = None # str # Error message self.message = None # str def __repr__(self): <|fim_middle|> <|fim▁end|>
properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))
<|file_name|>json_error_response.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class JsonErrorResponse(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ Swagger model :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'status': 'str', 'message': 'str' } self.attribute_map = { 'status': 'status', 'message': 'message' } # Status: \&quot;ok\&quot; or \&quot;error\&quot; self.status = None # str # Error message self.message = None # str def __repr__(self): properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': <|fim_middle|> return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) <|fim▁end|>
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
<|file_name|>json_error_response.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class JsonErrorResponse(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def <|fim_middle|>(self): """ Swagger model :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'status': 'str', 'message': 'str' } self.attribute_map = { 'status': 'status', 'message': 'message' } # Status: \&quot;ok\&quot; or \&quot;error\&quot; self.status = None # str # Error message self.message = None # str def __repr__(self): properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) <|fim▁end|>
__init__
<|file_name|>json_error_response.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class JsonErrorResponse(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ Swagger model :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'status': 'str', 'message': 'str' } self.attribute_map = { 'status': 'status', 'message': 'message' } # Status: \&quot;ok\&quot; or \&quot;error\&quot; self.status = None # str # Error message self.message = None # str def <|fim_middle|>(self): properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) <|fim▁end|>
__repr__
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0<|fim▁hole|> absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0<|fim▁end|>
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): <|fim_middle|> def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType)
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): <|fim_middle|> def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): <|fim_middle|> @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): <|fim_middle|> return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""Add something to the context.""" assert context == {} context.squee = "kapow"
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): <|fim_middle|> case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""Check that the context has been set up.""" assert context == {"squee": "kapow"}
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): <|fim_middle|> def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): <|fim_middle|> @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): <|fim_middle|> def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""Add something to the context.""" assert context == {} context.squee = "kapow"
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): <|fim_middle|> return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""Check that `context.squee` has changed.""" assert context == {"squee": "boing"}
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): <|fim_middle|> case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing"
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): <|fim_middle|> def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): <|fim_middle|> @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): <|fim_middle|> def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""Add something to the context.""" assert context == {} context.squee = "kapow"
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): <|fim_middle|> return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"}
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): <|fim_middle|> for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk"
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): <|fim_middle|> <|fim▁end|>
"""`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): <|fim_middle|> @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): <|fim_middle|> def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename)
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): <|fim_middle|> return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir)
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): <|fim_middle|> temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
"""Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): <|fim_middle|> else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
present += 1
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: <|fim_middle|> return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
absent += 1
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def <|fim_middle|>(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
test_exists
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def <|fim_middle|>(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
test_setup_only
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def <|fim_middle|>(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
setup_only
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def <|fim_middle|>(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
setup
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def <|fim_middle|>(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
case
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def <|fim_middle|>(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
test_setup_teardown
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def <|fim_middle|>(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
setup_teardown
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def <|fim_middle|>(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
setup
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def <|fim_middle|>(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
teardown
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def <|fim_middle|>(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
case
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def <|fim_middle|>(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
test_multiple_invocation
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def <|fim_middle|>(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
multiple
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def <|fim_middle|>(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
setup
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def <|fim_middle|>(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
teardown
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def <|fim_middle|>(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
case
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def <|fim_middle|>(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
test_external
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def <|fim_middle|>(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
external
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def <|fim_middle|>(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
setup
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def <|fim_middle|>(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
teardown
<|file_name|>test_with_fixture.py<|end_file_name|><|fim▁begin|>"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def <|fim_middle|>(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 <|fim▁end|>
check_files
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (C) 2014 Didotech srl (<http://www.didotech.com>). # # All Rights Reserved<|fim▁hole|># it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import sale_order from . import purchase_order<|fim▁end|>
# # This program is free software: you can redistribute it and/or modify
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist:<|fim▁hole|> if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j)<|fim▁end|>
distance = unit.norm( positions[i]-positions[j] )
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): <|fim_middle|> def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
""" Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): <|fim_middle|> def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value);
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): <|fim_middle|> def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
""" list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): <|fim_middle|> def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
""" Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx]
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): <|fim_middle|> def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
""" list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) )
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): <|fim_middle|> def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
""" add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance)
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): <|fim_middle|> def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
""" add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j)
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): <|fim_middle|> <|fim▁end|>
""" make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j)
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): <|fim_middle|> if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
return force
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: <|fim_middle|> return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
system.addForce(forcetype()) return findForce(system, forcetype)
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: <|fim_middle|> def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value);
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: <|fim_middle|> def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance)
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: <|fim_middle|> <|fim▁end|>
for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j)
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def <|fim_middle|>(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
findForce
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def <|fim_middle|>(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
setGlobalForceParameter
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def <|fim_middle|>(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
atomIndexInResidue
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def <|fim_middle|>(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
getResiduePositions
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def <|fim_middle|>(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
uniquePairs
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def <|fim_middle|>(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
addHarmonicConstraint
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def <|fim_middle|>(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
addExclusions
<|file_name|>openmm.py<|end_file_name|><|fim▁begin|>from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def <|fim_middle|>(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j) <|fim▁end|>
rigidifyResidue