Best Python code snippet using PyHamcrest_python
factories.py
Source:factories.py
1from datetime import datetime, date, timedelta2import factory3from factory import Sequence, LazyAttribute, SubFactory4from factory.fuzzy import FuzzyChoice, FuzzyDate, FuzzyNaiveDateTime, FuzzyDecimal, FuzzyInteger5from factory.alchemy import SQLAlchemyModelFactory6from segue.core import db7from segue.models import *8import logging9from cookielib import DAYS10logger = logging.getLogger('factory')11logger.addHandler(logging.StreamHandler())12logger.setLevel(logging.INFO)13def _Sequence(pattern):14 return Sequence(lambda counter: pattern.format(counter))15class SegueFactory(SQLAlchemyModelFactory):16 class Meta:17 sqlalchemy_session = db.session18class ValidTrackFactory(SegueFactory):19 class Meta:20 model = Track21 name_en = _Sequence('zona - track {0}')22 name_pt = _Sequence('zone - track {0}')23 public = True24class ValidRoomFactory(SegueFactory):25 class Meta:26 model = Room27 name = _Sequence('sala {0}')28 capacity = 20029 translation = False30class ValidSlotFactory(SegueFactory):31 class Meta:32 model = Slot33 room = SubFactory(ValidRoomFactory)34 blocked = False35 begins = datetime(2015,7,8,9,0,0)36 duration = 6037 status = 'empty'38class ValidAccountFactory(SegueFactory):39 class Meta:40 model = Account41 email = _Sequence('email_{0}@example.com')42 name = _Sequence('Joaozinho {0}')43 password = "password"44 document = _Sequence('123.456.789-2{0}')45 country = "Brazil"46 state = "RS"47 city = "Porto Alegre"48 phone = "51 2345678"49 organization = "manos da quebrada"50 resume = "um cara legal"51class ValidNonSelectionNoticeFactory(SegueFactory):52 class Meta:53 model = NonSelectionNotice54 account = SubFactory(ValidAccountFactory)55 hash = _Sequence('C0FFEE{0:04x}')56class ValidTournamentFactory(SegueFactory):57 class Meta:58 model = Tournament59 name = "fisl16"60 selection = "*"61 status = "open"62class ValidJudgeFactory(SegueFactory):63 class Meta:64 model = Judge65 hash = _Sequence('C0FFEE{0:04x}')66 email = _Sequence('email_{0}@example.com')67 votes = 568 tournament = SubFactory(ValidTournamentFactory)69class ValidAdminAccountFactory(ValidAccountFactory):70 role = "admin"71class ValidResetFactory(SegueFactory):72 class Meta:73 model = ResetPassword74 hash = _Sequence('C0FFEE{0:04x}')75 spent = False76 account = SubFactory(ValidAccountFactory)77class InvalidAccountFactory(ValidAccountFactory):78 email = "email"79 name = "nam"80 role = "luser"81 password = "p"82class ValidProposalFactory(SegueFactory):83 class Meta:84 model = Proposal85 title = _Sequence('Proposal Title #{0}')86 full = _Sequence('description #{0}')87 language = 'en'88 level = 'advanced'89class ValidProposalWithOwnerFactory(ValidProposalFactory):90 owner = SubFactory(ValidAccountFactory)91class ValidProposalWithOwnerWithTrackFactory(ValidProposalFactory):92 owner = SubFactory(ValidAccountFactory)93 track = SubFactory(ValidTrackFactory)94class InvalidProposalFactory(ValidProposalFactory):95 title = "x"96 full = "d"97 language = "xunga"98 level = "professional"99class ValidProposalTagFactory(SegueFactory):100 class Meta:101 model = ProposalTag102 name = _Sequence('proposal tag #{0}')103class ValidInviteFactory(SegueFactory):104 class Meta:105 model = ProposalInvite106 proposal = SubFactory(ValidProposalWithOwnerWithTrackFactory)107 recipient = _Sequence('fulano{0}@example.com')108 name = _Sequence('Fulano {0}')109 status = 'pending'110 hash = _Sequence('DEAD{0:04x}')111class ValidProductFactory(SegueFactory):112 class Meta:113 model = Product114 kind = "public"115 category = "normal"116 sold_until = FuzzyNaiveDateTime(datetime.now(), datetime(2025,12,1,0,0,0))117 public = True118 price = FuzzyDecimal(70, 400, 2)119 description = "ingresso fisl16 - lote 1 - muggles"120class ValidCaravanProductFactory(ValidProductFactory):121 class Meta:122 model = CaravanProduct123 category = "caravan"124class ValidProponentProductFactory(ValidProductFactory):125 class Meta:126 model = ProponentProduct127 category = "proponent"128class ValidSpeakerProductFactory(ValidProductFactory):129 class Meta:130 model = SpeakerProduct131 category = "speaker"132class ValidStudentProductFactory(ValidProductFactory):133 class Meta:134 model = StudentProduct135 category = "student"136class ValidBuyerFactory(SegueFactory):137 class Meta:138 model = Buyer139 address_state = 'RS'140 address_street = "Rua dos Bobos"141 address_number = _Sequence("#{0}")142 address_extra = _Sequence("apto #{0}")143 address_zipcode = _Sequence("90909-#{0:03}")144 address_neighborhood = "Menino de deus"145 address_city = "Porto Alegre"146 address_country = "Brasil"147class ValidBuyerCompanyFactory(ValidBuyerFactory):148 kind = "company"149 name = _Sequence("Empresa {0}")150 document = "66716451000138"151 contact = _Sequence("+55 23 4000-{0:04}")152class ValidBuyerPersonFactory(ValidBuyerFactory):153 kind = 'person'154 name = _Sequence("Pagador {0}")155 document = "59961743750"156 contact = _Sequence("+55 23 4567-{0:04}")157class ValidPurchaseFactory(SegueFactory):158 class Meta:159 model = Purchase160 product = SubFactory(ValidProductFactory)161 customer = SubFactory(ValidAccountFactory)162 status = "pending"163 amount = FuzzyDecimal(70, 400, 2)164 due_date = FuzzyDate(date.today())165class ValidPurchaseByPersonFactory(ValidPurchaseFactory):166 buyer = SubFactory(ValidBuyerPersonFactory)167class ValidPurchaseByCorpFactory(SegueFactory):168 buyer = SubFactory(ValidBuyerCompanyFactory)169class ValidPaymentFactory(SegueFactory):170 class Meta:171 model = Payment172 purchase = SubFactory(ValidPurchaseFactory)173 amount = FuzzyDecimal(70, 400, 2)174 due_date = FuzzyDate(date.today())175 status = "pending"176class ValidPagSeguroPaymentFactory(ValidPaymentFactory):177 class Meta:178 model = PagSeguroPayment179 reference = 'A00555-PU00444'180 code = 'LECODE'181class ValidBoletoPaymentFactory(ValidPaymentFactory):182 class Meta:183 model = BoletoPayment184 our_number = 101234185 due_date = FuzzyDate(date.today())186 document_hash = _Sequence("C0FFE#{:04d}")187class ValidPromoCodeFactory(SegueFactory):188 class Meta:189 model = PromoCode190 discount = 1.0191 creator = SubFactory(ValidAccountFactory)192 product = SubFactory(ValidProductFactory)193 hash_code = _Sequence("C0FFE#{:04d}")194 description = _Sequence("code #{:04d}")195 start_at = FuzzyDate(date.today() - timedelta(days=7), date.today())196 end_at = FuzzyDate(date.today(), date.today() + timedelta(days=7))197class ValidPromoCodePaymentFactory(ValidPaymentFactory):198 class Meta:199 model = PromoCodePayment200class ValidTransitionFactory(SegueFactory):201 class Meta:202 model = Transition203 payment = SubFactory(ValidPaymentFactory)204class ValidTransitionToPaidFactory(ValidTransitionFactory):205 old_status = 'pending'206 new_status = 'paid'207class ValidTransitionToPendingFactory(ValidTransitionFactory):208 old_status = 'started'209 new_status = 'pending'210class ValidCaravanFactory(SegueFactory):211 class Meta:212 model = Caravan213 name = _Sequence('Caravana dos Enxutos #{:04d}')214 city = 'Enxutolandia'215class ValidCaravanWithOwnerFactory(ValidCaravanFactory):216 owner = SubFactory(ValidAccountFactory)217class ValidCaravanInviteFactory(SegueFactory):218 class Meta:219 model = CaravanInvite220 caravan = SubFactory(ValidCaravanWithOwnerFactory)221 recipient = _Sequence('beltrano{0}@example.com')222 name = _Sequence('Beltrano {0}')223 status = FuzzyChoice(['pending','accepted','declined', 'cancelled'])224 hash = _Sequence("C0FFE#{:04d}")225class ValidCaravanPurchaseFactory(ValidPurchaseFactory):226 class Meta:227 model = CaravanRiderPurchase228 caravan = SubFactory(ValidCaravanWithOwnerFactory)229class ValidMatchFactory(SegueFactory):230 class Meta:231 model = Match232 round = 1233 player1 = SubFactory(ValidProposalWithOwnerWithTrackFactory)234 player2 = SubFactory(ValidProposalWithOwnerWithTrackFactory)235 tournament = SubFactory(ValidTournamentFactory)236class ValidCallNotificationFactory(SegueFactory):237 class Meta:238 model = CallNotification239 proposal = SubFactory(ValidProposalWithOwnerWithTrackFactory)240 account = SubFactory(ValidAccountFactory)241 status = 'pending'242 hash = _Sequence('C0FFE#{:04d}')243class ValidSlotNotificationFactory(SegueFactory):244 class Meta:245 model = SlotNotification246 slot = SubFactory(ValidSlotFactory)247 account = SubFactory(ValidAccountFactory)248 status = 'pending'249 hash = _Sequence('C0FFE#{:04d}')250class ValidCertificateFactory(SegueFactory):251 class Meta:252 model = Certificate253 account = SubFactory(ValidAccountFactory)254 ticket = SubFactory(ValidPurchaseFactory, customer=account)255 language = 'pt'256 hash_code = _Sequence('C0FFE#{:04d}')257class ValidAttendantCertificateFactory(ValidCertificateFactory):258 class Meta:...
buzzer.py
Source:buzzer.py
1import RPi.GPIO as GPIO # import the GPIO library2import time # import the time library3from threading import Thread4from queue import Queue5class Buzzer(Thread):6 def __init__(self, buzzerPin):7 Thread.__init__(self)8 self._gpio = GPIO9 self._gpio.setmode(GPIO.BCM)10 self._gpio.cleanup()11 self._buzzerPin = buzzerPin # set to GPIO pin 512 self._gpio.setup(self._buzzerPin, self._gpio.IN)13 self._gpio.setup(self._buzzerPin, self._gpio.OUT)14 self._buzzer = GPIO.PWM(self._buzzerPin,100)15 self._buzzer.ChangeFrequency(300)16 self._commandQ = Queue()17 def __del__(self):18 self._gpio.cleanup()19 def run(self):20 print('START THread')21 while(True):22 while not self._commandQ.empty():23 for tone in self._commandQ.get():24 if 1 == tone[0]:25 self.toneOn(tone[1])26 else:27 self.toneOff(tone[1])28 time.sleep(0.1)29 def toneOn(self,duration):30 if duration >= 255:31 print('duration ON forever')32 self._buzzer.start(100)33 else:34 print('sound ON for ', duration)35 self._buzzer.start(100)36 time.sleep(duration)37 self._buzzer.stop()38 def toneOff(self,duration):39 if duration >= 255:40 print('duration OFF forever')41 self._buzzer.stop()42 else:43 print('sound OFF for ', duration)44 self._buzzer.stop()45 time.sleep(duration)46 def TONE1(self):47 # notes = [294,330]48 _sequence = [[1,0.3],[0,0.2],[1,0.1],[0,255]]49 print(_sequence)50 self._commandQ.put(_sequence)51 def TONE2(self):52 # notes = [294,330]53 _sequence = [[1,0.1],[0,0.2],[1,0.3],[0,255]]54 print(_sequence)55 self._commandQ.put(_sequence)56 def TONE3(self):57 # notes = [294,330]58 _sequence = [[1,1],[0,0.1],[1,2],[0,255]]59 print(_sequence)60 self._commandQ.put(_sequence)61 def TONE4(self):62 # notes = [294,330]63 _sequence = [[1,2],[0,0.5],[1,2],[0,0.5],[1,2],[0,0.5],[1,2],[0,0.5],[1,2],[0,0.5],[1,2],[0,0.5],[1,2],[0,255]]64 print(_sequence)65 self._commandQ.put(_sequence)66 def TONE_ON(self):67 _sequence = [[1,255]]68 print(_sequence)69 self._commandQ.put(_sequence)70 def TONE_OFF(self):71 _sequence = [[0,255]]72 print(_sequence)73 self._commandQ.put(_sequence)74if __name__ == "__main__":75 # a = input("Enter Tune number 1-5:")76 buzzer = Buzzer(16)77 buzzer.start()78 buzzer.TONE1()79 time.sleep(1)80 buzzer.TONE2()81 time.sleep(1)82 buzzer.TONE_ON()83 time.sleep(5)84 buzzer.TONE_OFF()85 # buzzer.tone2()86 #buzzer.play(int(a))87 time.sleep(5)...
SortedList.py
Source:SortedList.py
1import collections.abc2import copy3from bisect import bisect_right4def _identity():5 return lambda x: x6class SortedList(collections.abc.Sequence):7 @property8 def key(self):9 return self._key10 def __init__(self, sequence=None, key=None):11 self._key = key or _identity()12 # breaks if key is not callable13 assert isinstance(self._key, collections.abc.Callable)14 self._sequence = list(sequence)15 self._sequence.sort(key=key)16 self._sequence.sort()17 def __str__(self):18 return f'SortedList({self._sequence})'19 def __getitem__(self, item):20 return self._sequence[item]21 def __len__(self):22 return len(self._sequence)23 def __delitem__(self, x):24 del self._sequence[x]25 return26 def __setitem__(self, key, value):27 self._sequence[key] = value28 def __iter__(self):29 return iter(self._sequence)30 def __reversed__(self):31 return self._sequence.reverse()32 def __contains__(self, item):33 if item in self._sequence:34 return True35 else:36 return False37 def __copy__(self):38 return copy.copy(self)39 def _find_index(self, value):40 i = bisect_right(self._sequence, value)41 if i:42 return i - 143 else:44 return 045 def add(self, value):46 self._sequence.insert(self._find_index(value), value)47 def pop(self, index):48 self._sequence.pop(index)49 def clear(self):50 del self._sequence51 self._sequence = []52 def remove(self, value):53 self._sequence.pop(self._find_index(value))54 def remove_every(self, value):55 while value in self._sequence:56 self._sequence.pop(self._find_index(value))57 def index(self, value):58 return self._find_index(value)59 def count(self, value):60 return self._sequence.count(value)61 def copy(self):62 self.__copy__()63 def extend(self, iterable_object):64 for i in iterable_object:...
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!!