#!/usr/bin/env python3 """ Unit tests for data_analysis.py """ import json import os import tempfile import unittest from pathlib import Path import numpy as np import pandas as pd # Import the functions from our module import sys sys.path.insert(0, str(Path(__file__).parent)) from data_analysis import ( analyze_data, clean_data, explore_data, load_data, save_results, ) class TestDataAnalysis(unittest.TestCase): """Test cases for data analysis functions.""" def setUp(self): """Set up test data.""" # Create sample data for testing self.sample_data = pd.DataFrame({ 'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50], 'C': ['x', 'y', 'x', 'y', 'z'], 'D': [1.1, 2.2, np.nan, 4.4, 5.5] }) # Create temporary directory for test files self.temp_dir = tempfile.mkdtemp() def tearDown(self): """Clean up after tests.""" # Remove temporary files import shutil shutil.rmtree(self.temp_dir) def test_load_data_csv(self): """Test loading CSV file.""" csv_path = os.path.join(self.temp_dir, 'test.csv') self.sample_data.to_csv(csv_path, index=False) df = load_data(csv_path) pd.testing.assert_frame_equal(df, self.sample_data) def test_load_data_csv_uppercase(self): """Test loading CSV file with uppercase extension.""" csv_path = os.path.join(self.temp_dir, 'test.CSV') self.sample_data.to_csv(csv_path, index=False) df = load_data(csv_path) pd.testing.assert_frame_equal(df, self.sample_data) def test_load_data_excel(self): """Test loading Excel file - skipped if openpyxl not available.""" try: import openpyxl except ImportError: self.skipTest("openpyxl not installed") excel_path = os.path.join(self.temp_dir, 'test.xlsx') self.sample_data.to_excel(excel_path, index=False) df = load_data(excel_path) pd.testing.assert_frame_equal(df, self.sample_data) def test_load_data_excel_uppercase(self): """Test loading Excel file with uppercase extension - skipped if openpyxl not available.""" try: import openpyxl except ImportError: self.skipTest("openpyxl not installed") excel_path = os.path.join(self.temp_dir, 'test.XLSX') self.sample_data.to_excel(excel_path, index=False) df = load_data(excel_path) pd.testing.assert_frame_equal(df, self.sample_data) def test_load_data_json(self): """Test loading JSON file.""" json_path = os.path.join(self.temp_dir, 'test.json') self.sample_data.to_json(json_path) df = load_data(json_path) # Need to reset index for comparison due to how to_json works df = df.reset_index(drop=True) expected = self.sample_data.reset_index(drop=True) pd.testing.assert_frame_equal(df, expected) def test_load_data_json_uppercase(self): """Test loading JSON file with uppercase extension.""" json_path = os.path.join(self.temp_dir, 'test.JSON') self.sample_data.to_json(json_path) df = load_data(json_path) df = df.reset_index(drop=True) expected = self.sample_data.reset_index(drop=True) pd.testing.assert_frame_equal(df, expected) def test_load_data_unsupported_format(self): """Test loading unsupported file format.""" txt_path = os.path.join(self.temp_dir, 'test.txt') with open(txt_path, 'w') as f: f.write('test') with self.assertRaises(ValueError) as context: load_data(txt_path) self.assertIn('Unsupported file format', str(context.exception)) def test_clean_data(self): """Test data cleaning function.""" # Create data with duplicates and empty column df_dirty = self.sample_data.copy() df_dirty = pd.concat([df_dirty, self.sample_data.iloc[0:1]], ignore_index=True) # Add duplicate # Add column with all NaN values (matching DataFrame length) df_dirty['E'] = [np.nan] * len(df_dirty) # All NaN column df_clean = clean_data(df_dirty) # Should have removed duplicate row (original had 5 rows, duplicate makes 6, after dedup should be 5) self.assertEqual(len(df_clean), len(self.sample_data)) # Should have removed the all-NaN column self.assertNotIn('E', df_clean.columns) # Should have original columns self.assertEqual(set(df_clean.columns), set(self.sample_data.columns)) def test_analyze_data(self): """Test data analysis function.""" results = analyze_data(self.sample_data) # Check that we have expected keys self.assertIn('correlations', results) self.assertIn('summary_stats', results) # Check correlations (should have data since we have numeric columns) self.assertIsInstance(results['correlations'], dict) if results['correlations']: # Only check if not empty self.assertIn('A', results['correlations']) self.assertIn('B', results['correlations']) # Check summary stats self.assertIsInstance(results['summary_stats'], dict) if results['summary_stats']: # Only check if not empty self.assertIn('A', results['summary_stats']) self.assertIn('B', results['summary_stats']) self.assertIn('D', results['summary_stats']) def test_analyze_data_no_numeric(self): """Test analysis with no numeric columns.""" text_data = pd.DataFrame({ 'A': ['x', 'y', 'z'], 'B': ['p', 'q', 'r'] }) results = analyze_data(text_data) # Should have empty correlations and summary_stats self.assertEqual(results['correlations'], {}) self.assertEqual(results['summary_stats'], {}) def test_explore_data(self): """Test data exploration function (mainly checks it runs without error).""" # This function primarily prints output, so we just verify it doesn't crash try: explore_data(self.sample_data) # If we get here, it didn't crash success = True except Exception: success = False self.assertTrue(success) def test_save_results(self): """Test saving results to JSON file.""" test_results = { 'correlations': {'A': {'B': 0.5}}, 'summary_stats': {'A': {'mean': 3.0}} } output_path = os.path.join(self.temp_dir, 'results.json') save_results(test_results, output_path) # Verify file was created self.assertTrue(os.path.exists(output_path)) # Verify content with open(output_path, 'r') as f: loaded_results = json.load(f) self.assertEqual(loaded_results, test_results) def test_save_results_numpy_types(self): """Test saving results with numpy types.""" # Create results with numpy types test_results = { 'numpy_float': np.float64(3.14), 'numpy_int': np.int64(42), 'numpy_array': np.array([1, 2, 3]) } output_path = os.path.join(self.temp_dir, 'results_numpy.json') save_results(test_results, output_path) # Verify file was created self.assertTrue(os.path.exists(output_path)) # Verify content # Check actual behavior: numpy.float64 IS JSON serializable (becomes Python float) # numpy.int64 is NOT JSON serializable (triggers default=str -> becomes string) # numpy.ndarray is NOT JSON serializable (triggers default=str -> becomes string) with open(output_path, 'r') as f: loaded_results = json.load(f) # Based on actual observed behavior in this environment: self.assertEqual(loaded_results['numpy_float'], 3.14) # float - remains numeric self.assertEqual(loaded_results['numpy_int'], '42') # int64 - becomes string self.assertEqual(loaded_results['numpy_array'], '[1 2 3]') # array - becomes string if __name__ == '__main__': unittest.main()