我正在尝试使用 Playwright 进行 API 测试。简单的情况是我正在尝试获取有关用户的信息。要使用curl 执行此操作,我可以发出命令:
curl --user username:password https://example.com/api/user/id
Run Code Online (Sandbox Code Playgroud)
这将返回一些 JSON。超级简单。
我已经阅读了 Playwright 文档,观看了一些 YouTube 视频并搜索了各种来源,但不知道如何在 Playwright 中复制它!
我的请求始终得到“403 Forbidden”的响应。
在我的playwright.config.ts文件中,我添加了httpCredentials这样的内容:
curl --user username:password https://example.com/api/user/id
Run Code Online (Sandbox Code Playgroud)
与此同时,在我的apiExperiment.spec.ts文件中:
import type { PlaywrightTestConfig } from '@playwright/test';
import { devices } from '@playwright/test';
const config: PlaywrightTestConfig = {
[...]
use: {
headless: false,
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
actionTimeout: 0,
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'https://example.com',
httpCredentials: {
username: 'username',
password: 'password'
},
[...]
Run Code Online (Sandbox Code Playgroud)
正如我之前所说,这只会导致“403 Forbidden”。
我尝试过此主题的变体,例如httpCredentials从配置文件中删除 ,然后将apiExperiment.spec.ts文件更改为:
import {test} from '@playwright/test';
test.describe('Test the API', () => {
test('Get user info', async({request}) => {
let userInfo = await request.post('/api/user/id');
});
});
Run Code Online (Sandbox Code Playgroud)
还有另一种变化...
import {test} from '@playwright/test';
test.describe('Test the API', () => {
test('Get user info', async({request}) => {
let userInfo = await request.post('/api/user/id', {
data: {
username: 'username',
password: 'password',
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
但无济于事。
任何与此有关的帮助将不胜感激。
经过一番广泛的挖掘后,我设法解决了这个问题。问题是,显然如果您使用httpCredentials,Playwright 将发出省略标头的请求Authorization。然后,它期望响应中出现 401 状态代码,如果收到该状态代码,将使用标头中指定的凭据重复请求。
这种行为对我来说是一个问题,因为没有凭据的请求会导致响应代码为 403。
在谈论我应用的修复之前,我应该添加一个警告,它可能并不适合所有情况 - 我在配置文件中进行了更改,因为我希望在Authorization整个测试中使用标头。另外,我确信有比将用户名和密码硬编码到配置文件中更安全/首选的方法来存储用户名和密码,但我在这里关心的是让某些东西正常工作。
记住这些注意事项,我实现此工作的方法是对用户名和密码进行编码并手动定义标Authorization头playwright.config.ts:
import type { PlaywrightTestConfig } from '@playwright/test';
import { devices } from '@playwright/test';
const httpCredentials = {
username: 'username',
password: 'password',
};
const btoa = (str: string) => Buffer.from(str).toString('base64');
const credentialsBase64 = btoa(`${httpCredentials.username}:${httpCredentials.password}`);
const config: PlaywrightTestConfig = {
// ...
use: {
// ...
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'https://example.com',
extraHTTPHeaders: {
'Authorization': `Basic ${credentialsBase64}`
},
// ...
};
Run Code Online (Sandbox Code Playgroud)
之后,Authorization标头将添加到对服务器的每次调用中,并且一切都会按预期进行。
| 归档时间: |
|
| 查看次数: |
11630 次 |
| 最近记录: |