Best Python code snippet using slash
api_tester.py
Source:api_tester.py
1"""Helper functions for performing API unit tests."""2import csv3import io4import re5from django.contrib.auth import get_user_model6from django.contrib.auth.models import Group7from django.http.response import StreamingHttpResponse8from rest_framework.test import APITestCase9class UserMixin:10 """Mixin to setup a user and login for tests.11 Use parameters to set username, password, email, roles and permissions.12 """13 # User information14 username = 'testuser'15 password = 'mypassword'16 email = 'test@testing.com'17 superuser = False18 is_staff = True19 auto_login = True20 # Set list of roles automatically associated with the user21 roles = []22 def setUp(self):23 """Setup for all tests."""24 super().setUp()25 # Create a user to log in with26 self.user = get_user_model().objects.create_user(27 username=self.username,28 password=self.password,29 email=self.email30 )31 # Create a group for the user32 self.group = Group.objects.create(name='my_test_group')33 self.user.groups.add(self.group)34 if self.superuser:35 self.user.is_superuser = True36 if self.is_staff:37 self.user.is_staff = True38 self.user.save()39 # Assign all roles if set40 if self.roles == 'all':41 self.assignRole(assign_all=True)42 # else filter the roles43 else:44 for role in self.roles:45 self.assignRole(role)46 if self.auto_login:47 self.client.login(username=self.username, password=self.password)48 def assignRole(self, role=None, assign_all: bool = False):49 """Set the user roles for the registered user."""50 # role is of the format 'rule.permission' e.g. 'part.add'51 if not assign_all and role:52 rule, perm = role.split('.')53 for ruleset in self.group.rule_sets.all():54 if assign_all or ruleset.name == rule:55 if assign_all or perm == 'view':56 ruleset.can_view = True57 elif assign_all or perm == 'change':58 ruleset.can_change = True59 elif assign_all or perm == 'delete':60 ruleset.can_delete = True61 elif assign_all or perm == 'add':62 ruleset.can_add = True63 ruleset.save()64 break65class InvenTreeAPITestCase(UserMixin, APITestCase):66 """Base class for running InvenTree API tests."""67 def getActions(self, url):68 """Return a dict of the 'actions' available at a given endpoint.69 Makes use of the HTTP 'OPTIONS' method to request this.70 """71 response = self.client.options(url)72 self.assertEqual(response.status_code, 200)73 actions = response.data.get('actions', None)74 if not actions:75 actions = {}76 return actions77 def get(self, url, data=None, expected_code=200):78 """Issue a GET request."""79 # Set default - see B00680 if data is None:81 data = {}82 response = self.client.get(url, data, format='json')83 if expected_code is not None:84 if response.status_code != expected_code:85 print(f"Unexpected response at '{url}':")86 print(response.data)87 self.assertEqual(response.status_code, expected_code)88 return response89 def post(self, url, data=None, expected_code=None, format='json'):90 """Issue a POST request."""91 response = self.client.post(url, data=data, format=format)92 if data is None:93 data = {}94 if expected_code is not None:95 if response.status_code != expected_code:96 print(f"Unexpected response at '{url}': status code = {response.status_code}")97 if hasattr(response, 'data'):98 print(response.data)99 else:100 print(f"(response object {type(response)} has no 'data' attribute")101 self.assertEqual(response.status_code, expected_code)102 return response103 def delete(self, url, data=None, expected_code=None, format='json'):104 """Issue a DELETE request."""105 if data is None:106 data = {}107 response = self.client.delete(url, data=data, format=format)108 if expected_code is not None:109 self.assertEqual(response.status_code, expected_code)110 return response111 def patch(self, url, data, expected_code=None, format='json'):112 """Issue a PATCH request."""113 response = self.client.patch(url, data=data, format=format)114 if expected_code is not None:115 self.assertEqual(response.status_code, expected_code)116 return response117 def put(self, url, data, expected_code=None, format='json'):118 """Issue a PUT request."""119 response = self.client.put(url, data=data, format=format)120 if expected_code is not None:121 if response.status_code != expected_code:122 print(f"Unexpected response at '{url}':")123 print(response.data)124 self.assertEqual(response.status_code, expected_code)125 return response126 def options(self, url, expected_code=None):127 """Issue an OPTIONS request."""128 response = self.client.options(url, format='json')129 if expected_code is not None:130 self.assertEqual(response.status_code, expected_code)131 return response132 def download_file(self, url, data, expected_code=None, expected_fn=None, decode=True):133 """Download a file from the server, and return an in-memory file."""134 response = self.client.get(url, data=data, format='json')135 if expected_code is not None:136 self.assertEqual(response.status_code, expected_code)137 # Check that the response is of the correct type138 if not isinstance(response, StreamingHttpResponse):139 raise ValueError("Response is not a StreamingHttpResponse object as expected")140 # Extract filename141 disposition = response.headers['Content-Disposition']142 result = re.search(r'attachment; filename="([\w.]+)"', disposition)143 fn = result.groups()[0]144 if expected_fn is not None:145 self.assertEqual(expected_fn, fn)146 if decode:147 # Decode data and return as StringIO file object148 fo = io.StringIO()149 fo.name = fo150 fo.write(response.getvalue().decode('UTF-8'))151 else:152 # Return a a BytesIO file object153 fo = io.BytesIO()154 fo.name = fn155 fo.write(response.getvalue())156 fo.seek(0)157 return fo158 def process_csv(self, fo, delimiter=',', required_cols=None, excluded_cols=None, required_rows=None):159 """Helper function to process and validate a downloaded csv file."""160 # Check that the correct object type has been passed161 self.assertTrue(isinstance(fo, io.StringIO))162 fo.seek(0)163 reader = csv.reader(fo, delimiter=delimiter)164 headers = []165 rows = []166 for idx, row in enumerate(reader):167 if idx == 0:168 headers = row169 else:170 rows.append(row)171 if required_cols is not None:172 for col in required_cols:173 self.assertIn(col, headers)174 if excluded_cols is not None:175 for col in excluded_cols:176 self.assertNotIn(col, headers)177 if required_rows is not None:178 self.assertEqual(len(rows), required_rows)179 # Return the file data as a list of dict items, based on the headers180 data = []181 for row in rows:182 entry = {}183 for idx, col in enumerate(headers):184 entry[col] = row[idx]185 data.append(entry)...
micro.py
Source:micro.py
...22])23def bench_shuffle(num_values):24 """Benchmarks stand-alone shuffle."""25 values = Array(num_values, sint)26 values.assign_all(1)27 config_bits = default_config_shuffle(values)28 default_shuffle(values, config=config_bits, reverse=False)29def bench_sort(num_values):30 """Benchmarks stand-alone sort."""31 keys = Array(num_values, sint)32 keys.assign_all(1)33 values = Array(num_values, sint)34 values.assign_all(1)35 default_sort(keys, values)36def bench_comp_mat(num_values):37 """Benchmarks naively computing O(n**2) comparison matrix."""38 values = Array(num_values, sint)39 values.assign_all(1)40 comp_mat = Matrix(num_values, num_values, sint)41 @for_range(0, num_values)42 def loop(i):43 @for_range(0, num_values - i)44 def inner(j):45 comp_mat[i][i + j] = values[i] <= values[i + j]46def bench_comp_mat_par(num_values):47 """Benchmarks naively computing O(n**2) comparison matrix."""48 values = Array(num_values, sint)49 values.assign_all(1)50 comp_mat = Matrix(num_values, num_values, sint)51 n_parallel = 3252 @for_range_parallel(n_parallel, num_values)53 def loop(i):54 @for_range_parallel(n_parallel, num_values - i)55 def inner(j):56 comp_mat[i][i + j] = values[i] <= values[i + j]57def bench_argmax_over_fracs(num_values):58 """Benchmarks argmax over fractions."""59 fractions = MultiArray(sizes=[num_values, 3], value_type=sint)60 fractions.assign_all(1)61 argmax_over_fracs(fractions)62def bench_lt_threshold(num_values):63 values = Array(num_values, sint)64 values.assign_all(1)65 lt_threshold(values, sint(1))66def bench_is_last_active(num_values, log_depth_version):67 values = Array(num_values, sint)68 values.assign_all(1)69 is_active = Array(num_values, sint)70 values.assign_all(1)71 compute_is_last_active(values, is_active, log_depth_version)72def run_bench():73 args = program.get_args()74 split_args = args[1].split("-")75 operation = split_args[0]76 num_elements = int(split_args[1])77 print "Running %s on %s values." % (operation, num_elements)78 if operation == "shuffle":79 bench_shuffle(num_values=num_elements)80 elif operation == "sort":81 bench_sort(num_values=num_elements)82 elif operation == "comp_mat":83 bench_comp_mat(num_values=num_elements)84 elif operation == "comp_mat_par":...
Main_Logic.py
Source:Main_Logic.py
1import numpy as np2import initialize_select_v2 as m3import encoder_decoder as ed4import crossoverMutation as cm5weapon_names = [] # Weapons list to be encoded 6weapon_instances = [] # Instances of each weapon also used in encoding7threat_list = [] # List of Threat Coefficients for each target8chrom_list = [] # population list9# Just for input 10w_name = "" 11w_inst = ""12# Getting the number of weapons with their names 13while (True):14 w_name, w_inst = input("Enter weapons and number of instances: \n").split(" ")15 if (w_name == "x" or w_inst == "x"): # Stop Delimeter16 break17 weapon_names.append(w_name)18 weapon_instances.append(int(w_inst))19noftargets= int(input("Enter the number of targets : \n")) # N of targets [1-> N]20print ("Enter Threat coefficient for each target : ")21# Get Threat coeff. from input22for k in range(noftargets):23 threat_list.append(int(input()))24#print(threat_coeff)25# Initializing probability matrix 26prob_matrix = []27print ("Enter Success probability matrix : ")28for i in range(0, len(weapon_names)):29 a=[]30 for j in range(0, noftargets):31 a.append(float(input()))32 prob_matrix.append(a)33# Encoding Dictionary 34enc = ed.encode(weapon_names, weapon_instances)35best_chrom = []36best_sol = sum(threat_list)37# Main Loop38for f in range(50):39 m.initialize(chrom_list, 5, sum(weapon_instances))40 #print("hromList: "+str(chrom_list))41 assign_all = m.assigne_all(chrom_list, threat_list)42 43 #print ("Assign All : " + str(assign_all))44 selected_chroms = m.select(assign_all, threat_list, enc, weapon_names, prob_matrix)45 46 #print("Selected : " + str(selected_chroms))47 out = cm.crossover(selected_chroms[0], selected_chroms[1])48 #print("CrossOvered " + str(out))49 out2 = cm.mutation(out, threat_list, enc, weapon_names, prob_matrix)50 #print("Mutated : " + str(out2))51 m.replace(out2, selected_chroms, assign_all, threat_list, enc, weapon_names, prob_matrix)52 for k in out2:53 fit_out = m.compute_fitness(k, threat_list, enc, weapon_names, prob_matrix)54 if (fit_out < best_sol) :55 best_chrom = k56 best_sol = fit_out57 58print("Total Expected Threat : " + str(best_sol))59print(best_chrom)60for h in range(1, noftargets+1):61 print("The waepon assigned to target " + str(h) + " is ")...
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!!