我正在尝试使用机器人框架自动进行一些测试。在某些测试案例中,我必须将cookie注入到webdriver中(目前仅使用Firefox)。我在测试用例中的注入代码如下:
Access MyDomain
[Documentation] Open browser in sub.mydomain.com and inject cookies.
[Arguments] ${pdata}
${json_str} = Get File ${pdata}
${json_data} = evaluate json.loads('''${json_str}''') json
Open Browser https://sub.mydomain.com browser=ff
Wait Until Page Contains Welcome to mydomain
FOR ${cookie} IN @{json_data["cookies"]}
add cookie ${cookie['name']} ${cookie['value']} path = ${cookie['path']} domain = ${cookie['domain']}
END
某些Cookie的域为“ sub.mydomain.com ”,而某些Cookie的域为“ .mydomain.com ”。对于第二个,RobotFramework导致 InvalidCookieDomainException 。
但是,以下python代码可以在同一Firefox Selenium WebDriver上直接正常运行:
import json, time
from selenium.webdriver import Firefox, FirefoxProfile
def inject_cookies_to_firefox(domain, dataCookies = None):
cookies_objects = []
if dataCookies:
mcookies= json.loads(dataCookies)
if "cookies" in mcookies:
cookies = credentials["cookies"]
for cookie in cookies:
cookies_objects.append({
'path': cookie.get("path"),
'domain': cookie.get("domain"),
'name': cookie.get("name"),
"value": cookie.get("value")}
)
else:
return -1
else:
return -1
ff_profile = FirefoxProfile()
driver = Firefox(ff_profile)
driver.get(domain)
for item in cookies_objects:
try:
driver.add_cookie(item)
except:
print(f"Error injecting cookie: {item}")
return -1
print("Cookies injected.")
time.sleep(10)
driver.quit()
return ff_profile.path
在浏览器(https://sub.mydomain.com)中打开相同的URL时,此代码将毫无例外地注入domain =“ sub.mydomain.com”的cookie和domain =“ .mydomain.com”的cookie。>
有什么区别?RF是否不使用完全相同的Selenium Webdriver代码?还是...?
答案 0 :(得分:0)
简单的答案,“请特别注意RF中的空格”。代替
add cookie ${cookie['name']} ${cookie['value']} path = ${cookie['path']} domain = ${cookie['domain']}
使用:
add cookie ${cookie['name']} ${cookie['value']} path=${cookie['path']} domain=${cookie['domain']}
我这边是个愚蠢的“ newby”错误。