Skip to content

Commit

Permalink
Merge pull request #53 from Iteo/decimal_example_fix
Browse files Browse the repository at this point in the history
Do not use random to generate example values for DecimalField
  • Loading branch information
mtyton authored Feb 2, 2024
2 parents 1613756 + abb0d34 commit a3ce2b6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
8 changes: 7 additions & 1 deletion audoma/examples.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import datetime
import random
from decimal import Decimal
from typing import (
Any,
Type,
Expand Down Expand Up @@ -49,7 +50,12 @@ def generate_value(self) -> float:
"""
min_val = float(getattr(self.field, "min_value", 1) or 1)
max_val = float(getattr(self.field, "max_value", 1000) or 1000)
return random.uniform(min_val, max_val)
decimal_places = getattr(self.field, "decimal_places", None)
if decimal_places:
fmt = f".{decimal_places}f"
return Decimal(f"{(max_val):{fmt}}")
ret = random.uniform(min_val, max_val)
return ret


class RegexExample(Example):
Expand Down
21 changes: 21 additions & 0 deletions audoma/tests/test_openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,27 @@ def test_map_serializer_field_choicefield_xchoices_success(self):
{"choices": {"SMALL": "small", "MEDIUM": "medium", "LARGE": "large"}},
)

def test_decimal_examples_are_generated_correctly(self):
fields_config = {
"order_value": audoma_fields.DecimalField(
max_digits=5, decimal_places=2, min_value=999.98, max_value=999.99
)
}
serializer = create_serializer(
fields_config=fields_config, serializer_base_classes=[Serializer]
)
serializer_fields = serializer.fields

request = self.factory.get("/example/")
view = create_basic_view(view_properties={"serializer_class": type(serializer)})
view.request = request
view.action = "retrieve"
view.schema = AudomaAutoSchema()
mapped_field = view.schema._map_serializer_field(
serializer_fields["order_value"], direction="response"
)
self.assertEqual(mapped_field["example"], "999.99")

def test_map_serializer_field_audoma_choicefield_xchoices_success(self):
fields_config = {
"company_name": audoma_fields.CharField(max_length=255),
Expand Down

0 comments on commit a3ce2b6

Please sign in to comment.