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
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
multi-language-chatbot
/
tests
RSK World
multi-language-chatbot
Multi-language Chatbot - Python + Flask + OpenAI API + NLP + Translation + Language Detection + Cultural Adaptation
tests
  • __init__.py258 B
  • test_chatbot.py10.9 KB
test_chatbot.py
tests/test_chatbot.py
Raw Download
Find: Go to:
"""
Multi-language Chatbot Tests
Author: RSK World (https://rskworld.in)
Founder: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
Description: Test suite for multi-language chatbot
"""

import pytest
import json
from app import app
from modules.language_detector import LanguageDetector
from modules.translator import Translator
from modules.cultural_adapter import CulturalAdapter
from modules.chatbot_core import ChatbotCore

@pytest.fixture
def client():
    """Create test client"""
    app.config['TESTING'] = True
    with app.test_client() as client:
        yield client

@pytest.fixture
def language_detector():
    """Create language detector instance"""
    return LanguageDetector()

@pytest.fixture
def translator():
    """Create translator instance"""
    return Translator()

@pytest.fixture
def cultural_adapter():
    """Create cultural adapter instance"""
    return CulturalAdapter()

@pytest.fixture
def chatbot_core():
    """Create chatbot core instance"""
    return ChatbotCore()

class TestLanguageDetector:
    """Test language detection functionality"""
    
    def test_detect_english(self, language_detector):
        """Test English language detection"""
        text = "Hello, how are you today?"
        detected = language_detector.detect(text)
        assert detected == 'en'
    
    def test_detect_hindi(self, language_detector):
        """Test Hindi language detection"""
        text = "नमस्ते, आप कैसे हैं?"
        detected = language_detector.detect(text)
        assert detected == 'hi'
    
    def test_detect_bengali(self, language_detector):
        """Test Bengali language detection"""
        text = "হ্যালো, আপনি কেমন আছেন?"
        detected = language_detector.detect(text)
        assert detected == 'bn'
    
    def test_empty_text(self, language_detector):
        """Test empty text handling"""
        detected = language_detector.detect("")
        assert detected == 'en'  # Default fallback
    
    def test_short_text(self, language_detector):
        """Test short text handling"""
        detected = language_detector.detect("Hi")
        assert detected in ['en']  # Should detect or fallback to English

class TestTranslator:
    """Test translation functionality"""
    
    def test_translate_same_language(self, translator):
        """Test translation to same language"""
        text = "Hello world"
        result = translator.translate(text, 'en', 'en')
        assert result == text
    
    def test_translate_empty_text(self, translator):
        """Test empty text translation"""
        result = translator.translate("", 'es', 'en')
        assert result == ""
    
    def test_translate_batch(self, translator):
        """Test batch translation"""
        texts = ["Hello", "World", "Test"]
        results = translator.translate_batch(texts, 'es', 'en')
        assert len(results) == len(texts)
        assert all(isinstance(r, str) for r in results)
    
    def test_language_support(self, translator):
        """Test language support checking"""
        assert translator.is_language_supported('en') == True
        assert translator.is_language_supported('invalid') == False

class TestCulturalAdapter:
    """Test cultural adaptation functionality"""
    
    def test_adapt_english(self, cultural_adapter):
        """Test English cultural adaptation"""
        text = "Hello, how are you?"
        adapted = cultural_adapter.adapt(text, 'en')
        assert isinstance(adapted, str)
        assert len(adapted) > 0
    
    def test_adapt_hindi(self, cultural_adapter):
        """Test Hindi cultural adaptation"""
        text = "नमस्ते, आप कैसे हैं?"
        adapted = cultural_adapter.adapt(text, 'hi')
        assert isinstance(adapted, str)
        assert len(adapted) > 0
    
    def test_get_cultural_tips(self, cultural_adapter):
        """Test cultural tips retrieval"""
        tips = cultural_adapter.get_cultural_tips('hi')
        assert isinstance(tips, list)
    
    def test_get_local_time(self, cultural_adapter):
        """Test local time retrieval"""
        time_str = cultural_adapter.get_local_time('en')
        assert isinstance(time_str, str)
        assert len(time_str) > 0
    
    def test_get_local_date(self, cultural_adapter):
        """Test local date retrieval"""
        date_str = cultural_adapter.get_local_date('en')
        assert isinstance(date_str, str)
        assert len(date_str) > 0

class TestChatbotCore:
    """Test chatbot core functionality"""
    
    def test_generate_response(self, chatbot_core):
        """Test response generation"""
        response = chatbot_core.generate_response("Hello")
        assert isinstance(response, str)
        assert len(response) > 0
    
    def test_greeting_response(self, chatbot_core):
        """Test greeting response"""
        response = chatbot_core.generate_response("Hello")
        assert any(word in response.lower() for word in ['hello', 'hi', 'hey'])
    
    def test_capabilities_response(self, chatbot_core):
        """Test capabilities response"""
        response = chatbot_core.generate_response("What can you do?")
        assert any(word in response.lower() for word in ['help', 'assist', 'capabilities'])
    
    def test_conversation_history(self, chatbot_core):
        """Test conversation history"""
        user_id = 'test_user'
        
        # Send a message
        chatbot_core.generate_response("Hello", user_id)
        
        # Check history
        history = chatbot_core.get_conversation_history(user_id)
        assert len(history) >= 2  # User message + bot response
    
    def test_clear_history(self, chatbot_core):
        """Test clearing conversation history"""
        user_id = 'test_user'
        
        # Add to history
        chatbot_core.generate_response("Hello", user_id)
        
        # Clear history
        chatbot_core.clear_history(user_id)
        
        # Check history is empty
        history = chatbot_core.get_conversation_history(user_id)
        assert len(history) == 0
    
    def test_get_stats(self, chatbot_core):
        """Test statistics retrieval"""
        stats = chatbot_core.get_stats()
        assert isinstance(stats, dict)
        assert 'total_conversations' in stats
        assert 'total_messages' in stats
        assert 'capabilities_count' in stats
        assert 'openai_enabled' in stats

class TestAPIEndpoints:
    """Test API endpoints"""
    
    def test_health_endpoint(self, client):
        """Test health check endpoint"""
        response = client.get('/health')
        assert response.status_code == 200
        
        data = json.loads(response.data)
        assert data['status'] == 'healthy'
        assert 'timestamp' in data
        assert 'version' in data
    
    def test_languages_endpoint(self, client):
        """Test languages endpoint"""
        response = client.get('/languages')
        assert response.status_code == 200
        
        data = json.loads(response.data)
        assert isinstance(data, dict)
        assert 'en' in data
        assert 'hi' in data
        assert 'bn' in data
    
    def test_chat_endpoint_valid_message(self, client):
        """Test chat endpoint with valid message"""
        response = client.post('/chat',
                              data=json.dumps({'message': 'Hello'}),
                              content_type='application/json')
        assert response.status_code == 200
        
        data = json.loads(response.data)
        assert 'response' in data
        assert 'detected_language' in data
        assert 'language_name' in data
        assert 'confidence' in data
    
    def test_chat_endpoint_empty_message(self, client):
        """Test chat endpoint with empty message"""
        response = client.post('/chat',
                              data=json.dumps({'message': ''}),
                              content_type='application/json')
        assert response.status_code == 400
    
    def test_chat_endpoint_no_message(self, client):
        """Test chat endpoint with no message"""
        response = client.post('/chat',
                              data=json.dumps({}),
                              content_type='application/json')
        assert response.status_code == 400
    
    def test_detect_language_endpoint(self, client):
        """Test language detection endpoint"""
        response = client.post('/detect_language',
                              data=json.dumps({'text': 'Hello, how are you?'}),
                              content_type='application/json')
        assert response.status_code == 200
        
        data = json.loads(response.data)
        assert 'language' in data
        assert 'language_name' in data
        assert 'confidence' in data
    
    def test_detect_language_endpoint_empty_text(self, client):
        """Test language detection endpoint with empty text"""
        response = client.post('/detect_language',
                              data=json.dumps({'text': ''}),
                              content_type='application/json')
        assert response.status_code == 400
    
    def test_translate_endpoint(self, client):
        """Test translation endpoint"""
        response = client.post('/translate',
                              data=json.dumps({
                                  'text': 'Hello, world',
                                  'source_language': 'en',
                                  'target_language': 'es'
                              }),
                              content_type='application/json')
        assert response.status_code == 200
        
        data = json.loads(response.data)
        assert 'translated_text' in data
        assert 'source_language' in data
        assert 'target_language' in data
    
    def test_translate_endpoint_empty_text(self, client):
        """Test translation endpoint with empty text"""
        response = client.post('/translate',
                              data=json.dumps({
                                  'text': '',
                                  'source_language': 'en',
                                  'target_language': 'es'
                              }),
                              content_type='application/json')
        assert response.status_code == 400

class TestIndexRoute:
    """Test index route"""
    
    def test_index_route(self, client):
        """Test index page loads correctly"""
        response = client.get('/')
        assert response.status_code == 200
        assert b'Multi-language Chatbot' in response.data
        assert b'RSK World' in response.data

if __name__ == '__main__':
    pytest.main([__file__, '-v'])
299 lines•10.9 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