def parse_api_iso3(country_codes):
"""
Parse the additional country data from the API and return a csv file.
The csv file will contain the following columns:
- adm0_code
- nutrition
- currencyExchangeGraph
- balanceOfTradeGraph
- inflationGraphs
- food
"""
output_dir = "../assets/iso3_data"
code
if not os.path.exists(output_dir):
os.makedirs(output_dir)
csv_file_path = os.path.join(output_dir, "iso3.csv")
json_file_path = os.path.join(output_dir, "iso3.json")
if os.path.exists(csv_file_path):
print("Removing the existing iso3.csv file.")
os.remove(csv_file_path)
if os.path.exists(json_file_path):
print("Removing the existing iso3.json file.")
os.remove(json_file_path)
# Prepare new CSV file
fieldnames = [
"countryCode",
"nutrition",
"currencyExchangeGraph",
"balanceOfTradeGraph",
"inflationGraphs",
"food",
]
with open(csv_file_path, "w", newline="", encoding="utf-8") as csv_file:
csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
csv_writer.writeheader()
all_responses = []
for country_code in country_codes:
url = COUNTRIES_ISO3.format(country_code)
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
all_responses.append(data)
row = {
"countryCode": country_code,
"nutrition": data.get("nutrition"),
"currencyExchangeGraph": data.get("currencyExchangeGraph"),
"balanceOfTradeGraph": data.get("balanceOfTradeGraph"),
"inflationGraphs": data.get("inflationGraphs"),
"food": data.get("food"),
}
csv_writer.writerow(row)
except Exception as e:
print(e)
# Save all responses to a JSON file
with open(json_file_path, "w", encoding="utf-8") as json_file:
json.dump(data, json_file, ensure_ascii=False, indent=4)
Assistant
def main():
country_codes = [country.alpha_3 for country in pycountry.countries]
parse_api_iso3(country_codes)
if name == "main":
main()
write a test file for this parser. It is in the parsers folder I mentioned above and also the test should be in the tests folder I mentioned above as well
Here is a test file for the parser code you provided. The test uses the unittest framework and mocks external dependencies like requests.get and file system operations to ensure that the parser function parse_api_iso3 works correctly without making actual API calls or writing to the real file system.
python
import unittest
from unittest.mock import patch, MagicMock
import tempfile
import os
import json
import csv
# Import the parser function from the parsers folder
from parsers.parse_iso3 import parse_api_iso3
class TestParseApiIso3(unittest.TestCase):
def setUp(self):
# Create a temporary directory to redirect file outputs
self.test_dir = tempfile.TemporaryDirectory()
# Patch os.path.join to redirect outputs to the temporary directory
self.patcher_os_path_join = patch('os.path.join', side_effect=self.mock_os_path_join)
self.mock_os_path_join = self.patcher_os_path_join.start()
def tearDown(self):
# Stop patching and clean up the temporary directory
self.patcher_os_path_join.stop()
self.test_dir.cleanup()
def mock_os_path_join(self, *args):
# Redirect the output directory to the temporary directory
path_components = list(args)
if args[0] == "../assets/iso3_data":
path_components[0] = self.test_dir.name
return os.path.join(*path_components)
@patch('requests.get')
def test_parse_api_iso3_success(self, mock_get):
# Prepare a mock response object
mock_response = MagicMock()
mock_response.raise_for_status.return_value = None
mock_response.json.return_value = {
"nutrition": {"data": "nutrition data"},
"currencyExchangeGraph": {"data": "currency exchange data"},
"balanceOfTradeGraph": {"data": "balance of trade data"},
"inflationGraphs": {"data": "inflation data"},
"food": {"data": "food data"},
}
# Configure the mock to return the mock response
mock_get.return_value = mock_response
# Test input with two country codes
test_country_codes = ['USA', 'CAN']
# Call the function to test
parse_api_iso3(test_country_codes)
# Check that the output files were created
csv_file_path = os.path.join(self.test_dir.name, 'iso3.csv')
json_file_path = os.path.join(self.test_dir.name, 'iso3.json')
self.assertTrue(os.path.exists(csv_file_path), f"{csv_file_path} should exist.")
self.assertTrue(os.path.exists(json_file_path), f"{json_file_path} should exist.")
# Read and validate the contents of the CSV file
with open(csv_file_path, 'r', encoding='utf-8') as csv_file:
reader = csv.DictReader(csv_file)
self.assertEqual(reader.fieldnames, [
"countryCode",
"nutrition",
"currencyExchangeGraph",
"balanceOfTradeGraph",
"inflationGraphs",
"food",
])
rows = list(reader)
# Expecting two rows in the CSV file
self.assertEqual(len(rows), 2)
for row in rows:
self.assertIn(row['countryCode'], test_country_codes)
for key in ['nutrition', 'currencyExchangeGraph', 'balanceOfTradeGraph', 'inflationGraphs', 'food']:
# The CSV stores string representations of the data
value = row[key]
expected_value = str(mock_response.json.return_value[key])
self.assertEqual(value, expected_value)
# Read and validate the contents of the JSON file
with open(json_file_path, 'r', encoding='utf-8') as json_file:
data = json.load(json_file)
# The JSON file contains the last response due to a bug in the parser
self.assertEqual(data, mock_response.json.return_value)
@patch('requests.get')
def test_parse_api_iso3_exception(self, mock_get):
# Configure the mock to raise an exception on the first API call
def side_effect(url, *args, **kwargs):
if 'USA' in url:
raise requests.exceptions.RequestException("API Error")
else:
mock_response = MagicMock()
mock_response.raise_for_status.return_value = None
mock_response.json.return_value = {
"nutrition": {"data": "nutrition data"},
"currencyExchangeGraph": {"data": "currency exchange data"},
"balanceOfTradeGraph": {"data": "balance of trade data"},
"inflationGraphs": {"data": "inflation data"},
"food": {"data": "food data"},
}
return mock_response
mock_get.side_effect = side_effect
# Test input with two country codes
test_country_codes = ['USA', 'CAN']
# Capture the print output
with patch('builtins.print') as mock_print:
parse_api_iso3(test_country_codes)
# Ensure that an exception message was printed
self.assertTrue(mock_print.called)
mock_print.assert_any_call('API Error')
# Check that the output files were created
csv_file_path = os.path.join(self.test_dir.name, 'iso3.csv')
json_file_path = os.path.join(self.test_dir.name, 'iso3.json')
self.assertTrue(os.path.exists(csv_file_path), f"{csv_file_path} should exist.")
self.assertTrue(os.path.exists(json_file_path), f"{json_file_path} should exist.")
# Read and validate the contents of the CSV file
with open(csv_file_path, 'r', encoding='utf-8') as csv_file:
reader = csv.DictReader(csv_file)
rows = list(reader)
# Expecting only one row since one API call failed
self.assertEqual(len(rows), 1)
row = rows[0]
self.assertEqual(row['countryCode'], 'CAN')
for key in ['nutrition', 'currencyExchangeGraph', 'balanceOfTradeGraph', 'inflationGraphs', 'food']:
value = row[key]
expected_value = str(mock_get.return_value.json.return_value[key])
self.assertEqual(value, expected_value)
# Read and validate the contents of the JSON file
with open(json_file_path, 'r', encoding='utf-8') as json_file:
data = json.load(json_file)
# The JSON file contains the last successful response due to a bug in the parser
self.assertEqual(data, mock_get.return_value.json.return_value)
if __name__ == '__main__':
unittest.main()
Explanation:
Imports and Setup:
We import necessary modules, including unittest, unittest.mock, and modules for handling temporary files and JSON/CSV operations.
We import the parse_api_iso3 function from the parsers folder.
Test Class and Setup:
We create a TestParseApiIso3 class that inherits from unittest.TestCase.
In the setUp method, we create a temporary directory to redirect file outputs and patch os.path.join to redirect any file operations to the temporary directory.
Test for Successful Parsing (test_parse_api_iso3_success):
We mock the requests.get method to return a predefined successful response.
We call the parse_api_iso3 function with test country codes.
We check that the CSV and JSON output files are created in the temporary directory.
We read the CSV file and validate that it contains the expected data.
We read the JSON file and validate that it contains the expected data.
Test for Exception Handling (test_parse_api_iso3_exception):
We configure the mock requests.get method to raise an exception for one of the country codes ('USA').
We call the parse_api_iso3 function and ensure that it handles the exception by printing an error message.
We check that the CSV and JSON output files are created and contain data only for the successful API calls.
We validate the contents of the output files.
Notes:
The test reveals a bug in the parser code where only the last API response is saved in the JSON file. Ideally, the parser should save all responses.
The test uses mocking extensively to avoid external dependencies and focuses on the logic within the parse_api_iso3 function.
Usage:
Place this test file in the tests folder alongside your parser code in the parsers folder. You can run the tests using a test runner like:
bash
python -m unittest tests.test_parse_iso3
Make sure to adjust the import paths according to your project's directory structure.