Best Python code snippet using autotest_python
model_logic.py
Source:model_logic.py
...432 """433 errors = {}434 cls = type(self)435 field_dict = self.get_field_dict()436 manager = cls.get_valid_manager()437 for field_name, field_obj in field_dict.iteritems():438 if not field_obj.unique:439 continue440 value = getattr(self, field_name)441 existing_objs = manager.filter(**{field_name : value})442 num_existing = existing_objs.count()443 if num_existing == 0:444 continue445 if num_existing == 1 and existing_objs[0].id == self.id:446 continue447 errors[field_name] = (448 'This value must be unique (%s)' % (value))449 return errors450 def do_validate(self):451 errors = self.validate()452 unique_errors = self.validate_unique()453 for field_name, error in unique_errors.iteritems():454 errors.setdefault(field_name, error)455 if errors:456 raise ValidationError(errors)457 # actually (externally) useful methods follow458 @classmethod459 def add_object(cls, data={}, **kwargs):460 """\461 Returns a new object created with the given data (a dictionary462 mapping field names to values). Merges any extra keyword args463 into data.464 """465 data = cls.prepare_data_args(data, kwargs)466 data = cls.provide_default_values(data)467 obj = cls(**data)468 obj.do_validate()469 obj.save()470 return obj471 def update_object(self, data={}, **kwargs):472 """\473 Updates the object with the given data (a dictionary mapping474 field names to values). Merges any extra keyword args into475 data.476 """477 data = self.prepare_data_args(data, kwargs)478 for field_name, value in data.iteritems():479 setattr(self, field_name, value)480 self.do_validate()481 self.save()482 @classmethod483 def query_objects(cls, filter_data, valid_only=True, initial_query=None):484 """\485 Returns a QuerySet object for querying the given model_class486 with the given filter_data. Optional special arguments in487 filter_data include:488 -query_start: index of first return to return489 -query_limit: maximum number of results to return490 -sort_by: list of fields to sort on. prefixing a '-' onto a491 field name changes the sort to descending order.492 -extra_args: keyword args to pass to query.extra() (see Django493 DB layer documentation)494 -extra_where: extra WHERE clause to append495 """496 filter_data = dict(filter_data) # copy so we don't mutate the original497 query_start = filter_data.pop('query_start', None)498 query_limit = filter_data.pop('query_limit', None)499 if query_start and not query_limit:500 raise ValueError('Cannot pass query_start without '501 'query_limit')502 sort_by = filter_data.pop('sort_by', [])503 extra_args = filter_data.pop('extra_args', {})504 extra_where = filter_data.pop('extra_where', None)505 if extra_where:506 # escape %'s507 extra_where = cls.objects.escape_user_sql(extra_where)508 extra_args.setdefault('where', []).append(extra_where)509 use_distinct = not filter_data.pop('no_distinct', False)510 if initial_query is None:511 if valid_only:512 initial_query = cls.get_valid_manager()513 else:514 initial_query = cls.objects515 query = initial_query.filter(**filter_data)516 if use_distinct:517 query = query.distinct()518 # other arguments519 if extra_args:520 query = query.extra(**extra_args)521 query = query._clone(klass=ReadonlyQuerySet)522 # sorting + paging523 assert isinstance(sort_by, list) or isinstance(sort_by, tuple)524 query = query.order_by(*sort_by)525 if query_start is not None and query_limit is not None:526 query_limit += query_start527 return query[query_start:query_limit]528 @classmethod529 def query_count(cls, filter_data, initial_query=None):530 """\531 Like query_objects, but retreive only the count of results.532 """533 filter_data.pop('query_start', None)534 filter_data.pop('query_limit', None)535 query = cls.query_objects(filter_data, initial_query=initial_query)536 return query.count()537 @classmethod538 def clean_object_dicts(cls, field_dicts):539 """\540 Take a list of dicts corresponding to object (as returned by541 query.values()) and clean the data to be more suitable for542 returning to the user.543 """544 for field_dict in field_dicts:545 cls.clean_foreign_keys(field_dict)546 cls._convert_booleans(field_dict)547 cls.convert_human_readable_values(field_dict,548 to_human_readable=True)549 @classmethod550 def list_objects(cls, filter_data, initial_query=None, fields=None):551 """\552 Like query_objects, but return a list of dictionaries.553 """554 query = cls.query_objects(filter_data, initial_query=initial_query)555 field_dicts = [model_object.get_object_dict(fields)556 for model_object in query]557 return field_dicts558 @classmethod559 def smart_get(cls, id_or_name, valid_only=True):560 """\561 smart_get(integer) -> get object by ID562 smart_get(string) -> get object by name_field563 """564 if valid_only:565 manager = cls.get_valid_manager()566 else:567 manager = cls.objects568 if isinstance(id_or_name, (int, long)):569 return manager.get(pk=id_or_name)570 if isinstance(id_or_name, basestring):571 return manager.get(**{cls.name_field : id_or_name})572 raise ValueError(573 'Invalid positional argument: %s (%s)' % (id_or_name,574 type(id_or_name)))575 @classmethod576 def smart_get_bulk(cls, id_or_name_list):577 invalid_inputs = []578 result_objects = []579 for id_or_name in id_or_name_list:580 try:581 result_objects.append(cls.smart_get(id_or_name))582 except cls.DoesNotExist:583 invalid_inputs.append(id_or_name)584 if invalid_inputs:585 raise cls.DoesNotExist('The following %ss do not exist: %s'586 % (cls.__name__.lower(),587 ', '.join(invalid_inputs)))588 return result_objects589 def get_object_dict(self, fields=None):590 """\591 Return a dictionary mapping fields to this object's values.592 """593 if fields is None:594 fields = self.get_field_dict().iterkeys()595 object_dict = dict((field_name, getattr(self, field_name))596 for field_name in fields)597 self.clean_object_dicts([object_dict])598 self._postprocess_object_dict(object_dict)599 return object_dict600 def _postprocess_object_dict(self, object_dict):601 """For subclasses to override."""602 pass603 @classmethod604 def get_valid_manager(cls):605 return cls.objects606 def _record_attributes(self, attributes):607 """608 See on_attribute_changed.609 """610 assert not isinstance(attributes, basestring)611 self._recorded_attributes = dict((attribute, getattr(self, attribute))612 for attribute in attributes)613 def _check_for_updated_attributes(self):614 """615 See on_attribute_changed.616 """617 for attribute, original_value in self._recorded_attributes.iteritems():618 new_value = getattr(self, attribute)619 if original_value != new_value:620 self.on_attribute_changed(attribute, original_value)621 self._record_attributes(self._recorded_attributes.keys())622 def on_attribute_changed(self, attribute, old_value):623 """624 Called whenever an attribute is updated. To be overridden.625 To use this method, you must:626 * call _record_attributes() from __init__() (after making the super627 call) with a list of attributes for which you want to be notified upon628 change.629 * call _check_for_updated_attributes() from save().630 """631 pass632class ModelWithInvalid(ModelExtensions):633 """634 Overrides model methods save() and delete() to support invalidation in635 place of actual deletion. Subclasses must have a boolean "invalid"636 field.637 """638 def save(self):639 first_time = (self.id is None)640 if first_time:641 # see if this object was previously added and invalidated642 my_name = getattr(self, self.name_field)643 filters = {self.name_field : my_name, 'invalid' : True}644 try:645 old_object = self.__class__.objects.get(**filters)646 self.id = old_object.id647 except self.DoesNotExist:648 # no existing object649 pass650 super(ModelWithInvalid, self).save()651 def clean_object(self):652 """653 This method is called when an object is marked invalid.654 Subclasses should override this to clean up relationships that655 should no longer exist if the object were deleted."""656 pass657 def delete(self):658 assert not self.invalid659 self.invalid = True660 self.save()661 self.clean_object()662 @classmethod663 def get_valid_manager(cls):664 return cls.valid_objects665 class Manipulator(object):666 """667 Force default manipulators to look only at valid objects -668 otherwise they will match against invalid objects when checking669 uniqueness.670 """671 @classmethod672 def _prepare(cls, model):673 super(ModelWithInvalid.Manipulator, cls)._prepare(model)674 cls.manager = model.valid_objects675class ModelWithAttributes(object):676 """677 Mixin class for models that have an attribute model associated with them....
test_login.py
Source:test_login.py
...6 def setUp(self, url="http://demo.guru99.com/v4/index.php"):7 self.app = Application()8 self.app.navigation_helper.open_main_page(url)9 def test_login(self):10 self.manager = get_valid_manager()11 self.assertEqual("Guru99 Bank", self.app.assertion_helper.get_product_name())12 self.app.login_helper.login_to_site(self.manager)13 self.assertEqual(self.manager.user_name, self.app.assertion_helper.get_manager_id())14 def tearDown(self):...
manager_helper.py
Source:manager_helper.py
...5 if user_password is not None:6 self.user_password = user_password7USER_NAME = "mngr163715"8USER_PASSWORD = "pUrereh"9def get_valid_manager():10 user = Manager(USER_NAME, USER_PASSWORD)11 return user12def get_nonvalid_user():13 user = Manager(USER_NAME, "")...
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!!