我使用 selenium 与 chromeDriver 进行端到端测试。要测试的网站需要 ssl 证书。当我手动打开浏览器时,会出现一个弹出窗口,让我选择已安装的证书。不同的测试访问不同的URL,也需要不同的证书。但是,如果我在无头模式下运行测试,则不会弹出窗口。因此,我需要一种以编程方式设置用于当前测试的证书(例如设置
.pem
文件)的方法。
我怎样才能实现这个目标? 我尝试设置一个 browserMob 代理,然后将其配置为 selenium 中的代理 - 但是,这似乎没有做任何事情......有更好的方法吗?我究竟做错了什么?这是我尝试过的:
PemFileCertificateSource pemFileCertificateSource = new PemFileCertificateSource(
new File("myCertificate.pem"),
new File("myPrivateKey.pem"),
"myPrivateKeyPassword");
ImpersonatingMitmManager mitmManager = ImpersonatingMitmManager.builder()
.rootCertificateSource(pemFileCertificateSource)
.build();
BrowserMobProxy browserMobProxy = new BrowserMobProxyServer();
browserMobProxy.setTrustAllServers(true);
browserMobProxy.setMitmManager(mitmManager);
browserMobProxy.start(8080);
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setProxy(ClientUtil.createSeleniumProxy(browserMobProxy));
WebDriver webDriver = new ChromeDriver(chromeOptions);
// use the webdriver for tests, e.g. assertEquals("foo", webDriver.findElement(...))
显然,这对于开箱即用的 BrowserMob 是不可能的。因此,我编写了一个代理扩展
SeleniumSslProxy
,可以插入 Selenium 并添加基于证书的身份验证来创建 HTTPS 连接。
这就是它的工作原理:
SSLContext
并提供证书(.pfx 文件)和密码 Response
转换为 netty FullHttpResponse
,以便可以由 Selenium 处理您可以在 github 上找到代码。以下是如何在 Selenium 端到端测试中使用它的示例(也适用于无头模式):
@Before
public void setup() {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File clientSslCertificate = new File(
classLoader.getResource("certificates/some-certificate.pfx").getFile());
String certificatePassword = "superSecret";
this.proxy = new SeleniumSslProxy(clientSslCertificate, certificatePassword);
this.proxy.start();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setProxy(proxy);
this.webDriver = new ChromeDriver(chromeOptions);
}
@Test
public void pageTitleIsFoo() {
// given
String url = "http://myurl.lol";
// NOTE: do not use https in the URL here. It will be converted to https by the proxy.
// when
this.webDriver.get(url);
this.webDriver.manage().timeouts().implicitlyWait(5, SECONDS);
// then
WebElement title = this.webDriver.findElement(By.className("title"));
assertEquals("Foo", title.getText());
}
@After
public void teardown() {
this.webDriver.quit();
this.proxy.stop();
}
请注意,我只使用了 chromeDriver,从未使用其他驱动程序对其进行过测试。可能需要对
SeleniumSslProxy
进行细微调整才能与其他驱动程序一起使用。
如何声明“this.proxy”? 我的代码无法识别“SeleniumSslProxy”。如何导入?
拜托,我需要帮助。