linkapi.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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, clip):
  15. self.page.goto(url)
  16. self.page.screenshot(path=output_path, clip=clip)
  17. def compare_images(self, image1_path, image2_path):
  18. image1 = Image.open(image1_path)
  19. image2 = Image.open(image2_path)
  20. diff = ImageChops.difference(image1, image2)
  21. if diff.getbbox() is None:
  22. INFO("两张图片完全相同")
  23. return True
  24. else:
  25. INFO("两张图片存在差异")
  26. return False
  27. #对比样本快照与当前快照
  28. def contrast_snapshot(self,url,expected_screenshot,current_screenshot,clip):
  29. # 如果不存在样本照片,生成样本照片
  30. if not os.path.exists(expected_screenshot):
  31. self.save_screenshot(url, expected_screenshot, clip)
  32. INFO(f"样本快照已保存:{expected_screenshot}")
  33. #生成对比照片
  34. apilink.save_screenshot(url, current_screenshot, clip)
  35. #返回对比结果
  36. result = apilink.compare_images(current_screenshot, expected_screenshot)
  37. return result
  38. apilink = APILink()