How to use convert_human_readable_values method in autotest

Best Python code snippet using autotest_python Github


Full Screen

...432 On deserializion, if the object to persist already exists, local fields433 will only be updated, if their name is in this set.434 """435 @classmethod436 def convert_human_readable_values(cls, data, to_human_readable=False):437 """\438 Performs conversions on user-supplied field data, to make it439 easier for users to pass human-readable data.440 For all fields that have choice sets, convert their values441 from human-readable strings to enum values, if necessary. This442 allows users to pass strings instead of the corresponding443 integer values.444 For all foreign key fields, call smart_get with the supplied445 data. This allows the user to pass either an ID value or446 the name of the object as a string.447 If to_human_readable=True, perform the inverse - i.e. convert448 numeric values to human readable values.449 This method modifies data in-place.450 """451 field_dict = cls.get_field_dict()452 for field_name in data:453 if field_name not in field_dict or data[field_name] is None:454 continue455 field_obj = field_dict[field_name]456 # convert enum values457 if field_obj.choices:458 for choice_data in field_obj.choices:459 # choice_data is (value, name)460 if to_human_readable:461 from_val, to_val = choice_data462 else:463 to_val, from_val = choice_data464 if from_val == data[field_name]:465 data[field_name] = to_val466 break467 # convert foreign key values468 elif field_obj.rel:469 dest_obj =[field_name],470 valid_only=False)471 if to_human_readable:472 # parameterized_jobs do not have a name_field473 if (field_name != 'parameterized_job' and474 dest_obj.name_field is not None):475 data[field_name] = getattr(dest_obj,476 dest_obj.name_field)477 else:478 data[field_name] = dest_obj479 def _validate_unique(self):480 """\481 Validate that unique fields are unique. Django manipulators do482 this too, but they're a huge pain to use manually. Trust me.483 """484 errors = {}485 cls = type(self)486 field_dict = self.get_field_dict()487 manager = cls.get_valid_manager()488 for field_name, field_obj in field_dict.iteritems():489 if not field_obj.unique:490 continue491 value = getattr(self, field_name)492 if value is None and field_obj.auto_created:493 # don't bother checking autoincrement fields about to be494 # generated495 continue496 existing_objs = manager.filter(**{field_name : value})497 num_existing = existing_objs.count()498 if num_existing == 0:499 continue500 if num_existing == 1 and existing_objs[0].id == continue502 errors[field_name] = (503 'This value must be unique (%s)' % (value))504 return errors505 def _validate(self):506 """507 First coerces all fields on this instance to their proper Python types.508 Then runs validation on every field. Returns a dictionary of509 field_name -> error_list.510 Based on validate() from django.db.models.Model in Django 0.96, which511 was removed in Django 1.0. It should reappear in a later version. See:512 """514 error_dict = {}515 for f in self._meta.fields:516 try:517 python_value = f.to_python(518 getattr(self, f.attname, f.get_default()))519 except django.core.exceptions.ValidationError, e:520 error_dict[] = str(e)521 continue522 if not f.blank and not python_value:523 error_dict[] = 'This field is required.'524 continue525 setattr(self, f.attname, python_value)526 return error_dict527 def do_validate(self):528 errors = self._validate()529 unique_errors = self._validate_unique()530 for field_name, error in unique_errors.iteritems():531 errors.setdefault(field_name, error)532 if errors:533 raise ValidationError(errors)534 # actually (externally) useful methods follow535 @classmethod536 def add_object(cls, data={}, **kwargs):537 """\538 Returns a new object created with the given data (a dictionary539 mapping field names to values). Merges any extra keyword args540 into data.541 """542 data = dict(data)543 data.update(kwargs)544 data = cls.prepare_data_args(data)545 cls.convert_human_readable_values(data)546 data = cls.provide_default_values(data)547 obj = cls(**data)548 obj.do_validate()549 return obj551 def update_object(self, data={}, **kwargs):552 """\553 Updates the object with the given data (a dictionary mapping554 field names to values). Merges any extra keyword args into555 data.556 """557 data = dict(data)558 data.update(kwargs)559 data = self.prepare_data_args(data)560 self.convert_human_readable_values(data)561 for field_name, value in data.iteritems():562 setattr(self, field_name, value)563 self.do_validate()564 # see query_objects()566 _SPECIAL_FILTER_KEYS = ('query_start', 'query_limit', 'sort_by',567 'extra_args', 'extra_where', 'no_distinct')568 @classmethod569 def _extract_special_params(cls, filter_data):570 """571 @returns a tuple of dicts (special_params, regular_filters), where572 special_params contains the parameters we handle specially and573 regular_filters is the remaining data to be handled by Django.574 """575 regular_filters = dict(filter_data)576 special_params = {}577 for key in cls._SPECIAL_FILTER_KEYS:578 if key in regular_filters:579 special_params[key] = regular_filters.pop(key)580 return special_params, regular_filters581 @classmethod582 def apply_presentation(cls, query, filter_data):583 """584 Apply presentation parameters -- sorting and paging -- to the given585 query.586 @returns new query with presentation applied587 """588 special_params, _ = cls._extract_special_params(filter_data)589 sort_by = special_params.get('sort_by', None)590 if sort_by:591 assert isinstance(sort_by, list) or isinstance(sort_by, tuple)592 query = query.extra(order_by=sort_by)593 query_start = special_params.get('query_start', None)594 query_limit = special_params.get('query_limit', None)595 if query_start is not None:596 if query_limit is None:597 raise ValueError('Cannot pass query_start without query_limit')598 # query_limit is passed as a page size599 query_limit += query_start600 return query[query_start:query_limit]601 @classmethod602 def query_objects(cls, filter_data, valid_only=True, initial_query=None,603 apply_presentation=True):604 """\605 Returns a QuerySet object for querying the given model_class606 with the given filter_data. Optional special arguments in607 filter_data include:608 -query_start: index of first return to return609 -query_limit: maximum number of results to return610 -sort_by: list of fields to sort on. prefixing a '-' onto a611 field name changes the sort to descending order.612 -extra_args: keyword args to pass to query.extra() (see Django613 DB layer documentation)614 -extra_where: extra WHERE clause to append615 -no_distinct: if True, a DISTINCT will not be added to the SELECT616 """617 special_params, regular_filters = cls._extract_special_params(618 filter_data)619 if initial_query is None:620 if valid_only:621 initial_query = cls.get_valid_manager()622 else:623 initial_query = cls.objects624 query = initial_query.filter(**regular_filters)625 use_distinct = not special_params.get('no_distinct', False)626 if use_distinct:627 query = query.distinct()628 extra_args = special_params.get('extra_args', {})629 extra_where = special_params.get('extra_where', None)630 if extra_where:631 # escape %'s632 extra_where = cls.objects.escape_user_sql(extra_where)633 extra_args.setdefault('where', []).append(extra_where)634 if extra_args:635 query = query.extra(**extra_args)636 # TODO: Use readonly connection for these queries.637 # This has been disabled, because it's not used anyway, as the638 # configured readonly user is the same as the real user anyway.639 if apply_presentation:640 query = cls.apply_presentation(query, filter_data)641 return query642 @classmethod643 def query_count(cls, filter_data, initial_query=None):644 """\645 Like query_objects, but retreive only the count of results.646 """647 filter_data.pop('query_start', None)648 filter_data.pop('query_limit', None)649 query = cls.query_objects(filter_data, initial_query=initial_query)650 return query.count()651 @classmethod652 def clean_object_dicts(cls, field_dicts):653 """\654 Take a list of dicts corresponding to object (as returned by655 query.values()) and clean the data to be more suitable for656 returning to the user.657 """658 for field_dict in field_dicts:659 cls.clean_foreign_keys(field_dict)660 cls._convert_booleans(field_dict)661 cls.convert_human_readable_values(field_dict,662 to_human_readable=True)663 @classmethod664 def list_objects(cls, filter_data, initial_query=None):665 """\666 Like query_objects, but return a list of dictionaries.667 """668 query = cls.query_objects(filter_data, initial_query=initial_query)669 extra_fields = query.query.extra_select.keys()670 field_dicts = [model_object.get_object_dict(extra_fields=extra_fields)671 for model_object in query]672 return field_dicts673 @classmethod674 def smart_get(cls, id_or_name, valid_only=True):675 """\...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:


You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?