"""Test for handler util.""" from datetime import datetime from unittest.mock import MagicMock import pytest from product.constants import error from product.models import ows_account from product.utils import handler_util def test_check_ownership_success( monkeypatch, fixture_subaccount_ownership_success): """Test subaccount ownership is success.""" account_type = 'subaccount' account_id = 2 grass_account_type = 'vendor' grass_account_id = 1 monkeypatch.setattr( ows_account, 'check_subaccount_ownership', MagicMock( return_value=fixture_subaccount_ownership_success)) result = handler_util.check_ownership( account_type, account_id, grass_account_type, grass_account_id) assert result.status == 200 def test_check_ownership_fails( monkeypatch, fixture_subaccount_ownership_failure): """Test subaccount ownership is failure.""" account_type = 'subaccount' account_id = 2 grass_account_type = 'vendor' grass_account_id = 1 monkeypatch.setattr( ows_account, 'check_subaccount_ownership', MagicMock( return_value=fixture_subaccount_ownership_failure)) result = handler_util.check_ownership( account_type, account_id, grass_account_type, grass_account_id) assert result.status == 403 assert result.errors['code'] == error.ERROR_CODE_AUTHORIZATION @pytest.mark.parametrize( ('account_type', 'account_id', 'grass_account_type', 'grass_account_id', 'expected_response'), [ ('subaccount', 2, 'subaccount', '2', True), ('vendor', 1, 'vendor', '1', True) ]) def test_check_ownership_valid_grass_access( account_type, account_id, grass_account_type, grass_account_id, expected_response): """Test valid grass access.""" result = handler_util.check_ownership( account_type, account_id, grass_account_type, grass_account_id) assert result is expected_response @pytest.mark.parametrize( ('account_type', 'account_id', 'grass_account_type', 'grass_account_id'), [ ('subaccount', 1, 'subaccount', '2'), ('vendor', 1, 'vendor', '2'), ('vendor', 1, 'subaccount', '1'), ('vendor', 1, 'subaccount', '2'), ]) def test_check_ownership_invalid_grass_access( account_type, account_id, grass_account_type, grass_account_id): """Test invalid grass access.""" result = handler_util.check_ownership( account_type, account_id, grass_account_type, grass_account_id) assert result.status == 403 assert result.errors['code'] == error.ERROR_CODE_AUTHORIZATION def test_json_datetime_encoder_datetime(): """Test DatetimeEncoder converts datetime objects to strings correctly.""" test_datetime = datetime.utcnow() test_datetime_str = test_datetime.isoformat() result = handler_util.DatetimeEncoder().default(test_datetime) assert result == test_datetime_str