Best Python code snippet using pytest-django_python
display_pattern.py
Source:display_pattern.py
1import base642import ctypes3import time4import logging5from ctypes import c_ulong, wintypes6import cv27import numpy as np8class DisplayPattern:9 def __init__(self):10 t = time.localtime()11 log_name = "log/" + \12 str(t.tm_year) + "-" + \13 str(t.tm_mon) + "-" +\14 str(t.tm_mday) + "-" + \15 str(t.tm_hour) + "-" +\16 str(t.tm_min) + "-" +\17 str(t.tm_sec) + ".log"18 log_format="<TIME>%(asctime)s <LINE>%(lineno)d %(funcName)s <%(levelname)s> %(message)s"19 logging.basicConfig(format=log_format,filename=log_name, filemode='w', level=logging.DEBUG)20 self.dis_num_dic = {}21 self.monitor_handle_position_dic = {}22 self.is_brightness_stop_change_flag = {23 "top": True, "n": True, "w": True, "s": True, "e": True}24 self.brightness_change_delay_time = {}25 self.last_change_brightness_time = {}26 self.dxva2 = ctypes.windll.Dxva227 import win32api28 monitor_list = win32api.EnumDisplayMonitors()29 for current_monitor in monitor_list:30 monitor_info = win32api.GetMonitorInfo(current_monitor[0])31 display_num = monitor_info["Device"].lstrip("\\.\\")32 monitor_handle_value = current_monitor[0].handle33 monitro_left_top_x = monitor_info["Monitor"][0]34 monitro_left_top_y = monitor_info["Monitor"][1]35 self.monitor_handle_position_dic[display_num] = [36 monitor_handle_value,37 (monitro_left_top_x, monitro_left_top_y),38 ]39 def show_display_number(self):40 try:41 for monitor_handle_position_dic in self.monitor_handle_position_dic:42 x, y = self.monitor_handle_position_dic[monitor_handle_position_dic][1]43 img_white_bg = np.zeros((1920, 1920, 3), np.uint8)44 img_white_bg[:] = (255, 255, 255)45 text = monitor_handle_position_dic46 cv2.putText(47 img_white_bg,48 text,49 (495, 1020),50 cv2.FONT_HERSHEY_TRIPLEX,51 6,52 (0, 0, 0),53 8,54 cv2.LINE_AA,55 )56 cv2.namedWindow(text, cv2.WINDOW_NORMAL)57 cv2.setWindowProperty(58 text, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)59 cv2.moveWindow(text, x, y)60 cv2.imshow(text, img_white_bg)61 cv2.waitKey(1)62 logging.info("OK")63 return True64 except Exception as ex:65 logging.error(str(ex))66 return False67 def set_direction(68 self,69 dis_num_top: str,70 dis_num_n: str,71 dis_num_w: str,72 dis_num_s: str,73 dis_num_e: str,74 ):75 try:76 dis_num_top = dis_num_top.upper()77 dis_num_n = dis_num_n.upper()78 dis_num_w = dis_num_w.upper()79 dis_num_s = dis_num_s.upper()80 dis_num_e = dis_num_e.upper()81 if dis_num_top[:7] == "DISPLAY":82 self.dis_num_dic["top"] = dis_num_top83 else:84 return False, ('top', dis_num_top)85 if dis_num_n[:7] == "DISPLAY":86 self.dis_num_dic["n"] = dis_num_n87 else:88 return False, ('n', dis_num_n)89 if dis_num_w[:7] == "DISPLAY":90 self.dis_num_dic["w"] = dis_num_w91 else:92 return False, ('w', dis_num_w)93 if dis_num_s[:7] == "DISPLAY":94 self.dis_num_dic["s"] = dis_num_s95 else:96 return False, ('s', dis_num_s)97 if dis_num_e[:7] == "DISPLAY":98 self.dis_num_dic["e"] = dis_num_e99 else:100 return False, ('e', dis_num_e)101 logging.info("OK")102 return True103 except Exception as ex:104 logging.error(str(ex))105 return False106 def get_brightness(self, direction: str):107 try:108 display_num = self.dis_num_dic[direction]109 monitor_handle = self.monitor_handle_position_dic[display_num][0]110 # Specify physical mointor111 physical_monitor = (PHYSICAL_MONITOR * 1)()112 self.dxva2.GetPhysicalMonitorsFromHMONITOR(113 monitor_handle, c_ulong(1), physical_monitor114 )115 # Get Minimum/Current/Maximum of brightness116 min_brightness = wintypes.DWORD()117 max_brightness = wintypes.DWORD()118 current_brightness = wintypes.DWORD()119 self.dxva2.GetMonitorBrightness(120 physical_monitor[0].hPhysicalMonitor,121 ctypes.byref(min_brightness),122 ctypes.byref(current_brightness),123 ctypes.byref(max_brightness),124 )125 logging.info("OK")126 return True, current_brightness.value127 except Exception as ex:128 logging.error(str(ex))129 return False, str(ex)130 def set_brightness(self, direction: str, target_brightness: int):131 try:132 if not self.is_brightness_stop_change_flag[direction]:133 sotp_change_brightness_time = (134 self.brightness_change_delay_time[direction] +135 self.last_change_brightness_time[direction]136 )137 if time.time() >= sotp_change_brightness_time:138 self.is_brightness_stop_change_flag[direction] = True139 else:140 brightness_change_time_left = sotp_change_brightness_time - time.time()141 logging.info("Brightness still change: " + str(round(brightness_change_time_left, 2)))142 return False, round(brightness_change_time_left, 2)143 if self.is_brightness_stop_change_flag[direction]:144 currnet_brightness = self.get_brightness(direction)[1]145 brightness_difference = abs(146 currnet_brightness - target_brightness)147 self.brightness_change_delay_time[direction] = brightness_difference / 3.33148 display_num = self.dis_num_dic[direction]149 monitor_handle = self.monitor_handle_position_dic[display_num][0]150 # Specify physical mointor151 physical_monitor = (PHYSICAL_MONITOR * 1)()152 self.dxva2.GetPhysicalMonitorsFromHMONITOR(153 monitor_handle, c_ulong(1), physical_monitor154 )155 # Modify brightness156 self.dxva2.SetMonitorBrightness(157 physical_monitor[0].hPhysicalMonitor, target_brightness158 )159 if brightness_difference > 0:160 self.is_brightness_stop_change_flag[direction] = False161 self.last_change_brightness_time[direction] = time.time()162 logging.info("OK")163 return True, round(self.brightness_change_delay_time[direction], 2)164 except Exception as ex:165 logging.error(str(ex))166 return False, str(ex)167 def set_all_brightness(self, target_brightness: int):168 try:169 is_assert, err_msg = self.set_brightness('top', target_brightness)170 err_msg = ('top', err_msg)171 assert is_assert172 is_assert, err_msg = self.set_brightness('n', target_brightness)173 err_msg = ('n', err_msg)174 assert is_assert175 is_assert, err_msg = self.set_brightness('w', target_brightness)176 err_msg = ('w', err_msg)177 assert is_assert178 is_assert, err_msg = self.set_brightness('s', target_brightness)179 err_msg = ('s', err_msg)180 assert is_assert181 is_assert, err_msg = self.set_brightness('e', target_brightness)182 err_msg = ('e', err_msg)183 assert is_assert184 logging.info("OK")185 return True186 except Exception as ex:187 logging.error(str(ex))188 logging.error(err_msg)189 return False190 def set_img(self, direction: str, img_base64: str):191 try:192 if True:193 display_num = self.dis_num_dic[direction]194 x, y = self.monitor_handle_position_dic[display_num][1]195 img_base64_decode = base64.b64decode(img_base64)196 img_np_ndarray = np.frombuffer(img_base64_decode, dtype=np.uint8)197 img_source = cv2.imdecode(img_np_ndarray, 1)198 # Set Window Title199 cv2.namedWindow(direction, cv2.WINDOW_NORMAL)200 # Set Window Property - FULLSCREEN201 cv2.setWindowProperty(direction, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)202 # Move Window - Position(x, y)203 cv2.moveWindow(direction, x, y)204 # Show Image Window205 cv2.imshow(direction, img_source)206 cv2.waitKey(1000)207 logging.info("OK")208 return True209 except Exception as ex:210 logging.error(str(ex))211 return False212 def set_brightness_img(self, direction: str, target_brightness: int, img_base64: str):213 try:214 is_assert = self.set_img(direction, img_base64)215 assert is_assert216 is_assert, err_msg = self.set_brightness(217 direction, target_brightness)218 assert is_assert219 logging.info("OK")220 return True, err_msg221 except Exception as ex:222 logging.error(str(ex))223 return False, str(ex)224 def close_all_window(self):225 try:226 cv2.destroyAllWindows()227 logging.info("OK")228 return True229 except Exception as ex:230 logging.error(str(ex))231 return False232 def close_window(self, direction: str):233 try:234 cv2.destroyWindow(direction)235 logging.info("OK")236 return True237 except Exception as ex:238 logging.error(str(ex))239 return False240class PHYSICAL_MONITOR(ctypes.Structure):241 _fields_ = [242 ("hPhysicalMonitor", wintypes.HANDLE),243 (244 "szPhysicalMonitorDescription",245 ctypes.c_wchar * 128,246 ),247 ]248if __name__ == "__main__":249 dp = DisplayPattern()250 import base64251 with open("pattern_top.png", "rb") as image_file:252 encoded_string = base64.b64encode(image_file.read())253 msg = dp.set_direction("DISPLAY4", "DISPLAY5",254 "DISPLAY6", "DISPLAY1", "DISPLAY2")255 print(msg)256 # print(dp.dis_num_dic)257 msg = dp.get_brightness("top")258 print(msg)259 dp.set_img("top", encoded_string)260 time.sleep(5)...
test_asserts.py
Source:test_asserts.py
...11 """12 from django.test import TestCase as DjangoTestCase13 from unittest import TestCase as DefaultTestCase14 obj = DjangoTestCase('run')15 def is_assert(func):16 return func.startswith('assert') and '_' not in func17 base_methods = [name for name, member in18 inspect.getmembers(DefaultTestCase)19 if is_assert(name)]20 return [name for name, member in inspect.getmembers(obj)21 if is_assert(name) and name not in base_methods]22def test_django_asserts_available():23 django_assertions = _get_actual_assertions_names()24 expected_assertions = asserts_all25 assert set(django_assertions) == set(expected_assertions)26 for name in expected_assertions:27 assert hasattr(pytest_django.asserts, name)28@pytest.mark.django_db29def test_sanity():30 from django.http import HttpResponse31 from pytest_django.asserts import assertContains, assertNumQueries32 response = HttpResponse('My response')33 assertContains(response, 'My response')34 with pytest.raises(AssertionError):35 assertContains(response, 'Not my response')...
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!!