From f58aecfb8e81725e69ff3de9ded41b28d30f5bda Mon Sep 17 00:00:00 2001 From: jharris1679 Date: Sun, 15 Feb 2026 23:51:48 -0500 Subject: [PATCH] feat: add 15 bootstrap test cases for universal coding tasks (#5) --- cases/bootstrap/api-documentation.yaml | 94 +++++++++++ cases/bootstrap/authentication.yaml | 64 ++++++++ cases/bootstrap/code-readability.yaml | 68 ++++++++ cases/bootstrap/component-extraction.yaml | 103 ++++++++++++ cases/bootstrap/error-handling.yaml | 63 ++++++++ cases/bootstrap/input-validation.yaml | 74 +++++++++ cases/bootstrap/logging.yaml | 70 ++++++++ cases/bootstrap/memory-leak.yaml | 78 +++++++++ cases/bootstrap/performance-optimization.yaml | 88 ++++++++++ cases/bootstrap/race-condition.yaml | 68 ++++++++ cases/bootstrap/refactor-long-functions.yaml | 153 ++++++++++++++++++ cases/bootstrap/sql-injection.yaml | 62 +++++++ cases/bootstrap/typescript-types.yaml | 61 +++++++ cases/bootstrap/unit-test-generation.yaml | 69 ++++++++ 14 files changed, 1115 insertions(+) create mode 100644 cases/bootstrap/api-documentation.yaml create mode 100644 cases/bootstrap/authentication.yaml create mode 100644 cases/bootstrap/code-readability.yaml create mode 100644 cases/bootstrap/component-extraction.yaml create mode 100644 cases/bootstrap/error-handling.yaml create mode 100644 cases/bootstrap/input-validation.yaml create mode 100644 cases/bootstrap/logging.yaml create mode 100644 cases/bootstrap/memory-leak.yaml create mode 100644 cases/bootstrap/performance-optimization.yaml create mode 100644 cases/bootstrap/race-condition.yaml create mode 100644 cases/bootstrap/refactor-long-functions.yaml create mode 100644 cases/bootstrap/sql-injection.yaml create mode 100644 cases/bootstrap/typescript-types.yaml create mode 100644 cases/bootstrap/unit-test-generation.yaml diff --git a/cases/bootstrap/api-documentation.yaml b/cases/bootstrap/api-documentation.yaml new file mode 100644 index 0000000..1c26c31 --- /dev/null +++ b/cases/bootstrap/api-documentation.yaml @@ -0,0 +1,94 @@ +id: bootstrap-019 +title: "Add API Documentation" +prompt: | + The following Node.js API has no documentation. Add comprehensive API documentation + to help developers understand and use the API. + + The documentation should: + - Document all endpoints + - Include request/response examples + - Describe parameters and their types + - Include error codes and their meanings + - Provide usage examples + - Follow API documentation best practices + - Include authentication requirements + + Run: npm run build + +source: bootstrap +category: documentation +language: javascript +difficulty: easy + +tags: + - javascript + - documentation + - api-docs + - openapi + +files: + - path: api_server.js + content: | + const http = require('http'); + + const server = http.createServer((req, res) => { + const url = req.url; + const method = req.method; + + // GET /api/users - Get all users + if (url === '/api/users' && method === 'GET') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify([ + { id: 1, name: 'Alice', email: 'alice@example.com' }, + { id: 2, name: 'Bob', email: 'bob@example.com' } + ])); + } + // POST /api/users - Create a new user + else if (url === '/api/users' && method === 'POST') { + let body = ''; + req.on('data', chunk => body += chunk); + req.on('end', () => { + const user = JSON.parse(body); + res.writeHead(201, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ id: 3, ...user })); + }); + } + // PUT /api/users/:id - Update a user + else if (url.startsWith('/api/users/') && method === 'PUT') { + const userId = url.split('/')[3]; + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ id: parseInt(userId), message: 'User updated' })); + } + // DELETE /api/users/:id - Delete a user + else if (url.startsWith('/api/users/') && method === 'DELETE') { + const userId = url.split('/')[3]; + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ id: parseInt(userId), message: 'User deleted' })); + } + // GET /api/posts - Get all posts + else if (url === '/api/posts' && method === 'GET') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify([ + { id: 1, title: 'First Post', content: 'Hello world' }, + { id: 2, title: 'Second Post', content: 'Another post' } + ])); + } + // POST /api/posts - Create a new post + else if (url === '/api/posts' && method === 'POST') { + let body = ''; + req.on('data', chunk => body += chunk); + req.on('end', () => { + const post = JSON.parse(body); + res.writeHead(201, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ id: 3, ...post })); + }); + } + else { + res.writeHead(404, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Not found' })); + } + }); + + server.listen(3000, () => { + console.log('Server running on port 3000'); + }); diff --git a/cases/bootstrap/authentication.yaml b/cases/bootstrap/authentication.yaml new file mode 100644 index 0000000..dbe5cfd --- /dev/null +++ b/cases/bootstrap/authentication.yaml @@ -0,0 +1,64 @@ +id: bootstrap-018 +title: "Implement Proper Authentication Checks" +prompt: | + The following Node.js API endpoints have no authentication or authorization. + Implement proper authentication to secure the API. + + The authentication should: + - Implement JWT-based authentication + - Add authentication middleware + - Protect sensitive endpoints + - Handle authentication errors properly + - Support role-based access control + - Use secure password hashing + + Run: node auth_test.js + +source: bootstrap +category: security +language: javascript +difficulty: medium + +tags: + - javascript + - security + - authentication + - authorization + +files: + - path: api_server.js + content: | + const http = require('http'); + + // Simple API server without authentication + const server = http.createServer((req, res) => { + const url = req.url; + const method = req.method; + + // Public endpoint + if (url === '/api/public' && method === 'GET') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ message: 'Public data' })); + } + // Protected endpoint - no authentication + else if (url === '/api/users' && method === 'GET') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify([ + { id: 1, name: 'Alice', email: 'alice@example.com' }, + { id: 2, name: 'Bob', email: 'bob@example.com' } + ])); + } + // Protected endpoint - no authentication + else if (url === '/api/admin' && method === 'GET') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ message: 'Admin data' })); + } + else { + res.writeHead(404, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Not found' })); + } + }); + + server.listen(3000, () => { + console.log('Server running on port 3000'); + }); diff --git a/cases/bootstrap/code-readability.yaml b/cases/bootstrap/code-readability.yaml new file mode 100644 index 0000000..e70aa30 --- /dev/null +++ b/cases/bootstrap/code-readability.yaml @@ -0,0 +1,68 @@ +id: bootstrap-015 +title: "Improve Code Readability" +prompt: | + The following JavaScript code is functional but has poor readability due to + unclear naming, complex logic, and lack of structure. + + Improve the code by: + - Renaming variables and functions to be descriptive + - Breaking down complex functions + - Adding comments where needed + - Following naming conventions + - Improving code structure + - Making the code self-documenting + + Run: node readability_test.js + +source: bootstrap +category: code-quality +language: javascript +difficulty: easy + +tags: + - javascript + - code-quality + - readability + - maintainability + +files: + - path: data_processor.js + content: | + function c(d, t, m) { + if (d <= 0) return 0; + if (m == 'domestic') { + if (d < 5) return 5; + if (d < 10) return 10; + if (d < 20) return 15; + return 25; + } + if (m == 'international') { + if (t == 'express') { + if (d < 5) return 20; + if (d < 10) return 35; + return 50; + } + if (d < 5) return 15; + if (d < 10) return 25; + return 40; + } + return null; + } + + function p(d, u) { + const r = c(d, 'standard', 'international'); + if (r === null) return null; + const s = r * 0.1; + const f = s + 2.5; + return f; + } + + function s(d, t, m) { + const r = c(d, t, m); + if (r === null) return null; + const s = r * 0.1; + const f = s + 2.5; + return f; + } + + module.exports = { c, p, s }; diff --git a/cases/bootstrap/component-extraction.yaml b/cases/bootstrap/component-extraction.yaml new file mode 100644 index 0000000..f9ae318 --- /dev/null +++ b/cases/bootstrap/component-extraction.yaml @@ -0,0 +1,103 @@ +id: bootstrap-013 +title: "Extract Reusable Components from Duplicated Code" +prompt: | + The following JavaScript code has significant code duplication. Extract common + logic into reusable functions or components. + + The refactoring should: + - Identify duplicated code patterns + - Extract common logic into reusable functions + - Maintain the same functionality + - Improve code maintainability + - Follow DRY (Don't Repeat Yourself) principle + - Add proper documentation + + Run: node component_test.js + +source: bootstrap +category: refactoring +language: javascript +difficulty: medium + +tags: + - javascript + - refactoring + - code-quality + - dpry + +files: + - path: data_processor.js + content: | + // Duplicated code - same validation logic repeated + function validateEmail1(email) { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(email)) { + throw new Error('Invalid email format'); + } + return true; + } + + function validateEmail2(email) { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(email)) { + throw new Error('Invalid email format'); + } + return true; + } + + function validateEmail3(email) { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(email)) { + throw new Error('Invalid email format'); + } + return true; + } + + // Duplicated code - same formatting logic + function formatName1(firstName, lastName) { + return `${firstName} ${lastName}`.trim(); + } + + function formatName2(firstName, lastName) { + return `${firstName} ${lastName}`.trim(); + } + + function formatName3(firstName, lastName) { + return `${firstName} ${lastName}`.trim(); + } + + // Duplicated code - same error handling + function processUser1(user) { + try { + validateEmail1(user.email); + const formatted = formatName1(user.firstName, user.lastName); + return { ...user, formattedName: formatted }; + } catch (err) { + console.error('Error processing user:', err.message); + return null; + } + } + + function processUser2(user) { + try { + validateEmail2(user.email); + const formatted = formatName2(user.firstName, user.lastName); + return { ...user, formattedName: formatted }; + } catch (err) { + console.error('Error processing user:', err.message); + return null; + } + } + + function processUser3(user) { + try { + validateEmail3(user.email); + const formatted = formatName3(user.firstName, user.lastName); + return { ...user, formattedName: formatted }; + } catch (err) { + console.error('Error processing user:', err.message); + return null; + } + } + + module.exports = { processUser1, processUser2, processUser3 }; diff --git a/cases/bootstrap/error-handling.yaml b/cases/bootstrap/error-handling.yaml new file mode 100644 index 0000000..d4537eb --- /dev/null +++ b/cases/bootstrap/error-handling.yaml @@ -0,0 +1,63 @@ +id: bootstrap-007 +title: "Add Error Handling to Functions" +prompt: | + The following JavaScript functions perform operations without proper error handling. + Add try-catch blocks to handle potential errors gracefully. + + The functions should: + - Handle file read errors + - Handle network request failures + - Handle invalid input types + - Return meaningful error messages + - Not crash the application + + Run: node error_handling.test.js + +source: bootstrap +category: error-handling +language: javascript +difficulty: easy + +tags: + - javascript + - error-handling + - robustness + +files: + - path: user_service.js + content: | + const fs = require('fs').promises; + const https = require('https'); + + // Function to read user profile + function getUserProfile(userId) { + const filePath = `/data/users/${userId}.json`; + const data = fs.readFileSync(filePath, 'utf-8'); + return JSON.parse(data); + } + + // Function to fetch user data from external API + function fetchUserData(userId) { + const url = `https://api.example.com/users/${userId}`; + const data = https.get(url, (res) => { + let body = ''; + res.on('data', (chunk) => body += chunk); + res.on('end', () => { + return JSON.parse(body); + }); + }); + return data; + } + + // Function to validate user input + function validateUserInput(input) { + if (typeof input !== 'string') { + throw new Error('Input must be a string'); + } + if (input.length === 0) { + throw new Error('Input cannot be empty'); + } + return true; + } + + module.exports = { getUserProfile, fetchUserData, validateUserInput }; diff --git a/cases/bootstrap/input-validation.yaml b/cases/bootstrap/input-validation.yaml new file mode 100644 index 0000000..e80ce40 --- /dev/null +++ b/cases/bootstrap/input-validation.yaml @@ -0,0 +1,74 @@ +id: bootstrap-009 +title: "Add Input Validation to User-Facing Functions" +prompt: | + The following Node.js API functions accept user input without proper validation. + Add comprehensive input validation to ensure data integrity and security. + + The functions should: + - Validate email format + - Validate password strength + - Validate required fields + - Validate data types + - Return appropriate error messages + - Sanitize user input + + Run: node input_validation.test.js + +source: bootstrap +category: security +language: javascript +difficulty: medium + +tags: + - javascript + - validation + - security + - input-validation + +files: + - path: auth_service.js + content: | + const crypto = require('crypto'); + + // Function to register a new user + function registerUser(userData) { + const { email, password, name } = userData; + + // TODO: Add proper validation + const user = { + id: crypto.randomUUID(), + email, + password, + name, + createdAt: new Date() + }; + + return user; + } + + // Function to update user profile + function updateUserProfile(userId, updates) { + const { email, name, bio } = updates; + + // TODO: Add proper validation + const user = { + id: userId, + email, + name, + bio, + updatedAt: new Date() + }; + + return user; + } + + // Function to change password + function changePassword(userId, currentPassword, newPassword) { + // TODO: Add proper validation + return { + id: userId, + passwordChangedAt: new Date() + }; + } + + module.exports = { registerUser, updateUserProfile, changePassword }; diff --git a/cases/bootstrap/logging.yaml b/cases/bootstrap/logging.yaml new file mode 100644 index 0000000..54b061c --- /dev/null +++ b/cases/bootstrap/logging.yaml @@ -0,0 +1,70 @@ +id: bootstrap-016 +title: "Add Proper Logging and Monitoring" +prompt: | + The following Node.js application has no logging or monitoring. Add comprehensive + logging to track application behavior and performance. + + The logging should: + - Log important events (user actions, errors, state changes) + - Include contextual information (timestamps, user IDs, request IDs) + - Use appropriate log levels (debug, info, warn, error) + - Log performance metrics + - Support structured logging + - Make logs searchable and analyzable + + Run: node logging_test.js + +source: bootstrap +category: observability +language: javascript +difficulty: medium + +tags: + - javascript + - logging + - monitoring + - observability + +files: + - path: api_server.js + content: | + const http = require('http'); + + // Simple HTTP server without logging + const server = http.createServer((req, res) => { + const url = req.url; + const method = req.method; + + if (url === '/api/users' && method === 'GET') { + // Get all users + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify([ + { id: 1, name: 'Alice', email: 'alice@example.com' }, + { id: 2, name: 'Bob', email: 'bob@example.com' } + ])); + } else if (url === '/api/users' && method === 'POST') { + // Create user + let body = ''; + req.on('data', chunk => body += chunk); + req.on('end', () => { + const user = JSON.parse(body); + res.writeHead(201, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ id: 3, ...user })); + }); + } else if (url === '/api/users' && method === 'PUT') { + // Update user + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ message: 'User updated' })); + } else if (url === '/api/users' && method === 'DELETE') { + // Delete user + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ message: 'User deleted' })); + } else { + res.writeHead(404, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Not found' })); + } + }); + + server.listen(3000, () => { + console.log('Server running on port 3000'); + }); diff --git a/cases/bootstrap/memory-leak.yaml b/cases/bootstrap/memory-leak.yaml new file mode 100644 index 0000000..d08c579 --- /dev/null +++ b/cases/bootstrap/memory-leak.yaml @@ -0,0 +1,78 @@ +id: bootstrap-017 +title: "Fix Memory Leaks" +prompt: | + The following Node.js application has a memory leak. The application keeps + accumulating data in memory over time, causing performance degradation. + + Fix the memory leak by: + - Identifying the source of the leak + - Implementing proper cleanup mechanisms + - Using weak references where appropriate + - Ensuring event listeners are removed + - Implementing proper resource management + - Testing for memory stability + + Run: node memory_leak_test.js + +source: bootstrap +category: performance +language: javascript +difficulty: hard + +tags: + - javascript + - performance + - memory-leak + - resource-management + +files: + - path: data_collector.js + content: | + const EventEmitter = require('events'); + + class DataCollector extends EventEmitter { + constructor() { + super(); + this.data = []; + this.intervalId = null; + } + + startCollecting(intervalMs) { + this.intervalId = setInterval(() => { + const newData = { + id: Date.now(), + timestamp: new Date(), + value: Math.random() * 100 + }; + this.data.push(newData); + this.emit('data', newData); + }, intervalMs); + } + + stopCollecting() { + if (this.intervalId) { + clearInterval(this.intervalId); + this.intervalId = null; + } + } + + getData() { + return this.data; + } + + clearData() { + this.data = []; + } + } + + if (__filename === require.main.path) { + const collector = new DataCollector(); + collector.startCollecting(1000); + + // Simulate running for 30 seconds + setTimeout(() => { + collector.stopCollecting(); + console.log(`Collected ${collector.getData().length} data points`); + process.exit(0); + }, 30000); + } diff --git a/cases/bootstrap/performance-optimization.yaml b/cases/bootstrap/performance-optimization.yaml new file mode 100644 index 0000000..1929003 --- /dev/null +++ b/cases/bootstrap/performance-optimization.yaml @@ -0,0 +1,88 @@ +id: bootstrap-010 +title: "Optimize Performance Bottlenecks" +prompt: | + The following Python code has performance issues, particularly an N+1 query problem + when fetching user data with their orders. + + Optimize the code to: + - Eliminate N+1 query problem + - Use database indexing where appropriate + - Implement proper caching + - Reduce database round trips + - Maintain the same functionality + + Run: python performance_test.py + +source: bootstrap +category: performance +language: python +difficulty: medium + +tags: + - python + - performance + - database + - optimization + +files: + - path: order_service.py + content: | + import sqlite3 + from typing import List, Dict + + class OrderService: + def __init__(self, db_path: str = ':memory:'): + self.conn = sqlite3.connect(db_path) + self._init_db() + + def _init_db(self): + cursor = self.conn.cursor() + cursor.execute(''' + CREATE TABLE users ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + email TEXT UNIQUE NOT NULL + ) + ''') + cursor.execute(''' + CREATE TABLE orders ( + id INTEGER PRIMARY KEY, + user_id INTEGER NOT NULL, + product TEXT NOT NULL, + amount REAL NOT NULL, + FOREIGN KEY (user_id) REFERENCES users(id) + ) + ''') + # Insert sample data + cursor.execute('INSERT INTO users (name, email) VALUES (?, ?)', ('Alice', 'alice@example.com')) + cursor.execute('INSERT INTO users (name, email) VALUES (?, ?)', ('Bob', 'bob@example.com')) + cursor.execute('INSERT INTO users (name, email) VALUES (?, ?)', ('Charlie', 'charlie@example.com')) + cursor.execute('INSERT INTO orders (user_id, product, amount) VALUES (?, ?, ?)', (1, 'Laptop', 999.99)) + cursor.execute('INSERT INTO orders (user_id, product, amount) VALUES (?, ?, ?)', (1, 'Mouse', 29.99)) + cursor.execute('INSERT INTO orders (user_id, product, amount) VALUES (?, ?, ?)', (2, 'Keyboard', 79.99)) + cursor.execute('INSERT INTO orders (user_id, product, amount) VALUES (?, ?, ?)', (2, 'Monitor', 299.99)) + cursor.execute('INSERT INTO orders (user_id, product, amount) VALUES (?, ?, ?)', (3, 'Headphones', 199.99)) + self.conn.commit() + + # VULNERABLE: N+1 query problem + def get_users_with_orders(self) -> List[Dict]: + cursor = self.conn.cursor() + cursor.execute('SELECT id, name, email FROM users') + users = [] + for user in cursor.fetchall(): + user_id, name, email = user + cursor.execute('SELECT product, amount FROM orders WHERE user_id = ?', (user_id,)) + orders = [{'product': row[0], 'amount': row[1]} for row in cursor.fetchall()] + users.append({ + 'id': user_id, + 'name': name, + 'email': email, + 'orders': orders + }) + return users + + if __name__ == '__main__': + service = OrderService() + users = service.get_users_with_orders() + for user in users: + print(f"{user['name']}: {len(user['orders'])} orders") diff --git a/cases/bootstrap/race-condition.yaml b/cases/bootstrap/race-condition.yaml new file mode 100644 index 0000000..f1e6b40 --- /dev/null +++ b/cases/bootstrap/race-condition.yaml @@ -0,0 +1,68 @@ +id: bootstrap-014 +title: "Fix Race Conditions in Concurrent Code" +prompt: | + The following Python code has a race condition when multiple threads try to + increment a shared counter simultaneously. + + Fix the race condition by: + - Using proper synchronization mechanisms (locks, semaphores, etc.) + - Ensuring thread safety + - Preventing data corruption + - Maintaining the same functionality + - Using appropriate concurrency primitives + + Run: python race_condition_test.py + +source: bootstrap +category: concurrency +language: python +difficulty: hard + +tags: + - python + - concurrency + - race-condition + - thread-safety + +files: + - path: counter.py + content: | + import threading + import time + from typing import List + + class Counter: + def __init__(self): + self.count = 0 + self.lock = threading.Lock() + + def increment(self): + # VULNERABLE: Race condition - multiple threads can read and write simultaneously + self.count += 1 + + def get_count(self) -> int: + return self.count + + def worker(counter: Counter, iterations: int, results: List[int]): + for _ in range(iterations): + counter.increment() + results.append(counter.get_count()) + + if __name__ == '__main__': + counter = Counter() + num_threads = 10 + iterations_per_thread = 1000 + results = [] + + threads = [] + for _ in range(num_threads): + t = threading.Thread(target=worker, args=(counter, iterations_per_thread, results)) + threads.append(t) + t.start() + + for t in threads: + t.join() + + print(f"Expected count: {num_threads * iterations_per_thread}") + print(f"Actual count: {counter.get_count()}") + print(f"Results: {results}") diff --git a/cases/bootstrap/refactor-long-functions.yaml b/cases/bootstrap/refactor-long-functions.yaml new file mode 100644 index 0000000..934b156 --- /dev/null +++ b/cases/bootstrap/refactor-long-functions.yaml @@ -0,0 +1,153 @@ +id: bootstrap-020 +title: "Refactor Long Functions into Smaller Ones" +prompt: | + The following Python function is too long and complex. Refactor it into + smaller, more focused functions that are easier to understand and maintain. + + The refactoring should: + - Break down the long function into smaller functions + - Give each function a single, clear responsibility + - Improve code readability + - Maintain the same functionality + - Add proper documentation + - Follow function decomposition best practices + + Run: python long_function_test.py + +source: bootstrap +category: refactoring +language: python +difficulty: medium + +tags: + - python + - refactoring + - code-quality + - function-decomposition + +files: + - path: order_processor.py + content: | + def process_order(order_data): + """ + Process an order with complex validation, calculation, and notification logic. + This function is too long and should be refactored. + """ + # Validate order data + if not order_data or not isinstance(order_data, dict): + raise ValueError("Invalid order data") + + # Validate customer + customer = order_data.get('customer') + if not customer or not isinstance(customer, dict): + raise ValueError("Invalid customer data") + + # Validate shipping address + shipping = customer.get('shipping') + if not shipping or not isinstance(shipping, dict): + raise ValueError("Invalid shipping address") + + # Validate items + items = order_data.get('items') + if not items or not isinstance(items, list): + raise ValueError("Invalid items") + + # Calculate subtotal + subtotal = 0.0 + for item in items: + if not item or not isinstance(item, dict): + continue + price = item.get('price', 0) + quantity = item.get('quantity', 0) + subtotal += price * quantity + + # Calculate tax + tax_rate = 0.08 + tax = subtotal * tax_rate + + # Calculate shipping cost + weight = 0 + for item in items: + if not item or not isinstance(item, dict): + continue + weight += item.get('weight', 0) + + if weight < 1: + shipping_cost = 5.99 + elif weight < 5: + shipping_cost = 9.99 + elif weight < 10: + shipping_cost = 14.99 + else: + shipping_cost = 19.99 + + # Calculate total + total = subtotal + tax + shipping_cost + + # Apply discount if applicable + discount = 0.0 + if customer.get('is_premium', False): + discount = total * 0.1 + elif subtotal > 100: + discount = 10.0 + + final_total = total - discount + + # Generate order number + import random + import string + order_number = 'ORD-' + ''.join(random.choices(string.digits, k=8)) + + # Save order to database + # (In a real application, this would save to a database) + print(f"Order {order_number} saved to database") + + # Send confirmation email + email = customer.get('email') + if email: + print(f"Sending confirmation email to {email}") + + # Send shipping notification + if shipping: + print(f"Shipping notification sent to {shipping.get('address')}") + + # Update inventory + for item in items: + if not item or not isinstance(item, dict): + continue + product_id = item.get('product_id') + quantity = item.get('quantity', 0) + print(f"Updating inventory: {product_id} -{quantity}") + + # Return order summary + return { + 'order_number': order_number, + 'customer': customer.get('name'), + 'subtotal': round(subtotal, 2), + 'tax': round(tax, 2), + 'shipping_cost': round(shipping_cost, 2), + 'discount': round(discount, 2), + 'total': round(final_total, 2) + } + + if __name__ == '__main__': + order = { + 'customer': { + 'name': 'John Doe', + 'email': 'john@example.com', + 'is_premium': True, + 'shipping': { + 'address': '123 Main St, City, State 12345', + 'phone': '555-1234' + } + }, + 'items': [ + {'product_id': 1, 'name': 'Widget', 'price': 29.99, 'quantity': 2, 'weight': 1.5}, + {'product_id': 2, 'name': 'Gadget', 'price': 49.99, 'quantity': 1, 'weight': 2.0} + ] + } + + result = process_order(order) + print("\nOrder Summary:") + for key, value in result.items(): + print(f" {key}: {value}") diff --git a/cases/bootstrap/sql-injection.yaml b/cases/bootstrap/sql-injection.yaml new file mode 100644 index 0000000..af1c8ab --- /dev/null +++ b/cases/bootstrap/sql-injection.yaml @@ -0,0 +1,62 @@ +id: bootstrap-008 +title: "Fix SQL Injection Vulnerability" +prompt: | + The following Node.js code has a SQL injection vulnerability. The user input + is directly concatenated into the SQL query without proper sanitization. + + Fix the vulnerability by: + - Using parameterized queries (prepared statements) + - Sanitizing user input + - Using an ORM or query builder + - Ensuring all user input is properly escaped + + Run: node sql_injection.test.js + +source: bootstrap +category: security +language: javascript +difficulty: medium + +tags: + - javascript + - security + - sql-injection + - database + +files: + - path: user_search.js + content: | + const mysql = require('mysql2/promise'); + + // Vulnerable function - user input is directly concatenated + async function searchUsers(username) { + const connection = await mysql.createConnection({ + host: 'localhost', + user: 'root', + password: 'password', + database: 'users_db' + }); + + // VULNERABLE: User input is directly concatenated + const query = `SELECT * FROM users WHERE username = '${username}'`; + const [rows] = await connection.execute(query); + await connection.end(); + return rows; + } + + // Another vulnerable function + async function deleteUser(userId) { + const connection = await mysql.createConnection({ + host: 'localhost', + user: 'root', + password: 'password', + database: 'users_db' + }); + + // VULNERABLE: User input is directly concatenated + const query = `DELETE FROM users WHERE id = ${userId}`; + await connection.execute(query); + await connection.end(); + } + + module.exports = { searchUsers, deleteUser }; diff --git a/cases/bootstrap/typescript-types.yaml b/cases/bootstrap/typescript-types.yaml new file mode 100644 index 0000000..48dac03 --- /dev/null +++ b/cases/bootstrap/typescript-types.yaml @@ -0,0 +1,61 @@ +id: bootstrap-012 +title: "Add TypeScript Types to JavaScript Code" +prompt: | + The following JavaScript code has no type annotations. Add TypeScript types + to improve code quality, catch errors at compile time, and provide better IDE support. + + The types should: + - Define interfaces for all data structures + - Add type annotations to all functions + - Use proper type guards + - Handle optional and nullable values + - Use union types where appropriate + - Enable strict mode + + Run: npm run build + +source: bootstrap +category: type-safety +language: typescript +difficulty: easy + +tags: + - typescript + - types + - type-safety + - javascript + +files: + - path: user_manager.ts + content: | + // JavaScript code without types + class UserManager { + constructor() { + this.users = []; + } + + addUser(user) { + this.users.push(user); + } + + getUser(id) { + return this.users.find(u => u.id === id); + } + + updateUser(id, updates) { + const user = this.users.find(u => u.id === id); + if (user) { + Object.assign(user, updates); + } + } + + deleteUser(id) { + this.users = this.users.filter(u => u.id !== id); + } + } + + const manager = new UserManager(); + manager.addUser({ id: 1, name: 'Alice', email: 'alice@example.com' }); + const user = manager.getUser(1); + manager.updateUser(1, { name: 'Alice Updated' }); + manager.deleteUser(1); diff --git a/cases/bootstrap/unit-test-generation.yaml b/cases/bootstrap/unit-test-generation.yaml new file mode 100644 index 0000000..bd92bfb --- /dev/null +++ b/cases/bootstrap/unit-test-generation.yaml @@ -0,0 +1,69 @@ +id: bootstrap-011 +title: "Write Unit Tests for Untested Code" +prompt: | + The following Python module has no unit tests. Write comprehensive unit tests + to cover all functions and edge cases. + + The tests should: + - Cover all public functions + - Test normal cases + - Test edge cases (empty inputs, None, etc.) + - Test error conditions + - Use proper test assertions + - Follow testing best practices + + Run: python test_all.py + +source: bootstrap +category: testing +language: python +difficulty: easy + +tags: + - python + - testing + - unit-tests + - test-coverage + +files: + - path: calculator.py + content: | + class Calculator: + def add(self, a, b): + return a + b + + def subtract(self, a, b): + return a - b + + def multiply(self, a, b): + return a * b + + def divide(self, a, b): + if b == 0: + raise ValueError("Cannot divide by zero") + return a / b + + def power(self, base, exponent): + return base ** exponent + + def factorial(self, n): + if n < 0: + raise ValueError("Factorial is not defined for negative numbers") + if n == 0 or n == 1: + return 1 + result = 1 + for i in range(2, n + 1): + result *= i + return result + + def is_prime(self, n): + if n <= 1: + return False + if n == 2: + return True + if n % 2 == 0: + return False + for i in range(3, int(n**0.5) + 1, 2): + if n % i == 0: + return False + return True