#!/usr/bin/env python3 """ Test for UniFi device connection using unifiControl library. This module tests the connection to a UniFi device using the credentials from the config.json file and the unifiControl library. """ import os import sys import json import unittest from unittest.mock import patch # Add the src directory to the Python path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../src'))) # Import the SSLManager class to access the config loading functionality from src.ssl_manager import SSLManager # Import the unifiControl library try: from unificontrol import UnifiClient except ImportError: print("ERROR: unifiControl library is not installed. Please install it using 'pip install unifiControl'") sys.exit(1) class TestUniFiConnection(unittest.TestCase): """Test case for UniFi device connection.""" def setUp(self): """Set up test fixtures.""" # Create an SSLManager instance to load the config self.ssl_manager = SSLManager() # Get the UniFi connection parameters self.unifi_params = self.ssl_manager.get_unifi_connection_params() # Print the connection parameters (without the password) print(f"Testing connection to UniFi device at: {self.unifi_params['host']}") print(f"Using username: {self.unifi_params['username']}") def test_unifi_connection(self): """Test the connection to the UniFi device.""" # Skip the test if any of the required parameters are missing if not self.unifi_params['host'] or not self.unifi_params['username'] or not self.unifi_params['password']: self.skipTest("UniFi connection parameters are missing in the config file") try: print("\nAttempting to connect to UniFi device...") print(f"Host: {self.unifi_params['host']}") print(f"Username: {self.unifi_params['username']}") print(f"Password: {'*' * len(self.unifi_params['password'])}") # Create a UnifiClient instance client = UnifiClient( host=self.unifi_params['host'], username=self.unifi_params['username'], password=self.unifi_params['password'], port=443, # Default port for UniFi controller site=self.unifi_params['site'], # Site name from config cert=None # Skip SSL certificate verification ) # Disable SSL verification in the requests session client._session.verify = False # Suppress InsecureRequestWarning import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # Enable debug logging for requests import logging from http.client import HTTPConnection HTTPConnection.debuglevel = 1 logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True print("\nAttempting to login...") # Attempt to login client.login() print("Login successful!") # If login is successful, get the system info to further verify the connection print("Retrieving system info...") system_info = client.get_system_info() # Print some information about the connected system print("\nConnection successful!") print(f"System name: {system_info.get('name', 'N/A')}") print(f"Version: {system_info.get('version', 'N/A')}") # Logout to clean up the session print("Logging out...") client.logout() print("Logout successful!") # Assert that we got a valid system_info response self.assertIsNotNone(system_info) self.assertIn('name', system_info) except Exception as e: # If an exception occurs, fail the test with the error message print(f"\nError: {str(e)}") print("\nAuthentication failed. Possible reasons:") print("1. The credentials in config.json are incorrect") print("2. The UniFi device requires additional authentication parameters") print("3. The UniFi device is not accessible from the current network") print("4. The UniFi device is not running or is not responding") self.fail(f"Connection to UniFi device failed: {str(e)}") if __name__ == '__main__': unittest.main()