-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
147 lines (126 loc) · 4.74 KB
/
Copy pathserver.js
File metadata and controls
147 lines (126 loc) · 4.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs-extra');
const axios = require('axios');
const app = express();
const PORT = 8082;
app.use(cors());
app.use(express.json());
app.use(express.static(__dirname));
// API endpoint for conversion
app.post('/api/convert', async (req, res) => {
const { source_code, target_lang = 'typescript' } = req.body;
if (!source_code) {
return res.status(400).json({ status: 'error', msg: 'No source code provided' });
}
try {
const result = await performConversion(source_code, target_lang);
res.json(result);
} catch (error) {
console.error('Conversion error:', error);
res.status(500).json({ status: 'error', msg: error.message });
}
});
async function performConversion(sourceCode, targetLang) {
const projectName = 'converted_playwright_test';
const baseDir = path.join(__dirname, projectName);
const testsDir = path.join(baseDir, 'tests');
// Ensure directory structure
if (!fs.existsSync(baseDir)) {
await fs.ensureDir(baseDir);
// package.json for generated project
await fs.writeJson(path.join(baseDir, 'package.json'), {
name: projectName,
version: "1.0.0",
devDependencies: { "@playwright/test": "^1.40.0" },
scripts: { test: "npx playwright test" }
}, { spaces: 2 });
// playwright.config.ts
const pwConfig = `import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true,
reporter: 'html',
use: { trace: 'on-first-retry', screenshot: 'only-on-failure' },
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
});`;
await fs.writeFile(path.join(baseDir, 'playwright.config.ts'), pwConfig);
// tsconfig.json
const tsConfig = `{
"compilerOptions": {
"target": "ESNext",
"module": "CommonJS",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"types": ["node", "@playwright/test"]
},
"include": ["tests/**/*.ts", "playwright.config.ts"]
}`;
await fs.writeFile(path.join(baseDir, 'tsconfig.json'), tsConfig);
}
await fs.ensureDir(testsDir);
// Get model info from Ollama
let model = 'tinyllama:latest';
try {
const tagsRes = await axios.get('http://localhost:11434/api/tags');
const models = tagsRes.data.models.map(m => m.name);
if (models.includes('llama3.2:1b')) model = 'llama3.2:1b';
else if (models.includes('llama3.2:3b')) model = 'llama3.2:3b';
else if (models.includes('tinyllama:latest')) model = 'tinyllama:latest';
} catch (e) {
console.warn('Ollama not reachable, using default model mapping');
}
const prompt = `### Role
You are a Senior Playwright Automation Engineer.
### Task
Convert the provided Selenium Java (TestNG) code into modern, idiomatic Playwright TypeScript.
### STRICT RULES:
1. Use Playwright Test runner style: test('description', async ({ page }) => { ... });
2. Import correctly: import { test, expect } from '@playwright/test';
3. Use page.goto() for navigation.
4. Use page.locator('selector') and perform actions: .fill(), .click().
5. Use web-first assertions: await expect(page).toHaveTitle('...'), await expect(locator).toBeVisible().
6. NO manual browser launching. NO decorators like @Test.
7. Wrap tests in test.describe if multiple tests are found.
### Example Conversion:
#### Input (Selenium):
@Test
public void loginTest() {
driver.get("url");
driver.findElement(By.id("u")).sendKeys("user");
Assert.assertEquals(driver.getTitle(), "Home");
}
#### Output (Playwright):
test('login test', async ({ page }) => {
await page.goto('url');
await page.locator('#u').fill('user');
await expect(page, "Should have correct title").toHaveTitle('Home');
});
### Code to Convert:
${sourceCode}`;
const generateRes = await axios.post('http://localhost:11434/api/generate', {
model: model,
prompt: prompt,
stream: false,
options: { temperature: 0 }
});
let code = generateRes.data.response.trim();
const codeMatch = code.match(/```(?:\w+)?\s*([\s\S]*?)```/);
if (codeMatch) code = codeMatch[1].trim();
const ext = targetLang === 'typescript' ? 'spec.ts' : 'spec.js';
const filePath = path.join(testsDir, `test.${ext}`);
await fs.writeFile(filePath, code);
return {
status: 'success',
path: filePath,
model: model,
converted_code: code
};
}
app.listen(PORT, () => {
console.log(`\x1b[36m🚀 Node.js Server started on http://localhost:${PORT}\x1b[0m`);
console.log(`Press Ctrl+C to stop.`);
});