How to Mock Hive Support in PySpark with unittest.mock
This code demonstrates how to mock Hive support in a PySpark environment using unittest.mock to simulate SQL queries returning fixed data.
Python code
39 linesfrom unittest.mock import Mock, patch
def get_hive_tables(spark):
"""Mock Hive support by returning a fixed list of tables."""
return spark.sql("SHOW TABLES").collect()
class HiveTable:
"""Simple class that mimics a Hive table row."""
def __init__(self, database, tableName):
self.database = database
self.tableName = tableName
def __repr__(self):
return f"HiveTable(database={self.database!r}, tableName={self.tableName!r})"
if __name__ == "__main__":
# Create a mock Spark session
spark = Mock()
# Mock the SQL method to return fake Hive table rows
spark.sql.return_value.collect.return_value = [
HiveTable("default", "users"),
HiveTable("default", "orders"),
HiveTable("analytics", "events"),
]
# Test our function with the mock
tables = get_hive_tables(spark)
print("Tables found in Hive:")
for table in tables:
print(f" {table.database}.{table.tableName}")
# Verify the mock was called correctly
spark.sql.assert_called_once_with("SHOW TABLES")
print(f"\nSQL called with: {spark.sql.call_args}")
Output
Tables found in Hive:
default.users
default.orders
analytics.events
SQL called with: call('SHOW TABLES')
How it works
The Mock object simulates a Spark session, allowing you to test functions without a real Spark cluster. By setting spark.sql.return_value.collect.return_value, you control what the mock returns when spark.sql() is called and then .collect() is invoked. The HiveTable class is a simple stand-in for a real Hive row, providing the same attributes you'd expect (database and tableName). This pattern is useful for unit testing code that depends on Spark's Hive support without the overhead of a live Hive metastore. The assert_called_once_with verifies the correct SQL command is executed, ensuring your mock is used exactly as expected.
Common mistakes
- Forgetting to set the return value of `collect` on the mock SQL result, causing `collect()` to return another mock instead of data.
- Not resetting the mock between tests, leading to assertion errors about unexpected calls.
- Using the mock outside of a test environment, which can hide integration issues with the real Spark session.
Variations
- Use `patch` to mock `spark.sql` globally for a test suite.
- Create a fixture that returns a fully mocked Spark session with preconfigured side effects for multiple queries.
Real-world use cases
- Unit testing data transformation functions that rely on Hive tables without spinning up Spark and Hive locally.
- Simulating Hive metadata for integration tests in CI pipelines where Spark Hive services are not available.
- Validating SQL query logic by mocking the result set to ensure downstream code handles various table schemas.
Sponsored
More from Big data & Spark
Keep learning
Related tutorials and quizzes for this topic.