|
| 1 | +""" |
| 2 | +Unit Testing II - Mocking & Stubbing: Database I/O Operations |
| 3 | +Nithikesh Reddy |
| 4 | +""" |
| 5 | +import pytest |
| 6 | +import pandas as pd |
| 7 | +import numpy as np |
| 8 | + |
| 9 | + |
| 10 | +class TestDatabaseIOMocking: |
| 11 | + """Test database I/O operations using mocks (FR-5)""" |
| 12 | + |
| 13 | + def test_read_sql_basic(self, monkeypatch): |
| 14 | + """ |
| 15 | + Test basic SQL read operation with mocked database connection |
| 16 | + |
| 17 | + Test Oracle (FR-5): Reading a SQL query that returns 100 rows and 3 columns |
| 18 | + should create a DataFrame with 100 rows and 3 columns |
| 19 | + |
| 20 | + Rationale: Database connections are external dependencies; mocking allows |
| 21 | + testing SQL functionality without a real database server |
| 22 | + """ |
| 23 | + # Setup: Mock data that would come from database |
| 24 | + expected_data = pd.DataFrame({ |
| 25 | + 'id': range(100), |
| 26 | + 'name': [f'user_{i}' for i in range(100)], |
| 27 | + 'value': np.random.rand(100) |
| 28 | + }) |
| 29 | + |
| 30 | + def mock_read_sql(query, con, **kwargs): |
| 31 | + return expected_data |
| 32 | + |
| 33 | + # Apply mock |
| 34 | + monkeypatch.setattr(pd, 'read_sql', mock_read_sql) |
| 35 | + |
| 36 | + # Execute: Read from "database" |
| 37 | + result = pd.read_sql("SELECT * FROM users", con=None) |
| 38 | + |
| 39 | + # Verify Test Oracle: Shape is (100, 3) |
| 40 | + assert result.shape == (100, 3), f"Expected (100, 3), got {result.shape}" |
| 41 | + assert list(result.columns) == ['id', 'name', 'value'] |
| 42 | + assert len(result) == 100 |
| 43 | + |
| 44 | + def test_read_sql_empty_result(self, monkeypatch): |
| 45 | + """ |
| 46 | + Test SQL query returning empty result set |
| 47 | + |
| 48 | + Rationale: Empty query results are common; pandas should handle |
| 49 | + them gracefully with an empty DataFrame |
| 50 | + """ |
| 51 | + # Setup: Mock empty result |
| 52 | + empty_data = pd.DataFrame(columns=['id', 'name', 'value']) |
| 53 | + |
| 54 | + def mock_read_sql(query, con, **kwargs): |
| 55 | + return empty_data |
| 56 | + |
| 57 | + monkeypatch.setattr(pd, 'read_sql', mock_read_sql) |
| 58 | + |
| 59 | + # Execute |
| 60 | + result = pd.read_sql("SELECT * FROM empty_table", con=None) |
| 61 | + |
| 62 | + # Verify: Empty DataFrame with correct columns |
| 63 | + assert len(result) == 0 |
| 64 | + assert list(result.columns) == ['id', 'name', 'value'] |
| 65 | + assert isinstance(result, pd.DataFrame) |
| 66 | + |
| 67 | + def test_read_sql_with_parameters(self, monkeypatch): |
| 68 | + """ |
| 69 | + Test parameterized SQL queries |
| 70 | + |
| 71 | + Rationale: Parameterized queries prevent SQL injection; verify pandas |
| 72 | + handles parameter passing correctly |
| 73 | + """ |
| 74 | + # Setup: Mock filtered data |
| 75 | + filtered_data = pd.DataFrame({ |
| 76 | + 'id': [5], |
| 77 | + 'name': ['user_5'], |
| 78 | + 'value': [0.5] |
| 79 | + }) |
| 80 | + |
| 81 | + def mock_read_sql(query, con, params=None, **kwargs): |
| 82 | + if params and params.get('user_id') == 5: |
| 83 | + return filtered_data |
| 84 | + return pd.DataFrame() |
| 85 | + |
| 86 | + monkeypatch.setattr(pd, 'read_sql', mock_read_sql) |
| 87 | + |
| 88 | + # Execute: Parameterized query |
| 89 | + result = pd.read_sql( |
| 90 | + "SELECT * FROM users WHERE id = :user_id", |
| 91 | + con=None, |
| 92 | + params={'user_id': 5} |
| 93 | + ) |
| 94 | + |
| 95 | + # Verify: Filtered result |
| 96 | + assert len(result) == 1 |
| 97 | + assert result['id'].iloc[0] == 5 |
| 98 | + |
| 99 | + def test_read_sql_dtype_handling(self, monkeypatch): |
| 100 | + """ |
| 101 | + Test SQL result data type conversion |
| 102 | + |
| 103 | + Test Oracle (FR-5): SQL INTEGER should convert to int64, VARCHAR to string, |
| 104 | + DECIMAL to float64 in the resulting DataFrame |
| 105 | + |
| 106 | + Rationale: Type mapping from SQL to pandas is critical for correctness |
| 107 | + """ |
| 108 | + # Setup: Mock with specific dtypes (using dict to avoid dtype conversion) |
| 109 | + typed_data = pd.DataFrame({ |
| 110 | + 'int_col': [1, 2, 3], |
| 111 | + 'str_col': ['a', 'b', 'c'], |
| 112 | + 'float_col': [1.1, 2.2, 3.3] |
| 113 | + }) |
| 114 | + # Explicitly set dtypes to ensure consistency |
| 115 | + typed_data['int_col'] = typed_data['int_col'].astype('int64') |
| 116 | + typed_data['float_col'] = typed_data['float_col'].astype('float64') |
| 117 | + |
| 118 | + def mock_read_sql(query, con, **kwargs): |
| 119 | + return typed_data |
| 120 | + |
| 121 | + monkeypatch.setattr(pd, 'read_sql', mock_read_sql) |
| 122 | + |
| 123 | + # Execute |
| 124 | + result = pd.read_sql("SELECT * FROM typed_table", con=None) |
| 125 | + |
| 126 | + # Verify Test Oracle: Correct data types |
| 127 | + assert result['int_col'].dtype == np.int64 |
| 128 | + # In pandas 3.0, strings may use string dtype instead of object |
| 129 | + assert result['str_col'].dtype in [object, 'string', pd.StringDtype()] |
| 130 | + assert result['float_col'].dtype == np.float64 |
| 131 | + |
| 132 | + def test_read_sql_connection_error_handling(self, monkeypatch): |
| 133 | + """ |
| 134 | + Test error handling when database connection fails |
| 135 | + |
| 136 | + Rationale: Connection failures are common in production; pandas should |
| 137 | + handle them with clear error messages |
| 138 | + """ |
| 139 | + # Setup: Mock to raise connection error |
| 140 | + def mock_read_sql(query, con, **kwargs): |
| 141 | + raise ConnectionError("Unable to connect to database") |
| 142 | + |
| 143 | + monkeypatch.setattr(pd, 'read_sql', mock_read_sql) |
| 144 | + |
| 145 | + # Execute & Verify: Should raise ConnectionError |
| 146 | + with pytest.raises(ConnectionError, match="Unable to connect"): |
| 147 | + pd.read_sql("SELECT * FROM users", con=None) |
0 commit comments