MCPcopy
hub / github.com/microsoft/playwright / PythonCodeGen

Class PythonCodeGen

packages/trace-viewer/src/ui/codegen.ts:102–177  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

100}
101
102class PythonCodeGen implements APIRequestCodegen {
103 generatePlaywrightRequestCall(request: har.Request, body: string | undefined): string {
104 const url = new URL(request.url);
105 const urlParam = `${url.origin}${url.pathname}`;
106 const params: string[] = [`"${urlParam}"`];
107
108
109 let method = request.method.toLowerCase();
110 if (!['delete', 'get', 'head', 'post', 'put', 'patch'].includes(method)) {
111 params.push(`method="${method}"`);
112 method = 'fetch';
113 }
114
115 if (url.searchParams.size)
116 params.push(`params=${this.prettyPrintObject(Object.fromEntries(url.searchParams.entries()))}`);
117 if (body)
118 params.push(`data=${this.prettyPrintObject(body)}`);
119 if (request.headers.length)
120 params.push(`headers=${this.prettyPrintObject(Object.fromEntries(request.headers.map(header => [header.name, header.value])))}`);
121
122 const paramsString = params.length === 1 ? params[0] : `\n${params.map(p => this.indent(p, 2)).join(',\n')}\n`;
123 return `await page.request.${method}(${paramsString})`;
124 }
125
126 private indent(v: string, level: number): string {
127 return v.split('\n').map(s => ' '.repeat(level) + s).join('\n');
128 }
129
130 private prettyPrintObject(obj: any, indent = 2, level = 0): string {
131 // Handle null and undefined
132 if (obj === null)
133 return 'None';
134 if (obj === undefined)
135 return 'None';
136
137 // Handle primitive types
138 if (typeof obj !== 'object') {
139 if (typeof obj === 'string')
140 return this.stringLiteral(obj);
141 if (typeof obj === 'boolean')
142 return obj ? 'True' : 'False';
143 return String(obj);
144 }
145
146 // Handle arrays
147 if (Array.isArray(obj)) {
148 if (obj.length === 0)
149 return '[]';
150 const spaces = ' '.repeat(level * indent);
151 const nextSpaces = ' '.repeat((level + 1) * indent);
152
153 const items = obj.map(item =>
154 `${nextSpaces}${this.prettyPrintObject(item, indent, level + 1)}`
155 ).join(',\n');
156
157 return `[\n${items}\n${spaces}]`;
158 }
159

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…