Best Python code snippet using tempest_python
types.py
Source:types.py  
...348                    error = "Verify function %s for type %s does not exist." \349                        % (functionName, type)350                    raise Exception(error)351                    sys.exit(1)352    def __get_value_info(self):353        valueInfo = { 'isValid' : 0, 'normalized' : 0, 'errorData' : 0 }354        return valueInfo355    def __set_value_info(self, valueInfo, **valueData):356        try:357            valueInfo['normalized'] = valueData['normalized']358            valueInfo['isValid'] = 1359        except KeyError:360            valueInfo['isValid'] = 0361            try:362                valueInfo['errorData'] = valueData['errorData']363            except:364                pass365    # start of 'private' verification methods, each one should correspond to a366    #   type string (see self.verify_config())367    def __verify_directory(self, type, value):368        valueInfo = self.__get_value_info()369        if os.path.isdir(value):370            self.__set_value_info(valueInfo, normalized=self.normalize(type, 371                                                                       value))372        else:373            self.__set_value_info(valueInfo)374        return valueInfo375      376    def __norm_directory(self, value):377        return self.__normalizedPath(value)378    def __verify_address(self, type, value):379        valueInfo = self.__get_value_info()380        try:381            socket = tcpSocket(value)382            if socket.verify():383                self.__set_value_info(valueInfo, normalized=self.normalize(type, 384                                                                       value))385            else:386                self.__set_value_info(valueInfo)387        except:388            self.__set_value_info(valueInfo)389        return valueInfo390      391    def __norm_address(self, value):392        return value.split(':')393    def __verify_ip_address(self, type, value):394        valueInfo = self.__get_value_info()395        if check_ip_address(value):396            self.__set_value_info(valueInfo, normalized=self.normalize(type, 397                                                                       value))398        else:399            self.__set_value_info(valueInfo)400        return valueInfo401    def __verify_net_address(self, type, value):402        valueInfo = self.__get_value_info()403        if check_net_address(value):404            self.__set_value_info(valueInfo, normalized=self.normalize(type, 405                                                                       value))406        else:407            self.__set_value_info(valueInfo)408        return valueInfo409    def __verify_bool(self, type, value):410        valueInfo = self.__get_value_info()411        value = str(value)412        if re.match("^false|0|f|no$", value, 2):413            self.__set_value_info(valueInfo, normalized=False)414        elif re.match("^true|1|t|yes$", value, 2):415            self.__set_value_info(valueInfo, normalized=True)416        else:417            self.__set_value_info(valueInfo)418        return valueInfo419      420    def __norm_bool(self, value):421        value = str(value)422        norm = ""423        if re.match("^false|0|f|no$", value, 2):424            norm = False425        elif re.match("^true|1|t|yes$", value, 2):426            norm = True427        else:428            raise Exception("invalid bool specified: %s" % value)429            430        return norm431    def __verify_int(self, type, value):432        valueInfo = self.__get_value_info()433        try:434            self.__set_value_info(valueInfo, normalized=self.normalize(type, 435                                                                       value))436        except:437            self.__set_value_info(valueInfo)438        return valueInfo439      440    def __norm_int(self, value):441        return int(value)442    def __verify_float(self, type, value):443        valueInfo = self.__get_value_info()444        try:445            self.__set_value_info(valueInfo, normalized=self.normalize(type, 446                                                                       value))447        except:448            self.__set_value_info(valueInfo)449        return valueInfo450      451    def __norm_float(self, value):452        return float(value)453    def __verify_pos_int(self, type, value):454        valueInfo = self.__get_value_info()455        try:456            value = self.normalize(type, value)457        except:458            self.__set_value_info(valueInfo)459        else:460            self.__set_value_info(valueInfo, normalized=value)461        return valueInfo462      463    def __norm_pos_int(self, value):464        value = int(value)465        if value < 0:466            raise Exception("value is not positive: %s" % value)467        468        return value469    def __verify_neg_int(self, type, value):470        valueInfo = self.__get_value_info()471        try:472            value = self.normalize(type, value)473        except:474            self.__set_value_info(valueInfo)475        else:476            self.__set_value_info(valueInfo, normalized=value)477        return valueInfo478      479    def __norm_neg_int(self, type, value):480        value = int(value)481        if value > 0:482            raise Exception("value is not negative: %s" % value)483        484        return value        485    def __verify_freq(self, type, value):486        return self.__verify_pos_int(type, value)487    def __norm_freq(self, value):488        return self.__norm_pos_int(value)489    def __verify_pos_float(self, type, value):490        valueInfo = self.__get_value_info()491        try:492            value = self.normalize(type, value)493        except:494            self.__set_value_info(valueInfo)495        else:496            self.__set_value_info(valueInfo, normalized=value)497        return valueInfo498    def __norm_pos_float(self, value):499        value = float(value)500        if value < 0:501            raise Exception("value is not positive: %s" % value)502        503        return value504    def __verify_pos_num(self, type, value):505        return self.__verify_pos_float(value)506      507    def __norm_pos_num(self, value):508        return self.__norm_pos_float(value)509    def __verify_neg_float(self, type, value):510        valueInfo = self.__get_value_info()511        try:512            value = self.normalize(type, value)513        except:514            self.__set_value_info(valueInfo)515        else:516            self.__set_value_info(valueInfo, normalized=value)517        return valueInfo518    def __norm_neg_float(self, value):519        value = float(value)520        if value >= 0:521            raise Exception("value is not negative: %s" % value)522        523        return value524    def __verify_string(self, type, value):525        valueInfo = self.__get_value_info()526        self.__set_value_info(valueInfo, normalized=self.normalize(type, 527                                                                   value))528        529        return valueInfo530      531    def __norm_string(self, value):532        return str(value)533    def __verify_keyval(self, type, value):534        valueInfo = self.__get_value_info()535        if reKeyVal.search(value):536          try:537            self.__set_value_info(valueInfo, normalized=self.normalize(type, 538                                value))539          except:540            self.__set_value_info(valueInfo, errorData = \541              "invalid list of key-value pairs : [ %s ]" % value)542        else:543            msg = "No key value pairs found?"544            self.__set_value_info(valueInfo, errorData=msg)545        return valueInfo546      547    def __norm_keyval(self, value):548        list = self.__norm_list(value)549        keyValue = {}550        for item in list:551            (key, value) = reKeyVal.split(item)552            #if not keyValue.has_key(key):553            #    keyValue[key] = []554            #keyValue[key].append(value)555            keyValue[key] = value556        return keyValue     557    def __verify_list(self, type, value):558        valueInfo = self.__get_value_info()559        self.__set_value_info(valueInfo, normalized=self.normalize(type,value))560        return valueInfo561      562    def __norm_list(self, value):563        norm = []564        if reList.search(value):565            norm = reList.split(value)566        else:567            norm = [value,]568            569        return norm570    def __verify_file(self, type, value):571        valueInfo = self.__get_value_info()572        if os.path.isfile(value):573            self.__set_value_info(valueInfo, normalized=self.normalize(type,574                                                                       value))575        else:576            self.__set_value_info(valueInfo)577        return valueInfo578      579    def __norm_file(self, value):580        return self.__normalizedPath(value)581    def __verify_size(self, type, value):582        valueInfo = self.__get_value_info()583        value = str(value)584        if reSizeFormat.match(value):585            numberPart = int(reSizeFormat.sub("\g<1>", value))586            factorPart = reSizeFormat.sub("\g<2>", value)587            try:588                normalized = normalize_size(numberPart, factorPart)589                self.__set_value_info(valueInfo,590                    normalized=normalized)591            except:592                self.__set_value_info(valueInfo)593        else:594            try:595                value = int(value)596            except:597                self.__set_value_info(valueInfo)598            else:599                if value >= 0:600                    self.__set_value_info(valueInfo, normalized=value)601                else:602                    self.__set_value_info(valueInfo)603        return valueInfo604    def __norm_size(self, file):605        norm = None606        if reSizeFormat.match(value):607            numberPart = int(reSizeFormat.sub("\g<1>", value))608            factorPart = reSizeFormat.sub("\g<2>", value)609            norm = normalize_size(numberPart, factorPart)            610        else:611            norm = int(value)612            613        return norm614        615        616    def __verify_eaddress(self, type, value):617        valueInfo = self.__get_value_info()618        emailList = reComma.split(value)619        for emailAddress in emailList:620            if reEmailAddress.match(emailAddress):621                emailParts = reEmailDelimit.split(emailAddress)622                try:623                    socket.gethostbyname(emailParts[1])624                    self.__set_value_info(valueInfo, normalized=self.normalize(625                                          type, value))626                except:627                    errorString = "%s is invalid (domain lookup failed)" % \628                        emailAddress629                    self.__set_value_info(valueInfo, errorData=errorString)630            else:631                errorString = "%s is invalid" % emailAddress632                self.__set_value_info(valueInfo, errorData=errorString)633        return valueInfo634    def __verify_tcp_port(self, type, value):635        valueInfo = self.__get_value_info()636        try:637            value = self.__norm_tcp_port(value)638        except:639            self.__set_value_info(valueInfo)640        else:641            if value in range(2, 65536):642                self.__set_value_info(valueInfo, normalized=value)643            else:644                self.__set_value_info(valueInfo)645        return valueInfo646      647    def __norm_tcp_port(self, value):648        return int(value)649    def __verify_http_version(self, type, value):650        valueInfo = self.__get_value_info()651        if value in ('1.0', '1.1'):652            self.__set_value_info(valueInfo, normalized=float(value))653        else:654            self.__set_value_info(valueInfo)655        return valueInfo656    def __verify_range(self, type, value):657        valueInfo = self.__get_value_info()658        range = reDash.split(value)659        try:660            if len(range) > 1:661                start = int(range[0])662                end = int(range[1])663            else:664                start = int(range[0])665                end = None666        except:667            self.__set_value_info(valueInfo)668        else:669            if end:670                if end - start != 0:671                    self.__set_value_info(valueInfo, normalized=(start, end))672                else:673                    self.__set_value_info(valueInfo)674            else:675                self.__set_value_info(valueInfo, normalized=(start,))676        return valueInfo677      678    def __norm_range(self, value):679        range = reDash.split(value)680        if len(range) > 1:681            start = int(range[0])682            end = int(range[1])683        else:684            start = int(range[0])685            end = None   686            687        return (start, end)     688    def __verify_uri(self, type, value):689        valueInfo = self.__get_value_info()690        _norm = None691        try:692            uriComponents = urlparse.urlparse(value)693            if uriComponents[0] == '' or uriComponents[0] == 'file':694              # if scheme is '' or 'file'695              if not os.path.isfile(uriComponents[2]) and \696                                         not os.path.isdir(uriComponents[2]):697                  raise Exception("Invalid local URI")698              else:699                  self.__set_value_info(valueInfo, normalized=self.normalize(700                                                                  type,value))701            else:702              # other schemes703              # currently not checking anything. TODO704              self.__set_value_info(valueInfo, normalized=self.normalize(705                                                                   type,value))706        except:707            errorString = "%s is an invalid uri" % value708            self.__set_value_info(valueInfo, errorData=errorString)709        return valueInfo710    def __norm_uri(self, value):711       uriComponents = list(urlparse.urlparse(value))712       if uriComponents[0] == '':713          # if scheme is '''714          return self.__normalizedPath(uriComponents[2])715       elif uriComponents[0] == 'file':716          # if scheme is 'file'717          normalizedPath = self.__normalizedPath(uriComponents[2])718          return urlparse.urlunsplit(uriComponents[0:1] + [normalizedPath] + uriComponents[3:])719       # Not dealing with any other case right now720       return value721    def __verify_timestamp(self, type, value):722        valueInfo = self.__get_value_info()723        if check_timestamp(value):724            self.__set_value_info(valueInfo, normalized=self.normalize(type, 725                                                                       value))726        else:727            self.__set_value_info(valueInfo)728        return valueInfo729    def __verify_hostname(self, type, value):730        valueInfo = self.__get_value_info()731        try:732            socket.gethostbyname(value)733            self.__set_value_info(valueInfo, normalized=self.normalize(type, 734                                                                       value))735        except:736            errorString = "%s is invalid (domain lookup failed)" % value737            self.__set_value_info(valueInfo, errorData=errorString)738        return valueInfo739    def __verify_user_account(self, type, value):740        valueInfo = self.__get_value_info()741        try:742            pwd.getpwnam(value)743        except:744            errorString = "'%s' user account does not exist" % value745            self.__set_value_info(valueInfo, errorData=errorString)746        else:747            self.__set_value_info(valueInfo, normalized=self.normalize(type, 748                                                                       value))749        return valueInfo750    def __verify_user_group(self, type, value):751        valueInfo = self.__get_value_info()752        try:753            grp.getgrnam(value)754        except:755            errorString = "'%s' group does not exist" % value756            self.__set_value_info(valueInfo, errorData=errorString)757        else:758            self.__set_value_info(valueInfo, normalized=self.normalize(type, 759                                                                       value))760        return valueInfo761    def __verify_nothing(self, type, value):762        valueInfo = self.__get_value_info()763        self.__set_value_info(valueInfo, normalized=self.normalize(type, 764                                                                   value))765        return valueInfo766    #--------------------------------------------------------------------------767    def normalize(self, type, value):768        try:769          normFunc = getattr(self, "_typeValidator__norm_%s" % type)770          return normFunc(value)771        except AttributeError, A:772          # this exception should occur only when we don't have corresponding normalize function773          return value774    def verify(self, type, value, allowNone=False):775        """Verifies a value based on its type.776           type      - supported configValidator type777           value     - data to be validated778           allowNone - don't freak out if None or '' is supplied779           returns a valueInfo dictionary:780            valueInfo = { 'isValid' : 1, 'normalized' : 5, 'errorData' : 0 }781           where:782            isValid    - true or false (0/1)783            normalized - the normalized value784            errorData  - if invalid an error string785           supported types:786            see top level"""787        result = None788        if allowNone:789            if value == '' or value == None:790                result = self.__verify_nothing(None, None)791                result['normalized'] = None792            else:793                result = self.verifyFunctions[type](type, value)794        else:795            result = self.verifyFunctions[type](type, value)796        return result797    def is_valid_type(self, type):798        """Returns true if type is valid."""799        return types.has_key(type)800    def type_info(self, type):801        """Returns type info dictionary."""802        dbInfo = dbTypes[types[type]['db']]803        typeInfo = types[type].copy()804        typeInfo['db'] = dbInfo805        return typeInfo806    def add(self, name, type, value):807        """Adds a value and type by name to the configValidate object to be808           verified using validate().809           name  - name used to key values and access the results of the810                   validation811           type  - configValidator type812           value - data to be verified"""813        self.validateList.append({ 'name' : name,814                                   'type' : type,815                                   'value': value })816    def validate(self, allowNone=False):817        """Validates configValidate object populating validatedInfo with818           valueInfo dictionaries for each value added to the object."""819        for valItem in self.validateList:820            valueInfo = self.verify(valItem['type'], valItem['value'],821                allowNone)822            if valueInfo:823                valueInfo['name'] = valItem['name']824                self.validatedInfo.append(valueInfo)825            else:826                raise Exception("\nMissing a return value: valueInfo\n%s" % \827                    self.verifyFunctions[valItem['type']](valItem['value']))828    def __normalizedPath(self, value):    829        oldWd = os.getcwd()830        if self.__originalDir:831          os.chdir(self.__originalDir)832        normPath = os.path.realpath(value)833        os.chdir(oldWd)834        return normPath835class display:836    def __init__(self):837        self.displayFunctions = {}838        self.__build_dispaly_functions()839    def __build_dispaly_functions(self):840        functions = {}841        for function in dir(self):842            functions[function] = 1843        for type in types.keys():844            # kinda bad, need to find out how to know the name of the class845            #  I'm in.  But it works.846            functionName = "_cisplay__display_%s" % type847            if functions.has_key(functionName):848                self.displayFunctions[type] = getattr(self, functionName)849            else:850                if type == '':851                    self.displayFunctions[type] = self.__display_default852                else:853                    error = "Display function %s for type %s does not exist." \854                        % (functionName, type)855                    raise Exception(error)856                    sys.exit(1)857    def __display_default(self, value, style):858        return value859    def __display_generic_number(self, value):860        displayNumber = ''861        splitNum = string.split(str(value), sep='.')862        numList = list(str(splitNum[0]))863        numList.reverse()864        length = len(numList)865        counter = 0866        for char in numList:867            counter = counter + 1868            if counter % 3 or counter == length:869                displayNumber = "%s%s" % (char, displayNumber)870            else:871                displayNumber = ",%s%s" % (char, displayNumber)872        if len(splitNum) > 1:873            displayNumber = "%s.%s" % (displayNumber, splitNum[1])874        return displayNumber875    def __display_generic_mappable(self, map, value, style, plural=True):876        displayValue = ''877        length = len(str(value))878        if length > 3:879            for factorSet in map:880                displayValue = float(value) / factorSet['factor']881                if len(str(int(displayValue))) <= 3 or \882                    factorSet['factor'] == map[-1]['factor']:883                    displayValue = "%10.2f" % displayValue    884                    if displayValue[-1] == '0':885                        if displayValue > 1 and style != 'short' and plural:886                            displayValue = "%s %ss" % (displayValue[:-1], 887                                                      factorSet[style])888                        else:889                            displayValue = "%s %s" % (displayValue[:-1], 890                                                      factorSet[style])891                    else:892                        if displayValue > 1 and style != 'short' and plural:893                            displayValue = "%s %ss" % (displayValue, 894                                                      factorSet[style])895                        else:896                            displayValue = "%s %s" % (displayValue, 897                                                      factorSet[style])898                    break899        return displayValue900    def __display_directory(self, value, style):901        return self.__display_default(value, style)902    def __display_address(self, value, style):903        return self.__display_default(value, style)904    def __display_ip_address(self, value, style):905        return self.__display_default(value, style)906    def __display_net_address(self, value, style):907        return self.__display_default(value, style)908    def __display_bool(self, value, style):909        displayValue = value910        911        if not isinstance(displayValue, bool):912            if re.match("^false|0|f|no$", value, 2):913                displayValue=False914            elif re.match("^true|1|t|yes$", value, 2):915                displayValue=True916        return displayValue917    def __display_int(self, value, style):918        return self.__display_generic_number(value)919    def __display_float(self, value, style):920        return self.__display_generic_number(value)921    def __display_pos_int(self, value, style):922        return self.__display_generic_number(value)923    def __display_neg_int(self, value, style):924        return self.__display_generic_number(value)925    def __display_pos_num(self, value, style):926        return self.__display_generic_number(value)927    def __display_pos_float(self, value, style):928        return self.__display_generic_number(value)929    def __display_neg_float(self, value, style):930        return self.__display_generic_number(value)931    def __display_string(self, value, style):932        return self.__display_default(value, style)933    def __display_list(self, value, style):934        value = value.rstrip()935        return value.rstrip(',')936    def __display_keyval(self, value, style):937        value = value.rstrip()938        return value.rstrip(',')939    def __display_file(self, value, style):940        return self.__display_default(value, style)941    def __display_size(self, value, style):942        return self.__display_generic_mappable(sizeMap, value, style)943    def __display_freq(self, value, style):944        return self.__display_generic_mappable(freqMap, value, style, False)945    def __display_eaddress(self, value, style):946        return self.__display_default(value, style)947    def __display_tcp_port(self, value, style):948        return self.__display_default(value, style)949    def __display_http_version(self, value, style):950        return self.__display_default(value, style)951    def __display_range(self, value, style):952        return self.__display_default(value, style)953    def __display_hostname(self, value, style):954        return self.__display_default(value, style)955    def __display_user_account(self, value, style):956        return self.__display_default(value, style)957    def __display_user_group(self, value, style):958        return self.__display_default(value, style)959    def __display_timestamp(self, value, style):960        return self.__display_default(value, style)961    def display(self, type, value, style='short'):962        displayValue = value963        if value != None:964            displayValue = self.displayFunctions[type](value, style)965        return displayValue966typeValidatorInstance = typeValidator()967def is_valid_type(type):968    """Returns true if type is valid."""969    return typeValidatorInstance.is_valid_type(type)970def type_info(type):971    """Returns type info dictionary."""972    return typeValidatorInstance.type_info(type)973def verify(type, value, allowNone=False):974    """Returns a normalized valueInfo dictionary."""975    return typeValidatorInstance.verify(type, value, allowNone)976def __normalize(map, val, factor):977    normFactor = string.lower(factor)978    normVal = float(val)979    return int(normVal * map[normFactor])980def normalize_size(size, factor):981    """ Normalize a size to bytes.982        size   - number of B, KB, MB, GB, TB, or PB983        factor - size factor (case insensitive):984                 b | bytes - bytes985                 k | kb    - kilobytes986                 m | mb    - megabytes...test_vmwareapi.py
Source:test_vmwareapi.py  
...48        stubs.set_stubs(self.stubs)49        self.conn = driver.VMwareESXDriver(None, False)50        # NOTE(vish): none of the network plugging code is actually51        #             being tested52        self.network_info = utils.get_test_network_info(legacy_model=False)53        self.image = {54            'id': 'c1c8ce3d-c2e0-4247-890c-ccf5cc1c004c',55            'disk_format': 'vhd',56            'size': 512,57        }58        nova.tests.image.fake.stub_out_image_service(self.stubs)59    def tearDown(self):60        super(VMwareAPIVMTestCase, self).tearDown()61        vmwareapi_fake.cleanup()62        nova.tests.image.fake.FakeImageService_reset()63    def _create_instance_in_the_db(self):64        values = {'name': 1,65                  'id': 1,66                  'project_id': self.project_id,67                  'user_id': self.user_id,68                  'image_ref': "1",69                  'kernel_id': "1",70                  'ramdisk_id': "1",71                  'mac_address': "de:ad:be:ef:be:ef",72                  'instance_type': 'm1.large',73                  }74        self.instance = db.instance_create(None, values)75    def _create_vm(self):76        """Create and spawn the VM."""77        self._create_instance_in_the_db()78        self.type_data = db.instance_type_get_by_name(None, 'm1.large')79        self.conn.spawn(self.context, self.instance, self.image,80                        injected_files=[], admin_password=None,81                        network_info=self.network_info,82                        block_device_info=None)83        self._check_vm_record()84    def _check_vm_record(self):85        """86        Check if the spawned VM's properties correspond to the instance in87        the db.88        """89        instances = self.conn.list_instances()90        self.assertEquals(len(instances), 1)91        # Get Nova record for VM92        vm_info = self.conn.get_info({'name': 1})93        # Get record for VM94        vms = vmwareapi_fake._get_objects("VirtualMachine")95        vm = vms[0]96        # Check that m1.large above turned into the right thing.97        mem_kib = long(self.type_data['memory_mb']) << 1098        vcpus = self.type_data['vcpus']99        self.assertEquals(vm_info['max_mem'], mem_kib)100        self.assertEquals(vm_info['mem'], mem_kib)101        self.assertEquals(vm.get("summary.config.numCpu"), vcpus)102        self.assertEquals(vm.get("summary.config.memorySizeMB"),103                          self.type_data['memory_mb'])104        # Check that the VM is running according to Nova105        self.assertEquals(vm_info['state'], power_state.RUNNING)106        # Check that the VM is running according to vSphere API.107        self.assertEquals(vm.get("runtime.powerState"), 'poweredOn')108    def _check_vm_info(self, info, pwr_state=power_state.RUNNING):109        """110        Check if the get_info returned values correspond to the instance111        object in the db.112        """113        mem_kib = long(self.type_data['memory_mb']) << 10114        self.assertEquals(info["state"], pwr_state)115        self.assertEquals(info["max_mem"], mem_kib)116        self.assertEquals(info["mem"], mem_kib)117        self.assertEquals(info["num_cpu"], self.type_data['vcpus'])118    def test_list_instances(self):119        instances = self.conn.list_instances()120        self.assertEquals(len(instances), 0)121    def test_list_instances_1(self):122        self._create_vm()123        instances = self.conn.list_instances()124        self.assertEquals(len(instances), 1)125    def test_list_interfaces(self):126        self._create_vm()127        interfaces = self.conn.list_interfaces(1)128        self.assertEquals(len(interfaces), 1)129        self.assertEquals(interfaces[0], 4000)130    def test_spawn(self):131        self._create_vm()132        info = self.conn.get_info({'name': 1})133        self._check_vm_info(info, power_state.RUNNING)134    def test_snapshot(self):135        expected_calls = [136            {'args': (),137             'kwargs':138                 {'task_state': task_states.IMAGE_PENDING_UPLOAD}},139            {'args': (),140             'kwargs':141                 {'task_state': task_states.IMAGE_UPLOADING,142                  'expected_state': task_states.IMAGE_PENDING_UPLOAD}}]143        func_call_matcher = matchers.FunctionCallMatcher(expected_calls)144        self._create_vm()145        info = self.conn.get_info({'name': 1})146        self._check_vm_info(info, power_state.RUNNING)147        self.conn.snapshot(self.context, self.instance, "Test-Snapshot",148                           func_call_matcher.call)149        info = self.conn.get_info({'name': 1})150        self._check_vm_info(info, power_state.RUNNING)151        self.assertIsNone(func_call_matcher.match())152    def test_snapshot_non_existent(self):153        self._create_instance_in_the_db()154        self.assertRaises(exception.InstanceNotFound, self.conn.snapshot,155                          self.context, self.instance, "Test-Snapshot",156                          lambda *args, **kwargs: None)157    def test_reboot(self):158        self._create_vm()159        info = self.conn.get_info({'name': 1})160        self._check_vm_info(info, power_state.RUNNING)161        reboot_type = "SOFT"162        self.conn.reboot(self.context, self.instance, self.network_info,163                         reboot_type)164        info = self.conn.get_info({'name': 1})165        self._check_vm_info(info, power_state.RUNNING)166    def test_reboot_non_existent(self):167        self._create_instance_in_the_db()168        self.assertRaises(exception.InstanceNotFound, self.conn.reboot,169                          self.context, self.instance, self.network_info,170                          'SOFT')171    def test_reboot_not_poweredon(self):172        self._create_vm()173        info = self.conn.get_info({'name': 1})174        self._check_vm_info(info, power_state.RUNNING)175        self.conn.suspend(self.instance)176        info = self.conn.get_info({'name': 1})177        self._check_vm_info(info, power_state.SUSPENDED)178        self.assertRaises(exception.InstanceRebootFailure, self.conn.reboot,179                          self.context, self.instance, self.network_info,180                          'SOFT')181    def test_suspend(self):182        self._create_vm()183        info = self.conn.get_info({'name': 1})184        self._check_vm_info(info, power_state.RUNNING)185        self.conn.suspend(self.instance)186        info = self.conn.get_info({'name': 1})187        self._check_vm_info(info, power_state.SUSPENDED)188    def test_suspend_non_existent(self):189        self._create_instance_in_the_db()190        self.assertRaises(exception.InstanceNotFound, self.conn.suspend,191                          self.instance)192    def test_resume(self):193        self._create_vm()194        info = self.conn.get_info({'name': 1})195        self._check_vm_info(info, power_state.RUNNING)196        self.conn.suspend(self.instance)197        info = self.conn.get_info({'name': 1})198        self._check_vm_info(info, power_state.SUSPENDED)199        self.conn.resume(self.instance, self.network_info)200        info = self.conn.get_info({'name': 1})201        self._check_vm_info(info, power_state.RUNNING)202    def test_resume_non_existent(self):203        self._create_instance_in_the_db()204        self.assertRaises(exception.InstanceNotFound, self.conn.resume,205                          self.instance, self.network_info)206    def test_resume_not_suspended(self):207        self._create_vm()208        info = self.conn.get_info({'name': 1})209        self._check_vm_info(info, power_state.RUNNING)210        self.assertRaises(exception.InstanceResumeFailure, self.conn.resume,211                          self.instance, self.network_info)212    def test_power_on(self):213        self._create_vm()214        info = self.conn.get_info({'name': 1})215        self._check_vm_info(info, power_state.RUNNING)216        self.conn.power_off(self.instance)217        info = self.conn.get_info({'name': 1})218        self._check_vm_info(info, power_state.SHUTDOWN)219        self.conn.power_on(self.instance)220        info = self.conn.get_info({'name': 1})221        self._check_vm_info(info, power_state.RUNNING)222    def test_power_on_non_existent(self):223        self._create_instance_in_the_db()224        self.assertRaises(exception.InstanceNotFound, self.conn.power_on,225                          self.instance)226    def test_power_off(self):227        self._create_vm()228        info = self.conn.get_info({'name': 1})229        self._check_vm_info(info, power_state.RUNNING)230        self.conn.power_off(self.instance)231        info = self.conn.get_info({'name': 1})232        self._check_vm_info(info, power_state.SHUTDOWN)233    def test_power_off_non_existent(self):234        self._create_instance_in_the_db()235        self.assertRaises(exception.InstanceNotFound, self.conn.power_off,236                          self.instance)237    def test_power_off_suspended(self):238        self._create_vm()239        self.conn.suspend(self.instance)240        info = self.conn.get_info({'name': 1})241        self._check_vm_info(info, power_state.SUSPENDED)242        self.assertRaises(exception.InstancePowerOffFailure,243                          self.conn.power_off, self.instance)244    def test_get_info(self):245        self._create_vm()246        info = self.conn.get_info({'name': 1})247        self._check_vm_info(info, power_state.RUNNING)248    def test_destroy(self):249        self._create_vm()250        info = self.conn.get_info({'name': 1})251        self._check_vm_info(info, power_state.RUNNING)252        instances = self.conn.list_instances()253        self.assertEquals(len(instances), 1)254        self.conn.destroy(self.instance, self.network_info)255        instances = self.conn.list_instances()256        self.assertEquals(len(instances), 0)257    def test_destroy_non_existent(self):258        self._create_instance_in_the_db()259        self.assertEquals(self.conn.destroy(self.instance, self.network_info),260                          None)261    def test_pause(self):262        pass263    def test_unpause(self):264        pass265    def test_diagnostics(self):...listeners.py
Source:listeners.py  
...15            return16        if is_special_view(view):17            self.on_activated_special_view(view)18        else:19            info = get_info(view)20            if info:21                self.on_activated_with_info(view, info)22    def on_activated_special_view(self, view):23        log.debug("on_activated_special_view")24        EventHub.run_listeners("on_activated_special_view", view)25    def on_activated_with_info(self, view, info):26        log.debug("on_activated_with_info")27        EventHub.run_listeners("on_activated_with_info", view, info)28    def on_modified(self, view):29        """30        Usually called by Sublime when the buffer is modified31        not called for undo, redo32        """33        log.debug("on_modified")34        if is_special_view(view):35            self.on_modified_special_view(view)36        else:37            info = get_info(view)38            if info:39                self.on_modified_with_info(view, info)40        self.post_on_modified(view)41    def on_modified_special_view(self, view):42        log.debug("on_modified_special_view")43        EventHub.run_listeners("on_modified_special_view", view)44    def on_modified_with_info(self, view, info):45        log.debug("on_modified_with_info")46        # A series state-updating for the info object to sync the file content on the server47        info.modified = True48        # Todo: explain49        if IS_ST2:50            info.modify_count += 151        info.last_modify_change_count = change_count(view)52        last_command, args, repeat_times = view.command_history(0)53        if info.pre_change_sent:54            # change handled in on_text_command55            info.client_info.change_count = change_count(view)56            info.pre_change_sent = False57        else:58            if last_command == "insert":59                if (60                    "\n" not in args['characters']  # no new line inserted61                    and info.prev_sel  # it is not a newly opened file62                    and len(info.prev_sel) == 1  # not a multi-cursor session63                    and info.prev_sel[0].empty()  # the last selection is not a highlighted selection64                    and not info.client_info.pending_changes  # no pending changes in the buffer65                ):66                    info.client_info.change_count = change_count(view)67                    prev_cursor = info.prev_sel[0].begin()68                    cursor = view.sel()[0].begin()69                    key = view.substr(sublime.Region(prev_cursor, cursor))70                    send_replace_changes_for_regions(view, static_regions_to_regions(info.prev_sel), key)71                    # mark change as handled so that on_post_text_command doesn't try to handle it72                    info.change_sent = True73                else:74                    # request reload because we have strange insert75                    info.client_info.pending_changes = True76            # Reload buffer after insert_snippet.77            # For Sublime 2 only. In Sublime 3, this logic is implemented in78            # on_post_text_command callback.79            # Issue: https://github.com/Microsoft/TypeScript-Sublime-Plugin/issues/27780            if IS_ST2 and last_command == "insert_snippet":81                reload_buffer(view);82        # Other listeners83        EventHub.run_listeners("on_modified_with_info", view, info)84    def post_on_modified(self, view):85        log.debug("post_on_modified")86        EventHub.run_listeners("post_on_modified", view)87    def on_selection_modified(self, view):88        """89        Called by Sublime when the cursor moves (or when text is selected)90        called after on_modified (when on_modified is called)91        """92        log.debug("on_selection_modified")93        # Todo: why do we only check this here? anyway to globally disable the listener for non-ts files94        if not is_typescript(view):95            return96        EventHub.run_listeners("on_selection_modified", view)97        info = get_info(view)98        if info:99            self.on_selection_modified_with_info(view, info)100    def on_selection_modified_with_info(self, view, info):101        log.debug("on_selection_modified_with_info")102        if not info.client_info:103            info.client_info = cli.get_or_add_file(view.file_name())104        if (105            info.client_info.change_count < change_count(view)106            and info.last_modify_change_count != change_count(view)107        ):108            # detected a change to the view for which Sublime did not call109            # 'on_modified' and for which we have no hope of discerning110            # what changed111            info.client_info.pending_changes = True112        # save the current cursor position so that we can see (in113        # on_modified) what was inserted114        info.prev_sel = regions_to_static_regions(view.sel())115        EventHub.run_listeners("on_selection_modified_with_info", view, info)116    def on_load(self, view):117        log.debug("on_load")118        EventHub.run_listeners("on_load", view)119    def on_window_command(self, window, command_name, args):120        log.debug("on_window_command")121        if command_name == "hide_panel" and cli.worker_client.started():122            cli.worker_client.stop()123        elif command_name == "exit":124            cli.service.exit()125        elif command_name in ["close_all", "close_window", "close_project"]:126            # Only set <about_to_close_all> flag if there exists at least one127            # view in the active window. This is important because we need128            # some view's on_close callback to reset the flag.129            window = sublime.active_window()130            if window is not None and window.views():131                TypeScriptEventListener.about_to_close_all = True132    def on_text_command(self, view, command_name, args):133        """134        ST3 only (called by ST3 for some, but not all, text commands)135        for certain text commands, learn what changed and notify the136        server, to avoid sending the whole buffer during completion137        or when key can be held down and repeated.138        If we had a popup session active, and we get the command to139        hide it, then do the necessary clean up.140        """141        log.debug("on_text_command")142        EventHub.run_listeners("on_text_command", view, command_name, args)143        info = get_info(view)144        if info:145            self.on_text_command_with_info(view, command_name, args, info)146    def on_text_command_with_info(self, view, command_name, args, info):147        log.debug("on_text_command_with_info")148        info.change_sent = True149        info.pre_change_sent = True150        if command_name == "left_delete":151            # backspace152            send_replace_changes_for_regions(view, left_expand_empty_region(view.sel()), "")153        elif command_name == "right_delete":154            # delete155            send_replace_changes_for_regions(view, right_expand_empty_region(view.sel()), "")156        else:157            # notify on_modified and on_post_text_command events that158            # nothing was handled. There are multiple flags because Sublime159            # does not always call all three events.160            info.pre_change_sent = False161            info.change_sent = False162            info.modified = False163        EventHub.run_listeners("on_text_command_with_info", view, command_name, args, info)164    def on_post_text_command(self, view, command_name, args):165        """166        ST3 only167        called by ST3 for some, but not all, text commands168        not called for insert command169        """170        log.debug("on_post_text_command")171        info = get_info(view)172        if info:173            if not info.change_sent and info.modified:174                self.on_post_text_command_with_info(view, command_name, args, info)175                # we are up-to-date because either change was sent to server or176                # whole buffer was sent to server177                info.client_info.change_count = view.change_count()178            # reset flags and saved regions used for communication among179            # on_text_command, on_modified, on_selection_modified,180            # on_post_text_command, and on_query_completion181            info.change_sent = False182            info.modified = False183            info.completion_sel = None184    def on_post_text_command_with_info(self, view, command_name, args, info):185        log.debug("on_post_text_command_with_info")186        if command_name not in \187            ["commit_completion",188             "insert_best_completion",189             "typescript_format_on_key",190             "typescript_format_document",191             "typescript_format_selection",192             "typescript_format_line",193             "typescript_paste_and_format"]:194            print(command_name)195            # give up and send whole buffer to server (do this eagerly196            # to avoid lag on next request to server)197            reload_buffer(view, info.client_info)198        EventHub.run_listeners("on_post_text_command_with_info", view, command_name, args, info)199    def on_query_completions(self, view, prefix, locations):200        log.debug("on_query_completions")201        return EventHub.run_listener_with_return("on_query_completions", view, prefix, locations)202    def on_query_context(self, view, key, operator, operand, match_all):203        log.debug("on_query_context")204        return EventHub.run_listener_with_return("on_query_context", view, key, operator, operand, match_all)205    def on_close(self, view):206        log.debug("on_close")207        file_name = view.file_name()208        info = get_info(view, open_if_not_cached=False)209        if info:210            info.is_open = False211        if view.is_scratch() and view.name() == "Find References":212            cli.dispose_ref_info()213        else:214            # info = get_info(view)215            # if info:216            #     if info in most_recent_used_file_list:217            #         most_recent_used_file_list.remove(info)218            # notify the server that the file is closed219            cli.service.close(file_name)220        # If this is the last view that is closed by a close_all command,221        # reset <about_to_close_all> flag.222        if TypeScriptEventListener.about_to_close_all:223            window = sublime.active_window()224            if window is None or not window.views():225                TypeScriptEventListener.about_to_close_all = False226                log.debug("all views have been closed")227    def on_pre_save(self, view):228        log.debug("on_pre_save")...pretty_docs.py
Source:pretty_docs.py  
1# Copyright 2015 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#     http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""A module for converting parsed doc content into markdown pages.16The adjacent `parser` module creates `PageInfo` objects, containing all data17necessary to document an element of the TensorFlow API.18This module contains one public function, which handels the conversion of these19`PageInfo` objects into a markdown string:20    md_page = build_md_page(page_info)21"""22from __future__ import absolute_import23from __future__ import division24from __future__ import print_function25import textwrap26def build_md_page(page_info):27  """Given a PageInfo object, return markdown for the page.28  Args:29    page_info: must be a `parser.FunctionPageInfo`, `parser.ClassPageInfo`, or30        `parser.ModulePageInfo`31  Returns:32    Markdown for the page33  Raises:34    ValueError: if `page_info` is an instance of an unrecognized class35  """36  if page_info.for_function():37    return _build_function_page(page_info)38  if page_info.for_class():39    return _build_class_page(page_info)40  if page_info.for_module():41    return _build_module_page(page_info)42  raise ValueError('Unknown Page Info Type: %s' % type(page_info))43def _build_function_page(page_info):44  """Given a FunctionPageInfo object Return the page as an md string."""45  parts = ['# %s\n\n' % page_info.full_name]46  if len(page_info.aliases) > 1:47    parts.append('### Aliases:\n\n')48    parts.extend('* `%s`\n' % name for name in page_info.aliases)49    parts.append('\n')50  if page_info.signature is not None:51    parts.append(_build_signature(page_info))52  if page_info.defined_in:53    parts.append('\n\n')54    parts.append(str(page_info.defined_in))55  parts.append(page_info.guides)56  parts.append(page_info.doc.docstring)57  parts.append(_build_function_details(page_info.doc.function_details))58  parts.append(_build_compatibility(page_info.doc.compatibility))59  return ''.join(parts)60def _build_class_page(page_info):61  """Given a ClassPageInfo object Return the page as an md string."""62  parts = ['# {page_info.full_name}\n\n'.format(page_info=page_info)]63  parts.append('## Class `%s`\n\n' % page_info.full_name.split('.')[-1])64  if page_info.bases:65    parts.append('Inherits From: ')66    link_template = '[`{short_name}`]({url})'67    parts.append(', '.join(68        link_template.format(**base._asdict()) for base in page_info.bases))69  parts.append('\n\n')70  if len(page_info.aliases) > 1:71    parts.append('### Aliases:\n\n')72    parts.extend('* Class `%s`\n' % name for name in page_info.aliases)73    parts.append('\n')74  if page_info.defined_in is not None:75    parts.append('\n\n')76    parts.append(str(page_info.defined_in))77  parts.append(page_info.guides)78  parts.append(page_info.doc.docstring)79  parts.append(_build_function_details(page_info.doc.function_details))80  parts.append(_build_compatibility(page_info.doc.compatibility))81  parts.append('\n\n')82  if page_info.classes:83    parts.append('## Child Classes\n')84    link_template = ('[`class {class_info.short_name}`]'85                     '({class_info.url})\n\n')86    class_links = sorted(87        link_template.format(class_info=class_info)88        for class_info in page_info.classes)89    parts.extend(class_links)90  if page_info.properties:91    parts.append('## Properties\n\n')92    for prop_info in sorted(page_info.properties):93      h3 = '<h3 id="{short_name}"><code>{short_name}</code></h3>\n\n'94      parts.append(h3.format(short_name=prop_info.short_name))95      parts.append(prop_info.doc.docstring)96      parts.append(_build_function_details(prop_info.doc.function_details))97      parts.append(_build_compatibility(prop_info.doc.compatibility))98      parts.append('\n\n')99    parts.append('\n\n')100  if page_info.methods:101    parts.append('## Methods\n\n')102    # Sort the methods list, but make sure constructors come first.103    constructors = ['__init__', '__new__']104    inits = [method for method in page_info.methods105             if method.short_name in constructors]106    others = [method for method in page_info.methods107              if method.short_name not in constructors]108    for method_info in sorted(inits) + sorted(others):109      h3 = ('<h3 id="{short_name}">'110            '<code>{short_name}</code>'111            '</h3>\n\n')112      parts.append(h3.format(**method_info._asdict()))113      if method_info.signature is not None:114        parts.append(_build_signature(method_info, use_full_name=False))115      parts.append(method_info.doc.docstring)116      parts.append(_build_function_details(method_info.doc.function_details))117      parts.append(_build_compatibility(method_info.doc.compatibility))118      parts.append('\n\n')119    parts.append('\n\n')120  if page_info.other_members:121    parts.append('## Class Members\n\n')122    # TODO(markdaoust): Document the value of the members,123    #                   at least for basic types.124    h3 = '<h3 id="{short_name}"><code>{short_name}</code></h3>\n\n'125    others_member_headings = (h3.format(short_name=info.short_name)126                              for info in sorted(page_info.other_members))127    parts.extend(others_member_headings)128  return ''.join(parts)129def _build_module_page(page_info):130  """Given a ClassPageInfo object Return the page as an md string."""131  parts = ['# Module: {full_name}\n\n'.format(full_name=page_info.full_name)]132  if len(page_info.aliases) > 1:133    parts.append('### Aliases:\n\n')134    parts.extend('* Module `%s`\n' % name for name in page_info.aliases)135    parts.append('\n')136  if page_info.defined_in is not None:137    parts.append('\n\n')138    parts.append(str(page_info.defined_in))139  parts.append(page_info.doc.docstring)140  parts.append(_build_compatibility(page_info.doc.compatibility))141  parts.append('\n\n')142  if page_info.modules:143    parts.append('## Modules\n\n')144    template = '[`{short_name}`]({url}) module'145    for item in page_info.modules:146      parts.append(template.format(**item._asdict()))147      if item.doc.brief:148        parts.append(': ' + item.doc.brief)149      parts.append('\n\n')150  if page_info.classes:151    parts.append('## Classes\n\n')152    template = '[`class {short_name}`]({url})'153    for item in page_info.classes:154      parts.append(template.format(**item._asdict()))155      if item.doc.brief:156        parts.append(': ' + item.doc.brief)157      parts.append('\n\n')158  if page_info.functions:159    parts.append('## Functions\n\n')160    template = '[`{short_name}(...)`]({url})'161    for item in page_info.functions:162      parts.append(template.format(**item._asdict()))163      if item.doc.brief:164        parts.append(': ' + item.doc.brief)165      parts.append('\n\n')166  if page_info.other_members:167    # TODO(markdaoust): Document the value of the members,168    #                   at least for basic types.169    parts.append('## Other Members\n\n')170    for item in page_info.other_members:171      parts.append('`{short_name}`\n\n'.format(**item._asdict()))172  return ''.join(parts)173def _build_signature(obj_info, use_full_name=True):174  """Returns a md code block showing the function signature."""175  # Special case tf.range, since it has an optional first argument176  if obj_info.full_name == 'tf.range':177    return (178        '``` python\n'179        "tf.range(limit, delta=1, dtype=None, name='range')\n"180        "tf.range(start, limit, delta=1, dtype=None, name='range')\n"181        '```\n\n')182  parts = ['``` python']183  parts.extend(['@' + dec for dec in obj_info.decorators])184  signature_template = '{name}({sig})'185  if not obj_info.signature:186    sig = ''187  elif len(obj_info.signature) == 1:188    sig = obj_info.signature[0]189  else:190    sig = ',\n'.join('    %s' % sig_item for sig_item in obj_info.signature)191    sig = '\n'+sig+'\n'192  if use_full_name:193    obj_name = obj_info.full_name194  else:195    obj_name = obj_info.short_name196  parts.append(signature_template.format(name=obj_name, sig=sig))197  parts.append('```\n\n')198  return '\n'.join(parts)199def _build_compatibility(compatibility):200  """Return the compatibility section as an md string."""201  parts = []202  sorted_keys = sorted(compatibility.keys())203  for key in sorted_keys:204    value = compatibility[key]205    # Dedent so that it does not trigger markdown code formatting.206    value = textwrap.dedent(value)207    parts.append('\n\n#### %s Compatibility\n%s\n' % (key.title(), value))208  return ''.join(parts)209def _build_function_details(function_details):210  """Return the function details section as an md string."""211  parts = []212  for detail in function_details:213    sub = []214    sub.append('#### ' + detail.keyword + ':\n\n')215    sub.append(textwrap.dedent(detail.header))216    for key, value in detail.items:217      sub.append('* <b>`%s`</b>: %s' % (key, value))218    parts.append(''.join(sub))...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!!
