"""Tests for product ownership validation.""" import json from unittest import mock from oto import response import pytest from assets.constants import error from assets.models import ows_product from assets.validation import ownership @pytest.fixture def success_response(): """Fixture to generate a success response.""" return response.Response(message=error.SUCCESS_CODE) @pytest.fixture def failure_response(): """Fixture to generate a failure response.""" return response.create_error_response( code=error.ERROR_CODE_HEADER_VALIDATION, message='Test error') @pytest.fixture def fixture_function(request, product_id): """Function to mock GET /asset/product/ endpoint handler.""" @ownership.check_products_ownership(request) def function(product_id): return 'test_result' return function(product_id) def test_validate_product_ownership_success( valid_alw_headers, monkeypatch, success_response): """Assert that ownership checking succeeds when parameters valid.""" monkeypatch.setattr(ows_product, 'check_ownership', mock.MagicMock( return_value=success_response)) request = mock.Mock() request.headers = valid_alw_headers assert 'test_result' == fixture_function(request, 123) def test_validate_product_ownership_failure( valid_alw_headers, monkeypatch, failure_response): """Assert that ownership checking fails when check_ownership fails.""" monkeypatch.setattr(ows_product, 'check_ownership', mock.MagicMock( return_value=failure_response)) request = mock.Mock() request.headers = valid_alw_headers fixture_response = fixture_function(request, 123) assert fixture_response.status_code == 400 @pytest.mark.parametrize('missed_arg', [ 'Grass-Account-Id', 'Grass-Account-Type']) def test_validate_alw_headers_wrong_grass_account_type( valid_alw_headers, monkeypatch, failure_response, missed_arg): """Assert that ownership checking fails when required field missed.""" monkeypatch.setattr(ows_product, 'check_ownership', mock.MagicMock( return_value=failure_response)) del valid_alw_headers[missed_arg] request = mock.Mock() request.headers = valid_alw_headers fixture_response = fixture_function(request, 123) assert fixture_response.status_code == 400 response_json = json.loads(fixture_response.data.decode()) assert response_json['code'] == error.ERROR_CODE_HEADER_VALIDATION