"""Unit tests for utils timezone module.""" from datetime import datetime import pytest import pytz from src.constants import common_consts from src.constants import timezones as tz_const from src.utils import timezone def get_date(hours=12, timezone_name=None): """Get test datetime. Args: hours (int): hours in test date (<24) timezone_name (str): local timezone Returns: datetime: UTC test date or in local timezone """ date = datetime(2018, 1, 1, hours, 0, 0, tzinfo=pytz.utc) if timezone_name: tz = pytz.timezone(timezone_name) date = date.astimezone(tz) return date.replace(tzinfo=None) @pytest.mark.parametrize( 'local_date, timezone_name, expected_result', ( (get_date(), str(pytz.utc), get_date()), (get_date(timezone_name=tz_const.US_EASTERN), tz_const.US_EASTERN, get_date()) ) ) def test_convert_to_utc_datetime(local_date, timezone_name, expected_result): """Test for convert_to_utc function.""" result = timezone.convert_to_utc_datetime(local_date, timezone_name) assert result == expected_result @pytest.mark.parametrize( 'local_date, passed_local_date, to_utc_datetime_return_value, ' 'expected_result, func_called', ( ( get_date(), # string get_date().strftime(common_consts.DYNAMODB_DATETIME_FORMAT), get_date(hours=2), get_date(hours=2).strftime(common_consts.OUTPUT_DATETIME_FORMAT), True ), ( get_date(), # string get_date().strftime(common_consts.MAXWELLS_DATETIME_FORMAT), get_date(hours=2), get_date(hours=2).strftime( common_consts.OUTPUT_DATETIME_FORMAT), True ), ( get_date(), # datetime get_date(), get_date(hours=2), get_date(hours=2).strftime(common_consts.OUTPUT_DATETIME_FORMAT), True ), (None, None, None, None, False) ) ) def test_convert_to_utc_str( local_date, passed_local_date, to_utc_datetime_return_value, expected_result, func_called, mocker): """Test for convert_to_utc_str function.""" timezone_name = 'tz' mocked_convert_to_utc = mocker.patch( 'src.utils.timezone.convert_to_utc_datetime') mocked_convert_to_utc.return_value = to_utc_datetime_return_value result = timezone.convert_to_utc_str(passed_local_date, timezone_name) assert result == expected_result assert mocked_convert_to_utc.call_count == func_called if func_called: assert mocked_convert_to_utc.call_args[0] == ( local_date, timezone_name) def test_convert_to_utc_str_raises(mocker): """Test for convert_to_utc_str function.""" mocked_convert_to_utc = mocker.patch( 'src.utils.timezone.convert_to_utc_datetime') with pytest.raises(ValueError): timezone.convert_to_utc_str('funky date', 'tz') assert mocked_convert_to_utc.call_count == 0