我会尝试简化我的问题。我正在使用 py.test 和 appium 编写一个测试程序。现在:
在应用程序中,我有 4 种媒体格式:视频、音频、图像和文档。 我有一个带有上一个、下一个、播放、停止按钮的控制界面。 每种媒体格式都有一个唯一的 ID,例如
video_playbutton、audio_playbutton、document_playbutton、image_playbutton、video_stopbutton、audio_stopbutton ...等等等
但是我必须做的操作对于所有这些都是相同的,例如按播放按钮。
当我像这样明确给出它们时,我可以解决每个播放按钮的问题
find_element_by_id("video_playbutton")
当我想按其他播放按钮时,我每次都必须重复上面的行。像这样:
find_element_by_id("video_playbutton")
find_element_by_id("audio_playbutton")
find_element_by_id("image_playbutton")
find_element_by_id("document_playbutton")
因为我是从另一个脚本调用这个函数,所以我必须首先区分我得到的字符串,例如:
def play(mediatype):
if mediatype == "video"
el = find_element_by_id("video_playbutton")
el.click()
if mediatype == "audio"
el = find_element_by_id("audio_playbutton")
el.click()
if .....
解决这种情况的最佳方法是什么?我想避免数百个 if 语句,因为还有 stop、next、previous 等按钮。
我正在寻找这样的东西
def play(mediatype)
find_element_by_id(mediatype.playbutton)
最佳答案
您可以将选择器和操作分离到两个字典中,这样可以更好地扩展。否则映射最终会变得巨大。这是示例。
dictMedia = {'video':['video_playbutton', 'video_stopbutton','video_nextbutton'], 'audio':['audio_playbutton', 'audio_stopbutton', 'audio_nextbutton']}
dictOperations = {'play':0, 'stop':1, 'next':2}
def get_selector(mediatype, operation):
return dictMedia[mediatype][dictOperations[operation]]
print get_selector('video', 'play')
PS:以上操作不会检查 key 未找到错误。 不过,我仍然觉得,如果媒体特定操作增长,那么页面对象模型会更好。
关于Python 如何避免大量 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37792150/