def test_save_test(self): element = ElementState(locators=[Locator(by=By.NAME, value="q")]) element.save() state1 = State(elements=[], url="") state2 = State(elements=[element], url="http://www.google.com") state1.save() state2.save() config = RunConfig(params={ "url": "http://www.google.com/", "search": "Something" }) commands = [ Command(command=Command.NAVIGATE, config_key="url"), Command(command=Command.SENDKEYS, element=element, config_key="search") ] action = Action(name="Some Action", steps=commands, start_state=state1, end_state=state2) action.save() test = Test(name="Some test", actions=[action]) test.save() suite = Suite(tests=[test], url="http://www.google.com/") suite.execute(self.driver, config) suite.save() assert suite.suite_results[-1].passed, suite.suite_results[-1].message
def rentCar(self, rental): car = self.getCarById(rental.car_id) rent_period = datetime.datetime.strptime( rental.end_date, '%Y-%m-%d').date() - datetime.datetime.strptime( rental.start_date, '%Y-%m-%d').date() rent_days = rent_period.days + 1 price = rent_days * car.price_per_day + rental.distance * car.price_per_km price = self.decreasePrice(price, rent_days, car, rental) totalCommission = 0.3 * price insurance_fee = totalCommission / 2 assistance_fee = rent_days * 100 drivy_fee = totalCommission - (insurance_fee + assistance_fee) commission = Commission(insurance_fee, assistance_fee, drivy_fee) actions = [] actions.append(Action("driver", "debit", price)) actions.append(Action("owner", "credit", price - totalCommission)) actions.append(Action("insurance", "credit", insurance_fee)) actions.append(Action("drivy", "credit", drivy_fee)) actions.append(Action("assistance", "credit", assistance_fee)) return Rental(rental.id, actions)
def test_verify_state_action(self): element = ElementState(locators=[Locator(by=By.NAME, value="q")]) element2 = ElementState(locators=[Locator(by=By.NAME, value="btnK")]) element.save() element2.save() state1 = State(elements=[], url="") state1.save() state = State(elements=[element], url="http://www.google.com") state.save() verify_state = action_builder.get_verify_state_action(state) commands = [Command(command=Command.NAVIGATE, config_key="url")] action = Action(name="Google Nav", steps=commands, start_state=state1, end_state=state) action.save() state.actions = [] results = action.execute( self.driver, config=RunConfig(params={ "url": "http://www.google.com/", "search": "Something" }))
def test_execute(self): element = ElementState(locators=[Locator(by=By.NAME, value="q")]) element2 = ElementState(locators=[Locator(by=By.NAME, value="btnG")]) element.save() element2.save() state1 = State(elements=[], url="") state2 = State(elements=[element], url="http://www.google.com") state3 = State(elements=[element2], url="http://www.google.com") state1.save() state2.save() state3.save() commands = [ Command(command=Command.NAVIGATE, config_key="url"), Command(command=Command.SENDKEYS, element=element, config_key="search"), Command(command=Command.CLICK, element=element2) ] action = Action(name="Google Search", steps=commands, start_state=state1, end_state=state3) action.save() results = action.execute( self.driver, config=RunConfig(params={ "url": "http://www.google.com/", "search": "Something" }))
def test_save_action(self): element = ElementState(locators=[Locator(by=By.NAME, value="q")]) element.save() google_home = State(url=self.driver.current_url, elements=[element]) google_home.save() action = action_builder.get_nav_action("http://www.google.com/", google_home) action.save() state1 = State(elements=[element], url="http://www.google.com") state1.save() state2 = State(elements=[element], url="http://www.google.com") state2.save() commands = [ Command(command=Command.NAVIGATE, params="http://www.google.com/"), Command(command=Command.SENDKEYS, element=element, params="Something") ] action = Action(name="Some Action", steps=commands, start_state=state1, end_state=state2) action.save() state1.actions = [action] state1.save() print state1.id assert state1.actions[0].steps == commands assert state1.actions[0].end_state == state2
def test_local_suite(self): element = ElementState(locators=[Locator(by=By.NAME, value="q")]) element.save() state1 = State(elements=[], url="") state2 = State(elements=[element], url="http://www.google.com") state1.save() state2.save() params = {} params["url"] = "http://www.google.com/" params["search"] = "Something" commands = [ Command(command=Command.NAVIGATE, config_key="url"), Command(command=Command.SENDKEYS, element=element, config_key="search") ] action = Action(name="Some Action", steps=commands, start_state=state1, end_state=state2) action.save() test = Test(name="Some test", actions=[action]) test.save() suite = TestSuite(tests=[test], url="http://www.google.com/") config1 = RunConfig(browser="Firefox", params=params) config2 = RunConfig(browser="Chrome", params=params) configs = SuiteConfig(configs=[config1, config2], suite=suite) configs.save() suite.suite_config = configs suite.save() executor = SuiteExecutor(suite) executor.execute()
def get_click_action(element, start_state, end_state): command = Command(element=element, command=Command.CLICK) action = Action(name="Click %s" % str(element), steps=[command], start_state=start_state, end_state=end_state) action.save() return action
def get_nav_action(url, end_state): command1 = Command(command=Command.NAVIGATE, config_key="url") action = Action(name="Get %s" % url, steps=[command1], start_state=state_builder.get_blank_state(), end_state=end_state) action.save() return action
def get_sendkeys_action(element, start_state, end_state): command = Command(element=element, command=Command.SENDKEYS, config_key=element.type) action = Action(name="Send Keys %s" % str(element), steps=[command], start_state=start_state, end_state=end_state) action.save() return action
def get_verify_state_action(state): all_commands = [] for element in state.elements: all_commands.append(Command(element=element, command=Command.VERIFY)) action = Action(name="Verify %s" % state, steps=all_commands, start_state=state, end_state=state) action.save() return action
def event_to_action(self, event, context): ''' Passes event.args to action.args Note that event.args comes from previous action.output. ''' event_info = self.pipeline.event_to_action(event, context) self.logger.info(f'Event to action {event_info}') return Action(event_info, args=event.args)
def __init__(self, actions, data): self.actions = [Action(name, event) for name, event in actions.items()] self.db_path = os.path.join(data['directory'], data['dbname']) self.table_name = data['tablename'] self.neurons = [ Neuron(action, Condition(self.db_path, self.table_name)) for action in self.actions ]
def load_request(xacml): if not isinstance(xacml, dict): xacml = json.loads(xacml) user_attrs = xacml["Request"]["AccessSubject"][0]["Attribute"] subject = Subject() for attr in user_attrs: if "Issuer" in attr.keys(): subject.add_attribute(attr["AttributeId"], attr["Value"], attr["Issuer"], attr["DataType"], attr["IncludeInResult"]) else: subject.add_attribute(attr["AttributeId"], attr["Value"], None, attr["DataType"], attr["IncludeInResult"]) action_attrs = xacml["Request"]["Action"][0]["Attribute"] action = Action() for attr in action_attrs: action.add_attribute(attr["AttributeId"], attr["Value"]) resource = Resource() if len(xacml["Request"]["Resource"]) == 1: resource_attrs = xacml["Request"]["Resource"][0]["Attribute"] for attr in resource_attrs: resource.add_attribute(attr["AttributeId"], attr["Value"], attr["DataType"], attr["IncludeInResult"]) else: resource_ids = [] resource_values = [] resource_data_types = [] resource_include_results = [] for i in range(0, len(xacml["Request"]["Resource"])): resource_attrs = xacml["Request"]["Resource"][i]["Attribute"] for attr in resource_attrs: resource_ids.append(attr["AttributeId"]) resource_values.append(attr["Value"]) resource_data_types.append(attr["DataType"]) resource_include_results.append(attr["IncludeInResult"]) resource.add_attribute(resource_ids, resource_values, resource_data_types, resource_include_results) return subject, action, resource
def test_sauce_suite(self): element = ElementState(locators=[Locator(by=By.NAME, value="q")]) element.save() state1 = State(elements=[], url="") state2 = State(elements=[element], url="http://www.google.com") state1.save() state2.save() params = {} params["url"] = "http://www.google.com/" params["search"] = "Something" commands = [ Command(command=Command.NAVIGATE, config_key="url"), Command(command=Command.SENDKEYS, element=element, config_key="search") ] action = Action(name="Some Action", steps=commands, start_state=state1, end_state=state2) action.save() test = Test(name="Some test", actions=[action]) test.save() suite = TestSuite(tests=[test], url="http://www.google.com/") config1 = RunConfig(browser="iphone", sauce_user="******", host="sauce", sauce_key="c479e821-57e7-4b3f-8548-48e520585187", params=params) config2 = RunConfig(browser="ipad", sauce_user="******", shost="sauce", auce_key="c479e821-57e7-4b3f-8548-48e520585187", params=params) configs = SuiteConfig(configs=[config1], suite=suite) configs.save() suite.suite_config = configs suite.save() executor = SuiteExecutor(suite) executor.execute()
def test_compare_state(self): self.driver.get("http://www.google.com/") state1 = state_builder.get_blank_state() state1.save() state2 = state_builder.get_current_state(self.driver) state2.save() self.driver.get("https://www.google.com/#q=something") state3 = state_builder.get_current_state(self.driver) state3.save() config = RunConfig(params={ "url": "http://www.google.com/", "search": "Something" }) search_fields = element_filter.filter_contains_text( state2.elements, "Search") search_field = search_fields[0] commands1 = [Command(command=Command.NAVIGATE, config_key="url")] commands2 = [ Command(command=Command.SENDKEYS, element=search_field, config_key="search") ] nav_action = Action(name="Google Nav", steps=commands1, start_state=state1, end_state=state2) search_action = Action(name="Google Search", steps=commands2, start_state=state2, end_state=state3) nav_action.save() search_action.save() test = Test(name="Google Search Failure", actions=[nav_action, search_action]) test.save() suite = Suite(name="Failure Example", tests=[test]) suite.execute(self.driver, config) suite.save(cascade=True) print suite.id assert suite.suite_results[-1].passed search_field.locators = [Locator(by=By.CLASS_NAME, value="INVALID")] search_field.save() suite.execute(self.driver, config=config) results = suite.suite_results[-1] assert not results.passed comparison = StateComparer(self.driver).compare_states( results.failed_state, results.actual_state) assert len(comparison[0].elements) == len(comparison[1].elements)
def post(self, post_id): # Check user information before processing if current_user.role: if not current_user.name or not current_user.phone: return jsonify({ 'message': 'Name and phone number are required!' }) else: if not current_user.name or not current_user.job: return jsonify({ 'message': 'Name and job information are required!' }) user_id = current_user.id action = Action.query.filter_by(post_id=post_id, user_id=user_id).all() print(action) if len(action) == 0: like = Action(post_id=post_id, user_id=user_id) like.save() res = {post_id: dict(user_id=user_id)} return json.dumps(res)
def get_logout_action(self): command1 = Command(command=Command.SENDKEYS, element=self.username, config_key=ElementType.USERNAME) command2 = Command(command=Command.SENDKEYS, element=self.password, config_key=ElementType.PASSWORD) command3 = Command(command=Command.CLICK, element=self.submit) action = Action(name="Login %s" % self.start_state.url, steps=[command1, command2, command3], start_state=self.start_state) response = action.execute(self.driver, self.config) if response.passed and not self.start_state.is_state_present( self.driver): print "assuming login was successful because the state is no longer present" self.end_state = state_builder.get_current_state(self.driver) self.end_state.save() action.end_state = self.end_state action.save() return action else: raise Exception("Could not generate login action")
def test_failure_report(self): element = ElementState(locators=[Locator(by=By.NAME, value="INVALID")]) element2 = ElementState( locators=[Locator(by=By.NAME, value="INVALID")]) element.save() element2.save() state1 = State(elements=[], url="") state2 = State(elements=[element], url="http://www.google.com") state3 = State(elements=[element2], url="http://www.google.com") state1.save() state2.save() state3.save() commands = [ Command(command=Command.NAVIGATE, config_key="http://www.google.com/"), Command(command=Command.SENDKEYS, element=element, config_key="search"), Command(command=Command.CLICK, element=element2) ] action = Action(name="Google Search", steps=commands, start_state=state1, end_state=state3) action.save() test = Test(name="Some test", actions=[action]) test.save() suite = Suite(name="some name", tests=[test]) suite.execute(self.driver, config=RunConfig(params={ "url": "http://www.google.com/", "search": "Something" })) suite.save() assert not suite.suite_results[-1].passed assert suite.suite_results[-1].actual_state is not None assert suite.suite_results[-1].failed_state is not None assert suite.suite_results[-1].html is not None and not "" assert suite.suite_results[-1].screenshot is not None and not ""
def rentCar(self, rental): car = self.getCarById(rental.car_id) rent_period = datetime.datetime.strptime( rental.end_date, '%Y-%m-%d').date() - datetime.datetime.strptime( rental.start_date, '%Y-%m-%d').date() rent_days = rent_period.days + 1 price = rent_days * car.price_per_day + rental.distance * car.price_per_km price = self.decreasePrice(price, rent_days, car, rental) totalCommission = 0.3 * price owner_credit = price - totalCommission rental_options = [] for option in self.options: if option.rental_id == rental.id: rental_options.append(option.type) new_values = self.computeOptionCost(totalCommission, owner_credit, option, rent_days) totalCommission = new_values["totalCommission"] owner_credit = new_values["owner_credit"] insurance_fee = totalCommission / 2 assistance_fee = rent_days * 100 drivy_fee = totalCommission - (insurance_fee + assistance_fee) commission = Commission(insurance_fee, assistance_fee, drivy_fee) actions = [] actions.append(Action("driver", "debit", price)) actions.append(Action("owner", "credit", owner_credit)) actions.append(Action("insurance", "credit", insurance_fee)) actions.append(Action("drivy", "credit", drivy_fee)) actions.append(Action("assistance", "credit", assistance_fee)) rental = Rental(rental.id, actions, rental_options) return rental
def explore(self, state, stops, pois): if np.random.randint(0, len(stops) + len(pois)) < len(stops): p = None idx = np.random.choice(np.arange(len(stops)), p=p) place_idx, eta, route_idx = stops.pop(idx) target = self.create_bus_stop(place_idx) else: p = self.poi_map.get_scores([place_id for place_id, _, _ in pois]) idx = np.random.choice(np.arange(len(pois)), p=p) place_idx, eta, route_idx = pois.pop(idx) target = self.create_poi(place_idx) if route_idx is None: mode = MODE_WALK route = None else: mode = MODE_BUS route = self.bus_network.bus_routes[route_idx] action = Action(state.time, state.place, target, mode, eta, route) return action
def test_init_state(self): self.url = "http://www.google.com" blank_state = state_builder.get_blank_state() blank_state.save() self.driver.get(self.url) state = state_builder.get_current_state(self.driver) state.save() element = ElementState(locators=[Locator(by=By.NAME, value="q")]) element2 = ElementState(locators=[Locator(by=By.NAME, value="btnG")]) element.save() element2.save() nav_command = [Command(command=Command.NAVIGATE, config_key="url")] type_command = [ Command(command=Command.SENDKEYS, element=element, config_key="search"), Command(command=Command.SENDKEYS, element=element, config_key="enter") ] action = Action(name="Navigate", steps=nav_command, start_state=blank_state, end_state=state) action.save() action2 = Action(name="Search", steps=type_command, start_state=state, end_state=blank_state) action2.save() config = RunConfig( params={ "url": "http://www.google.com/", "search": "Something", "enter": Keys.ENTER }) action.execute(self.driver, config) action2.execute(self.driver, config) time.sleep(5) new_state = state_builder.get_current_state(self.driver) new_state.save() action2.end_state = new_state action2.save() new_state.init_actions = [action, action2] new_state.save() state_id = new_state.id print state_id self.driver.get("http://www.msn.com/") new_state.initialize_state(self.driver, config)
def action(): return Action('jump')
def __init__(self, actions, data): self.actions = [Action(name, event) for name, event in actions.items()] self.data = data self.neurons = [Neuron(action, Condition(self.data)) for action in self.actions]
def getNextAction(self): self.step += 1 return Action(self.actions[self.step], self.context)
def _prepare_base_model(self, base_model): print('=> base model: {}'.format(base_model)) if 'resnet' in base_model: self.base_model = getattr( torchvision.models, base_model)(True if self.pretrain == 'imagenet' else False) if self.is_shift: print('Adding action...') from models.action import make_temporal_shift make_temporal_shift(self.base_model, self.num_segments, n_div=self.shift_div, place=self.shift_place, temporal_pool=self.temporal_pool) if self.non_local: print('Adding non-local module...') from ops.non_local import make_non_local make_non_local(self.base_model, self.num_segments) self.base_model.last_layer_name = 'fc' self.input_size = 224 self.input_mean = [0.485, 0.456, 0.406] self.input_std = [0.229, 0.224, 0.225] self.base_model.avgpool = nn.AdaptiveAvgPool2d(1) if self.modality == 'Flow': self.input_mean = [0.5] self.input_std = [np.mean(self.input_std)] elif self.modality == 'RGBDiff': self.input_mean = [0.485, 0.456, 0.406 ] + [0] * 3 * self.new_length self.input_std = self.input_std + [ np.mean(self.input_std) * 2 ] * 3 * self.new_length elif 'res2net' in base_model: from archs.res2net import res2net50_26w_4s self.base_model = res2net50_26w_4s(True if self.pretrain == 'imagenet' else False) if self.is_shift: from models.temporal_shift_res2net import make_temporal_shift make_temporal_shift(self.base_model, self.num_segments, n_div=self.shift_div, place=self.shift_place, temporal_pool=self.temporal_pool) if self.non_local: print('Adding non-local module...') from ops.non_local import make_non_local make_non_local(self.base_model, self.num_segments) self.base_model.last_layer_name = 'fc' self.input_size = 224 self.input_mean = [0.485, 0.456, 0.406] self.input_std = [0.229, 0.224, 0.225] self.base_model.avgpool = nn.AdaptiveAvgPool2d(1) if self.modality == 'Flow': self.input_mean = [0.5] self.input_std = [np.mean(self.input_std)] elif self.modality == 'RGBDiff': self.input_mean = [0.485, 0.456, 0.406 ] + [0] * 3 * self.new_length self.input_std = self.input_std + [ np.mean(self.input_std) * 2 ] * 3 * self.new_length elif base_model == 'mobilenetv2': from archs.mobilenet_v2 import mobilenet_v2, InvertedResidual self.base_model = mobilenet_v2(True if self.pretrain == 'imagenet' else False) self.base_model.last_layer_name = 'classifier' self.input_size = 224 self.input_mean = [0.485, 0.456, 0.406] self.input_std = [0.229, 0.224, 0.225] self.base_model.avgpool = nn.AdaptiveAvgPool2d(1) if self.is_shift: from models.action import Action for m in self.base_model.modules(): if isinstance(m, InvertedResidual) and len( m.conv) == 8 and m.use_res_connect: m.conv[0] = Action(m.conv[0], n_segment=self.num_segments, shift_div=self.shift_div) if self.modality == 'Flow': self.input_mean = [0.5] self.input_std = [np.mean(self.input_std)] elif self.modality == 'RGBDiff': self.input_mean = [0.485, 0.456, 0.406 ] + [0] * 3 * self.new_length self.input_std = self.input_std + [ np.mean(self.input_std) * 2 ] * 3 * self.new_length elif base_model == 'BNInception': if self.is_shift: from archs.bn_inception_action import bninception self.base_model = bninception(pretrained=self.pretrain, n_segment=self.num_segments, fold_div=self.shift_div) self.input_size = self.base_model.input_size self.input_mean = self.base_model.mean self.input_std = self.base_model.std self.base_model.last_layer_name = 'fc' if self.modality == 'Flow': self.input_mean = [128] elif self.modality == 'RGBDiff': self.input_mean = self.input_mean * (1 + self.new_length) self.base_model.build_temporal_ops( self.num_segments, is_temporal_shift=self.shift_place, shift_div=self.shift_div) else: raise ValueError('Unknown base model: {}'.format(base_model))