def open(self): LOG.debug("the client %s connected with compute socket", self.request.remote_ip) if self not in HostHandler.clients: HostHandler.clients.add(self) self.stream.set_nodelay(True) if not self.running: HostHandler.running = time.time() start(HostHandler, _HOST_CACHE, _c.STATE_INTERVAL_TIME, HostHandler.run_host_state)
def check_multi_windows(browser): # Done: 1) зайти в админку # Done: 2) открыть пункт меню Countries (или страницу http://localhost/litecart/admin/?app=countries&doc=countries) # Done: 3) открыть на редактирование какую-нибудь страну или начать создание новой # Done: 4) возле некоторых полей есть ссылки с иконкой в виде квадратика со стрелкой -- они ведут на внешние страницы и открываются в новом окне, именно это и нужно проверить. # Done: требуется именно кликнуть по ссылке, чтобы она открылась в новом окне, потом переключиться в новое окно, закрыть его, вернуться обратно, и повторить эти действия для всех таких ссылок. common.start("Checking multiple windows on countries") function_result = True wait10 = WebDriverWait(browser, 10) common_litecart.do_login_admin(browser) browser.get("http://localhost/litecart/admin/?app=countries&doc=countries") wait10.until( EC.element_to_be_clickable((By.CSS_SELECTOR, "button[name=disable]"))) common.success("Countries page opened") browser.find_element_by_link_text("Add New Country").click() common.success("New country add page opened") # find all links targeting new window and go through them for i in range( len(browser.find_elements_by_css_selector(".fa-external-link"))): common.info("") # take another link current_element = browser.find_elements_by_css_selector( ".fa-external-link")[i] # get handles of all windows and current window start_handles = set(browser.window_handles) start_active_handle = browser.current_window_handle # click on the link to open new window current_element.click() WebDriverWait(browser, 30).until(EC.new_window_is_opened(list(start_handles))) # get handles of windows and find new one next_handles = set(browser.window_handles) new_handle = next_handles ^ start_handles common.info("New window id = %s" % list(new_handle)[0]) # switch to the new window browser.switch_to_window(list(new_handle)[0]) common.success("Switched to window '%s'" % list(new_handle)[0]) common.info("Window title = '%s'" % browser.title) # close active (new) window using javascript browser.execute_script("close();") final_handles = set(browser.window_handles) if final_handles == start_handles: call_function = common.success else: common.info("Cannot close window '%s'" % browser.title) call_function = common.fail call_function("Closed window '%s'" % list(new_handle)[0]) # switch back to the main window browser.switch_to_window(start_active_handle) common.success("Switched to main window '%s'" % start_active_handle) common.finish(function_result, "Checking multiple windows") return function_result
def register_user(browser): common.start("Starting registration") function_result = True browser.get("http://www.localhost/litecart/") browser.find_element_by_link_text("New customers click here").click() common.success("Get to the registration page") user = get_user_data('en') # set registration data registration_data = [ {"location": "input[name=firstname]", "value": user["first_name"] }, {"location": "input[name=lastname]", "value": user["last_name"] }, {"location": "input[name=address1", "value": user["street"] }, {"location": "input[name=city]", "value": user["city"] }, {"location": "#box-create-account input[name=email]", "value": user["email"] }, {"location": "#box-create-account input[name=password]", "value": user["password"] }, {"location": "input[name=confirmed_password]", "value": user["password"] }, {"location": "input[name=postcode]", "value": user["postcode"] } ] for field in registration_data: function_result = input_value_to_input_field(browser, field) and function_result # select country and state from dropdown list registration_data = [ {"location": "select[name=country_code]", "value": user["country_code"], "description": user["country"] }, {"location": "select[name=zone_code]", "value": user["state_code"], "description": user["state"] } ] for field in registration_data: function_result = select_from_dropdown_list(browser, field) and function_result # unsubscribe from newsletters function_result = set_check_box(browser, "input[name=newsletter]", False) and function_result common.info("Uncheck '%s' to unsubscribe from newsletters: ok" % "input[name=newsletter]") # click registration button browser.find_element_by_css_selector("button[name=create_account]").click() common.success("Login successfull") # make logout with first appropriate link browser.find_element_by_link_text("Logout").click() common.success("Logout successfull") # make login back using left form registration_data = [ {"location": "#box-account-login input[name=email]", "value": user["email"] }, {"location": "#box-account-login input[name=password]", "value": user["password"] } ] for field in registration_data: function_result = input_value_to_input_field(browser, field) and function_result browser.find_element_by_css_selector("button[name=login]").click() common.success("Second login successfull") # make logout again to get out of store browser.find_element_by_link_text("Logout").click() common.success("Logout successfull") common.finish(function_result, "Registration") return function_result
def browse_catalog(browser): common.start("Start browsing catalog") function_result = True common_litecart.do_login_admin(browser) wait10 = WebDriverWait(browser, 10) # go to the 'Catalog' page browser.get( "http://localhost/litecart/admin/?app=catalog&doc=catalog&category_id=1" ) wait10.until( EC.presence_of_element_located((By.CSS_SELECTOR, ".data-table"))) length = len(browser.find_elements_by_css_selector("tbody tr")) for i in range(1, length): common.info("") # go to the 'Catalog' page browser.get( "http://localhost/litecart/admin/?app=catalog&doc=catalog&category_id=1" ) wait10.until( EC.presence_of_element_located((By.CSS_SELECTOR, ".data-table"))) common.success("Open 'Catalog' page") check_log(browser) table_lines = browser.find_elements_by_css_selector("tbody tr") category = table_lines[i].find_elements_by_css_selector( "input")[0].get_property("name") if "products" in category: product = table_lines[i].find_elements_by_css_selector("a")[0] product_name = product.get_property("innerText") common.info("Process product '%s'" % product_name) product.click() wait10.until( EC.presence_of_element_located( (By.CSS_SELECTOR, "button[name=delete]"))) common.success("Process product '%s'" % product_name) # Замечание: если раскомментировать эту строку, то получим замечание в логе драйвера и аварийный останов теста, # но эта строка использовалась для просмотра, что лог доступен и можно вывести его сообщения #browser.execute_script("alert('OK');") check_log(browser) # Done: зайти в админскую часть # Done: открыть каталог, категорию, которая содержит товары # Done: последовательно открывать страницы товаров # Done: проверять, не появляются ли в логе браузера сообщения (любого уровня) common.finish(function_result, "Browse catalog") return function_result
def open(self): if self not in NetworkHandler.clients: NetworkHandler.clients.add(self) LOG.debug("the client %s connected with compute socket", self.request.remote_ip) self.stream.set_nodelay(True) if not NetworkHandler.running: NetworkHandler.running = time.time() yield start(NetworkHandler, _NETWORK_CACHE, _c.STATE_INTERVAL_TIME, NetworkHandler.run_net_state)
def deploy_tomcat_apps(apps='',ext='war',version='release',silent=1,profile=''): get_tomcat_apps(apps=apps,version=version,ext=ext) put_tomcat_apps(apps=apps,ext=ext) # Formating a list of services applications=apps.split(' ') services=list() for app in applications: services.append('tomcat7-'+app) services=' '.join(services) common.start(services=services,silent=1) common.stop(services=services,silent=1) install_tomcat_apps(apps=apps,ext=ext) get_profile_app(apps=apps,ext='tar.gz',version='',profile=profile) put_profile_app(profiles=profile,ext='tar.gz') install_profile_app(apps=apps,profile=profile,ext='tar.gz') common.start(services=services,silent=1)
def start_bot(player, color, seed): try: bot = common.start(player, colors[color].lower(), seed) except OSError: print(colors[color ^ 1] + 'e') print() sys.exit() atexit.register(bot.terminate) return bot
def open(self): LOG.debug("the client %s connected with compute socket", self.request.remote_ip) if self not in ImageHandler.clients: ImageHandler.clients.add(self) self.stream.set_nodelay(True) if not ImageHandler.running: ImageHandler.running = time.time() yield start(ImageHandler, _IMAGE_CACHE, _c.STATE_INTERVAL_TIME, ImageHandler.run_image_state)
def open(self): if self not in VolumeHandler.clients: VolumeHandler.clients.add(self) LOG.debug("the client %s connected with compute socket", self.request.remote_ip) self.stream.set_nodelay(True) if not VolumeHandler.running: VolumeHandler.running = time.time() yield start(VolumeHandler, _VOLUME_CACHE, _c.STATE_INTERVAL_TIME, VolumeHandler.run_volume_state)
def deploy_tomcat_apps(apps='', ext='war', version='release', silent=1, profile=''): get_tomcat_apps(apps=apps, version=version, ext=ext) put_tomcat_apps(apps=apps, ext=ext) # Formating a list of services applications = apps.split(' ') services = list() for app in applications: services.append('tomcat7-' + app) services = ' '.join(services) common.start(services=services, silent=1) common.stop(services=services, silent=1) install_tomcat_apps(apps=apps, ext=ext) get_profile_app(apps=apps, ext='tar.gz', version='', profile=profile) put_profile_app(profiles=profile, ext='tar.gz') install_profile_app(apps=apps, profile=profile, ext='tar.gz') common.start(services=services, silent=1)
def handle(): DashBoardHandler.get_log() start(DashBoardHandler, _DASHBOARD_STAT_CACHE, _c.DASHBOARD_STAT_INTERVAL_TIME, DashBoardHandler.get_stat) start(DashBoardHandler, _DASHBOARD_ALARM_CACHE, _c.DASHBOARD_ALARM_INTERVAL_TIME, DashBoardHandler.get_alarm) start(DashBoardHandler, _DASHBOARD_TOPN_CACHE, _c.DASHBOARD_TOP_INTERVAL_TIME, DashBoardHandler.get_top)
def handle(): start(HostDetailHandler, _HOST_DETAIL_ALARM, _c.HOST_DETAIL_ALARM_INTERVAL_TIME, HostDetailHandler.get_alarm) start(HostDetailHandler, _HOST_DETAIL_VMS, _c.HOST_DETAIL_VMS_INTERVAL_TIME, HostDetailHandler.run_host_vms) start(HostDetailHandler, _HOST_DETAIL_STATE, _c.STATE_INTERVAL_TIME, HostDetailHandler.run_host_state) HostDetailHandler.run(HostDetailHandler)
def handle(): start(ComputeDetailsHandler, _VM_DETAIL_LOG, _c.VM_DETAIL_LOG_INTERVAL_TIME, ComputeDetailsHandler.get_computer_detail_log) start(ComputeDetailsHandler, _VM_DETAIL_ALARM, _c.VM_DETAIL_ALARM_INTERVAL_TIME, ComputeDetailsHandler.get_alarm) start(ComputeDetailsHandler, _VM_DETAIL_STATE, _c.STATE_INTERVAL_TIME, ComputeDetailsHandler.run_vm_state) start(ComputeDetailsHandler, _VM_DETAIL_PIE, _c.VM_DETAIL_PIE_INTERVAL_TIME, ComputeDetailsHandler.run_vm_pie) ComputeDetailsHandler.run(ComputeDetailsHandler)
def sample_output(player, color, seed): def fail(msg): banner('Failed: ' + player.name, '!') sys.exit(msg) try: proc = common.start(player, color, seed) except OSError: fail('Run command failed to start.') moves = [] for _ in range(1000): line = proc.stdout.readline() attempts = common.line_to_moves(line) if attempts is None: fail('Invalid output line: %r' % line) moves.append(attempts[1]) proc.terminate() return moves
def process_shopping_cart(browser): common.start("Process shopping") function_result = True wait10 = WebDriverWait(browser, 10) items_to_buy = ["Yellow Duck", "Green Duck", "Purple Duck"] for i in range(3): browser.get("http://localhost/litecart/en/") wait10.until( EC.presence_of_element_located((By.LINK_TEXT, "Rubber Ducks"))) common.success("Open main page") browser.find_elements_by_link_text("Rubber Ducks")[0].click() common.success("Open 'Rubber Ducks' sales page") time.sleep(5) product_list = browser.find_elements_by_css_selector(".product") for product in product_list: item = product.find_element_by_css_selector(".info") if (items_to_buy[i] in item.get_property("innerText")): common.success("Found product '%s'" % items_to_buy[i]) item.click() wait10.until( EC.presence_of_element_located( (By.CSS_SELECTOR, "div#view-full-page a"))) full_page_link_object = browser.find_elements_by_css_selector( "div#view-full-page a") if (len(full_page_link_object)): common.info( "Popup window with desciption opened, looking for full page.." ) full_page_link_object[0].click() common.success("Product '%s' page opened" % items_to_buy[i]) common.info("Set parameters of the product to buy..") if (browser.find_elements_by_css_selector( "select[name='options[Size]']")): common_litecart.select_from_dropdown_list( browser, { "location": "select[name='options[Size]']", "value": "Small", "description": "Small" }) common_litecart.input_value_to_scrollable_field( browser, { "location": "input[name='quantity']", "value": "1" }) # save the text for the shopping cart dut to it contains price before product adding previous_amount = browser.find_element_by_css_selector( ".quantity").get_property("innerText") previous_summ = browser.find_element_by_css_selector( ".formatted_value").get_property("innerText") common.info( "Shopping cart before operation contains %d products with summ = '%s'" % (int(previous_amount), previous_summ)) browser.find_element_by_css_selector( "button[name='add_cart_product']").click() # wait for the summ for shopping cart to be changed, i.e. previous text to disappear wait10.until_not( EC.text_to_be_present_in_element( (By.CSS_SELECTOR, ".quantity"), previous_amount)) # check the data of the shopping cart operation_amount = browser.find_element_by_css_selector( ".quantity").get_property("innerText") operation_summ = browser.find_element_by_css_selector( ".formatted_value").get_property("innerText") common.info( "Shopping cart after adding contains %d products with summ = '%s'" % (int(operation_amount), operation_summ)) if (int(operation_amount) - 1) == int(previous_amount): common.success("Product '%s' added to the Shopping Cart" % items_to_buy[i]) else: common.fail("Product '%s' added to the Shopping Cart" % items_to_buy[i]) function_result = False break # break from loop [for product in product_list] # process Shopping Cart browser.find_element_by_css_selector("div#cart a").click() wait10.until( EC.presence_of_element_located((By.CSS_SELECTOR, ".table-bordered"))) common.success("Open Shopping Cart checkout page") items_to_remove = browser.find_elements_by_css_selector(".item") while (len(items_to_remove) > 1): # save total payment summ to watch for its change previous_payment_due = str.split( browser.find_element_by_css_selector( ".table-bordered .footer").get_property("innerText"))[2] # get the name of the product to delete from shopping cart item_name = items_to_remove[1].find_element_by_css_selector( "strong").get_property("innerText") common.info("Delete product '%s' from Shopping Cart.." % item_name) common.info("Payment summ before deleting of the product '%s' is: %s" % (item_name, previous_payment_due)) remove_button = items_to_remove[1].find_element_by_css_selector( "button[name=remove_cart_item]") remove_button.click() wait10.until_not( EC.text_to_be_present_in_element( (By.CSS_SELECTOR, ".table-bordered .footer"), previous_payment_due)) if (len( browser.find_elements_by_css_selector( ".table-bordered .footer"))): final_payment_due = str.split( browser.find_element_by_css_selector( ".table-bordered .footer").get_property("innerText"))[2] else: final_payment_due = '$00.00 (There are no items in the cart)' common.info("Payment summ after deleting of the product '%s' is: %s" % (item_name, final_payment_due)) common.success("Delete product '%s' from Shopping Cart" % item_name) items_to_remove = browser.find_elements_by_css_selector(".item") # Done: открыть главную страницу # Done: открыть первый товар из списка (Замечание: сделал по другому, ищу товар с заданным именем, а не какой попался первым) # Done: добавить первый товар в корзину (при этом может случайно добавиться товар, который там уже есть, ничего страшного) # Done: подождать, пока счётчик товаров в корзине обновится (Замечание: отслеживаю сумму для корзины, а не счётчик товаров) # Done: вернуться на главную страницу, повторить предыдущие шаги ещё два раза, чтобы в общей сложности в корзине было 3 единицы товара # Done: открыть корзину (в правом верхнем углу кликнуть по ссылке Checkout) # Done: удалить все товары из корзины один за другим, после каждого удаления подождать, пока внизу обновится таблица common.finish(function_result, "Processing to buy") return function_result
def main(): common.start() common.CONF['data_to_fetch'] = common.ask('Fetch Tweet Data or User Data? 1/Tweet 2/User', answer=list, default='2', options=[1, 2]) request_params = {} if common.CONF['data_to_fetch'] == '2': print("You requested User Data") common.CONF['query'] = common.ask('Search terms? ' + 'Found here: https://dev.twitter.com/rest/public/search', answer=common.str_compat) request_params['q'] = common.CONF['query'] url = 'https://api.twitter.com/1.1/users/search.json?' else: print("You requested Tweet Data") common.CONF['query'] = common.ask('Search terms? ' + 'Found here: https://dev.twitter.com/rest/public/search', answer=common.str_compat) request_params['q'] = common.CONF['query'] result_data_type = common.ask('Type of search results? 1/Popular 2/Recent 3/Mixed', answer=list, default='1', options=[1, 2, 3]) request_params['result_type'] = common.RESULT_MAP[result_data_type] location = common.ask('Location? Eg. 1600 Amphitheatre Parkway, Mountain View, CA', answer=common.str_compat, default=" ") if location.strip(): encode_location = urllib.urlencode({'address': location}) response_location = requests.get('https://maps.googleapis.com/maps/api/geocode/json?' + encode_location) try: location_json = response_location.json() location_data = location_json['results'][0]['geometry']['location'] location_array = [str(value) for value in location_data.itervalues()] if location_array: radius_mi = common.ask('Distance to search within in miles', answer=common.str_compat) location_array.append(radius_mi + u'mi') common.CONF['geocode'] = ",".join(location_array) request_params['geocode'] = common.CONF['geocode'] except: print('Unable to fetch lat and long for location') # date = common.ask('Include tweets before? eg. 2015-07-19', answer=dateObject, default=" ") # if date.strip(): # request_params['until'] = date url = 'https://api.twitter.com/1.1/search/tweets.json?' output_file_name = common.ask('Output file name', answer=common.str_compat, default="output") print('Sending request to API...') json_search_data = get_json_data(url, request_params, common.CONF['consumer_key'], common.CONF['consumer_secret'], common.CONF['api_key'], common.CONF['api_secret']) if json_search_data['nodes']: print('API response received.') with open('json_dump.json', 'w') as outfile: json.dump(json_search_data, outfile) outline = gen_outline.make_outline('json_dump.json', False, 'nodes') print('Generating outline file..') outfile = 'outline.json' with open(outfile, 'w') as f: json.dump(outline, f, indent=2, sort_keys=True) print('Outline file generation done.') with open(outfile) as f: key_map = json.load(f) loader = json2csv.Json2Csv(key_map) outfile = output_file_name + '.csv' if os.path.isfile(outfile): os.remove(outfile) print('Writing to %s' % outfile) with open('json_dump.json') as f: loader.load(f) loader.write_csv(filename=outfile, make_strings=True) print('Output file generated.') else: print('Search yield no results')
import aiostomp from common import MessageRouter, start, get_logger logger = get_logger() class RecipientsRouter(MessageRouter): async def on_message(self, frame: aiostomp.aiostomp.Frame, message: bytes): if message is None: logger.error(f'Empty message: {frame.headers["message-id"]}') else: for channel in self.recipients: self._loop.call_soon(self._client.send, channel, message, {}) if __name__ == '__main__': message_route = RecipientsRouter() start(message_route)
def handle_noargs(self, **options): if common.is_running(): return common.start()
def handle_noargs(self, **options): common.stop() common.start()
def add_new_goods(browser): common.start("Start add new goods") function_result = True common_litecart.do_login_admin(browser) wait = WebDriverWait(browser, 10) # go to the 'Add New Product' page browser.find_element_by_link_text("Catalog").click() wait.until( EC.presence_of_element_located((By.CSS_SELECTOR, "ul.pull-right"))) common.success("Open 'Add New Product' page") browser.find_elements_by_css_selector("ul.pull-right a")[1].click() common.success("Open 'General' tab") # fill the data on the 'General' tab # Status browser.execute_script( "arguments[0].click();", browser.find_element_by_css_selector("input[name=status][value='1']")) #browser.execute_script("document.querySelector(\"input[name=status][value='1']\").click()") common.info("Set %s = '%s': ok" % ("input[name=status]", "Enabled")) # Categories common_litecart.set_checkbox(browser, "input[name='categories[]'][value='0']", True) common_litecart.set_checkbox(browser, "input[name='categories[]'][value='1']", True) # Default category -- skipped # Product Groups common_litecart.set_checkbox( browser, "input[name='product_groups[]'][value='1-1']", False) common_litecart.set_checkbox( browser, "input[name='product_groups[]'][value='1-2']", False) common_litecart.set_checkbox( browser, "input[name='product_groups[]'][value='1-3']", True) # Date Valid From browser.find_element_by_css_selector( "input[name=date_valid_from]").send_keys("01.05.2017") common.info("Set %s = '%s': ok" % ("input[name=date_valid_from]", "01.05.2017")) # Date Valid To browser.find_element_by_css_selector( "input[name=date_valid_to]").send_keys("01.09.2017") common.info("Set %s = '%s': ok" % ("input[name=date_valid_to]", "01.09.2017")) # Code common_litecart.input_value_to_input_field(browser, { "location": "input[name=code]", "value": "fd001" }) # Name common_litecart.input_value_to_input_field(browser, { "location": "input[name='name[en]']", "value": "Fried Duck" }) # SKU common_litecart.input_value_to_input_field(browser, { "location": "input[name=sku]", "value": "FD001" }) # GTIN -- skipped # TARIC -- skipped # Quantity common_litecart.input_value_to_input_field(browser, { "location": "input[name=quantity]", "value": 70 }) common_litecart.select_from_dropdown_list( browser, { "location": "select[name=quantity_unit_id]", "value": "1", "description": "pcs" }) # Weight common_litecart.input_value_to_scrollable_field(browser, { "location": "input[name=weight]", "value": "4.5" }) common_litecart.select_from_dropdown_list( browser, { "location": "select[name=weight_class]", "value": "lb", "description": "lb" }) # Width x Height x Length common_litecart.input_value_to_scrollable_field(browser, { "location": "input[name=dim_x]", "value": "20,0" }) common_litecart.input_value_to_scrollable_field(browser, { "location": "input[name=dim_y]", "value": "30,0" }) common_litecart.input_value_to_scrollable_field(browser, { "location": "input[name=dim_z]", "value": "40,0" }) common_litecart.select_from_dropdown_list(browser, { "location": "select[name=dim_class]", "value": "cm", "description": "cm" }) # Delivery Status common_litecart.select_from_dropdown_list( browser, { "location": "select[name=delivery_status_id]", "value": "1", "description": "3-5 days" }) # Sold Out Status common_litecart.select_from_dropdown_list( browser, { "location": "select[name=sold_out_status_id]", "value": "1", "description": "Sold out" }) # Images common_litecart.input_value_to_input_field( browser, { "location": "input[name='new_images[]']", "value": os.getcwd() + "\\images\\fried_duck.jpg" }) common.info("Set %s = '%s': ok" % ("input[name='new_images[]']", os.getcwd() + "\\images\\fried_duck.jpg")) # go to the 'Information' tab browser.find_element_by_css_selector("a[href='#tab-information']").click() wait.until( EC.presence_of_element_located( (By.CSS_SELECTOR, "input[name='meta_description[en]']"))) common.success("Open 'Information' tab") # fill the data on the 'Information' tab # Manufacturer common_litecart.select_from_dropdown_list( browser, { "location": "select[name=manufacturer_id]", "value": "1", "description": "ACME Corp." }) # Supplier -- skipped # Keywords common_litecart.input_value_to_input_field(browser, { "location": "input[name=keywords]", "value": "fried duck food" }) # Short Description common_litecart.input_value_to_input_field( browser, { "location": "input[name='short_description[en]']", "value": "short description" }) # Description common_litecart.input_value_to_input_field( browser, { "location": "textarea[name='description[en]']", "value": "Full description of the fried duck" }) # Attributes -- skipped # Head Title -- skipped # Meta Description -- skipped # go to the 'Prices' tab browser.find_element_by_css_selector("a[href='#tab-prices']").click() wait.until( EC.presence_of_element_located( (By.CSS_SELECTOR, "input[name='gross_prices[EUR]']"))) common.success("Open 'Prices' tab") # fill the data on the 'Prices' tab # Purchase Price common_litecart.input_value_to_scrollable_field(browser, { "location": "input[name=purchase_price]", "value": "25" }) common_litecart.select_from_dropdown_list( browser, { "location": "select[name=purchase_price_currency_code]", "value": "USD", "description": "US Dollars" }) # Tax Class -- skipped # Price common_litecart.input_value_to_input_field(browser, { "location": "input[name='prices[USD]']", "value": "25" }) # Price Incl. Tax -- skipped # press 'SAVE' button browser.find_element_by_css_selector("button[name=save]").click() # go to the main store page, tab 'NEW' and check if new goods are there browser.get("http://localhost/litecart/") browser.find_element_by_css_selector("a[href='#latest-products']").click() if (browser.find_elements_by_css_selector("a[title='Fried Duck']")): common.success("Found new item in the store") common.finish(function_result, "Add new goods") return function_result
def main(): sizex, sizey = terminalsize.get_terminal_size() init(autoreset=True) color = True numb = 1 common.start() parameters = {'sort': 'stars', 'order': 'desc'} topic = common.ask( 'What topic would you want your project in? Eg. AI, Machine Learning, Image Processing?', answer=common.str_compat, default="Machine Learning") language = common.ask('Any specific language?', answer=common.str_compat, default=" ") if topic: search_term = 'topic:' + topic if language.strip(): search_term += ' language:' + language.strip() parameters['q'] = search_term project_request = requests.get( 'https://api.github.com/search/repositories', params=parameters).json() if 'items' in project_request: git_details = project_request['items'] for project in git_details: if color: prefix = Fore.RED + Style.BRIGHT + '*' * (sizex / 4) else: prefix = Fore.MAGENTA + Style.BRIGHT + '*' * (sizex / 4) wrapper = textwrap.TextWrapper(initial_indent=prefix, width=sizex, subsequent_indent=' ') print wrapper.fill('*' * (sizex / 4)) print('{} . Project Name: {}'.format(str(numb), project['name'])) print('-' * (sizex / 8)) print('Project Description: \n%s' % project['description']) print('-' * (sizex / 8)) print('Project Url: %s' % project['html_url']) color = not color numb += 1 print('\n\n') clone_index = common.ask( 'Select one of the Projects to clone. Enter index. Eg. 1 for first', answer=list, default="1", options=range(1, len(git_details))) clone_path = common.ask('Path to clone? Leave blank if same path.', answer=common.str_compat, default=' ') if subprocess.check_call('git --version', shell=True) != 0: print( 'git not installed installed, please read link ' + 'https://git-scm.com/book/en/v2/Getting-Started-Installing-Git.') exit() else: clone_url = git_details[int(clone_index)]['clone_url'] command = 'git clone ' + clone_url if clone_path.strip(): if os.path.isdir(clone_path): command += ' ' + clone_path print('Cloning..') subprocess.check_call(command, shell=True)
def handle(): start(TenantDetailHandler, _TENANT_DETAIL_CACHE, _c.STATE_INTERVAL_TIME, TenantDetailHandler.run_tenant_hosts)
def handle(): start(NetworkDetailHandler, _NETWORK_DETAIL_CACHE, _c.STATE_INTERVAL_TIME, NetworkDetailHandler.run_net_hosts) start(NetworkDetailHandler, _NETWORK_HOSTS_CACHE, _c.STATE_INTERVAL_TIME, NetworkDetailHandler.run_net_detail)