Skip to content

Commit

Permalink
change language
Browse files Browse the repository at this point in the history
  • Loading branch information
longyuqing112 committed Jun 18, 2024
1 parent 2951de5 commit bd4e80b
Show file tree
Hide file tree
Showing 12 changed files with 89 additions and 89 deletions.
44 changes: 22 additions & 22 deletions base/base_page.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#存放所有页面的公共方法
#Store common methods for all pages
import os
import time

Expand All @@ -15,46 +15,46 @@
# wd = webdriver.Chrome()
# wd.get(HOST)
class BasePage:
# 初始化方法
# Initialization method
def __init__(self,driver):
self.driver = driver
#这样不用每次都要船建一个WebDriverWait实例而是直接用wait
#This way,you don't have to create a new WebDriverWait instance each time,but can directly use wait
self.wait = WebDriverWait(driver,10,0.5)

# 查找元素方法 # 假设 loc 参数为 ("id", "myElement"),那么 *loc 将被解包为 "id" "myElement",然后传递给 find_element 方法进行元素查找。
# Find Element Method Assuming the loc parameter is ("id", "myElement"), then *loc will be unpacked into "id" and "myElement", and then passed to the find_element method for element lookup.
def base_find(self,loc):
# 使用expected_conditions的visibility_of_element_located方法等待元素可见
# Use the expected_conditions visibility_of_element_located method to wait for the element to be visible
return self.wait.until(EC.visibility_of_element_located(loc))

# 点击方法

def base_click(self, loc):
# 等待元素可点击并点击
# Wait for the element to be clickable and clickable
self.wait.until(EC.element_to_be_clickable(loc)).click()

# 输入方法
# input
def enter_text(self,loc,value):
# 获取元素(找到这个元素)
# Get Element (Find this Element)
el = self.wait.until(EC.visibility_of_element_located(loc))
# 清空操作

el.clear()
# 输入内容

el.send_keys(value)

# 获取文本值方法
# Get text value method
def base_get_text(self,loc):
els = self.wait.until(EC.visibility_of_all_elements_located(loc))
# return el.text
return [element.text for element in els]

# 截图方法
# Screenshot method
def base_get_img(self):
img_path = os.path.join(DIR_PATH, "img", "{}.png".format(time.strftime("%Y%m%d%H%M%S")))
self.driver.get_screenshot_as_file(img_path)

def is_visible(self, locator, timeout=10):
return WebDriverWait(self.driver, timeout).until(EC.visibility_of_element_located(locator))
def wait_for_element_invisible(self, loc, text):
"""等待特定文本的元素不可见。"""
"""Wait until element with specific text is not visible.。"""
self.wait.until(
test_invisibility_of_element_located(loc, text)
)
Expand All @@ -64,18 +64,18 @@ def wait_masks_invisible(self):
try:
self.wait.until(lambda d:d.execute_script('return document.readyState') == 'complete')
masks = [
((By.XPATH, '//*[@id="root"]/div/div/div[1]/div/div'), '登录中...'),
((By.XPATH, '//*[@id="root"]/div/div/div[1]/div/div'), '同步中...')
((By.XPATH, '//*[@id="root"]/div/div/div[1]/div/div'), 'logging in...'),
((By.XPATH, '//*[@id="root"]/div/div/div[1]/div/div'), 'synchronizing...')
]
for loc,text in masks:
try:
# 尝试找到元素并确认其不可见
# # Try to find the element and confirm it is invisible
self.wait_for_element_invisible(loc, text)
# print(f"{text} 遮罩消失了。")
# print(f"{text} The mask disappeared。")
except TimeoutException:
print(f"等待 {text} 遮罩消失超时。")
print(f"wait {text} Mask disappear timeout。")
except TimeoutException:
print("页面加载超时,尝试重新加载页面。")
print("Page load timed out, try reloading the page.")
self.reload_page_if_stuck()

def javascript_click(self,locator):
Expand All @@ -85,5 +85,5 @@ def javascript_click(self,locator):
def reload_page_if_stuck(self):
current_url = self.driver.current_url
self.driver.get(current_url)
print("页面重新加载尝试解决问题。")
self.wait_masks_invisible() # 再次等待遮罩消失
print("Reload the page to try to resolve the issue。")
self.wait_masks_invisible() # Wait again for the mask to disappear
16 changes: 8 additions & 8 deletions data/register_data.yaml
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
register_tests:

- description: "注册成功"
- description: "registration success"
generate_phone: True
verification_code: "666666"
expected: "注册成功"
expected: "registration success"

- description: "注册成功"
- description: "registration success"
generate_phone: True
verification_code: "666666"
expected: "注册成功"
expected: "registration success"

- description: "注册失败"
- description: "registration failed"
generate_phone: False
expected: "手机号已注册"
expected: "Mobile phone number has been registered"

- description: "注册失败,验证码错误"
- description: "registration failed,Verification code error"
generate_phone: True
verification_code: "123456"
expected: "验证码错误"
expected: "Verification code error"

18 changes: 9 additions & 9 deletions pages/add_friend_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,14 @@ def add_friend(self,friend_phone,greeting_message='Hello'):

# Pop-up window adds successful and failed element positioning
msg_loc = (By.CSS_SELECTOR,'.ant-message-custom-content.ant-message-success > span:nth-child(2)')
message_check = test_visibility_of_element_located(msg_loc,'发送好友请求成功!')
message_check = test_visibility_of_element_located(msg_loc,'Friend request sent successfully!')
if message_check(self.driver):
print("发送好友请求成功。")
print("Friend request sent successfully。")
else:
# Here we need to check the failure situation
message_fail_check = test_visibility_of_element_located(msg_loc, "发送请求失败!")
message_fail_check = test_visibility_of_element_located(msg_loc, "Failed to send request!")
if message_fail_check(self.driver):
print("发送好友请求失败。")
print("Failed to send friend request。")
else:
# If it is neither a success nor a failure message, an unknown result is printed
# You need to get the message text for printing
Expand All @@ -62,9 +62,9 @@ def add_friend(self,friend_phone,greeting_message='Hello'):
EC.visibility_of_element_located(msg_loc)
)
message_text = message_element.text
print("未知的结果,弹窗文本为:", message_text)
print("Unknown result, the pop-up text is:", message_text)
except TimeoutException:
print("没有找到预期的反馈消息。")
print("The expected feedback message was not found。")


def agree_friend(self,addfriend_nickname):
Expand All @@ -73,11 +73,11 @@ def agree_friend(self,addfriend_nickname):
self.base_click(Locators.contacts)
self.base_click(Locators.newFriend_list)
friend_names = self.base_get_text(Locators.friend_name)
print('检测申请列表的好友有:', friend_names)
print('Friends in the detection application list include:', friend_names)
if addfriend_nickname in friend_names:
print(f"已收到该{addfriend_nickname}好友的申请。")
print(f"Received this{addfriend_nickname}Friend's Request。")
else:
print(f"{addfriend_nickname}申请不存在。")
print(f"{addfriend_nickname}Application does not exist。")
self.base_click(Locators.agree)
time.sleep(2)

Expand Down
14 changes: 7 additions & 7 deletions pages/registration_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ def register(self, phoneNumber,invitation_code=None,nickname='',password='',pass
error_message_element = self.wait.until(EC.visibility_of_element_located(error_message_locator))
error_message_text = error_message_element.text

if "手机号已注册" in error_message_text:
print("手机号已注册,请换号码")
return "手机号已注册"
if "Mobile phone number has been registered" in error_message_text:
print("Mobile phone number has been registered,Please change your number")
return "Mobile phone number has been registered"

except TimeoutException:
# No error message found, continue trying to fill in the captcha.
Expand All @@ -70,14 +70,14 @@ def register(self, phoneNumber,invitation_code=None,nickname='',password='',pass
for index, element in enumerate(verification_code_elements):
element.send_keys(verification_code[index])
except TimeoutException:
return "验证码输入框未出现"
return "The verification code input box does not appear"
# Check if the error message "Incorrect verification code" appears.
try:
error_message_locator = (By.XPATH, '/html/body/div[2]/div/div/div/div/span[2]')
error_message_element = self.wait.until(EC.visibility_of_element_located(error_message_locator))
error_message_text = error_message_element.text
if "验证码错误" in error_message_text:
return "验证码错误"
if "Verification code error" in error_message_text:
return "Verification code error"
except TimeoutException:
pass

Expand All @@ -92,7 +92,7 @@ def register(self, phoneNumber,invitation_code=None,nickname='',password='',pass
try:
WebDriverWait(self.driver, 10).until(EC.url_to_be(expected_url))
save_registered_account(phoneNumber, password,nickname)
return "注册成功"
return "registration success"

except TimeoutException:
return f"Expecting redirection to. {expected_url},But failed to redirect. Current URL: {self.driver.current_url}"
Expand Down
44 changes: 22 additions & 22 deletions pages/send_msg_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,18 @@ def scroll_to_top_of_chat(self):
chat_window = self.driver.find_element(By.ID, 'chat-list')
self.driver.execute_script("arguments[0].scrollTop = 0;", chat_window)
time.sleep(3)
print('页面已经滚动到了顶部')
# print('The page has scrolled to the top')

def scroll_to_bottom(self):
chat_window = self.driver.find_element(By.ID, 'chat-list')
self.driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight;", chat_window)
print('页面已经滚动到了底部')
# print('The page has scrolled to the bottom')
time.sleep(2)

def scroll_to_element(self, element):
# chat_window = self.driver.find_element(By.CSS_SELECTOR, 'div.chat-window-selector') # 更新选择器为聊天窗口的实际选择器
self.driver.execute_script("arguments[0].scrollIntoView(true);", element)
print('页面已经滚动到了', element, '元素的位置上', element.text)
print('The page has scrolled to', element, 'The position of the element', element.text)
time.sleep(1)

def navigate_to_add_friend(self, strange_phone):
Expand Down Expand Up @@ -66,7 +66,7 @@ def send_msg(self, strange_phone, msg):
# all_msgs += messages + " " # Assuming messages are separated by spaces
time.sleep(1) # A brief pause to ensure message sending
self.scroll_to_bottom()
# print('发送3条消息后滚到底部以便发送图片等')
# print('After sending 3 messages, scroll to the bottom to send pictures, etc.')

def upload_file(self, file_path, file_type):
locator = Locators.file_type_to_loc[file_type]
Expand All @@ -77,7 +77,7 @@ def upload_file(self, file_path, file_type):
try:
file_input = self.driver.find_element(*locator)
file_input.send_keys(file_path) # Use "send_keys" to upload files
print(f"尝试上传文件: {file_path}")
print(f"Try uploading a file: {file_path}")
time.sleep(3)

upload_success_indicator = Locators.file_sent_success_loc[file_type]
Expand Down Expand Up @@ -108,15 +108,15 @@ def check_msg_send(self, msg):

for element in message_elements:
self.scroll_to_element(element)
# print('捕捉到滚动到消息元素:', element.text)
# print('Capture scrolling to message element:', element.text)
messages_texts.append(element.text)

message_text = ' '.join(messages_texts)
# print('检查验证消息有:', message_text)
# print('Check the verification message:', message_text)
# Check if each message appears in the chat history

all_messages_present = all(message in message_text for message in msg)
print('所有消息-------:', all_messages_present)
print('all msg-------:', all_messages_present)

return all_messages_present

Expand All @@ -137,7 +137,7 @@ def check_received_messages(self):
for element in message_element:
self.scroll_to_element(element)
messages.append(element.text)
print('接收的内容有:', messages)
print('The content received is:', messages)
return messages

def check_received_files(self, file_type):
Expand All @@ -148,43 +148,43 @@ def check_received_files(self, file_type):
elements = self.base_find(locator)
WebDriverWait(self.driver, 10).until(
lambda driver: driver.execute_script('return document.readyState') == 'complete')
print('查看接收类型:', file_type)
print('等待元素可见看看是什么:', elements)
print('View Receiving Type:', file_type)
# print('Wait for the element to be visible to see what it is:', elements)
self.scroll_to_element(elements)
print('页面已完全加载且滚动到该元素上')
# print('The page is fully loaded and scrolled to the element')
if file_type == 'image' or file_type == 'video':
is_valid = self.driver.execute_script(
"return arguments[0].complete && typeof arguments[0].naturalWidth != 'undefined' && arguments[0].naturalWidth > 0",
elements)
if not is_valid:
raise ValueError(f"{file_type.capitalize()}未正确加载。")
print(f'接收到的{file_type.capitalize()}文件: {elements.get_attribute("src")}')
raise ValueError(f"{file_type.capitalize()}Not loaded correctly。")
print(f'Received{file_type.capitalize()}file: {elements.get_attribute("src")}')
if file_type == 'video':
play_button = self.base_find(Locators.video_svg)
if not play_button:
raise ValueError("视频播放按钮未找到。")
print("播放按钮存在,确认是视频文件。")
raise ValueError("Video play button not found。")
print("The play button exists, confirming that it is a video file。")
elif file_type == 'file':
if not elements.is_displayed() or "OpenIM.pdf" not in elements.text:
raise ValueError("文件未正确显示或文件名不匹配。")
print(f'接收到的普通文件: {elements.text}')
raise ValueError("The file is not displayed correctly or the file name does not match。")
print(f'Received normal files: {elements.text}')
return True

except TimeoutException:
self.driver.save_screenshot(f'file_receiving_failed_{file_type}.png')
print(f"超时:在检查接收到的文件类型时遇到 TimeoutException: {file_type}")
print(f"当前URL: {self.driver.current_url}")
print(f"Timeout: Encountered while checking received file type TimeoutException: {file_type}")
print(f"Current URL: {self.driver.current_url}")
return False

except StaleElementReferenceException:
self.driver.save_screenshot(f'file_stale_element_error_{file_type}.png')
print(
f"StaleElementReferenceException:在检查接收到的文件类型时遇到 StaleElementReferenceException: {file_type}")
f"StaleElementReferenceException:When checking the received file type, StaleElementReferenceException: {file_type}")
return False

except Exception as e: # Catch other anomalies more broadly
self.driver.save_screenshot(f'file_invalid_{file_type}.png')
print(f"无效元素{e}")
print(f"Invalid elements{e}")
return False


12 changes: 6 additions & 6 deletions script/test_add_friend.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@ def test_add_friends(driver, login):
add_friend_page.go_to()

registered_accounts = read_registered_accounts(1)
print("注册 账号:", registered_accounts)
print("Register an account:", registered_accounts)

if registered_accounts:
friend_phone, friend_pwd, _ = registered_accounts
add_friend_page.add_friend(friend_phone, "你好,加个好友把!")
add_friend_page.add_friend(friend_phone, "Hello, add me as a friend!")
else:
assert False, "没有可用的注册账号来进行添加好友的测试"
assert False, "There is no available registered account to test adding friends"
#
# driver.execute_script("window.open('');")
# driver.switch_to.window(driver.window_handles[1])
Expand All @@ -72,8 +72,8 @@ def test_agree_friends(driver, login):
)

text = element.text
print('验证是否成功同意:', text)
assert text == "已同意", "断言失败:文本内容不是 '已同意'"
print('Verify successful consent:', text)
assert text == "Agreed", "Assertion failed: The text content is not 'Agreed'"
else:
assert False, "没有可用的注册账号来进行同意好友申请的测试"
assert False, "There is no available registered account to test the friend request approval"

2 changes: 1 addition & 1 deletion script/test_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import sys
from config import DIR_PATH, HOST

#登录测试脚本 (scripts/test_login.py)
#Login test script (scripts/test_login.py)
import time
import yaml
from selenium import webdriver
Expand Down
4 changes: 2 additions & 2 deletions script/test_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,10 @@ def test_register(driver,case):
# Dynamically generate phone numbers based on test cases.
if case.get('generate_phone', False):
phoneNumber = generate_phone_number()
print("随机号码注册成功:",phoneNumber)
print("Random number registration successful:",phoneNumber)
else:
phoneNumber = case.get('username',read_first_registered_account())# If not provided, generate one anyway.
print("csv账号已存在:", phoneNumber)
print("csv account already exists:", phoneNumber)

# Get values for other fields from the test data.

Expand Down
Loading

0 comments on commit bd4e80b

Please sign in to comment.