def parse_pdc():
"""
Parse the pdc data from the API and return a csv file.
The csv file will contain the following columns:
- id
- type
- severityId
- hazardName
- latitude
- longitude
- createDate
- lastUpdate
"""
code
# Clean the existing files
if not os.path.exists(os.path.join(SRC, "assets", "pdc_data")):
os.makedirs(os.path.join(SRC, "assets", "pdc_data"))
elif os.path.exists(os.path.join(SRC, "assets", "pdc_data", "pdc.csv")):
print("Removing the existing pdc.csv file.")
os.remove(os.path.join(SRC, "assets", "pdc_data", "pdc.csv"))
if os.path.exists(os.path.join(SRC, "assets", "pdc_data", "pdc.json")):
print("Removing the existing pdc.json file.")
os.remove(os.path.join(SRC, "assets", "pdc_data", "pdc.json"))
# Prepare new csv file
csv_file = open(
os.path.join(SRC, "assets", "pdc_data", "pdc.csv"), "w", encoding="utf-8"
)
csv_writer = csv.writer(csv_file)
csv_writer.writerow(
[
"id",
"type",
"severityId",
"hazardName",
"latitude",
"longitude",
"createDate",
"lastUpdate",
]
)
# Get the data from the API
response = requests.get(COUNTRIES_PDC).json()
with open(
os.path.join(SRC, "assets", "pdc_data", "pdc.json"), "w", encoding="utf-8"
) as json_file:
json.dump(response, json_file)
response = response["body"]
# Write the data to the csv file
for feature in response:
id = feature["Id"]
type = feature["type"]
severity_id = feature["severity_id"]
hazard_name = feature["hazard_name"]
latitude = feature["latitude"]
longitude = feature["longitude"]
create_date = feature["create_date"]
last_update = feature["last_update"]
csv_writer.writerow(
[
id,
type,
severity_id,
hazard_name,
latitude,
longitude,
create_date,
last_update,
]
)
csv_file.close()
Assistant
def parse_pdc_per_country(csv_file_path):
"""
This function preprocesses the csv-file coming from parse_pdc function.
It groups the data by country and writes the data to a new csv file.
A file is created for each country with the following columns:
-- id
-- type
-- severityId
-- hazardName
-- latitude
-- longitude
-- createDate
-- lastUpdate
code
Args:
csv_file_path (_type_): The path to the csv file containing the pdc data.
"""
if os.path.exists(os.path.join(SRC, "assets", "pdc_data", "countries")):
print("Removing the existing countries folder.")
shutil.rmtree(os.path.join(SRC, "assets", "pdc_data", "countries"))
os.makedirs(os.path.join(SRC, "assets", "pdc_data", "countries"))
file = open(csv_file_path, "r", encoding="utf-8")
# Iterate over the rows and group the data by country using `get_country_and_city` function
country_data = {}
# get line count from file
line_count = 0
for line in file:
line_count += 1
# reset file pointer
file.seek(0)
csv_reader = csv.reader(file)
next(csv_reader) # Skip the header
for row in tqdm(csv_reader, desc="Processing PDC data", total=line_count):
if len(row) < 8:
print(f"Skipping row with insufficient columns: {row}")
continue
latitude = row[4]
longitude = row[5]
country, city = get_country_and_city(latitude, longitude)
if country is None:
country = "Not specified area"
if country not in country_data:
country_data[country] = []
# Add city to the data
country_data[country].append(
[
row[0],
row[1],
row[2],
row[3],
row[4],
row[5],
row[6],
row[7],
]
)
# Write the data to the csv files
for country, data in country_data.items():
csv_file = open(
os.path.join(SRC, "assets", "pdc_data", "countries", f"{country}.csv"),
"w",
encoding="utf-8",
)
csv_writer = csv.writer(csv_file)
csv_writer.writerow(
[
"id",
"type",
"severityId",
"hazardName",
"latitude",
"longitude",
"createDate",
"lastUpdate",
]
)
for row in data:
csv_writer.writerow(row)
csv_file.close()
Certainly! Here's a test file for your parser code. This test suite uses the unittest module along with unittest.mock to mock external dependencies like API requests and file system operations. This ensures that your tests are reliable and do not depend on external factors like network availability or the actual API response.
python
import unittest
from unittest.mock import patch, MagicMock, mock_open, call
import os
import json
import shutil
from io import StringIO
# Assuming your parser code is in a module named 'pdc_parser'
# and the file structure is as follows:
# - project_root/
# - pdc_parser.py
# - tests/
# - test_pdc_parser.py
# You may need to adjust the import statements based on your actual module name and structure
from pdc_parser import parse_pdc, parse_pdc_per_country
class TestPDCParser(unittest.TestCase):
@patch('pdc_parser.requests.get')
@patch('pdc_parser.os.makedirs')
@patch('pdc_parser.os.path.exists')
@patch('pdc_parser.open', new_callable=mock_open)
@patch('pdc_parser.os.remove')
def test_parse_pdc(self, mock_remove, mock_open_file, mock_exists, mock_makedirs, mock_requests_get):
# Mock the API response
mock_response_data = {
"body": [
{
"Id": "1",
"type": "Earthquake",
"severity_id": "High",
"hazard_name": "Earthquake",
"latitude": "34.05",
"longitude": "-118.25",
"create_date": "2023-10-01",
"last_update": "2023-10-02"
},
{
"Id": "2",
"type": "Flood",
"severity_id": "Medium",
"hazard_name": "Flood",
"latitude": "51.51",
"longitude": "-0.13",
"create_date": "2023-10-03",
"last_update": "2023-10-04"
}
]
}
mock_response = MagicMock()
mock_response.json.return_value = mock_response_data
mock_requests_get.return_value = mock_response
# Mock os.path.exists to control flow
def side_effect_exists(path):
if 'pdc.csv' in path or 'pdc.json' in path:
return True
return False
mock_exists.side_effect = side_effect_exists
# Call the function under test
parse_pdc()
# Assertions
mock_requests_get.assert_called_once()
# Check that files were removed
expected_remove_calls = [
call(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets", "pdc_data", "pdc.csv")),
call(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets", "pdc_data", "pdc.json"))
]
mock_remove.assert_has_calls(expected_remove_calls, any_order=True)
# Check that the CSV file was opened for writing
csv_file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets", "pdc_data", "pdc.csv")
mock_open_file.assert_any_call(csv_file_path, 'w', encoding='utf-8')
# You can add more assertions to check the CSV writer calls if needed
@patch('pdc_parser.get_country_and_city')
@patch('pdc_parser.os.makedirs')
@patch('pdc_parser.os.path.exists')
@patch('pdc_parser.shutil.rmtree')
@patch('pdc_parser.open', new_callable=mock_open, read_data='id,type,severityId,hazardName,latitude,longitude,createDate,lastUpdate\n1,Earthquake,High,Earthquake,34.05,-118.25,2023-10-01,2023-10-02\n2,Flood,Medium,Flood,51.51,-0.13,2023-10-03,2023-10-04\n')
def test_parse_pdc_per_country(self, mock_open_file, mock_rmtree, mock_exists, mock_makedirs, mock_get_country_and_city):
# Mock get_country_and_city
def side_effect_get_country_and_city(lat, lon):
if lat == '34.05' and lon == '-118.25':
return ('United States', 'Los Angeles')
elif lat == '51.51' and lon == '-0.13':
return ('United Kingdom', 'London')
else:
return (None, None)
mock_get_country_and_city.side_effect = side_effect_get_country_and_city
# Mock os.path.exists to control flow
mock_exists.return_value = True
# Call the function under test
csv_file_path = 'dummy_path/pdc.csv'
parse_pdc_per_country(csv_file_path)
# Assertions
mock_rmtree.assert_called_once()
# Check that directories were made
mock_makedirs.assert_called_once()
# Check that files were opened for writing
self.assertTrue(mock_open_file.call_count >= 3) # One for reading, at least two for writing
# Check that the correct files were written
# Extract the file handles used for writing
file_handles = [handle for handle in mock_open_file.mock_calls if handle[0] == '().__enter__']
# Since we're using mock_open, we can't access the actual file names directly
# If needed, you can adjust the mock to better capture file names
# You can add more detailed assertions to check that data was written correctly
if __name__ == '__main__':
unittest.main()
Explanation:
Imports:
We import the necessary modules, including unittest, unittest.mock, and functions from your parser code.
Adjust the import statements based on the actual location of your parser functions.
Mocking External Dependencies:
We use @patch decorators to mock external dependencies:
requests.get is mocked to return a predefined JSON response.
os.makedirs, os.path.exists, shutil.rmtree, and open are mocked to prevent actual file system operations.
Testing parse_pdc:
We mock the API response to return a known set of data.
We control the flow of os.path.exists to simulate the presence or absence of files.
We assert that:
requests.get is called correctly.
Files are opened and written as expected.
Files are removed if they exist.
Testing parse_pdc_per_country:
We mock the get_country_and_city function to return predefined country and city names based on input coordinates.
We simulate reading from a CSV file by providing read_data in mock_open.
We assert that:
Directories are created or removed as expected.
Files are opened and written for each country.
Running the Tests:
The test suite can be run directly by executing the script.
Make sure to adjust any file paths or module names to match your project's structure.
Notes:
Adjustments May Be Needed:
Replace 'pdc_parser' in the @patch decorators with the actual module name where your parser functions reside.
If your get_country_and_city function requires additional dependencies or different return values, adjust the side_effect accordingly.
Enhancing Assertions:
You can enhance the test by adding assertions to check the contents of the written files.
Since we are using mock_open, accessing the file content written can be complex. You might want to use io.StringIO or other methods to intercept file writes if needed.
Testing External Interactions:
By mocking external interactions, the tests become unit tests, focusing on the logic within your functions without relying on external systems.
Integration Tests:
If you want to perform integration tests that involve actual API calls and file operations, you should write separate tests and handle them carefully to avoid unwanted side effects.
Running the Test:
Save the Test File:
Save the test code in a file, e.g., test_pdc_parser.py, inside a tests directory in your project.
Install Requirements:
Ensure that the requests and unittest modules are available in your environment (they are part of the standard library, except for requests which you should have).
Execute the Test:
Run the test using the command:
code
python -m unittest tests/test_pdc_parser.py
Adjust the path as necessary based on your project structure.
I hope this helps you create a comprehensive test suite for your parser code!