Best Python code snippet using autotest_python
paths.py
Source:paths.py
...150 else:151 del obj[index]152 else:153 delattr(obj, self[-1])154def _get_object_dict(obj):155 return {name: getattr(obj, name) for name in dir(obj) if not (name.startswith("__") and name.endswith("__"))156 and not callable(getattr(obj.__class__, name, None))}157def _get_with_key(value, k):158 if isinstance(value, Mapping):159 return value[k]160 return value161def _get_with_index(value, index):162 if isinstance(value, value_sequence_types):163 return value164 if isinstance(value, Sequence):165 return value[index]166 return value167class WildPath(BasePath):168 """169 Implementation of the baseclass that allows for wildcards, multiple keys and slicing.170 """171 sep = "."172 tokens = "!&|*?:"173 algebra = KeyParser()174 _preprocessed = {}175 def __new__(cls, string_or_seq=None, _parse=algebra.parse, _tokens=tokens, preprocessed=_preprocessed):176 self = super(WildPath, cls).__new__(cls, string_or_seq)177 for wild_key in self:178 # if wild_cards or slicing are used, multiple results are returned and the boolean logic is applied179 if wild_key not in preprocessed and any(t in wild_key for t in _tokens):180 preprocessed[wild_key] = _parse(wild_key, simplify=True)181 self.depth = self._get_depth()182 return self183 def _get_depth(self):184 prep = self._preprocessed185 return len([k for k in self if k in prep]) - 1186 def call_in(self, obj, *args, **kwargs):187 results = self.get_in(obj)188 for path, instance_method in Path.items(results, _call=True):189 path.set_in(results, instance_method(*args, **kwargs))190 return results191 def get_in(self, obj, default=_marker, flat=False):192 result = super(WildPath, self).get_in(obj, default)193 if flat:194 return flatten(result, depth=self.depth)195 return result196 def _get_in(self, obj, default=_marker, get_object_dict=_get_object_dict,197 preprocessed=_preprocessed):198 """returns item(s) at wildpath 'self' from the 'obj'"""199 if not len(self):200 return obj201 key = self[0]202 if key in preprocessed: # this is not a single key or index203 if len(self) == 1:204 if isinstance(obj, Mapping):205 return {k: obj[k] for k in preprocessed[key](*obj)}206 elif isinstance(obj, Sequence):207 try:208 indices = preprocessed[key](*range(len(obj)))209 except ValueError:210 obj_dict = get_object_dict(obj)211 return {k: obj_dict[k] for k in preprocessed[key](*obj_dict)}212 else:213 return [obj[i] for i in indices]214 else:215 obj_dict = get_object_dict(obj)216 return {k: obj_dict[k] for k in preprocessed[key](*obj_dict)}217 else:218 if isinstance(obj, Mapping):219 return {k: self[1:]._get_in(obj[k], default) for k in preprocessed[key](*obj)}220 elif isinstance(obj, Sequence):221 try:222 indices = preprocessed[key](*range(len(obj)))223 except ValueError:224 obj_dict = get_object_dict(obj)225 return {k: self[1:]._get_in(obj_dict[k], default) for k in preprocessed[key](*obj_dict)}226 else:227 return [self[1:].get_in(obj[i], default) for i in indices]228 else:229 obj_dict = get_object_dict(obj)230 return {k: self[1:]._get_in(obj_dict[k], default) for k in preprocessed[key](*obj_dict)}231 else:232 try:233 if len(self) == 1:234 if isinstance(obj, Mapping):235 return obj[key]236 elif isinstance(obj, Sequence):237 try:238 index = int(key)239 except ValueError:240 return getattr(obj, key)241 else:242 return obj[index]243 else:244 return getattr(obj, key)245 else:246 if isinstance(obj, Mapping):247 return self[1:]._get_in(obj[key], default)248 elif isinstance(obj, Sequence):249 try:250 index = int(key)251 except ValueError:252 return self[1:]._get_in(getattr(obj, key), default)253 else:254 return self[1:]._get_in(obj[index], default)255 else:256 return self[1:]._get_in(getattr(obj, key), default)257 except (KeyError, IndexError, AttributeError):258 if default is _marker:259 raise260 return default261 def _set_in(self, obj, value, get_object_dict=_get_object_dict,262 get_with_key=_get_with_key, # speed up function access263 get_with_index=_get_with_index,264 preprocessed=_preprocessed):265 """sets item(s) at wildpath 'self' of 'obj' to 'value'"""266 key = self[0]267 if key in preprocessed:268 if len(self) == 1:269 if isinstance(obj, MutableMapping):270 for k in preprocessed[key](*obj):271 obj[k] = get_with_key(value, k)272 elif isinstance(obj, MutableSequence):273 try:274 indices = preprocessed[key](*range(len(obj)))275 except ValueError:276 for k in preprocessed[key](*get_object_dict(obj)):277 setattr(obj, k, get_with_key(value, k))278 else:279 for i, j in enumerate(indices):280 obj[j] = get_with_index(value, i)281 else:282 for k in preprocessed[key](*get_object_dict(obj)):283 setattr(obj, k, get_with_key(value, k))284 else:285 if isinstance(obj, MutableMapping):286 for k in preprocessed[key](*obj):287 self[1:]._set_in(obj[k], get_with_key(value, k))288 elif isinstance(obj, MutableSequence):289 try:290 indices = preprocessed[key](*range(len(obj)))291 except ValueError:292 obj_dict = get_object_dict(obj)293 for k in preprocessed[key](*obj_dict):294 self[1:]._set_in(obj_dict[k], _get_with_key(value, k))295 else:296 for i, j in enumerate(indices):297 self[1:]._set_in(obj[j], _get_with_index(value, i))298 else:299 obj_dict = get_object_dict(obj)300 for k in preprocessed[key](*obj_dict):301 self[1:]._set_in(obj_dict[k], _get_with_key(value, k))302 else:303 if len(self) == 1:304 if isinstance(obj, MutableMapping):305 obj[key] = value306 elif isinstance(obj, MutableSequence):307 try:308 index = int(key)309 except ValueError:310 setattr(obj, key, value)311 else:312 obj[index] = value313 else:314 setattr(obj, key, value)315 else:316 if isinstance(obj, MutableMapping):317 self[1:]._set_in(obj[key], _get_with_key(value, key))318 elif isinstance(obj, MutableSequence):319 try:320 index = int(key)321 except ValueError:322 self[1:]._set_in(getattr(obj, key), _get_with_key(value, key))323 else:324 self[1:]._set_in(obj[index], _get_with_index(value, index))325 else:326 self[1:]._set_in(getattr(obj, key), _get_with_key(value, key))327 def _del_in(self, obj, get_object_dict=_get_object_dict,328 preprocessed=_preprocessed):329 """deletes item(s) at wildpath 'self' from the 'obj'"""330 key = self[0]331 if key in preprocessed:332 if len(self) == 1:333 if isinstance(obj, MutableMapping):334 for k in preprocessed[key](*obj):335 del obj[k]336 elif isinstance(obj, MutableSequence):337 try:338 indices = preprocessed[key](*range(len(obj)))339 except ValueError:340 for k in preprocessed[key](*get_object_dict(obj)):341 delattr(obj, k)342 else:343 for i in indices:344 obj[i] = _marker # marked for deletion345 obj[:] = [v for v in obj if v is not _marker]346 else:347 for k in preprocessed[key](*get_object_dict(obj)):348 delattr(obj, k)349 else:350 if isinstance(obj, MutableMapping):351 for k in preprocessed[key](*obj):352 self[1:]._del_in(obj[k])353 elif isinstance(obj, MutableSequence):354 try:355 indices = preprocessed[key](*range(len(obj)))356 except ValueError:357 obj_dict = get_object_dict(obj)358 for k in preprocessed[key](*obj_dict):359 self[1:]._del_in(obj_dict[k])360 else:361 for i in indices:362 self[1:]._del_in(obj[i])363 else:364 obj_dict = get_object_dict(obj)365 for k in preprocessed[key](*obj_dict):366 self[1:]._del_in(obj_dict[k])367 else:368 if len(self) == 1:369 if isinstance(obj, MutableMapping):370 del obj[key]371 elif isinstance(obj, MutableSequence):372 try:373 index = int(key)374 except ValueError:375 delattr(obj, key)376 else:377 del obj[index]378 else:...
views.py
Source:views.py
...20def apiOverview(request):21 data = {"error": "not a valid endpoint", "create user": "/api/create-user/",22 "developer list": ["/api/developer", ["GET", "POST"]], "developer detail": ["/api/developer-detail", ["GET", "PUT", "DELETE"]]}23 return Response(data)24def get_object_dict(result):25 result['designation'] = Designation.objects.get(26 id=result['designation']).name27 result['employment_type'] = EmploymentType.objects.get(28 id=result['employment_type']).name29 tech_stack_result = []30 for value in result['tech_stack']:31 tech_stack_result.append(TechStack.objects.get(32 id=value).name)33 result['tech_stack'] = tech_stack_result34 user_result = model_to_dict(35 User.objects.get(id=result['user']))36 user_result.pop('id')37 result['user'] = user_result38 return result39class UserAPIView(APIView):40 serializer_class = UserSerializer41 def post(self, request, *args, **kwargs):42 usr_data = request.data43 new_usr = User.objects.create(44 name=usr_data['name'], age=usr_data['age'], sex=usr_data['sex'], email=usr_data['email'])45 new_usr.save()46 serializer = UserSerializer(new_usr)47 return Response(serializer.data)48class DeveloperList(APIView):49 serializer_class = DeveloperCreateSerializer50 def get(self, request, format=None):51 developer = Developer.objects.all()52 serializer = DeveloperSerializer(developer, many=True)53 return Response(serializer.data)54 def post(self, request, format=None):55 serializer = DeveloperCreateSerializer(data=request.data)56 if serializer.is_valid():57 serializer.save()58 result = get_object_dict(serializer.data)59 create_offer_letter(result['user']['name'], result['location'],60 result['designation'], result['start_date'], result['annual_ctc'])61 return Response(result, status=status.HTTP_201_CREATED)62 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)63class DeveloperDetail(APIView):64 serializer_class = DeveloperCreateSerializer65 def get_object(self, pk):66 try:67 return Developer.objects.get(pk=pk)68 except Developer.DoesNotExist:69 raise Http40470 def get(self, request, pk, format=None):71 developer = self.get_object(pk)72 serializer = DeveloperSerializer(developer)73 return Response(serializer.data)74 def put(self, request, pk, format=None):75 developer = self.get_object(pk)76 serializer = DeveloperCreateSerializer(developer, data=request.data)77 if serializer.is_valid():78 serializer.save()79 result = get_object_dict(serializer.data)80 print(result['user']['name'])81 create_offer_letter(result['user']['name'], result['location'],82 result['designation'], result['start_date'], result['annual_ctc'])83 return Response(result)84 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)85 def delete(self, request, pk, format=None):86 developer = self.get_object(pk)87 developer.delete()...
test_fixtures_start.py
Source:test_fixtures_start.py
...3@pytest.fixture(scope="session")4def get_path():5 return 'tests/resources/cities/clean_map.csv'6@pytest.fixture(scope="function")7def get_object_dict(get_path):8 data = data_processor.csv_reader(get_path)9 data_to_transform = map_population_update.MapData(data, False)10 population_dict = {11 'Andorra': 77142,12 'Argentina': 44780677,13 'Cape Verde': 546388,14 'Germany': 83670653,15 'Greece': 10473455,16 'India': 1366417754,17 'Japan': 128860301,18 'Morocco': 36471769,19 'Senegal': 16296364,20 'United States': 32906491721 }...
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!!