繁体   English   中英

如何处理用户登录 session 并为 selenium 中的所有任务使用相同的会话/用户?

[英]How to handle user login session and use the same session/user for all the task in selenium?

我想运行一次登录脚本,每当我再次运行它时,它都不会要求我登录。

请帮助我如何处理 selenium 中的这种情况。

访问 Selenium 文档指南生成应用程序 state有提到

应创建一种方法来访问 AUT*(例如,使用 API 登录并设置 cookie)

您可以编写一个方法来在登录后保存所有 cookies。 现在在需要登录的测试中使用相同的 cookies。

driver = new ChromeDriver();
driver.get("https://www.somesite.com/login/");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElementById("email").sendKeys("someemail@gmail.com");
driver.findElementById("pass").sendKeys("pass@312");
driver.findElementById("send2").click();

// after successful login get cookies and store in a map for further use
Set<Cookie> cookies = driver.manage().getCookies();
Map<String, Object> cookieMap = new HashMap<>();
cookieMap.put("myCookies", cookies);
driver.quit();

// some other testcase which require auto login
driver = new ChromeDriver();
driver.get("https://www.somesite.com");
    
// get store cookies and add them after refresh the page you will see user automatically get logged in
Set<Cookie> storeCookies = (Set<Cookie>) cookieMap.get("myCookies");
storeCookies.forEach(cookie -> driver.manage().addCookie(cookie));
driver.navigate().refresh();

请注意,我已经在单个文件中编写了所有代码,您需要根据您的框架来管理它。 例如,这个 Cookie Map 应该可以在您的所有测试课程中访问。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM