Best Python code snippet using avocado_python
api.py
Source:api.py  
1"""2    File: api.py3    Namespace: basis_testing4    Date: 26 April 20205    Defines functions usable in templates.6"""7import numpy8import random9import itertools10import pkg_resources11BACKLOG = []12VARIABLES = {}13ALIASES = {}14BAD_WORDS = {}15def __load_bad_words():16    """17        Function __load_bad_words18        Loads the list of bad words into the set BAD_WORDS19        Inputs: None20        Output: None21    """22    global BAD_WORDS23    # Load datafile24    data = pkg_resources.resource_string(__name__, 'data/bad_words.txt').decode("utf-8")25    # Fill BAD_WORDS26    BAD_WORDS = {word.strip() for word in data.splitlines()}27def get_variables():28    global VARIABLES29    return VARIABLES30def clear_variables():31    global VARIABLES32    global ALIASES33    VARIABLES = {}34    ALIASES = {}35def set_backlog(in_backlog):36    """37        Function set_backlog38        Sets the choice backlog39        Inputs: 40        - in_backlog: the choice backlog to set41        Output: None42    """43    global BACKLOG44    BACKLOG = in_backlog45def choice(choices):46    """47        Function choice48        Make a choice between options49        Inputs: 50        - choices: the possible options51        Output: One of the options52    """53    global BACKLOG54    if not BACKLOG:55        sys_random = random.SystemRandom()56        return sys_random.choice(choices)57    else:58        return BACKLOG.pop(0)59def alias(alias, reference):60    """61        Function alias62        Defines a new alias63        Inputs: 64        - alias: the reference of the alias to define65        - reference: the reference to define the alias as66        Output: None67    """68    global ALIASES69    ALIASES[alias] = reference70def __generate_var(length = 3, depth = 0):71    """72        Function __generate_var73        Generates a random variable name of the specified length74        Inputs: 75        - length: the length of the variable to generate76        Output: A new random variable name77    """78    global VARIABLES79    global BAD_WORDS80    vowels = 'aeiou'81    consonants = 'bcdfghjklmnpqrstvwxyz'82    variable = ''83    # Generate some pseudo-language variable84    for i in range(length):85        # Randomly determine to use consonants or vowels86        random_number = random.random()87        if random_number < 0.5:88            variable += random.choice(consonants)89        else: 90            variable += random.choice(vowels)91    92    # Determine invalid variable names93    invalid = set(VARIABLES.values())94    # Recursively generate a different variable name if the variable name is invalid95    if variable in invalid or variable in BAD_WORDS:96        # Don't run forever!97        if depth > 100:98            raise Exception('No more variable names available')99        return __generate_var(length, depth + 1)100        101    return variable102def var(reference):103    """104        Function var105        Returns a known or new variable name based on the provided reference106        Inputs: 107        - reference: the reference of the variable, optionally with a variable length108        Output: Known or new variable name109    """110    global VARIABLES111    global ALIASES112    # Split actual reference from length specification113    reference_split = reference.split(':')114    assert 1 <= len(reference_split) <= 2, f'Variable reference \'{reference}\' is invalid.'115    # Attempt to find the variable in the known references116    if reference_split[0] in VARIABLES:117        return VARIABLES[reference_split[0]]118    # Attempt to find the variable in the known aliases119    if reference_split[0] in ALIASES:120        return VARIABLES[ALIASES[reference_split[0]]]121    # Attempt to indentify if the reference is a combination of known variables (max 5)122    for i in range(1, 6):123        # Determine possible combinations for this specific length124        permutations = itertools.permutations(VARIABLES, i)125        joint_variables = {''.join(permutation) : permutation for permutation in permutations}126        127        # Compare to the provided reference and create new alias if found128        if reference_split[0] in joint_variables:129            alias(reference_split[0], random.choice(joint_variables[reference_split[0]]))130            return VARIABLES[ALIASES[reference_split[0]]]131    # Generate random variable132    if len(reference_split) == 1:133        random_var = __generate_var()134    else:135        random_var = __generate_var(length = int(reference_split[1]))136    # Assign and return new variable137    VARIABLES[reference_split[0]] = random_var138    return VARIABLES[reference_split[0]]139v = var140def relop():141    """142        Function relop143        Return a random comparison operator144        Inputs: None145        Output: a string containing a random comparison operator146    """147    return random.choice(["==", "<=", ">", "<", ">=", "!="])148def integer(start, end, steps=1):149    """150        Function integer151        Return a random integer152        Inputs:153        - start: minimum allowed value154        - end: maximum allowed value (inclusive)155        - steps: the interval from which to select the random integers156        Output: a string containing a random integer157    """158    if type(steps) == float or steps < 1:159        steps = 1160        161    return str(int(random.randrange(start, end + 1, steps)))162i = integer163def floating(start, end, steps=0.5, max_decimals=2):164    """165        Function floating166        Return a random float167        Inputs:168        - start: minimum allowed value169        - end: maximum allowed value (inclusive)170        - steps: the interval from which to select the random floats171        - max_decimals: maximum number of decimals172        Output: a string containing a random float173    """174    return round(float(random.choice(numpy.arange(start, end + 1, steps))), max_decimals)175f = floating176def number(start, end, steps=1, max_decimals=2):177    """178        Function number179        Return a random number180        Inputs:181        - start: minimum allowed value182        - end: maximum allowed value (inclusive)183        - steps: the interval from which to select the random numbers184        - max_decimals: maximum number of decimals185        Output: a string containing a random number, int or float186    """187    is_int = random.choice([2, 3])188    if is_int == 2:189        stps = round(steps)190        if stps < 1:191            stps = 1192        return integer(start, end, steps=stps)193    else:194        return floating(start, end, steps=steps, max_decimals=max_decimals)195n = number196def intlist(start, end, minlength, maxlength, intsteps=1, lengthsteps=1):197    """198        Function intlist199        Return a list of random length containing random integers200        Inputs:201        - start: minimum allowed integer value202        - end: maximum allowed integer value (inclusive)203        - minlength: the minimum amount of integers in the list204        - maxlength: the maximum amount of integers in the list (inclusive)205        - intsteps: the interval from which to select the random integers206        - lengthsteps: the interval from which to select the amount of integers in the list207        Output: a string containing a list of random integers208    """209    # Determine length of the list 210    length = int(random.randrange(minlength, maxlength + 1, lengthsteps))211    # Generate and return list212    return str([int(random.randrange(start, end + 1, intsteps)) for _ in range(length)])213__load_bad_words()214def compex(variable, start, end, steps):215    sys_random = random.SystemRandom()...uri.py
Source:uri.py  
1from __future__ import (absolute_import, print_function, division)2from urlparse import urlsplit, parse_qsl3from . import rfc65704def is_template(url):5    """6        If a URL has variables it is assumed to be a URI Template (RFC 6570)7    """8    return len(rfc6570.varlist(url)) > 09def eq(a, b):10    """11        Checks for equality based on different URI components and expands12        templates if any.13    """14    a_is_tpl = is_template(a)15    b_is_tpl = is_template(b)16    if a_is_tpl and b_is_tpl:17        False18    if a_is_tpl:19        a = expand_template(a, b)20    if b_is_tpl:21        b = expand_template(b, a)22    actual = parse(a)23    expected = parse(b)24    return (match_host(actual, expected) and25            match_schema(actual, expected) and26            match_path(actual, expected) and27            match_querystring(actual, expected))28def expand_template(template, reference):29    """30        Receives a template and a URI reference. Decomposes the reference into31        pairs and segments and returns a valid URI result of expanding the32        template.33        TODO: fragments (#) are ignored.34    """35    reference_split = parse(reference)36    segments = path_segments(reference_split.path)37    pairs = query_pairs(reference_split.query)38    return rfc6570.expand(template, pairs, segments)39def parse(uri):40    return urlsplit(uri)41def path_segments(path):42    """43        Receives a URI path (str) and returns its segments.44    """45    return filter(lambda x: len(x) > 0, path.split("/"))46def query_pairs(query):47    """48        Receives a URI querystring (str) and returns its pairs as tuples.49    """50    return parse_qsl(query, keep_blank_values=True)51def match_host(actual, expected):52    return expected.hostname == actual.hostname53def match_path(actual, expected):54    return expected.path == actual.path55def match_querystring(actual, expected):56    return sorted(parse_qsl(expected.query)) == sorted(parse_qsl(actual.query))57def match_schema(actual, expected):...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!!
