def flake8_scan_file(commit_sha, owner, repo, parent_sha=None): """Runs flake8 scan on all changed files and returns array of warnings""" if parent_sha is None: parent_sha = get_commit_parent(commit_sha, owner, repo) diff_url = GIT_COMPARE_URL.format(base=parent_sha, head=commit_sha, owner=owner, repo=repo, host=host_api) diff_info = get(diff_url, auth=auth).json() diff_content = get(diff_url, auth=auth, headers={ "Accept": "application/vnd.github.v3.diff" }).content.decode('utf8') patch_set = PatchSet(diff_content) comments_per_file = {} for file in diff_info['files']: content = get(file['contents_url'], auth=auth).json() file_content = get(content['download_url']).content with open("flake8_tmp_file.py", 'wb') as test_file: test_file.write(file_content) style_guide = flake8.get_style_guide(ignore=['E24', 'W503']) style_guide.input_file('./flake8_tmp_file.py', ) results = style_guide._application.file_checker_manager.checkers[ 0].results comments_per_line = {} for code, line_n, offset, text, src in results: if changed_in_diff(get_file_by_name(patch_set, file['filename']), line_n): comments = comments_per_line.get(line_n, []) comments.append((file['filename'], line_n, offset, code, text)) comments_per_line[line_n] = comments comments_per_file[file['filename']] = comments_per_line return comments_per_file
def evolucoes_proximas(nome): evolution = [] check_str(nome) nome = nome.lower() request = api.get(f"http://localhost:8000/api/v2/pokemon-species/{nome}") dados = request.json() def next_evol(nome, lista): for dicio in lista: for chave, valor in dicio.items(): if isinstance(valor, dict): if valor['name'] == nome and len(dicio['evolves_to']) != 0: nome = 'flag' next_evol(nome, dicio['evolves_to']) elif valor['name'] == nome and len( dicio['evolves_to']) == 0: return evolution elif nome == 'flag': evolution.append(valor['name']) else: next_evol(nome, dicio['evolves_to']) return evolution if request.status_code == 200: request = api.get(dados['evolution_chain']['url']) dados = request.json() if dados['chain']['species']['name'] == nome: nome = "flag" next_evol(nome, dados['chain']['evolves_to']) else: next_evol(nome, dados['chain']['evolves_to']) else: raise PokemonNaoExisteException return evolution
def travis(self): url_to_send = self.travis_api_url + "/repos/betheluniversity/tinker/branches" r = Requests_API.get(url_to_send, headers=self.travis_get_headers) branches = re.findall("\"branch\":[ ]?\"(.+?)\"", r.content) url_to_send = self.travis_api_url + "/repos/betheluniversity/tinker/builds" r = Requests_API.get(url_to_send, headers=self.travis_get_headers) list_of_builds = r.json()['builds'] list_of_commits = r.json()['commits'] info_packets = [] # Merge the commit information and build information into one packet for render_template simplicity for i in range(0, len(list_of_builds)): b = list_of_builds[i] c = list_of_commits[i] # Make sure that the build and commit info match; in theory this should be a redundant check if b['commit_id'] == c['id']: new_packet = dict() new_packet['build_id'] = b['id'] new_packet['state'] = b['state'] new_packet['commit'] = c['sha'] new_packet['branch'] = c['branch'] new_packet['author'] = c['committer_name'] new_packet['date'] = format_date(c['committed_at']) info_packets.append(new_packet) return render_template("travis.html", list_of_info=info_packets, branches=branches)
def nivel_do_pokemon(nome, experiencia): if nome is None or nome == "": raise PokemonNaoExisteException() resposta1 = api.get(f"{site_pokeapi}/api/v2/pokemon-species/{nome}", timeout = limite) teste = resposta1.json()['growth_rate']['url'] resposta2 = api.get(teste) if experiencia resposta2['formula'] < 0: raise ValueError
def online(): pokeapi = "offline" try: resposta1 = api.get("http://localhost:8000/api/v2/") pokeapi = "zumbi" if resposta1.status_code == 200 and resposta1.json( )['pokemon'] == 'http://localhost:8000/api/v2/pokemon/': pokeapi = "online" except exceptions.ConnectionError as x: pokeapi = "offline" except: pokeapi = "zumbi" treinador = "offline" try: resposta2 = api.get("http://localhost:9000/hello") treinador = "zumbi" if resposta2.status_code == 200 and resposta2.text == 'Pikachu, eu escolho você!': treinador = "online" except exceptions.ConnectionError as x: treinador = "offline" except: treinador = "zumbi" if pokeapi == "online" and treinador == "online": return "online" if pokeapi == "offline" and treinador == "offline": return "offline" return "zumbi"
def test_15b_treinador_nao_existe(self): reset() assert cadastrar_treinador("Kiawe") cadastrar_pokemon("Kiawe", "c", "charizard", 50000) treinador_nao_cadastrado(lambda: excluir_pokemon("Lillie", "c")) resposta = api.get(f"{site_treinador}/treinador") assert resposta.json() == { "Kiawe": { "nome": "Kiawe", "pokemons": { "c": { "apelido": "c", "tipo": "charizard", "experiencia": 50000 } } } } localizar_pokemon("Kiawe", "c") assert api.get(f"{site_treinador}/treinador").json() == { "Kiawe": { "nome": "Kiawe", "pokemons": { "c": { "apelido": "c", "tipo": "charizard", "experiencia": 50000 } } } }
def test_15b_treinador_nao_existe(self): self.reset() self.assertTrue(cadastrar_treinador("Kiawe")) cadastrar_pokemon("Kiawe", "c", "charizard", 50000) treinador_nao_cadastrado(lambda: excluir_pokemon("Lillie", "c"), self) resposta = api.get(f"{site_treinador}/treinador") self.assertEqual( resposta.json(), { "Kiawe": { "nome": "Kiawe", "pokemons": { "c": { "apelido": "c", "tipo": "charizard", "experiencia": 50000 } } } }) localizar_pokemon("Kiawe", "c") self.assertEqual( api.get(f"{site_treinador}/treinador").json(), { "Kiawe": { "nome": "Kiawe", "pokemons": { "c": { "apelido": "c", "tipo": "charizard", "experiencia": 50000 } } } })
def test_14a_ok(self): reset() assert cadastrar_treinador("Ash Ketchum") cadastrar_pokemon("Ash Ketchum", "P", "pikachu", 50000) assert cadastrar_treinador("Prof. Carvalho") assert cadastrar_treinador("James") cadastrar_pokemon("James", "P", "WEEZING", 10000) cadastrar_pokemon("James", "Q", "WeepinBElL", 12000) excluir_treinador("Ash Ketchum") resposta1 = api.get(f"{site_treinador}/treinador") assert resposta1.json() == { "James": { "nome": "James", "pokemons": { "P": { "apelido": "P", "tipo": "weezing", "experiencia": 10000 }, "Q": { "apelido": "Q", "tipo": "weepinbell", "experiencia": 12000 } } }, "Prof. Carvalho": { "nome": "Prof. Carvalho", "pokemons": {} } } treinador_nao_cadastrado(lambda: detalhar_treinador("Ash Ketchum")) treinador_nao_cadastrado(lambda: localizar_pokemon("Ash Ketchum", "P")) excluir_treinador("James") resposta2 = api.get(f"{site_treinador}/treinador") assert resposta2.json() == { "Prof. Carvalho": { "nome": "Prof. Carvalho", "pokemons": {} } } treinador_nao_cadastrado(lambda: detalhar_treinador("James")) treinador_nao_cadastrado(lambda: localizar_pokemon("James", "P")) treinador_nao_cadastrado(lambda: localizar_pokemon("James", "Q")) excluir_treinador("Prof. Carvalho") resposta3 = api.get(f"{site_treinador}/treinador") assert resposta3.json() == {} treinador_nao_cadastrado(lambda: detalhar_treinador("Prof. Carvalho"))
def numero_do_pokemon(nome): if nome is None or nome == "": raise PokemonNaoExisteException() resposta = api.get(f"{site_pokeapi}/api/v2/pokemon/{nome}", timeout = limite) if resposta.status_code == 404: raise PokemonNaoExisteException() if resposta.status_code != 200: raise Exception(f"{resposta.status_code} - {resposta.text}") dic = resposta.json() return dic['id']
def test_12d_treinador_errado(self): self.reset() self.assertTrue(cadastrar_treinador("Serena")) self.assertTrue(cadastrar_treinador("Dawn")) cadastrar_pokemon("Serena", "fen", "fennekin", 5000) pokemon_nao_cadastrado(lambda: localizar_pokemon("Dawn", "fen"), self) resposta = api.get(f"{site_treinador}/treinador") self.assertEqual( resposta.json(), { "Serena": { "nome": "Serena", "pokemons": { "fen": { "apelido": "fen", "tipo": "fennekin", "experiencia": 5000 } } }, "Dawn": { "nome": "Dawn", "pokemons": {} } })
def test_10a_ok(): reset() assert cadastrar_treinador("Ash Ketchum") cadastrar_pokemon("Ash Ketchum", "P", "Pikachu", 50000) assert cadastrar_treinador("Misty") cadastrar_pokemon("Misty", "A", "STARYU", 10000) cadastrar_pokemon("Misty", "B", "sTaRyU", 12000) assert cadastrar_treinador("Brock") cadastrar_pokemon("Brock", "O", "onix", 8000) cadastrar_pokemon("Brock", "G", "Geodude", 20000) assert cadastrar_treinador("James") cadastrar_pokemon("James", "A", "KOFFING", 5000) cadastrar_pokemon("James", "B", "MeowTH", 20000) resposta = api.get(f"{site_treinador}/treinador") assert resposta.json() == { "Ash Ketchum": {"nome": "Ash Ketchum", "pokemons": {"P": {"apelido": "P", "tipo": "pikachu", "experiencia": 50000}}}, "Misty": {"nome": "Misty", "pokemons": {"A": {"apelido": "A", "tipo": "staryu", "experiencia": 10000}, "B": {"apelido": "B", "tipo": "staryu", "experiencia": 12000}}}, "Brock": {"nome": "Brock", "pokemons": {"O": {"apelido": "O", "tipo": "onix", "experiencia": 8000}, "G": {"apelido": "G", "tipo": "geodude", "experiencia": 20000}}}, "James": { "nome": "James", "pokemons": { "A": {"apelido": "A", "tipo": "koffing", "experiencia": 5000}, "B": {"apelido": "B", "tipo": "meowth", "experiencia": 20000} } } }
def treinador_pid(): try: resposta = api.get(f"{ler_configuracao()['treinador-url']}/pid") if resposta.status_code == 200: return int(resposta.text) return -1 except: return -1
def get_book_details(self): url = 'https://www.goodreads.com/book/show/{}.xml?key={}'.format( self.book_name, self.API_KEY) logging.basicConfig(filename='app.log', filemode='a', format='%(asctime)s - %(message)s', level=logging.INFO) try: resp = get(url) book_xml = xml.etree.ElementTree.fromstring(resp.content) for book in book_xml: title = book.findtext('./title') or '' average_rating = book.findtext('./average_rating') or '' ratings_count = book.findtext('./ratings_count') or '' num_pages = book.findtext('./num_pages') or '' image_url = book.findtext('./image_url') or '' publication_year = book.findtext('./publication_year') or '' authors = book.findtext('./authors/author/name') or '' book_dict = { "title": title, "average_rating": average_rating, "ratings_count": ratings_count, "num_pages": num_pages, "image_url": image_url, "publication_year": publication_year, "authors": authors } logging.info('Book: {}, result: {}'.format(self.book_name, book_dict)) return book_dict except Exception as e: raise InvalidGoodreadsURL
def __get_detail_urls__(search_value: str, nbr_pages: int) -> List: """construct each detail url Args: search_value (str): the property we search (apartment or gouse) nbr_pages (int): the number of page for the property searched Returns: list: the list of the urls for the property searched """ detail_urls = [] for i in range(nbr_pages): # get a search page url = f"https://www.immoweb.be/fr/search-results/{search_value}/a-vendre?countries=BE&page={i}&orderBy=relevance" response = get(url) source = None if response.status_code == 200: source = response.json() if source: results = source["results"] for j in range(len(results)): id_ = results[j]["id"] locality = results[j]["property"]["location"]["locality"] postal_code = results[j]["property"]["location"]["postalCode"] #for each result in the search page, get the detail url detail_urls.append( f"https://www.immoweb.be/fr/annonce/{search_value}/a-vendre/{locality}/{postal_code}/{id_}") return detail_urls
def test_09c_repetido(self): self.reset() self.assertTrue(cadastrar_treinador("Jessie")) self.assertFalse(cadastrar_treinador("Jessie")) self.assertEqual(detalhar_treinador("Jessie"), {}) cadastrar_pokemon("Jessie", "A", "ARBOK", 20000) cadastrar_pokemon("Jessie", "B", "wobbuffet", 2000) cadastrar_pokemon("Jessie", "C", "Lickitung", 2500) self.assertFalse(cadastrar_treinador("Jessie")) resposta = api.get(f"{site_treinador}/treinador") self.assertEqual( resposta.json(), { "Jessie": { "nome": "Jessie", "pokemons": { "A": { "apelido": "A", "tipo": "arbok", "experiencia": 20000 }, "B": { "apelido": "B", "tipo": "wobbuffet", "experiencia": 2000 }, "C": { "apelido": "C", "tipo": "lickitung", "experiencia": 2500 } } } })
def nome_do_pokemon(numero): if numero < 1 or numero >= 5000: raise PokemonNaoExisteException() resposta = api.get(f"{site_pokeapi}/api/v2/pokemon/{numero}", timeout = limite) if resposta.status_code == 404: raise PokemonNaoExisteException() if resposta.status_code != 200: raise Exception(f"{resposta.status_code} - {resposta.text}") dic = resposta.json() return dic['name']
def test_09c_repetido(self): reset() assert cadastrar_treinador("Jessie") assert not cadastrar_treinador("Jessie") assert detalhar_treinador("Jessie") == {} cadastrar_pokemon("Jessie", "A", "ARBOK", 20000) cadastrar_pokemon("Jessie", "B", "wobbuffet", 2000) cadastrar_pokemon("Jessie", "C", "Lickitung", 2500) assert not cadastrar_treinador("Jessie") resposta = api.get(f"{site_treinador}/treinador") assert resposta.json() == { "Jessie": { "nome": "Jessie", "pokemons": { "A": { "apelido": "A", "tipo": "arbok", "experiencia": 20000 }, "B": { "apelido": "B", "tipo": "wobbuffet", "experiencia": 2000 }, "C": { "apelido": "C", "tipo": "lickitung", "experiencia": 2500 } } } }
def _get_gcp_auth_token(url: str) -> str: token_request_url = ( "http://metadata/computeMetadata/v1/instance/service-accounts" f"/default/identity?audience={url}") token_response = requests_api.get(token_request_url, headers={"Metadata-Flavor": "Google"}) return token_response.content.decode("utf-8")
def test_10c_pokemon_nao_existe(self): reset() assert cadastrar_treinador("Iris") pokemon_nao_existe( lambda: cadastrar_pokemon("Iris", "D", "homer", 40000)) resposta = api.get(f"{site_treinador}/treinador") assert resposta.json() == {"Iris": {"nome": "Iris", "pokemons": {}}}
def color_of_pokemon(nome): if nome is None or nome == "": raise PokemonNaoExisteException() resposta = api.get(f"{site_pokeapi}/api/v2/pokemon-species/{nome}", timeout = limite) if resposta.status_code == 404: raise PokemonNaoExisteException() if resposta.status_code != 200: raise Exception(f"{resposta.status_code} - {resposta.text}") dic = resposta.json() return dic['color']['name']
def dst_request(path, params=None): """Send get request to Statistics Denmark. Sends a get request to Statistics Denmark. Raises an HTTPError if an error message from Statistics Denmark is present. Otherwise a :class:`Response<requests:requests.Response>` is returned. Args: path (:obj:`str`): The path is added as the path to the base url. params (:obj:`dict`): The params is added as the query to the base url. """ parsed = urlparse('http://api.statbank.dk/v1/') url = urlunparse([ parsed.scheme, parsed.hostname, urljoin(parsed.path, path), parsed.params, parsed.query, parsed.fragment ]) r = get(url, params) if dst_error(r): http_error_msg = u'%s Client Error: %s for url: %s'\ % (r.status_code, r.reason, r.url) http_error_msg += u'\nError message from Statistics Denmark: \n\t> %s'\ % r.json().get('message', 'No error message.') raise HTTPError(http_error_msg, response=r) return r
def nome_do_pokemon(numero): check_int(numero) if numero <= 0 or numero >= 808: raise PokemonNaoExisteException url = 'http://localhost:8000/api/pokemon/' + str(numero) dic_pokemon = api.get(url).json() return dic_pokemon['name']
def test_get_correct_city(self): """ Checks weather for a city and checks that response is describing the city asked and not another one. :return: """ response = get(get_url({'q': f'{CITY},{COUNTRY}', 'appid': f'{self.api_key}'})) res_json = json.loads(response.text) assert CITY == res_json['name']
def nome_do_pokemon(numero): check_int(numero) request = api.get(f"http://localhost:8000/api/v2/pokemon/{numero}") dados = request.json() if request.status_code == 200: return dados['name'] else: raise PokemonNaoExisteException
def get_pokemon(param): result = api.get(site_pokeapi + pokeapi_version + '/pokemon/' + str(param).lower() + '/') if result.status_code == 200: return result.json() else: raise PokemonNaoExisteException()
def numero_do_pokemon(nome): check_str(nome) nome = nome.lower() url = 'http://localhost:8000/api/pokemon/' + str(nome) dic_pokemon = api.get(url).json() if 'detail' in dic_pokemon: raise PokemonNaoExisteException return dic_pokemon['id']
def get_location_by_ip(query: str, timeout: int) -> LocationDict: """Get location information from a guess by IP address.""" try: res = api.get(IPINFO_URL, timeout=timeout).json() except ConnectionError: raise AzelyError("Failed to get location by IP address") return Location(res["city"], *res["loc"].split(",")[::-1]).to_dict()
def test_login(self): url = '%s:%s/recruit.students/login/in' % (self.env['ip'], self.env['port']) params = { 'account':'admin', 'pwd':'660B8D2D5359FF6F94F8D3345698F88C' } response = get(url, params, cookies=self.cookies) assert response.status_code == 200
def test_10e_treinador_errado(): reset() assert cadastrar_treinador("Ash Ketchum") treinador_nao_cadastrado(lambda : cadastrar_pokemon("Gary", "pi", "pikachu", 40000)) resposta = api.get(f"{site_treinador}/treinador") assert resposta.json() == { "Ash Ketchum": {"nome": "Ash Ketchum", "pokemons": {}} }
def numero_do_pokemon(nome): check_str(nome) request = api.get(f"http://localhost:8000/api/v2/pokemon/{nome.lower()}") dados = request.json() if request.status_code == 200: return dados['id'] else: raise PokemonNaoExisteException
def code_500(driver_instance): wait_for_visibility_of_element_id(driver_instance, code_id_500) code500 = driver_instance.find_element_by_id(code_id_500) link500 = code500.get_attribute('href') r = api.get(link500) if r.status_code == 500: return True else: return False
def view_travis_build(self, build_id): url_to_send = self.travis_api_url + "/builds/" + build_id r = Requests_API.get(url_to_send, headers=self.travis_get_headers) condensed_packet = dict() alias = r.json() condensed_packet['commit_id'] = alias['build']['commit_id'] language = alias['build']['config']['language'] condensed_packet['language'] = language + " " + alias['build']['config'].get(language, ["0.0.0"])[0] condensed_packet['duration'] = alias['build']['duration'] condensed_packet['event_type'] = alias['build']['event_type'] condensed_packet['build_id'] = alias['build']['id'] condensed_packet['repository_id'] = alias['build']['repository_id'] condensed_packet['state'] = alias['build']['state'] condensed_packet['author'] = alias['commit']['committer_name'] condensed_packet['branch'] = alias['commit']['branch'] condensed_packet['compare_url'] = alias['commit']['compare_url'] key_order = ['build_id', 'state', 'duration', 'language', 'repository_id', 'commit_id', 'event_type', 'branch', 'compare_url', 'author'] return render_template("travis_build_view.html", order=key_order, packet=condensed_packet)
def get(self, **kwargs): response = api.get(self.url, headers=self.headers, **kwargs) self.handle_errors(response.status_code) return response