Skip to content

Commit cdce387

Browse files
bites 111
1 parent a1caa19 commit cdce387

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,4 @@
4949
/191/README.md
5050
/113/README.md
5151
/119/README.md
52+
/111/README.md

111/ipinfo.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import json
2+
3+
import requests
4+
5+
IPINFO_URL = 'http://ipinfo.io/{ip}/json'
6+
7+
8+
def get_ip_country(ip_address):
9+
"""Receives ip address string, use IPINFO_URL to get geo data,
10+
parse the json response returning the country code of the IP"""
11+
r=requests.get(IPINFO_URL[0:16],ip_address)
12+
data=r.text
13+
jsondata=json.loads(data)
14+
return jsondata['country']

111/test_ipinfo.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import json
2+
from unittest.mock import patch, Mock
3+
4+
import requests
5+
6+
from ipinfo import get_ip_country
7+
8+
9+
@patch.object(requests, 'get')
10+
def test_ipinfo_mexican_ip(mockget):
11+
# hardcoding a requests response
12+
content = (b'{\n "ip": "187.190.38.36",\n "hostname": "domain.net",\n'
13+
b' "city": "Mexico City",\n "region": "Mexico City",\n '
14+
b'"country": "MX",\n ' b'"loc": "11.0000,-00.1111",\n '
15+
b'"postal": "12345",\n "org": "some org"\n}')
16+
mockget.return_value = Mock(content=content,
17+
text=content.decode("utf-8"),
18+
json=lambda: json.loads(content),
19+
status_code=200)
20+
assert get_ip_country('187.190.38.36') == 'MX'
21+
22+
23+
@patch.object(requests, 'get')
24+
def test_ipinfo_japan_ip(mockget):
25+
# and another IP in Japan
26+
content = (b'{\n "ip": "185.161.200.10",\n "city": "Tokyo",\n '
27+
b'"region": "Tokyo",\n ' b'"country": "JP",\n "loc": '
28+
b'"00.1111,11.0000",\n "postal": "123-4567",\n '
29+
b'"org": "some other org"\n}')
30+
mockget.return_value = Mock(content=content,
31+
text=content.decode("utf-8"),
32+
json=lambda: json.loads(content),
33+
status_code=200)
34+
assert get_ip_country('185.161.200.10') == 'JP'

0 commit comments

Comments
 (0)