How to use Resource method in devicefarmer-stf

Best JavaScript code snippet using devicefarmer-stf

main.js

Source:main.js Github

copy

Full Screen

...267 var uid$2 = 0;268 /*269 needs a full store so that it can populate children too270 */271 function parseResource(input, parentId, store, calendar) {272 if (parentId === void 0) { parentId = ''; }273 var leftovers0 = {};274 var props = core.refineProps(input, RESOURCE_PROPS, {}, leftovers0);275 var leftovers1 = {};276 var ui = core.processScopedUiProps('event', leftovers0, calendar, leftovers1);277 if (!props.id) {278 props.id = PRIVATE_ID_PREFIX + (uid$2++);279 }280 if (!props.parentId) { // give precedence to the parentId property281 props.parentId = parentId;282 }283 props.businessHours = props.businessHours ? core.parseBusinessHours(props.businessHours, calendar) : null;284 props.ui = ui;285 props.extendedProps = __assign({}, leftovers1, props.extendedProps);286 // help out ResourceApi from having user modify props287 Object.freeze(ui.classNames);288 Object.freeze(props.extendedProps);289 if (store[props.id]) ;290 else {291 store[props.id] = props;292 if (props.children) {293 for (var _i = 0, _a = props.children; _i < _a.length; _i++) {294 var childInput = _a[_i];295 parseResource(childInput, props.id, store, calendar);296 }297 delete props.children;298 }299 }300 return props;301 }302 /*303 TODO: use this in more places304 */305 function getPublicId(id) {306 if (id.indexOf(PRIVATE_ID_PREFIX) === 0) {307 return '';308 }309 return id;310 }311 function reduceResourceStore (store, action, source, calendar) {312 switch (action.type) {313 case 'INIT':314 return {};315 case 'RECEIVE_RESOURCES':316 return receiveRawResources(store, action.rawResources, action.fetchId, source, calendar);317 case 'ADD_RESOURCE':318 return addResource(store, action.resourceHash);319 case 'REMOVE_RESOURCE':320 return removeResource(store, action.resourceId);321 case 'SET_RESOURCE_PROP':322 return setResourceProp(store, action.resourceId, action.propName, action.propValue);323 case 'RESET_RESOURCES':324 // must make the calendar think each resource is a new object :/325 return core.mapHash(store, function (resource) {326 return __assign({}, resource);327 });328 default:329 return store;330 }331 }332 function receiveRawResources(existingStore, inputs, fetchId, source, calendar) {333 if (source.latestFetchId === fetchId) {334 var nextStore = {};335 for (var _i = 0, inputs_1 = inputs; _i < inputs_1.length; _i++) {336 var input = inputs_1[_i];337 parseResource(input, '', nextStore, calendar);338 }339 return nextStore;340 }341 else {342 return existingStore;343 }344 }345 function addResource(existingStore, additions) {346 // TODO: warn about duplicate IDs347 return __assign({}, existingStore, additions);348 }349 function removeResource(existingStore, resourceId) {350 var newStore = __assign({}, existingStore);351 delete newStore[resourceId];352 // promote children353 for (var childResourceId in newStore) { // a child, *maybe* but probably not354 if (newStore[childResourceId].parentId === resourceId) {355 newStore[childResourceId] = __assign({}, newStore[childResourceId], { parentId: '' });356 }357 }358 return newStore;359 }360 function setResourceProp(existingStore, resourceId, name, value) {361 var _a, _b;362 var existingResource = existingStore[resourceId];363 // TODO: sanitization364 if (existingResource) {365 return __assign({}, existingStore, (_a = {}, _a[resourceId] = __assign({}, existingResource, (_b = {}, _b[name] = value, _b)), _a));366 }367 else {368 return existingStore;369 }370 }371 function reduceResourceEntityExpansions(expansions, action) {372 var _a;373 switch (action.type) {374 case 'INIT':375 return {};376 case 'SET_RESOURCE_ENTITY_EXPANDED':377 return __assign({}, expansions, (_a = {}, _a[action.id] = action.isExpanded, _a));378 default:379 return expansions;380 }381 }382 function resourcesReducers (state, action, calendar) {383 var resourceSource = reduceResourceSource(state.resourceSource, action, state.dateProfile, calendar);384 var resourceStore = reduceResourceStore(state.resourceStore, action, resourceSource, calendar);385 var resourceEntityExpansions = reduceResourceEntityExpansions(state.resourceEntityExpansions, action);386 return __assign({}, state, { resourceSource: resourceSource,387 resourceStore: resourceStore,388 resourceEntityExpansions: resourceEntityExpansions });389 }390 var RESOURCE_RELATED_PROPS = {391 resourceId: String,392 resourceIds: function (items) {393 return (items || []).map(function (item) {394 return String(item);395 });396 },397 resourceEditable: Boolean398 };399 function parseEventDef(def, props, leftovers) {400 var resourceRelatedProps = core.refineProps(props, RESOURCE_RELATED_PROPS, {}, leftovers);401 var resourceIds = resourceRelatedProps.resourceIds;402 if (resourceRelatedProps.resourceId) {403 resourceIds.push(resourceRelatedProps.resourceId);404 }405 def.resourceIds = resourceIds;406 def.resourceEditable = resourceRelatedProps.resourceEditable;407 }408 function massageEventDragMutation(eventMutation, hit0, hit1) {409 var resource0 = hit0.dateSpan.resourceId;410 var resource1 = hit1.dateSpan.resourceId;411 if (resource0 && resource1 &&412 resource0 !== resource1) {413 eventMutation.resourceMutation = {414 matchResourceId: resource0,415 setResourceId: resource1416 };417 }418 }419 /*420 TODO: all this would be much easier if we were using a hash!421 */422 function applyEventDefMutation(eventDef, mutation, calendar) {423 var resourceMutation = mutation.resourceMutation;424 if (resourceMutation && computeResourceEditable(eventDef, calendar)) {425 var index = eventDef.resourceIds.indexOf(resourceMutation.matchResourceId);426 if (index !== -1) {427 var resourceIds = eventDef.resourceIds.slice(); // copy428 resourceIds.splice(index, 1); // remove429 if (resourceIds.indexOf(resourceMutation.setResourceId) === -1) { // not already in there430 resourceIds.push(resourceMutation.setResourceId); // add431 }432 eventDef.resourceIds = resourceIds;433 }434 }435 }436 /*437 HACK438 TODO: use EventUi system instead of this439 */440 function computeResourceEditable(eventDef, calendar) {441 var resourceEditable = eventDef.resourceEditable;442 if (resourceEditable == null) {443 var source = eventDef.sourceId && calendar.state.eventSources[eventDef.sourceId];444 if (source) {445 resourceEditable = source.extendedProps.resourceEditable; // used the Source::extendedProps hack446 }447 if (resourceEditable == null) {448 resourceEditable = calendar.opt('eventResourceEditable');449 if (resourceEditable == null) {450 resourceEditable = calendar.opt('editable'); // TODO: use defaults system instead451 }452 }453 }454 return resourceEditable;455 }456 function transformEventDrop(mutation, calendar) {457 var resourceMutation = mutation.resourceMutation;458 if (resourceMutation) {459 return {460 oldResource: calendar.getResourceById(resourceMutation.matchResourceId),461 newResource: calendar.getResourceById(resourceMutation.setResourceId)462 };463 }464 else {465 return {466 oldResource: null,467 newResource: null468 };469 }470 }471 function transformDateSelectionJoin(hit0, hit1) {472 var resourceId0 = hit0.dateSpan.resourceId;473 var resourceId1 = hit1.dateSpan.resourceId;474 if (resourceId0 && resourceId1) {475 if (hit0.component.allowAcrossResources === false &&476 resourceId0 !== resourceId1) {477 return false;478 }479 else {480 return { resourceId: resourceId0 };481 }482 }483 }484 var ResourceApi = /** @class */ (function () {485 function ResourceApi(calendar, rawResource) {486 this._calendar = calendar;487 this._resource = rawResource;488 }489 ResourceApi.prototype.setProp = function (name, value) {490 this._calendar.dispatch({491 type: 'SET_RESOURCE_PROP',492 resourceId: this._resource.id,493 propName: name,494 propValue: value495 });496 };497 ResourceApi.prototype.remove = function () {498 this._calendar.dispatch({499 type: 'REMOVE_RESOURCE',500 resourceId: this._resource.id501 });502 };503 ResourceApi.prototype.getParent = function () {504 var calendar = this._calendar;505 var parentId = this._resource.parentId;506 if (parentId) {507 return new ResourceApi(calendar, calendar.state.resourceSource[parentId]);508 }509 else {510 return null;511 }512 };513 ResourceApi.prototype.getChildren = function () {514 var thisResourceId = this._resource.id;515 var calendar = this._calendar;516 var resourceStore = calendar.state.resourceStore;517 var childApis = [];518 for (var resourceId in resourceStore) {519 if (resourceStore[resourceId].parentId === thisResourceId) {520 childApis.push(new ResourceApi(calendar, resourceStore[resourceId]));521 }522 }523 return childApis;524 };525 /*526 this is really inefficient!527 TODO: make EventApi::resourceIds a hash or keep an index in the Calendar's state528 */529 ResourceApi.prototype.getEvents = function () {530 var thisResourceId = this._resource.id;531 var calendar = this._calendar;532 var _a = calendar.state.eventStore, defs = _a.defs, instances = _a.instances;533 var eventApis = [];534 for (var instanceId in instances) {535 var instance = instances[instanceId];536 var def = defs[instance.defId];537 if (def.resourceIds.indexOf(thisResourceId) !== -1) { // inefficient!!!538 eventApis.push(new core.EventApi(calendar, def, instance));539 }540 }541 return eventApis;542 };543 Object.defineProperty(ResourceApi.prototype, "id", {544 get: function () { return this._resource.id; },545 enumerable: true,546 configurable: true547 });548 Object.defineProperty(ResourceApi.prototype, "title", {549 get: function () { return this._resource.title; },550 enumerable: true,551 configurable: true552 });553 Object.defineProperty(ResourceApi.prototype, "eventConstraint", {554 get: function () { return this._resource.ui.constraints[0] || null; },555 enumerable: true,556 configurable: true557 });558 Object.defineProperty(ResourceApi.prototype, "eventOverlap", {559 get: function () { return this._resource.ui.overlap; },560 enumerable: true,561 configurable: true562 });563 Object.defineProperty(ResourceApi.prototype, "eventAllow", {564 get: function () { return this._resource.ui.allows[0] || null; },565 enumerable: true,566 configurable: true567 });568 Object.defineProperty(ResourceApi.prototype, "eventBackgroundColor", {569 get: function () { return this._resource.ui.backgroundColor; },570 enumerable: true,571 configurable: true572 });573 Object.defineProperty(ResourceApi.prototype, "eventBorderColor", {574 get: function () { return this._resource.ui.borderColor; },575 enumerable: true,576 configurable: true577 });578 Object.defineProperty(ResourceApi.prototype, "eventTextColor", {579 get: function () { return this._resource.ui.textColor; },580 enumerable: true,581 configurable: true582 });583 Object.defineProperty(ResourceApi.prototype, "eventClassNames", {584 // NOTE: user can't modify these because Object.freeze was called in event-def parsing585 get: function () { return this._resource.ui.classNames; },586 enumerable: true,587 configurable: true588 });589 Object.defineProperty(ResourceApi.prototype, "extendedProps", {590 get: function () { return this._resource.extendedProps; },591 enumerable: true,592 configurable: true593 });594 return ResourceApi;595 }());596 core.Calendar.prototype.addResource = function (input, scrollTo) {597 if (scrollTo === void 0) { scrollTo = true; }598 var _a;599 var resourceHash;600 var resource;601 if (input instanceof ResourceApi) {602 resource = input._resource;603 resourceHash = (_a = {}, _a[resource.id] = resource, _a);604 }605 else {606 resourceHash = {};607 resource = parseResource(input, '', resourceHash, this);608 }609 // HACK610 if (scrollTo) {611 this.component.view.addScroll({ forcedRowId: resource.id });612 }613 this.dispatch({614 type: 'ADD_RESOURCE',615 resourceHash: resourceHash616 });617 return new ResourceApi(this, resource);618 };619 core.Calendar.prototype.getResourceById = function (id) {620 id = String(id);621 if (this.state.resourceStore) { // guard against calendar with no resource functionality...

Full Screen

Full Screen

factory.py

Source:factory.py Github

copy

Full Screen

1# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License"). You4# may not use this file except in compliance with the License. A copy of5# the License is located at6#7# http://aws.amazon.com/apache2.0/8#9# or in the "license" file accompanying this file. This file is10# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF11# ANY KIND, either express or implied. See the License for the specific12# language governing permissions and limitations under the License.13import logging14from functools import partial15from .action import ServiceAction16from .action import WaiterAction17from .base import ResourceMeta, ServiceResource18from .collection import CollectionFactory19from .model import ResourceModel20from .response import build_identifiers, ResourceHandler21from ..exceptions import ResourceLoadException22from ..docs import docstring23logger = logging.getLogger(__name__)24class ResourceFactory(object):25 """26 A factory to create new :py:class:`~boto3.resources.base.ServiceResource`27 classes from a :py:class:`~boto3.resources.model.ResourceModel`. There are28 two types of lookups that can be done: one on the service itself (e.g. an29 SQS resource) and another on models contained within the service (e.g. an30 SQS Queue resource).31 """32 def __init__(self, emitter):33 self._collection_factory = CollectionFactory()34 self._emitter = emitter35 def load_from_definition(self, resource_name,36 single_resource_json_definition, service_context):37 """38 Loads a resource from a model, creating a new39 :py:class:`~boto3.resources.base.ServiceResource` subclass40 with the correct properties and methods, named based on the service41 and resource name, e.g. EC2.Instance.42 :type resource_name: string43 :param resource_name: Name of the resource to look up. For services,44 this should match the ``service_name``.45 :type single_resource_json_definition: dict46 :param single_resource_json_definition:47 The loaded json of a single service resource or resource48 definition.49 :type service_context: :py:class:`~boto3.utils.ServiceContext`50 :param service_context: Context about the AWS service51 :rtype: Subclass of :py:class:`~boto3.resources.base.ServiceResource`52 :return: The service or resource class.53 """54 logger.debug('Loading %s:%s', service_context.service_name,55 resource_name)56 # Using the loaded JSON create a ResourceModel object.57 resource_model = ResourceModel(58 resource_name, single_resource_json_definition,59 service_context.resource_json_definitions60 )61 # Do some renaming of the shape if there was a naming collision62 # that needed to be accounted for.63 shape = None64 if resource_model.shape:65 shape = service_context.service_model.shape_for(66 resource_model.shape)67 resource_model.load_rename_map(shape)68 # Set some basic info69 meta = ResourceMeta(70 service_context.service_name, resource_model=resource_model)71 attrs = {72 'meta': meta,73 }74 # Create and load all of attributes of the resource class based75 # on the models.76 # Identifiers77 self._load_identifiers(78 attrs=attrs, meta=meta, resource_name=resource_name,79 resource_model=resource_model80 )81 # Load/Reload actions82 self._load_actions(83 attrs=attrs, resource_name=resource_name,84 resource_model=resource_model, service_context=service_context85 )86 # Attributes that get auto-loaded87 self._load_attributes(88 attrs=attrs, meta=meta, resource_name=resource_name,89 resource_model=resource_model,90 service_context=service_context)91 # Collections and their corresponding methods92 self._load_collections(93 attrs=attrs, resource_model=resource_model,94 service_context=service_context)95 # References and Subresources96 self._load_has_relations(97 attrs=attrs, resource_name=resource_name,98 resource_model=resource_model, service_context=service_context99 )100 # Waiter resource actions101 self._load_waiters(102 attrs=attrs, resource_name=resource_name,103 resource_model=resource_model, service_context=service_context104 )105 # Create the name based on the requested service and resource106 cls_name = resource_name107 if service_context.service_name == resource_name:108 cls_name = 'ServiceResource'109 cls_name = service_context.service_name + '.' + cls_name110 base_classes = [ServiceResource]111 if self._emitter is not None:112 self._emitter.emit(113 'creating-resource-class.%s' % cls_name,114 class_attributes=attrs, base_classes=base_classes,115 service_context=service_context)116 return type(str(cls_name), tuple(base_classes), attrs)117 def _load_identifiers(self, attrs, meta, resource_model, resource_name):118 """119 Populate required identifiers. These are arguments without which120 the resource cannot be used. Identifiers become arguments for121 operations on the resource.122 """123 for identifier in resource_model.identifiers:124 meta.identifiers.append(identifier.name)125 attrs[identifier.name] = self._create_identifier(126 identifier, resource_name)127 def _load_actions(self, attrs, resource_name, resource_model,128 service_context):129 """130 Actions on the resource become methods, with the ``load`` method131 being a special case which sets internal data for attributes, and132 ``reload`` is an alias for ``load``.133 """134 if resource_model.load:135 attrs['load'] = self._create_action(136 action_model=resource_model.load, resource_name=resource_name,137 service_context=service_context, is_load=True)138 attrs['reload'] = attrs['load']139 for action in resource_model.actions:140 attrs[action.name] = self._create_action(141 action_model=action, resource_name=resource_name,142 service_context=service_context)143 def _load_attributes(self, attrs, meta, resource_name, resource_model,144 service_context):145 """146 Load resource attributes based on the resource shape. The shape147 name is referenced in the resource JSON, but the shape itself148 is defined in the Botocore service JSON, hence the need for149 access to the ``service_model``.150 """151 if not resource_model.shape:152 return153 shape = service_context.service_model.shape_for(154 resource_model.shape)155 identifiers = dict(156 (i.member_name, i)157 for i in resource_model.identifiers if i.member_name)158 attributes = resource_model.get_attributes(shape)159 for name, (orig_name, member) in attributes.items():160 if name in identifiers:161 prop = self._create_identifier_alias(162 resource_name=resource_name,163 identifier=identifiers[name],164 member_model=member,165 service_context=service_context166 )167 else:168 prop = self._create_autoload_property(169 resource_name=resource_name,170 name=orig_name, snake_cased=name,171 member_model=member,172 service_context=service_context173 )174 attrs[name] = prop175 def _load_collections(self, attrs, resource_model, service_context):176 """177 Load resource collections from the model. Each collection becomes178 a :py:class:`~boto3.resources.collection.CollectionManager` instance179 on the resource instance, which allows you to iterate and filter180 through the collection's items.181 """182 for collection_model in resource_model.collections:183 attrs[collection_model.name] = self._create_collection(184 resource_name=resource_model.name,185 collection_model=collection_model,186 service_context=service_context187 )188 def _load_has_relations(self, attrs, resource_name, resource_model,189 service_context):190 """191 Load related resources, which are defined via a ``has``192 relationship but conceptually come in two forms:193 1. A reference, which is a related resource instance and can be194 ``None``, such as an EC2 instance's ``vpc``.195 2. A subresource, which is a resource constructor that will always196 return a resource instance which shares identifiers/data with197 this resource, such as ``s3.Bucket('name').Object('key')``.198 """199 for reference in resource_model.references:200 # This is a dangling reference, i.e. we have all201 # the data we need to create the resource, so202 # this instance becomes an attribute on the class.203 attrs[reference.name] = self._create_reference(204 reference_model=reference,205 resource_name=resource_name,206 service_context=service_context207 )208 for subresource in resource_model.subresources:209 # This is a sub-resource class you can create210 # by passing in an identifier, e.g. s3.Bucket(name).211 attrs[subresource.name] = self._create_class_partial(212 subresource_model=subresource,213 resource_name=resource_name,214 service_context=service_context215 )216 self._create_available_subresources_command(217 attrs, resource_model.subresources)218 def _create_available_subresources_command(self, attrs, subresources):219 _subresources = [subresource.name for subresource in subresources]220 _subresources = sorted(_subresources)221 def get_available_subresources(factory_self):222 """223 Returns a list of all the available sub-resources for this224 Resource.225 :returns: A list containing the name of each sub-resource for this226 resource227 :rtype: list of str228 """229 return _subresources230 attrs['get_available_subresources'] = get_available_subresources231 def _load_waiters(self, attrs, resource_name, resource_model,232 service_context):233 """234 Load resource waiters from the model. Each waiter allows you to235 wait until a resource reaches a specific state by polling the state236 of the resource.237 """238 for waiter in resource_model.waiters:239 attrs[waiter.name] = self._create_waiter(240 resource_waiter_model=waiter,241 resource_name=resource_name,242 service_context=service_context243 )244 def _create_identifier(factory_self, identifier, resource_name):245 """246 Creates a read-only property for identifier attributes.247 """248 def get_identifier(self):249 # The default value is set to ``None`` instead of250 # raising an AttributeError because when resources are251 # instantiated a check is made such that none of the252 # identifiers have a value ``None``. If any are ``None``,253 # a more informative user error than a generic AttributeError254 # is raised.255 return getattr(self, '_' + identifier.name, None)256 get_identifier.__name__ = str(identifier.name)257 get_identifier.__doc__ = docstring.IdentifierDocstring(258 resource_name=resource_name,259 identifier_model=identifier,260 include_signature=False261 )262 return property(get_identifier)263 def _create_identifier_alias(factory_self, resource_name, identifier,264 member_model, service_context):265 """266 Creates a read-only property that aliases an identifier.267 """268 def get_identifier(self):269 return getattr(self, '_' + identifier.name, None)270 get_identifier.__name__ = str(identifier.member_name)271 get_identifier.__doc__ = docstring.AttributeDocstring(272 service_name=service_context.service_name,273 resource_name=resource_name,274 attr_name=identifier.member_name,275 event_emitter=factory_self._emitter,276 attr_model=member_model,277 include_signature=False278 )279 return property(get_identifier)280 def _create_autoload_property(factory_self, resource_name, name,281 snake_cased, member_model, service_context):282 """283 Creates a new property on the resource to lazy-load its value284 via the resource's ``load`` method (if it exists).285 """286 # The property loader will check to see if this resource has already287 # been loaded and return the cached value if possible. If not, then288 # it first checks to see if it CAN be loaded (raise if not), then289 # calls the load before returning the value.290 def property_loader(self):291 if self.meta.data is None:292 if hasattr(self, 'load'):293 self.load()294 else:295 raise ResourceLoadException(296 '{0} has no load method'.format(297 self.__class__.__name__))298 return self.meta.data.get(name)299 property_loader.__name__ = str(snake_cased)300 property_loader.__doc__ = docstring.AttributeDocstring(301 service_name=service_context.service_name,302 resource_name=resource_name,303 attr_name=snake_cased,304 event_emitter=factory_self._emitter,305 attr_model=member_model,306 include_signature=False307 )308 return property(property_loader)309 def _create_waiter(factory_self, resource_waiter_model, resource_name,310 service_context):311 """312 Creates a new wait method for each resource where both a waiter and313 resource model is defined.314 """315 waiter = WaiterAction(resource_waiter_model,316 waiter_resource_name=resource_waiter_model.name)317 def do_waiter(self, *args, **kwargs):318 waiter(self, *args, **kwargs)319 do_waiter.__name__ = str(resource_waiter_model.name)320 do_waiter.__doc__ = docstring.ResourceWaiterDocstring(321 resource_name=resource_name,322 event_emitter=factory_self._emitter,323 service_model=service_context.service_model,324 resource_waiter_model=resource_waiter_model,325 service_waiter_model=service_context.service_waiter_model,326 include_signature=False327 )328 return do_waiter329 def _create_collection(factory_self, resource_name, collection_model,330 service_context):331 """332 Creates a new property on the resource to lazy-load a collection.333 """334 cls = factory_self._collection_factory.load_from_definition(335 resource_name=resource_name, collection_model=collection_model,336 service_context=service_context,337 event_emitter=factory_self._emitter)338 def get_collection(self):339 return cls(340 collection_model=collection_model, parent=self,341 factory=factory_self, service_context=service_context)342 get_collection.__name__ = str(collection_model.name)343 get_collection.__doc__ = docstring.CollectionDocstring(344 collection_model=collection_model, include_signature=False)345 return property(get_collection)346 def _create_reference(factory_self, reference_model, resource_name,347 service_context):348 """349 Creates a new property on the resource to lazy-load a reference.350 """351 # References are essentially an action with no request352 # or response, so we can re-use the response handlers to353 # build up resources from identifiers and data members.354 handler = ResourceHandler(355 search_path=reference_model.resource.path, factory=factory_self,356 resource_model=reference_model.resource,357 service_context=service_context358 )359 # Are there any identifiers that need access to data members?360 # This is important when building the resource below since361 # it requires the data to be loaded.362 needs_data = any(i.source == 'data' for i in363 reference_model.resource.identifiers)364 def get_reference(self):365 # We need to lazy-evaluate the reference to handle circular366 # references between resources. We do this by loading the class367 # when first accessed.368 # This is using a *response handler* so we need to make sure369 # our data is loaded (if possible) and pass that data into370 # the handler as if it were a response. This allows references371 # to have their data loaded properly.372 if needs_data and self.meta.data is None and hasattr(self, 'load'):373 self.load()374 return handler(self, {}, self.meta.data)375 get_reference.__name__ = str(reference_model.name)376 get_reference.__doc__ = docstring.ReferenceDocstring(377 reference_model=reference_model,378 include_signature=False379 )380 return property(get_reference)381 def _create_class_partial(factory_self, subresource_model, resource_name,382 service_context):383 """384 Creates a new method which acts as a functools.partial, passing385 along the instance's low-level `client` to the new resource386 class' constructor.387 """388 name = subresource_model.resource.type389 def create_resource(self, *args, **kwargs):390 # We need a new method here because we want access to the391 # instance's client.392 positional_args = []393 # We lazy-load the class to handle circular references.394 json_def = service_context.resource_json_definitions.get(name, {})395 resource_cls = factory_self.load_from_definition(396 resource_name=name,397 single_resource_json_definition=json_def,398 service_context=service_context399 )400 # Assumes that identifiers are in order, which lets you do401 # e.g. ``sqs.Queue('foo').Message('bar')`` to create a new message402 # linked with the ``foo`` queue and which has a ``bar`` receipt403 # handle. If we did kwargs here then future positional arguments404 # would lead to failure.405 identifiers = subresource_model.resource.identifiers406 if identifiers is not None:407 for identifier, value in build_identifiers(identifiers, self):408 positional_args.append(value)409 return partial(resource_cls, *positional_args,410 client=self.meta.client)(*args, **kwargs)411 create_resource.__name__ = str(name)412 create_resource.__doc__ = docstring.SubResourceDocstring(413 resource_name=resource_name,414 sub_resource_model=subresource_model,415 service_model=service_context.service_model,416 include_signature=False417 )418 return create_resource419 def _create_action(factory_self, action_model, resource_name,420 service_context, is_load=False):421 """422 Creates a new method which makes a request to the underlying423 AWS service.424 """425 # Create the action in in this closure but before the ``do_action``426 # method below is invoked, which allows instances of the resource427 # to share the ServiceAction instance.428 action = ServiceAction(429 action_model, factory=factory_self,430 service_context=service_context431 )432 # A resource's ``load`` method is special because it sets433 # values on the resource instead of returning the response.434 if is_load:435 # We need a new method here because we want access to the436 # instance via ``self``.437 def do_action(self, *args, **kwargs):438 response = action(self, *args, **kwargs)439 self.meta.data = response440 # Create the docstring for the load/reload mehtods.441 lazy_docstring = docstring.LoadReloadDocstring(442 action_name=action_model.name,443 resource_name=resource_name,444 event_emitter=factory_self._emitter,445 load_model=action_model,446 service_model=service_context.service_model,447 include_signature=False448 )449 else:450 # We need a new method here because we want access to the451 # instance via ``self``.452 def do_action(self, *args, **kwargs):453 response = action(self, *args, **kwargs)454 if hasattr(self, 'load'):455 # Clear cached data. It will be reloaded the next456 # time that an attribute is accessed.457 # TODO: Make this configurable in the future?458 self.meta.data = None459 return response460 lazy_docstring = docstring.ActionDocstring(461 resource_name=resource_name,462 event_emitter=factory_self._emitter,463 action_model=action_model,464 service_model=service_context.service_model,465 include_signature=False466 )467 do_action.__name__ = str(action_model.name)468 do_action.__doc__ = lazy_docstring...

Full Screen

Full Screen

testresources.py

Source:testresources.py Github

copy

Full Screen

...85 old_resources = old_resource_set - new_resource_set86 for resource in old_resources:87 resource.finishedWith(resource._currentResource, result)88 for resource in new_resources:89 resource.getResource(result)90 def run(self, result):91 self.sortTests()92 current_resources = set()93 for test in self._tests:94 if result.shouldStop:95 break96 resources = getattr(test, 'resources', [])97 new_resources = set()98 for name, resource in resources:99 new_resources.update(resource.neededResources())100 self.switch(current_resources, new_resources, result)101 current_resources = new_resources102 test(result)103 self.switch(current_resources, set(), result)104 return result105 def _arrange(self, by_res_comb):106 """Sorts by_res_comb's values using a greedy cost-minimizing107 heuristic.108 by_res_comb maps sets of resources used to a list of the109 corresponding tests. The heuristic works by figuring out the110 test most expensive to set up and collecting all resource111 sets that contain it. It will then separately arrange112 this test subset and the set of tests not requiring this113 currently most expensive test.114 The recursion stops when only one (or less) resource set115 is left in by_res_comb.116 """117 if not by_res_comb:118 return []119 if len(by_res_comb)==1:120 return by_res_comb.values()[0]121 most_expensive_here = max(reduce(122 lambda a,b: a.union(b),123 by_res_comb),124 key=lambda res: res.setUpCost)125 126 with_most_expensive, not_handled = {}, {}127 for res_required in by_res_comb:128 if most_expensive_here in res_required:129 with_most_expensive[130 res_required-frozenset((most_expensive_here,))131 ] = by_res_comb[res_required]132 else:133 not_handled[res_required] = by_res_comb[res_required]134 135 return self._arrange(with_most_expensive136 )+self._arrange(not_handled)137 def sortTests(self):138 """Sorts _tests in some way that minimizes the total cost139 of creating and deleting resources.140 We're using a heuristic where we attempt to keep the most141 expensive resources unchanged for the longest time.142 """143 resource_set_tests = split_by_resources(self._tests)144 self._tests = self._arrange(resource_set_tests)145class TestLoader(unittest.TestLoader):146 """Custom TestLoader to set the right TestSuite class."""147 suiteClass = OptimisingTestSuite148class TestResource(object):149 """A resource that can be shared across tests.150 Resources can report activity to a TestResult. The methods151 - startCleanResource(resource)152 - stopCleanResource(resource)153 - startMakeResource(resource)154 - stopMakeResource(resource)155 will be looked for and if present invoked before and after cleaning or156 creation of resource objects takes place.157 :cvar resources: The same as the resources list on an instance, the default158 constructor will look for the class instance and copy it. This is a159 convenience to avoid needing to define __init__ solely to alter the160 dependencies list.161 :ivar resources: The resources that this resource needs. Calling162 neededResources will return the closure of this resource and its needed163 resources. The resources list is in the same format as resources on a 164 test case - a list of tuples (attribute_name, resource).165 :ivar setUpCost: The relative cost to construct a resource of this type.166 One good approach is to set this to the number of seconds it normally167 takes to set up the resource.168 :ivar tearDownCost: The relative cost to tear down a resource of this169 type. One good approach is to set this to the number of seconds it170 normally takes to tear down the resource.171 """172 setUpCost = 1173 tearDownCost = 1174 def __init__(self):175 """Create a TestResource object."""176 self._dirty = False177 self._uses = 0178 self._currentResource = None179 self.resources = list(getattr(self.__class__, "resources", []))180 def _call_result_method_if_exists(self, result, methodname, *args):181 """Call a method on a TestResult that may exist."""182 method = getattr(result, methodname, None)183 if callable(method):184 method(*args)185 def _clean_all(self, resource, result):186 """Clean the dependencies from resource, and then resource itself."""187 self._call_result_method_if_exists(result, "startCleanResource", self)188 self.clean(resource)189 for name, manager in self.resources:190 manager.finishedWith(getattr(self, name))191 self._call_result_method_if_exists(result, "stopCleanResource", self)192 def clean(self, resource):193 """Override this to class method to hook into resource removal."""194 def dirtied(self, resource):195 """Mark the resource as having been 'dirtied'.196 A resource is dirty when it is no longer suitable for use by other197 tests.198 e.g. a shared database that has had rows changed.199 """200 self._dirty = True201 def finishedWith(self, resource, result=None):202 """Indicate that 'resource' has one less user.203 If there are no more registered users of 'resource' then we trigger204 the `clean` hook, which should do any resource-specific205 cleanup.206 :param resource: A resource returned by `TestResource.getResource`.207 :param result: An optional TestResult to report resource changes to.208 """209 self._uses -= 1210 if self._uses == 0:211 self._clean_all(resource, result)212 self._setResource(None)213 def getResource(self, result=None):214 """Get the resource for this class and record that it's being used.215 The resource is constructed using the `make` hook.216 Once done with the resource, pass it to `finishedWith` to indicated217 that it is no longer needed.218 :param result: An optional TestResult to report resource changes to.219 """220 if self._uses == 0:221 self._setResource(self._make_all(result))222 elif self.isDirty():223 self._setResource(self.reset(self._currentResource, result))224 self._uses += 1225 return self._currentResource226 def isDirty(self):227 """Return True if this managers cached resource is dirty.228 229 Calling when the resource is not currently held has undefined230 behaviour.231 """232 if self._dirty:233 return True234 for name, mgr in self.resources:235 if mgr.isDirty():236 return True237 res = mgr.getResource()238 try:239 if res is not getattr(self, name):240 return True241 finally:242 mgr.finishedWith(res)243 def _make_all(self, result):244 """Make the dependencies of this resource and this resource."""245 self._call_result_method_if_exists(result, "startMakeResource", self)246 dependency_resources = {}247 for name, resource in self.resources:248 dependency_resources[name] = resource.getResource()249 resource = self.make(dependency_resources)250 for name, value in dependency_resources.items():251 setattr(self, name, value)252 self._call_result_method_if_exists(result, "stopMakeResource", self)253 return resource254 def make(self, dependency_resources):255 """Override this to construct resources.256 257 :param dependency_resources: A dict mapping name -> resource instance258 for the resources specified as dependencies.259 """260 raise NotImplementedError(261 "Override make to construct resources.")262 def neededResources(self):263 """Return the resources needed for this resource, including self.264 265 :return: A list of needed resources, in topological deepest-first266 order.267 """268 seen = set([self])269 result = []270 for name, resource in self.resources:271 for resource in resource.neededResources():272 if resource in seen:273 continue274 seen.add(resource)275 result.append(resource)276 result.append(self)277 return result278 def reset(self, old_resource, result=None):279 """Overridable method to return a clean version of old_resource.280 By default, the resource will be cleaned then remade if it had281 previously been `dirtied`. 282 This function needs to take the dependent resource stack into283 consideration as _make_all and _clean_all do.284 :return: The new resource.285 :param result: An optional TestResult to report resource changes to.286 """287 if self._dirty:288 self._clean_all(old_resource, result)289 resource = self._make_all(result)290 else:291 resource = old_resource292 return resource293 def _setResource(self, new_resource):294 """Set the current resource to a new value."""295 self._currentResource = new_resource296 self._dirty = False297class ResourcedTestCase(unittest.TestCase):298 """A TestCase parent or utility that enables cross-test resource usage.299 :ivar resources: A list of (name, resource) pairs, where 'resource' is a300 subclass of `TestResource` and 'name' is the name of the attribute301 that the resource should be stored on.302 """303 resources = []304 def __get_result(self):305 # unittest hides the result. This forces us to look up the stack.306 # The result is passed to a run() or a __call__ method 4 or more frames307 # up: that method is what calls setUp and tearDown, and they call their308 # parent setUp etc. Its not guaranteed that the parameter to run will309 # be calls result as its not required to be a keyword parameter in 310 # TestCase. However, in practice, this works.311 stack = inspect.stack()312 for frame in stack[3:]:313 if frame[3] in ('run', '__call__'):314 # Not all frames called 'run' will be unittest. It could be a315 # reactor in trial, for instance.316 result = frame[0].f_locals.get('result')317 if (result is not None and318 getattr(result, 'startTest', None) is not None):319 return result320 def setUp(self):321 unittest.TestCase.setUp(self)322 self.setUpResources()323 def setUpResources(self):324 """Set up any resources that this test needs."""325 result = self.__get_result()326 for resource in self.resources:327 setattr(self, resource[0], resource[1].getResource(result))328 def tearDown(self):329 self.tearDownResources()330 unittest.TestCase.tearDown(self)331 def tearDownResources(self):332 """Tear down any resources that this test declares."""333 result = self.__get_result()334 for resource in self.resources:335 resource[1].finishedWith(getattr(self, resource[0]), result)336 delattr(self, resource[0])...

Full Screen

Full Screen

IonResourceSpec.js

Source:IonResourceSpec.js Github

copy

Full Screen

...13 attributions: [],14 };15 it("constructs with expected values", function () {16 spyOn(Resource, "call").and.callThrough();17 var endpointResource = IonResource._createEndpointResource(assetId);18 var resource = new IonResource(endpoint, endpointResource);19 expect(resource).toBeInstanceOf(Resource);20 expect(resource._ionEndpoint).toEqual(endpoint);21 expect(Resource.call).toHaveBeenCalledWith(resource, {22 url: endpoint.url,23 retryCallback: resource.retryCallback,24 retryAttempts: 1,25 });26 });27 it("clone works", function () {28 var endpointResource = IonResource._createEndpointResource(assetId);29 var resource = new IonResource(endpoint, endpointResource);30 var cloned = resource.clone();31 expect(cloned).not.toBe(resource);32 expect(cloned._ionRoot).toBe(resource);33 cloned._ionRoot = undefined;34 expect(cloned.retryCallback).toBe(resource.retryCallback);35 expect(cloned.headers.Authorization).toBe(resource.headers.Authorization);36 expect(cloned).toEqual(resource);37 });38 it("create creates the expected resource", function () {39 var endpointResource = IonResource._createEndpointResource(assetId);40 var resource = new IonResource(endpoint, endpointResource);41 expect(resource.getUrlComponent()).toEqual(endpoint.url);42 expect(resource._ionEndpoint).toBe(endpoint);43 expect(resource._ionEndpointResource).toEqual(endpointResource);44 expect(resource.retryCallback).toBeDefined();45 expect(resource.retryAttempts).toBe(1);46 });47 it("fromAssetId calls constructor for non-external endpoint with expected parameters", function () {48 var tilesAssetId = 123890213;49 var tilesEndpoint = {50 type: "3DTILES",51 url: "https://assets.cesium.com/" + tilesAssetId + "/tileset.json",52 accessToken: "not_really_a_refresh_token",53 attributions: [],54 };55 var options = {};56 var resourceEndpoint = IonResource._createEndpointResource(57 tilesAssetId,58 options59 );60 spyOn(IonResource, "_createEndpointResource").and.returnValue(61 resourceEndpoint62 );63 spyOn(resourceEndpoint, "fetchJson").and.returnValue(64 when.resolve(tilesEndpoint)65 );66 return IonResource.fromAssetId(tilesAssetId, options).then(function (67 resource68 ) {69 expect(IonResource._createEndpointResource).toHaveBeenCalledWith(70 tilesAssetId,71 options72 );73 expect(resourceEndpoint.fetchJson).toHaveBeenCalled();74 expect(resource._ionEndpointResource).toEqual(resourceEndpoint);75 expect(resource._ionEndpoint).toEqual(tilesEndpoint);76 });77 });78 function testNonImageryExternalResource(externalEndpoint) {79 var resourceEndpoint = IonResource._createEndpointResource(123890213);80 spyOn(IonResource, "_createEndpointResource").and.returnValue(81 resourceEndpoint82 );83 spyOn(resourceEndpoint, "fetchJson").and.returnValue(84 when.resolve(externalEndpoint)85 );86 return IonResource.fromAssetId(123890213).then(function (resource) {87 expect(resource.url).toEqual(externalEndpoint.options.url);88 expect(resource.headers.Authorization).toBeUndefined();89 expect(resource.retryCallback).toBeUndefined();90 });91 }92 it("fromAssetId returns basic Resource for external 3D tilesets", function () {93 return testNonImageryExternalResource({94 type: "3DTILES",95 externalType: "3DTILES",96 options: { url: "http://test.invalid/tileset.json" },97 attributions: [],98 });99 });100 it("fromAssetId returns basic Resource for external 3D tilesets", function () {101 return testNonImageryExternalResource({102 type: "TERRAIN",103 externalType: "STK_TERRAIN_SERVER",104 options: { url: "http://test.invalid/world" },105 attributions: [],106 });107 });108 it("fromAssetId rejects for external imagery", function () {109 return testNonImageryExternalResource({110 type: "IMAGERY",111 externalType: "URL_TEMPLATE",112 url: "http://test.invalid/world",113 attributions: [],114 })115 .then(fail)116 .otherwise(function (e) {117 expect(e).toBeInstanceOf(RuntimeError);118 });119 });120 it("createEndpointResource creates expected values with default parameters", function () {121 var assetId = 2348234;122 var resource = IonResource._createEndpointResource(assetId);123 expect(resource.url).toBe(124 Ion.defaultServer.url +125 "v1/assets/" +126 assetId +127 "/endpoint?access_token=" +128 Ion.defaultAccessToken129 );130 });131 it("createEndpointResource creates expected values with overridden options", function () {132 var serverUrl = "https://api.cesium.test/";133 var accessToken = "not_a_token";134 var assetId = 2348234;135 var resource = IonResource._createEndpointResource(assetId, {136 server: serverUrl,137 accessToken: accessToken,138 });139 expect(resource.url).toBe(140 serverUrl +141 "v1/assets/" +142 assetId +143 "/endpoint?access_token=" +144 accessToken145 );146 });147 it("createEndpointResource creates expected values with overridden defaults", function () {148 var defaultServer = Ion.defaultServer;149 var defaultAccessToken = Ion.defaultAccessToken;150 Ion.defaultServer = new Resource({ url: "https://api.cesium.test/" });151 Ion.defaultAccessToken = "not_a_token";152 var assetId = 2348234;153 var resource = IonResource._createEndpointResource(assetId);154 expect(resource.url).toBe(155 Ion.defaultServer.url +156 "v1/assets/" +157 assetId +158 "/endpoint?access_token=" +159 Ion.defaultAccessToken160 );161 Ion.defaultServer = defaultServer;162 Ion.defaultAccessToken = defaultAccessToken;163 });164 it("Calls base _makeRequest with expected options when resource no Authorization header is defined", function () {165 var originalOptions = {};166 var expectedOptions = {167 headers: {168 Authorization: "Bearer " + endpoint.accessToken,169 },170 };171 var _makeRequest = spyOn(Resource.prototype, "_makeRequest");172 var endpointResource = IonResource._createEndpointResource(assetId);173 var resource = new IonResource(endpoint, endpointResource);174 resource._makeRequest(originalOptions);175 expect(_makeRequest).toHaveBeenCalledWith(expectedOptions);176 });177 it("Calls base _makeRequest with expected options when resource Authorization header is already defined", function () {178 var originalOptions = {};179 var expectedOptions = {180 headers: {181 Authorization: "Bearer " + endpoint.accessToken,182 },183 };184 var _makeRequest = spyOn(Resource.prototype, "_makeRequest");185 var endpointResource = IonResource._createEndpointResource(assetId);186 var resource = new IonResource(endpoint, endpointResource);187 resource.headers.Authorization = "Not valid";188 resource._makeRequest(originalOptions);189 expect(_makeRequest).toHaveBeenCalledWith(expectedOptions);190 });191 it("Calls base _makeRequest with no changes for external assets", function () {192 var externalEndpoint = {193 type: "3DTILES",194 externalType: "3DTILES",195 options: { url: "http://test.invalid/tileset.json" },196 attributions: [],197 };198 var options = {};199 var _makeRequest = spyOn(Resource.prototype, "_makeRequest");200 var endpointResource = IonResource._createEndpointResource(assetId);201 var resource = new IonResource(externalEndpoint, endpointResource);202 resource._makeRequest(options);203 expect(_makeRequest.calls.argsFor(0)[0]).toBe(options);204 });205 it("Calls base _makeRequest with no changes for ion assets with external urls", function () {206 var originalOptions = {};207 var expectedOptions = {};208 var _makeRequest = spyOn(Resource.prototype, "_makeRequest");209 var endpointResource = IonResource._createEndpointResource(assetId);210 var resource = new IonResource(endpoint, endpointResource);211 resource.url = "http://test.invalid";212 resource._makeRequest(originalOptions);213 expect(_makeRequest).toHaveBeenCalledWith(expectedOptions);214 });215 it("Calls base fetchImage with preferBlob for ion assets", function () {216 var fetchImage = spyOn(Resource.prototype, "fetchImage");217 var endpointResource = IonResource._createEndpointResource(assetId);218 var resource = new IonResource(endpoint, endpointResource);219 resource.fetchImage();220 expect(fetchImage).toHaveBeenCalledWith({221 preferBlob: true,222 });223 });224 it("Calls base fetchImage with no changes for external assets", function () {225 var externalEndpoint = {226 type: "3DTILES",227 externalType: "3DTILES",228 options: { url: "http://test.invalid/tileset.json" },229 attributions: [],230 };231 var fetchImage = spyOn(Resource.prototype, "fetchImage");232 var endpointResource = IonResource._createEndpointResource(assetId);233 var resource = new IonResource(externalEndpoint, endpointResource);234 resource.fetchImage({235 preferBlob: false,236 });237 expect(fetchImage).toHaveBeenCalledWith({238 preferBlob: false,239 });240 });241 describe("retryCallback", function () {242 var endpointResource;243 var resource;244 var retryCallback;245 beforeEach(function () {246 endpointResource = new Resource({247 url: "https://api.test.invalid",248 access_token: "not_the_token",249 });250 resource = new IonResource(endpoint, endpointResource);251 retryCallback = resource.retryCallback;252 });253 it("returns false when error is undefined", function () {254 return retryCallback(resource, undefined).then(function (result) {255 expect(result).toBe(false);256 });257 });258 it("returns false when error is non-401", function () {259 var error = new RequestErrorEvent(404);260 return retryCallback(resource, error).then(function (result) {261 expect(result).toBe(false);262 });263 });264 it("returns false when error is event with non-Image target", function () {265 var event = { target: {} };266 return retryCallback(resource, event).then(function (result) {267 expect(result).toBe(false);268 });269 });270 function testCallback(resource, event) {271 var deferred = when.defer();272 spyOn(endpointResource, "fetchJson").and.returnValue(deferred.promise);273 var newEndpoint = {274 type: "3DTILES",275 url: "https://assets.cesium.com/" + assetId,276 accessToken: "not_not_really_a_refresh_token",277 };278 var promise = retryCallback(resource, event);279 var resultPromise = promise.then(function (result) {280 expect(result).toBe(true);281 expect(resource._ionEndpoint).toBe(newEndpoint);282 });283 expect(endpointResource.fetchJson).toHaveBeenCalledWith();284 //A second retry should re-use the same pending promise285 var promise2 = retryCallback(resource, event);286 expect(promise._pendingPromise).toBe(promise2._pendingPromise);287 deferred.resolve(newEndpoint);288 return resultPromise;289 }290 it("works when error is a 401", function () {291 var error = new RequestErrorEvent(401);292 return testCallback(resource, error);293 });294 it("works when error is event with Image target", function () {295 var event = { target: new Image() };296 return testCallback(resource, event);297 });298 it("works with derived resource and sets root access_token", function () {299 var derived = resource.getDerivedResource("1");300 var error = new RequestErrorEvent(401);301 return testCallback(derived, error).then(function () {302 expect(derived._ionEndpoint).toBe(resource._ionEndpoint);303 expect(derived.headers.Authorization).toEqual(304 resource.headers.Authorization305 );306 });307 });308 });...

Full Screen

Full Screen

NetworkManager.js

Source:NetworkManager.js Github

copy

Full Screen

...105 if (resource) {106 this.responseReceived(identifier, time, "Other", redirectResponse);107 resource = this._appendRedirect(identifier, time, request.url);108 } else109 resource = this._createResource(identifier, frameId, loaderId, request.url, documentURL, stackTrace);110 this._updateResourceWithRequest(resource, request);111 resource.startTime = time;112 this._startResource(resource);113 },114 resourceMarkedAsCached: function(identifier)115 {116 var resource = this._inflightResourcesById[identifier];117 if (!resource)118 return;119 resource.cached = true;120 this._updateResource(resource);121 },122 responseReceived: function(identifier, time, resourceType, response)123 {124 var resource = this._inflightResourcesById[identifier];125 if (!resource)126 return;127 resource.responseReceivedTime = time;128 resource.type = WebInspector.Resource.Type[resourceType];129 this._updateResourceWithResponse(resource, response);130 this._updateResource(resource);131 },132 dataReceived: function(identifier, time, dataLength, encodedDataLength)133 {134 var resource = this._inflightResourcesById[identifier];135 if (!resource)136 return;137 resource.resourceSize += dataLength;138 if (encodedDataLength != -1)139 resource.increaseTransferSize(encodedDataLength);140 resource.endTime = time;141 this._updateResource(resource);142 },143 loadingFinished: function(identifier, finishTime)144 {145 var resource = this._inflightResourcesById[identifier];146 if (!resource)147 return;148 this._finishResource(resource, finishTime);149 },150 loadingFailed: function(identifier, time, localizedDescription, canceled)151 {152 var resource = this._inflightResourcesById[identifier];153 if (!resource)154 return;155 resource.failed = true;156 resource.canceled = canceled;157 resource.localizedFailDescription = localizedDescription;158 this._finishResource(resource, time);159 },160 resourceLoadedFromMemoryCache: function(frameId, loaderId, documentURL, time, cachedResource)161 {162 var resource = this._createResource("cached:" + ++this._lastIdentifierForCachedResource, frameId, loaderId, cachedResource.url, documentURL);163 this._updateResourceWithCachedResource(resource, cachedResource);164 resource.cached = true;165 resource.requestMethod = "GET";166 this._startResource(resource);167 resource.startTime = resource.responseReceivedTime = time;168 this._finishResource(resource, time);169 },170 initialContentSet: function(identifier, sourceString, type)171 {172 var resource = WebInspector.networkResourceById(identifier);173 if (!resource)174 return;175 resource.type = WebInspector.Resource.Type[type];176 resource.setInitialContent(sourceString);177 this._updateResource(resource);178 },179 webSocketCreated: function(identifier, requestURL)180 {181 var resource = this._createResource(identifier, null, null, requestURL);182 resource.type = WebInspector.Resource.Type.WebSocket;183 this._startResource(resource);184 },185 webSocketWillSendHandshakeRequest: function(identifier, time, request)186 {187 var resource = this._inflightResourcesById[identifier];188 if (!resource)189 return;190 resource.requestMethod = "GET";191 resource.requestHeaders = request.headers;192 resource.webSocketRequestKey3 = request.requestKey3;193 resource.startTime = time;194 this._updateResource(resource);195 },196 webSocketHandshakeResponseReceived: function(identifier, time, response)197 {198 var resource = this._inflightResourcesById[identifier];199 if (!resource)200 return;201 resource.statusCode = response.status;202 resource.statusText = response.statusText;203 resource.responseHeaders = response.headers;204 resource.webSocketChallengeResponse = response.challengeResponse;205 resource.responseReceivedTime = time;206 this._updateResource(resource);207 },208 webSocketClosed: function(identifier, time)209 {210 var resource = this._inflightResourcesById[identifier];211 if (!resource)212 return;213 this._finishResource(resource, time);214 },215 _appendRedirect: function(identifier, time, redirectURL)216 {217 var originalResource = this._inflightResourcesById[identifier];218 var previousRedirects = originalResource.redirects || [];219 originalResource.identifier = "redirected:" + identifier + "." + previousRedirects.length;220 delete originalResource.redirects;221 this._finishResource(originalResource, time);222 var newResource = this._createResource(identifier, originalResource.frameId, originalResource.loaderId,223 redirectURL, originalResource.documentURL, originalResource.stackTrace);224 newResource.redirects = previousRedirects.concat(originalResource);225 return newResource;226 },227 _startResource: function(resource)228 {229 this._inflightResourcesById[resource.identifier] = resource;230 this._inflightResourcesByURL[resource.url] = resource;231 this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.ResourceStarted, resource);232 },233 _updateResource: function(resource)234 {235 this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.ResourceUpdated, resource);236 },237 _finishResource: function(resource, finishTime)238 {239 resource.endTime = finishTime;240 resource.finished = true;241 this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.ResourceFinished, resource);242 delete this._inflightResourcesById[resource.identifier];243 delete this._inflightResourcesByURL[resource.url];244 },245 _dispatchEventToListeners: function(eventType, resource)246 {247 this._manager.dispatchEventToListeners(eventType, resource);248 },249 _createResource: function(identifier, frameId, loaderId, url, documentURL, stackTrace)250 {251 var resource = new WebInspector.Resource(identifier, url, loaderId);252 resource.documentURL = documentURL;253 resource.frameId = frameId;254 resource.stackTrace = stackTrace;255 return resource;256 }...

Full Screen

Full Screen

resource.ts

Source:resource.ts Github

copy

Full Screen

...22 }23 add(resource: string, amount: number) {24 let resourceItem = this.resources.find(x => x.resource === resource);25 if (isNullOrUndefined(resourceItem)) {26 resourceItem = new Resource(resource, 0);27 this.resources.push(resourceItem);28 }29 resourceItem.amount += amount;30 if (resourceItem.amount > resourceItem.max && resourceItem.max !== 0) {31 resourceItem.amount = resourceItem.max;32 }33 }34 addCollection(other: ResourceCollection) {35 other.resources.forEach(element => {36 this.add(element.resource, element.amount);37 }, this);38 }39 remove(resource: string, amount: number): boolean {40 let couldAfford = true;41 const resourceItem = this.resources.find(x => x.resource === resource);42 if (isNullOrUndefined(resourceItem)) {return false; }43 resourceItem.amount -= amount;44 if (resourceItem.amount < 0) {45 resourceItem.amount = 0;46 couldAfford = false;47 }48 return couldAfford;49 }50 removeCollection(other: ResourceCollection): boolean {51 let couldAfford = true;52 other.resources.forEach(element => {53 const removeResult = this.remove(element.resource, element.amount);54 if (!removeResult) { couldAfford = false; }55 });56 return couldAfford;57 }58 setMax(resource: string, max: number) {59 let resourceItem = this.resources.find(x => x.resource === resource);60 if (isNullOrUndefined(resourceItem)) {61 resourceItem = new Resource(resource, 0);62 this.resources.push(resourceItem);63 }64 resourceItem.max = max;65 if (resourceItem.amount > resourceItem.max) {66 resourceItem.amount = resourceItem.max;67 }68 }69 addProductionRate(resource: string, rate: number) {70 let resourceItem = this.resources.find(x => x.resource === resource);71 if (isNullOrUndefined(resourceItem)) {72 resourceItem = new Resource(resource, 0);73 this.resources.push(resourceItem);74 }75 resourceItem.productionRate += rate;76 }77 setProductionRate(resource: string, rate: number) {78 let resourceItem = this.resources.find(x => x.resource === resource);79 if (isNullOrUndefined(resourceItem)) {80 resourceItem = new Resource(resource, 0);81 this.resources.push(resourceItem);82 }83 resourceItem.productionRate = rate;84 }85 addConsumptionRate(resource: string, rate: number) {86 let resourceItem = this.resources.find(x => x.resource === resource);87 if (isNullOrUndefined(resourceItem)) {88 resourceItem = new Resource(resource, 0);89 this.resources.push(resourceItem);90 }91 resourceItem.consumptionRate += rate;92 }93 setConsumptionRate(resource: string, rate: number) {94 let resourceItem = this.resources.find(x => x.resource === resource);95 if (isNullOrUndefined(resourceItem)) {96 resourceItem = new Resource(resource, 0);97 this.resources.push(resourceItem);98 }99 resourceItem.consumptionRate = rate;100 }101 resetRates() {102 this.resources.forEach(resource => {resource.productionRate = 0; resource.consumptionRate = 0; });103 }104 has(resource: string, amount?: number): boolean {105 if (!amount) { amount = 0.01; }106 const resourceItem = this.resources.find(x => x.resource === resource);107 if (isNullOrUndefined(resourceItem)) {return false; }108 return resourceItem.amount >= amount;109 }110 getAmount(resource: string): number {...

Full Screen

Full Screen

execute.py

Source:execute.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import logging3from django.db import transaction4from django.db.models import QuerySet5from .resource import ModelResource, DataResource6logger = logging.getLogger(__name__)7class Dumper(object):8 def __init__(self, root_objs):9 # 根资源10 if isinstance(root_objs, (tuple, list, QuerySet)):11 self.root_objs = root_objs12 else:13 self.root_objs = [root_objs]14 # 生成资源类15 self.model_resource_class = type('ModelResource', (ModelResource,), {})16 # 初始化根资源索引17 self.resource_root = []18 # 初始化资源关联关系索引19 self.resource_index = {}20 # 初始化资源数据21 self.resource_data = {}22 # 初始化资源关联文件23 self.files = set()24 def dumps(self, dest_dir=None):25 self.model_resource_class.reset()26 for obj in self.root_objs:27 root_resource = self.model_resource_class(obj, obj._meta.model)28 self.resource_root.append(root_resource.p_key)29 # 解析根资源的资源关联树, 注满资源池30 root_resource.parse_related_tree()31 root_resource.check_circular_dependency()32 # 序列化资源池资源,设置关联关系索引,资源数据,关联文件33 for key, resource in self.model_resource_class.resource_pool.items():34 resource.dumps()35 self.resource_index[key] = resource.get_relation_index()36 self.resource_data[key] = resource.data37 self.files.update(resource.files)38 # 复制资源关联文件39 if dest_dir and self.files:40 self.model_resource_class.copy_files(dest_dir, list(self.files))41 return {42 'root': self.resource_root,43 'index': self.resource_index,44 'data': self.resource_data,45 'files': self.files,46 }47class Loader(object):48 def __init__(self):49 # 生成资源类50 self.data_resource_class = type('DataResource', (DataResource,), {})51 def loads(self, data, src_dir=None):52 resource_root = data['root']53 resource_index = data['index']54 resource_data = data['data']55 self.data_resource_class.reset(resource_index, resource_data)56 # 从根资源解析资源树57 root_resources = []58 for root_key in resource_root:59 root_data = resource_data[root_key]60 root_model = self.data_resource_class.parse_model(root_data)61 resource = self.data_resource_class(root_data, root_model)62 resource.parse_related_tree()63 resource.check_circular_dependency()64 root_resources.append(resource)65 # 从根资源开始递归导入数据66 with transaction.atomic():67 for root_resource in root_resources:68 logger.info('save root resource[%s] start', root_resource.p_key)69 root_resource.save()70 logger.info('save root resource[%s] end', root_resource.p_key)71 # 复制资源关联文件72 if src_dir:...

Full Screen

Full Screen

routes.js

Source:routes.js Github

copy

Full Screen

1import Dashboard from '@/views/Dashboard'2import ResourceIndex from '@/views/Index'3import ResourceDetail from '@/views/Detail'4import CreateResource from '@/views/Create'5import UpdateResource from '@/views/Update'6import AttachResource from '@/views/Attach'7import UpdateAttachedResource from '@/views/UpdateAttached'8import Lens from '@/views/Lens'9import Error403 from '@/views/403'10import Error404 from '@/views/404'11export default [12 {13 name: 'dashboard',14 path: '/',15 redirect: '/dashboards/main',16 },17 {18 name: 'dashboard.custom',19 path: '/dashboards/:name',20 component: Dashboard,21 props: true,22 },23 {24 name: 'action-events.edit',25 path: '/resources/action-events/:id/edit',26 redirect: {27 name: '404',28 },29 },30 {31 name: 'index',32 path: '/resources/:resourceName',33 component: ResourceIndex,34 props: true,35 },36 {37 name: 'lens',38 path: '/resources/:resourceName/lens/:lens',39 component: Lens,40 props: true,41 },42 {43 name: 'create',44 path: '/resources/:resourceName/new',45 component: CreateResource,46 props: route => {47 return {48 resourceName: route.params.resourceName,49 viaResource: route.query.viaResource || '',50 viaResourceId: route.query.viaResourceId || '',51 viaRelationship: route.query.viaRelationship || '',52 }53 },54 },55 {56 name: 'edit',57 path: '/resources/:resourceName/:resourceId/edit',58 component: UpdateResource,59 props: route => {60 return {61 resourceName: route.params.resourceName,62 resourceId: route.params.resourceId,63 viaResource: route.query.viaResource || '',64 viaResourceId: route.query.viaResourceId || '',65 viaRelationship: route.query.viaRelationship || '',66 }67 },68 },69 {70 name: 'attach',71 path: '/resources/:resourceName/:resourceId/attach/:relatedResourceName',72 component: AttachResource,73 props: route => {74 return {75 resourceName: route.params.resourceName,76 resourceId: route.params.resourceId,77 relatedResourceName: route.params.relatedResourceName,78 viaRelationship: route.query.viaRelationship,79 polymorphic: route.query.polymorphic == '1',80 }81 },82 },83 {84 name: 'edit-attached',85 path:86 '/resources/:resourceName/:resourceId/edit-attached/:relatedResourceName/:relatedResourceId',87 component: UpdateAttachedResource,88 props: route => {89 return {90 resourceName: route.params.resourceName,91 resourceId: route.params.resourceId,92 relatedResourceName: route.params.relatedResourceName,93 relatedResourceId: route.params.relatedResourceId,94 viaRelationship: route.query.viaRelationship,95 }96 },97 },98 {99 name: 'detail',100 path: '/resources/:resourceName/:resourceId',101 component: ResourceDetail,102 props: true,103 },104 {105 name: '403',106 path: '/403',107 component: Error403,108 },109 {110 name: '404',111 path: '/404',112 component: Error404,113 },114 {115 name: 'catch-all',116 path: '*',117 component: Error404,118 },...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var Resource = require('devicefarmer-stf-client').Resource;2resource.get('/devices', function(err, res, body) {3 if (err) {4 throw err;5 }6 console.log(body);7});8var Device = require('devicefarmer-stf-client').Device;9device.list(function(err, res, body) {10 if (err) {11 throw err;12 }13 console.log(body);14});15var Device = require('devicefarmer-stf-client').Device;16device.get('HT4C1SK00058', function(err, res, body) {17 if (err) {18 throw err;19 }20 console.log(body);21});22var Device = require('devicefarmer-stf-client').Device;23device.get('HT4C1SK00058', function(err, res, body) {24 if (err) {25 throw err;26 }27 console.log(body);28});29var Device = require('devicefarmer-stf-client').Device;30device.get('HT4C1SK00058', function(err, res, body) {31 if (err) {32 throw err;33 }34 console.log(body);35});36var Device = require('devicefarmer-stf-client').Device;37device.get('HT4C1SK00058', function(err, res, body) {38 if (err) {39 throw err;40 }41 console.log(body);42});43var Device = require('devicefarmer

Full Screen

Using AI Code Generation

copy

Full Screen

1var Resource = require('devicefarmer-stf-client').Resource;2resource.getDevices().then(function (devices) {3 console.log(devices);4});5var Device = require('devicefarmer-stf-client').Device;6device.getDevices().then(function (devices) {7 console.log(devices);8});9var DeviceGroup = require('devicefarmer-stf-client').DeviceGroup;10deviceGroup.getDevices().then(function (devices) {11 console.log(devices);12});13var DeviceGroup = require('devicefarmer-stf-client').DeviceGroup;14deviceGroup.getDevices().then(function (devices) {15 console.log(devices);16});17var DeviceGroup = require('devicefarmer-stf-client').DeviceGroup;18deviceGroup.getDevices().then(function (devices) {19 console.log(devices);20});21var DeviceGroup = require('devicefarmer-stf-client').DeviceGroup;22deviceGroup.getDevices().then(function (devices) {23 console.log(devices);24});25var DeviceGroup = require('devicefarmer-stf-client').DeviceGroup;26deviceGroup.getDevices().then(function (devices) {27 console.log(devices);28});29var DeviceGroup = require('devicefarmer-stf-client').DeviceGroup;

Full Screen

Using AI Code Generation

copy

Full Screen

1var devicefarmer = require('devicefarmer-stf-client');2resource.getDevices(function(err, devices) {3 console.log(devices);4});5var devicefarmer = require('devicefarmer-stf-client');6device.getDevices(function(err, devices) {7 console.log(devices);8});9var devicefarmer = require('devicefarmer-stf-client');10resource.getDevices(function(err, devices) {11 console.log(devices);12});13var devicefarmer = require('devicefarmer-stf-client');14device.getDevices(function(err, devices) {15 console.log(devices);16});17var devicefarmer = require('devicefarmer-stf-client');18resource.getDevices(function(err, devices) {19 console.log(devices);20});21var devicefarmer = require('devicefarmer-stf-client');22device.getDevices(function(err, devices) {23 console.log(devices);24});25var devicefarmer = require('devicefarmer-stf-client');26resource.getDevices(function(err, devices) {27 console.log(devices);28});29var devicefarmer = require('devicefarmer-stf-client');30device.getDevices(function(err, devices) {31 console.log(devices);32});

Full Screen

Using AI Code Generation

copy

Full Screen

1var stf = require('devicefarmer-stf-client');2resource.getDevices().then(function (devices) {3 console.log(devices);4});5var stf = require('devicefarmer-stf-client');6device.getDevices().then(function (devices) {7 console.log(devices);8});9var stf = require('devicefarmer-stf-client');10resource.getDevices().then(function (devices) {11 console.log(devices);12});13var stf = require('devicefarmer-stf-client');14device.getDevices().then(function (devices) {15 console.log(devices);16});17Copyright (c) 2019 DeviceFarmer18Licensed under the Apache License, Version 2.0 (the "License");

Full Screen

Using AI Code Generation

copy

Full Screen

1var resource = require('devicefarmer-stf').Resource;2resource.getDevices().then(function(devices) {3 console.log(devices);4}).catch(function(err) {5 console.log(err);6});7var device = require('devicefarmer-stf').Device;8device.getDevices().then(function(devices) {9 console.log(devices);10}).catch(function(err) {11 console.log(err);12});13var device = require('devicefarmer-stf').Device;14device.getDevices().then(function(devices) {15 console.log(devices);16}).catch(function(err) {17 console.log(err);18});19var device = require('devicefarmer-stf').Device;20device.getDevices().then(function(devices) {21 console.log(devices);22}).catch(function(err) {23 console.log(err);24});25var device = require('devicefarmer-stf').Device;26device.getDevices().then(function(devices) {27 console.log(devices);28}).catch(function(err) {29 console.log(err);30});31var device = require('devicefarmer-stf').Device;32device.getDevices().then(function(devices) {33 console.log(devices);34}).catch(function(err) {35 console.log(err);36});37var device = require('devicefarmer-stf').Device;38device.getDevices().then(function(devices) {39 console.log(devices);40}).catch(function(err) {41 console.log(err);42});

Full Screen

Using AI Code Generation

copy

Full Screen

1var DeviceFarmer = require('devicefarmer-stf-client');2var resource = client.resource('devices');3resource.get(function (err, result) {4 if (err) {5 console.log(err);6 }7 console.log(result);8});9var resource = client.resource('users');10resource.get(function (err, result) {11 if (err) {12 console.log(err);13 }14 console.log(result);15});16var resource = client.resource('users/1');17resource.get(function (err, result) {18 if (err) {19 console.log(err);20 }21 console.log(result);22});23client.get('users/1', function (err, result) {24 if (err) {25 console.log(err);26 }27 console.log(result);28});29client.get('users/1', function (err, result) {30 if (err) {31 console.log(err);32 }33 console.log(result);34});35client.get('users/1', function (err, result) {36 if (err) {37 console.log(err

Full Screen

Using AI Code Generation

copy

Full Screen

1var devicefarmer = require('devicefarmer-stf-client');2var resource = devicefarmer.resource;3var client = devicefarmer.client;4var options = {5};6var req = client.request(options, function(res) {7 console.log('STATUS: ' + res.statusCode);8 console.log('HEADERS: ' + JSON.stringify(res.headers));9 res.setEncoding('utf8');10 res.on('data', function (chunk) {11 console.log('BODY: ' + chunk);12 });13});14req.on('error', function(e) {15 console.log('problem with request: ' + e.message);16});17req.end();18var http = require('http');19var https = require('https');20module.exports = {21 request: function(options, callback) {22 var protocol = options.protocol === 'https:' ? https : http;23 return protocol.request(options, callback);24 }25};26var client = require('./client');27module.exports = {28 request: function(options, callback) {29 return client.request(options, callback);30 }31};32var devicefarmer = require('devicefarmer-stf-client');33var resource = devicefarmer.resource;34var client = devicefarmer.client;35var options = {36};37resource.request(options, function(res) {38 console.log('STATUS: ' + res.statusCode);39 console.log('HEADERS: ' + JSON.stringify(res.headers));40 res.setEncoding('utf8');41 res.on('data', function (chunk) {42 console.log('BODY: ' + chunk);43 });44});

Full Screen

Using AI Code Generation

copy

Full Screen

1var resource = require('devicefarmer-stf').Resource;2var rest = new resource();3var device = rest.getDevice("device_id");4console.log(device);5var device = require('devicefarmer-stf').Device;6var dev = new device();7var device = dev.getDevice("device_id");8console.log(device);

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run devicefarmer-stf automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful