python自动化测试脚本。4个例子
时间: 2024-03-31 19:35:51 浏览: 94
好的,以下是四个Python自动化测试脚本的示例:
1. Selenium Web自动化测试脚本:
```
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.google.com")
assert "Google" in driver.title
elem = driver.find_element_by_name("q")
elem.send_keys("Python")
elem.submit()
assert "No results found." not in driver.page_source
driver.quit()
```
2. API自动化测试脚本:
```
import requests
url = 'https://jsonplaceholder.typicode.com/posts'
data = {"title": "foo", "body": "bar", "userId": 1}
response = requests.post(url, json=data)
assert response.status_code == 201
assert response.json()["title"] == "foo"
```
3. 数据库自动化测试脚本:
```
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Create table
cursor.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
# Insert a row of data
cursor.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
# Save (commit) the changes
conn.commit()
# Query the database
cursor.execute("SELECT * FROM stocks WHERE symbol='RHAT'")
rows = cursor.fetchall()
assert len(rows) == 1
# Close the connection
conn.close()
```
4. GUI自动化测试脚本:
```
import pyautogui
# Click on the Start button
start_button = pyautogui.locateOnScreen('start_button.png')
assert start_button is not None
start_button_center = pyautogui.center(start_button)
pyautogui.click(start_button_center)
# Type some text in Notepad
notepad_icon = pyautogui.locateOnScreen('notepad_icon.png')
assert notepad_icon is not None
notepad_icon_center = pyautogui.center(notepad_icon)
pyautogui.click(notepad_icon_center)
pyautogui.typewrite('Hello, World!')
# Save the file
file_menu = pyautogui.locateOnScreen('file_menu.png')
assert file_menu is not None
file_menu_center = pyautogui.center(file_menu)
pyautogui.click(file_menu_center)
save_as = pyautogui.locateOnScreen('save_as.png')
assert save_as is not None
save_as_center = pyautogui.center(save_as)
pyautogui.click(save_as_center)
pyautogui.typewrite('test.txt')
save_button = pyautogui.locateOnScreen('save_button.png')
assert save_button is not None
save_button_center = pyautogui.center(save_button)
pyautogui.click(save_button_center)
```
以上是四个Python自动化测试脚本的简单示例。希望对你有所帮助。
阅读全文