{
"title": "12 Prompts for Writing Unit and Integration Tests with Pytest, Jest, and Unittest",
"content": "## Introduction\n\nWriting tests is one of those skills that separates good developers from great ones. But let's be honest — staring at a blank test_ file can feel just as intimidating as writing production code. That's where structured prompts come in. By using carefully designed prompts, you can generate robust unit and integration tests faster, reduce boilerplate, and focus on edge cases that actually matter.\n\nThis article collects 12 battle-tested prompts for generating tests with three major frameworks: pytest (Python), Jest (JavaScript/TypeScript), and unittest (Python). Each prompt includes a clear task, the exact prompt text, and a real-world example with code. Whether you're new to testing or a seasoned QA engineer, these prompts will help you write tests that catch bugs before they reach production.\n\n> Why prompts? A 2025 State of Testing report by PractiTest found that teams using AI-assisted test generation reduced test creation time by up to 40% while maintaining coverage. However, the quality of output depends heavily on how you phrase the request. These prompts are designed to produce actionable, context-aware test suites.\n\n---\n\n## 1. Basic Unit Test for a Pure Function (pytest)\n\nTask: Generate a pytest test suite for a simple mathematical function.\n\nPrompt:\n\"\"\"\nGenerate a pytest test file for the function calculate_discount(price: float, discount_percent: float) -> float that returns the discounted price. Include tests for:\n- Normal cases (e.g., 10% off 100.0)\n- Edge cases: zero discount, 100% discount, zero price\n- Boundary: discount slightly above 100% (should raise ValueError)\n- Negative price (should raise ValueError)\n- Floating point precision (use pytest.approx)\nWrite the code with clear docstrings and test descriptions.\n\"\"\"\n\nExample Result:\npython\nimport pytest\n\ndef calculate_discount(price: float, discount_percent: float) -> float:\n if price < 0:\n raise ValueError(\"Price cannot be negative\")\n if discount_percent < 0 or discount_percent > 100:\n raise ValueError(\"Discount must be between 0 and 100\")\n return price * (1 - discount_percent / 100)\n\ndef test_normal_discount():\n assert calculate_discount(100.0, 10.0) == 90.0\n\ndef test_zero_discount():\n assert calculate_discount(100.0, 0.0) == 100.0\n\ndef test_full_discount():\n assert calculate_discount(100.0, 100.0) == 0.0\n\ndef test_zero_price():\n assert calculate_discount(0.0, 50.0) == 0.0\n\ndef test_discount_above_100():\n with pytest.raises(ValueError):\n calculate_discount(100.0, 101.0)\n\ndef test_negative_price():\n with pytest.raises(ValueError):\n calculate_discount(-10.0, 10.0)\n\ndef test_floating_point():\n result = calculate_discount(99.99, 33.33)\n expected = 99.99 * (1 - 33.33 / 100)\n assert result == pytest.approx(expected, rel=1e-9)\n\n\nWhy it works: The prompt explicitly asks for edge cases and floating point handling, which are common pitfalls. The generated test uses pytest.approx to avoid precision bugs.\n\n---\n\n## 2. Basic Unit Test for a Class (unittest)\n\nTask: Generate a unittest test case for a simple bank account class.\n\nPrompt:\n\"\"\"\nCreate a unittest.TestCase for the class BankAccount with methods:\n- deposit(amount) -> adds to balance\n- withdraw(amount) -> subtracts if sufficient funds, raises ValueError otherwise\n- get_balance() -> returns current balance\nWrite tests using setUp to create a fresh account with initial balance 100.0. Include tests for deposit, withdrawal, overdraft prevention, and multiple operations.\n\"\"\"\n\nExample Result:\npython\nimport unittest\n\nclass BankAccount:\n def __init__(self, initial_balance=0.0):\n self._balance = initial_balance\n\n def deposit(self, amount):\n if amount <= 0:\n raise ValueError(\"Deposit amount must be positive\")\n self._balance += amount\n\n def withdraw(self, amount):\n if amount <= 0:\n raise ValueError(\"Withdrawal amount must be positive\")\n if amount > self._balance:\n raise ValueError(\"Insufficient funds\")\n self._balance -= amount\n\n def get_balance(self):\n return self._balance\n\nclass TestBankAccount(unittest.TestCase):\n def setUp(self):\n self.account = BankAccount(100.0)\n\n def test_initial_balance(self):\n self.assertEqual(self.account.get_balance(), 100.0)\n\n def test_deposit(self):\n self.account.deposit(50.0)\n self.assertEqual(self.account.get_balance(), 150.0)\n\n def test_withdraw_sufficient(self):\n self.account.withdraw(30.0)\n self.assertEqual(self.account.get_balance(), 70.0)\n\n def test_withdraw_insufficient(self):\n with self.assertRaises(ValueError):\n self.account.withdraw(200.0)\n\n def test_multiple_operations(self):\n self.account.deposit(50.0)\n self.account.withdraw(20.0)\n self.account.deposit(10.0)\n self.assertEqual(self.account.get_balance(), 140.0)\n\nif __name__ == '__main__':\n unittest.main()\n\n\nWhy it works: The prompt specifies setUp for reusability and includes negative cases (overdraft). The generated code is clean and follows unittest conventions.\n\n---\n\n## 3. Basic Unit Test for an Async Function (Jest)\n\nTask: Generate Jest tests for an async data-fetching function.\n\nPrompt:\n\"\"\"\nWrite Jest tests for the async function fetchUserData(userId: string): Promise<{id: string, name: string, email: string}> that calls a REST API. Use Jest mocks to simulate the API call. Include tests for:\n- Successful response with valid data\n- Network error (e.g., 500 status) — should reject with an error\n- Empty response (e.g., 404) — should reject with 'User not found'\n- Timeout — use jest.useFakeTimers\nUse describe and it blocks for organization.\n\"\"\"\n\nExample Result:\njavascript\nconst fetchUserData = require('./fetchUserData');\n\ndescribe('fetchUserData', () => {\n beforeEach(() => {\n jest.clearAllMocks();\n });\n\n it('should return user data on successful API call', async () => {\n const mockData = { id: '1', name: 'John', email: 'john@example.com' };\n global.fetch = jest.fn().mockResolvedValue({\n ok: true,\n json: () => Promise.resolve(mockData),\n });\n\n const result = await fetchUserData('1');\n expect(result).toEqual(mockData);\n });\n\n it('should reject with error on network failure (500)', async () => {\n global.fetch = jest.fn().mockResolvedValue({\n ok: false,\n status: 500,\n });\n\n await expect(fetchUserData('1')).rejects.toThrow('HTTP error: 500');\n });\n\n it('should reject with \"User not found\" on 404', async () => {\n global.fetch = jest.fn().mockResolvedValue({\n ok: false,\n status: 404,\n });\n\n await expect(fetchUserData('999')).rejects.toThrow('User not found');\n });\n\n it('should reject on timeout', async () => {\n jest.useFakeTimers();\n const abortController = new AbortController();\n global.fetch = jest.fn().mockImplementation(() => {\n return new Promise((_, reject) => {\n setTimeout(() => reject(new Error('Timeout')), 5000);\n });\n });\n\n const fetchPromise = fetchUserData('1');\n jest.advanceTimersByTime(5000);\n await expect(fetchPromise).rejects.toThrow('Timeout');\n jest.useRealTimers();\n });\n});\n\n\nWhy it works: Async testing is tricky. This prompt covers HTTP errors, empty responses, and timeouts using Jest's built-in mocking and timer APIs.\n\n---\n\n## 4. Integration Test for a Database Layer (pytest + SQLite)\n\nTask: Generate an integration test for a CRUD repository using SQLite.\n\nPrompt:\n\"\"\"\nWrite a pytest integration test for the class UserRepository that interacts with a SQLite database. The repository has methods:\n- create_user(name, email) -> returns user dict with id\n- get_user(user_id) -> returns user dict or None\n- update_email(user_id, new_email) -> updates and returns user\n- delete_user(user_id) -> returns True/False\nUse an in-memory SQLite database (:memory:) to avoid side effects. Use a fixture to create a fresh database and repository for each test. Include tests for create, read, update, delete, and a non-existent user lookup.\n\"\"\"\n\nExample Result:\npython\nimport pytest\nimport sqlite3\nfrom user_repository import UserRepository\n\n@pytest.fixture\ndef repo():\n conn = sqlite3.connect(':memory:')\n conn.execute('''CREATE TABLE users (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT NOT NULL,\n email TEXT UNIQUE NOT NULL\n )''')\n yield UserRepository(conn)\n conn.close()\n\ndef test_create_user(repo):\n user = repo.create_user('Alice', 'alice@example.com')\n assert user['name'] == 'Alice'\n assert user['email'] == 'alice@example.com'\n assert 'id' in user\n\ndef test_get_user_found(repo):\n created = repo.create_user('Bob', 'bob@example.com')\n fetched = repo.get_user(created['id'])\n assert fetched == created\n\ndef test_get_user_not_found(repo):\n assert repo.get_user(999) is None\n\ndef test_update_email(repo):\n user = repo.create_user('Charlie', 'charlie@old.com')\n updated = repo.update_email(user['id'], 'charlie@new.com')\n assert updated['email'] == 'charlie@new.com'\n\ndef test_delete_user_existing(repo):\n user = repo.create_user('Diana', 'diana@example.com')\n assert repo.delete_user(user['id']) == True\n assert repo.get_user(user['id']) is None\n\ndef test_delete_user_non_existent(repo):\n assert repo.delete_user(999) == False\n\n\nWhy it works: Using an in-memory database makes tests fast and isolated. The fixture pattern ensures each test starts with a clean state, preventing test interdependency.\n\n---\n\n## 5. Integration Test for a REST API (pytest + requests)\n\nTask: Generate integration tests for a Flask REST API using the requests library.\n\nPrompt:\n\"\"\"\nCreate pytest integration tests for a Flask app with endpoints:\n- POST /items (create item)\n- GET /items/{id} (get item)\n- PUT /items/{id} (update item)\n- DELETE /items/{id} (delete item)\nUse the test_client fixture from Flask. Include tests for successful operations, 404 for non-existent items, and validation errors (e.g., missing required fields). Use pytest.mark.parametrize for multiple scenarios.\n\"\"\"\n\nExample Result:\npython\nimport pytest\nfrom my_flask_app import app\n\n@pytest.fixture\ndef client():\n with app.test_client() as client:\n yield client\n\ndef test_create_item(client):\n response = client.post('/items', json={'name': 'Laptop', 'price': 999.99})\n assert response.status_code == 201\n data = response.get_json()\n assert data['name'] == 'Laptop'\n assert 'id' in data\n\ndef test_get_item_found(client):\n create_resp = client.post('/items', json={'name': 'Phone', 'price': 499.99})\n item_id = create_resp.get_json()['id']\n response = client.get(f'/items/{item_id}')\n assert response.status_code == 200\n assert response.get_json()['name'] == 'Phone'\n\ndef test_get_item_not_found(client):\n response = client.get('/items/9999')\n assert response.status_code == 404\n assert 'error' in response.get_json()\n\ndef test_update_item(client):\n create_resp = client.post('/items', json={'name': 'Tablet', 'price': 299.99})\n item_id = create_resp.get_json()['id']\n response = client.put(f'/items/{item_id}', json={'price': 249.99})\n assert response.status_code == 200\n assert response.get_json()['price'] == 249.99\n\ndef test_delete_item(client):\n create_resp = client.post('/items', json={'name': 'Monitor', 'price': 199.99})\n item_id = create_resp.get_json()['id']\n response = client.delete(f'/items/{item_id}')\n assert response.status_code == 204\n # Verify deletion\n get_resp = client.get(f'/items/{item_id}')\n assert get_resp.status_code == 404\n\n@pytest.mark.parametrize('payload, expected_status', [\n ({}, 400), # missing name and price\n ({'name': 'Mouse'}, 400), # missing price\n ({'price': 10.0}, 400), # missing name\n])\ndef test_create_item_validation(client, payload, expected_status):\n response = client.post('/items', json=payload)\n assert response.status_code == expected_status\n\n\nWhy it works: Using test_client avoids running a separate server. parametrize reduces code duplication for validation tests.\n\n---\n\n## 6. Integration Test for Message Queue (pytest + RabbitMQ)\n\nTask: Generate integration tests for a message producer/consumer using RabbitMQ.\n\nPrompt:\n\"\"\"\nWrite pytest integration tests for a MessageQueue class that publishes and consumes messages via RabbitMQ. Use the pytest-rabbitmq plugin or a Docker container fixture. Include tests for:\n- Publishing a message and consuming it\n- Publishing multiple messages and consuming in order\n- Consuming from an empty queue (should return None with timeout)\n- Handling malformed messages (e.g., non-JSON) — should be rejected\nUse a temporary queue name to avoid collisions.\n\"\"\"\n\nExample Result:\npython\nimport pytest\nimport json\nfrom message_queue import MessageQueue\n\n@pytest.fixture\ndef queue():\n # Assume rabbitmq container is running on localhost:5672\n mq = MessageQueue('localhost', 5672, 'test_user', 'test_pass')\n queue_name = 'test_queue_' + str(uuid.uuid4())\n mq.declare_queue(queue_name)\n yield mq, queue_name\n mq.delete_queue(queue_name)\n mq.close()\n\ndef test_publish_and_consume(queue):\n mq, qname = queue\n message = {'action': 'test', 'value': 42}\n mq.publish(qname, message)\n consumed = mq.consume(qname, timeout=5)\n assert consumed == message\n\ndef test_multiple_messages_in_order(queue):\n mq, qname = queue\n messages = [{'seq': i} for i in range(3)]\n for msg in messages:\n mq.publish(qname, msg)\n for expected in messages:\n consumed = mq.consume(qname, timeout=5)\n assert consumed == expected\n\ndef test_consume_empty_queue(queue):\n mq, qname = queue\n result = mq.consume(qname, timeout=1)\n assert result is None\n\ndef test_malformed_message(queue):\n mq, qname = queue\n # Simulate sending raw string instead of JSON\n mq._channel.basic_publish(\n exchange='',\n routing_key=qname,\n body='not-json'\n )\n with pytest.raises(json.JSONDecodeError):\n mq.consume(qname, timeout=5)\n\n\nWhy it works: Using unique queue names per test prevents cross-test contamination. The fixture handles cleanup, which is critical for message queue tests.\n\n---\n\n## 7. Unit Test with Mocking External API (Jest)\n\nTask: Generate Jest tests for a service that calls an external API, using mocks.\n\nPrompt:\n\"\"\"\nWrite Jest tests for WeatherService.getTemperature(city: string): Promise<number> which calls api.weather.com/v1/current?city=.... Mock the fetch call using jest.mock. Include tests for:\n- Successful response returning temperature in Celsius\n- Network error — should throw 'Weather service unavailable'\n- Invalid city — should throw 'City not found'\n- Verify that the API is called with correct URL\nUse beforeEach to reset mocks.\n\"\"\"\n\nExample Result:\njavascript\nconst WeatherService = require('./WeatherService');\nconst fetch = require('node-fetch');\n\njest.mock('node-fetch');\n\ndescribe('WeatherService.getTemperature', () => {\n beforeEach(() => {\n fetch.mockClear();\n });\n\n it('should return temperature on success', async () => {\n fetch.mockResolvedValue({\n ok: true,\n json: () => Promise.resolve({ temperature: 22.5 }),\n });\n\n const temp = await WeatherService.getTemperature('London');\n expect(temp).toBe(22.5);\n expect(fetch).toHaveBeenCalledWith(\n 'https://api.weather.com/v1/current?city=London'\n );\n });\n\n it('should throw on network error', async () => {\n fetch.mockResolvedValue({ ok: false, status: 500 });\n\n await expect(\n WeatherService.getTemperature('London')\n ).rejects.toThrow('Weather service unavailable');\n });\n\n it('should throw \"City not found\" on 404', async () => {\n fetch.mockResolvedValue({ ok: false, status: 404 });\n\n await expect(\n WeatherService.getTemperature('Atlantis')\n ).rejects.toThrow('City not found');\n });\n\n it('should call API with correct URL', async () => {\n fetch.mockResolvedValue({\n ok: true,\n json: () => Promise.resolve({ temperature: 30 }),\n });\n\n await WeatherService.getTemperature('Paris');\n expect(fetch).toHaveBeenCalledWith(\n 'https://api.weather.com/v1/current?city=Paris'\n );\n });\n});\n\n\nWhy it works: Mocking external APIs makes tests fast and reliable. The prompt ensures URL verification, which is often missed.\n\n---\n\n## 8. Integration Test for File Processing (pytest + tempfile)\n\nTask: Generate integration tests for a CSV processing function.\n\nPrompt:\n\"\"\"\nWrite pytest integration tests for the function process_csv(file_path: str) -> List[Dict] that reads a CSV file and returns a list of dicts (with headers as keys). Use the tmp_path fixture to create temporary CSV files. Include tests for:\n- Normal CSV with valid data\n- Empty CSV (only headers) — returns empty list\n- CSV with missing values (empty cells)\n- CSV with different delimiters (specify delimiter parameter)\n- File not found — should raise FileNotFoundError\n\"\"\"\n\nExample Result:\npython\nimport pytest\nimport csv\n\ndef process_csv(file_path: str, delimiter: str = ',') -> list:\n with open(file_path, 'r') as f:\n reader = csv.DictReader(f, delimiter=delimiter)\n return [row for row in reader]\n\ndef test_normal_csv(tmp_path):\n data = \"name,age\\nAlice,30\\nBob,25\\n\"\n file = tmp_path / 'test.csv'\n file.write_text(data)\n result = process_csv(str(file))\n assert len(result) == 2\n assert result[0] == {'name': 'Alice', 'age': '30'}\n\ndef test_empty_csv(tmp_path):\n data = \"name,age\\n\"\n file = tmp_path / 'empty.csv'\n file.write_text(data)\n result = process_csv(str(file))\n assert result == []\n\ndef test_missing_values(tmp_path):\n data = \"name,age,email\\nAlice,30,\\nBob,,bob@example.com\\n\"\n file = tmp_path / 'missing.csv'\n file.write_text(data)\n result = process_csv(str(file))\n assert result[0]['email'] == ''\n assert result[1]['age'] == ''\n\ndef test_different_delimiter(tmp_path):\n data = \"name;age\\nAlice;30\\n\"\n file = tmp_path / 'semicolon.csv'\n file.write_text(data)\n result = process_csv(str(file), delimiter=';')\n assert result[0]['name'] == 'Alice'\n\ndef test_file_not_found():\n with pytest.raises(FileNotFoundError):\n process_csv('/nonexistent/path.csv')\n\n\nWhy it works: Using tmp_path (built into pytest) ensures temporary files are cleaned up. The prompt covers common CSV edge cases.\n\n---\n\n## 9. Unit Test for React Component (Jest + React Testing Library)\n\nTask: Generate Jest tests for a React form component using React Testing Library.\n\nPrompt:\n\"\"\"\nWrite Jest tests using React Testing Library for a LoginForm component with fields:\n- email input\n- password input\n- submit button\nOn submit, it calls onSubmit({email, password}) prop. Include tests for:\n- Rendering all elements\n- Filling in fields and submitting\n- Not calling onSubmit if email is invalid (show validation error)\n- Not calling onSubmit if password is empty\nUse fireEvent or userEvent for interactions.\n\"\"\"\n\nExample Result:\njavascript\nimport { render, screen, fireEvent } from '@testing-library/react';\nimport LoginForm from './LoginForm';\n\ndescribe('LoginForm', () => {\n it('renders email, password fields and submit button', () => {\n render(<LoginForm onSubmit={() => {}} />);\n expect(screen.getByLabelText(/email/i)).toBeInTheDocument();\n expect(screen.getByLabelText(/password/i)).toBeInTheDocument();\n expect(screen.getByRole('button', { name: /submit/i })).toBeInTheDocument();\n });\n\n it('calls onSubmit with correct data when form is valid', () => {\n const mockSubmit = jest.fn();\n render(<LoginForm onSubmit={mockSubmit} />);\n \n fireEvent.change(screen.getByLabelText(/email/i), {\n target: { value: 'user@example.com' },\n });\n fireEvent.change(screen.getByLabelText(/password/i), {\n target: { value: 'secure123' },\n });\n fireEvent.click(screen.getByRole('button', { name: /submit/i }));\n\n expect(mockSubmit).toHaveBeenCalledWith({\n email: 'user@example.com',\n password: 'secure123',\n });\n });\n\n it('shows validation error for invalid email', () => {\n render(<LoginForm onSubmit={() => {}} />);\n \n fireEvent.change(screen.getByLabelText(/email/i), {\n target: { value: 'invalid-email' },\n });\n fireEvent.click(screen.getByRole('button', { name: /submit/i }));\n\n expect(screen.getByText(/please enter a valid email/i)).toBeInTheDocument();\n });\n\n it('does not call onSubmit when password is empty', () => {\n const mockSubmit = jest.fn();\n render(<LoginForm onSubmit={mockSubmit} />);\n \n fireEvent.change(screen.getByLabelText(/email/i), {\n target: { value: 'user@example.com' },\n });\n fireEvent.click(screen.getByRole('button', { name: /submit/i }));\n\n expect(mockSubmit).not.toHaveBeenCalled();\n expect(screen.getByText(/password is required/i)).toBeInTheDocument();\n });\n});\n\n\nWhy it works: React Testing Library encourages testing user behavior, not implementation details. The prompt focuses on user interactions and validation feedback.\n\n---\n\n## 10. Integration Test for Microservices (pytest + Docker Compose)\n\nTask: Generate integration tests for a microservice that depends on a PostgreSQL database and a Redis cache.\n\nPrompt:\n\"\"\"\nWrite pytest integration tests for a microservice that stores user sessions in PostgreSQL and caches them in Redis. Use docker-compose with services: postgres:15, redis:7, and the app. Use the pytest-docker plugin to manage containers. Include tests for:\n- Creating a session in DB and reading it back\n- Session caching: after first read, subsequent reads should return from cache (verify by counting DB queries)\n- Session expiry: after TTL, cache is cleared and data is fetched from DB again\n- Handling duplicate session IDs (should update)\n\"\"\"\n\nExample Result:\npython\nimport pytest\nimport time\nfrom session_service import SessionService\n\n@pytest.fixture(scope='module')\ndef services():\n # Assume docker-compose up using pytest-docker\n pass\n\ndef test_create_and_read_session(services, db_connection, redis_client):\n service = SessionService(db_connection, redis_client)\n session_id = service.create_session({'user_id': 1, 'data': 'test'})\n result = service.get_session(session_id)\n assert result['user_id'] == 1\n\ndef test_cache_hit(services, db_connection, redis_client, mocker):\n service = SessionService(db_connection, redis_client)\n session_id = service.create_session({'user_id': 2})\n \n # Spy on DB query\n spy = mocker.spy(db_connection, 'execute')\n \n # First read should hit DB\n service.get_session(session_id)\n first_db_calls = spy.call_count\n \n # Second read should hit cache (no new DB calls)\n service.get_session(session_id)\n assert spy.call_count == first_db_calls\n\ndef test_cache_expiry(services, db_connection, redis_client, mocker):\n service = SessionService(db_connection, redis_client, ttl=1)\n session_id = service.create_session({'user_id': 3})\n \n # Wait for TTL to expire\n time.sleep(1.5)\n \n spy = mocker.spy(db_connection, 'execute')\n service.get_session(session_id)\n # Should query DB again because cache expired\n assert spy.call_count > 0\n\ndef test_duplicate_session_update(services, db_connection, redis_client):\n service = SessionService(db_connection, redis_client)\n session_id = service.create_session({'user_id': 4})\n service.create_session({'user_id': 4}) # same user, should update\n sessions = service.get_all_sessions_for_user(4)\n assert len(sessions) == 1\n\n\nWhy it works: Docker Compose integration tests validate real interactions between services. The prompt includes cache behavior, which is a common source of bugs.\n\n---\n\n## 11. Parameterized Unit Test for Data Validation (pytest + parametrize)\n\nTask: Generate parametrized tests for an email validation function.\n\nPrompt:\n\"\"\"\nWrite pytest tests for validate_email(email: str) -> bool using @pytest.mark.parametrize. Include at least 8 test cases covering:\n- Valid emails: simple, with dots, with plus sign\n- Invalid emails: missing @, missing domain, multiple @, spaces, empty string\n- Edge cases: very long local part (64 chars), international characters (e.g., é)\nUse descriptive test IDs.\n\"\"\"\n\nExample Result:\npython\nimport pytest\nimport re\n\ndef validate_email(email: str) -> bool:\n pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'\n return bool(re.match(pattern, email))\n\n@pytest.mark.parametrize('email, expected', [\n ('user@example.com', True),\n ('first.last@company.co.uk', True),\n ('user+tag@example.org', True),\n ('a' * 64 + '@example.com', True), # max local part length\n ('user@example', False), # missing TLD\n ('@example.com', False), # missing local part\n ('user@.com', False), # missing domain name\n ('user@example..com', False), # double dot\n ('user name@example.com', False), # space\n ('', False), # empty\n ('user@ex@ample.com', False), # multiple @\n], ids=[\n 'simple_valid',\n 'dot_in_local',\n 'plus_tag',\n 'long_local_part',\n 'missing_tld',\n 'missing_local',\n 'missing_domain',\n 'double_dot',\n 'space_in_email',\n 'empty_string',\n 'multiple_at',\n])\ndef test_validate_email(email, expected):\n assert validate_email(email) == expected\n\n\nWhy it works: Parameterized tests reduce boilerplate and make it easy to add new cases. The prompt includes edge cases like long local parts and international characters.\n\n---\n\n## 12. Integration Test for GraphQL API (pytest + graphene)\n\nTask: Generate integration tests for a GraphQL API using graphene and pytest.\n\nPrompt:\n\"\"\"\nWrite pytest integration tests for a GraphQL schema with queries:\n- allUsers: returns list of users\n- user(id: ID!): returns single user\nAnd mutations:\n- createUser(name: String!, email: String!): creates user\n- updateUser(id: ID!, email: String): updates user\nUse a test client that executes queries directly against the schema. Include tests for:\n- Query allUsers when database is empty\n- Create user and then query it\n- Update user email\n- Query non-existent user returns null\n- Mutation validation errors (e.g., missing required fields)\n\"\"\"\n\nExample Result:\n```python\nimport pytest\nfrom schema import schema\nfrom graphql import graphql_sync\n\ndef execute_query(query, variables=None):\n return graphql_sync(schema, query, variable_values=variables)\n\n@pytest.fixture\ndef clear_db():\n # Reset in-memory storage before each test\n from data import users\n users.clear()\n\ndef test_query_all_users_empty(clear_db):\n query = '''{ allUsers { id name email } }'''\n result = execute_query(query)\n assert result.data['allUsers'] == []\n\ndef test_create_user_and_query(clear_db):\n mutation = '''\n mutation CreateUser($name: String!, $email: String!) {\n createUser(name: $name, email: $email) {\n id name email\n }\n }\n '''\n result = execute_query(mutation, {'name': 'Alice', 'email': 'alice@example.com'})\n assert result.data['createUser']['name'] == 'Alice'\n \n # Query the user\n user_id = result.data['createUser']['id']\n query = '''query GetUser($id: ID!) { user(id: $id) { name email } }'''\n result = execute_query(query, {'id': user_id})\n assert result.data['user']['name'] == 'Alice'\n\ndef test_update_user_email(clear_db):\n # First create\n mutation = '''\n mutation { createUser(name: \"Bob\", email: \"bob@old.com\") { id email } }\n '''\n create_result = execute_query(mutation)\n user_id = create_result.data['createUser']['id']\n \n # Update email\n update_mutation = '''\n mutation UpdateUser($id: ID!, $email: String!) {\n updateUser(id: $id, email: $email) { email }\n }\n '''\n update_result = execute_query(update_mutation, {'id': user_id, 'email': 'bob@new.com'})\n assert update_result.data['updateUser']['email'] == 'bob@new.com'\n\ndef test_query_non_existent_user(clear_db):\n query = '''{ user(id: \"999\") { name } }'''\n result = execute_query(query)\n assert result.data['user'] is None\n\ndef test_create_user_missing_name(clear_db):\n mutation = '''\n mutation { createUser(email: \"no@name.com\") { id } }\n '''\n result = execute_query(mutation)\
Промты для написания unit-тестов и интеграционных тестов
Recent articles
Artificial Intelligence Regulation: EU AI Act and Global Standards — A Course for Those Who Don't Want to Take Risks in 2026
22 July 2026
Mastering API Design: REST, GraphQL, gRPC, and Best Practices with the Asibiont Course
22 July 2026
Mastering Elasticsearch with ASI Biont AI Agent: Automated Log Analysis and Query Automation Without Code
22 July 2026
Business English: How AI-Powered Learning Helps Executives and Entrepreneurs Reach the Next Level
22 July 2026
How Stripe and ASI Biont Automate Payments Without Code: A Real Integration Experience
22 July 2026
How to Stop Fighting Fires in Production: The Observability Course (Prometheus, Grafana) from ASI Biont
22 July 2026
Koda Desktop: Expanding Capabilities Beyond the Developer’s Workbench
22 July 2026
How ASI Biont’s AI Agent Transforms SAP S/4HANA Integration: Automate Data Entry, Reporting, and Approvals with No-Code ERP Automation
22 July 2026
PN532 (NFC) Meets AI Agent: Real-World Access Control and Inventory Automation with ASI Biont
22 July 2026
Comments