闲得无聊,借助gpt写了下测试客户端软件的,网上好像基本都是web端,找了好久没找到,就自学+自己写点,抛砖引玉。
# -*- ecoding: utf-8 -*-
# @ModuleName: test_openTypora
# @Author: Ming Qing
# @Time: 2023/5/22 16:02
# @Version:Python 3.10.8, pytest-7.3.1, pluggy-1.0.0
# 需要pip install pytest安装
import pytest
# 内置模块,无需安装
import os
# 内置模块,无需安装
import subprocess
# 内置模块,无需安装
import time
# 内置模块,无需安装
import tkinter as tk
# 需要pip install pygetwindow安装,获取指定标题的窗口对象列表
import pygetwindow as gw
# 需要pip install pyautogui安装,模拟鼠标和键盘操作
import pyautogui
# 一个全局变量声明,用于存储 Typora 窗口的引用。在代码中,它被初始化为 None,表示当前没有找到 Typora 窗口。
typora_window = None
@pytest.fixture(scope="session", autouse=True)
def setup_typora():
# 声明全局变量
global typora_window
# 启动Typora客户端软件(这个是设置了环境变量的打开方式)
# subprocess.Popen(["typora"])
# 下述是没有设置环境变量,直接输入路径打开软件的方式
subprocess.Popen(["D:\\Typora\\typora.exe"])
time.sleep(1)
# getWindowsWithTitle("Typora") 是 pygetwindow 库提供的一个函数,用于获取指定标题的窗口对象列表。
# 它返回一个包含所有标题为 "Typora" 的窗口对象的列表。
# 通过 [0],获取得了窗口列表中的第一个窗口对象,并赋值给全局变量typora_window。
# 在后续的代码中,我们可以使用 typora_window 来引用该窗口对象,执行一些与窗口相关的操作,如激活窗口、发送快捷键等。
typora_window = gw.getWindowsWithTitle("Typora")[0]
yield
# 执行完毕后关闭Typora客户端软件
# os.system(command) 函数用于执行操作系统命令。
# 在这里,command 是一个字符串参数,表示要执行的命令。
# 命令 "taskkill /f /im typora.exe" 是一个 Windows 系统命令,用于终止名为 "typora.exe" 的进程。
# taskkill 是一个 Windows 命令行工具,用于终止正在运行的进程。
# /f 参数表示强制终止进程,即不会弹出确认对话框。
# /im 参数后面跟着进程的映像名称(image name),即要终止的进程名。
# 执行 os.system("taskkill /f /im typora.exe") 时,它将调用操作系统的命令行界面,执行相应的命令。
# 在这种情况下,该命令将强制终止名为 "typora.exe" 的进程,关闭 Typora 客户端软件。
os.system("taskkill /f /im typora.exe")
def test_typora_is_running():
# 检查Typora客户端软件是否正在运行
assert typora_is_running()
def test_typora_open_file():
# 打开文件并检查是否成功
file_path = r"D:\Typora\TyporaFile\front\uniapp.md"
print(file_path)
time.sleep(0.5)
open_file_in_typora(file_path)
time.sleep(0.5)
#assert断言,执行后面的函数,判断是否执行成功,成功返回true,失败返回false
assert is_file_opened_in_typora(file_path)
def typora_is_running():
# 检查Typora客户端软件是否正在运行
return "Typora.exe" in os.popen("tasklist").read()
# 打开文件
def open_file_in_typora(file_path):
global typora_window
if typora_window:
typora_window.activate()
time.sleep(1)
# 模拟按下Ctrl+O
pyautogui.hotkey('ctrl', 'o')
time.sleep(1)
# 输入文件路径并按下回车
pyautogui.write(file_path)
time.sleep(0.5)
pyautogui.press('enter')
time.sleep(0.5)
pyautogui.press('enter')
time.sleep(0.5)
else:
# 如果快捷键ctrl+o不能打开文件,则直接打开文件
# subprocess.run(["typora", file_path])#执行当前代码会多打开一个typora文件
subprocess.Popen(["typora", file_path], creationflags=subprocess.DETACHED_PROCESS)#执行代码将在原有typora文件上执行打开文件
time.sleep(2)
def is_file_opened_in_typora(file_path):
# 使用getWindows()函数获取所有窗口,并逐个检查窗口的标题和进程名称是否符合Typora窗口的条件。
windows = gw.getWindowsWithTitle("Typora")
#提取文件名,而不是整个路径,如果不进行转换,则获取的是整个file_name路径"D:\Typora\TyporaFile\front\ES6.md"
#然后将其与Typora窗口的标题进行比较
file_name = os.path.basename(file_path)
# 对windows中的每一个元素进行遍历
for window in windows:
# 判断文件名和windows打开的typora文件的标头是否相同,相同返回Ture,不相同返回False
if file_name in window.title:
return True
return False