How to use screenshot_as_png method in Selene

Best Python code snippet using selene_python

schedules_test.py

Source:schedules_test.py Github

copy

Full Screen

1# Licensed to the Apache Software Foundation (ASF) under one2# or more contributor license agreements. See the NOTICE file3# distributed with this work for additional information4# regarding copyright ownership. The ASF licenses this file5# to you under the Apache License, Version 2.0 (the6# "License"); you may not use this file except in compliance7# with the License. You may obtain a copy of the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing,12# software distributed under the License is distributed on an13# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14# KIND, either express or implied. See the License for the15# specific language governing permissions and limitations16# under the License.17import unittest18from datetime import datetime, timedelta19from unittest.mock import Mock, patch, PropertyMock20from flask_babel import gettext as __21from selenium.common.exceptions import WebDriverException22from superset import app, db23from superset.models.core import Dashboard, Slice24from superset.models.schedules import (25 DashboardEmailSchedule,26 EmailDeliveryType,27 SliceEmailReportFormat,28 SliceEmailSchedule,29)30from superset.tasks.schedules import (31 create_webdriver,32 deliver_dashboard,33 deliver_slice,34 next_schedules,35)36from .utils import read_fixture37class SchedulesTestCase(unittest.TestCase):38 RECIPIENTS = "recipient1@superset.com, recipient2@superset.com"39 BCC = "bcc@superset.com"40 CSV = read_fixture("trends.csv")41 @classmethod42 def setUpClass(cls):43 cls.common_data = dict(44 active=True,45 crontab="* * * * *",46 recipients=cls.RECIPIENTS,47 deliver_as_group=True,48 delivery_type=EmailDeliveryType.inline,49 )50 # Pick up a random slice and dashboard51 slce = db.session.query(Slice).all()[0]52 dashboard = db.session.query(Dashboard).all()[0]53 dashboard_schedule = DashboardEmailSchedule(**cls.common_data)54 dashboard_schedule.dashboard_id = dashboard.id55 dashboard_schedule.user_id = 156 db.session.add(dashboard_schedule)57 slice_schedule = SliceEmailSchedule(**cls.common_data)58 slice_schedule.slice_id = slce.id59 slice_schedule.user_id = 160 slice_schedule.email_format = SliceEmailReportFormat.data61 db.session.add(slice_schedule)62 db.session.commit()63 cls.slice_schedule = slice_schedule.id64 cls.dashboard_schedule = dashboard_schedule.id65 @classmethod66 def tearDownClass(cls):67 db.session.query(SliceEmailSchedule).filter_by(id=cls.slice_schedule).delete()68 db.session.query(DashboardEmailSchedule).filter_by(69 id=cls.dashboard_schedule70 ).delete()71 db.session.commit()72 def test_crontab_scheduler(self):73 crontab = "* * * * *"74 start_at = datetime.now().replace(microsecond=0, second=0, minute=0)75 stop_at = start_at + timedelta(seconds=3600)76 # Fire off the task every minute77 schedules = list(next_schedules(crontab, start_at, stop_at, resolution=0))78 self.assertEqual(schedules[0], start_at)79 self.assertEqual(schedules[-1], stop_at - timedelta(seconds=60))80 self.assertEqual(len(schedules), 60)81 # Fire off the task every 10 minutes, controlled via resolution82 schedules = list(next_schedules(crontab, start_at, stop_at, resolution=10 * 60))83 self.assertEqual(schedules[0], start_at)84 self.assertEqual(schedules[-1], stop_at - timedelta(seconds=10 * 60))85 self.assertEqual(len(schedules), 6)86 # Fire off the task every 12 minutes, controlled via resolution87 schedules = list(next_schedules(crontab, start_at, stop_at, resolution=12 * 60))88 self.assertEqual(schedules[0], start_at)89 self.assertEqual(schedules[-1], stop_at - timedelta(seconds=12 * 60))90 self.assertEqual(len(schedules), 5)91 def test_wider_schedules(self):92 crontab = "*/15 2,10 * * *"93 for hour in range(0, 24):94 start_at = datetime.now().replace(95 microsecond=0, second=0, minute=0, hour=hour96 )97 stop_at = start_at + timedelta(seconds=3600)98 schedules = list(next_schedules(crontab, start_at, stop_at, resolution=0))99 if hour in (2, 10):100 self.assertEqual(len(schedules), 4)101 else:102 self.assertEqual(len(schedules), 0)103 def test_complex_schedule(self):104 # Run the job on every Friday of March and May105 # On these days, run the job at106 # 5:10 pm107 # 5:11 pm108 # 5:12 pm109 # 5:13 pm110 # 5:14 pm111 # 5:15 pm112 # 5:25 pm113 # 5:28 pm114 # 5:31 pm115 # 5:34 pm116 # 5:37 pm117 # 5:40 pm118 crontab = "10-15,25-40/3 17 * 3,5 5"119 start_at = datetime.strptime("2018/01/01", "%Y/%m/%d")120 stop_at = datetime.strptime("2018/12/31", "%Y/%m/%d")121 schedules = list(next_schedules(crontab, start_at, stop_at, resolution=60))122 self.assertEqual(len(schedules), 108)123 fmt = "%Y-%m-%d %H:%M:%S"124 self.assertEqual(schedules[0], datetime.strptime("2018-03-02 17:10:00", fmt))125 self.assertEqual(schedules[-1], datetime.strptime("2018-05-25 17:40:00", fmt))126 self.assertEqual(schedules[59], datetime.strptime("2018-03-30 17:40:00", fmt))127 self.assertEqual(schedules[60], datetime.strptime("2018-05-04 17:10:00", fmt))128 @patch("superset.tasks.schedules.firefox.webdriver.WebDriver")129 def test_create_driver(self, mock_driver_class):130 mock_driver = Mock()131 mock_driver_class.return_value = mock_driver132 mock_driver.find_elements_by_id.side_effect = [True, False]133 create_webdriver()134 create_webdriver()135 mock_driver.add_cookie.assert_called_once()136 @patch("superset.tasks.schedules.firefox.webdriver.WebDriver")137 @patch("superset.tasks.schedules.send_email_smtp")138 @patch("superset.tasks.schedules.time")139 def test_deliver_dashboard_inline(self, mtime, send_email_smtp, driver_class):140 element = Mock()141 driver = Mock()142 mtime.sleep.return_value = None143 driver_class.return_value = driver144 # Ensure that we are able to login with the driver145 driver.find_elements_by_id.side_effect = [True, False]146 driver.find_element_by_class_name.return_value = element147 element.screenshot_as_png = read_fixture("sample.png")148 schedule = (149 db.session.query(DashboardEmailSchedule)150 .filter_by(id=self.dashboard_schedule)151 .all()[0]152 )153 deliver_dashboard(schedule)154 mtime.sleep.assert_called_once()155 driver.screenshot.assert_not_called()156 send_email_smtp.assert_called_once()157 @patch("superset.tasks.schedules.firefox.webdriver.WebDriver")158 @patch("superset.tasks.schedules.send_email_smtp")159 @patch("superset.tasks.schedules.time")160 def test_deliver_dashboard_as_attachment(161 self, mtime, send_email_smtp, driver_class162 ):163 element = Mock()164 driver = Mock()165 mtime.sleep.return_value = None166 driver_class.return_value = driver167 # Ensure that we are able to login with the driver168 driver.find_elements_by_id.side_effect = [True, False]169 driver.find_element_by_id.return_value = element170 driver.find_element_by_class_name.return_value = element171 element.screenshot_as_png = read_fixture("sample.png")172 schedule = (173 db.session.query(DashboardEmailSchedule)174 .filter_by(id=self.dashboard_schedule)175 .all()[0]176 )177 schedule.delivery_type = EmailDeliveryType.attachment178 deliver_dashboard(schedule)179 mtime.sleep.assert_called_once()180 driver.screenshot.assert_not_called()181 send_email_smtp.assert_called_once()182 self.assertIsNone(send_email_smtp.call_args[1]["images"])183 self.assertEqual(184 send_email_smtp.call_args[1]["data"]["screenshot.png"],185 element.screenshot_as_png,186 )187 @patch("superset.tasks.schedules.firefox.webdriver.WebDriver")188 @patch("superset.tasks.schedules.send_email_smtp")189 @patch("superset.tasks.schedules.time")190 def test_dashboard_chrome_like(self, mtime, send_email_smtp, driver_class):191 # Test functionality for chrome driver which does not support192 # element snapshots193 element = Mock()194 driver = Mock()195 mtime.sleep.return_value = None196 type(element).screenshot_as_png = PropertyMock(side_effect=WebDriverException)197 driver_class.return_value = driver198 # Ensure that we are able to login with the driver199 driver.find_elements_by_id.side_effect = [True, False]200 driver.find_element_by_id.return_value = element201 driver.find_element_by_class_name.return_value = element202 driver.screenshot.return_value = read_fixture("sample.png")203 schedule = (204 db.session.query(DashboardEmailSchedule)205 .filter_by(id=self.dashboard_schedule)206 .all()[0]207 )208 deliver_dashboard(schedule)209 mtime.sleep.assert_called_once()210 driver.screenshot.assert_called_once()211 send_email_smtp.assert_called_once()212 self.assertEqual(send_email_smtp.call_args[0][0], self.RECIPIENTS)213 self.assertEqual(214 list(send_email_smtp.call_args[1]["images"].values())[0],215 driver.screenshot.return_value,216 )217 @patch("superset.tasks.schedules.firefox.webdriver.WebDriver")218 @patch("superset.tasks.schedules.send_email_smtp")219 @patch("superset.tasks.schedules.time")220 def test_deliver_email_options(self, mtime, send_email_smtp, driver_class):221 element = Mock()222 driver = Mock()223 mtime.sleep.return_value = None224 driver_class.return_value = driver225 # Ensure that we are able to login with the driver226 driver.find_elements_by_id.side_effect = [True, False]227 driver.find_element_by_class_name.return_value = element228 element.screenshot_as_png = read_fixture("sample.png")229 schedule = (230 db.session.query(DashboardEmailSchedule)231 .filter_by(id=self.dashboard_schedule)232 .all()[0]233 )234 # Send individual mails to the group235 schedule.deliver_as_group = False236 # Set a bcc email address237 app.config["EMAIL_REPORT_BCC_ADDRESS"] = self.BCC238 deliver_dashboard(schedule)239 mtime.sleep.assert_called_once()240 driver.screenshot.assert_not_called()241 self.assertEqual(send_email_smtp.call_count, 2)242 self.assertEqual(send_email_smtp.call_args[1]["bcc"], self.BCC)243 @patch("superset.tasks.schedules.firefox.webdriver.WebDriver")244 @patch("superset.tasks.schedules.send_email_smtp")245 @patch("superset.tasks.schedules.time")246 def test_deliver_slice_inline_image(self, mtime, send_email_smtp, driver_class):247 element = Mock()248 driver = Mock()249 mtime.sleep.return_value = None250 driver_class.return_value = driver251 # Ensure that we are able to login with the driver252 driver.find_elements_by_id.side_effect = [True, False]253 driver.find_element_by_class_name.return_value = element254 element.screenshot_as_png = read_fixture("sample.png")255 schedule = (256 db.session.query(SliceEmailSchedule)257 .filter_by(id=self.slice_schedule)258 .all()[0]259 )260 schedule.email_format = SliceEmailReportFormat.visualization261 schedule.delivery_format = EmailDeliveryType.inline262 deliver_slice(schedule)263 mtime.sleep.assert_called_once()264 driver.screenshot.assert_not_called()265 send_email_smtp.assert_called_once()266 self.assertEqual(267 list(send_email_smtp.call_args[1]["images"].values())[0],268 element.screenshot_as_png,269 )270 @patch("superset.tasks.schedules.firefox.webdriver.WebDriver")271 @patch("superset.tasks.schedules.send_email_smtp")272 @patch("superset.tasks.schedules.time")273 def test_deliver_slice_attachment(self, mtime, send_email_smtp, driver_class):274 element = Mock()275 driver = Mock()276 mtime.sleep.return_value = None277 driver_class.return_value = driver278 # Ensure that we are able to login with the driver279 driver.find_elements_by_id.side_effect = [True, False]280 driver.find_element_by_class_name.return_value = element281 element.screenshot_as_png = read_fixture("sample.png")282 schedule = (283 db.session.query(SliceEmailSchedule)284 .filter_by(id=self.slice_schedule)285 .all()[0]286 )287 schedule.email_format = SliceEmailReportFormat.visualization288 schedule.delivery_type = EmailDeliveryType.attachment289 deliver_slice(schedule)290 mtime.sleep.assert_called_once()291 driver.screenshot.assert_not_called()292 send_email_smtp.assert_called_once()293 self.assertEqual(294 send_email_smtp.call_args[1]["data"]["screenshot.png"],295 element.screenshot_as_png,296 )297 @patch("superset.tasks.schedules.urllib.request.OpenerDirector.open")298 @patch("superset.tasks.schedules.urllib.request.urlopen")299 @patch("superset.tasks.schedules.send_email_smtp")300 def test_deliver_slice_csv_attachment(301 self, send_email_smtp, mock_open, mock_urlopen302 ):303 response = Mock()304 mock_open.return_value = response305 mock_urlopen.return_value = response306 mock_urlopen.return_value.getcode.return_value = 200307 response.content = self.CSV308 schedule = (309 db.session.query(SliceEmailSchedule)310 .filter_by(id=self.slice_schedule)311 .all()[0]312 )313 schedule.email_format = SliceEmailReportFormat.data314 schedule.delivery_type = EmailDeliveryType.attachment315 deliver_slice(schedule)316 send_email_smtp.assert_called_once()317 file_name = __("%(name)s.csv", name=schedule.slice.slice_name)318 self.assertEqual(send_email_smtp.call_args[1]["data"][file_name], self.CSV)319 @patch("superset.tasks.schedules.urllib.request.urlopen")320 @patch("superset.tasks.schedules.urllib.request.OpenerDirector.open")321 @patch("superset.tasks.schedules.send_email_smtp")322 def test_deliver_slice_csv_inline(self, send_email_smtp, mock_open, mock_urlopen):323 response = Mock()324 mock_open.return_value = response325 mock_urlopen.return_value = response326 mock_urlopen.return_value.getcode.return_value = 200327 response.content = self.CSV328 schedule = (329 db.session.query(SliceEmailSchedule)330 .filter_by(id=self.slice_schedule)331 .all()[0]332 )333 schedule.email_format = SliceEmailReportFormat.data334 schedule.delivery_type = EmailDeliveryType.inline335 deliver_slice(schedule)336 send_email_smtp.assert_called_once()337 self.assertIsNone(send_email_smtp.call_args[1]["data"])...

Full Screen

Full Screen

Compare_image.py

Source:Compare_image.py Github

copy

Full Screen

1import glob2import os3from selenium import webdriver4from selenium.webdriver.common.by import By5from selenium.webdriver.chrome.service import Service6from PIL import Image, ImageChops, ImageStat7import time8s = Service(executable_path="../drivers/chromedriver")9input_logo = '../input/0345.png'10output_logo = '../output/0345.png'11comparison_result = 'output/result1.png'12def clear_result():13 files = glob.glob('output/*')14 for f in files:15 os.remove(f)16def capture_image():17 driver = webdriver.Chrome(service=s)18 driver.get("http://192.168.0.103:8102/landing")19 driver.maximize_window()20 driver.implicitly_wait(5)21 time.sleep(3)22 driver.find_element(By.XPATH,"//ion-button[@color='primary']").click()23 time.sleep(2)24 driver.find_element(By.XPATH, "//ion-input[@type='email']/input").send_keys("venkateshrv307@gmail.com")25 driver.find_element(By.XPATH, "//input[@name='ion-input-1']").send_keys("Venkat@2000")26 time.sleep(2)27 driver.find_element(By.XPATH, "//ion-button[@size='large']").click()28 time.sleep(4)29 driver.find_element(By.XPATH, "//ion-tab-button[@tab='settings']").click()30 time.sleep(2)31 driver.find_element(By.XPATH,"(//ion-label[@class='sc-ion-label-md-h sc-ion-label-md-s md hydrated'])[9]").click()32 time.sleep(2)33 driver.find_element(By.XPATH,"//input[@class='native-input sc-ion-input-md']").send_keys("0345")34 time.sleep(1)35 driver.find_element(By.XPATH,"(//ion-button[@color='primary'])[3]").click()36 time.sleep(2)37 with open(output_logo,'wb') as file:38 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0341.png']").screenshot_as_png)39 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0342.png']").screenshot_as_png)40 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0343.png']").screenshot_as_png)41 file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0345.png']").screenshot_as_png)42 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0346.png']").screenshot_as_png)43 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0347.png']").screenshot_as_png)44 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0358.png']").screenshot_as_png)45 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0359.png']").screenshot_as_png)46 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0364.png']").screenshot_as_png)47 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0369.png']").screenshot_as_png)48 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0370.png']").screenshot_as_png)49 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0371.png']").screenshot_as_png)50 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0375.png']").screenshot_as_png)51 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0376.png']").screenshot_as_png)52 #file.write(driver.find_element(By.XPATH,"(//img[@src='assets/img/scales/0383.png'])[1]").screenshot_as_png)53 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0380.png']").screenshot_as_png)54 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0382.png']").screenshot_as_png)55 #file.write(driver.find_element(By.XPATH,"(//img[@src='assets/img/scales/0383.png'])[2]").screenshot_as_png)56 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0384.png']").screenshot_as_png)57 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0385.png']").screenshot_as_png)58 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0396.png']").screenshot_as_png)59 #file.write(driver.find_element(By.XPATH,"//img[@src='assets/img/scales/0396.png']").screenshot_as_png)60 img1 = Image.open(input_logo)61 img2 = Image.open(output_logo)62 logoresult = ImageChops.difference(img1,img2)63 stat = ImageStat.Stat(logoresult)64 diff_value = sum(stat.mean)65 print(diff_value)66 if diff_value > 1:67 result = "FAIL"68 print(result)69 else:70 result = "PASS"71 print(result)72 logoresult.show()73 logoresult.save(comparison_result)74 driver.close()75 driver.quit()76if __name__ == '__main__':77 clear_result()...

Full Screen

Full Screen

selenium_验证码.py

Source:selenium_验证码.py Github

copy

Full Screen

1# -*- coding:utf-8 -*-2# @Time : 2022/5/18 15:163# Auther : shenyuming4# @File : selenium_验证码.py5# @Software : PyCharm6'''7知识点: screenshot_as_png 保存元素的截图 , ddddocr验证码识别8'''9from selenium import webdriver10from time import sleep11import ddddocr12driver = webdriver.Chrome()13driver.get('http://121.41.14.39:8088/index.html')14sleep(2)15driver.find_element_by_css_selector('#username').send_keys('sq2')16driver.find_element_by_css_selector('#password').send_keys('123')17# 获得验证码图片18ele_img = driver.find_element_by_css_selector('img')19## 可以保存图片20# with open('ocr.img','wb') as f:21# f.write(ele_img.screenshot_as_png) # screenshot_as_png bytes类型, 可以保存图片22## 直接获得img的文本 , 导入ddddcor,实例化ddddocr23ocr = ddddocr.DdddOcr()24text = ocr.classification(ele_img.screenshot_as_png)25## 输入验证码26driver.find_element_by_css_selector('#code').send_keys(text)27driver.find_element_by_css_selector('#submitButton').click()28sleep(1)...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Selene automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful