Best Python code snippet using localstack_python
1.py
Source:1.py
...16 option_number = int(input_string)17 return 1 <= option_number <= number_of_options18 except ValueError as e:19 return False20def get_response_payload(url, params={}):21 response = requests.get(url, params)22 if response.status_code == 200:23 return loads(response.text)24 else:25 return26def user_menu(user_id):27 while True:28 selected_option = get_option("ÐÑбеÑиÑе дейÑÑвие:",29 ("1. ÐÑоÑмоÑÑеÑÑ Ð¿ÑоÑилÑ", "2. ÐÑоÑмоÑÑеÑÑ Ð¿Ð¾ÑÑÑ", "3. СпиÑок задаÑ",30 "4. СÑÑлка на ÑлÑÑайнÑÑ ÐºÐ°ÑÑинкÑ", "5. Ðазад"))31 if selected_option == 1:32 show_user_info(user_id)33 elif selected_option == 2:34 user_posts_menu(user_id)35 elif selected_option == 3:36 user_todos_menu(user_id)37 elif selected_option == 4:38 show_random_user_image(user_id)39 elif selected_option == 5:40 return41def user_posts_menu(user_id):42 while True:43 selected_option = get_option("ÐÑбеÑиÑе дейÑÑвие:",44 ("1. ÐÑоÑмоÑÑеÑÑ ÑпиÑок поÑÑов полÑзоваÑелÑ", "2. ÐÑоÑмоÑÑеÑÑ ÐºÐ¾Ð½ÐºÑеÑнÑй поÑÑ Ð¿Ð¾Ð»ÑзоваÑелÑ",45 "3. Ðазад"))46 if selected_option == 1:47 show_user_posts(user_id)48 elif selected_option == 2:49 show_user_post(user_id)50 elif selected_option == 3:51 return52def user_todos_menu(user_id):53 while True:54 selected_option = get_option("ÐÑбеÑиÑе дейÑÑвие:",55 ("1. ÐÑоÑмоÑÑеÑÑ Ð½ÐµÐ²ÑолненнÑе задаÑи", "2. ÐÑоÑмоÑÑеÑÑ Ð²ÑолненнÑе задаÑи",56 "3. Ðазад"))57 if selected_option == 1:58 show_todos(user_id, False, "ÐевÑполненнÑе задаÑи")59 elif selected_option == 2:60 show_todos(user_id, True, "ÐÑполненнÑе задаÑи")61 elif selected_option == 3:62 return63def show_todos(user_id, status, title):64 print()65 print(title)66 status = "true" if status else "false"67 todos = get_response_payload(API_BASE_URL + f"/users/{user_id}/todos", {"completed": status})68 for todo in todos:69 print(f"ID: {todo['id']}".ljust(10) + f"Ðазвание: {todo['title']}")70 print()71def show_user_info(user_id):72 user_info = get_response_payload(API_BASE_URL + f"/users/{user_id}")73 print()74 print("ÐнÑоÑмаÑÐ¸Ñ Ð¾ полÑзоваÑеле: ")75 print("ID: ".ljust(20), user_info["id"])76 print("ÐмÑ: ".ljust(20), user_info["name"])77 print("ÐÐ¼Ñ Ð¿Ð¾Ð»ÑзоваÑелÑ: ".ljust(20), user_info["username"])78 print("E-mail: ".ljust(20), user_info["email"])79 print("ТелеÑон: ".ljust(20), user_info["phone"])80 print("СайÑ: ".ljust(20), user_info["website"], end='\n\n')81 user_address = user_info["address"]82 print("ÐдÑÐµÑ Ð¿Ð¾Ð»ÑзоваÑелÑ: ")83 print("УлиÑа: ".ljust(20), user_address["street"])84 print("Ðом: ".ljust(20), user_address["suite"])85 print("ÐоÑод: ".ljust(20), user_address["city"])86 print("ÐоÑÑовÑй индекÑ: ".ljust(20), user_address["zipcode"])87 print("ÐооÑдинаÑÑ: ".ljust(20), user_address["geo"]["lat"] + "; " + user_address["geo"]["lng"], end='\n\n')88 user_company = user_info["company"]89 print("ÐнÑоÑмаÑÐ¸Ñ Ð¾ компании полÑзоваÑелÑ: ")90 print("Ðазвание: ".ljust(20), user_company["name"])91 print("Ðевиз: ".ljust(20), user_company["catchPhrase"])92 print("ÐпиÑание: ".ljust(20), user_company["bs"], end='\n\n')93def show_user_posts(user_id):94 posts = get_response_payload(API_BASE_URL + f"/users/{user_id}/posts")95 posts_info = [get_post_short_info(posts, i) for i in range(len(posts))]96 for post_info in posts_info:97 print(post_info)98def show_user_post(user_id):99 while True:100 post_id = input("ÐведиÑе ID поÑÑа, коÑоÑÑй Ñ
оÑиÑе пÑоÑмоÑÑеÑÑ:\n")101 if not validate_positive_int(post_id):102 selected_option = get_option("ÐÑ Ð²Ð²Ð²ÐµÐ»Ð¸ недопÑÑÑимÑй ID поÑÑа. ÐопÑобоваÑÑ ÐµÑе Ñаз?")103 if selected_option == 1:104 continue105 elif selected_option == 2:106 print("ÐÑÑ
од")107 break108 if not validate_post_belongs_to_user(post_id, user_id):109 selected_option = get_option("ÐаннÑй поÑÑ Ð½Ðµ пÑÐ¸Ð½Ð°Ð´Ð»ÐµÐ¶Ð¸Ñ Ð²ÑбÑÐ°Ð½Ð½Ð¾Ð¼Ñ Ð¿Ð¾Ð»ÑзоваÑелÑ. ÐопÑобоваÑÑ ÐµÑе Ñаз?")110 if selected_option == 1:111 continue112 elif selected_option == 2:113 print("ÐÑÑ
од")114 break115 break116 post = get_response_payload(API_BASE_URL + f"/posts/{post_id}")117 if post is not None:118 print()119 print(f"ID: {post['id']}")120 print(f"Ðаголовок: {post['title']}")121 comments = get_response_payload(API_BASE_URL + f"/posts/{post_id}/comments")122 print(f"ÐолиÑеÑÑво комменÑаÑиев: {len(comments)}")123 print("ID комменÑаÑиев: ", *list(map(lambda comment: comment['id'], comments)))124 print("ТекÑÑ:")125 print(post["body"])126 print()127def show_random_user_image(user_id):128 albums = get_response_payload(API_BASE_URL + f"/users/{user_id}/albums")129 photos = get_response_payload(API_BASE_URL + f"/albums/{choice(albums)['id']}/photos")130 print(f"СÑÑлка на ÑлÑÑайнÑÑ ÐºÐ°ÑÑÐ¸Ð½ÐºÑ Ð¿Ð¾Ð»ÑзоваÑелÑ: {choice(photos)['url']}")131def get_user_short_info(users, index):132 return f"{index + 1}.".ljust(4) + f"ID: {users[index]['id']}".ljust(10) + \133 f"ÐмÑ: {users[index]['name']}".ljust(30) + f"ÐÐ¼Ñ Ð¿Ð¾Ð»ÑзоваÑелÑ: {users[index]['username']}"134def get_post_short_info(post, index):135 return f"{index + 1}.".ljust(4) + f"ID: {post[index]['id']}".ljust(10) + \136 f"Ðаголовок: {post[index]['title']}"137def validate_positive_int(string):138 try:139 return int(string) > 0140 except ValueError as e:141 return False142def validate_post_belongs_to_user(post_id, user_id):143 post = get_response_payload(API_BASE_URL + f"/posts/{post_id}")144 return post is not None and post["userId"] == user_id145def main():146 while True:147 users = get_response_payload(API_BASE_URL + "/users")148 options_list = [get_user_short_info(users, i) for i in range(len(users))]149 options_list.append(f"{len(users) + 1}. ÐÑÑ
од")150 options = tuple(options_list)151 selected_option = get_option("ÐÑбеÑиÑе полÑзоваÑÐµÐ»Ñ Ð¸Ð»Ð¸ вÑйдиÑе из пÑогÑаммÑ: ", options)152 if selected_option <= len(users):153 user_id = users[selected_option - 1]["id"]154 user_menu(user_id)155 else:156 return...
test_flaskr.py
Source:test_flaskr.py
...26 """27 @TODO:28 Write at least one test for each test for successful operation and for expected errors.29 """30 def get_response_payload(self, url):31 """Get HTTP response and json payload"""32 response = self.client().get(url)33 payload = json.loads(response.data)34 return response, payload35 def post_payload(self, url, post):36 """Post payload"""37 response = self.client().post(url, json=post)38 payload = json.loads(response.data)39 return response, payload40 def assert_status(self, response, payload, status_code, success):41 """Helper function for asserting status of http request"""42 self.assertEqual(response.status_code, status_code)43 self.assertEqual(payload['success'], success)44 def test_categories(self):45 """Test categories"""46 response, payload = self.get_response_payload('/categories')47 self.assert_status(response, payload, 200, True)48 self.assertTrue(len(payload['categories']) > 0)49 def test_questions(self):50 """Test questions"""51 response, payload = self.get_response_payload('/questions?page=1')52 self.assert_status(response, payload, 200, True)53 self.assertTrue(len(payload['categories']) > 0)54 self.assertTrue(len(payload['questions']) > 0)55 self.assertTrue(payload['totalQuestions'] > 0)56 def test_questions_in_categories(self):57 """Test questions in categories"""58 response, payload = self.get_response_payload('/categories/1/questions')59 self.assert_status(response, payload, 200, True)60 def test_post_question(self):61 """Test posting questions"""62 pre_test = Question.query.all()63 test_question = {64 "question": "What is the best telescope",65 "answer": "James Webb",66 "category": 1,67 "difficulty": 268 }69 response, payload = self.post_payload('/questions', post=test_question)70 TriviaTestCase.question_added = payload['id']71 post_test = Question.query.all()72 self.assert_status(response, payload, 200, True)73 self.assertTrue(payload['id'])74 self.assertTrue(len(post_test) - len(pre_test) == 1)75 def test_search_questions(self):76 """Test search question endpoint"""77 search = {78 "searchTerm": "telescope"79 }80 response, payload = self.post_payload('/questions/search', post=search)81 self.assert_status(response, payload, 200, True)82 self.assertTrue(len(payload['questions']) > 0)83 self.assertTrue(payload['totalQuestions'] > 0)84 def test_z_delete_question(self):85 """Test delete questions"""86 response = self.client().delete(f'/questions/{TriviaTestCase.question_added}')87 payload = json.loads(response.data)88 self.assert_status(response, payload, 200, True)89 self.assertEqual(payload['deleted'], TriviaTestCase.question_added)90 def test_play(self):91 """Test play endpoint"""92 play = {93 "quiz_category": {94 "id": 195 },96 "previous_questions": [20, 21, 24, 25]97 }98 response, payload = self.post_payload('/quizzes', play)99 self.assert_status(response, payload, 200, True)100 # self.assertEqual(payload['question']['id'], 22)101 def test_404_question_pagination(self):102 """Check question pagination returns 404 if no questions on page"""103 response, payload = self.get_response_payload('/questions?page=1000')104 self.assert_status(response, payload, 404, False)105 def test_404_missing_category(self):106 """Check categories returns 404 for non existent category"""107 response, payload = self.get_response_payload('/categories/10/questions')108 self.assert_status(response, payload, 404, False)109 def test_404_no_search_results(self):110 """Return 404 if no results found in search"""111 search = {112 "searchTerm": "gravy"113 }114 response, payload = self.post_payload('/questions/search', search)115 self.assert_status(response, payload, 404, False)116 def test_422_post_malformed_question(self):117 """Return 422 if new question malformed"""118 question = {119 "question": "What is the distance between earth and the moon?",120 "answer": "A fair distance",121 "category": 1...
harness_api.py
Source:harness_api.py
...64def register(url, timeout, alive_time):65 return run_host_tool("./host_tool -s " + url + " -t " + str(timeout) + " -a " + str(alive_time), output)66def deregister(url):67 return run_host_tool("./host_tool -d " + url, output)68def get_response_payload():69 line_num = 070 ft = open(output, 'r')71 lines = ft.readlines()72 for line in reversed(lines):73 if (line[0:16] == "response status "):74 break75 line_num = line_num + 176 payload_lines = lines[-(line_num):-1]77 ft.close()78 return payload_lines79def check_query_apps(expected_app_list):80 if (check_is_timeout() == True):81 return False82 json_lines = get_response_payload()83 json_str = " ".join(json_lines)84 json_dict = json.loads(json_str)85 app_list = []86 for key, value in json_dict.items():87 if key[0:6] == "applet":88 app_list.append(value)89 if (sorted(app_list) == sorted(expected_app_list)):90 return True91 else:92 return False93def check_response_payload(expected_payload):94 if (check_is_timeout() == True):95 return False96 json_lines = get_response_payload()97 json_str = " ".join(json_lines)98 if (json_str.strip() != ""):99 json_dict = json.loads(json_str)100 else:101 json_dict = {}102 if (json_dict == expected_payload):103 return True104 else:105 return False106def check_get_event():107 line_num = 0108 ft = open(output, 'r')109 lines = ft.readlines()110 for line in reversed(lines):...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!