add test for ip_online check

This commit is contained in:
martin legrand 2025-04-26 10:27:17 +02:00
parent dce9074969
commit e4ae8162a0
2 changed files with 73 additions and 4 deletions

View File

@ -45,7 +45,6 @@ class Provider:
self.api_key = self.get_api_key(self.provider_name)
elif self.provider_name != "ollama":
pretty_print(f"Provider: {provider_name} initialized at {self.server_ip}", color="success")
print("IP online?", self.is_ip_online(self.server_ip.split(":")[0]))
def get_api_key(self, provider):
load_dotenv()
@ -85,11 +84,11 @@ class Provider:
"""
if not address:
return False
if address.lower() in ["127.0.0.1", "localhost", "0.0.0.0"]:
return True
parsed = urlparse(address if address.startswith(('http://', 'https://')) else f'http://{address}')
hostname = parsed.hostname or address
if "127.0.0.1" in address or "localhost" in address:
return True
try:
ip_address = socket.gethostbyname(hostname)
except socket.gaierror:

70
tests/test_provider.py Normal file
View File

@ -0,0 +1,70 @@
import unittest
from unittest.mock import patch, MagicMock
import os, sys
import socket
import subprocess
from urllib.parse import urlparse
import platform
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) # Add project root to Python path
from sources.llm_provider import Provider
class TestIsIpOnline(unittest.TestCase):
def setUp(self):
self.checker = Provider("ollama", "deepseek-r1:32b")
def test_empty_address(self):
"""Test with empty address"""
result = self.checker.is_ip_online("")
self.assertFalse(result)
def test_localhost(self):
"""Test with localhost"""
test_cases = [
"localhost",
"http://localhost",
"https://localhost",
"127.0.0.1",
"http://127.0.0.1",
"https://127.0.0.1:8080"
]
for address in test_cases:
with self.subTest(address=address):
result = self.checker.is_ip_online(address)
self.assertTrue(result)
def test_google_ips(self):
"""Test with known Google IPs"""
google_ips = [
"74.125.197.100",
"74.125.197.139",
"74.125.197.101",
"74.125.197.113",
"74.125.197.102",
"74.125.197.138"
]
for ip in google_ips:
with self.subTest(ip=ip), \
patch('socket.gethostbyname', return_value=ip), \
patch('subprocess.run', return_value=MagicMock(returncode=0)):
result = self.checker.is_ip_online(ip)
self.assertTrue(result)
def test_unresolvable_hostname(self):
"""Test with unresolvable hostname"""
address = "nonexistent.example.com"
with patch('socket.gethostbyname', side_effect=socket.gaierror):
result = self.checker.is_ip_online(address)
self.assertFalse(result)
def test_valid_domain(self):
"""Test with valid domain name"""
address = "google.com"
with patch('socket.gethostbyname', return_value="142.250.190.78"), \
patch('subprocess.run', return_value=MagicMock(returncode=0)):
result = self.checker.is_ip_online(address)
self.assertTrue(result)
if __name__ == '__main__':
unittest.main()