@@ -57,109 +57,9 @@ Provides a simple abstraction for HTTP operations:
5757
5858Supports URL path parameters and query strings.
5959
60- #### 2. ** Database Connection** (` src/database.py ` )
61- Manages PostgreSQL connections with connection pooling:
62- - ` execute_query() ` - Fetch multiple rows as tuples
63- - ` execute_query_one() ` - Fetch a single row
64- - ` execute_query_dict() ` - Fetch rows as dictionaries
65- - ` execute_update() ` - Insert, update, or delete operations
66- - ` execute_many() ` - Batch operations
67- - Context manager support for safe connection handling
68-
69- Features:
70- - Connection pooling (SimpleConnectionPool)
71- - Automatic commit/rollback
72- - SQL injection prevention via parameterized queries
73- - Type hints and comprehensive docstrings
74-
75- #### 3. ** Pytest Fixtures** (` tests/conftest.py ` )
60+ #### 2. ** Pytest Fixtures** (` tests/conftest.py ` )
7661Reusable test fixtures:
77- - ` api_client ` - Pre-configured REST API client (module scope)
78- - ` db_connection ` - PostgreSQL connection instance (module scope)
79-
80- ## 🐳 Docker Setup for Database Testing
81-
82- ### Prerequisites
83- - Docker and Docker Compose installed
84- - No need to install PostgreSQL locally
85-
86- ### Quick Start
87-
88- 1 . ** Start the PostgreSQL Container**
89-
90- ``` bash
91- cd docker
92- docker-compose up -d
93- ```
94-
95- This will:
96- - Create a PostgreSQL container with credentials:
97- - ** User** : ` user `
98- - ** Password** : ` 1234 `
99- - ** Database** : ` testdb `
100- - ** Port** : ` 5432 `
101- - Initialize the database with sample data from ` init.sql `
102-
103- 2 . ** Verify the Container is Running**
104-
105- ``` bash
106- docker-compose ps
107- ```
108-
109- 3 . ** Access the Database** (optional)
110-
111- ``` bash
112- docker-compose exec db psql -U user -d testdb
113- ```
114-
115- ### Database Schema
116-
117- The initialization script (` docker/init.sql ` ) creates the following table:
118-
119- ``` sql
120- CREATE TABLE people (
121- id SERIAL PRIMARY KEY ,
122- fname VARCHAR (100 ),
123- age INT
124- );
125- ```
126-
127- ** Sample Data** :
128- ```
129- id | fname | age
130- ---|---------|-----
131- 1 | Alice | 30
132- 2 | Bob | 25
133- 3 | Charlie | 35
134- ```
135-
136- ### Environment Configuration
137-
138- Update ` tests/conftest.py ` with your PostgreSQL credentials:
139-
140- ``` python
141- @pytest.fixture (scope = " module" )
142- def db_connection ():
143- db = DatabaseConnection(
144- host = " localhost" , # Change if Docker is on different host
145- database = " testdb" , # Match POSTGRES_DB from docker-compose.yml
146- user = " user" , # Match POSTGRES_USER from docker-compose.yml
147- password = " 1234" , # Match POSTGRES_PASSWORD from docker-compose.yml
148- port = 5432
149- )
150- yield db
151- db.close()
152- ```
153-
154- ### Stop and Clean Up
155-
156- ``` bash
157- # Stop the container
158- docker-compose down
159-
160- # Remove the container and volumes
161- docker-compose down -v
162- ```
62+ - ` __all__ = ["base_url", "http"] ` - Expose fixtures for test modules
16363
16464## 🚀 Installation & Execution
16565
@@ -175,15 +75,20 @@ pip install -r requirements.txt
17575- ` psycopg2-binary ` - PostgreSQL adapter for Python
17676- ` mypy ` - Static type checker
17777- ` pytest-reporter-html1 ` - HTML test report generation
78+ - ` pytest-xdist ` - Parallel test execution
79+ - ` pytest-sugar ` - Enhanced test output
80+ - ` jsonschema ` - JSON schema validation
81+ - ` python-dotenv ` - Environment variable management
82+ - ` vcrpy ` - HTTP interaction recording
17883
17984### 2. Run Tests
18085
18186``` bash
18287# Run all tests
18388pytest
18489
185- # Run tests with @pytest.mark (example: testdb )
186- pytest -m testdb
90+ # Run tests with @pytest.mark (example: smoke )
91+ pytest -m smoke
18792
18893# Run with verbose output
18994pytest -v
@@ -192,55 +97,22 @@ pytest -v
19297pytest -s -v
19398
19499# Run specific test file
195- pytest tests/test_db_connection .py
100+ pytest tests/test_smoke/test_sample_smoke .py -v
196101
197102# Generate HTML report
198103pytest --html=reports/html1-report.html
199104```
200-
201- ### 3. Running Database Tests
202-
203- Ensure the Docker container is running before executing database tests:
204-
205- ``` bash
206- # Start PostgreSQL
207- cd docker && docker-compose up -d && cd ..
208-
209- # Run database tests
210- pytest tests/test_db_connection.py -v
211- ```
212-
213- ## 📝 Example Test Usage
214-
215- ### Testing the Database Connection
216-
217- ``` python
218- def test_users (db_connection ):
219- # Query the database
220- people = db_connection.execute_query_dict(
221- " SELECT * FROM people WHERE id = %s " ,
222- (1 ,)
223- )
224-
225- # Validate results
226- assert len (people) > 0
227- person = people[0 ]
228- assert person[" fname" ] == " Alice"
229- assert person[" age" ] == 30
230- ```
231-
232105### Testing API Endpoints
233106
234107``` python
235- def test_get_activity (api_client ):
236- response = api_client.get(Endpoints.ACTIVITIES_BY_ID , id = 1 )
237- assert response.status_code == 200
108+ def test_api_available (http , base_url ):
109+ r = http.get(Endpoints.PEOPLE )
110+ assert r.status_code == 200
111+ assert r.headers.get(" Content-Type" , " " ).startswith(" application/json" )
238112```
239113
240114## 🔒 Best Practices
241115
242- - ** Parameterized Queries** : Always use ` %s ` placeholders to prevent SQL injection
243- - ** Connection Management** : Use context managers (` with ` statements) for safe connection handling
244116- ** Fixtures** : Leverage Pytest fixtures for setup and teardown
245117- ** Type Hints** : Use type annotations for better code documentation
246118- ** Error Handling** : Catch and log errors appropriately
@@ -258,22 +130,20 @@ See `requirements.txt` for the complete list. Key dependencies:
258130| psycopg2-binary | Latest | PostgreSQL adapter |
259131| mypy | Latest | Type checking |
260132| pytest-reporter-html1 | Latest | HTML reports |
133+ | pytest-xdist | Latest | Parallel test execution |
134+ | pytest-sugar | Latest | Enhanced output |
135+ | jsonschema | Latest | JSON schema validation |
136+ | python-dotenv | Latest | Environment variables |
261137
262138## 🛠️ Troubleshooting
263139
264- ### PostgreSQL Connection Issues
265- - Verify Docker container is running: ` docker-compose ps `
266- - Check credentials in ` conftest.py ` match ` docker-compose.yml `
267- - Ensure port 5432 is not in use: ` lsof -i :5432 `
268-
269140### Import Errors
270141- Activate virtual environment: ` source venv/bin/activate `
271142- Reinstall dependencies: ` pip install -r requirements.txt `
272143
273144### Test Failures
274145- Use ` -v ` flag for verbose output
275146- Use ` -s ` flag to see print statements
276- - Check database initialization: ` docker-compose logs db `
277147
278148## 📄 License
279149
0 commit comments