Best Python code snippet using localstack_python
test_list.py
Source:test_list.py  
1import pytest2from aiohttp_admin2.resources.exceptions import (3    ClientException,4    BadParameters,5)6from aiohttp_admin2.resources.types import FilterTuple7from .utils import generate_fake_instance8@pytest.mark.asyncio9async def test_list_order(resource):10    """11    In this test check corrected work sort in get_list method of resource.12        1. Check default order13        2. Check asc order14        3. Error of ordering for cursor pagination15    """16    await generate_fake_instance(resource, 10)17    # 1. Check default order18    list_objects = await resource.get_list()19    assert len(list_objects.instances) == 1020    # 2. Check desc order21    list_objects_second = await resource.get_list(order_by='id')22    compare_list = zip(23        list_objects.instances,24        reversed(list_objects_second.instances),25    )26    for a, b in compare_list:27        assert a.get_pk() == b.get_pk()28    # 3. Error of ordering for cursor pagination29    with pytest.raises(ClientException):30        await resource.get_list(order_by='val', cursor=1)31@pytest.mark.asyncio32@pytest.mark.parametrize("ordering", ("id", "-id"))33async def test_list_page_pagination(resource, ordering):34    """35    In this test check corrected work page pagination in get_list method of36    resource. + ordering37        1. Check of correct work page pagination38        - Check of correct work has_next and has_prev values39        - Check of correct work count value40        2. Check of correct work page pagination with remainder41    """42    instance_count = 943    await generate_fake_instance(resource, instance_count)44    # 1. Check of correct work page pagination45    full_list_objects = \46        await resource.get_list(limit=instance_count, order_by=ordering)47    full_list_objects_ids = [i.get_pk() for i in full_list_objects.instances]48    assert len(full_list_objects_ids) == instance_count49    # page 150    list_objects = await resource.get_list(limit=3, order_by=ordering)51    list_objects_ids = [i.get_pk() for i in list_objects.instances]52    assert len(list_objects_ids) == 353    assert set(full_list_objects_ids[:3]) == set(list_objects_ids)54    # Check of correct work has_next and has_prev values55    assert list_objects.has_next56    assert not list_objects.has_prev57    assert list_objects.count == instance_count58    # page 259    list_objects = await resource.get_list(limit=3, page=2, order_by=ordering)60    list_objects_ids = [i.get_pk() for i in list_objects.instances]61    assert len(list_objects_ids) == 362    assert set(full_list_objects_ids[3:6]) == set(list_objects_ids)63    # Check of correct work has_next and has_prev values64    assert list_objects.has_next65    assert list_objects.has_prev66    assert list_objects.count == instance_count67    # page 368    list_objects = await resource.get_list(limit=3, page=3, order_by=ordering)69    list_objects_ids = [i.get_pk() for i in list_objects.instances]70    assert len(list_objects_ids) == 371    assert set(full_list_objects_ids[6:9]) == set(list_objects_ids)72    # Check of correct work has_next and has_prev values73    assert not list_objects.has_next74    assert list_objects.has_prev75    assert list_objects.count == instance_count76    # 2. Check of correct work page pagination with remainder77    await generate_fake_instance(resource, 1)78    # page 479    list_objects = await resource.get_list(limit=3, page=4, order_by=ordering)80    list_objects_ids = [i.get_pk() for i in list_objects.instances]81    assert len(list_objects_ids) == 182    # Check of correct work has_next and has_prev values83    assert not list_objects.has_next84    assert list_objects.has_prev85@pytest.mark.asyncio86async def test_list_page_pagination_parameters_error(resource):87    """88    In this test check errors which can been raised if pass bad arguments.89        1. limit must be greater than zero90        2. cursor can't be use together with page91        3. page must be greater than zero92    """93    # 1. limit must be greater than zero94    with pytest.raises(BadParameters):95        await resource.get_list(limit=0)96    # 2. cursor can't be use together with page97    instances = await generate_fake_instance(resource, 1)98    with pytest.raises(BadParameters):99        await resource.get_list(page=2, cursor=instances[0].get_pk())100    # 3. page must be greater than zero101    with pytest.raises(BadParameters):102        await resource.get_list(page=0)103@pytest.mark.asyncio104@pytest.mark.parametrize("ordering", ("id", "-id"))105async def test_list_cursor_pagination(resource, ordering):106    """107    In this test check corrected work cursor pagination in get_list method of108    resource. + ordering109        1. Check of correct work cursor pagination110        - Check of correct work has_next and has_prev values111        - Check of correct work count value112    """113    instance_count = 5114    await generate_fake_instance(resource, instance_count)115    # 1. Check of correct work cursor pagination116    full_list_objects = \117        await resource.get_list(limit=instance_count, order_by=ordering)118    full_list_objects_ids = [i.get_pk() for i in full_list_objects.instances]119    assert len(full_list_objects_ids) == instance_count120    # page 1121    list_objects = await resource.get_list(122        cursor=full_list_objects_ids[0],123        limit=3,124        order_by=ordering,125    )126    list_objects_ids = [i.get_pk() for i in list_objects.instances]127    assert len(list_objects_ids) == 3128    assert set(full_list_objects_ids[1:4]) == set(list_objects_ids)129    assert list_objects.has_next130    assert list_objects.has_prev131    assert list_objects.count is None132    # page 2133    list_objects = await resource.get_list(134        cursor=full_list_objects_ids[3],135        limit=3,136        order_by=ordering,137    )138    list_objects_ids = [i.get_pk() for i in list_objects.instances]139    assert len(list_objects_ids) == 1140    assert set(full_list_objects_ids[4:7]) == set(list_objects_ids)141    assert not list_objects.has_next142    assert list_objects.has_prev143    assert list_objects.count is None144@pytest.mark.asyncio145async def test_filter_api_for_get_list(resource):146    """147    In this test check corrected work filter api in get_list method of resource.148    + ordering149        1. Check corrected work of one filter + ordering150        2. Check corrected work of two filter + ordering151    """152    # 1. Check corrected work of one filter + ordering153    instances = await generate_fake_instance(resource, 10)154    full_list_objects_ids = [i.get_pk() for i in instances]155    # desc156    list_objects = await resource.get_list(157        filters=[158            FilterTuple('id', full_list_objects_ids[0], "gt"),159        ],160        limit=len(full_list_objects_ids),161    )162    list_objects_ids = [i.get_pk() for i in list_objects.instances]163    assert set(list_objects_ids) == set(full_list_objects_ids[1:])164    # asc165    list_objects = await resource.get_list(166        filters=[167            FilterTuple('id', full_list_objects_ids[-1], "lt"),168        ],169        limit=len(full_list_objects_ids),170        order_by='id'171    )172    asc_list_objects_ids = [i.get_pk() for i in list_objects.instances]173    for x, y in zip(list_objects_ids[1:], reversed(asc_list_objects_ids[1:])):174        assert x == y175    # 2. Check corrected work of two filter + ordering176    list_objects = await resource.get_list(177        filters=[178            FilterTuple('id', full_list_objects_ids[0], "gt"),179            FilterTuple('id', full_list_objects_ids[2], "lt"),180        ],181        limit=len(full_list_objects_ids),182    )183    list_objects_ids = [i.get_pk() for i in list_objects.instances]184    assert len(list_objects_ids) == 1185    assert list_objects_ids[0] == full_list_objects_ids[1]186@pytest.mark.asyncio187async def test_common_filters_for_get_list(resource):188    """189    In this test we check corrected work of common filters in get_list method190    of resource.191    Check corrected work of filters:192        eq, ne, lt, lte, gt, gte, in, nin, like193    """194    instances = await generate_fake_instance(resource, 10)195    full_list_objects_ids = [i.get_pk() for i in instances]196    # eq197    list_objects = await resource.get_list(198        filters=[199            FilterTuple('id', full_list_objects_ids[0], "eq"),200        ],201        limit=len(full_list_objects_ids),202    )203    list_objects_ids = [i.get_pk() for i in list_objects.instances]204    assert len(list_objects_ids) == 1205    assert list_objects_ids[0] == full_list_objects_ids[0]206    # ne207    list_objects = await resource.get_list(208        filters=[209            FilterTuple('id', full_list_objects_ids[0], "ne"),210        ],211        limit=len(full_list_objects_ids),212    )213    list_objects_ids = [i.get_pk() for i in list_objects.instances]214    assert len(list_objects_ids) == len(full_list_objects_ids) - 1215    assert full_list_objects_ids[0] not in list_objects_ids216    # gt217    list_objects = await resource.get_list(218        filters=[219            FilterTuple('id', full_list_objects_ids[-2], "gt"),220        ],221        limit=len(full_list_objects_ids),222    )223    list_objects_ids = [i.get_pk() for i in list_objects.instances]224    assert len(list_objects_ids) == 1225    assert list_objects_ids[0] == full_list_objects_ids[-1]226    # gte227    list_objects = await resource.get_list(228        filters=[229            FilterTuple('id', full_list_objects_ids[-2], "gte"),230        ],231        limit=len(full_list_objects_ids),232    )233    list_objects_ids = [i.get_pk() for i in list_objects.instances]234    assert len(list_objects_ids) == 2235    assert set(list_objects_ids) == set(full_list_objects_ids[-2:])236    # lt237    list_objects = await resource.get_list(238        filters=[239            FilterTuple('id', full_list_objects_ids[1], "lt"),240        ],241        limit=len(full_list_objects_ids),242    )243    list_objects_ids = [i.get_pk() for i in list_objects.instances]244    assert len(list_objects_ids) == 1245    assert list_objects_ids[0] == full_list_objects_ids[0]246    # lte247    list_objects = await resource.get_list(248        filters=[249            FilterTuple('id', full_list_objects_ids[1], "lte"),250        ],251        limit=len(full_list_objects_ids),252    )253    list_objects_ids = [i.get_pk() for i in list_objects.instances]254    assert len(list_objects_ids) == 2255    assert set(list_objects_ids) == set(full_list_objects_ids[:2])256    # in257    ids = full_list_objects_ids[1], full_list_objects_ids[0]258    list_objects = await resource.get_list(259        filters=[260            FilterTuple('id', ids, "in"),261        ],262        limit=len(full_list_objects_ids),263    )264    list_objects_ids = [i.get_pk() for i in list_objects.instances]265    assert len(list_objects_ids) == 2266    assert set(list_objects_ids) == set(ids)267    # nin268    list_objects = await resource.get_list(269        filters=[270            FilterTuple('id', ids, "nin"),271        ],272        limit=len(full_list_objects_ids),273    )274    list_objects_ids = [i.get_pk() for i in list_objects.instances]275    assert len(list_objects_ids) == len(full_list_objects_ids) - 2276    assert not (set(list_objects_ids) & set(ids))277    # like278    list_objects = await resource.get_list(279        filters=[280            FilterTuple('val', instances[0].data.val, "like"),281        ],282        limit=len(full_list_objects_ids),283    )284    list_objects_ids = [i.get_pk() for i in list_objects.instances]285    assert len(list_objects_ids) == 1...websites.py
Source:websites.py  
1import re2import requests3import urllib.request4from bs4 import BeautifulSoup5from objects import ObjectCrawl6class NewsCloud365(object):7    def __init__(self):8        self.url = "https://news.cloud365.vn/"9        self.source = "Cloud365"10    def get_dom(self, val):11        self.page_id = val12        page = urllib.request.urlopen(self.url + 'page/{}'.format(self.page_id))13        dom = BeautifulSoup(page, 'html5lib')14        return dom15    def get_objects(self):16        try:17            start_page = 118            list_objects = []19            while True:20                html_dom = self.get_dom(start_page)21                mark = html_dom.findAll(class_="post-header")22                for x in mark:23                    title_search = x.find(['a', "href"])24                    self.title = title_search.string25                    link_search = x.find(['a', "href"])26                    self.link = link_search['href']27                    time_search = x.find(attrs={'class' : 'post-date'})28                    self.time = time_search.string29                    author_search = x.find(attrs={'class' : 'post-author'})30                    self.author = author_search.string31                32                    new_post = ObjectCrawl(self.title, self.link, self.time, self.author, self.source)33                    dic = new_post.to_dict()34                    list_objects.append(dic)35                start_page+=136        except:37            pass38        return list_objects39class TecAdmin(NewsCloud365):40    def __init__(self):41        self.url = 'https://tecadmin.net/'42        self.source = 'TecAdmin'43    def get_objects(self):44        try:45            start_page = 146            list_objects = []47            while start_page <= 10:48                html_dom = self.get_dom(start_page)49                mark = html_dom.findAll(class_="post-box")50                for x in mark:51                    title_search = x.find(['a', "href"])52                    self.title = title_search.string53                    link_search = x.find(['a', "href"])54                    self.link = link_search['href']55                    time_search = x.find(attrs={'class' : 'updated'})56                    self.time = time_search['datetime']57                    author_search = x.find(attrs={'class' : 'fn'})58                    self.author = author_search.string59                60                    new_post = ObjectCrawl(self.title, self.link, self.time, self.author, self.source)61                    dic = new_post.to_dict()62                    list_objects.append(dic)63                start_page+=164        except:65            pass66        return list_objects67class Techrum(object):68    def __init__(self):69        self.url = 'https://www.techrum.vn/articles/'70        self.homepage = 'https://www.techrum.vn'71        self.source = 'Techrum'72    def get_dom(self, val):73        self.page_id = val74        page = urllib.request.urlopen(self.url + 'page-{}'.format(self.page_id))75        dom = BeautifulSoup(page, 'html5lib')76        return dom77    def get_objects(self):78        try:79            start_page = 180            list_objects = []81            while start_page <= 5:82                html_dom = self.get_dom(start_page)83                mark = html_dom.findAll(class_="porta-article-item")84                for x in mark:85                    title_search = x.find(['a', "href"])86                    self.title = title_search.string87                    self.title = self.title.strip()88                    link_search = x.find(['a', "href"])89                    self.link = link_search['href']90                    self.link = self.homepage + self.link91                    time_search = x.find(attrs={'class' : 'u-dt'})92                    self.time = time_search['data-date-string']93                    author_search = x.find(attrs={'class' : 'u-concealed'})94                    self.author = author_search.string95                    self.author = self.author.strip()96                97                    new_post = ObjectCrawl(self.title, self.link, self.time, self.author, self.source)98                    dic = new_post.to_dict()99                    list_objects.append(dic)100                start_page+=1101        except:102            pass103        return list_objects104class DigitalOcean(object):105    def __init__(self):106        self.url = "https://www.digitalocean.com/community/tutorials"107        self.homepage = "https://www.digitalocean.com/community/"108        self.source = "DigitalOcean"109    110    def get_objects(self):111        list_objects = []112        page = requests.get(self.url)113        html_dom = BeautifulSoup(page.text, 'html5lib')114        mark = html_dom.findAll(attrs={'class' : 'feedable-details'})115        for x in mark:116            title_search = x.find('h3')117            self.title = title_search.string.strip()118                    119            link_search = x.find("a", {"data-js": True})120            self.link = self.homepage + link_search['href']121            time_search = x.find(attrs={'class' : 'publish-date timeago'})122            self.time = time_search['title']123            124            author_search = x.find(attrs={'class' : 'authors'})125            self.author = author_search.string.strip()126            self.author = re.sub('By', '', self.author)127            self.author = self.author.strip()128            new_post = ObjectCrawl(self.title, self.link, self.time, self.author, self.source)129            dic = new_post.to_dict()130            list_objects.append(dic)131        return list_objects132class CuongQuach(NewsCloud365):133    def __init__(self):134        self.url = "https://cuongquach.com/category/linux/"135        self.source = "CuongQuach"136    def get_objects(self):137        try:138            start_page = 1139            list_objects = []140            while True:141                html_dom = self.get_dom(start_page)142                mark = html_dom.findAll(class_="td-block-span6")143                for x in mark:144                    title_search = x.find(attrs={'class' : 'entry-title td-module-title'})145                    title_search = title_search.a146                    self.title = title_search['title']147                    self.link = title_search['href']148                    time_search = x.find(attrs={'class' : 'entry-date updated td-module-date'})149                    self.time = time_search.string150                    author_search = x.find(attrs={'class' : 'td-post-author-name'})151                    author_search = author_search.a152                    self.author = author_search.string153                    154                    new_post = ObjectCrawl(self.title, self.link, self.time, self.author, self.source)155                    dic = new_post.to_dict()156                    list_objects.append(dic)157                start_page+=1158        except:159            pass160        return list_objects161class ICTNews(object):162    def __init__(self):163        self.url = "https://ictnews.vn/"164        self.source = "ICTNews"165    def get_objects(self):166        list_objects = []167        page = requests.get(self.url)168        html_dom = BeautifulSoup(page.text, 'html5lib')169        mark_0 = html_dom.find(class_="news-list")170        mark = mark_0.findAll(class_="g-content")171        for x in mark:172            title_search = x.find(attrs={'class' : 'g-title'})173            self.title = title_search.string174            self.link = title_search['href']175            self.time = 'None'176            self.author = 'None'177            new_post = ObjectCrawl(self.title, self.link, self.time, self.author, self.source)178            dic = new_post.to_dict()179            list_objects.append(dic)180        return list_objects181class TinhTe(object):182    def __init__(self):183        self.url = "https://tinhte.vn/"184        self.source = "TinhTe"185    def get_objects(self):186        list_objects = []187        page = requests.get(self.url)188        html_dom = BeautifulSoup(page.text, 'html5lib')189        mark_0 = html_dom.find('ol', class_="jsx-1525933963")190        mark = mark_0.findAll('li')191        for x in mark:192            self.title = x.div.article.a.h3.string193            self.link = x.div.article.a['href']194            self.time = 'None'195            author_search = x.find(class_="jsx-2418319489 author")196            self.author = author_search.string197            new_post = ObjectCrawl(self.title, self.link, self.time, self.author, self.source)198            dic = new_post.to_dict()199            list_objects.append(dic)...Task_2_2.py
Source:Task_2_2.py  
1# 2. Ðан ÑпиÑок:2# ['в', '5', 'ÑаÑов', '17', 'минÑÑ', 'ÑемпеÑаÑÑÑа', 'воздÑÑ
а', 'бÑла', '+5', 'гÑадÑÑов']3#4# ÐеобÑ
одимо его обÑабоÑаÑÑ â обоÑобиÑÑ ÐºÐ°Ð¶Ð´Ð¾Ðµ Ñелое ÑиÑло (веÑеÑÑвеннÑе не ÑÑогаем) кавÑÑками5# (добавиÑÑ ÐºÐ°Ð²ÑÑÐºÑ Ð´Ð¾ и кавÑÑÐºÑ Ð¿Ð¾Ñле ÑлеменÑа ÑпиÑка, ÑвлÑÑÑегоÑÑ ÑиÑлом) и дополниÑÑ Ð½ÑлÑм6# до двÑÑ
 ÑелоÑиÑленнÑÑ
 ÑазÑÑдов:7#8# ['в', '"', '05', '"', 'ÑаÑов', '"', '17', '"', 'минÑÑ', 'ÑемпеÑаÑÑÑа', 'воздÑÑ
а', 'бÑла', '"', '+05', '"', 'гÑадÑÑов']9# СÑоÑмиÑоваÑÑ Ð¸Ð· обÑабоÑанного ÑпиÑка ÑÑÑокÑ:10#11# в "05" ÑаÑов "17" минÑÑ ÑемпеÑаÑÑÑа воздÑÑ
а бÑла "+05" гÑадÑÑов12# ÐодÑмаÑÑ, какое ÑÑловие запиÑаÑÑ, ÑÑÐ¾Ð±Ñ Ð²ÑÑвиÑÑ ÑиÑла ÑÑеди ÑлеменÑов ÑпиÑка?13# Ðак модиÑиÑиÑоваÑÑ ÑÑо ÑÑловие Ð´Ð»Ñ ÑиÑел Ñо знаком?14#15# ÐÑимеÑание: еÑли обоÑобление ÑиÑел кавÑÑками не бÑÐ´ÐµÑ Ð¿Ð¾Ð»ÑÑаÑÑÑÑ - можеÑе веÑнÑÑÑÑÑ Ðº его ÑеализаÑии позже.16# Ðлавное: дополниÑÑ ÑиÑла до двÑÑ
 ÑазÑÑдов нÑлÑм!17# ÐаÑ
одим инÑеÑвал кодов коÑоÑÑй ÑооÑвеÑÑÑвÑÐµÑ ÑиÑÑам Ð¾Ñ 0 до 918# print(ord('0'))   #48 int19# print(ord('9'))   #57 int20#print(ord('Ð'))   #104021#print(ord('Ñ'))   #110322list_objects = ['в', '5', 'ÑаÑов', '17', 'минÑÑ', 'ÑемпеÑаÑÑÑа', 'воздÑÑ
а', 'бÑла', '+5', 'гÑадÑÑов']23new_list = []24for i in range(len(list_objects) - 1, -1, -1):25    for m in range(len(list_objects[i]) - 1, -1, -1):26        if list_objects[i][m].isdigit() and len(list_objects[i]) < 2:27            new_list.extend(['"', f'0{list_objects[i]}', '"'])28            break29        elif list_objects[i][m].isdigit() and list_objects[i][m - 1].isdigit():30            new_list.extend(['"', f'{list_objects[i]}', '"'])31            break32        elif list_objects[i][m].isdigit() and len(list_objects[i]) < 3:33            new_list.extend(['"', f'{list_objects[i][0]}0{list_objects[i][-1]}', '"'])34            break35        else:36            new_list.append(list_objects[i])37            break38print('ÐÑÑ
однÑй ÑпиÑок: ', list_objects)39new_list.reverse()40print('ÐÑÑоÑмаÑиÑованнÑй ÑпиÑок: ', new_list)41print('СообÑение: ', ' '.join(new_list))42# ÐÑÑ
однÑй ÑпиÑок оÑÑоÑмаÑиÑован Ñак как Ñказано в задании,43# но ÑклеиÑÑ Ð² ÑообÑение не полÑÑилоÑÑ Ð±ÐµÐ· пÑобелов. ÐÑжно подÑмаÑÑ ÐºÐ°Ðº ÑÑо ÑделаÑÑ44# Ðиже пÑиведен вÑоÑой ваÑÐ¸Ð°Ð½Ñ ÑеÑениÑ, ÑообÑение вÑводиÑÑÑ ÐºÐ°Ðº в задании,45# но ÑпиÑок оÑÑоÑмаÑиÑован без Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ ÑлеменÑов ÑпиÑка Ñ ÐºÐ¾Ð²ÑÑками '"'46# РпÑинÑипе иÑполÑзÑÑ Ð´Ð²Ð° ÑеÑÐµÐ½Ð¸Ñ Ð¼Ð¾Ð¶Ð½Ð¾ вÑвеÑÑи нÑжнÑй ÑезÑлÑÑÐ°Ñ Ð¸Ð· каждого, но ÑÑо не ÑовÑем веÑно.47print('***************** ÐÑоÑой ваÑÐ¸Ð°Ð½Ñ ÑеÑÐµÐ½Ð¸Ñ ***************')48list_objects = ['в', '5', 'ÑаÑов', '17', 'минÑÑ', 'ÑемпеÑаÑÑÑа', 'воздÑÑ
а', 'бÑла', '+5', 'гÑадÑÑов']49new_list = []50for i in range(len(list_objects)-1, -1, -1):51    for m in range(len(list_objects[i])-1, -1, -1):52       if  list_objects[i][m].isdigit() and len(list_objects[i]) < 2:53           new_list.append(f'"0{list_objects[i]}"')54           break55       elif list_objects[i][m].isdigit() and list_objects[i][m-1].isdigit():56           new_list.append(f'"{list_objects[i]}"')57           break58       elif list_objects[i][m].isdigit() and len(list_objects[i]) < 3:59           new_list.append(f'"{list_objects[i][0]}0{list_objects[i][-1]}"')60           break61       else:62           new_list.append(list_objects[i])63           break64print('ÐÑÑ
однÑй ÑпиÑок: ', list_objects)65new_list.reverse()66print('ÐÑÑоÑмаÑиÑованнÑй ÑпиÑок: ', new_list) #...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!!
