Files
bun.sh/test/cli/user-agent.test.ts
robobun 599947de28 Add --user-agent flag to customize HTTP request User-Agent header (#21894)
## Summary
- Adds `--user-agent` CLI flag to allow customizing the default
User-Agent header for HTTP requests
- Maintains backward compatibility with existing default behavior
- Includes comprehensive tests

## Test plan
- [x] Added unit tests for both custom and default user-agent behavior
- [x] Tested manually with external HTTP service (httpbin.org)
- [x] Verified existing tests still pass

@thdxr I built this for you! 🎉

🤖 Generated with [Claude Code](https://claude.ai/code)

---------

Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2025-08-15 17:51:35 -07:00

80 lines
1.8 KiB
TypeScript

import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, tempDirWithFiles } from "harness";
describe("--user-agent flag", () => {
test("custom user agent is sent in HTTP requests", async () => {
const customUserAgent = "MyCustomUserAgent/1.0";
const testScript = `
const server = Bun.serve({
port: 0,
async fetch(request) {
const userAgent = request.headers.get("User-Agent");
if (userAgent === "${customUserAgent}") {
process.exit(0); // SUCCESS
} else {
process.exit(1); // FAIL
}
},
});
// Make request to self
try {
await fetch(\`http://localhost:\${server.port}/test\`);
} catch (error) {
process.exit(1);
}
`;
const dir = tempDirWithFiles("user-agent-test", {
"test.js": testScript,
});
await using proc = Bun.spawn({
cmd: [bunExe(), "--user-agent", customUserAgent, "test.js"],
env: bunEnv,
cwd: dir,
});
const exitCode = await proc.exited;
expect(exitCode).toBe(0);
});
test("default user agent is used when --user-agent is not specified", async () => {
const testScript = `
const server = Bun.serve({
port: 0,
async fetch(request) {
const userAgent = request.headers.get("User-Agent");
// Default Bun user agent should contain "Bun/"
if (userAgent && userAgent.includes("Bun/")) {
process.exit(0); // SUCCESS
} else {
process.exit(1); // FAIL
}
},
});
// Make request to self
try {
await fetch(\`http://localhost:\${server.port}/test\`);
} catch (error) {
process.exit(1);
}
`;
const dir = tempDirWithFiles("user-agent-default-test", {
"test.js": testScript,
});
await using proc = Bun.spawn({
cmd: [bunExe(), "test.js"],
env: bunEnv,
cwd: dir,
});
const exitCode = await proc.exited;
expect(exitCode).toBe(0);
});
});