help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
real-estate-bot
/
tests
RSK World
real-estate-bot
Real Estate Bot - Python + Flask + OpenAI + SQLite + Property Search + AI Chatbot + Viewing Scheduler
tests
  • __pycache__
  • test_chatbot.py14.1 KB
test_chatbot.py
tests/test_chatbot.py
Raw Download
Find: Go to:
"""
Test Suite for Real Estate Chatbot
Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: info@rskworld.com, +91 93305 39277
Year: 2026
"""

import unittest
from unittest.mock import Mock, patch
import sys
import os

# Add the src directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))

from chatbot import RealEstateChatbot
from database import DatabaseManager
from property_search import PropertySearchEngine

class TestRealEstateChatbot(unittest.TestCase):
    """Test cases for RealEstateChatbot class"""
    
    def setUp(self):
        """Set up test fixtures"""
        self.mock_openai = Mock()
        self.mock_property_search = Mock()
        self.mock_db_manager = Mock()
        
        self.chatbot = RealEstateChatbot(
            self.mock_openai,
            self.mock_property_search,
            self.mock_db_manager
        )
    
    def test_analyze_message_property_search(self):
        """Test message analysis for property search intent"""
        test_cases = [
            ("Show me apartments in Mumbai", "property_search"),
            ("Find houses under 50 lakhs", "property_search"),
            ("Looking for 2BHK flats in Delhi", "property_search"),
            ("Search properties in Bangalore", "property_search")
        ]
        
        for message, expected_intent in test_cases:
            with self.subTest(message=message):
                intent, entities = self.chatbot._analyze_message(message)
                self.assertEqual(intent, expected_intent)
    
    def test_analyze_message_schedule_viewing(self):
        """Test message analysis for scheduling intent"""
        test_cases = [
            ("Schedule a viewing for property 123", "schedule_viewing"),
            ("I want to visit the apartment tomorrow", "schedule_viewing"),
            ("Book an appointment for house viewing", "schedule_viewing"),
            ("When can I see the property?", "schedule_viewing")
        ]
        
        for message, expected_intent in test_cases:
            with self.subTest(message=message):
                intent, entities = self.chatbot._analyze_message(message)
                self.assertEqual(intent, expected_intent)
    
    def test_analyze_message_property_inquiry(self):
        """Test message analysis for property inquiry intent"""
        test_cases = [
            ("Tell me about property 456", "property_inquiry"),
            ("What's the price of the house?", "property_inquiry"),
            ("Information about the 2BHK flat", "property_inquiry"),
            ("Details about the property in Pune", "property_inquiry")
        ]
        
        for message, expected_intent in test_cases:
            with self.subTest(message=message):
                intent, entities = self.chatbot._analyze_message(message)
                self.assertEqual(intent, expected_intent)
    
    def test_extract_entities_location(self):
        """Test location entity extraction"""
        test_cases = [
            ("apartments in Mumbai", {"location": "mumbai"}),
            ("houses in Delhi area", {"location": "delhi area"}),
            ("properties near Bangalore city", {"location": "bangalore city"})
        ]
        
        for message, expected_entities in test_cases:
            with self.subTest(message=message):
                entities = self.chatbot._extract_entities(message, "property_search")
                self.assertIn("location", entities)
                self.assertEqual(entities["location"], expected_entities["location"])
    
    def test_extract_entities_price_range(self):
        """Test price range entity extraction"""
        test_cases = [
            ("under 50 lakhs", {"price_max": 5000000}),
            ("between 30 and 70 lakhs", {"price_min": 3000000, "price_max": 7000000}),
            ("over 1 crore", {"price_min": 10000000})
        ]
        
        for message, expected_entities in test_cases:
            with self.subTest(message=message):
                entities = self.chatbot._extract_entities(message, "property_search")
                
                if "price_max" in expected_entities:
                    self.assertEqual(entities.get("price_max"), expected_entities["price_max"])
                if "price_min" in expected_entities:
                    self.assertEqual(entities.get("price_min"), expected_entities["price_min"])
    
    def test_extract_entities_bedrooms(self):
        """Test bedrooms entity extraction"""
        test_cases = [
            ("2 bedroom house", {"bedrooms": 2}),
            ("3BHK apartment", {"bedrooms": 3}),
            ("4 bed villa", {"bedrooms": 4})
        ]
        
        for message, expected_entities in test_cases:
            with self.subTest(message=message):
                entities = self.chatbot._extract_entities(message, "property_search")
                self.assertEqual(entities.get("bedrooms"), expected_entities["bedrooms"])
    
    def test_extract_entities_property_type(self):
        """Test property type entity extraction"""
        test_cases = [
            ("apartment in Mumbai", {"property_type": "apartment"}),
            ("house for sale", {"property_type": "house"}),
            ("condo near beach", {"property_type": "condo"}),
            ("townhouse with garden", {"property_type": "townhouse"})
        ]
        
        for message, expected_entities in test_cases:
            with self.subTest(message=message):
                entities = self.chatbot._extract_entities(message, "property_search")
                self.assertEqual(entities.get("property_type"), expected_entities["property_type"])
    
    @patch('src.chatbot.RealEstateChatbot._handle_property_search')
    def test_process_message_property_search(self, mock_handler):
        """Test message processing for property search"""
        mock_handler.return_value = "Found 5 properties matching your criteria"
        
        response = self.chatbot.process_message("Show me apartments in Mumbai", "user123")
        
        self.assertEqual(response, "Found 5 properties matching your criteria")
        mock_handler.assert_called_once()
    
    @patch('src.chatbot.RealEstateChatbot._handle_schedule_viewing')
    def test_process_message_schedule_viewing(self, mock_handler):
        """Test message processing for scheduling viewing"""
        mock_handler.return_value = "Viewing scheduled successfully"
        
        response = self.chatbot.process_message("Schedule a viewing for property 123", "user123")
        
        self.assertEqual(response, "Viewing scheduled successfully")
        mock_handler.assert_called_once()
    
    @patch('src.chatbot.RealEstateChatbot._handle_property_inquiry')
    def test_process_message_property_inquiry(self, mock_handler):
        """Test message processing for property inquiry"""
        mock_handler.return_value = "Property details: 2BHK apartment in Mumbai"
        
        response = self.chatbot.process_message("Tell me about property 456", "user123")
        
        self.assertEqual(response, "Property details: 2BHK apartment in Mumbai")
        mock_handler.assert_called_once()
    
    def test_conversation_history_management(self):
        """Test conversation history is properly managed"""
        user_id = "test_user"
        
        # Send first message
        self.chatbot.process_message("Hello", user_id)
        self.assertEqual(len(self.chatbot.conversation_history[user_id]), 2)  # user + bot
        
        # Send second message
        self.chatbot.process_message("Show properties", user_id)
        self.assertEqual(len(self.chatbot.conversation_history[user_id]), 4)  # 2 user + 2 bot
        
        # Test history limit (should keep only last 10 messages)
        for i in range(10):
            self.chatbot.process_message(f"Message {i}", user_id)
        
        self.assertLessEqual(len(self.chatbot.conversation_history[user_id]), 10)


class TestPropertySearchEngine(unittest.TestCase):
    """Test cases for PropertySearchEngine class"""
    
    def setUp(self):
        """Set up test fixtures"""
        self.search_engine = PropertySearchEngine()
    
    def test_search_with_criteria(self):
        """Test property search with various criteria"""
        criteria = {
            'location': 'Mumbai',
            'property_type': 'apartment',
            'price_max': 5000000,
            'bedrooms': 2
        }
        
        # Mock the database search
        with patch.object(self.search_engine.db_manager, 'search_properties') as mock_search:
            mock_search.return_value = [
                {
                    'id': 1,
                    'title': 'Test Apartment',
                    'location': 'Mumbai',
                    'price': 4500000,
                    'bedrooms': 2
                }
            ]
            
            results = self.search_engine.search(criteria)
            
            self.assertEqual(len(results), 1)
            self.assertEqual(results[0]['title'], 'Test Apartment')
            mock_search.assert_called_once_with(criteria)
    
    def test_get_property_by_id(self):
        """Test getting property by ID"""
        with patch.object(self.search_engine.db_manager, 'get_property_by_id') as mock_get:
            mock_get.return_value = {
                'id': 123,
                'title': 'Test Property',
                'location': 'Delhi'
            }
            
            property_data = self.search_engine.get_property_by_id(123)
            
            self.assertEqual(property_data['id'], 123)
            self.assertEqual(property_data['title'], 'Test Property')
            mock_get.assert_called_once_with(123)
    
    def test_get_similar_properties(self):
        """Test getting similar properties"""
        with patch.object(self.search_engine, 'get_property_by_id') as mock_get:
            with patch.object(self.search_engine, 'search') as mock_search:
                # Mock reference property
                mock_get.return_value = {
                    'id': 123,
                    'title': 'Reference Property',
                    'property_type': 'apartment',
                    'price': 5000000,
                    'bedrooms': 2,
                    'location': 'Mumbai'
                }
                
                # Mock similar properties
                mock_search.return_value = [
                    {'id': 124, 'title': 'Similar Property 1'},
                    {'id': 125, 'title': 'Similar Property 2'},
                    {'id': 123, 'title': 'Reference Property'}  # This should be excluded
                ]
                
                similar = self.search_engine.get_similar_properties(123)
                
                # Should exclude the reference property
                self.assertEqual(len(similar), 2)
                self.assertNotIn(123, [prop['id'] for prop in similar])


class TestDatabaseManager(unittest.TestCase):
    """Test cases for DatabaseManager class"""
    
    def setUp(self):
        """Set up test fixtures"""
        # Use in-memory database for testing
        self.db_manager = DatabaseManager(':memory:')
    
    def test_database_initialization(self):
        """Test database tables are created properly"""
        # Check if tables exist by trying to query them
        import sqlite3
        tables = ['properties', 'users', 'appointments', 'inquiries', 'chat_history']
        
        conn = sqlite3.connect(self.db_manager.db_path)
        cursor = conn.cursor()
        
        for table in tables:
            cursor.execute(
                "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
                (table,)
            )
            result = cursor.fetchone()
            self.assertIsNotNone(result, f"Table {table} should exist")
        
        conn.close()
    
    def test_insert_sample_properties(self):
        """Test sample properties are inserted"""
        properties = self.db_manager.search_properties({})
        
        # Should have sample properties
        self.assertGreater(len(properties), 0)
        
        # Check sample property structure
        first_property = properties[0]
        required_fields = ['id', 'title', 'description', 'price', 'location']
        
        for field in required_fields:
            self.assertIn(field, first_property)
    
    def test_search_properties(self):
        """Test property search functionality"""
        # Test empty search
        all_properties = self.db_manager.search_properties({})
        self.assertGreater(len(all_properties), 0)
        
        # Test location search
        mumbai_properties = self.db_manager.search_properties({'location': 'Mumbai'})
        for prop in mumbai_properties:
            self.assertIn('mumbai', prop['location'].lower())
        
        # Test price range search
        budget_properties = self.db_manager.search_properties({'price_max': 10000000})
        for prop in budget_properties:
            self.assertLessEqual(prop['price'], 10000000)
    
    def test_schedule_appointment(self):
        """Test appointment scheduling"""
        appointment_id = self.db_manager.schedule_appointment(
            user_id='test_user',
            property_id=1,
            date_time='2026-01-15 10:00:00',
            contact_info={'phone': '+91 93305 39277'}
        )
        
        self.assertIsNotNone(appointment_id)
        self.assertGreater(appointment_id, 0)
    
    def test_create_inquiry(self):
        """Test inquiry creation"""
        inquiry_id = self.db_manager.create_inquiry(
            user_id='test_user',
            property_id=1,
            message='Is this property still available?',
            contact_info={'email': 'test@example.com'}
        )
        
        self.assertIsNotNone(inquiry_id)
        self.assertGreater(inquiry_id, 0)


if __name__ == '__main__':
    unittest.main()
347 lines•14.1 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer