IP to Geo

IP to Geo Git Source Tree

Root/tests/test_ip_to_geo.py

1#!/usr/bin/env python
2# -*- coding: utf-8
3
4import os
5import sys
6import socket
7from iptogeo import IPToGeo, IPToGeoException
8
9TIMEOUT = None
10# TIMEOUT = 5.0
11
12iptogeo = IPToGeo(timeout=TIMEOUT, family=socket.AF_INET6, remote_addr='::1')
13
14def get_random_ip_v4():
15 ip = '%d.%d.%d.%d' % \
16 (ord(os.urandom(1)), ord(os.urandom(1)), ord(os.urandom(1)), ord(os.urandom(1)))
17 return ip
18
19def test_ip(ip, verbose=True, proxy=iptogeo, result=None):
20 try:
21 (ipres, country_code) = proxy.ip_to_geo(ip)
22 except IPToGeoException, e:
23 if verbose:
24 print 'Error with IP %s' % (ip)
25 print e
26 return
27
28 if verbose:
29 if not country_code:
30 print 'Country code for %s (%s) not found' % (ip, ipres)
31 else:
32 print 'Country code for %s (%s) is %s' % (ip, ipres, country_code)
33
34 if not result is None:
35 if not country_code: country_code = ''
36 if result != country_code:
37 raise Exception('Bad result %s != %s' % (country_code, result))
38
39print '#### Coherence test'
40test_ip('1.5.7.3', result='jp')
41test_ip('1.5.255.4', result='jp')
42test_ip('1.6.255.4', result='in')
43test_ip('2.0.0.0', result='fr')
44test_ip('127.0.0.1', result='')
45test_ip('1.55.3.12', result='vn')
46test_ip('1.57.0.0', result='cn')
47test_ip('192.168.2.2', result='')
48
49test_ip('2001:600::', result='eu')
50test_ip('2001:608::00', result='de')
51test_ip('2001:0660:0000:0000:0000:0000:0000:0000', result='fr')
52test_ip('2001:670:1234:5678:9abc:def0:1234:5678', result='fi')
53test_ip('8001::', result='')
54test_ip('fe80::1a03:73ff:fee9:8705', result='')
55
56print '#### 5 sockets test'
57for i in range(0, 6):
58 print 'Test %d' % (i)
59 test_ip(get_random_ip_v4(), verbose=False, proxy=IPToGeo(timeout=TIMEOUT))
60
61print '#### 35 sockets test'
62for i in range(0, 36):
63 print 'Test %d' % (i)
64 test_ip(get_random_ip_v4(), verbose=False, proxy=IPToGeo(timeout=TIMEOUT))
65
66print '#### 1 socket heavy test'
67for i in range(0, 1000):
68 print 'Test %d' % (i)
69 test_ip(get_random_ip_v4(), verbose=False)
70
71print '#### 35 sockets heavy test'
72geo_proxy = []
73for i in range(0, 36):
74 geo_proxy.append(IPToGeo(timeout=TIMEOUT))
75
76for i in range(0, 1000):
77 print 'Test %d' % (i)
78 for proxy in geo_proxy:
79 test_ip(get_random_ip_v4(), verbose=False, proxy=proxy)
80
81print 'All is OK for me'

Archive Download this file

Branches

Tags