Best Python code snippet using hypothesis
dgdata.py
Source:dgdata.py  
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3import random4from exceptions import ErrorInKeywords, UndefinedData5class DgData:6    def __init__(self, data, categories, footer_links = 5, pages_in_category = 10):7        self.categories = categories8        self.footer_links = footer_links9        self.pages_in_category = pages_in_category10        if data:11            if isinstance(data[0], dict):12                self.data = self.__split_by_categories(data)13            elif isinstance(data[0], list):14                self.data = data15            else:16                raise UndefinedData()17        self.__make_filenames()18        self.__make_links(footer_links)19        self.__make_categories()20    def __split_by_categories(self, data):21        result = []22        temp = []23        for i in xrange(len(data)):24            temp.append(data[i])25            if len(temp) == self.pages_in_category or i == len(data)-1:26                result.append(temp)27                temp = []28        return result29    def __make_categories(self):30        self.cat_tuples = [] #[(name, self.make_filename(name)) for name in self.categories]31        min_data = min(len(self.data), len(self.categories))32        for i in range(min_data):33            self.cat_tuples.append((self.categories[i], self.make_filename(self.categories[i])))34        for e in self.iterable():35            e["categories"] = self.cat_tuples36    def __make_filenames(self):37        for e in self.iterable():38            e["file"] = self.make_filename(e["keyword"])39    def __make_links(self, number):40        filenames = [page for page in self.iterable()]41        if number > self.count() - 1:42            print "[WARN] You want pages to have {0} links but specify only {1} keywords".format(number, self.count())43            number = self.count() - 144        for e in self.iterable():45            e["links"] = []46            i = 047            while i < number:48                candidate = random.choice(filenames)49                i+=150                while candidate == e or candidate["keyword"] in (l[0] for l in e["links"]):51                    candidate = random.choice(filenames)52                e["links"].append((candidate["keyword"], candidate["file"]))53    def make_filename(self, name):54        TRANSTABLE = (55            (u" ", u"_"),56            (u"â", u""),57            (u"â", u""),58            (u"«", u''),59            (u"»", u''),60            (u"â", u''),61            (u"â", u''),62            (u"â", u"-"),63            (u"â", u"-"), 64            (u"â", u"-"), 65            (u"â", u"-"),66            (u"â¦", u""),67            (u"â", u""),68            (u"Ñ", u"sch"),69            (u"Ñ", u"yo"),70            (u"ж", u"zh"),71            (u"Ñ", u"ts"),72            (u"Ñ", u"ch"),73            (u"Ñ", u"sh"),74            (u"Ñ", u"yi"),75            (u"Ñ", u"yu"),76            (u"Ñ", u"ya"),77            (u"а", u"a"),78            (u"б", u"b"),79            (u"в", u"v"),80            (u"г", u"g"),81            (u"д", u"d"),82            (u"е", u"e"),83            (u"з", u"z"),84            (u"и", u"i"),85            (u"й", u"j"),86            (u"к", u"k"),87            (u"л", u"l"),88            (u"м", u"m"),89            (u"н", u"n"),90            (u"о", u"o"),91            (u"п", u"p"),92            (u"Ñ", u"r"),93            (u"Ñ", u"s"),94            (u"Ñ", u"t"),95            (u"Ñ", u"u"),96            (u"Ñ", u"f"),97            (u"Ñ
", u"h"),98            (u"Ñ", u"e"),99            (u"Ñ", u""),100            (u"Ñ", u"")101        )102        translit = name.lower()103        for s_in, s_out in TRANSTABLE:104            translit = translit.replace(s_in, s_out)105        try:106            translit = str(translit)107        except UnicodeEncodeError:108            raise ErrorInKeywords()109        return translit + ".html"110    def get_filenames(self):111        return [e["file"] for e in self.iterable() if "file" in e]112    def get_key_by_filename(self, filename):113        for page in self.iterable():114            if page["filename"] == filename:115                return page["keyword"]116        return None117    def count(self):118        return sum(len(category) for category in self.data)119    def iterable(self):120        for l in self.data:121            for e in l:122                yield e123    def icategories(self):124        for cat_tuple in self.cat_tuples:125            yield cat_tuple126    def get_categories(self):127        return [c for c in self.icategories()]128    def get_all_by_category(self, category_tuple = None):129        if category_tuple:130            category_index = self.cat_tuples.index(category_tuple)131            return self.data[category_index]132        else:...test_clrucache.py
Source:test_clrucache.py  
1import pytest2import fastcache3import itertools4import warnings5try:6    itertools.count(start=0, step=-1)7    count = itertools.count8except TypeError:9    def count(start=0, step=1):10        i = step-111        for j, c in enumerate(itertools.count(start)):12            yield c + i*j13def arg_gen(min=1, max=100, repeat=3):14    for i in range(min, max):15        for r in range(repeat):16            for j, k in zip(range(i), count(i, -1)):17                yield j, k18@pytest.fixture(scope='module', params=[fastcache.clru_cache,19                                        fastcache.lru_cache])20def cache(request):21    param = request.param22    return param23def test_function_attributes(cache):24    """ Simple tests for attribute preservation. """25    def tfunc(a, b):26        """test function docstring."""27        return a + b28    cfunc = cache()(tfunc)29    assert cfunc.__doc__ == tfunc.__doc__30    assert hasattr(cfunc, 'cache_info')31    assert hasattr(cfunc, 'cache_clear')32    assert hasattr(cfunc, '__wrapped__')33def test_function_cache(cache):34    """ Test that cache returns appropriate values. """35    cat_tuples = [True]36    def tfunc(a, b, c=None):37        if (cat_tuples[0] == True):38            return (a, b, c) + (c, a)39        else:40            return 2*a-10*b41    cfunc = cache(maxsize=100, state=cat_tuples)(tfunc)42    for i, j in arg_gen(max=75, repeat=5):43        assert cfunc(i, j) == tfunc(i, j)44    # change extra state45    cat_tuples[0] = False46    for i, j in arg_gen(max=75, repeat=5):47        assert cfunc(i, j) == tfunc(i, j)48    # test dict state49    d = {}50    cfunc = cache(maxsize=100, state=d)(tfunc)51    cfunc(1, 2)52    assert cfunc.cache_info().misses == 153    d['a'] = 4254    cfunc(1, 2)55    assert cfunc.cache_info().misses == 256    cfunc(1, 2)57    assert cfunc.cache_info().misses == 258    assert cfunc.cache_info().hits == 159    d.clear()60    cfunc(1, 2)61    assert cfunc.cache_info().misses == 262    assert cfunc.cache_info().hits == 263    d['a'] = 4464    cfunc(1, 2)65    assert cfunc.cache_info().misses == 366def test_memory_leaks(cache):67    """ Longer running test to check for memory leaks. """68    def tfunc(a, b, c):69        return (a-1, 2*c) + (10*b-1, a*b, a*b+c)70    cfunc = cache(maxsize=2000)(tfunc)71    for i, j in arg_gen(max=1500, repeat=5):72        assert cfunc(i, j, c=i-j) == tfunc(i, j, c=i-j)73def test_warn_unhashable_args(cache, recwarn):74    """ Function arguments must be hashable. """75    @cache(unhashable='warning')76    def f(a, b):77        return (a, ) + (b, )78    with warnings.catch_warnings() :79        warnings.simplefilter("always")80        assert f([1], 2) == f.__wrapped__([1], 2)81        w = recwarn.pop(UserWarning)82        assert issubclass(w.category, UserWarning)83        assert "Unhashable arguments cannot be cached" in str(w.message)84        assert w.filename85        assert w.lineno86def test_ignore_unhashable_args(cache):87    """ Function arguments must be hashable. """88    @cache(unhashable='ignore')89    def f(a, b):90        return (a, ) + (b, )91    assert f([1], 2) == f.__wrapped__([1], 2)92def test_default_unhashable_args(cache):93    @cache()94    def f(a, b):95        return (a, ) + (b, )96    with pytest.raises(TypeError):97        f([1], 2)98    @cache(unhashable='error')99    def f(a, b):100        pass101    with pytest.raises(TypeError):102        f([1], 2)103def test_state_type(cache):104    """ State must be a list or dict. """105    f = lambda x : x106    with pytest.raises(TypeError):107        cache(state=(1, ))(f)108    with pytest.raises(TypeError):109        cache(state=-1)(f)110def test_typed_False(cache):111    """ Verify typed==False. """112    @cache(typed=False)113    def cfunc(a, b):114        return a+b115    # initialize cache with integer args116    cfunc(1, 2)117    assert cfunc(1, 2) is cfunc(1.0, 2)118    assert cfunc(1, 2) is cfunc(1, 2.0)119    # test keywords120    cfunc(1, b=2)121    assert cfunc(1,b=2) is cfunc(1.0,b=2)122    assert cfunc(1,b=2) is cfunc(1,b=2.0)123def test_typed_True(cache):124    """ Verify typed==True. """125    @cache(typed=True)126    def cfunc(a, b):127        return a+b128    assert cfunc(1, 2) is not cfunc(1.0, 2)129    assert cfunc(1, 2) is not cfunc(1, 2.0)130    # test keywords131    assert cfunc(1,b=2) is not cfunc(1.0,b=2)132    assert cfunc(1,b=2) is not cfunc(1,b=2.0)133def test_dynamic_attribute(cache):134    f = lambda x : x135    cfunc = cache()(f)136    cfunc.new_attr = 5...probas2dict.py
Source:probas2dict.py  
1#-*- coding: utf-8 -*-2import operator3import codecs4from operator import itemgetter5infile = r"cat_probas.txt"6def dict_probas(proba_file) :7	probas = {}8	with codecs.open(proba_file,'r', 'utf-8') as inputFileObj :9		for line in inputFileObj:10			cat_tuples = []11			data = line.split('\t')12			suff = data[0]13			cats = data[1].split('; ')14			cats = cats[:-1]15			for cat in cats:16				c = cat.split(' : ')17				pos = c[0]18				prob = c[1]19				cat_tuples.append((pos,prob))20			sorted_cats = sorted(cat_tuples, key=itemgetter(1), reverse=True)21			max_value = float(sorted_cats[0][1])22			new_cats = []23			for t in sorted_cats :24				if float(t[1]) > (max_value - 0.25) :25					new_cats.append(t)26			probas[suff] = new_cats27		28	inputFileObj.close()29	return probas...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!!
