def backup_attack_loop(self): g = self.g self.image = self.orginalImage.subsurface((160, 0, 32, 32)) speed = self.walktimer self.walktimer += 1 if self.walktimer > 6: self.walktimer = 6 self.timer += 1 timergate = self.timer % 100 if timergate >= 80: if timergate == 80: self.face_the_player() if timergate == 85: Shot(g, self.direction, (self.rect.x + 16, self.rect.y + 8), 'shot8', 'enemy') self.walking = 0 else: self.walking = 1 if timergate % 100 == 0: self.face_the_player() dx = self.rect.x - g.player.rect.x if dx <40 and dx > -40: if self.dy == 10.0: self.dy = -10.0 if self.walking: self.rect.x += (1 - (self.direction * 2)) * speed framen = self.timer / 2 % 3 self.image = self.orginalImage.subsurface((32 + framen * 32, 0, 32, 32)) else: self.walktimer = 0 self.dy += .5 if self.dy > 10.0: self.dy = 10.0 self.rect.y += self.dy if self.rect.x < 416: self.direction = 0 self.image = pygame.transform.flip(self.image, self.direction, 0) # hitting the bullets and player s = Rect(self.rect) if s.colliderect (g.player.rect): g.player.touch(self) for b in g.bullets: if b.owner == 'player': drect = (b.rect.x + 30, b.rect.y ) if s.collidepoint(drect): b.destroy() self.health -= b.get_damage() e = Effect(self.g, 'health', (self.rect.x, self.rect.y)) e.healthchange = -b.get_damage() self.image = g.make_image_white(self.image)
def tick(self): self.host.game.do_damage(self.host, d(3), D_COLD, self.owner) if self.host == self.host.game.player: self.host.game.shout('You are freezing!') else: self.host.game.shout('%s is freezing!' % (self.host.name)) Effect.tick(self)
def tick(self): self.host.game.do_damage(self.host, d(3), D_FIRE, self.owner) if self.host == self.host.game.player: self.host.game.shout('You are getting burned!') else: self.host.game.shout('%s is getting burned!' % (self.host.name)) Effect.tick(self)
def touch(self, e): if self.imortal == 0: self.g.hurt.play() self.imortal = 10 self.health -= e.get_damage() ef = Effect(self.g, "health", (self.rect.x, self.rect.y)) ef.healthchange = -e.get_damage() # drop some skyberries if "weapon" in self.g.saveData: if self.g.saveData["weapon"] >= 1: wpnstr = "shot" + str(self.g.saveData["weapon"]) + "_lvl" if self.g.saveData[wpnstr] > 1: self.g.saveData[wpnstr] -= 1 if self.g.saveData[wpnstr] == 9: Effect(self.g, "msg", (self.rect.x, self.rect.y), "Level Down") if self.g.saveData[wpnstr] == 19: Effect(self.g, "msg", (self.rect.x, self.rect.y), "Level Down") sb = Inventory(self.g, "skyberry", (self.rect.x, self.rect.y)) sb.canget = 0 sb = Inventory(self.g, "skyberry", (self.rect.x, self.rect.y)) sb.canget = 0 sb = Inventory(self.g, "skyberry", (self.rect.x, self.rect.y)) sb.canget = 0 self.g.player.gravity = 15 self.g.player.jumping = 1 if self.g.saveData["weapon"] != 0: shotType = "shot" + str(self.g.saveData["weapon"]) self.g.saveData[shotType] -= 1 self.g.saveData["health"] = self.health
def tick(self): self.host.dazzled = True if self.host == self.host.game.player: self.host.game.shout('You are blinded!') else: self.host.game.shout('%s is blinded!' % (self.host.name)) Effect.tick(self)
def __init__(self, host, owner): dur = 1 Effect.__init__(self, dur, host, owner) actors = owner.game.get_all_srd_actors(owner.pos()) for act in actors: Effect.__init__(self, dur, act, owner) weaponinfotext = 'Splatters the enemy'
def tick(self): self.host.game.do_damage(self.host, d(3), D_GENERIC, self.owner) if self.host == self.host.game.player: self.host.game.shout('You are bleeding') else: self.host.game.shout('%s bleeds' % (self.host.name)) Effect.tick(self)
def addHealth(self, n): self.health += n ef = Effect(self.g, "health", (self.rect.x, self.rect.y - 10)) ef.healthchange = n if self.health > self.healthmax: self.health = self.healthmax self.g.saveData["health"] = self.health
def tick(self): self.host.game.do_damage(self.host, d(3), D_ACID, self.owner) if self.host == self.host.game.player: self.host.game.shout('You are splashed by acid!') else: self.host.game.shout('%s is splashed by acid!' % (self.host.name)) Effect.tick(self)
def get_groups_to_converge(config_func): """ Get all tenant's all groups that needs convergence triggering """ eff = Effect(GetAllValidGroups()) eff = eff.on( filter(lambda g: tenant_is_enabled(g["tenantId"], config_func))) return eff.on(list)
def tick(self): self.host.timer += self.host.speed * d(3) if self.host == self.host.game.player: self.host.game.shout('You are stunned') else: self.host.game.shout('%s is stunned' % (self.host.name)) Effect.tick(self)
def tick(self): if d(100) < 5: self.host.timer += self.host.speed * d(5) if self.host == self.host.game.player: self.host.game.shout('You suddenly fell asleep') else: self.host.game.shout('%s suddenly fells asleep' % (self.host.name)) Effect.tick(self)
def tick(self): self.host.timer += 1000 if self.host == self.host.game.player: self.host.game.shout('You are stunned by the Floating Eye`s gaze!') else: self.host.game.shout('%s is stunned by the Floating Eye`s gaze!' % (self.host.name)) Effect.tick(self)
def concretize_service_request( authenticator, log, service_configs, throttler, tenant_id, service_request): """ Translate a high-level :obj:`ServiceRequest` into a low-level :obj:`Effect` of :obj:`pure_http.Request`. This doesn't directly conform to the Intent performer interface, but it's intended to be used by a performer. :param ICachingAuthenticator authenticator: the caching authenticator :param BoundLog log: info about requests will be logged to this. :param dict service_configs: As returned by :func:`otter.constants.get_service_configs`. :param callable throttler: A function of ServiceType, HTTP method -> Deferred bracketer or None, used to throttle requests. See :obj:`_Throttle`. :param tenant_id: tenant ID. """ auth_eff = Effect(Authenticate(authenticator, tenant_id, log)) invalidate_eff = Effect(InvalidateToken(authenticator, tenant_id)) if service_request.log is not None: log = service_request.log service_config = service_configs[service_request.service_type] region = service_config['region'] service_name = service_config['name'] def got_auth((token, catalog)): request_ = add_headers(otter_headers(token), request) request_ = add_effect_on_response( invalidate_eff, service_request.reauth_codes, request_) request_ = add_json_request_data(request_) if 'url' in service_config: request_ = add_bind_root(service_config['url'], request_) else: request_ = add_bind_service( catalog, service_name, region, log, request_) request_ = add_error_handling( service_request.success_pred, request_) if service_request.json_response: request_ = add_json_response(request_) return request_( service_request.method, service_request.url, headers=service_request.headers, data=service_request.data, params=service_request.params, log=log) eff = auth_eff.on(got_auth) bracket = throttler(service_request.service_type, service_request.method.lower(), tenant_id) if bracket is not None: return Effect(_Throttle(bracket=bracket, effect=eff)) else: return eff
def mushroom_attack_loop(self): g = self.g if self.health <= 0: if self.feeling != 'dead': self.feeling = 'dead' self.timer = 0 if self.feeling == 'dead': if self.timer > 70: self.image = pygame.Surface((1, 1), SRCALPHA) self.dead = 1 return if self.timer % 10 == 0: self.exp2.play() if self.timer % 3 == 0: # flash on and off self.image = pygame.Surface((1, 1), SRCALPHA) else: x = random.randint(0, 256) y = random.randint(0, 256) e = Effect(self.g, 'explosion', (self.rect.x + x, self.rect.y + y)) return if self.timer % 20 == 1: if self.timer % 200 < 100: c = random.randint(0, 20) s = Shot(self.g, self.direction, (self.rect.x + 128, self.rect.y + 128 + c), 'shot5', 'enemy') s.callback = self.create_slime_monster self.squirt2.play() s = Rect(self.rect) s.x += 80 s.width -= 100 s.y += 100 s.height -= 180 if s.colliderect (g.player.rect): g.player.touch(self) for b in g.bullets: if b.owner == 'player': drect = (b.rect.x + 30, b.rect.y ) if s.collidepoint(drect): b.destroy() self.health -= b.get_damage() e = Effect(self.g, 'health', (self.rect.x, self.rect.y)) e.healthchange = -b.get_damage() tmp = pygame.Surface((256, 256), SRCALPHA) tmp.blit(self.image, (0,0)) tmp.blit(self.secondImage, (0,0)) self.image = tmp self.hitme.play() speed = 2 self.rect.x += (1 - (self.direction * 2)) * speed self.draw_health_meter()
def tick(self): a = -d(4) if self.host.cur_health - a > self.host.health: a = self.host.cur_health - self.host.health self.host.game.do_damage(self.host, a, D_ORDER) if self.host == self.host.game.player: self.host.game.shout('You are regenerating') else: self.host.game.shout('%s is regenerating' % (self.host.name)) Effect.tick(self)
def as_effect(self): """Produce a :obj:`Effect` to create a stack.""" eff = Effect(Func(uuid4)) def got_uuid(uuid): stack_config = append_stack_uuid(self.stack_config, uuid) return create_stack(thaw(stack_config)).on( _success_reporter('Waiting for stack to create')) return eff.on(got_uuid)
def get_last_info(fname): eff = Effect(ReadFileLines(fname)).on( lambda lines: (int(lines[0]), datetime.utcfromtimestamp(float(lines[1])))) def log_and_return(e): _eff = err(e, "error reading previous number of tenants") return _eff.on(lambda _: (None, None)) return eff.on(error=log_and_return)
def get_org_repos(name): """ Fetch the repos that belong to an organization. :return: An Effect resulting in a list of strings naming the repositories. """ req = Effect( HTTPRequest("get", "https://api.github.com/orgs/{0}/repos".format(name))) return req.on(success=lambda x: [repo['name'] for repo in json.loads(x)])
def tick(self): self.host.game.do_damage(self.host, d(3), D_POISON, self.owner) if d(100) < 35: StunEffect(self.host, self.owner) if d(100) < 35: DazzleEffect(self.host, self.owner) if self.host == self.host.game.player: self.host.game.shout('You are poisoned') else: self.host.game.shout('%s is poisoned' % (self.host.name)) Effect.tick(self)
def get_orgs(name): """ Fetch the organizations a user belongs to. :return: An Effect resulting in a list of strings naming the user's organizations. """ req = Effect( HTTPRequest("get", "https://api.github.com/users/{0}/orgs".format(name))) return req.on(success=lambda x: [org['login'] for org in json.loads(x)])
def main_effect(): """ Request a username from the keyboard, and look up all repos in all of that user's organizations. :return: an Effect resulting in a list of repositories. """ intent = ReadLine("Enter Github Username> ") read_eff = Effect(intent) org_repos_eff = read_eff.on(success=get_orgs_repos) return org_repos_eff
def as_effect(self): """Produce a :obj:`Effect` to create a server.""" eff = Effect(Func(generate_server_name)) def got_name(random_name): server_config = set_server_name(self.server_config, random_name) return create_server(thaw(server_config)) return eff.on(got_name).on( success=_success_reporter('waiting for server to become active'), error=_failure_reporter(CreateServerConfigurationError, CreateServerOverQuoteError))
def tick(self): new_pos = self.host.game.get_free_adj(self.owner.pos()) if new_pos != None: self.owner.game.shout('%s splits in half!' % (self.owner.name)) new = dungeon.Populator.create_creature(self.owner.pop_name, self.owner.filename) new.set_pos(new_pos) new.game.add_actor(new) self.owner.health = self.owner.health / 2 + 1 self.owner.cur_health = self.owner.cur_health / 2 + 1 new.health = self.owner.health new.cur_health = self.owner.cur_health new.xp_value = self.owner.xp_value / 3 + 2 Effect.tick(self)
def tick(self): self.host.game.do_damage(self.host, d(3), D_POISON, self.owner) notice = False if d(100) < 10: StunEffect(self.host, self.owner) notice = True if d(100) < 10: DazzleEffect(self.host, self.owner) notice = True if d(100) < 10: self.host.game.do_damage(self.host, d(3), D_POISON, self.owner) notice = True if d(100) < 2: self.host.game.do_damage(self.host, d(25), D_POISON, self.owner) notice = True if notice: if self.host == self.host.game.player: self.host.game.shout('You are poisoned') else: self.host.game.shout('%s is poisoned' % (self.host.name)) Effect.tick(self)
def get_all_metrics_effects(tenanted_groups, log, _print=False): """ Gather server data for and produce metrics for all groups across all tenants in a region :param dict tenanted_groups: Scaling groups grouped with tenantId :param bool _print: Should the function print while processing? :return: ``list`` of :obj:`Effect` of (``list`` of :obj:`GroupMetrics`) or None """ effs = [] for tenant_id, groups in tenanted_groups.iteritems(): eff = get_all_scaling_group_servers() eff = Effect(TenantScope(eff, tenant_id)) eff = eff.on(partial(get_tenant_metrics, tenant_id, groups, _print=_print)) eff = eff.on(list) eff = eff.on( error=lambda exc_info: log.err(exc_info_to_failure(exc_info))) effs.append(eff) return effs
def robot_attack_loop(self): g = self.g self.timer += 1 speed = 9 attackphase = self.timer % 70 self.image = self.orginalImage.subsurface((0, 32, 32, 32)) if attackphase == 1: # lunge at the player self.face_the_player() self.attacking = 2 # 2 = lunging elif attackphase == 50: # fire a ball of death at the player Shot(self.g, self.direction, (self.rect.x + 16, self.rect.y + 20), 'shot8', 'enemy') if attackphase >= 50 and attackphase <= 65: # fire a ball of death at the player self.image = self.orginalImage.subsurface((64, 32, 32, 32)) # lunging if self.attacking == 2: self.image = self.orginalImage.subsurface((32, 32, 32, 32)) if self.rect.colliderect (self.g.player.rect): self.g.player.touch(self) self.rect.x += speed if self.direction: self.rect.x -= speed*2 # loop through bullets and see if I die for b in g.bullets: if b.owner == 'player': drect = (b.rect.x + 30, b.rect.y ) if self.rect.collidepoint(drect): b.destroy() self.health -= b.get_damage() e = Effect(self.g, 'health', (self.rect.x, self.rect.y)) e.healthchange = -b.get_damage() self.image = g.make_image_white(self.image, (32, 32)) self.image = pygame.transform.flip(self.image, not self.direction, 0) if self.health <= 0: self.feeling = 'dead' self.attacking = 0 self.dontwalk = 1
def loop_hit_death(self, g, r, canbehit, canhitplayer): self.timer += 1 self.image = pygame.transform.flip(self.image, self.direction, 0) s = Rect(self.rect) if self.mode != 'death': if s.colliderect (g.player.rect): if canhitplayer: g.player.touch(self) if canbehit: for b in g.bullets: if b.owner == 'player': drect = (b.rect.x, b.rect.y) if s.collidepoint(drect): b.destroy() self.health -= b.get_damage() e = Effect(self.g, 'health', (self.rect.x, self.rect.y)) e.healthchange = -b.get_damage() if self.mode != 'ouch': self.birdhit.play() self.mode = 'ouch' self.btimer = 0 #k = Rect(b.rect) #k.x -= g.view.x #k.y -= g.view.y #pygame.draw.rect(g.screen, (0,255,255), k) #s.x -= g.view.x #s.y -= g.view.y #pygame.draw.rect(g.screen, (255,0,255), s) # dead if self.health <= 0: if self.mode != 'death': self.mode = 'death' self.btimer = 0
def __init__(self, fight, src = None): ''' Конструктор. Fight fight - битва, в которой участвует файтер. src - документ. ''' if src: self.__dict__.update(src) self.deck = [Card.js_load(c) for c in self.deck] self.hand = [Card.js_load(c) for c in self.hand] self.stats = Stats(self.stats) self.effects = [Effect.js_load(eff, self) for eff in self.effects] else: self.id = unique_id() self.stats = Stats() self.fight = fight
def task_cli_pkg_install(distribution, package_source=PackageSource()): """ Install the Flocker CLI package. :param bytes distribution: The distribution the node is running. :param PackageSource package_source: The source from which to install the package. :return: a sequence of commands to run on the distribution """ commands = task_package_install("clusterhq-flocker-cli", distribution, package_source) # Although client testing is currently done as root.e want to use # sudo for better documentation output. return sequence([(Effect( Sudo(command=e.intent.command, log_command_filter=e.intent.log_command_filter)) if isinstance( e.intent, Run) else e) for e in commands.intent.effects])
def test_event_added(self): """ Event is added to cloud feed """ class AddEvent(object): pass add_event_performer = deferred_performer( lambda d, i: succeed('performed')) cf = self.make_cf( add_event=lambda *a: Effect(AddEvent()), get_disp=lambda *a: TypeDispatcher( {AddEvent: add_event_performer})) d = cf({'event': 'dict', 'cloud_feed': True, 'message': ('m', )}) self.assertEqual(self.successResultOf(d), 'performed') self.assertFalse(self.log.err.called)
def test_one_retry(self): """ Retry the effect if it fails once. """ divisors = [0, 1] def tester(): x = divisors.pop(0) return 1 / x seq = [ (Delay(1), lambda ignore: None), ] retrier = retry_effect_with_timeout(Effect(Func(tester)), 10, time=self.get_time()) result = perform_sequence(seq, retrier) self.assertEqual(result, 1 / 1)
def _is_server_in_group(group, server_id): """ Given a group and server ID, determines if the server is a member of the group. If it isn't, it raises a :class:`ServerNotFoundError`. """ try: response, server_info = yield Effect( TenantScope( retry_effect(get_server_details(server_id), retry_times(3), exponential_backoff_interval(2)), group.tenant_id)) except NoSuchServerError: raise ServerNotFoundError(group.tenant_id, group.uuid, server_id) group_id = group_id_from_metadata( get_in(('server', 'metadata'), server_info, {})) if group_id != group.uuid: raise ServerNotFoundError(group.tenant_id, group.uuid, server_id)
def check_and_trigger(tenant_id, group_id): """ Trigger convergence on given group if it is ACTIVE and not paused """ try: group, info = yield Effect( GetScalingGroupInfo(tenant_id=tenant_id, group_id=group_id)) except NoSuchScalingGroupError: # Nothing to do if group has been deleted yield msg("selfheal-group-deleted", tenant_id=tenant_id, scaling_group_id=group_id) else: state = info["state"] if (state.status == ScalingGroupStatus.ACTIVE and not (state.paused or state.suspended)): yield with_log(trigger_convergence(tenant_id, group_id), tenant_id=tenant_id, scaling_group_id=group_id)
def service_request( service_type, method, url, headers=None, data=None, params=None, log=None, reauth_codes=(401, 403), success_pred=has_code(200), json_response=True): """ Make an HTTP request to a Rackspace service, with a bunch of awesome behavior! :param otter.constants.ServiceType service_type: The service against which the request should be made. :param bytes method: HTTP method :param url: partial URL (appended to service endpoint) :param dict headers: base headers; will have auth headers added. :param data: JSON-able object or None. :param params: dict of query param ids to lists of values, or a list of tuples of query key to query value. :param log: log to send request info to. :param sequence success_pred: A predicate of responses which determines if a response indicates success or failure. :param sequence reauth_codes: HTTP codes upon which to invalidate the auth cache. :param bool json_response: Specifies whether the response should be parsed as JSON. :param bool parse_errors: Whether to parse :class:`APIError` :raise APIError: Raised asynchronously when the response HTTP code is not in success_codes. :return: Effect of :obj:`ServiceRequest`, resulting in a tuple of (:obj:`twisted.web.client.Response`, JSON-parsed HTTP response body). """ return Effect(ServiceRequest( service_type=service_type, method=method, url=url, headers=headers, data=data, params=params, log=log, reauth_codes=reauth_codes, success_pred=success_pred, json_response=json_response))
def update_servers_cache(group, now, servers, lb_nodes, include_deleted=True): """ Updates the cache, adding servers, with a flag if autoscale is active on each one. :param group: scaling group :param list servers: list of NovaServer objects :param list lb_nodes: list of CLBNode objects :param include_deleted: Include deleted servers in cache. Defaults to True. """ server_dicts = [] for server in servers: sd = thaw(server.json) if is_autoscale_active(server, lb_nodes): sd["_is_as_active"] = True if server.state != ServerState.DELETED or include_deleted: server_dicts.append(sd) return Effect( UpdateServersCache(group.tenant_id, group.uuid, now, server_dicts))
def test_configuration(self): """ Source AMIs, build region, and target regions can all be overridden in a chosen template. """ expected_build_region = AWS_REGIONS.EU_WEST_1 expected_publish_regions = [ AWS_REGIONS.AP_NORTHEAST_1, AWS_REGIONS.AP_SOUTHEAST_1, AWS_REGIONS.AP_SOUTHEAST_2, ] expected_source_ami_map = { AWS_REGIONS.EU_WEST_1: random_name(self) } intent = PackerConfigure( build_region=expected_build_region, publish_regions=expected_publish_regions, source_ami_map=expected_source_ami_map, template=u"docker", ) # Call the performer packer_configuration_path = sync_perform( dispatcher=RealPerformers( working_directory=self.make_temporary_directory() ).dispatcher(), effect=Effect(intent=intent) ) with packer_configuration_path.open('r') as f: packer_configuration = json.load(f) [builder] = packer_configuration["builders"] build_region = builder['region'] build_source_ami = builder['source_ami'] publish_regions = builder['ami_regions'] [provisioner] = packer_configuration["provisioners"] self.assertEqual( (expected_build_region.value, set(c.value for c in expected_publish_regions), expected_source_ami_map[expected_build_region]), (build_region, set(publish_regions), build_source_ami) )
def test_perform(self): """ ``StandardOut`` has a performer that writes content to sys.stdout. """ fake_sys_module = FakeSysModule() intent = StandardOut( content=random_name(self).encode('ascii'), ) result = sync_perform( dispatcher=RealPerformers( sys_module=fake_sys_module ).dispatcher(), effect=Effect(intent=intent) ) self.assertIs(None, result) self.assertEqual( intent.content, fake_sys_module.stdout.getvalue() )
def test_delete_server(self, mock_dav): """ :obj:`DeleteServer.as_effect` calls `delete_and_verify` with retries. It returns SUCCESS on completion and RETRY on failure """ mock_dav.side_effect = lambda sid: Effect(sid) eff = DeleteServer(server_id='abc123').as_effect() self.assertIsInstance(eff.intent, Retry) self.assertEqual( eff.intent.should_retry, ShouldDelayAndRetry(can_retry=retry_times(3), next_interval=exponential_backoff_interval(2))) self.assertEqual(eff.intent.effect.intent, 'abc123') self.assertEqual( resolve_effect(eff, (None, {})), (StepResult.RETRY, [ErrorReason.String('must re-gather after deletion in order to ' 'update the active cache')]))
def test_get_scaling_group_info_log_context(self): """ When run in an effectful log context, the fields are bound to the log passed to delete_group. """ manifest = {} def view_manifest(with_policies, with_webhooks, get_deleting): return manifest self.group.view_manifest.side_effect = view_manifest eff = Effect(GetScalingGroupInfo(tenant_id='00', group_id='g1')) expected_lookup = (matches(IsBoundWith(base_log=True, effectful=True)), '00', 'g1') result = self.perform_with_group( eff, expected_lookup, self.group, fallback_dispatcher=get_log_dispatcher(self.log, {'effectful': True})) self.assertEqual(result, (self.group, manifest))
class TestEffect(unittest.TestCase): def setUp(self): self.expected_str = 'Effect:\n\tATT - MAGIC: 5 PHYSICAL: 5\n\tDEF - MAGIC: 5 PHYSICAL: 5\n\tSTATS - HP: 5 STR: 5 INT: 5 AGI: 5' self.expected_attack = Damage(6,6) self.expected_defense = Damage(6,6) self.expected_stats = Stats(6,6,6,6) self.test_effect = Effect(Damage(5,5), Damage(5,5), Stats(5,5,5,5)) def tearDown(self): self.expected_attack = None self.expected_defense = None self.expected_stats = None self.test_effect = None def test_total_strength(self): self.assertEqual(5, self.test_effect.total_strength()) def test_total_intelligence(self): self.assertEqual(5, self.test_effect.total_intelligence()) def test_total_agility(self): self.assertEqual(5, self.test_effect.total_agility()) def test_total_hp(self): self.assertEqual(5, self.test_effect.total_hp()) def test_total_attack(self): self.assertEqual(Damage(5,5), self.test_effect.total_attack()) def test_total_defense(self): self.assertEqual(Damage(5,5), self.test_effect.total_defense()) # def test_increase_attack(self): # self.test_effect.increase_attack((1,1)) # self.assertEqual(self.expected_attack, self.test_effect.attack) # def test_increase_defense(self): # self.test_effect.increase_defense((1,1)) # self.assertEqual(self.expected_defense, self.test_effect.defense) # def test_increase_stats(self): # self.test_effect.increase_stats((1,1,1,1)) # self.assertEqual(self.expected_stats, self.test_effect.stats) def test_str(self): self.assertEqual(self.expected_str, str(self.test_effect))
def provision_rackspace(node, package_source, distribution, variants): """ Provision flocker on this node. :param LibcloudNode node: Node to provision. :param PackageSource package_source: See func:`task_install_flocker` :param bytes distribution: See func:`task_install_flocker` :param set variants: The set of variant configurations to use when provisioning """ commands = [] if distribution in ('centos-7', ): commands.append( run_remotely( username='******', address=node.address, commands=sequence([ task_upgrade_kernel_centos(), Effect(Func(node.reboot)), ]), )) commands.append( run_remotely( username='******', address=node.address, commands=sequence([ provision( package_source=package_source, distribution=node.distribution, variants=variants, ), # https://clusterhq.atlassian.net/browse/FLOC-1550 # This should be part of ._install.configure_cluster task_open_control_firewall(), ]), )) return sequence(commands)
def modify_and_trigger(dispatcher, group, logargs, modifier, *args, **kwargs): """ Modify group state and trigger convergence after that :param IScalingGroup group: Scaling group whose state is getting modified :param log: Bound logger :param modifier: Callable as described in IScalingGroup.modify_state :return: Deferred with None """ cannot_exec_pol_err = None try: yield group.modify_state(modifier, *args, **kwargs) except CannotExecutePolicyError as ce: cannot_exec_pol_err = ce if tenant_is_enabled(group.tenant_id, config_value): eff = Effect( BoundFields(trigger_convergence(group.tenant_id, group.uuid), logargs)) yield perform(dispatcher, eff) if cannot_exec_pol_err is not None: raise cannot_exec_pol_err
def test_exponential_backoff(self): """ Retry the effect multiple times with exponential backoff between retries. """ divisors = [0, 0, 0, 1] def tester(): x = divisors.pop(0) return 1 / x seq = [ (Delay(1), lambda ignore: None), (Delay(2), lambda ignore: None), (Delay(4), lambda ignore: None), ] retrier = retry_effect_with_timeout( Effect(Func(tester)), timeout=10, time=self.get_time(), ) result = perform_sequence(seq, retrier) self.assertEqual(result, 1)
def test_template_error(self): """ Template errors result in the process exiting and an error message printed to stderr. Packer prints machine-readable output to stderr and ``publish-installer-images`` echos those lines to its stderr as well as parsing the output. """ sys_module = FakeSysModule() self.addCleanup( lambda: self.addDetail( name="stderr", content_object=text_content( sys_module.stderr.getvalue() ) ) ) configuration_path = self.make_temporary_file(content='') d = async_perform( dispatcher=RealPerformers( sys_module=sys_module, ).dispatcher(), effect=Effect( intent=PackerBuild( configuration_path=configuration_path, ) ) ) d = self.assertFailure(d, ProcessTerminated) def check_error(exception): self.assertEqual(1, exception.exitCode) self.assertIn( "Failed to parse template", sys_module.stderr.getvalue() ) return d.addCallback(check_error)
def print_avgs(data, prefix=""): used = [] output = [] longest = 0 for d in data: if d.name not in used: used.append(d.name) output.append( Effect(d.name, avg(data, d.name) - avg(data, d.name, True))) if len(d.name) > longest: longest = len(d.name) output.sort() for d in output: adj = "more" if d.score < 0: adj = "less" spacer = ' ' * (longest - len(d.name)) print(prefix + d.name + spacer + " makes you " + ("{0:." + str(decimal_points) + "f}").format(abs(d.score) * 100) + "% " + adj + " happy")
def test_timeout_measured_from_perform(self): """ The timeout is measured from the time the effect is performed (not from the time it is created). """ timeout = 3.0 time = self.get_time([0.0] + list(timeout + i for i in range(10))) exceptions = [Exception("One problem")] result = object() def tester(): if exceptions: raise exceptions.pop() return result retrier = retry_effect_with_timeout( Effect(Func(tester)), timeout=3, time=time, ) # The retry effect has been created. Advance time a little bit before # performing it. time() expected_intents = [ # The first call raises an exception and should be retried even # though (as a side-effect of the `time` call above) the timeout, # as measured from when `retry_effect_with_timeout` was called, has # already elapsed. # # There's no second intent because the second call to the function # succeeds. (Delay(1), lambda ignore: None), ] self.assertThat( perform_sequence(expected_intents, retrier), Is(result) )
def test_perform_fails(self): """ If performing effect to add event fails, error is logged """ class AddEvent(object): pass add_event_performer = deferred_performer( lambda d, i: fail(ValueError('bad'))) cf = self.make_cf(add_event=lambda *a: Effect(AddEvent()), get_disp=lambda *a: TypeDispatcher( {AddEvent: add_event_performer})) d = cf({'event': 'dict', 'cloud_feed': True, 'message': ('m', )}) self.successResultOf(d) # log doesn't have cloud_feed in it self.log.err.assert_called_once_with(CheckFailure(ValueError), 'cf-add-failure', event_data={'event': 'dict'}, system='otter.cloud_feed', cf_msg='m')
def test_log_effectful_fields(self): """ The log passed to treq is bound with the fields from BoundFields. """ log = mock_log().bind(duplicate='should be overridden') expected_log = matches( IsBoundWith(duplicate='effectful', bound='stuff')) req = ('GET', 'http://google.com/', None, None, None, { 'log': expected_log }) response = StubResponse(200, {}) treq = StubTreq(reqs=[(req, response)], contents=[(response, "content")]) req = Request(method="get", url="http://google.com/", log=log) req.treq = treq req_eff = Effect(req) bound_log_eff = with_log(req_eff, bound='stuff', duplicate='effectful') dispatcher = ComposedDispatcher( [get_simple_dispatcher(None), get_log_dispatcher(log, {})]) self.assertEqual( self.successResultOf(perform(dispatcher, bound_log_eff)), (response, "content"))
def run_remotely(username, address, commands, port=22, log_command_filter=identity): """ Run some commands on a remote host. :param bytes address: The address of the remote host to connect to. :param bytes username: The user to connect as. :param Effect commands: The commands to run. :param int port: The port of the ssh server to connect to. :param callable log_command_filter: A filter to apply to any logging of the executed command. :return Effect: """ return Effect( RunRemotely(username=username, address=address, commands=commands, port=port, log_command_filter=log_command_filter))
def perform_retry_without_delay(actual_retry_intent): should_retry = actual_retry_intent.should_retry if isinstance(should_retry, ShouldDelayAndRetry): def should_retry(exc_info): exc_type, exc_value, exc_traceback = exc_info failure = Failure(exc_value, exc_type, exc_traceback) return Effect(Constant( actual_retry_intent.should_retry.can_retry(failure))) new_retry_effect = Effect(Retry( effect=actual_retry_intent.effect, should_retry=should_retry)) _dispatchers = [TypeDispatcher({Retry: perform_retry}), base_dispatcher] if fallback_dispatcher is not None: _dispatchers.append(fallback_dispatcher) seq = [(expected_retry_intent.effect.intent, performer) for performer in performers] return perform_sequence(seq, new_retry_effect, ComposedDispatcher(_dispatchers))
def test_no_exponential_backoff(self): """ If ``False`` is passed for the ``backoff`` parameter, the effect is always retried with the same delay. """ divisors = [0, 0, 0, 1] def tester(): x = divisors.pop(0) return 1 / x seq = [ (Delay(5), lambda ignore: None), (Delay(5), lambda ignore: None), (Delay(5), lambda ignore: None), ] retrier = retry_effect_with_timeout( Effect(Func(tester)), timeout=1, retry_wait=timedelta(seconds=5), backoff=False, ) result = perform_sequence(seq, retrier) self.assertEqual(result, 1)
def delete_divergent_flag(tenant_id, group_id, version): """ Delete the dirty flag, if its version hasn't changed. See note [Divergent flags] for more info. :return: Effect of None. """ flag = format_dirty_flag(tenant_id, group_id) path = CONVERGENCE_DIRTY_DIR + '/' + flag fields = dict(path=path, dirty_version=version) try: yield Effect(DeleteNode(path=path, version=version)) except BadVersionError: # BadVersionError shouldn't be logged as an error because it's an # expected occurrence any time convergence is requested multiple times # rapidly. yield msg('mark-clean-skipped', **fields) except NoNodeError: yield msg('mark-clean-not-found', **fields) except Exception: yield err(None, 'mark-clean-failure', **fields) else: yield msg('mark-clean-success')
def test_perform_eviction(self): """ Call supervisor's scrub metadata function. """ supervisor = FakeSupervisor() set_supervisor(supervisor) self.addCleanup(set_supervisor, None) log, group = (object(), mock_group(None)) intent = EvictServerFromScalingGroup(log=log, transaction_id='transaction_id', scaling_group=group, server_id='server_id') r = sync_perform( TypeDispatcher({ EvictServerFromScalingGroup: partial(perform_evict_server, supervisor) }), Effect(intent)) self.assertIsNone(r) self.assertEqual( supervisor.scrub_calls, [(log, "transaction_id", group.tenant_id, 'server_id')])
def _generic_rcv3_request(step_class, request_bag, lb_id, server_id): """ Perform a generic RCv3 bulk step on a single (lb, server) pair. :param IStep step_class: The step class to perform the action. :param request_bag: An object with a bunch of useful data on it. :param str lb_id: The id of the RCv3 load balancer to act on. :param str server_id: The Nova server id to act on. :return: A deferred that will fire when the request has been performed, firing with the parsed result of the request, or :data:`None` if the request has no body. """ effect = step_class(lb_node_pairs=s((lb_id, server_id)))._bare_effect() if step_class is BulkAddToRCv3: svc_req = effect.intent codes = set(svc_req.success_pred.codes) - set([409]) svc_req.success_pred = has_code(*codes) # Unfortunate that we have to TenantScope here, but here's where we're # performing. scoped = Effect(TenantScope(effect, request_bag.tenant_id)) d = perform(request_bag.dispatcher, scoped) return d.addCallback(itemgetter(1))
def test_upload_content_type(self): """ A content type can be set for an uploaded file. """ filename = random_name(self) tmpdir = FilePath(self.mktemp()) tmpdir.makedirs() tmpfile = tmpdir.child(filename) tmpfile.setContent('foo') s3 = boto.connect_s3() bucket = s3.get_bucket(bucket_name) self.addCleanup(bucket.delete_key, filename) sync_perform(dispatcher=ComposedDispatcher( [boto_dispatcher, base_dispatcher]), effect=Effect( UploadToS3( source_path=tmpdir, target_bucket=bucket_name, target_key=filename, file=tmpfile, content_type='application/json', ))) key = bucket.get_key(filename) self.assertEqual('application/json', key.content_type)
def request(method, url, **kwargs): """Return a Request wrapped in an Effect.""" return Effect(Request(method=method, url=url, **kwargs))
def _with_conv_runid(self, eff): """ Return Effect wrapped with converger_run_id log field """ return Effect(Func(uuid.uuid4)).on(str).on(lambda uid: with_log( eff, otter_service='converger', converger_run_id=uid))
def Continue(): return Effect(Constant(None))
def play(self): # Create a VideoCapture object and read from input file # If the input is the camera, pass 0 instead of the video file name cap = cv2.VideoCapture(self.video_file) # Check if camera opened successfully if cap.isOpened() is False: print("Error opening video stream or file") index = 0 # find out the video dimensions self.height, self.width, _ = cap.read()[1].shape if not self.multi: shape = Shape( self.width, self.height, self.paint_x, self.paint_y, self.speed, self.image_paths[index % len(self.image_paths)], self.animation, ) else: shapes = [ Shape( self.width, self.height, randint(0, self.width), randint(0, self.height), # int(self.height / 4 * (i + 1)), # int(self.width / (4 * (i + 1))), self.speed, image, "fall", # must be with fall!!! it's 02:03am ) for i, image in enumerate(self.image_paths[:4]) ] effect = Effect(self.color_effect) text = Subtitles(self.text, self.text_speed, acceleration=3, font=self.font) # text = Subtitles('FAST\nFURIOUS\nFANCY', self.text_speed, # './data/fonts/Dogfish/Dogfish.ttf') title = Subtitles(self.title, self.text_speed, font=self.font) title.font_scale = 3 title.thick = 3 # Read until video is completed # Default resolutions of the frame are obtained.The default resolutions # are system dependent. We convert the resolutions from float to # integer. # frame_width = int(cap.get(3)) # frame_height = int(cap.get(4)) # print("width ", frame_width) # print("height ", frame_height) out = cv2.VideoWriter(self.output, cv2.VideoWriter_fourcc(*'MP4V'), 17, (self.width, self.height)) while cap.isOpened(): # Capture frame-by-frame ret, frame = cap.read() try: self.width = frame.shape[1] self.height = frame.shape[0] except AttributeError: break if ret is True: frame = effect.apply(frame) if self.multi: for shape in shapes: shape.paint(frame) else: shape.paint(frame) pass frame = title.show_title(frame, self.width, self.height) # frame = text.show_low(frame, self.width, self.height) frame = text.show_price(frame, self.width, self.height) # if title.counter == 1: # text.counter = title.counter if self.render: cv2.imshow("Frame", frame) out.write(frame) if not self.multi and shape.end: index += 1 if index >= len(self.image_paths): index = 0 shape = Shape( self.width, self.height, self.paint_x, self.paint_y, self.speed, self.image_paths[index % len(self.image_paths)], self.animation, ) # Press Q on keyboard to exit if cv2.waitKey(25) & 0xFF == ord("q"): return # Break the loop else: break # When everything done, release the video capture object cap.release() # Closes all the frames cv2.destroyAllWindows()