Best Python code snippet using playwright-python
docker-swarm.py
Source:docker-swarm.py  
...20                                                                  'eu-west-1',21                                                                  'eu-west-2']),22                                   default='us-east-2', show_default=True,23                                   help='The AWS region name where the docker swarm will be deployed.')24def _highlight(x, fg='green'):25    """Write to the console, highlighting the text in green (by default)26    _highlight will also convert any object not a string to a json string27    and write that instead.28    """29    if not isinstance(x, str):30        x = json.dumps(x, sort_keys=True, indent=2)31    click.secho(x, fg=fg)32def _get_stack_manager_instances(stack_name, region):33    """Get the IP addresses of all manager nodes of a docker swarm created by the named cloudformation Stack34    returns a list of manager node instance dicts containing the id and ip of the instance35    """36    try:37        # To get the manager instances, we find the manager autoscaling group and get the38        # instances from it, then look up that instance and get its IP. (The ASG is responsible39        # for creating an new instance if one fails, so that the desired number of managers40        # exist in the swarm, and similarly for the worker nodes)41        cloudformation = boto3.client('cloudformation', region_name=region)42        autoscaling = boto3.client('autoscaling', region_name=region)43        ec2 = boto3.client('ec2', region_name=region)44        # get the Manager ASG ID45        mgr_asg_srd = cloudformation.describe_stack_resource(StackName=stack_name, LogicalResourceId='ManagerAsg')46        mgr_asg_id = mgr_asg_srd['StackResourceDetail']['PhysicalResourceId']47        # get the manager instance IDs48        mgr_instances = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[mgr_asg_id])['AutoScalingGroups'][0]['Instances']49        mgr_instance_ids = [ instance['InstanceId'] for instance in mgr_instances ]50        #click.echo('mgr_instance_ids: {resp}'.format(resp=mgr_instance_ids))51        # get the manager instance IPs52        reservations = ec2.describe_instances(InstanceIds=mgr_instance_ids)['Reservations']53        # extract the instance id and ip from the instances of all returned reservations54        #   Note: a reservation in this situation is a request to start a group of instances55        #         see https://serverfault.com/questions/749118/aws-ec2-what-is-a-reservation-id-exactly-and-what-does-it-represent56        instances = [{'id': inst['InstanceId'],57                      'ip': inst['PublicIpAddress'],58                      'dns': inst['PublicDnsName'],59                     }60                     for res in reservations for inst in res['Instances']]61    except ClientError as e:62        _highlight('{code}: {msg}'.format(code=e.response['Error']['Code'], msg=e.response['Error']['Message']), fg='red')63        instances = []64    return instances65def _get_stack_status(stack_name, region):66    """67    Returns the stack status which will be one of:68        'CREATE_IN_PROGRESS'69        'CREATE_FAILED'70        'CREATE_COMPLETE'71        'ROLLBACK_IN_PROGRESS'72        'ROLLBACK_FAILED'73        'ROLLBACK_COMPLETE'74        'DELETE_IN_PROGRESS'75        'DELETE_FAILED'76        'DELETE_COMPLETE'77        'UPDATE_IN_PROGRESS'78        'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS'79        'UPDATE_COMPLETE'80        'UPDATE_ROLLBACK_IN_PROGRESS'81        'UPDATE_ROLLBACK_FAILED'82        'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS'83        'UPDATE_ROLLBACK_COMPLETE'84        'REVIEW_IN_PROGRESS'85        cloudformation exceptions will be raised, in particular ClientError86        when the given stack_name does not exist.87    """88    cloudformation = boto3.client('cloudformation', region_name=region)89    stack = cloudformation.describe_stacks(StackName=stack_name)['Stacks'][0]90    return stack['StackStatus']91def _start_docker_tunnel(ip, user=None, key_name=None):92    """Start an ssh tunnel to a network location (IP) running docker.93    This function exists so that it can be used by the tunnel command which94    tunnels to a manager of a docker swarm running on an AWS Cloudformation stack95    as well as by the start-docker-tunnel command which can tunnel to an arbitrary96    docker machine.97    The given ip may be an alias defined in the ~/.ssh/config file which specifies98    the host user and actual ip address.99    """100    port = 2374101    # check if we have existing ssh tunnel processes102    kill_tunnels, tunnel_cnt = _kill_existing_tunnels(port, prompt='Do you want to kill the existing tunnel(s)\n'103                                                                   'and create a new one to {ip}? (y/n)'.format(ip=ip))104    if tunnel_cnt > 0:105        if not kill_tunnels:106            _highlight('Leaving existing tunnels and aborting creating the tunnel to {ip}.'.format(ip=ip))107            if 'DOCKER_HOST' in os.environ:108                _highlight('\nYou have DOCKER_HOST exported in your environment:\n  DOCKER_HOST={}'.format(os.environ['DOCKER_HOST']))109            else:110                _highlight('\nYou don\'t have DOCKER_HOST exported in your environment you should:\n'111                           '  export DOCKER_HOST=localhost:{}'.format(port))112            return113    # create the tunnel114    remote_ip = ip115    if user is not None:116        remote_ip = '{user}@{ip}'.format(user=user, ip=ip)117    tunnel_cmd = ['ssh', '-f',118                         '-NL', 'localhost:{port}:/var/run/docker.sock'.format(port=port),119                         '{remote_ip}'.format(remote_ip=remote_ip)]120    # if a key was supplied add it to the command121    if key_name is not None:122        tunnel_cmd[2:2] = ['-i', '{}'.format(key_name)]123    click.echo('Creating the tunnel to {ip} using cmd:\n  {cmd}'.format(cmd=click.style(' '.join(tunnel_cmd), fg='green'), ip=ip))124    ps = subprocess.Popen(tunnel_cmd, start_new_session=True,125                          stdin=subprocess.DEVNULL,126                          stdout=subprocess.DEVNULL,127                          stderr=subprocess.DEVNULL)128    # ps.pid won't be the tunnel process's pid because ssh -f forks129    # see https://stackoverflow.com/questions/4996311/python-subprocess-popen-get-pid-of-the-process-that-forks-a-process130    # which also lets us wait for it to exit so we can check the returncode131    ssh_retcode = ps.wait()132    # if retcode is 0 all is good, otherwise (likely 255) creating the tunnel failed133    if ssh_retcode != 0:134        sys.exit('Creating the tunnel failed (ssh cmd returned {})'.format(ssh_retcode))135    click.echo('\n'.join(136        [137            '\nTo use this tunnel w/ your local docker you will need DOCKER_HOST set',138            'appropriately in your environment. Set it with the command:',139            click.style('  export DOCKER_HOST=localhost:{port}\n'.format(port=port), fg='cyan'),140        ]))141def _get_tunnel_info(port):142    """Get info on any running ssh tunnel processes using the given local port143    Each process gets: { 'pid', 'ip' }144    """145    # [bind_address:]port:remote_socket146    bind_re = re.compile('(?P<bind_address>.*):(?P<port>.*):(?P<remote_socket>.*)')147    # remote_user@remote_ip148    user_ip_re = re.compile('(?:(?P<remote_user>.*)@)?(?P<remote_ip>.*)')149    # This is an example of what the tunnel process(es) info from psutil look like:150    # {'name': 'ssh',151    #  'pid': 26332,152    #  'exe': '/usr/bin/ssh',153    #  'username': 'mjl',154    #  'cmdline': ['ssh', '-f', '-NL', 'localhost:2374:/var/run/docker.sock', 'docker@18.191.218.147']155    # }156    def is_tunnel_proc(pinfo):157        """Test if a process is an ssh tunnel using given port158        """159        if pinfo['name'] != 'ssh':160            return False161        if len(pinfo['cmdline']) < 5:162            return False163        if pinfo['cmdline'][-3] != '-NL':164            return False165        bind = bind_re.fullmatch(pinfo['cmdline'][-2])166        if not (bind and bind.group('port') == str(port)):167            return False168        return True169    tunnel_info = [{'pid': int(p.info['pid']),170                    'ip': user_ip_re.fullmatch(p.info['cmdline'][-1]).group('remote_ip'),171                   }172                   for p in psutil.process_iter(attrs=['pid', 'name', 'cmdline']) if is_tunnel_proc(p.info)]173    return tunnel_info174def _kill(pids):175    """176    """177    for pid in pids:178        _highlight("Killing PID {}".format(pid), fg='green')179        os.kill(pid, signal.SIGKILL)180def _kill_existing_tunnels(port, **kwargs):181    """182    """183    # check if we have existing ssh tunnel processes184    tunnel_info = _get_tunnel_info(port)185    if len(tunnel_info) == 0:186        return True, 0187    tunnel_ref = 'this existing tunnel'188    if len(tunnel_info) > 1:189        _highlight('There are {cnt} existing ssh tunnels! More than one is unexpected!'.format(cnt=len(tunnel_info)))190        tunnel_ref = 'these existing tunnels'191    click.echo('\nFound {} (pid: ip addr):'.format(tunnel_ref))192    _highlight('\n'.join(['  {pid}: {ip}'.format(**info) for info in tunnel_info]))193    if 'prompt' in kwargs:194        prompt = kwargs['prompt']195    else:196        prompt = 'Kill {} (y/n)?'.format(tunnel_ref)197    kill_tunnels = click.prompt(prompt, type=bool)198    if kill_tunnels:199        _kill([tinfo['pid'] for tinfo in tunnel_info])200    return kill_tunnels, len(tunnel_info)201@click.command()202@click_region_option203@click.option('--key', 'key_name', required=True)204@click.option('--manager-count', '-m', type=int, default='3', required=True, help='Number of managers to spin up. Recommended (and default) number is 3 (from Docker for AWS) for reliability.')205@click.option('--manager-type', '-I', default='t2.micro', required=True, help='AWS Instance type for managers. Defaults to t2.micro.')206@click.option('--worker-count', '-w', type=int, default='4', required=True, help='Number of workers to spin up. Defaults to 4')207@click.option('--worker_type', '-i', default='t2.micro', required=True, help='AWS Instance type for workers. Defaults to t2.micro.')208@click.argument('stack_name', required=True)209def create(stack_name, region, key_name, manager_count, manager_type, worker_count, worker_type):210    """Create a CloudFormation stack for a docker swarm.211    A cloudformation stack name can contain only alphanumeric characters (case sensitive) and hyphens.212    It must start with an alphabetic character and cannot be longer than 128 characters.213    """214    # Cloudformation stack template to use. This is the Docker for AWS template (community edition, stable)215    template_url = 'https://editions-us-east-1.s3.amazonaws.com/aws/stable/Docker.tmpl'216    cloudformation = boto3.client('cloudformation', region_name=region)217    click.echo('Creating cloudformation stack:\n'218               '      name: {name} ; region: \'{region}\'\n'219               '       key: {key}\n'220               '  managers: {mgr_cnt} {mgr_type} instance(s)\n'221               '   workers: {wkr_cnt} {wkr_type} instance(s)\n'222               .format(name=stack_name, region=region, key=key_name,223                       mgr_cnt=manager_count, mgr_type=manager_type,224                       wkr_cnt=worker_count, wkr_type=worker_type))225    try:226        response = cloudformation.create_stack(227            StackName=stack_name,228            TemplateURL=template_url,229            Parameters=[230                { 'ParameterKey': 'KeyName',                'ParameterValue': key_name },231                { 'ParameterKey': 'ManagerSize',            'ParameterValue': str(manager_count) },232                { 'ParameterKey': 'ManagerInstanceType',    'ParameterValue': manager_type },233                { 'ParameterKey': 'ClusterSize',            'ParameterValue': str(worker_count) },234                { 'ParameterKey': 'InstanceType',           'ParameterValue': worker_type },235                { 'ParameterKey': 'ManagerDiskSize',        'ParameterValue': '20' },236                { 'ParameterKey': 'ManagerDiskType',        'ParameterValue': 'standard' },237                { 'ParameterKey': 'WorkerDiskSize',         'ParameterValue': '20' },238                { 'ParameterKey': 'WorkerDiskType',         'ParameterValue': 'standard' },239                { 'ParameterKey': 'EnableCloudWatchLogs',   'ParameterValue': 'yes' },240                { 'ParameterKey': 'EnableSystemPrune',      'ParameterValue': 'no' },241            ],242            TimeoutInMinutes=40,243            Capabilities=[ 'CAPABILITY_IAM' ],244            OnFailure='ROLLBACK'245        )246    except ClientError as e:247        _highlight('{code}: {msg}'.format(code=e.response['Error']['Code'], msg=e.response['Error']['Message']), fg='red')248        sys.exit(1)249    # This seems more debugging, not sure what a failure would look like, but I'm guessing250    # there's some exceptions that need catching (this code should be updated when that is251    # discovered)252    #click.echo('create_stack response: {resp}'.format(resp=response))253@click.command()254@click_region_option255@click.argument("stack_name", required=True)256def delete(stack_name, region):257    """Delete the CloudFormation stack(s) with the given name258    """259    cloudformation = boto3.client('cloudformation', region_name=region)260    try:261        stacks = cloudformation.describe_stacks(StackName=stack_name)['Stacks']262        _highlight('Found {cnt} stacks with the name {name}'.format(name=stack_name, cnt=len(stacks)))263        delete_stacks = click.prompt('Are you sure you want to delete these stack(s)? (y/n)', type=bool)264        if delete_stacks:265            for stack in stacks:266                _highlight("Deleting stack {}".format(stack['StackId']))267                cloudformation.delete_stack(StackName=stack['StackId'])268    except ClientError as e:269        _highlight('{code}: {msg}'.format(code=e.response['Error']['Code'], msg=e.response['Error']['Message']), fg='red')270        sys.exit(1)271@click.command()272@click_region_option273@click.argument("stack_name", required=True)274def status(stack_name, region):275    """Get the current status of an existing cloudformation stack276    """277    try:278        status = _get_stack_status(stack_name, region)279        _highlight(status)280    except ClientError as e:281        _highlight('{code}: {msg}'.format(code=e.response['Error']['Code'], msg=e.response['Error']['Message']), fg='red')282        sys.exit(1)283@click.command()284@click_region_option285@click.argument("stack_name", required=True)286def wait_for_complete(stack_name, region):287    """Wait for the stack status to be *_COMPLETE288    Wait for the stack status to become complete (any status289    ending in '_COMPLETE' is considered complete.290    """291    # how long to wait before the next check for complete (seconds)292    period = 60293    try:294        while True:295            status = _get_stack_status(stack_name, region)296            _highlight('{time}: {status}'.format(time=time.strftime('%H:%M:%S'), status=click.style(status, fg='yellow')))297            complete = status.endswith('_COMPLETE')298            if complete:299                break;300            time.sleep(period)301    except ClientError as e:302        # if waiting for delete to complete, then this is expected, but still should be reported specially just in case303        _highlight('{code}: {msg}'.format(code=e.response['Error']['Code'], msg=e.response['Error']['Message']), fg='red')304@click.command()305@click_region_option306@click.argument("stack_name", required=True)307def get_stack_dns(stack_name, region):308    """Gets the public DNS of a stack with the name stack_name309    """310    cloudformation = boto3.client('cloudformation', region_name=region)311    try:312        stack = cloudformation.describe_stacks(StackName=stack_name)['Stacks'][0]313        # The DefaultDNSTarget is one of the outputs from the Docker for AWS template we use to create the stack314        outputs = stack['Outputs']315        for o in outputs:316            if o['OutputKey'] == 'DefaultDNSTarget':317                dns = o['OutputValue']318                click.echo('\n'.join(['The {name} stack\'s public DNS is:'.format(name=stack_name),319                                      click.style('  {dns}\n'.format(dns=dns), fg='green')]))320    except ClientError as e:321        _highlight('{code}: {msg}'.format(code=e.response['Error']['Code'], msg=e.response['Error']['Message']), fg='red')322@click.command()323@click_region_option324@click.argument("stack_name", required=True)325def get_stack_manager_ips(stack_name, region):326    """Get the IP addresses of all manager nodes of a docker swarm created by the named cloudformation Stack327    Retrieves the IP addresses all manager nodes from a CloudFormation328    docker swarm Stack with the given stack_name329    """330    instances = _get_stack_manager_instances(stack_name, region)331    click.echo('manager instances:')332    _highlight('\n'.join(['  {id}: {ip}'.format(**inst) for inst in instances]))333@click.command()334@click_region_option335@click.option('-i', 'index', default=0, help='The index of manager whose ip should be returned. 0 is the index of the 1st manager')336@click.argument("stack_name", required=True)337def get_stack_manager_ip(stack_name, index, region):338    """Get the IP address of the specified manager node of a docker swarm created by the named cloudformation Stack339    Retrieves the IP address of the manager node at the specified index340    from a CloudFormation docker swarm Stack with the given stack_name341    with no extra text, so it can be used in a environment variable.342    """343    try:344        instances = _get_stack_manager_instances(stack_name, region)345        click.echo(instances[index]['ip'])346    except IndexError:347        click.echo('Only {cnt} mananger(s) found, could not get the ip of manager[{i}]'.format(i=index, cnt=len(instances)), err=True)348@click.command()349@click_region_option350@click.argument("stack_name", required=True)351def get_stack_manager_dns(stack_name, region):352    """Get the DNS addresses of all manager nodes of a docker swarm created by the named cloudformation Stack353    Retrieves the DNS addresses all manager nodes from a CloudFormation354    docker swarm Stack with the given stack_name355    """356    instances = _get_stack_manager_instances(stack_name, region)357    click.echo('manager instances:')358    _highlight('\n'.join(['  {id}: {dns}'.format(**inst) for inst in instances]))359@click.command()360@click.option('--key', 'key_name',361              help='The full path to the AWS key file for the docker swarm. If unspecified, '362                   'the key must be associated with the node\'s IP address in ~/.ssh/config')363@click_region_option364@click.argument("stack_name", required=True)365def tunnel(stack_name, region, key_name):366    """Create a tunnel to a docker swarm manager node of a cloudformation stack367    An ssh tunnel to a selected manager node will be created. If there is more368    than one manager node the user will be prompted to select one of them.369    If there is an existing tunnel, the user will be prompted on whether to370    replace it or abort, leaving the existing tunnel alone.371    The tunnel will always be created at localhost port 2374.372    After creating the tunnel, in order for docker to use it the evironment373    variable DOCKER_HOST must be exported pointing to the tunnel.374      export DOCKER_HOST=localhost:2374375    """376    # how to tunnel to the docker swarm manager is described at377    # https://docs.docker.com/docker-for-aws/deploy/#manager-nodes378    # There's no need at this time to allow the user or tunnel port to be configurable379    # so they are hardcoded here. This makes them easily configurable in the future if desired.380    user = 'docker'381    # Check that the stack exists and that create has completed382    try:383        status = _get_stack_status(stack_name, region)384        if status != 'CREATE_COMPLETE':385            _highlight('Stack not ready. Status: {status}'.format(status=status), fg='red')386            _highlight('You can wait for it to be ready using:\n'387                       '  docker-swarm.py wait-for-complete {name} --region={region}\n\n'388                       .format(name=stack_name, region=region))389            return390    except ClientError as e:391        _highlight('{code}: {msg}'.format(code=e.response['Error']['Code'], msg=e.response['Error']['Message']), fg='red')392        return393    mgr_instances = _get_stack_manager_instances(stack_name, region)394    if len(mgr_instances) == 1:395        mgr_ip = mgr_instances[0]['ip']396    else:397        # Ask which manager to tunnel to398        _highlight('Select the manager you want to tunnel to:', fg='white')399        selection_str = '\n'.join(['  {n}) {id}: {ip}'.format(n=n + 1, id=inst['id'], ip=inst['ip'])400                                   for n, inst in enumerate(mgr_instances)])401        _highlight(selection_str)402        sel = click.prompt('Your selection', type=int)403        if sel < 1 or sel > len(mgr_instances):404            mgr_ip = mgr_instances[0]['ip']405        else:406            mgr_ip = mgr_instances[sel - 1]['ip']407    # create the tunnel (will check for existing ssh tunnel processes which we want to408    # happen after selecting the mgr so the user can see the mgr IPs)409    _start_docker_tunnel(mgr_ip, user=user, key_name=key_name)410@click.command()411def kill_tunnel():412    """Kill running tunnels to docker swarm manager nodes413    """414    port = 2374415    kill_tunnel, tunnel_cnt = _kill_existing_tunnels(port)416    if kill_tunnel and tunnel_cnt > 0:417        if 'DOCKER_HOST' in os.environ:418            _highlight('\nYou have DOCKER_HOST exported in your environment:\n'419                       '  DOCKER_HOST={}\n'420                       'You can remove it using:\n'421                       '  unset DOCKER_HOST\n'.format(os.environ['DOCKER_HOST']))422    else:423        # did not kill existing tunnel (ie replied no to prompt)424        if tunnel_cnt > 0:425            sys.exit(1)426@click.command()427@click.option('--key', 'key_name',428              help='The full path to the AWS key file for the docker swarm. If unspecified, '429                   'the key must be associated with the node\'s IP address in ~/.ssh/config')430@click.option('--user', '-u', help='The username for the shell on the remote IP if different from the ssh default')431@click.argument("ip", required=True)432def start_docker_tunnel(ip, user, key_name):...web_element.py
Source:web_element.py  
...29        self.sID = identifier_type  # identifier type, which should be a "identifier" object method30        self.sIDV = identifier_value  # identifier value31        self.sNN = nick_name  # identifier nick name32        33    def _highlight(self, driver, index=None):34        locator = driver.find_elements(by=self.sID,35                                       value=self.sIDV)[index] if index else driver.find_element(by=self.sID,36                                                                                                 value=self.sIDV)37        for i in range(3):38            driver.execute_script("arguments[0].setAttribute('style', arguments[1]);",39                                  locator,40                                  "color: red; border: 2px solid red;")41            time.sleep(0.2)42            driver.execute_script("arguments[0].setAttribute('style', arguments[1]);",43                                  locator,44                                  "")45            time.sleep(0.2)46    def click(self, driver,  elementsClickByIndex_indexNumber = None):47        if elementsClickByIndex_indexNumber == None:48            '''Click a Web Element'''49            if self._if_exist(driver): # Check Existence50                if settings.DEMO:51                    self._highlight(driver)52                WebDriverWait(driver,settings.T_SHORT).until(lambda x: x.find_element(by=self.sID, value=self.sIDV).is_displayed())53                driver.find_element(by=self.sID, value=self.sIDV).click()54                time.sleep(settings.T_SHORT)55                prt(3, 'Click %s Button' % self.sNN)56            else:57                prt(3, 'Element %s is NOT found!' % self.sNN)58        else:59            '''Click A Element from Lots of Matching Elements by IndexNumber'''60            if self._if_exist(driver): # Check Existence61                try:62                    if settings.DEMO:63                        self._highlight(driver, elementsClickByIndex_indexNumber - 1)64                    driver.find_elements(by=self.sID, value=self.sIDV)[elementsClickByIndex_indexNumber - 1].click()65                    prt(3, 'Click the %s Element from "%s"' % (formatedStrNumber(elementsClickByIndex_indexNumber), self.sNN))66                    time.sleep(settings.T_SHORT)67                except Exception as e:68                    prt(3, str(e))69            else:70                prt(3, 'Element %s is NOT found!' % self.sNN)71        72    def db_click(self, driver):73        '''Double Click a Web Element'''74        if self._if_exist(driver):  # Check Existence75            if settings.DEMO:76                self._highlight(driver)77            driver.find_element(by=self.sID, value=self.sIDV).double_click()78            prt(3, 'Double Click %s Button' % self.sNN)79        else:80            prt(3, 'Element %s is NOT found!' % self.sNN)81            82    def if_exist(self, driver, elementsExistByText_textValue = None, waitTime = settings.T_LONG):83        ''' Check the Existence of a Web Element / Lots of Matching Web Elements'''84        if elementsExistByText_textValue == None:85            '''Check the Existence of a Web Element'''86            try:87                WebDriverWait(driver,waitTime).until(lambda x: x.find_element(by=self.sID, value=self.sIDV))88                if settings.DEMO:89                    self._highlight(driver)90                prt(3, 'Check Existence of %s: Existed!' % self.sNN)91                return True92            except:93                prt(3, 'Check Existence of %s: NOT Existed!' % self.sNN)94                return False95        else:96            '''Find if an Element is Existed in Lots of Matching Elemets'''97            prt(3, 'Check Existence of Text Value "%s" in Elemets "%s"' % (elementsExistByText_textValue, self.sNN))98            if self._if_exist(driver): # Check Existence99                index = 1 # initiate looping value100                for locator in driver.find_elements(self.sID, value=self.sIDV):101                    if locator.text == elementsExistByText_textValue:102                        if settings.DEMO:103                            self._highlight(driver, index - 1)104                        return index105                    else:106                        index += 1107                return 0108            else:109                return 0110            111           112    def _if_exist(self, driver):113        '''Check Web Element Existence, Private Use Only! '''114        try:115            WebDriverWait(driver, settings.T_LONG).until(lambda x: x.find_element(by=self.sID, value=self.sIDV))116            return True117        except:118            return False119        120    def is_enabled(self, driver):121        '''Click if the Web Element is enabled'''122        if self._if_exist(driver):  # Check Existence123            if settings.DEMO:124                self._highlight(driver)125            prt(3, 'Check if Element %s is enabled' % self.sNN)126            if self.__is_visible(driver):127                return driver.find_element(by=self.sID, value=self.sIDV).is_enabled()128            else:129                return False    130        else:131            prt(3, 'Element %s is NOT found!' % self.sNN)132            return False133    134    def is_visible(self, driver):135        '''Click if a Web Element is visible'''136        if self._if_exist(driver):  # Check Existence137            if settings.DEMO:138                self._highlight(driver)139            prt(3, 'Check if Element %s is visible' % self.sNN)140            return driver.find_element(by=self.sID, value=self.sIDV).is_displayed()141        else:142            prt(3, 'Element %s is NOT found!' % self.sNN)143            return False144    145    def __is_visible(self, driver):146        '''Click if a Web Element is visible'''147        if self._if_exist(driver):  # Check Existence148            if settings.DEMO:149                self._highlight(driver)150            return driver.find_element(by=self.sID, value=self.sIDV).is_displayed()151        else:152            return False153    154    def get_text(self, driver, elementsGetTextByIndex_IndexNumber = None):155        import datetime156        if not elementsGetTextByIndex_IndexNumber:157            '''Get the Text Value From a Web Element'''158            if self._if_exist(driver) == True: # Check Existence159                if settings.DEMO:160                    self._highlight(driver)161                prt(3, 'Get Text Value from Element: %s @ %s' % (self.sNN, datetime.datetime.now().strftime("%m-%d %H:%M:%S.%f")))162                return driver.find_element(by=self.sID, value=self.sIDV).text163            else:164                prt(3, 'Element %s is NOT found!' % self.sNN)165                return ''166        else:167            '''Get the Text Value FromFrom Matching Elements'''168            if self._if_exist(driver): # Check Existence169                if settings.DEMO:170                    self._highlight(driver, elementsGetTextByIndex_IndexNumber - 1)171                prt(3, 'Get the %s Text Value from: %s' % (formatedStrNumber(elementsGetTextByIndex_IndexNumber), self.sNN))172                return driver.find_elements(self.sID, value=self.sIDV)[elementsGetTextByIndex_IndexNumber + 1].text173            else:174                prt(3, 'Element %s is NOT found!' % self.sNN)175                return ''176            177    def _get_text(self, driver, elementsGetTextByIndex_IndexNumber=None):178        if not elementsGetTextByIndex_IndexNumber:179            '''Get the Text Value From a Web Element'''180            if self._if_exist(driver): # Check Existence181                if settings.DEMO:182                    self._highlight(driver)183                return driver.find_element(by=self.sID, value=self.sIDV).text184            else:185                return ''186        else:187            '''Get the Text Value FromFrom Matching Elements'''188            if self._if_exist(driver): # Check Existence189                if settings.DEMO:190                    self._highlight(driver, elementsGetTextByIndex_IndexNumber - 1)191                return driver.find_elements(self.sID, value=self.sIDV)[elementsGetTextByIndex_IndexNumber + 1].text192            else:193                return ''194              195    def get_texts(self, driver):196        '''197        Note: This is only used for elemets not for single element198        '''199        if self._if_exist(driver): # Check Existence200            if settings.DEMO:201                    self._highlight(driver)202            prt(3, 'Get All Texts From %s' % self.sNN)203            ret = []204            for element in driver.find_elements(self.sID, value=self.sIDV):205                ret.append(element.text)206            return ret207        else:208            prt(3, 'Element %s is NOT found!' % self.sNN)209            return ''210        211    def get_value(self, driver, attribute, elementsGetTextByIndex_IndexNumber = None):212        if not elementsGetTextByIndex_IndexNumber:213            '''Get the Text Value From a Web Element'''214            if self._if_exist(driver): # Check Existence215                if settings.DEMO:216                    self._highlight(driver)217                prt(3, "Get Text's %s from Element: %s" % (attribute, self.sNN))218                return driver.find_element(by=self.sID, value=self.sIDV).get_attribute(attribute)219            else:220                prt(3, 'Element %s is NOT found!' % self.sNN)221                return ''222        else:223            '''Get the Text Value FromFrom Matching Elements'''224            if self._if_exist(driver): # Check Existence225                if settings.DEMO:226                    self._highlight(driver, elementsGetTextByIndex_IndexNumber - 1)227                prt(3, "Get the %s Text's %s from: %s" % (formatedStrNumber(elementsGetTextByIndex_IndexNumber), attribute, self.sNN))228                return driver.find_element(by=self.sID, value=self.sIDV)[elementsGetTextByIndex_IndexNumber + 1].get_attribute(attribute)229            else:230                prt(3, 'Element %s is NOT found!' % self.sNN)231                return ''232    233    def get_values(self, driver, attribute):234        '''Get the Text Value From a Web Element'''235        if self._if_exist(driver): # Check Existence236            if settings.DEMO:237                self._highlight(driver)238            ret = []239            for elem in driver.find_elements(by=self.sID,value=self.sIDV):240                ret.append(elem.get_attribute(attribute))241            prt(3, "Get All Value from: %s" % (self.sNN))242            return ret243        else:244            prt(3, 'Element %s is NOT found!' % self.sNN)245            return ''246    def get_elements(self, driver):247        if self._if_exist(driver): # Check Existence248            if settings.DEMO:249                self._highlight(driver)250            return driver.find_elements(by=self.sID,value=self.sIDV)251        else:252            prt(3, 'Element %s is NOT found!' % self.sNN)253            return ''254           255    def wait_until_text_present(self, driver, textWait, waitTime=settings.T_LONG):256        if self._if_exist(driver): # Check Existence257            if settings.DEMO:258                self._highlight(driver)259            prt(3, 'Wait for Text "%s" to be Present in %s' % (textWait, self.sNN))260            261            for i in range(waitTime):262                if self._get_text(driver).find(textWait) >= 0:263                    return True264                else:265                    time.sleep(1)266            return False267        else:268            prt(3, 'Element %s is NOT found!' % self.sNN)269            return False270    def wait_until_value_present(self, driver, attribute, textWait, waitTime=settings.T_LONG):271        if self._if_exist(driver): # Check Existence272            if settings.DEMO:273                self._highlight(driver)274            prt(3, 'Wait for Text "%s" to be Present in %s' % (textWait, self.sNN))275            276            for i in range(waitTime / 4):277                if self.get_value(driver, attribute).find(textWait) >= 0:278                    return True279                else:280                    time.sleep(15)281                    282            return False283        else:284            prt(3, 'Element %s is NOT found!' % self.sNN)285            return False286        287    def mouse_over(self, driver):288        if self._if_exist(driver):  # Check Existence289            if settings.DEMO:290                self._highlight(driver)291            prt(3, 'Mouse over on: %s' % (self.sNN))292            293            elemToHover = driver.find_element(by=self.sID, value=self.sIDV)294            hover = ActionChains(driver).move_to_element(elemToHover)295            hover.perform()296            297        else:298            prt(3, 'Element %s is NOT found!' % self.sNN)299            return False300        301    def send_ESC_key(self, driver):302        if self._if_exist(driver): # Check Existence303            if settings.DEMO:304                self._highlight(driver)305            prt(3, 'Send Keys to: %s' % (self.sNN))306            307            elemToSend = driver.find_element(by=self.sID, value=self.sIDV)308            key = ActionChains(driver).send_keys_to_element(elemToSend, u'\ue00c')309            key.perform()310            311        else:312            prt(3, 'Element %s is NOT found!' % self.sNN)313            return False314 315    def send_key(self, driver, key):316        317        if self._if_exist(driver): # Check Existence318            if settings.DEMO:319                self._highlight(driver)320            prt(3, 'Send Keys to: %s' % (self.sNN))321            322            elemToSend = driver.find_element(by=self.sID, value=self.sIDV)323            key = ActionChains(driver).send_keys_to_element(elemToSend, key)324            key.perform()325            326        else:327            prt(3, 'Element %s is NOT found!' % self.sNN)328            return False329class WebCheckbox(_BaseElement):330    def __init__(self, identityMethod, identityValue, nickName):331        _BaseElement.__init__(self, identityMethod, identityValue, nickName)332    333    def is_checked(self, driver):334        '''Check if the Checkbox is checked'''335        if self._if_exist(driver) == True: # Check Existence336            if settings.DEMO:337                self._highlight(driver)338            prt(3, 'Check if Element %s is checked' % self.sNN)339            return driver.find_element(by=self.sID, value=self.sIDV).is_selected()340        else:341            prt(3, 'Element %s is NOT found!' % self.sNN)342            return False343    344    def check(self, driver):345        '''Set "ON" to a Checkbox'''346        if self._if_exist(driver) == True: # Check Existence347            if settings.DEMO:348                self._highlight(driver)349            if driver.find_element(by=self.sID, value=self.sIDV).is_selected() == True:350                pass351            else:352                driver.find_element(by=self.sID, value=self.sIDV).click()353            prt(3, 'Set Checkbox %s to "ON" (checked)' % self.sNN)354        else:355            prt(3, 'Element %s is NOT found!' % self.sNN)356    357    def check_all(self,driver):358        '''Set "ON" to a Checkbox'''359        if self._if_exist(driver) == True: # Check Existence360            if settings.DEMO:361                self._highlight(driver)362            matchItems = driver.find_elements(by=self.sID, value=self.sIDV)363            if len(matchItems) > 0:364                for item in matchItems:365                    if item.is_selected() == True:366                        pass367                    else:368                        item.click()369            prt(3, 'Set Checkbox %s to "ON" (checked)' % self.sNN)370        else:371            prt(3, 'Element %s is NOT found!' % self.sNN)        372    373    def uncheck(self, driver):374        '''Set "OFF" to a Checkbox'''375        if self._if_exist(driver) == True: # Check Existence376            if settings.DEMO:377                self._highlight(driver)378            if driver.find_element(by=self.sID, value=self.sIDV).is_selected() == True:379                driver.find_element(by=self.sID, value=self.sIDV).click()380            else:381                pass382            prt(3, 'Set Checkbox %s to "OFF" (unchecked)' % self.sNN)383        else:384            prt(3, 'Element %s is NOT found!' % self.sNN)385        386    def uncheck_all(self, driver):387        '''Set "OFF" to a Checkbox'''388        if self._if_exist(driver) == True: # Check Existence389            if settings.DEMO:390                self._highlight(driver)391                392            matchItems = driver.find_elements(by=self.sID, value=self.sIDV)393            if len(matchItems) > 0:394                for item in matchItems:395                    if item.is_selected() == True:396                        item.click()397                    else:398                        pass399            prt(3, 'Set Checkbox %s to "OFF" (unchecked)' % self.sNN)400        else:401            prt(3, 'Element %s is NOT found!' % self.sNN)402    403class WebEdit(_BaseElement):404    def __init__(self, identityMethod, identityValue, nickName):405        _BaseElement.__init__(self, identityMethod, identityValue, nickName)406        407    def set_txt(self, driver, text):408        ''' Set Text to a Editbox '''409        if self._if_exist(driver) == True: # Check Existence410            if settings.DEMO:411                self._highlight(driver)412            driver.find_element(by=self.sID, value=self.sIDV).clear()413            driver.find_element(by=self.sID, value=self.sIDV).send_keys(text)414#            if self.sID == 'id':415#                driver.find_element_by_id(self.sIDV).clear()416#                driver.find_element_by_id(self.sIDV).send_keys(text)417#            elif self.sID == 'name':418#                driver.find_element_by_name(self.sIDV).clear()419#                driver.find_element_by_name(self.sIDV).send_keys(text)420            prt(3, 'Set %s as: %s' % (self.sNN, text))421        else:422            prt(3, 'Element %s is NOT found!' % self.sNN)    423class WebButton(_BaseElement):424    def __init__(self, identityMethod, identityValue, nickName):425        _BaseElement.__init__(self, identityMethod, identityValue, nickName)426    427    def submit(self, driver):428        ''' Submit a Web Form'''429        if self._if_exist(driver) == True: # Check Existence430            if settings.DEMO:431                self._highlight(driver)432            driver.find_element(by=self.sID, value=self.sIDV).submit()433            prt(3, 'Click %s Button' % self.sNN)434        else:435            prt(3, 'Element %s is NOT found!' % self.sNN)436class WebList(_BaseElement):437    438    def __init__(self, identityMethod, identityValue, nickName):439        _BaseElement.__init__(self, identityMethod, identityValue, nickName)440    441    def select_by_index(self, driver, indexNumber):442        '''Select an Item from List by Index Number'''443        if self._if_exist(driver) == True: # Check Existence444            if settings.DEMO:445                self._highlight(driver)446            selectObj = Select(driver.find_element(by=self.sID, value=self.sIDV))447            selectorSize = selectObj.size()448            if indexNumber > selectorSize:449                pass450            else:451                selectObj.select_by_index(self, indexNumber)452            prt(3, 'Select %s to by index number: %d' % self.sNN, indexNumber)453        else:454            prt(3, 'Element %s is NOT found!' % self.sNN)455        456    def select_by_text(self, driver, text):457        '''Select an Item from List by Text'''458        if self._if_exist(driver) == True: # Check Existence459            if settings.DEMO:460                self._highlight(driver)461            selectObj = Select(driver.find_element(by=self.sID, value=self.sIDV))462            selectObj.select_by_visible_text(text)463            prt(3, 'Select %s to by visible text: %s' % (self.sNN, text))464        else:465            prt(3, 'Element %s is NOT found!' % self.sNN)466    467    def get_current_selection(self, driver):468        '''Get Current Selection from a List'''469        if self._if_exist(driver) == True: # Check Existence470            try:471                selectObj = Select(driver.find_element(by=self.sID, value=self.sIDV))472                prt(3, "Get Selector %s's Current Selected Option" % self.sNN)473                if settings.DEMO:474                    self._highlight(driver)475                return selectObj.first_selected_option().getText()476            except:477                prt(3, "Get Selector %s's Current Selected Option, But No Item Seleted" % self.sNN)478                return ''479        else:480            prt(3, 'Element %s is NOT found!' % self.sNN)481        482    def get_all_options(self, driver):483        '''Get all options from a List, return value is a Python List'''484        if self._if_exist(driver) == True: # Check Existence485            prt(3, "Get Selector %s's Current Selected Option" % self.sNN)486            selectObj = Select(driver.find_element(by=self.sID, value=self.sIDV))487            if settings.DEMO:488                self._highlight(driver)489            return selectObj.options()490                491        else:492            prt(3, 'Element %s is NOT found!' % self.sNN)493            return []494    495class WebLabel(_BaseElement):496    def __init__(self, identityMethod, identityValue, nickName):497        _BaseElement.__init__(self, identityMethod, identityValue, nickName)498class WebLink(_BaseElement):499    def __init__(self, identityMethod, identityValue, nickName):500        _BaseElement.__init__(self, identityMethod, identityValue, nickName)501class WebTable(_BaseElement):502    '''503    To By Done!!!504    '''505    def __init__(self, identityMethod, identityValue, nickName):506        _BaseElement.__init__(self, identityMethod, identityValue, nickName)  507        508class WebItem(_BaseElement):509    def __init__(self, identityMethod, identityValue, nickName):510        _BaseElement.__init__(self, identityMethod, identityValue, nickName)511        512class WebGeneral(_BaseElement):513    def __init__(self, identityMethod, identityValue, nickName):514        _BaseElement.__init__(self, identityMethod, identityValue, nickName)515        516class WebIframe(_BaseElement):517    def __init__(self, identityMethod, identityValue, nickName):518        _BaseElement.__init__(self, identityMethod, identityValue, nickName)519        520class WebPicture(_BaseElement):521    def __init__(self, identityMethod, identityValue, nickName):522        _BaseElement.__init__(self, identityMethod, identityValue, nickName)523        524    def get_pic_url(self, driver):525        if self._if_exist(driver) == True: # Check Existence526            prt(3, "Get URL of Picture: %s" % self.sNN)527            try:528                if settings.DEMO:529                    self._highlight(driver)530                selectObj = driver.find_element(by=self.sID, value=self.sIDV).get_attribute('src')531                return selectObj532            except:533                return ''534        else:...highlight.py
Source:highlight.py  
1# This file was automatically generated by SWIG (http://www.swig.org).2# Version 1.3.333#4# Don't modify this file, modify the SWIG interface instead.5# This file is compatible with both classic and new-style classes.6import _highlight7import new8new_instancemethod = new.instancemethod9try:10    _swig_property = property11except NameError:12    pass # Python < 2.2 doesn't have 'property'.13def _swig_setattr_nondynamic(self,class_type,name,value,static=1):14    if (name == "thisown"): return self.this.own(value)15    if (name == "this"):16        if type(value).__name__ == 'PySwigObject':17            self.__dict__[name] = value18            return19    method = class_type.__swig_setmethods__.get(name,None)20    if method: return method(self,value)21    if (not static) or hasattr(self,name):22        self.__dict__[name] = value23    else:24        raise AttributeError("You cannot add attributes to %s" % self)25def _swig_setattr(self,class_type,name,value):26    return _swig_setattr_nondynamic(self,class_type,name,value,0)27def _swig_getattr(self,class_type,name):28    if (name == "thisown"): return self.this.own()29    method = class_type.__swig_getmethods__.get(name,None)30    if method: return method(self)31    raise AttributeError,name32def _swig_repr(self):33    try: strthis = "proxy of " + self.this.__repr__()34    except: strthis = ""35    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)36import types37try:38    _object = types.ObjectType39    _newclass = 140except AttributeError:41    class _object : pass42    _newclass = 043del types44STANDARD = _highlight.STANDARD45STRING = _highlight.STRING46NUMBER = _highlight.NUMBER47SL_COMMENT = _highlight.SL_COMMENT48ML_COMMENT = _highlight.ML_COMMENT49ESC_CHAR = _highlight.ESC_CHAR50DIRECTIVE = _highlight.DIRECTIVE51DIRECTIVE_STRING = _highlight.DIRECTIVE_STRING52LINENUMBER = _highlight.LINENUMBER53SYMBOL = _highlight.SYMBOL54KEYWORD = _highlight.KEYWORD55STRING_END = _highlight.STRING_END56NUMBER_END = _highlight.NUMBER_END57SL_COMMENT_END = _highlight.SL_COMMENT_END58ML_COMMENT_END = _highlight.ML_COMMENT_END59ESC_CHAR_END = _highlight.ESC_CHAR_END60DIRECTIVE_END = _highlight.DIRECTIVE_END61SYMBOL_END = _highlight.SYMBOL_END62KEYWORD_END = _highlight.KEYWORD_END63IDENTIFIER_BEGIN = _highlight.IDENTIFIER_BEGIN64IDENTIFIER_END = _highlight.IDENTIFIER_END65_UNKNOWN = _highlight._UNKNOWN66_EOL = _highlight._EOL67_EOF = _highlight._EOF68_WS = _highlight._WS69PARSE_OK = _highlight.PARSE_OK70BAD_INPUT = _highlight.BAD_INPUT71BAD_OUTPUT = _highlight.BAD_OUTPUT72BAD_STYLE = _highlight.BAD_STYLE73BAD_BINARY = _highlight.BAD_BINARY74WRAP_DISABLED = _highlight.WRAP_DISABLED75WRAP_SIMPLE = _highlight.WRAP_SIMPLE76WRAP_DEFAULT = _highlight.WRAP_DEFAULT77LOAD_FAILED = _highlight.LOAD_FAILED78LOAD_NEW = _highlight.LOAD_NEW79LOAD_NONE = _highlight.LOAD_NONE80HTML = _highlight.HTML81XHTML = _highlight.XHTML82TEX = _highlight.TEX83LATEX = _highlight.LATEX84RTF = _highlight.RTF85XML = _highlight.XML86ANSI = _highlight.ANSI87XTERM256 = _highlight.XTERM25688HTML32 = _highlight.HTML3289CASE_UNCHANGED = _highlight.CASE_UNCHANGED90CASE_LOWER = _highlight.CASE_LOWER91CASE_UPPER = _highlight.CASE_UPPER92CASE_CAPITALIZE = _highlight.CASE_CAPITALIZE93class LanguageDefinition(_object):94    __swig_setmethods__ = {}95    __setattr__ = lambda self, name, value: _swig_setattr(self, LanguageDefinition, name, value)96    __swig_getmethods__ = {}97    __getattr__ = lambda self, name: _swig_getattr(self, LanguageDefinition, name)98    __repr__ = _swig_repr99    def __init__(self, *args): 100        this = _highlight.new_LanguageDefinition(*args)101        try: self.this.append(this)102        except: self.this = this103    __swig_destroy__ = _highlight.delete_LanguageDefinition104    __del__ = lambda self : None;105    def getSymbolString(*args): return _highlight.LanguageDefinition_getSymbolString(*args)106    def getRawStringPrefix(*args): return _highlight.LanguageDefinition_getRawStringPrefix(*args)107    def getContinuationChar(*args): return _highlight.LanguageDefinition_getContinuationChar(*args)108    def getSyntaxHighlight(*args): return _highlight.LanguageDefinition_getSyntaxHighlight(*args)109    def isIgnoreCase(*args): return _highlight.LanguageDefinition_isIgnoreCase(*args)110    def isKeyword(*args): return _highlight.LanguageDefinition_isKeyword(*args)111    def load(*args): return _highlight.LanguageDefinition_load(*args)112    def isVHDL(*args): return _highlight.LanguageDefinition_isVHDL(*args)113    def allowNestedMLComments(*args): return _highlight.LanguageDefinition_allowNestedMLComments(*args)114    def highlightingDisabled(*args): return _highlight.LanguageDefinition_highlightingDisabled(*args)115    def needsReload(*args): return _highlight.LanguageDefinition_needsReload(*args)116    def enableReformatting(*args): return _highlight.LanguageDefinition_enableReformatting(*args)117    def allowExtEscSeq(*args): return _highlight.LanguageDefinition_allowExtEscSeq(*args)118    def getKeywords(*args): return _highlight.LanguageDefinition_getKeywords(*args)119    def getKeywordClasses(*args): return _highlight.LanguageDefinition_getKeywordClasses(*args)120    def getRegexElements(*args): return _highlight.LanguageDefinition_getRegexElements(*args)121    def getDescription(*args): return _highlight.LanguageDefinition_getDescription(*args)122    def delimiterIsDistinct(*args): return _highlight.LanguageDefinition_delimiterIsDistinct(*args)123    def getDelimiterPairID(*args): return _highlight.LanguageDefinition_getDelimiterPairID(*args)124LanguageDefinition_swigregister = _highlight.LanguageDefinition_swigregister125LanguageDefinition_swigregister(LanguageDefinition)126class RegexElement(_object):127    __swig_setmethods__ = {}128    __setattr__ = lambda self, name, value: _swig_setattr(self, RegexElement, name, value)129    __swig_getmethods__ = {}130    __getattr__ = lambda self, name: _swig_getattr(self, RegexElement, name)131    __repr__ = _swig_repr132    def __init__(self, *args): 133        this = _highlight.new_RegexElement(*args)134        try: self.this.append(this)135        except: self.this = this136    __swig_destroy__ = _highlight.delete_RegexElement137    __del__ = lambda self : None;138    __swig_setmethods__["open"] = _highlight.RegexElement_open_set139    __swig_getmethods__["open"] = _highlight.RegexElement_open_get140    if _newclass:open = _swig_property(_highlight.RegexElement_open_get, _highlight.RegexElement_open_set)141    __swig_setmethods__["end"] = _highlight.RegexElement_end_set142    __swig_getmethods__["end"] = _highlight.RegexElement_end_get143    if _newclass:end = _swig_property(_highlight.RegexElement_end_get, _highlight.RegexElement_end_set)144    __swig_setmethods__["rePattern"] = _highlight.RegexElement_rePattern_set145    __swig_getmethods__["rePattern"] = _highlight.RegexElement_rePattern_get146    if _newclass:rePattern = _swig_property(_highlight.RegexElement_rePattern_get, _highlight.RegexElement_rePattern_set)147    __swig_setmethods__["kwClass"] = _highlight.RegexElement_kwClass_set148    __swig_getmethods__["kwClass"] = _highlight.RegexElement_kwClass_get149    if _newclass:kwClass = _swig_property(_highlight.RegexElement_kwClass_get, _highlight.RegexElement_kwClass_set)150    __swig_setmethods__["groupID"] = _highlight.RegexElement_groupID_set151    __swig_getmethods__["groupID"] = _highlight.RegexElement_groupID_get152    if _newclass:groupID = _swig_property(_highlight.RegexElement_groupID_get, _highlight.RegexElement_groupID_set)153RegexElement_swigregister = _highlight.RegexElement_swigregister154RegexElement_swigregister(RegexElement)155class RegexDef(_object):156    __swig_setmethods__ = {}157    __setattr__ = lambda self, name, value: _swig_setattr(self, RegexDef, name, value)158    __swig_getmethods__ = {}159    __getattr__ = lambda self, name: _swig_getattr(self, RegexDef, name)160    __repr__ = _swig_repr161    def __init__(self, *args): 162        this = _highlight.new_RegexDef(*args)163        try: self.this.append(this)164        except: self.this = this165    __swig_setmethods__["reString"] = _highlight.RegexDef_reString_set166    __swig_getmethods__["reString"] = _highlight.RegexDef_reString_get167    if _newclass:reString = _swig_property(_highlight.RegexDef_reString_get, _highlight.RegexDef_reString_set)168    __swig_setmethods__["capturingGroup"] = _highlight.RegexDef_capturingGroup_set169    __swig_getmethods__["capturingGroup"] = _highlight.RegexDef_capturingGroup_get170    if _newclass:capturingGroup = _swig_property(_highlight.RegexDef_capturingGroup_get, _highlight.RegexDef_capturingGroup_set)171    __swig_destroy__ = _highlight.delete_RegexDef172    __del__ = lambda self : None;173RegexDef_swigregister = _highlight.RegexDef_swigregister174RegexDef_swigregister(RegexDef)175class CodeGenerator(_object):176    __swig_setmethods__ = {}177    __setattr__ = lambda self, name, value: _swig_setattr(self, CodeGenerator, name, value)178    __swig_getmethods__ = {}179    __getattr__ = lambda self, name: _swig_getattr(self, CodeGenerator, name)180    def __init__(self): raise AttributeError, "No constructor defined"181    __repr__ = _swig_repr182    __swig_destroy__ = _highlight.delete_CodeGenerator183    __del__ = lambda self : None;184    __swig_getmethods__["getInstance"] = lambda x: _highlight.CodeGenerator_getInstance185    if _newclass:getInstance = staticmethod(_highlight.CodeGenerator_getInstance)186    __swig_getmethods__["deleteInstance"] = lambda x: _highlight.CodeGenerator_deleteInstance187    if _newclass:deleteInstance = staticmethod(_highlight.CodeGenerator_deleteInstance)188    def generateFile(*args): return _highlight.CodeGenerator_generateFile(*args)189    def generateString(*args): return _highlight.CodeGenerator_generateString(*args)190    def generateStringFromFile(*args): return _highlight.CodeGenerator_generateStringFromFile(*args)191    def generateCString(*args): return _highlight.CodeGenerator_generateCString(*args)192    def initTheme(*args): return _highlight.CodeGenerator_initTheme(*args)193    def styleFound(*args): return _highlight.CodeGenerator_styleFound(*args)194    def formattingDisabled(*args): return _highlight.CodeGenerator_formattingDisabled(*args)195    def formattingIsPossible(*args): return _highlight.CodeGenerator_formattingIsPossible(*args)196    def initLanguage(*args): return _highlight.CodeGenerator_initLanguage(*args)197    def getLanguage(*args): return _highlight.CodeGenerator_getLanguage(*args)198    def setPrintLineNumbers(*args): return _highlight.CodeGenerator_setPrintLineNumbers(*args)199    def getPrintLineNumbers(*args): return _highlight.CodeGenerator_getPrintLineNumbers(*args)200    def setPrintZeroes(*args): return _highlight.CodeGenerator_setPrintZeroes(*args)201    def getPrintZeroes(*args): return _highlight.CodeGenerator_getPrintZeroes(*args)202    def setFragmentCode(*args): return _highlight.CodeGenerator_setFragmentCode(*args)203    def setLineNumberWidth(*args): return _highlight.CodeGenerator_setLineNumberWidth(*args)204    def getLineNumberWidth(*args): return _highlight.CodeGenerator_getLineNumberWidth(*args)205    def getFragmentCode(*args): return _highlight.CodeGenerator_getFragmentCode(*args)206    def setValidateInput(*args): return _highlight.CodeGenerator_setValidateInput(*args)207    def getValidateInput(*args): return _highlight.CodeGenerator_getValidateInput(*args)208    def getStyleName(*args): return _highlight.CodeGenerator_getStyleName(*args)209    def setBaseFont(*args): return _highlight.CodeGenerator_setBaseFont(*args)210    def getBaseFont(*args): return _highlight.CodeGenerator_getBaseFont(*args)211    def setBaseFontSize(*args): return _highlight.CodeGenerator_setBaseFontSize(*args)212    def getBaseFontSize(*args): return _highlight.CodeGenerator_getBaseFontSize(*args)213    def setPreformatting(*args): return _highlight.CodeGenerator_setPreformatting(*args)214    def setIncludeStyle(*args): return _highlight.CodeGenerator_setIncludeStyle(*args)215    def setSpecialOptions(*args): return _highlight.CodeGenerator_setSpecialOptions(*args)216    def printExternalStyle(*args): return _highlight.CodeGenerator_printExternalStyle(*args)217    def printIndexFile(*args): return _highlight.CodeGenerator_printIndexFile(*args)218    def initIndentationScheme(*args): return _highlight.CodeGenerator_initIndentationScheme(*args)219    def getFormatter(*args): return _highlight.CodeGenerator_getFormatter(*args)220    def setStyleInputPath(*args): return _highlight.CodeGenerator_setStyleInputPath(*args)221    def setStyleOutputPath(*args): return _highlight.CodeGenerator_setStyleOutputPath(*args)222    def setEncoding(*args): return _highlight.CodeGenerator_setEncoding(*args)223    def getStyleInputPath(*args): return _highlight.CodeGenerator_getStyleInputPath(*args)224    def getStyleOutputPath(*args): return _highlight.CodeGenerator_getStyleOutputPath(*args)225    def setTitle(*args): return _highlight.CodeGenerator_setTitle(*args)226    def getTitle(*args): return _highlight.CodeGenerator_getTitle(*args)227    def setHTMLAnchorPrefix(*args): return _highlight.CodeGenerator_setHTMLAnchorPrefix(*args)228    def setMaxInputLineCnt(*args): return _highlight.CodeGenerator_setMaxInputLineCnt(*args)229    def hasWhiteBGColour(*args): return _highlight.CodeGenerator_hasWhiteBGColour(*args)230    def setKeyWordCase(*args): return _highlight.CodeGenerator_setKeyWordCase(*args)231    def addMarkedLine(*args): return _highlight.CodeGenerator_addMarkedLine(*args)232CodeGenerator_swigregister = _highlight.CodeGenerator_swigregister233CodeGenerator_swigregister(CodeGenerator)234CodeGenerator_getInstance = _highlight.CodeGenerator_getInstance235CodeGenerator_deleteInstance = _highlight.CodeGenerator_deleteInstance236class ReGroup(_object):237    __swig_setmethods__ = {}238    __setattr__ = lambda self, name, value: _swig_setattr(self, ReGroup, name, value)239    __swig_getmethods__ = {}240    __getattr__ = lambda self, name: _swig_getattr(self, ReGroup, name)241    __repr__ = _swig_repr242    def __init__(self, *args): 243        this = _highlight.new_ReGroup(*args)244        try: self.this.append(this)245        except: self.this = this246    __swig_destroy__ = _highlight.delete_ReGroup247    __del__ = lambda self : None;248    __swig_setmethods__["length"] = _highlight.ReGroup_length_set249    __swig_getmethods__["length"] = _highlight.ReGroup_length_get250    if _newclass:length = _swig_property(_highlight.ReGroup_length_get, _highlight.ReGroup_length_set)251    __swig_setmethods__["state"] = _highlight.ReGroup_state_set252    __swig_getmethods__["state"] = _highlight.ReGroup_state_get253    if _newclass:state = _swig_property(_highlight.ReGroup_state_get, _highlight.ReGroup_state_set)254    __swig_setmethods__["kwClass"] = _highlight.ReGroup_kwClass_set255    __swig_getmethods__["kwClass"] = _highlight.ReGroup_kwClass_get256    if _newclass:kwClass = _swig_property(_highlight.ReGroup_kwClass_get, _highlight.ReGroup_kwClass_set)257ReGroup_swigregister = _highlight.ReGroup_swigregister...cstate.py
Source:cstate.py  
1import curses2# if they ever decide to fix this...3try:4    curses.BUTTON5_PRESSED5    pass6except AttributeError:7    curses.BUTTON5_PRESSED = 0x2000008    pass9# Curses makes highlighting a problem.  Each foreground/background/textcolor10# combination must be registered as a separate "color" within curses, and the11# total number is capped.  So currently, a character can be: on an edge,12# highlighted, or part of a deadline - or, more importantly, any subseteq of13# those.  Rather than having nine color pairs, leave it at (2 * 2 + 1) for now14# - maybe it'll get fixed if live highlihting of text entry ever happens.15# Probably not, though.16COLOR_PAIRS = {17    "HIGHLIGHT": lambda: curses.color_pair(1),18    "EDGE": lambda: curses.color_pair(2),19    "EDGE_HIGHLIGHT": lambda: curses.color_pair(3),20    "DEADLINE": lambda: curses.color_pair(4),21}22class CState:23    def __init__(self, stdscr, store, helptext):24        self.stdscr = stdscr25        self.store = store26        self.helptext = helptext27        self._highlight = 028        self._offset = 029        self.stdscr.scrollok(True)30        self.rows, self.cols = stdscr.getmaxyx()31        self.stdscr.setscrreg(0, self.rows - 1)32        curses.curs_set(0) # invisible cursor33        # 1 is left click, 4 is scroll up, 5 is scroll down34        curses.mousemask(curses.BUTTON1_PRESSED | curses.BUTTON4_PRESSED |35                         curses.BUTTON5_PRESSED) # button5 defined above36        curses.mouseinterval(0) # waiting here makes everything really laggy37        curses.use_default_colors()38        curses.init_pair(1, 0, 0xb)39        curses.init_pair(2, 0xc, -1)40        curses.init_pair(3, 0xc, 0xb)41        curses.init_pair(4, 0xa, -1)42        pass43    def display_nth(self, n):44        at = n - self._offset45        if at >= self.rows or at < 0:46            return47        elif n >= len(self.store):48            return49        text = self.store[n]["text"]50        cmdlen = len(self.store.cmds)51        qlen = len(self.store.queue)52        done = " ->" if n < cmdlen else "[ ]" if n - cmdlen < qlen else "[X]"53        self.stdscr.move(at, 0)54        self.stdscr.clrtoeol()55        maxw = self.cols - 156        if n == self._highlight and (n == 0 or n == len(self.store) - 1):57            return self.stdscr.addnstr(f"{done} {text}", maxw,58                                       COLOR_PAIRS["EDGE_HIGHLIGHT"]())59        elif n == self._highlight:60            return self.stdscr.addnstr(f"{done} {text}", maxw,61                                       COLOR_PAIRS["HIGHLIGHT"]())62        elif n == 0 or n == len(self.store) - 1:63            return self.stdscr.addnstr(f"{done} {text}", maxw,64                                       COLOR_PAIRS["EDGE"]())65        elif done == "[ ]" and " by " in text:66            idx = text.index(" by ")67            task = text[:idx]68            due = text[idx:]69            self.stdscr.addnstr(f"{done} {task}", maxw)70            return self.stdscr.addnstr(due, maxw, COLOR_PAIRS["DEADLINE"]())71        return self.stdscr.addnstr(f"{done} {text}", maxw)72    def display_store(self):73        self.stdscr.erase()74        self.stdscr.move(0, 0)75        for i in range(self.rows):76            self.display_nth(i + self._offset)77            pass78        return79    def resize(self):80        old_rows = self.rows81        self.rows, self.cols = self.stdscr.getmaxyx()82        self.stdscr.setscrreg(0, self.rows - 1)83        for old_row in range(old_rows, self.rows):84            self.display_nth(old_row + self._offset)85            pass86        else:87            # have to make a draw call here; otherwise, it doesn't actually88            # process the resize and you get a blank screen89            self.stdscr.refresh()90            pass91        pass92    def scroll_down(self):93        self._offset += 194        max_offset = len(self.store) - 195        if self._offset > max_offset:96            self._offset = max_offset97            return98        self.stdscr.scroll(1)99        if self._highlight < self._offset:100            self._highlight = self._offset101            self.display_nth(self._highlight)102            pass103        self.display_nth(self.rows + self._offset - 1)104        return105    def scroll_up(self):106        self._offset -= 1107        if self._offset < 0:108            self._offset = 0109            return110        self.stdscr.scroll(-1)111        bot = min(self.rows + self._offset, len(self.store)) - 1112        if self._highlight > bot:113            self._highlight = bot114            self.display_nth(self._highlight)115            pass116        self.display_nth(self._offset)117        return118    def _set_highlight_abs(self, new):119        if new == self._highlight:120            return True121        oldh = self._highlight122        self._highlight = new123        bot = min(self.rows + self._offset, len(self.store)) - 1124        if self._highlight < 0:125            self._highlight = 0126            pass127        elif self._highlight >= bot:128            self._highlight = bot129            pass130        self.display_nth(oldh)131        self.display_nth(self._highlight)132        return False133    def set_highlight_local(self, i):134        return self._set_highlight_abs(i + self._offset)135    def get_highlight_abs(self):136        return self._highlight137    def get_highlight_local(self):138        return self._highlight - self._offset139    def getline(self, stdscr, text="", edge=False):140        # surprise!  State machine.  (For text entry.)141        curses.curs_set(1) # visible cursor142        color = "EDGE_HIGHLIGHT" if edge else "HIGHLIGHT"143        stdscr.addstr(text, COLOR_PAIRS[color]())144        while True:145            c = stdscr.get_wch()146            if c in [curses.KEY_ENTER, "\n", "\r", "\r\n"]:147                break148            elif c == curses.KEY_RESIZE:149                self.resize()150                continue151            elif c == curses.KEY_MOUSE:152                # see comment in tood.py153                try:154                    _, _, row, _, bstate = curses.getmouse()155                    pass156                except Exception:157                    continue158                if bstate & curses.BUTTON4_PRESSED:159                    self.scroll_up()160                    continue161                if bstate & curses.BUTTON5_PRESSED:162                    self.scroll_down()163                    continue164                if bstate & curses.BUTTON1_PRESSED:165                    curses.curs_set(0) # invisible cursor166                    return row, text167                continue168            elif c in [curses.KEY_BACKSPACE, "\x7f"]:169                if text == "":170                    continue171                text = text[:-1]172                row, col = stdscr.getyx()173                stdscr.move(row, col - 1)174                stdscr.delch()175                continue176            elif c < ' ':177                continue178            # addch seems to ignore the attrs passed...179            stdscr.addstr(c, COLOR_PAIRS[color]())180            text += c181            continue182        curses.curs_set(0) # invisible cursor183        return stdscr.getyx()[0], text...LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
