summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rwxr-xr-xtests/run_tests.py61
-rwxr-xr-xtests/test_cloudflare_api.py106
-rw-r--r--tests/test_connectivity.py58
-rw-r--r--tests/test_integration.py126
-rwxr-xr-xtests/test_namecheap_api.py88
5 files changed, 126 insertions, 313 deletions
diff --git a/tests/run_tests.py b/tests/run_tests.py
deleted file mode 100755
index 4933017..0000000
--- a/tests/run_tests.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/env python3
-
-import sys
-import os
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-from tests.test_namecheap_api import test_namecheap_api
-from tests.test_cloudflare_api import test_cloudflare_api
-
-def run_all_tests():
- """Run all integration tests"""
- print("๐Ÿงช REGFLOW INTEGRATION TEST SUITE")
- print("="*60)
- print("Testing API integrations with real endpoints")
- print("(Non-mutating operations only)")
- print("="*60)
-
- results = []
-
- # Test Namecheap API
- print("\n" + "="*60)
- namecheap_success = test_namecheap_api()
- results.append(("Namecheap API", namecheap_success))
-
- # Test Cloudflare API
- print("\n" + "="*60)
- cloudflare_success = test_cloudflare_api()
- results.append(("Cloudflare API", cloudflare_success))
-
- # Summary
- print("\n" + "="*60)
- print("TEST RESULTS SUMMARY")
- print("="*60)
-
- all_passed = True
- for test_name, success in results:
- status = "โœ… PASSED" if success else "โŒ FAILED"
- print(f"{test_name:20} {status}")
- if not success:
- all_passed = False
-
- print("="*60)
- if all_passed:
- print("๐ŸŽ‰ ALL TESTS PASSED! API integrations are working correctly.")
- print("\nYour API credentials are valid and the system is ready for use.")
- print("\nNext steps:")
- print(" - Use --dry-run for safe testing")
- print(" - Use --setup-only for existing domains")
- print(" - Run without flags for live domain registration")
- else:
- print("โŒ SOME TESTS FAILED! Please check your API credentials and network connection.")
- print("\nTroubleshooting:")
- print(" - Verify API tokens are correct and complete")
- print(" - Check that APIs are enabled for your accounts")
- print(" - Ensure network connectivity to API endpoints")
-
- return all_passed
-
-if __name__ == "__main__":
- success = run_all_tests()
- sys.exit(0 if success else 1) \ No newline at end of file
diff --git a/tests/test_cloudflare_api.py b/tests/test_cloudflare_api.py
deleted file mode 100755
index 97c19b3..0000000
--- a/tests/test_cloudflare_api.py
+++ /dev/null
@@ -1,106 +0,0 @@
-#!/usr/bin/env python3
-
-import sys
-import os
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-from config import Config
-from cloudflare_api import CloudflareAPI
-
-def test_cloudflare_api():
- """Test Cloudflare API integration with non-mutating calls"""
- print("="*50)
- print("CLOUDFLARE API INTEGRATION TESTS")
- print("="*50)
-
- # Load configuration
- config = Config.from_env()
-
- # Check if API credentials are available
- if not config.cloudflare_api_token or config.cloudflare_api_token == "your_cloudflare_api_token":
- print("โŒ Cloudflare API token not found. Please set CLOUDFLARE_API_TOKEN in .env file.")
- return False
-
- print(f"โœ“ API credentials loaded")
- print(f" - API Token: {'*' * (len(config.cloudflare_api_token) - 8)}{config.cloudflare_api_token[-8:]}")
- print(f" - Token length: {len(config.cloudflare_api_token)} chars")
-
- # Initialize API
- api = CloudflareAPI(config)
-
- # Test 1: List existing zones (non-mutating)
- print(f"\n1. Testing zones listing...")
- try:
- zones = api.list_zones()
- print(f" โœ“ Zone listing successful")
- print(f" - Found {len(zones)} zones in account")
-
- if zones:
- print(f" - Example zones:")
- for i, zone in enumerate(zones[:3]): # Show first 3 zones
- print(f" โ€ข {zone.get('name', 'Unknown')} (ID: {zone.get('id', 'Unknown')[:8]}...)")
- if i >= 2: # Limit to 3 zones
- break
- except Exception as e:
- print(f" โŒ Zone listing failed: {e}")
- return False
-
- # Test 2: Get zone info for an existing zone (if any)
- if zones:
- print(f"\n2. Testing zone info retrieval...")
- try:
- first_zone = zones[0]
- zone_name = first_zone.get('name')
- zone_info = api.get_zone_info(zone_name)
-
- if zone_info:
- print(f" โœ“ Zone info retrieved successfully")
- print(f" - Zone: {zone_info.get('name')}")
- print(f" - Status: {zone_info.get('status')}")
- print(f" - ID: {zone_info.get('id')[:8]}...")
-
- # Test 3: Get nameservers for the zone
- print(f"\n3. Testing nameserver retrieval...")
- try:
- nameservers = api.get_zone_nameservers(zone_info['id'])
- print(f" โœ“ Nameservers retrieved successfully")
- print(f" - Nameservers for {zone_name}:")
- for ns in nameservers:
- print(f" โ€ข {ns}")
- except Exception as e:
- print(f" โŒ Nameserver retrieval failed: {e}")
- return False
-
- # Test 4: Get DNS records for the zone (non-mutating)
- print(f"\n4. Testing DNS records retrieval...")
- try:
- dns_records = api.get_zone_dns_records(zone_info['id'])
- print(f" โœ“ DNS records retrieved successfully")
- print(f" - Found {len(dns_records)} DNS records")
-
- if dns_records:
- print(f" - Example records:")
- for i, record in enumerate(dns_records[:3]): # Show first 3 records
- print(f" โ€ข {record.get('type', 'Unknown')} {record.get('name', 'Unknown')} -> {record.get('content', 'Unknown')}")
- if i >= 2: # Limit to 3 records
- break
- except Exception as e:
- print(f" โŒ DNS records retrieval failed: {e}")
- return False
- else:
- print(f" โŒ Zone info retrieval failed: No zone info returned")
- return False
- except Exception as e:
- print(f" โŒ Zone info retrieval failed: {e}")
- return False
- else:
- print(f"\n2. Skipping zone-specific tests (no zones found)")
- print(f"3. Skipping nameserver tests (no zones found)")
- print(f"4. Skipping DNS records tests (no zones found)")
-
- print(f"\nโœ… All Cloudflare API tests passed!")
- return True
-
-if __name__ == "__main__":
- success = test_cloudflare_api()
- sys.exit(0 if success else 1) \ No newline at end of file
diff --git a/tests/test_connectivity.py b/tests/test_connectivity.py
deleted file mode 100644
index a344861..0000000
--- a/tests/test_connectivity.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/env python3
-
-import sys
-import os
-import requests
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-from config import Config
-
-def test_api_connectivity():
- """Test basic API connectivity"""
- print("="*50)
- print("API CONNECTIVITY TEST")
- print("="*50)
-
- config = Config.from_env()
-
- # Test Namecheap API connectivity
- print("\n1. Testing Namecheap API connectivity...")
- try:
- response = requests.get("https://api.namecheap.com/xml.response",
- params={"Command": "namecheap.domains.check", "DomainList": "test.com"},
- timeout=10)
- print(f" โœ“ Namecheap API reachable (Status: {response.status_code})")
- except Exception as e:
- print(f" โŒ Namecheap API unreachable: {e}")
-
- # Test Cloudflare API connectivity
- print("\n2. Testing Cloudflare API connectivity...")
- try:
- headers = {"Authorization": f"Bearer {config.cloudflare_api_token}"}
- response = requests.get("https://api.cloudflare.com/client/v4/user/tokens/verify",
- headers=headers, timeout=10)
- print(f" โœ“ Cloudflare API reachable (Status: {response.status_code})")
-
- if response.status_code == 200:
- result = response.json()
- if result.get('success'):
- print(f" โœ“ Cloudflare API token is valid")
- else:
- print(f" โŒ Cloudflare API token is invalid: {result.get('errors', [])}")
- else:
- print(f" โŒ Cloudflare API token verification failed")
- except Exception as e:
- print(f" โŒ Cloudflare API unreachable: {e}")
-
- print("\n3. API Token Information:")
- print(f" - Namecheap API Key: {len(config.namecheap_api_key)} chars")
- print(f" - Cloudflare API Token: {len(config.cloudflare_api_token)} chars")
- print(f" - Expected Cloudflare token length: 40 chars")
-
- if len(config.cloudflare_api_token) < 40:
- print(f" โš  Cloudflare token appears to be truncated")
- print(f" - Current token: {config.cloudflare_api_token}")
- print(f" - Please check if the token is complete in .env file")
-
-if __name__ == "__main__":
- test_api_connectivity() \ No newline at end of file
diff --git a/tests/test_integration.py b/tests/test_integration.py
new file mode 100644
index 0000000..4748172
--- /dev/null
+++ b/tests/test_integration.py
@@ -0,0 +1,126 @@
+import pytest
+import os
+from config import Config
+from namecheap_api import NamecheapAPI
+from cloudflare_api import CloudflareAPI
+
+
+@pytest.fixture
+def config():
+ """Load configuration for tests"""
+ return Config.from_env()
+
+
+@pytest.fixture
+def namecheap_api(config):
+ """Create Namecheap API instance"""
+ return NamecheapAPI(config)
+
+
+@pytest.fixture
+def cloudflare_api(config):
+ """Create Cloudflare API instance"""
+ return CloudflareAPI(config)
+
+
+def test_namecheap_credentials_loaded(config):
+ """Test that Namecheap credentials are loaded"""
+ assert config.namecheap_api_key, "Namecheap API key not found"
+ assert config.namecheap_api_user, "Namecheap API user not found"
+ assert config.namecheap_username, "Namecheap username not found"
+ assert config.namecheap_client_ip, "Namecheap client IP not found"
+
+
+def test_cloudflare_credentials_loaded(config):
+ """Test that Cloudflare credentials are loaded"""
+ assert config.cloudflare_api_token, "Cloudflare API token not found"
+ assert config.cloudflare_api_token != "your_cloudflare_api_token", "Cloudflare API token is placeholder"
+ assert len(config.cloudflare_api_token) == 40, f"Cloudflare API token should be 40 chars, got {len(config.cloudflare_api_token)}"
+
+
+def test_namecheap_domain_availability(namecheap_api):
+ """Test domain availability check"""
+ test_domain = "test-domain-12345.com"
+ is_available = namecheap_api.check_domain_availability(test_domain)
+ assert isinstance(is_available, bool), "Domain availability should return boolean"
+
+
+def test_namecheap_account_balance(namecheap_api):
+ """Test account balance retrieval"""
+ balance = namecheap_api.get_account_balance()
+ assert isinstance(balance, (int, float)), "Balance should be numeric"
+ assert balance >= 0, "Balance should be non-negative"
+
+
+def test_namecheap_domain_pricing(namecheap_api):
+ """Test domain pricing retrieval"""
+ pricing = namecheap_api.get_domain_pricing("example.com")
+ assert isinstance(pricing, dict), "Pricing should be a dictionary"
+ assert "register" in pricing, "Pricing should contain 'register' key"
+ assert "renew" in pricing, "Pricing should contain 'renew' key"
+ assert pricing["register"] > 0, "Registration price should be positive"
+ assert pricing["renew"] > 0, "Renewal price should be positive"
+
+
+def test_namecheap_different_tld_pricing(namecheap_api):
+ """Test pricing for different TLD"""
+ pricing = namecheap_api.get_domain_pricing("example.xyz")
+ assert isinstance(pricing, dict), "Pricing should be a dictionary"
+ assert pricing["register"] > 0, ".xyz registration price should be positive"
+
+
+def test_cloudflare_list_zones(cloudflare_api):
+ """Test listing Cloudflare zones"""
+ zones = cloudflare_api.list_zones()
+ assert isinstance(zones, list), "Zones should be a list"
+
+ if zones:
+ zone = zones[0]
+ assert "id" in zone, "Zone should have 'id' field"
+ assert "name" in zone, "Zone should have 'name' field"
+
+
+def test_cloudflare_zone_info(cloudflare_api):
+ """Test getting zone information"""
+ zones = cloudflare_api.list_zones()
+
+ if zones:
+ zone_name = zones[0]["name"]
+ zone_info = cloudflare_api.get_zone_info(zone_name)
+
+ assert zone_info is not None, "Zone info should not be None"
+ assert zone_info["name"] == zone_name, "Zone name should match"
+ assert "id" in zone_info, "Zone info should have 'id' field"
+
+
+def test_cloudflare_nameservers(cloudflare_api):
+ """Test getting zone nameservers"""
+ zones = cloudflare_api.list_zones()
+
+ if zones:
+ zone_id = zones[0]["id"]
+ nameservers = cloudflare_api.get_zone_nameservers(zone_id)
+
+ assert isinstance(nameservers, list), "Nameservers should be a list"
+ assert len(nameservers) > 0, "Should have at least one nameserver"
+
+ for ns in nameservers:
+ assert isinstance(ns, str), "Nameserver should be a string"
+ assert "cloudflare.com" in ns, "Nameserver should be from Cloudflare"
+
+
+def test_cloudflare_dns_records(cloudflare_api):
+ """Test getting DNS records"""
+ zones = cloudflare_api.list_zones()
+
+ if zones:
+ zone_id = zones[0]["id"]
+ records = cloudflare_api.get_zone_dns_records(zone_id)
+
+ assert isinstance(records, list), "DNS records should be a list"
+
+ if records:
+ record = records[0]
+ assert "type" in record, "Record should have 'type' field"
+ assert "name" in record, "Record should have 'name' field"
+ assert "content" in record, "Record should have 'content' field" \ No newline at end of file
diff --git a/tests/test_namecheap_api.py b/tests/test_namecheap_api.py
deleted file mode 100755
index c1df4c5..0000000
--- a/tests/test_namecheap_api.py
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/env python3
-
-import sys
-import os
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-from config import Config
-from namecheap_api import NamecheapAPI
-
-def test_namecheap_api():
- """Test Namecheap API integration with non-mutating calls"""
- print("="*50)
- print("NAMECHEAP API INTEGRATION TESTS")
- print("="*50)
-
- # Load configuration
- config = Config.from_env()
-
- # Check if API credentials are available
- if not all([
- config.namecheap_api_key,
- config.namecheap_api_user,
- config.namecheap_username,
- config.namecheap_client_ip
- ]):
- print("โŒ Namecheap API credentials not found. Please set them in .env file.")
- return False
-
- print(f"โœ“ API credentials loaded")
- print(f" - API User: {config.namecheap_api_user}")
- print(f" - Username: {config.namecheap_username}")
- print(f" - Client IP: {config.namecheap_client_ip}")
- print(f" - API Key: {'*' * len(config.namecheap_api_key)}")
-
- # Initialize API
- api = NamecheapAPI(config)
-
- # Test 1: Check domain availability (non-mutating)
- print(f"\n1. Testing domain availability check...")
- try:
- test_domain = "test-domain-12345.com"
- is_available = api.check_domain_availability(test_domain)
- print(f" โœ“ Domain availability check successful")
- print(f" - {test_domain} is {'available' if is_available else 'not available'}")
- except Exception as e:
- print(f" โŒ Domain availability check failed: {e}")
- return False
-
- # Test 2: Get account balance (non-mutating)
- print(f"\n2. Testing account balance retrieval...")
- try:
- balance = api.get_account_balance()
- print(f" โœ“ Account balance retrieved successfully")
- print(f" - Current balance: ${balance:.2f}")
- except Exception as e:
- print(f" โŒ Account balance retrieval failed: {e}")
- return False
-
- # Test 3: Get domain pricing (non-mutating)
- print(f"\n3. Testing domain pricing retrieval...")
- try:
- test_domain = "example.com"
- pricing = api.get_domain_pricing(test_domain)
- print(f" โœ“ Domain pricing retrieved successfully")
- print(f" - .com registration: ${pricing['register']:.2f}")
- print(f" - .com renewal: ${pricing['renew']:.2f}")
- except Exception as e:
- print(f" โŒ Domain pricing retrieval failed: {e}")
- return False
-
- # Test 4: Test with different TLD
- print(f"\n4. Testing pricing for different TLD...")
- try:
- test_domain = "example.xyz"
- pricing = api.get_domain_pricing(test_domain)
- print(f" โœ“ .xyz domain pricing retrieved successfully")
- print(f" - .xyz registration: ${pricing['register']:.2f}")
- print(f" - .xyz renewal: ${pricing['renew']:.2f}")
- except Exception as e:
- print(f" โŒ .xyz domain pricing retrieval failed: {e}")
- return False
-
- print(f"\nโœ… All Namecheap API tests passed!")
- return True
-
-if __name__ == "__main__":
- success = test_namecheap_api()
- sys.exit(0 if success else 1) \ No newline at end of file