linkapi.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from hytest import *
  2. from playwright.sync_api import sync_playwright
  3. from PIL import Image, ImageChops
  4. class APILink():
  5. def setup(self):
  6. # 初始化 Playwright
  7. self.playwright = sync_playwright().start()
  8. self.browser = self.playwright.chromium.launch(headless=True)
  9. self.page = self.browser.new_page()
  10. def teardown(self):
  11. # 关闭浏览器
  12. self.browser.close()
  13. self.playwright.stop()
  14. def save_screenshot(self,url, output_path, elements, clip=None):
  15. locs = []
  16. self.page.goto(url)
  17. for element in elements:
  18. loc = self.page.locator(element)
  19. locs.append(loc)
  20. self.page.screenshot(path=output_path,mask=locs, clip=clip)
  21. def compare_images(self, image1_path, image2_path):
  22. image1 = Image.open(image1_path)
  23. image2 = Image.open(image2_path)
  24. diff = ImageChops.difference(image1, image2)
  25. if diff.getbbox() is None:
  26. INFO("两张图片完全相同")
  27. return True
  28. else:
  29. INFO("两张图片存在差异")
  30. return False
  31. #对比样本快照与当前快照
  32. def contrast_snapshot(self,url,expected_screenshot,current_screenshot,element,clip):
  33. # 如果不存在样本照片,生成样本照片
  34. self.save_screenshot(url, expected_screenshot,element,clip)
  35. INFO(f"样本快照已保存:{expected_screenshot}")
  36. #生成对比照片
  37. apilink.save_screenshot(url, current_screenshot,element,clip)
  38. INFO(f"对比快照已保存:{expected_screenshot}")
  39. #返回对比结果
  40. result = apilink.compare_images(current_screenshot, expected_screenshot)
  41. return result
  42. apilink = APILink()