Skip to content

Commit

Permalink
test - consistent and mock
Browse files Browse the repository at this point in the history
  • Loading branch information
hannhegg committed Apr 19, 2025
1 parent 75fbf2d commit dc6e2df
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions tests/unit/test_format_yeardata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import unittest
import os
import requests
from unittest.mock import patch
from src.my_package.year_data import fetch_data

class TestDataFormatConsistency(unittest.TestCase):

@patch('requests.get')
def test_fetch_data_success(self, mock_get):
# Sample valid response data structure for the API
mock_data = {
'city': {
'name': 'Maura',
'country': 'NO'
},
'data': [
{'year': 2020, 'temperature': 12.5, 'precipitation': 100},
{'year': 2021, 'temperature': 13.0, 'precipitation': 120},
]
}

# Mock the API response
mock_response = unittest.mock.Mock()
mock_response.status_code = 200
mock_response.json.return_value = mock_data

mock_get.return_value = mock_response

city_name = 'Maura'
data, folder = fetch_data(city_name)

# Check if the data returned is a dictionary and contains the expected keys
self.assertIsInstance(data, dict)
self.assertIn('city', data)
self.assertIn('data', data)

# Check if the 'city' key contains the expected structure
self.assertIn('name', data['city'])
self.assertIn('country', data['city'])

# Check if the 'data' key contains a list of dictionaries with required fields
self.assertIsInstance(data['data'], list)
self.assertGreater(len(data['data']), 0) # Check that there is at least one year record

for record in data['data']:
self.assertIn('year', record)
self.assertIn('temperature', record)
self.assertIn('precipitation', record)
self.assertIsInstance(record['year'], int)
self.assertIsInstance(record['temperature'], (int, float))
self.assertIsInstance(record['precipitation'], (int, float))

# Test that the folder variable exists and is a valid path
self.assertEqual(folder, "../data/output_statistikk")

@patch('requests.get')
def test_fetch_data_failure(self, mock_get):
# Mock an unsuccessful response (non-200 status code)
mock_response = unittest.mock.Mock()
mock_response.status_code = 404
mock_response.json.return_value = {}

mock_get.return_value = mock_response

city_name = 'Maura'
data, folder = fetch_data(city_name)

# Ensure data is empty and folder is correct even on failure
self.assertEqual(data, {})
self.assertEqual(folder, "../data/output_statistikk")

def test_api_key_in_env(self):
# Check if the API_KEY is loaded from the environment
api_key = os.getenv("API_KEY")

self.assertIsNotNone(api_key, "API_KEY is not set in the environment.")
self.assertIsInstance(api_key, str)
self.assertGreater(len(api_key), 0, "API_KEY should not be an empty string.")

if __name__ == '__main__':
unittest.main()

0 comments on commit dc6e2df

Please sign in to comment.