|
| 1 | +from pyspark.sql.types import StringType, StructField, StructType |
| 2 | + |
| 3 | +from sparkdantic import SparkField, SparkModel |
| 4 | + |
| 5 | + |
| 6 | +class DescriptionModel(SparkModel): |
| 7 | + field_with_description: str = SparkField(description='This is a test description.') |
| 8 | + field_with_examples: str = SparkField(examples=['test']) |
| 9 | + field_with_description_and_examples: str = SparkField( |
| 10 | + description='testing description', examples=['testing example'] |
| 11 | + ) |
| 12 | + |
| 13 | + field_without_metadata: str = SparkField() |
| 14 | + |
| 15 | + |
| 16 | +def test_spark_schema_contains_field_metadata(): |
| 17 | + expected_schema = StructType( |
| 18 | + [ |
| 19 | + StructField( |
| 20 | + 'field_with_description', |
| 21 | + StringType(), |
| 22 | + False, |
| 23 | + metadata={'comment': 'This is a test description.'}, |
| 24 | + ), |
| 25 | + StructField( |
| 26 | + 'field_with_examples', |
| 27 | + StringType(), |
| 28 | + False, |
| 29 | + metadata={'examples': ['test']}, |
| 30 | + ), |
| 31 | + StructField( |
| 32 | + 'field_with_description_and_examples', |
| 33 | + StringType(), |
| 34 | + False, |
| 35 | + metadata={ |
| 36 | + 'comment': 'testing description', |
| 37 | + 'examples': ['testing example'], |
| 38 | + }, |
| 39 | + ), |
| 40 | + StructField( |
| 41 | + 'field_without_metadata', |
| 42 | + StringType(), |
| 43 | + False, |
| 44 | + metadata={}, |
| 45 | + ), |
| 46 | + ] |
| 47 | + ) |
| 48 | + |
| 49 | + actual_schema = DescriptionModel.model_spark_schema() |
| 50 | + print('hmmm') |
| 51 | + print(actual_schema) |
| 52 | + assert actual_schema == expected_schema |
| 53 | + |
| 54 | + |
| 55 | +def test_spark_schema_json_contains_field_metadata(): |
| 56 | + expected_json_schema = { |
| 57 | + 'type': 'struct', |
| 58 | + 'fields': [ |
| 59 | + { |
| 60 | + 'name': 'field_with_description', |
| 61 | + 'type': 'string', |
| 62 | + 'nullable': False, |
| 63 | + 'metadata': {'comment': 'This is a test description.'}, |
| 64 | + }, |
| 65 | + { |
| 66 | + 'name': 'field_with_examples', |
| 67 | + 'type': 'string', |
| 68 | + 'nullable': False, |
| 69 | + 'metadata': {'examples': ['test']}, |
| 70 | + }, |
| 71 | + { |
| 72 | + 'name': 'field_with_description_and_examples', |
| 73 | + 'type': 'string', |
| 74 | + 'nullable': False, |
| 75 | + 'metadata': { |
| 76 | + 'comment': 'testing description', |
| 77 | + 'examples': ['testing example'], |
| 78 | + }, |
| 79 | + }, |
| 80 | + { |
| 81 | + 'name': 'field_without_metadata', |
| 82 | + 'type': 'string', |
| 83 | + 'nullable': False, |
| 84 | + 'metadata': {}, |
| 85 | + }, |
| 86 | + ], |
| 87 | + } |
| 88 | + |
| 89 | + actual_json_schema = DescriptionModel.model_json_spark_schema() |
| 90 | + assert actual_json_schema == expected_json_schema |
0 commit comments