|
| 1 | +import pytest |
| 2 | +from collections import OrderedDict |
| 3 | +from unittest import mock |
| 4 | + |
| 5 | +from rest_framework.exceptions import ValidationError |
| 6 | + |
| 7 | +from awx.api.fields import DeprecatedCredentialField |
| 8 | + |
| 9 | + |
| 10 | +class TestDeprecatedCredentialField: |
| 11 | + """Test that DeprecatedCredentialField handles unexpected input types gracefully.""" |
| 12 | + |
| 13 | + def test_dict_value_raises_validation_error(self): |
| 14 | + """Passing a dict instead of an integer should return a 400 validation error, not a 500 TypeError.""" |
| 15 | + field = DeprecatedCredentialField() |
| 16 | + with pytest.raises(ValidationError): |
| 17 | + field.to_internal_value({"username": "admin", "password": "secret"}) |
| 18 | + |
| 19 | + def test_ordered_dict_value_raises_validation_error(self): |
| 20 | + """Passing an OrderedDict should return a 400 validation error, not a 500 TypeError.""" |
| 21 | + field = DeprecatedCredentialField() |
| 22 | + with pytest.raises(ValidationError): |
| 23 | + field.to_internal_value(OrderedDict([("username", "admin")])) |
| 24 | + |
| 25 | + def test_list_value_raises_validation_error(self): |
| 26 | + """Passing a list should return a 400 validation error, not a 500 TypeError.""" |
| 27 | + field = DeprecatedCredentialField() |
| 28 | + with pytest.raises(ValidationError): |
| 29 | + field.to_internal_value([1, 2, 3]) |
| 30 | + |
| 31 | + def test_string_value_raises_validation_error(self): |
| 32 | + """Passing a non-numeric string should return a 400 validation error.""" |
| 33 | + field = DeprecatedCredentialField() |
| 34 | + with pytest.raises(ValidationError): |
| 35 | + field.to_internal_value("not_a_number") |
| 36 | + |
| 37 | + @mock.patch('awx.api.fields.Credential.objects') |
| 38 | + def test_valid_integer_value_works(self, mock_cred_objects): |
| 39 | + """Passing a valid integer PK should work when the credential exists.""" |
| 40 | + mock_cred_objects.get.return_value = mock.MagicMock() |
| 41 | + field = DeprecatedCredentialField() |
| 42 | + assert field.to_internal_value(42) == 42 |
| 43 | + |
| 44 | + @mock.patch('awx.api.fields.Credential.objects') |
| 45 | + def test_valid_string_integer_value_works(self, mock_cred_objects): |
| 46 | + """Passing a numeric string PK should work when the credential exists.""" |
| 47 | + mock_cred_objects.get.return_value = mock.MagicMock() |
| 48 | + field = DeprecatedCredentialField() |
| 49 | + assert field.to_internal_value("42") == 42 |
0 commit comments