正在学习
14.3 Backend and API Prompts (2)
14.3 Backend and API Prompts (2)
{
"code": "return jsonify({\"message\": \"Book added successfully\"}), 201\n\n@app.route(\"/books\", methods=[\"GET\"])\ndef get_books():\n books = Book.query.all()\n return jsonify([{\"id\": b.id, \"title\": b.title, \"author\": b.author} for b in books])\n\n@app.route(\"/books/<int:book_id>\", methods=[\"GET\"])\ndef get_book(book_id):\n book = Book.query.get(book_id)\n if not book:\n return jsonify({\"error\": \"Book not found\"}), 404\n return jsonify({\"id\": book.id, \"title\": book.title, \"author\": book.author})\n\n@app.route(\"/books/<int:book_id>\", methods=[\"DELETE\"])\ndef delete_book(book_id):\n book = Book.query.get(book_id)\n if not book:\n return jsonify({\"error\": \"Book not found\"}), 404\n db.session.delete(book)\n db.session.commit()\n return jsonify({\"message\": \"Book deleted\"})\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n## 14.4 Testing and Debugging Prompts\nTesting and debugging are where Claude Code transitions from being a coding assistant to acting as a software quality partner. Well-written prompts can help Claude not only generate test cases but also diagnose logic errors, interpret stack traces, and even explain how to fix bugs. This section focuses on writing structured, reproducible testing and debugging prompts that yield high-quality, verifiable results.\n\nClaude’s advantage lies in its ability to reason contextually — to understand what a function should do, detect why it fails, and produce both tests and fixes in a single workflow. With the right prompt structure, you can treat Claude as a flexible test engineer that complements your own intuition and saves hours of manual inspection.\n\n### Concept Development\nWhen prompting Claude for testing and debugging, clarity and containment are critical. Unlike human testers, Claude does not infer unstated requirements well — you must specify scope, framework, and expected behavior explicitly. Key prompt elements that consistently yield strong results include:\n\n- Framework specification– e.g., “Use pytest,” “Use Jest,” or “Use unittest.”\n- Coverage scope– Define which functions, modules, or edge cases to test.\n- Expected format– Ask for runnable test files, not snippets.\n- Error handling– Provide sample stack traces for Claude to analyze.\n- Verification intent– Instruct Claude to confirm that the fix passes all tests.\n\nA well-structured debugging prompt doesn’t just request a fix; it explains the observed behavior and invites Claude to reason through it step-by-step.\n\n### Hands-On Example 1: Writing Unit Tests with Pytest\n**Prompt**:\nYou are a Python QA engineer.\nWrite pytest test cases for the following function.\nEnsure coverage for valid input, invalid input, and edge cases.\nReturn a complete runnable test file.\n\n```python\ndef divide(a, b):\n return a / b\n```\n\n**Claude Output (Example)**:\n```python\nimport pytest\nfrom main import divide\n\ndef test_divide_valid():\n assert divide(10, 2) == 5\n assert divide(-6, 3) == -2\n\ndef test_divide_zero_division():\n with pytest.raises(ZeroDivisionError):\n divide(5, 0)\n\ndef test_divide_floats():\n assert pytest.approx(divide(5.0, 2.0), 0.001) == 2.5\n\ndef test_divide_large_numbers():\n assert divide(1_000_000, 10) == 100_000\n```\n\n**Explanation**: Claude created a clean, structured test file with edge coverage — including floating-point precision and error handling. It automatically inferred boundary conditions without being told exactly what to test, thanks to a well-framed prompt.\n\n### Hands-On Example 2: Debugging with Error Trace Analysis\n**Prompt**:\nYou are a debugging assistant.\nAnalyze the following Python traceback and identify the root cause.\nThen, rewrite the buggy code correctly with an explanation.\n\n```\nTraceback (most recent call last):\n File \"app.py\", line 10, in <module>\n result = calculate_area(5)\nTypeError: calculate_area() missing 1 required positional argument: 'height'\n\n```python\ndef calculate_area(width, height=2):\n return width * height\n```\n\n**Claude Output (Example)**:\n```python\n# Fixed Code\ndef calculate_area(width, height=2):\n return width * height\n\n# Correct Usage\nresult = calculate_area(5, 4)\nprint(result) # Output: 20\n```\n\n**Explanation**: Claude correctly identifies the issue — the function call is missing a required positional argument. It not only provides the corrected code but also explains the fix in context, turning debugging into a learning process rather than a guessing game.\n\n### Hands-On Example 3: JavaScript Jest Test Automation\n**Prompt:**\nWrite Jest test cases for the following Express.js route.\nCover success, failure, and validation scenarios.\n\n```javascript\napp.post(\"/users\", (req, res) => {\n const { name, email } = req.body;\n if (!name || !email) return res.status(400).json({ message: \"Invalid input\" });\n res.status(201).json({ message: \"User created\" });\n});\n```\n\n**Claude Output (Example):**\n```javascript\nimport request from \"supertest\";\nimport express from \"express\";\n\nconst app = express();\napp.use(express.json());\n\napp.post(\"/users\", (req, res) => {\n const { name, email } = req.body;\n if (!name || !email) return res.status(400).json({ message: \"Invalid input\" });\n```"
}
res.status(201).json({ message: "User created" });
});
describe("POST /users", () => {
it("should create a user successfully", async () => {
const res = await request(app)
.post("/users")
.send({ name: "Alice", email: "alice@example.com" });
expect(res.statusCode).toBe(201);
expect(res.body.message).toBe("User created");
});
it("should return 400 for invalid input", async () => {
const res = await request(app).post("/users").send({});
expect(res.statusCode).toBe(400);
});
});
Why It Works: The prompt defines three expectations — framework, test coverage, and validation behavior. Claude responds with a working test suite that uses Supertest, handles both valid and invalid inputs, and runs immediately in Node.js.
Hands-On Example 4: Debugging Logic Errors in a Loop
Prompt:
Analyze this Python code that produces incorrect results.
Explain the logical bug and provide the corrected version.
def calculate_sum(numbers):
total = 0
for num in numbers:
total = num # bug here
return total
print(calculate_sum([1, 2, 3]))
Claude Output (Example):
练习题
When adding a book via a POST request, what status code and message should be returned upon successful addition?
A. 200, "Book added"
B. 201, "Book added successfully"
C. 404, "Book not found"
D. 500, "Internal server error"
Which route and method should be used to retrieve all books from the database?
What are the required elements when writing a prompt for Claude to generate a FastAPI CRUD application?
A. Framework and programming language
B. Purpose of the API
C. Requirements such as authentication
D. Format of the expected output
E. Environment constraints
F. Database connection details
When retrieving a specific book via a GET request, if the book is not found, a 404 status code should be returned with an error message.
When deleting a book via a DELETE request, the response should include the message "___" upon successful deletion.
Explain the importance of specifying the framework and programming language in a backend prompt for Claude.
Which of the following is NOT a requirement for a FastAPI CRUD application prompt?
A. Endpoints for CRUD operations
B. Validation of request bodies using Pydantic
C. Use of async functions
D. Exception handling for missing tasks
What are the key elements for effective testing and debugging prompts when using Claude?
A. Framework specification
B. Coverage scope
C. Expected format
D. Error handling
E. Verification intent
F. Code optimization suggestions
When writing Jest test cases for an Express.js route, it is sufficient to cover only the success scenario.
Describe how Claude can assist in debugging a Python application by analyzing a traceback.
When writing a Flask API for book management, which HTTP status code should be returned when a book is successfully added via a POST request?
A. 200 OK
B. 201 Created
C. 404 Not Found
D. 500 Internal Server Error
Which of the following are essential elements to include when writing a prompt for Claude to generate a FastAPI CRUD application for task management? (Select all that apply)
A. The framework and programming language (e.g., Python + FastAPI)
B. The purpose of the API (e.g., task management)
C. The requirements such as authentication and validation
D. The expected output format (e.g., a single module or multiple routes)
E. The color scheme for the frontend interface
In a Flask API for book management, the route /books/<int:book_id> with a GET method should return a 404 Not Found status code if the book with the specified ID does not exist in the database.
Explain how you would structure a prompt for Claude to generate a Flask API for a book catalog that includes SQLite database integration, SQLAlchemy ORM models, and CRUD routes for books.
登录后解锁笔记、知识点解析、AI 问答
立即登录