Best Python code snippet using autotest_python
CustomerManagementController.py
Source:CustomerManagementController.py
1#!/usr/bin/python2# -*- coding: utf-8 -*-3from BusinessLogic.AbstractUseCaseController import AbstractUseCaseController4from GUI_NotificationHandler import GUI_NotificationHandler5from SystemController import SystemController6from Data.Models.Customer import Customer7from Exceptions.DataValidationException import DataValidationException8from Exceptions.InternalErrorException import InternalErrorException9import re as regex10class CustomerManagementController(AbstractUseCaseController):11 def __init__(self, repository):12 super().__init__()13 self._repository = repository14 def registerCustomer(self, customerDetails):15 if not self._validateInput(customerDetails):16 return False17 customer = self._constructDataModel(customerDetails)18 customer.setCreatedBy(SystemController.getUserId())19 ref = self._repository.write(customer)20 if ref:21 GUI_NotificationHandler.raiseInfoMessg(22 "Registration Success", "Customer reference: " + str(ref))23 return True24 def updateCustomer(self, customerDetails):25 splitDob = dict(zip(["dobDD", "dobMM", "dobYYYY"], customerDetails["dob"].split("/")))26 del customerDetails["dob"] # delete atomic __dob element27 customerDetails = {**splitDob, **customerDetails} # merge dictionaries28 if not self._validateInput(customerDetails):29 return False30 customer = self._constructDataModel(customerDetails)31 if self._repository.update(customer):32 GUI_NotificationHandler.raiseInfoMessg("Success", "Customer was updated successfully")33 return True34 def _constructDataModel(self, data):35 customer = Customer()36 if "id" in data:37 customer.setId(data["id"])38 if "name" in data:39 customer.setName(data["name"])40 if "surname" in data:41 customer.setSurname(data["surname"])42 if "dobDD" in data and "dobMM" in data and "dobYYYY" in data:43 customer.setDob(data["dobDD"],44 data["dobMM"],45 data["dobYYYY"])46 if "dob" in data:47 customer.setDob(data["dob"])48 if "email" in data:49 customer.setEmail(data["email"])50 if "address" in data:51 customer.setAddress(data["address"])52 if "ref" in data:53 customer.setId(data["ref"])54 if "employee_id" in data:55 customer.setCreatedBy(data["employee_id"])56 if "createdBy" in data:57 customer.setCreatedBy(data["createdBy"])58 return customer59 def findCustomers(self, customerDetails):60 customerDetails = {k: v for k, v in customerDetails.items() if len(v) > 0}61 if not len(customerDetails):62 GUI_NotificationHandler.raiseWarningMessg("Warning", "No search criteria was given")63 return None64 if not self._validateInput(customerDetails):65 return None66 customerModel = self._constructDataModel(customerDetails)67 customers = self._repository.read(customerModel.getData())68 customerModels = []69 for customer in customers:70 customerModels.append(self._constructDataModel(customer))71 if len(customers) > 0:72 return customerModels73 else:74 GUI_NotificationHandler.raiseWarningMessg("Warning", "No customer matches the search criteria")75 return None76 def _validateInput(self, customerDetails):77 try:78 self._inputValidation(customerDetails)79 return True80 except DataValidationException as err:81 GUI_NotificationHandler.raiseErrorMessg("Validation Error", str(err))82 except InternalErrorException as err:83 GUI_NotificationHandler.raiseErrorMessg("Internal Error", str(err))84 return False85 def _inputValidation(self, input):86 import datetime87 validFieldNames = ["ref", "name", "surname", "dobDD", "createdBy",88 "email", "address", "dobMM", "dobYYYY", "id"]89 for fn in input:90 if fn not in validFieldNames:91 raise InternalErrorException("Field "+fn+"not recognised")92 if "name" in input:93 if len(input["name"]) not in range(2, 255):94 raise DataValidationException("First Name invalid")95 if regex.search(r'\d', input["name"]):96 raise DataValidationException("First Name must be alphabetic")97 if "surname" in input:98 if len(input["surname"]) not in range(2, 255):99 raise DataValidationException("Last Name invalid")100 if regex.search(r'\d', input["surname"]):101 raise DataValidationException("Last Name must be alphabetic")102 if "dobDD" in input or "dobMM" in input or "dobYYYY" in input:103 try:104 if self.__isInt(input["dobDD"]) \105 and self.__isInt(input["dobMM"]) \106 and self.__isInt(input["dobYYYY"]):107 if int(input["dobYYYY"]) not in range(1900, 2018):108 raise DataValidationException("Invalid year")109 try:110 datetime.date(int(input["dobYYYY"]), int(input["dobMM"]), int(input["dobDD"]))111 except ValueError:112 raise DataValidationException("Non-existent date")113 else:114 raise DataValidationException("Inappropriate date format")115 except KeyError:116 raise DataValidationException("Some part of date of birth is missing")117 if "email" in input:118 validEmail = \119 regex.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$',120 input["email"])121 if not validEmail:122 raise DataValidationException("Email invalid")123 if "address" in input:124 if len(input["address"]) not in range(10, 255):125 raise DataValidationException("Address invalid")126 return True127 def deleteCustomer(self, id):128 confirmation = GUI_NotificationHandler.raiseDialog("Delete", "Are You Sure?")129 if confirmation:130 if self._repository.delete(id):131 GUI_NotificationHandler.raiseInfoMessg("Success", "Customer was deleted")132 return True133 else:134 GUI_NotificationHandler.raiseWarningMessg("Failure", "Unable to delete customer")135 return False136 def __isInt(self, input):137 try:138 num = int(input)139 except ValueError:140 return False...
NestedDict.py
Source:NestedDict.py
1# Standard Library Imports2import logging3# Third Party Imports4# Local/Application Specific Imports5class NestedDict(dict):6 __SPLIT = '.'7 8 def __init__(self, *args):9 dict.__init__(self, args)10 self.logger = logging.getLogger(self.__class__.__name__)11 def __IsInt(self, s):12 try: 13 int(s)14 return True15 except ValueError:16 return False17 def __get_nested_dict(self, key):18 index = str(key).split(self.__SPLIT, 1)19 if (self.__IsInt(index[0])):20 key1 = int(index[0])21 else:22 key1 = index[0]23 if ( key1 not in self or self[key1] == None):24 self[key1] = NestedDict()25 if (len(index) > 1):26 ret = (self[key1]).__get_nested_dict(index[1])27 else:28 ret = self[key1] 29 return ret30 31 def __getitem__(self, key):32 index = str(key).rsplit(self.__SPLIT, 1)33 if (len(index) > 1):34 # nested key of the form 'a.b.c' ... find the nested dict!!!35 nested_dict = self.__get_nested_dict(index[0])36 if (self.__IsInt(index[1])):37 key1 = int(index[1])38 else:39 key1 = index[1]40 val = dict.__getitem__(nested_dict, key1)41 else: 42 # this is a standard key of the form 'a' ... just behave normally43 val = dict.__getitem__(self,key)44 45 self.logger.debug("'%s' = %s", str(key), str(val))46 return val47 def __setitem__(self, key, val):48 index = str(key).rsplit(self.__SPLIT, 1)49 if (len(index) > 1):50 # nested key of the form 'a.b.c' ... find the nested dict!!!51 nested_dict = self.__get_nested_dict(index[0])52 if (self.__IsInt(index[1])):53 key1 = int(index[1])54 else:55 key1 = index[1]56 if ( nested_dict ):57 dict.__setitem__(nested_dict, key1, val)58 else:59 self.logger.error("Cannot set key '" + key + "'. Improperly formed? (Check the config file)")60 else: 61 # this is a standard key of the form 'a' ... just behave normally62 dict.__setitem__(self, key, val)63 64 self.logger.debug("'%s' = %s", str(key), str(val))65 def get (self, key, default=None, check_inherited=False):66 #print( "key = " + str(key))67 index = str(key).rsplit(self.__SPLIT, 1)68 if (len(index) > 1):69 # nested key of the form 'a.b.c' ... find the nested dict!!!70 nested_dict = self.__get_nested_dict(index[0])71 if (self.__IsInt(index[1])):72 key1 = int(index[1])73 else:74 key1 = index[1]75 #print( "nested_dict = " + str(nested_dict))76 if nested_dict:77 val = dict.get(nested_dict, key1, default)78 else:79 val = default80 if ( check_inherited and val == default ) :81 #print("check inherited")82 # check in parent for non-default value83 i_index = index[0].rsplit(self.__SPLIT, 1)84 if ( len(i_index) > 1 ):85 val = self.get(i_index[0] + '.' + index[1], default, True)86 else:87 val = self.get(index[1], default, True)88 else:89 val = dict.get(self,key,default)90 self.logger.debug("'%s' = %s", str(key), str(val))91 return val92 #def get_inherited (self, key, default=None):93 # index = str(key).rsplit(self.__SPLIT, 1)94 #95 # if (len(index) > 1):96 # # nested key of the form 'a.b.c' ... find the nested dict!!!97 # nested_dict = self.__get_nested_dict(index[0])98 # if (self.__IsInt(index[1])):99 # key1 = int(index[1])100 # else:101 # key1 = index[1]102 # val = dict.get(nested_dict, key1, default)103 #104 # if ( val == default ) :105 # # check in parent for non-default value106 # i_index = index[0].rsplit(self.__SPLIT, 1)107 # if ( len(i_index) > 1 ):108 # val = self.get_inherited(i_index[0] + '.' + index[1], default)109 # else:110 # val = self.get_inherited(index[1], default)111 # else:112 # val = dict.get(self,key,default)113 #114 # self.logger.debug("'%s' = %s", str(key), str(val))115 #116 # return val117 def setdefault (self, key, default=None):118 index = str(key).rsplit(self.__SPLIT, 1)119 if (len(index) > 1):120 # nested key of the form 'a.b.c' ... find the nested dict!!!121 nested_dict = self.__get_nested_dict(index[0])122 if (self.__IsInt(index[1])):123 key1 = int(index[1])124 else:125 key1 = index[1]126 val = dict.setdefault(nested_dict, key1, default)127 else:128 val = dict.setdefault(self,key,default)129 self.logger.debug("'%s' = %s", str(key), str(val))130 return val131 def copy_recursive(self, orig_dict, new_dict):132 for key in orig_dict:133 if isinstance(orig_dict[key],dict):134 new_dict[key] = NestedDict()135 self.copy_recursive(orig_dict[key], new_dict[key])136 else:137 new_dict[key] = orig_dict[key]138 def getBoolean(self, key, default = False):139 s = self.get(key)140 if s is True or s is False:141 return s142 s = str(s).strip().lower()143 res = not s in ['false','f','n','0','']144 self.logger.debug("Boolean value is: %d", res)145 return res146 147if __name__ == '__main__':148 logging.basicConfig(format='%(levelname) -10s %(asctime)s %(module)s:%(funcName)s[%(lineno)s] %(message)s',149 level="DEBUG")150 a = NestedDict()151 a['x'] = 'b'152 a['y.1'] = 'q'153 a['y.2.3'] = 'b'...
__init__.py
Source:__init__.py
...30 def zero(self):31 self.__x, self.__y = 0, 032 33 def update(self, x=0,y=0):34 self.__x += Vector2.__isint(x)35 self.__y += Vector2.__isint(y)363738 @staticmethod39 def __isint(value):40 if isinstance(value, int):41 return value 42 else:43 raise TypeError("Must be int", value)4445 46 def distance_to(self, vector):47 if not isinstance(vector, Vector2):48 raise ValueError("Must be Vector2")49 else:50 return hypot(self.__x - vector.__x, self.__y - vector.__y)5152 53
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!!