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
weather-chatbot
/
tests
RSK World
weather-chatbot
Weather Chatbot - Python + Flask + OpenWeatherMap + OpenAI + Weather Forecast + Weather Alerts + Natural Language Processing
tests
  • __init__.py110 B
  • conftest.py1.3 KB
  • test_app.py3.3 KB
  • test_utils.py1.8 KB
  • test_weather_api.py1.6 KB
weather_api.pyADVANCED_FEATURES.mdconfig.pytest_app.py
weather_api.py
Raw Download
Find: Go to:
# Author: RSK World
# Website: https://rskworld.in
# Email: your.email@example.com
# Year: 2026

import os
import requests

def get_weather(location):
    api_key = os.getenv("OPENWEATHER_API_KEY")
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    params = {
        "q": location,
        "appid": api_key,
        "units": "metric"
    }
    try:
        response = requests.get(base_url, params=params)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        return {"error": str(e)}
23 lines•578 B
python
config.py
Raw Download
Find: Go to:
#!/usr/bin/env python3
"""
Weather Chatbot Configuration
============================

Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: +91 93305 39277, hello@rskworld.in, support@rskworld.in
Location: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147
Year: 2026

Description: Configuration settings for the Weather Chatbot application
"""

import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

class Config:
    """Base configuration class for Weather Chatbot"""
    
    # Basic Flask Configuration
    SECRET_KEY = os.getenv('SECRET_KEY', 'weather-chatbot-secret-key-2026')
    DEBUG = os.getenv('FLASK_DEBUG', 'True').lower() == 'true'
    
    # Server Configuration
    HOST = os.getenv('HOST', '0.0.0.0')
    PORT = int(os.getenv('PORT', 5000))
    
    # API Keys
    OPENWEATHER_API_KEY = os.getenv('OPENWEATHER_API_KEY')
    OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
    
    # Weather API Configuration
    WEATHER_UNITS = os.getenv('WEATHER_UNITS', 'metric')
    WEATHER_LANGUAGE = os.getenv('WEATHER_LANGUAGE', 'en')
    DEFAULT_CITY = os.getenv('DEFAULT_CITY', 'London')
    
    # OpenWeatherMap API URLs
    OPENWEATHER_BASE_URL = "https://api.openweathermap.org/data/2.5"
    OPENWEATHER_GEO_URL = "http://api.openweathermap.org/geo/1.0"
    
    # Logging Configuration
    LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')
    LOG_FILE = os.getenv('LOG_FILE', 'logs/weather_chatbot.log')
    
    # Rate Limiting
    RATE_LIMIT_ENABLED = os.getenv('RATE_LIMIT_ENABLED', 'True').lower() == 'true'
    RATE_LIMIT_PER_MINUTE = int(os.getenv('RATE_LIMIT_PER_MINUTE', 30))
    
    # Cache Configuration
    CACHE_ENABLED = os.getenv('CACHE_ENABLED', 'False').lower() == 'true'
    CACHE_TTL = int(os.getenv('CACHE_TTL', 300))  # 5 minutes
    
    # Database Configuration (for chat history)
    DATABASE_URL = os.getenv('DATABASE_URL', 'sqlite:///weather_chatbot.db')
    
    # CORS Configuration
    CORS_ORIGINS = os.getenv('CORS_ORIGINS', '*').split(',')
    
    # Security Configuration
    SESSION_COOKIE_SECURE = os.getenv('SESSION_COOKIE_SECURE', 'False').lower() == 'true'
    SESSION_COOKIE_HTTPONLY = os.getenv('SESSION_COOKIE_HTTPONLY', 'True').lower() == 'true'
    SESSION_COOKIE_SAMESITE = os.getenv('SESSION_COOKIE_SAMESITE', 'Lax')
    
    # Application Information
    APP_NAME = "Weather Chatbot"
    APP_VERSION = "1.0.0"
    APP_AUTHOR = "RSK World"
    APP_WEBSITE = "https://rskworld.in"
    APP_YEAR = "2026"
    
    # Supported Cities for Quick Access
    SUPPORTED_CITIES = [
        'London', 'New York', 'Paris', 'Tokyo', 'Delhi', 'Mumbai', 
        'Kolkata', 'Chennai', 'Bangalore', 'Sydney', 'Moscow', 
        'Beijing', 'Dubai', 'Singapore', 'Hong Kong'
    ]
    
    # Weather Alert Thresholds
    ALERT_TEMPERATURE_HIGH = 40.0  # Celsius
    ALERT_TEMPERATURE_LOW = -10.0  # Celsius
    ALERT_WIND_SPEED_HIGH = 20.0   # m/s
    ALERT_HUMIDITY_HIGH = 90.0     # Percentage
    
    @staticmethod
    def validate_config():
        """Validate required configuration settings"""
        errors = []
        
        if not Config.OPENWEATHER_API_KEY:
            errors.append("OPENWEATHER_API_KEY is required")
        
        if errors:
            raise ValueError("Configuration validation failed: " + ", ".join(errors))
        
        return True
    
    @staticmethod
    def get_app_info():
        """Get application information"""
        return {
            'name': Config.APP_NAME,
            'version': Config.APP_VERSION,
            'author': Config.APP_AUTHOR,
            'website': Config.APP_WEBSITE,
            'year': Config.APP_YEAR,
            'contact': {
                'phone': '+91 93305 39277',
                'email': 'hello@rskworld.in',
                'support': 'support@rskworld.in'
            },
            'location': 'Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147'
        }

class DevelopmentConfig(Config):
    """Development configuration"""
    DEBUG = True
    LOG_LEVEL = 'DEBUG'

class ProductionConfig(Config):
    """Production configuration"""
    DEBUG = False
    SESSION_COOKIE_SECURE = True
    LOG_LEVEL = 'WARNING'

class TestingConfig(Config):
    """Testing configuration"""
    TESTING = True
    DEBUG = True
    OPENWEATHER_API_KEY = 'test_key'
    OPENAI_API_KEY = 'test_key'

# Configuration mapping
config_map = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'testing': TestingConfig,
    'default': DevelopmentConfig
}

def get_config(config_name=None):
    """Get configuration based on environment"""
    if config_name is None:
        config_name = os.getenv('FLASK_ENV', 'default')
    
    return config_map.get(config_name, DevelopmentConfig)
151 lines•4.9 KB
python
tests/test_app.py
Raw Download
Find: Go to:
#!/usr/bin/env python3
"""
Weather Chatbot Application Tests
==================================

Author: RSK World (https://rskworld.in)
Year: 2026

Description: Unit tests for the Weather Chatbot Flask application
"""

import pytest
import os
import sys
from unittest.mock import patch, MagicMock

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

from app import app, chatbot

@pytest.fixture
def client():
    """Create a test client for the Flask application."""
    app.config['TESTING'] = True
    app.config['SECRET_KEY'] = 'test-secret-key'
    with app.test_client() as client:
        yield client

def test_index_route(client):
    """Test the index route."""
    response = client.get('/')
    assert response.status_code == 200
    assert b'Weather Chatbot' in response.data

def test_health_check(client):
    """Test the health check endpoint."""
    response = client.get('/health')
    assert response.status_code == 200
    data = response.get_json()
    assert data['status'] == 'healthy'
    assert 'timestamp' in data

def test_chat_route_empty_message(client):
    """Test chat route with empty message."""
    response = client.post('/chat', data={'message': ''})
    assert response.status_code == 200
    data = response.get_json()
    assert 'error' in data

def test_chat_route_with_message(client):
    """Test chat route with a message."""
    with patch.object(chatbot, 'chat', return_value={'city': 'London', 'temperature': 15}):
        response = client.post('/chat', data={'message': 'What is the weather in London?'})
        assert response.status_code == 200
        data = response.get_json()
        assert 'city' in data or 'error' in data

def test_weather_route(client):
    """Test weather endpoint."""
    with patch.object(chatbot, 'get_weather_by_city', return_value={'city': 'London', 'temperature': 15}):
        response = client.get('/weather/London')
        assert response.status_code == 200
        data = response.get_json()
        assert 'city' in data or 'error' in data

def test_forecast_route(client):
    """Test forecast endpoint."""
    with patch.object(chatbot, 'get_forecast_by_city', return_value={'city': 'London', 'forecasts': []}):
        response = client.get('/forecast/London')
        assert response.status_code == 200
        data = response.get_json()
        assert 'city' in data or 'error' in data

def test_alerts_route(client):
    """Test alerts endpoint."""
    with patch.object(chatbot, 'get_weather_alerts', return_value={'city': 'London', 'alerts': []}):
        response = client.get('/alerts/London')
        assert response.status_code == 200
        data = response.get_json()
        assert 'city' in data or 'error' in data

def test_404_error(client):
    """Test 404 error handling."""
    response = client.get('/nonexistent')
    assert response.status_code == 404

def test_500_error_handling(client):
    """Test 500 error handling."""
    with patch.object(chatbot, 'chat', side_effect=Exception('Test error')):
        response = client.post('/chat', data={'message': 'test'})
        assert response.status_code == 200
        data = response.get_json()
        assert 'error' in data
95 lines•3.3 KB
python
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

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