Download Game! Currently 58 players and visitors. Last logged in:NarcosisIberiamsspVihaanSirda

Blitzer's Blog >> 72288

Back to blogs index
Posted: 12 Sep 2026 03:47 [ permalink ]
Yes, automated unit testing is the absolute gold standard for building a
reliable code library with an API. This entirely removes human guesswork and
ensures you only save code that actually works.
Because we explicitly instructed the model to output raw code without markdown
formatting, we can use JavaScript's native eval() or a safer isolated
execution context to run the generated code against your test inputs
immediately.
Here is a self-contained test runner script. It sends your prompt, dynamically
creates the function from DeepSeek's raw response, runs your test case, and
verifies the output.
## ð  The Automated Test Runner (test_and_build.js)

const https = require('https');
const SYSTEM_PROMPT = "Act as an expert software engineer. Output valid
JavaScript function code only. Do not include markdown formatting blocks (no
```). Do not include any explanations, usage examples, or comments.";
 * Requests the function string from DeepSeek
 */function generateCode(taskDescription) {
    return new Promise((resolve, reject) => {
        const apiKey = process.env.DEEPSEEK_API_KEY;
        if (!apiKey) return reject(new Error("Missing DEEPSEEK_API_KEY
environment variable."));

        const data = JSON.stringify({
            model: "deepseek-chat",
            messages: [
                { role: "system", content: SYSTEM_PROMPT },
                { role: "user", content: taskDescription }
            ],
            temperature: 0.1,
            max_tokens: 600
        });

        const req = https.request({
            hostname: '://deepseek.com',
            path: '/v1/chat/completions',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`,
                'Content-Length': data.length
            }
        }, (res) => {
            let body = '';
            res.on('data', (chunk) => body += chunk);
            res.on('end', () => {
                try {
                    const json = JSON.parse(body);
                    if (json.error) return reject(new Error(json.error.message)
);
                    resolve(json.choices[0].message.content.trim());
                } catch (e) { reject(e); }
            });
        });

        req.on('error', reject);
        req.write(data);
        req.end();
    });
}
 * Safely evaluates the string and tests it against inputs/outputs
 */function testAndVerify(functionCodeString, testInput, expectedOutput) {
    try {
        // Evaluate the string to instantiate the function in local scope
        // This expects DeepSeek to return something like: function
reverseString(str) { ... }
        const instantiatedFunction = eval(`(${functionCodeString})`);
        
        // Execute the function with your sample input
        const actualOutput = instantiatedFunction(testInput);
        
        // Deep equality check for primitives or objects/arrays
        const pass = JSON.stringify(actualOutput) === JSON.stringify(expectedOu
tput);
        
        return {
            pass,
            actual: actualOutput,
            error: null
        };
    } catch (err) {
        return { pass: false, actual: null, error: err.message };
    }
}
    // 1. Define your blueprint cleanly
    const task = `Write a JavaScript function named 'extractDomain' that
accepts a full URL string and extracts just the domain name.
    Input example: "https://deepseek.com"
    Expected output: "://deepseek.com"`;

    const sampleInput = "https://deepseek.com";
    const expectedOutput = "://deepseek.com";

    console.log("ð Sending routine task to DeepSeek...");
    try {
        const rawCode = await generateCode(task);
        console.log("
--- RECEIVED RAW CODE ---");
        console.log(rawCode);
        console.log("-------------------------
");

        console.log("𧪠Executing automated test assertion...");
        const result = testAndVerify(rawCode, sampleInput, expectedOutput);

        if (result.pass) {
            console.log("â TEST PASSED! The routine matches your expected
output perfectly.");
            // Here you could safely append/write rawCode to your library
file!
        } else {
            console.log("â TEST FAILED.");
            if (result.error) {
                console.log(`Runtime Error: ${result.error}`);
            } else {
                console.log(`Expected: ${JSON.stringify(expectedOutput)}`);
                console.log(`Received: ${JSON.stringify(result.actual)}`);
            }
        }
    } catch (error) {
        console.error("Pipeline failure:", error.message);
    }
}

main();

## ð Efficiency and Execution Strategy

* Double Input Optimization: By supplying the input and output directly inside
your prompt description, you ground the AI. It uses significantly fewer tokens
iterating because it doesn't have to guess what your edge cases are.
* Instant Validation: If a script fails the testAndVerify function, you can
throw it away immediately without ever looking at it, saving engineering time.

Would you like to build an automated loop around this so that if a test fails,
the runner automatically takes the error message, feeds it back into DeepSeek
as a follow-up prompt, and asks for a corrected version?