:>json list response: A forum poll :statuscode 200: View successful :statuscode 403: User does not have permission to view thread :statuscode 404: Thread does not exist """ return flask.jsonify(ForumPoll.from_pk(id, error=True, _404=True)) MODIFY_FORUM_POLL_SCHEMA = Schema({ 'choices': Schema({ Optional('add', default=[]): [str], Optional('delete', default=[]): [int], }), 'closed': BoolGET, 'featured': BoolGET, }) @bp.route('/polls/<int:id>', methods=['PUT']) @require_permission('modify_forum_polls') @validate_data(MODIFY_FORUM_POLL_SCHEMA) def modify_poll( id: int, choices: Dict[str, list] = None, closed: bool = None, featured: bool = None,
class DescribeServerHandler(Searcher, handler.TriggeredHandler): """Finds a virtual machine and describes it. This is on purpose eerily similar to OSC `server show` command. """ requires_topo_loader = True handles_what = { 'message_matcher': matchers.match_or(matchers.match_slack("message"), matchers.match_telnet("message")), 'channel_matcher': matchers.match_channel(c.TARGETED), 'triggers': [ trigger.Trigger('openstack server show', takes_args=True), ], 'args': { 'order': [ 'server', 'only_private', 'cloud', ], 'help': { 'server': 'server (name or id)', 'only_private': ('only search the private clouds' ' and skip the public clouds'), 'cloud': ("filter to only specific cloud (empty" " searches all clouds)"), }, 'converters': { 'only_private': hu.strict_bool_from_string, }, 'schema': Schema({ Required("server"): All(su.string_types(), Length(min=1)), Required("only_private"): bool, Required("cloud"): su.string_types(), }), 'defaults': { 'only_private': True, 'cloud': '', }, }, 'authorizer': auth.user_in_ldap_groups('admins_cloud_viewers'), } def _run(self, server, only_private=True, cloud=''): # Search should be unique across clouds target_search = True if uuidutils.is_uuid_like(server): # Find by UUID filters = {'uuid': server} elif netutils.is_valid_ip(server): # Find by IP address # Note: Much more expensive. Calling when exactly like an IP. filters = {'ip': _force_exact(server)} else: # Find by name (across all clouds) filters = {'name': _force_exact(server)} target_search = False # Name could exist in multiple clouds replier = functools.partial(self.message.reply_text, threaded=True, prefixed=False) servers, searched_clouds, _found_clouds = self._search( server, filters, target_search=target_search, only_private=only_private, cloud=cloud, replier=replier) if servers: self._emit_servers(servers) replier("Found %s possible matches, hopefully one of" " them was what you were looking for..." % len(servers)) else: replier("Sorry I could not find `%s` in %s clouds," " try another?" % (server, searched_clouds))
'true value allocation', 'waste treatment', ) valid_byproducts = Any('allocatable product', 'waste', 'recyclable') valid_technology_levels = Any(*list(TECHNOLOGY_LEVEL.values())) # Uncertainty distribution schemas valid_pedigree_matrix = Any({lbl: int for lbl in PEDIGREE_LABELS.values()}, {}) valid_lognormal = Schema( { 'mean': float, 'pedigree matrix': valid_pedigree_matrix, 'type': 'lognormal', 'variance with pedigree uncertainty': float, Optional('mu'): float, # Somehow this is optional (/missing) in some ecospold2 datasets Optional('variance'): float, }, required=True) valid_normal = Schema( { 'mean': float, 'pedigree matrix': valid_pedigree_matrix, 'type': 'normal', 'variance with pedigree uncertainty': float, Optional('variance'): float, }, required=True)
def _with_not(entity: object) -> Schema: """Add possibility to provide 'not' in the given configuration entity.""" return Schema(Any(entity, Schema({"not": entity})))
class ListServersOnHypervisor(Searcher, handler.TriggeredHandler): """Lists virtual machines on a hypervisor.""" requires_topo_loader = True handles_what = { 'message_matcher': matchers.match_or(matchers.match_slack("message"), matchers.match_telnet("message")), 'channel_matcher': matchers.match_channel(c.TARGETED), 'triggers': [ trigger.Trigger('openstack hypervisor list-vms', takes_args=True), ], 'args': { 'order': [ 'hypervisor', 'only_private', 'cloud', ], 'help': { 'hypervisor': 'hypervisor to list vms on', 'only_private': ('only search the private clouds' ' and skip the public clouds'), 'cloud': ("filter to only specific cloud (empty" " searches all clouds)"), }, 'converters': { 'only_private': hu.strict_bool_from_string, }, 'schema': Schema({ Required("hypervisor"): All(su.string_types(), Length(min=1)), Required("only_private"): bool, Required("cloud"): su.string_types(), }), 'defaults': { 'only_private': True, 'cloud': '', }, }, 'authorizer': auth.user_in_ldap_groups('admins_cloud_viewers'), } def _run(self, hypervisor, only_private=True, cloud=''): replier = functools.partial(self.message.reply_text, threaded=True, prefixed=False) servers, searched_clouds, _found_clouds = self._search( hypervisor, {'host': hypervisor}, target_search=True, only_private=only_private, cloud=cloud, replier=replier) if servers: self._emit_servers(servers) replier("Found %s possible matches, hopefully one of" " them was what you were looking for..." % len(servers)) else: replier("Sorry I could not find `%s` in %s clouds," " try another?" % (hypervisor, searched_clouds))
def test_url_validation(): """ test with valid URL """ schema = Schema({"url": Url()}) out_ = schema({"url": "http://example.com/"}) assert 'http://example.com/', out_.get("url")
def test_in(): """Verify that In works.""" schema = Schema({"color": In(frozenset(["blue", "red", "yellow"]))}) schema({"color": "blue"})
def main(): """Main entry point.""" try: with open(FILENAME, 'rb') as f: botmeta = yaml.safe_load(f) except yaml.error.MarkedYAMLError as ex: print('%s:%d:%d: YAML load failed: %s' % (FILENAME, ex.context_mark.line + 1, ex.context_mark.column + 1, re.sub(r'\s+', ' ', str(ex)))) return except Exception as ex: # pylint: disable=broad-except print('%s:%d:%d: YAML load failed: %s' % (FILENAME, 0, 0, re.sub(r'\s+', ' ', str(ex)))) return # Validate schema MacroSchema = Schema({ (str): Any(str, None), }, extra=PREVENT_EXTRA) FilesSchema = Schema( { (str): { ('supershipit'): str, ('support'): Any('community'), ('maintainers'): str, ('labels'): str, ('keywords'): str, ('notify'): str, ('ignore'): str, }, }, extra=PREVENT_EXTRA) schema = Schema( { ('notifications'): bool, ('automerge'): bool, ('macros'): MacroSchema, ('files'): FilesSchema, }, extra=PREVENT_EXTRA) try: schema(botmeta) except MultipleInvalid as ex: for error in ex.errors: # No way to get line/column numbers print('%s:%d:%d: %s' % (FILENAME, 0, 0, humanize_error(botmeta, error))) return # Preprocess (substitute macros, convert to lists) macros = botmeta.get('macros') or {} macro_re = re.compile(r'\$([a-zA-Z_]+)') def convert_macros(text, macros): def f(m): macro = m.group(1) replacement = (macros[macro] or '') if macro == 'team_ansible_core': return '$team_ansible_core %s' % replacement return replacement return macro_re.sub(f, text) files = {} try: for file, filedata in (botmeta.get('files') or {}).items(): file = convert_macros(file, macros) filedata = dict( (k, convert_macros(v, macros)) for k, v in filedata.items()) files[file] = filedata for k, v in filedata.items(): if k in LIST_ENTRIES: filedata[k] = v.split() except KeyError as e: print('%s:%d:%d: %s' % (FILENAME, 0, 0, 'Found unknown macro %s' % e)) return # Scan all files unmatched = set(files) for dirs in ('plugins', 'tests', 'changelogs'): for dirpath, dirnames, filenames in os.walk(dirs): for file in sorted(filenames): if file.endswith('.pyc'): continue filename = os.path.join(dirpath, file) if os.path.islink(filename): continue if os.path.isfile(filename): matching_files = [] for file, filedata in files.items(): if filename.startswith(file): matching_files.append((file, filedata)) if file in unmatched: unmatched.remove(file) if not matching_files: print('%s:%d:%d: %s' % (FILENAME, 0, 0, 'Did not find any entry for %s' % filename)) matching_files.sort(key=lambda kv: kv[0]) filedata = dict() for k in LIST_ENTRIES: filedata[k] = [] for dummy, data in matching_files: for k, v in data.items(): if k in LIST_ENTRIES: v = filedata[k] + v filedata[k] = v validate(filename, filedata) for file in unmatched: print('%s:%d:%d: %s' % (FILENAME, 0, 0, 'Entry %s was not used' % file))
from marshmallow import fields, validates, ValidationError from voluptuous import Schema, Required, All, MultipleInvalid from app.core.request_objects import ValidRequestObject, InvalidRequestObject from app.extensions import ma from app.swagger import swagger_definition validate_post_item_request_object = Schema({Required("id"): All(int)}) class PostListRequestObject(ValidRequestObject): @classmethod def from_dict(cls, _): return cls() class PostItemRequestObject(ValidRequestObject): def __init__(self, id): self.id = id @classmethod def from_dict(cls, adict): invalid_req = InvalidRequestObject() try: validate_post_item_request_object(adict) except MultipleInvalid as exc: for error in exc.errors: invalid_req.add_error("validation", str(error)) if invalid_req.has_errors():
job_description_schema = Schema({ # The name of the job and the job's label. At least one must be specified, # and the label will be generated from the name if necessary, by prepending # the kind. Optional('name'): basestring, Optional('label'): basestring, # the following fields are passed directly through to the task description, # possibly modified by the run implementation. See # taskcluster/taskgraph/transforms/task.py for the schema details. Required('description'): task_description_schema['description'], Optional('attributes'): task_description_schema['attributes'], Optional('dependencies'): task_description_schema['dependencies'], Optional('expires-after'): task_description_schema['expires-after'], Optional('routes'): task_description_schema['routes'], Optional('scopes'): task_description_schema['scopes'], Optional('extra'): task_description_schema['extra'], Optional('treeherder'): task_description_schema['treeherder'], Optional('index'): task_description_schema['index'], Optional('run-on-projects'): task_description_schema['run-on-projects'], Optional('coalesce-name'): task_description_schema['coalesce-name'], Optional('worker-type'): task_description_schema['worker-type'], Required('worker'): task_description_schema['worker'], Optional('when'): task_description_schema['when'], # A description of how to run this job. 'run': { # The key to a job implementation in a peer module to this one 'using': basestring, # Any remaining content is verified against that job implementation's # own schema. Extra: object, }, })
# -*- coding: utf-8 -*- from .. import BaseHandler, require from autumn.torn.paginator import Paginator from voluptuous import Schema from autumn.torn.form import Form from tornado.httputil import url_concat from tornado.web import StaticFileHandler import tornado.web from autumn.goods import contract_url schema = Schema({ 'id': str, 'start_at': str, 'expire_at': str, 'remark': str, 'action': str }) class List(BaseHandler): @require() def get(self): uid = self.get_argument('agent_id') sql = 'select * from contract where deleted = 0 and type = 2 and uid = %s order by created_at desc' contracts = Paginator(self, sql, [uid]) agent = self.db.get( 'select id, name, short_name from agent where id = %s', uid) self.render('agent/contract/list.html', contracts=contracts,
import random from voluptuous import All, Match, Range, Required, Schema from .basemodel import Collection, ModelMixin, collection from .errors import GameConflict, MemberDoesntExist from .team_members import TeamMember from .utils import utcnow CREATE_GAME_VALIDATOR = Schema( { Required("team"): Match(r"^[-a-zA-Z0-9]+$"), Required("team_members"): collection(TeamMember, min_length=1), Required("state", default="ready"): "ready", Required("duration"): All(int, Range(min=1)), } ) class _TeamMemberCollection(Collection): not_exist_error = MemberDoesntExist def generate_id(self, obj): id_ = random.randint(1000, 9999) obj.id = id_ return id_ class Game(ModelMixin):
SAFE_STRING = '^[a-zA-Z ]+$' SKILLS_STRING = '^[a-zA-Z +/]+$' URL = '(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' PHONE = '^\+[0-9]+ \([0-9]{3}\) [0-9]{3}-[0-9]{4}$' def _Skills(skills): if not isinstance(skills, list): raise TypeError('Invalid Skills, expected a list') for skill in skills: if not isinstance(skill['rating'], int): raise TypeError('Invalid Skills Rating, expected an INT') _skills = Schema(_Skills) user_put_schema = Schema( { Optional('name'): All(str, Match(SAFE_STRING, msg="Invalid Name")), Optional('company'): All(str, Match(SAFE_STRING, msg="Invalid Company")), Optional('email'): All(Email(msg="Invalid Email")), Optional('latitude'): All(float, msg="Invalid Latitude"), Optional('longitude'): All(float, msg="Invalid Longitude"), Optional('picture'): All(str, Match(URL, msg="Invalid URL")), Optional('skills'): _skills, Optional('phone'): All(str, Match(PHONE, msg="Invalid Phone")) }, extra=REMOVE_EXTRA)
import ruamel.yaml from voluptuous import Schema, Required, Invalid from dvc.repo import Repo from dvc.exceptions import DvcException from dvc.external_repo import external_repo SUMMON_FILE_SCHEMA = Schema( { Required("objects"): [ { Required("name"): str, "meta": dict, Required("summon"): { Required("type"): str, "deps": [str], str: object, }, } ] } ) SUMMON_PYTHON_SCHEMA = Schema( { Required("type"): "python", Required("call"): str, "args": dict, "deps": [str], } )
def test_email_validation(): """ test with valid email """ schema = Schema({"email": Email()}) out_ = schema({"email": "*****@*****.**"}) assert '*****@*****.**"', out_.get("url")
class TestSmartPlug(TestCase): sysinfo_schema = Schema({ 'active_mode': check_mode, 'alias': basestring, 'dev_name': basestring, 'deviceId': basestring, 'feature': basestring, 'fwId': basestring, 'hwId': basestring, 'hw_ver': basestring, 'icon_hash': basestring, 'latitude': All(float, Range(min=-90, max=90)), 'led_off': check_int_bool, 'longitude': All(float, Range(min=-180, max=180)), 'mac': check_mac, 'model': basestring, 'oemId': basestring, 'on_time': int, 'relay_state': int, 'rssi': All(int, Range(max=0)), 'sw_ver': basestring, 'type': basestring, 'updating': check_int_bool, }) current_consumption_schema = Schema({ 'voltage': All(float, Range(min=0, max=300)), 'power': All(float, Range(min=0)), 'total': All(float, Range(min=0)), 'current': All(float, Range(min=0)), }) tz_schema = Schema({ 'zone_str': basestring, 'dst_offset': int, 'index': All(int, Range(min=0)), 'tz_str': basestring, }) def setUp(self): self.plug = SmartPlug(PLUG_IP) def tearDown(self): self.plug = None def test_initialize(self): self.assertIsNotNone(self.plug.sys_info) self.sysinfo_schema(self.plug.sys_info) def test_initialize_invalid_connection(self): plug = SmartPlug('127.0.0.1') with self.assertRaises(SmartPlugException): plug.sys_info['model'] def test_query_helper(self): with self.assertRaises(SmartPlugException): self.plug._query_helper("test", "testcmd", {}) # TODO check for unwrapping? @skipIf(SKIP_STATE_TESTS, "SKIP_STATE_TESTS is True, skipping") def test_state(self): def set_invalid(x): self.plug.state = x set_invalid_int = partial(set_invalid, 1234) self.assertRaises(ValueError, set_invalid_int) set_invalid_str = partial(set_invalid, "1234") self.assertRaises(ValueError, set_invalid_str) set_invalid_bool = partial(set_invalid, True) self.assertRaises(ValueError, set_invalid_bool) orig_state = self.plug.state if orig_state == SmartPlug.SWITCH_STATE_OFF: self.plug.state = "ON" self.assertTrue(self.plug.state == SmartPlug.SWITCH_STATE_ON) self.plug.state = "OFF" self.assertTrue(self.plug.state == SmartPlug.SWITCH_STATE_OFF) elif orig_state == SmartPlug.SWITCH_STATE_ON: self.plug.state = "OFF" self.assertTrue(self.plug.state == SmartPlug.SWITCH_STATE_OFF) self.plug.state = "ON" self.assertTrue(self.plug.state == SmartPlug.SWITCH_STATE_ON) elif orig_state == SmartPlug.SWITCH_STATE_UNKNOWN: self.fail("can't test for unknown state") def test_get_sysinfo(self): # initialize checks for this already, but just to be sure self.sysinfo_schema(self.plug.get_sysinfo()) @skipIf(SKIP_STATE_TESTS, "SKIP_STATE_TESTS is True, skipping") def test_turns_and_isses(self): orig_state = self.plug.is_on if orig_state: self.plug.turn_off() self.assertFalse(self.plug.is_on) self.assertTrue(self.plug.is_off) self.plug.turn_on() self.assertTrue(self.plug.is_on) else: self.plug.turn_on() self.assertFalse(self.plug.is_off) self.assertTrue(self.plug.is_on) self.plug.turn_off() self.assertTrue(self.plug.is_off) def test_has_emeter(self): # a not so nice way for checking for emeter availability.. if "110" in self.plug.sys_info["model"]: self.assertTrue(self.plug.has_emeter) else: self.assertFalse(self.plug.has_emeter) def test_get_emeter_realtime(self): self.current_consumption_schema((self.plug.get_emeter_realtime())) def test_get_emeter_daily(self): self.assertEqual(self.plug.get_emeter_daily(year=1900, month=1), {}) k, v = self.plug.get_emeter_daily().popitem() self.assertTrue(isinstance(k, int)) self.assertTrue(isinstance(v, float)) def test_get_emeter_monthly(self): self.assertEqual(self.plug.get_emeter_monthly(year=1900), {}) d = self.plug.get_emeter_monthly() k, v = d.popitem() self.assertTrue(isinstance(k, int)) self.assertTrue(isinstance(v, float)) @skip("not clearing your stats..") def test_erase_emeter_stats(self): self.fail() def test_current_consumption(self): x = self.plug.current_consumption() self.assertTrue(isinstance(x, float)) self.assertTrue(x >= 0.0) def test_identify(self): ident = self.plug.identify() self.assertTrue(isinstance(ident, tuple)) self.assertTrue(len(ident) == 3) def test_alias(self): test_alias = "TEST1234" original = self.plug.alias self.assertTrue(isinstance(original, basestring)) self.plug.alias = test_alias self.assertEqual(self.plug.alias, test_alias) self.plug.alias = original self.assertEqual(self.plug.alias, original) def test_led(self): original = self.plug.led self.plug.led = False self.assertFalse(self.plug.led) self.plug.led = True self.assertTrue(self.plug.led) self.plug.led = original def test_icon(self): self.assertEqual(set(self.plug.icon.keys()), {'icon', 'hash'}) def test_time(self): self.assertTrue(isinstance(self.plug.time, datetime.datetime)) # TODO check setting? def test_timezone(self): self.tz_schema(self.plug.timezone) def test_hw_info(self): self.sysinfo_schema(self.plug.hw_info) def test_on_since(self): self.assertTrue(isinstance(self.plug.on_since, datetime.datetime)) def test_location(self): self.sysinfo_schema(self.plug.location) def test_rssi(self): self.sysinfo_schema({'rssi': self.plug.rssi}) # wrapping for vol def test_mac(self): self.sysinfo_schema({'mac': self.plug.mac}) # wrapping for val
def test_fqdn_url_validation(): """ test with valid fully qualified domain name url """ schema = Schema({"url": FqdnUrl()}) out_ = schema({"url": "http://example.com/"}) assert 'http://example.com/', out_.get("url")
class TestSmartBulb(TestCase): SYSINFO = sysinfo_lb130 # type: Dict[str, Any] # these schemas should go to the mainlib as # they can be useful when adding support for new features/devices # as well as to check that faked devices are operating properly. sysinfo_schema = Schema({ 'active_mode': check_mode, 'alias': str, 'ctrl_protocols': { 'name': str, 'version': str, }, 'description': str, 'dev_state': str, 'deviceId': str, 'disco_ver': str, 'heapsize': int, 'hwId': str, 'hw_ver': str, 'is_color': check_int_bool, 'is_dimmable': check_int_bool, 'is_factory': bool, 'is_variable_color_temp': check_int_bool, 'light_state': { 'brightness': All(int, Range(min=0, max=100)), 'color_temp': int, 'hue': All(int, Range(min=0, max=360)), 'mode': str, 'on_off': check_int_bool, 'saturation': All(int, Range(min=0, max=255)), }, 'mic_mac': str, 'mic_type': str, 'model': str, 'oemId': str, 'preferred_state': [{ 'brightness': All(int, Range(min=0, max=100)), 'color_temp': int, 'hue': All(int, Range(min=0, max=360)), 'index': int, 'saturation': All(int, Range(min=0, max=255)), }], 'rssi': All(int, Range(max=0)), 'sw_ver': str, }) current_consumption_schema = Schema({ 'power_mw': int, }) tz_schema = Schema({ 'zone_str': str, 'dst_offset': int, 'index': All(int, Range(min=0)), 'tz_str': str, }) def setUp(self): self.bulb = SmartBulb(BULB_IP, protocol=FakeTransportProtocol(self.SYSINFO)) def tearDown(self): self.bulb = None def test_initialize(self): self.assertIsNotNone(self.bulb.sys_info) self.sysinfo_schema(self.bulb.sys_info) def test_initialize_invalid_connection(self): bulb = SmartBulb('127.0.0.1', protocol=FakeTransportProtocol(self.SYSINFO, invalid=True)) with self.assertRaises(SmartDeviceException): bulb.sys_info['model'] def test_query_helper(self): with self.assertRaises(SmartDeviceException): self.bulb._query_helper("test", "testcmd", {}) # TODO check for unwrapping? @skipIf(SKIP_STATE_TESTS, "SKIP_STATE_TESTS is True, skipping") def test_state(self): def set_invalid(x): self.bulb.state = x set_invalid_int = partial(set_invalid, 1234) self.assertRaises(ValueError, set_invalid_int) set_invalid_str = partial(set_invalid, "1234") self.assertRaises(ValueError, set_invalid_str) set_invalid_bool = partial(set_invalid, True) self.assertRaises(ValueError, set_invalid_bool) orig_state = self.bulb.state if orig_state == SmartBulb.BULB_STATE_OFF: self.bulb.state = SmartBulb.BULB_STATE_ON self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_ON) self.bulb.state = SmartBulb.BULB_STATE_OFF self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_OFF) elif orig_state == SmartBulb.BULB_STATE_ON: self.bulb.state = SmartBulb.BULB_STATE_OFF self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_OFF) self.bulb.state = SmartBulb.BULB_STATE_ON self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_ON) def test_get_sysinfo(self): # initialize checks for this already, but just to be sure self.sysinfo_schema(self.bulb.get_sysinfo()) @skipIf(SKIP_STATE_TESTS, "SKIP_STATE_TESTS is True, skipping") def test_turns_and_isses(self): orig_state = self.bulb.state if orig_state == SmartBulb.BULB_STATE_ON: self.bulb.state = SmartBulb.BULB_STATE_OFF self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_OFF) self.bulb.state = SmartBulb.BULB_STATE_ON self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_ON) else: self.bulb.state = SmartBulb.BULB_STATE_ON self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_ON) self.bulb.state = SmartBulb.BULB_STATE_OFF self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_OFF) def test_get_emeter_realtime(self): self.current_consumption_schema((self.bulb.get_emeter_realtime())) def test_get_emeter_daily(self): self.assertEqual(self.bulb.get_emeter_daily(year=1900, month=1), {}) k, v = self.bulb.get_emeter_daily(kwh=False).popitem() self.assertTrue(isinstance(k, int)) self.assertTrue(isinstance(v, int)) k, v = self.bulb.get_emeter_daily(kwh=True).popitem() self.assertTrue(isinstance(k, int)) self.assertTrue(isinstance(v, float)) def test_get_emeter_monthly(self): self.assertEqual(self.bulb.get_emeter_monthly(year=1900), {}) d = self.bulb.get_emeter_monthly(kwh=False) k, v = d.popitem() self.assertTrue(isinstance(k, int)) self.assertTrue(isinstance(v, int)) d = self.bulb.get_emeter_monthly(kwh=True) k, v = d.popitem() self.assertTrue(isinstance(k, int)) self.assertTrue(isinstance(v, float)) @skip("not clearing your stats..") def test_erase_emeter_stats(self): self.fail() def test_current_consumption(self): x = self.bulb.current_consumption() self.assertTrue(isinstance(x, float)) self.assertTrue(x >= 0.0) def test_alias(self): test_alias = "TEST1234" original = self.bulb.alias self.assertTrue(isinstance(original, str)) self.bulb.alias = test_alias self.assertEqual(self.bulb.alias, test_alias) self.bulb.alias = original self.assertEqual(self.bulb.alias, original) def test_icon(self): self.assertEqual(set(self.bulb.icon.keys()), {'icon', 'hash'}) def test_rssi(self): self.sysinfo_schema({'rssi': self.bulb.rssi}) # wrapping for vol def test_temperature_range(self): self.assertEqual(self.bulb.valid_temperature_range, (2500, 9000)) with self.assertRaises(ValueError): self.bulb.color_temp = 1000 with self.assertRaises(ValueError): self.bulb.color_temp = 10000 def test_hsv(self): hue, saturation, brightness = self.bulb.hsv self.assertTrue(0 <= hue <= 360) self.assertTrue(0 <= saturation <= 100) self.assertTrue(0 <= brightness <= 100) for invalid_hue in [-1, 360, 0.5]: with self.assertRaises(SmartDeviceException): self.bulb.hsv = (invalid_hue, 0, 0) for invalid_saturation in [-1, 101, 0.5]: with self.assertRaises(SmartDeviceException): self.bulb.hsv = (0, invalid_saturation, 0) for invalid_brightness in [-1, 101, 0.5]: with self.assertRaises(SmartDeviceException): self.bulb.hsv = (0, 0, invalid_brightness)
def test_fix_157(): s = Schema(All([Any('one', 'two', 'three')]), Length(min=1)) assert_equal(['one'], s(['one'])) assert_raises(MultipleInvalid, s, ['four'])
compiled_node_contract = parsed_node_contract.extend({ # compiled fields Required('compiled'): bool, Required('compiled_sql'): Any(basestring, None), # injected fields Required('extra_ctes_injected'): bool, Required('extra_ctes'): All(OrderedDict, { basestring: Any(basestring, None) }), Required('injected_sql'): Any(basestring, None), }) compiled_nodes_contract = Schema({ str: compiled_node_contract, }) compiled_macro_contract = parsed_macro_contract compiled_macros_contract = Schema({ str: compiled_macro_contract, }) compiled_graph_contract = Schema({ Required('nodes'): compiled_nodes_contract, Required('macros'): compiled_macros_contract, }) def validate_node(compiled_node):
try: normalized = PackageVersion.normalize_python_package_name(n) except Exception as exc: raise Invalid(f"Failed to parse Python package name {n!r}: {str(exc)}") else: if normalized != n: raise Invalid( f"Python package name {n!r} is not in a normalized form, normalized: {normalized!r}" ) _RPM_PACKAGE_VERSION_SCHEMA = Schema({ Required("package_name"): _NONEMPTY_STRING, Optional("arch"): _NONEMPTY_STRING, Optional("epoch"): _NONEMPTY_STRING, Optional("package_identifier"): _NONEMPTY_STRING, Optional("package_version"): _NONEMPTY_STRING, Optional("release"): _NONEMPTY_STRING, Optional("src"): bool, }) _PYTHON_PACKAGE_VERSION_SCHEMA = Schema({ Required("name"): _python_package_name, Optional("version"): _specifier_set, Optional("location"): Any(_NONEMPTY_STRING, None), }) PRESCRIPTION_UNIT_SHOULD_INCLUDE_RUNTIME_ENVIRONMENTS_SCHEMA = Schema({
schema = Schema( { 'id': basestring, 'name': basestring, 'title': basestring, 'notes': Any(All(basestring, normalize_string), None), 'license_id': All(DefaultTo('not-specified'), basestring), 'tags': [tag], 'metadata_created': All(basestring, to_date), 'metadata_modified': All(basestring, to_date), 'organization': Any(organization, None), 'resources': [resource], 'revision_id': basestring, 'extras': [{ 'key': basestring, 'value': Any(basestring, int, float, boolean, {}, []), }], 'private': boolean, 'type': 'dataset', 'author': Any(basestring, None), 'author_email': All(empty_none, Any(All(basestring, email), None)), 'maintainer': Any(basestring, None), 'maintainer_email': All(empty_none, Any(All(basestring, email), None)), 'state': Any(basestring, None), }, required=True, extra=True)
from voluptuous import Schema, Required, In, All, Optional, Length, Email, Url, Date login_schema = Schema({ Required('phone'): All(str, ), Required('password'): str, }) register_schema = Schema({ Required('phone'): All(str, ), Required('sms_code'): All(str, ), Required('password1'): str, Required('password2'): str, }) sms_schema = Schema({ Required('phone'): All(str, ), }) user_info_schema = Schema({ Optional('id'): int, Optional('avatar'): Url(), Optional('name'): str, Optional('phone'): str, Optional('birthday'): Date(), Optional('gender'): str, Optional('email'): Email(), })
user_schema = Schema( { Required('email'): check( ("Email must be between 5 and 50 characters.", [str, Length(min=5, max=50)]), ("Your email does not look like an email address.", [_check_email_format]), ), Required('firstname'): check(("First Name must be between 1 and 50 characters.", [str, Length(min=1, max=50)])), Required('lastname'): check(("Last Name must be between 1 and 50 characters.", [str, Length(min=1, max=50)])), Required('country'): check(("Please select a country", [str, Length(min=2, max=2)])), Required('username'): check(("Usernames must be between 3 and 20 characters.", [str, Length(min=3, max=20)]), ("Usernames must be alphanumeric.", [_check_username]), ("This username already exists.", [lambda name: safe_fail(get_user, name=name) is None]), ("This username conflicts with an existing team.", [lambda name: safe_fail(api.team.get_team, name=name) is None]), ("This username is reserved. Please choose another one.", [check_blacklisted_usernames])), Required('password'): check(("Passwords must be between 3 and 20 characters.", [str, Length(min=3, max=20)])), Required('affiliation'): check( ("You must specify an affiliation.", [str, Length(min=3, max=50)])), Required('eligibility'): check(("You must specify whether or not your account is eligibile.", [str, lambda status: status in ["eligible", "ineligible"]])), }, extra=True)
class NotifyOwnersOfServersOnHypervisor(Searcher, handler.TriggeredHandler): """Notify some owners of VMs on a hypervisor about something.""" requires_topo_loader = True required_clients = ('ecm', ) confirms_action = 'notification' confirms_what = 'something' template_subdir = 'maintenance' handles_what = { 'message_matcher': matchers.match_or(matchers.match_slack("message"), matchers.match_telnet("message")), 'channel_matcher': matchers.match_channel(c.TARGETED), 'triggers': [ trigger.Trigger('openstack hypervisor notify-vm-owners', takes_args=True), ], 'args': { 'order': [ 'hypervisor', 'template', 'what', 'description', 'when', 'only_private', 'cloud', # Various ecm passthroughs... 'test_mode', 'notify_slack', 'notify_email', ], 'help': { 'hypervisor': 'hypervisor to find vms on', 'template': "notification template to use", 'what': 'one word for what is about to happen', 'when': ("when the event is going to happen" " in iso8601 format (if not" " provided then the current time is used)"), 'description': 'multiple words for what is about to happen', 'only_private': ('only search the private clouds' ' and skip the public clouds'), 'cloud': ("filter to only specific cloud (empty" " searches all clouds)"), # Various ecm passthroughs... 'test_mode': 'ecm notification api test mode passthrough', 'notify_slack': 'send notification via slack', 'notify_email': 'send notification via email', }, # This will be filled in during setup_class call (since it # needs semi-dynamic information from the bot configuration). 'converters': {}, 'schema': Schema({ Required("hypervisor"): All(su.string_types(), Length(min=1)), Required("only_private"): bool, Required("cloud"): su.string_types(), Required("what"): All(su.string_types(), Length(min=1)), Required("description"): All(su.string_types(), Length(min=1)), Required("template"): All(su.string_types(), Length(min=1)), Required("when"): Any(None, datetime.datetime), # Various ecm passthroughs... Required("test_mode"): bool, Required("notify_email"): bool, Required("notify_slack"): bool, }), 'defaults': { 'only_private': True, 'cloud': '', 'when': None, # Various ecm passthroughs... 'test_mode': False, 'notify_slack': True, 'notify_email': True, }, }, 'authorizer': auth.user_in_ldap_groups('admins_cloud'), } @classmethod def setup_class(cls, bot): tz = bot.config.tz cls.handles_what['args']['converters'].update({ 'only_private': hu.strict_bool_from_string, 'when': functools.partial(_convert_dt, pytz.timezone(tz)), # Various ecm passthroughs... 'test_mode': hu.strict_bool_from_string, 'notify_slack': hu.strict_bool_from_string, 'notify_email': hu.strict_bool_from_string, }) def _build_template(self, servers, hypervisor, template, what, when, description, test_mode=False): tmp_servers = [] for s in servers: s_owner = None try: s_owner = s.metadata.owning_group except AttributeError: pass if s_owner: # Present a smaller view of which servers are here (for now). tmp_servers.append( munch.Munch({ 'id': s.id, 'owner': s_owner, 'name': s.name, })) subject = self.render_template('hv_subject', {'what': what.title()}) subject = subject.strip() body = self.render_template( template, { 'hypervisor': hypervisor, 'vms': tmp_servers, 'what': what, 'description': description, 'when': when, 'subject': subject, 'test_mode': test_mode, }) return subject, body def _run(self, hypervisor, template, what, description, when=None, only_private=True, cloud='', test_mode=False, notify_email=True, notify_slack=True): ecm = self.bot.clients.ecm_client replier = functools.partial(self.message.reply_text, threaded=True, prefixed=False) if when is None: when = self.date_wrangler.get_now() if not self.template_exists(template): replier("Template `%s` does not exist. Try again." % template) else: servers, searched_clouds, _found_clouds = self._search( hypervisor, {'host': hypervisor}, target_search=True, only_private=only_private, cloud=cloud, replier=replier) if servers: self._emit_servers(servers) subject, body = self._build_template(servers, hypervisor, template, what, when, description, test_mode=test_mode) attachment = { 'pretext': ("Found %s servers hosted on hypervisor `%s`, please" " confirm that you wish to notify owners" " of these servers using bundled template" " `%s`." % (len(servers), hypervisor, template)), 'text': "\n".join([ "_Subject:_ `%s`" % subject, "_Body:_", '```', body, '```', ]), 'mrkdwn_in': ["text", 'pretext'], } self.message.reply_attachments( attachments=[attachment], log=LOG, link_names=True, as_user=True, text=' ', thread_ts=self.message.body.ts, channel=self.message.body.channel, unfurl_links=False) f = followers.ConfirmMe(confirms_what='notification') replier(f.generate_who_satisifies_message(self)) self.wait_for_transition(wait_timeout=300, wait_start_state='CONFIRMING', follower=f) if self.state != 'CONFIRMED_CANCELLED': self.change_state("SPAMMING") admin_owning_group = self.config.get('admin_owning_group') sent, _unknowns, targets = ecm.notify_server_owners( servers, subject, body, test_mode=test_mode, notify_email=notify_email, notify_slack=notify_slack, admin_owning_group=admin_owning_group) if sent: replier("Notification spam" " sent (via slack and/or email) to %s" " groups." % (len(targets))) else: replier("Spam not sent (either no targets found" " or no requested spam mechanisms" " provided).") else: replier("Notification cancelled.") else: replier("Sorry I could not find `%s` in %s clouds," " try another?" % (hypervisor, searched_clouds))
import dbt.exceptions from dbt.compat import basestring from dbt.utils import get_materialization from dbt.node_types import NodeType from dbt.contracts.common import validate_with from dbt.contracts.graph.unparsed import unparsed_node_contract, \ unparsed_base_contract from dbt.logger import GLOBAL_LOGGER as logger # noqa hook_contract = Schema({ Required('sql'): basestring, Required('transaction'): bool, Required('index'): int, }) config_contract = Schema( { Required('enabled'): bool, Required('materialized'): basestring, Required('post-hook'): [hook_contract], Required('pre-hook'): [hook_contract], Required('vars'): dict, }, extra=ALLOW_EXTRA) parsed_node_contract = unparsed_node_contract.extend({ # identifiers
# comparable, so we cast all of the keys back to regular strings task_description_schema = {str(k): v for k, v in task_description_schema.schema.iteritems()} transforms = TransformSequence() # shortcut for a string where task references are allowed taskref_or_string = Any( basestring, {Required('task-reference'): basestring}) balrog_description_schema = Schema({ # the dependent task (object) for this balrog job, used to inform balrogworker. Required('dependent-task'): object, # unique label to describe this balrog task, defaults to balrog-{dep.label} Optional('label'): basestring, # treeherder is allowed here to override any defaults we use for beetmover. See # taskcluster/taskgraph/transforms/task.py for the schema details, and the # below transforms for defaults of various values. Optional('treeherder'): task_description_schema['treeherder'], }) @transforms.add def validate(config, jobs): for job in jobs: label = job.get('dependent-task', object).__dict__.get('label', '?no-label?') yield validate_schema( balrog_description_schema, job, "In balrog ({!r} kind) task for {!r}:".format(config.kind, label))
def test_extra_empty_errors(): schema = Schema({'a': {Extra: object}}, required=True) schema({'a': {}})
from taskgraph.transforms.task import task_description_schema from voluptuous import Optional, Required, Schema from fenix_taskgraph.util.scriptworker import generate_beetmover_artifact_map logger = logging.getLogger(__name__) beetmover_description_schema = Schema({ # unique name to describe this beetmover task, defaults to {dep.label}-beetmover Required("name"): str, Required("worker"): { "upstream-artifacts": [dict] }, # treeherder is allowed here to override any defaults we use for beetmover. Optional("treeherder"): task_description_schema["treeherder"], Optional("attributes"): task_description_schema["attributes"], Optional("dependencies"): task_description_schema["dependencies"], Optional("run-on-tasks-for"): [str], Optional("bucket-scope"): optionally_keyed_by("level", "build-type", str), }) transforms = TransformSequence() transforms.add_validate(beetmover_description_schema) @transforms.add def make_task_description(config, tasks):
# uses installed code #emborg_exe = "emborg".split() #emborg_overdue_exe = "emborg-overdue".split() set_prefs(use_inform=True) tests_dir = to_path(__file__).parent emborg_dir = str(tests_dir.parent) emborg_dir_wo_slash = emborg_dir.strip('/') # remove the leading slashes, it will be added back in tests if needed # schema for test cases {{{2 emborg_schema = Schema( { Required('name'): str, Optional('args', default='<PASS>'): Any(str, list), Optional('expected', default=""): str, Optional('expected_type', default=""): str, Optional('cmp_dirs', default=""): str, Optional('remove', default=""): str, Optional('dependencies', default=""): str, }, required=True) emborg_overdue_schema = Schema( { Required('name'): str, Optional('conf', default=""): str, Optional('args', default=[]): Any(str, list), Required('expected', default=""): str, Required('expected_type', default=""): str, Optional('dependencies', default=""): str, }, required=True)