Best Python code snippet using hypothesis
main.py
Source:main.py
...15 """16 self.name = name17 self.email = email18 self.cv = cv19 def _print_step(self, message: str) -> None:20 """ 21 Print step22 """23 print("*" * 50)24 print(message)25 return26 def _get_session_id(self) -> None:27 """28 Get session id from _response header and save it to variable29 """30 request = self._response.get(self._base_url)31 session_id = request.cookies['PHPSESSID']32 self._session_id = session_id33 self._print_step(f"Get session id: {session_id}")34 def _get_token(self) -> None:35 """36 Get token from _response header and save it to variable37 """38 request = self._response.get(self._base_url)39 soup = BeautifulSoup(request.text, 'html.parser')40 self._token = soup.find('input', {'name': 'statefulhash'})['value']41 self._print_step(f"Get token: {self._token}")42 def _activate_account(self):43 """44 Activate account with token45 """46 request = self._response.get(47 f'{self._base_url}/activate?statefulhash={self._token}'48 )49 self._print_step(request.text)50 def _get_image(self) -> bytes:51 """52 Get image from _response and save it to file 53 """54 request = self._response.get(55 f"{self._base_url}/payload",56 stream=True57 )58 image = request.raw59 return image60 def _sing_image(self) -> None:61 """62 Sing image with name 63 """64 image = Image.open(self._get_image())65 draw = ImageDraw.Draw(image)66 draw.text(67 (image.width / 2, image.height / 2),68 f"{self.name}, Hash: {self._token}",69 fill=(255, 255, 255),70 )71 image.save("image.jpg", "JPEG")72 self._print_step("Sing image successfully")73 def _code_copy(self) -> None:74 """ 75 Copy code to file76 """77 copyfile("main.py", "code.py")78 self._print_step("Copy code successfully")79 def _form_submit(self) -> None:80 """81 Submit form with image and cv82 """83 payload = self._response.get(f"{self._base_url}/payload")84 url = payload.headers['X-Post-Back-To']85 files = {86 "code": open(self._file_path / "code.py", "rb"),87 "resume": open(self._file_path / "resume.pdf", "rb"),88 "image": open(self._file_path / "image.jpg", "rb")89 }90 data = {91 "email": self.email,92 "name": self.name,93 "aboutme": "I'm backend developer from Venezuela, I'm a Python developer.",94 }95 request = self._response.post(96 url,97 files=files,98 data=data,99 )100 self._print_step(request.status_code)101 self._print_step(request.text)102 def main(self) -> None:103 """104 Main function105 """106 self._get_session_id()107 self._get_token()108 self._activate_account()109 self._sing_image()110 self._code_copy()111 self._form_submit()112if __name__ == "__main__":113 name = input("Name: ")114 email = input("Email: ")115 job_test = JobTest(name, email, "cv.pdf")...
multiprocessing_utils.py
Source:multiprocessing_utils.py
1"""2Threading (multiprocessing) utilities.3"""4import math5import time6from itertools import cycle7from multiprocessing import Manager8from multiprocessing.pool import Pool9from typing import Optional10class AtomicCounter(object):11 """12 A thread safe (atomic) counter with automatic printing13 of global progression.14 """15 def __init__(self,16 manager: Manager,17 total_count: int,18 print_step: Optional[int] = None):19 """20 Constructs the counter with the given arguments21 :param manager: the manager has to be instanciated outside for shared22 resources23 :param total_count: the total number of elements to process24 :param print_step: the number of step between each print, initialized25 to sensible default if not provided26 """27 self._lock = manager.Lock()28 self._value = manager.Value('i', 0)29 self._total_count = total_count30 self._start_time = time.time()31 if print_step:32 self._print_step = print_step33 else:34 # Nearest (floored) power of 10 from the total count:35 # - if count is 456, the print step will be of 10036 # - if count is 55698, the print step will be of 1000037 if total_count < 10:38 self._print_step = 139 else:40 self._print_step = int(10 ** (math.floor(math.log10(total_count))) / 10)41 def _print(self):42 if not self._value.value:43 print(f"Iteration count: {self._value.value}/{self._total_count}")44 return45 current_time = time.time() - self._start_time46 expected_time = (current_time / self._value.value) * self._total_count47 remaining_time = expected_time - current_time48 completed_percentage = (current_time / expected_time) * 10049 print(f"Iteration count: {self._value.value}/{self._total_count} ("50 f"elapsed: {int(current_time)} sec, "51 f"remaining: {int(remaining_time)} sec, "52 f"total: {int(expected_time)} sec, "53 f"completion: {int(completed_percentage)}%)")54 def increment(self):55 """56 Increments the counter and prints the value if the print_step is met57 """58 with self._lock:59 if self._value.value == 0:60 self._print()61 self._value.value += 162 if self._value.value % self._print_step == 0:63 self._print()64 def value(self):65 """66 Returns the value for the counter67 """68 with self._lock:69 return self._value.value70def _process(x: int, counter: AtomicCounter):71 try:72 # Process here, you can return None73 pass74 except Exception as e:75 print(f"Exception during processing of {x}: {e}")76 finally:77 counter.increment()78def main():79 # Example usage80 with Pool(4) as pool:81 # Add elements to process here82 elements = []83 manager = Manager()84 counter = AtomicCounter(manager, len(elements))85 print("START")86 results = pool.starmap(_process, zip(elements, cycle([counter])))87 results = [result for result in results if result]88 print("END")89if __name__ == "__main__":...
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!!