You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用WP_UnitTestCase与Selenium测试WordPress时如何登录用户?

解决Selenium与WP_UnitTestCase的登录状态共享问题

这个问题我之前也碰到过!核心原因是WP_UnitTestCase的PHP运行环境和Selenium控制的浏览器是完全隔离的两个进程——你在PHP里调用的wp_set_current_user和wp_set_auth_cookie只存在于单元测试的内存和PHP环境中,浏览器根本拿不到这些Cookie。要解决这个问题,我们需要手动把WordPress生成的登录Cookie注入到Selenium的浏览器里,具体步骤和代码如下:

关键思路

  1. 在单元测试环境中生成符合WordPress标准的登录Cookie值
  2. 初始化Selenium WebDriver后,先访问一次WordPress站点(确保浏览器处于目标域名下)
  3. 将生成的Cookie逐个添加到浏览器中,刷新页面使Cookie生效

修改后的Fixture代码

public function setUp() {
    // 务必先调用父类的setUp,初始化WordPress测试环境
    parent::setUp();

    // 1. 创建测试管理员用户(不依赖固定ID=1,更可靠)
    $user_id = $this->factory->user->create([
        'role' => 'administrator',
        'user_login' => 'test_admin',
        'user_pass' => 'test_pass123'
    ]);
    $user = get_user_by('id', $user_id);

    if ($user) {
        // 2. 生成WordPress认证所需的Cookie值
        $expiration = time() + DAY_IN_SECONDS; // Cookie有效期设为1天
        $logged_in_cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in');
        $auth_cookie = wp_generate_auth_cookie($user_id, $expiration, 'auth');

        // 获取WordPress的Cookie配置
        $logged_in_cookie_name = LOGGED_IN_COOKIE;
        $auth_cookie_name = AUTH_COOKIE;
        $cookie_domain = COOKIE_DOMAIN ?: parse_url(get_home_url(), PHP_URL_HOST);
        $cookie_path = COOKIE_PATH ?: '/';
        $is_secure = is_ssl();
        $is_httponly = true; // WordPress默认开启HttpOnly保护
    }

    // 3. 初始化Selenium WebDriver
    $host = 'http://localhost:4444/wd/hub';
    $desired_capabilities = DesiredCapabilities::firefox();
    $desired_capabilities->setCapability('acceptSslCerts', false);
    $this->webDriver = RemoteWebDriver::create($host, $desired_capabilities);

    // 4. 先访问WordPress首页,确保浏览器处于目标域名下(必须步骤!)
    $home_url = get_home_url();
    $this->webDriver->get($home_url);

    // 5. 向浏览器注入登录Cookie
    if ($user) {
        // 添加Logged In Cookie(核心登录凭证)
        $this->webDriver->manage()->addCookie([
            'name'     => $logged_in_cookie_name,
            'value'    => $logged_in_cookie,
            'domain'   => $cookie_domain,
            'path'     => $cookie_path,
            'secure'   => $is_secure,
            'httpOnly' => $is_httponly,
            'expires'  => $expiration
        ]);

        // 添加Auth Cookie(部分后台操作可能需要)
        $this->webDriver->manage()->addCookie([
            'name'     => $auth_cookie_name,
            'value'    => $auth_cookie,
            'domain'   => $cookie_domain,
            'path'     => $cookie_path,
            'secure'   => $is_secure,
            'httpOnly' => $is_httponly,
            'expires'  => $expiration
        ]);

        // 刷新页面,让Cookie生效
        $this->webDriver->navigate()->refresh();
    }
}

重要细节说明

  • 调用parent::setUp():WP_UnitTestCase的父类方法会初始化数据库连接、测试工厂等核心环境,必须放在最前面。
  • 使用测试工厂创建用户:避免依赖固定用户ID(比如1),测试环境中可能不存在该用户,用$this->factory->user->create()能确保用户存在。
  • 先访问站点再设置Cookie:Selenium的Cookie是绑定到当前页面域名的,如果不先访问目标站点,会因域名不匹配导致Cookie添加失败。
  • 使用wp_generate_auth_cookie:这是WordPress内部生成认证Cookie的官方函数,能保证Cookie格式和登录逻辑完全一致,比手动构造更可靠。
  • Cookie属性匹配:确保domain、secure等属性和WordPress的配置一致,比如站点是HTTPS时,secure要设为true。

问题排查小技巧

如果注入Cookie后还是未登录,可以检查:

  1. 浏览器访问的URL和get_home_url()返回的地址是否完全一致(包括端口、HTTP/HTTPS)
  2. 查看浏览器的开发者工具(Application -> Cookies),确认Cookie是否成功添加且属性正确
  3. 检查WordPress的COOKIE_DOMAIN配置是否正确,若为空则会自动从home_url解析

内容的提问来源于stack exchange,提问作者Hans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:17:55