11import os
22import unittest
33from urllib .error import HTTPError
4+ from urllib .request import Request
45from meteoclimatic .exceptions import StationNotFound , MeteoclimaticError
56from meteoclimatic import MeteoclimaticClient
6- from unittest .mock import patch
7+ from meteoclimatic import __version__
8+ from unittest .mock import patch , MagicMock
79
810
911class TestMeteoclimaticClient (unittest .TestCase ):
@@ -19,8 +21,14 @@ def test_get_station_info_ok(self, mock_urlopen):
1921
2022 res = self .client .weather_at_station ("ESCAT4300000043206B" )
2123
22- mock_urlopen .assert_called_with (
23- "https://www.meteoclimatic.net/feed/rss/ESCAT4300000043206B" )
24+ # Verify urlopen was called with a Request object
25+ self .assertEqual (mock_urlopen .call_count , 1 )
26+ called_request = mock_urlopen .call_args [0 ][0 ]
27+ self .assertIsInstance (called_request , Request )
28+ self .assertEqual (called_request .full_url ,
29+ "https://www.meteoclimatic.net/feed/rss/ESCAT4300000043206B" )
30+ self .assertEqual (called_request .get_header ("User-agent" ),
31+ f"pymeteoclimatic/{ __version__ } " )
2432 self .assertEqual (res .station .code , "ESCAT4300000043206B" )
2533
2634 @patch ('meteoclimatic.client.urlopen' , autospec = True )
@@ -41,3 +49,21 @@ def test_get_station_info_404(self, mock_urlopen):
4149 self .client .weather_at_station ("ESCAT4300000043206B" )
4250 self .assertEqual (str (
4351 error .exception ), "Error fetching station data [status_code=404]" )
52+
53+ @patch ('meteoclimatic.client.urlopen' , autospec = True )
54+ def test_user_agent_header_is_set (self , mock_urlopen ):
55+ """Test that the User-Agent header is correctly set with version"""
56+ mock_response = MagicMock ()
57+ mock_response .read .return_value = open (os .path .join (
58+ os .path .dirname (__file__ ), "feeds" , "full_station.xml" )).read ()
59+ mock_urlopen .return_value = mock_response
60+
61+ self .client .weather_at_station ("ESCAT4300000043206B" )
62+
63+ # Verify the Request object has the correct User-Agent
64+ called_request = mock_urlopen .call_args [0 ][0 ]
65+ self .assertIsInstance (called_request , Request )
66+ user_agent = called_request .get_header ("User-agent" )
67+ self .assertEqual (user_agent , f"pymeteoclimatic/{ __version__ } " )
68+ # Verify it follows the expected format
69+ self .assertTrue (user_agent .startswith ("pymeteoclimatic/" ))
0 commit comments