|
| 1 | +import pytest |
| 2 | +from collections import defaultdict |
| 3 | +from generator.formatter import _is_valid_identifier, format_data_with_schema |
| 4 | + |
| 5 | + |
| 6 | +class TestIsValidIdentifier: |
| 7 | + @pytest.mark.parametrize("key,expected", [ |
| 8 | + ("valid_key", True), |
| 9 | + ("_valid_key", True), |
| 10 | + ("ValidKey123", True), |
| 11 | + ("key123", True), |
| 12 | + ("key.with.dots", False), |
| 13 | + ("123invalid", False), |
| 14 | + (".starts_with_dot", False), |
| 15 | + ("", False), |
| 16 | + ("key-with-dash", False), |
| 17 | + ("key with space", False), |
| 18 | + ("key@special", False), |
| 19 | + ]) |
| 20 | + def test_is_valid_identifier(self, key, expected): |
| 21 | + assert _is_valid_identifier(key) == expected |
| 22 | + |
| 23 | + |
| 24 | +class TestFormatDataWithSchemaDictWithSpecialChars: |
| 25 | + def test_ocsf_dotted_keys_actual_failing_case(self): |
| 26 | + data = { |
| 27 | + "ocsf.activity_name": "Other", |
| 28 | + "ocsf.activity_id": "99" |
| 29 | + } |
| 30 | + schema = { |
| 31 | + "additionalProperties": { |
| 32 | + "type": "string" |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + result, imports = format_data_with_schema( |
| 37 | + data, |
| 38 | + schema, |
| 39 | + version="v1" |
| 40 | + ) |
| 41 | + |
| 42 | + assert result.startswith("{") |
| 43 | + assert result.endswith("}") |
| 44 | + assert '"ocsf.activity_name": \'Other\'' in result |
| 45 | + assert '"ocsf.activity_id": \'99\'' in result |
| 46 | + assert "dict(" not in result |
| 47 | + |
| 48 | + def test_multiple_dotted_keys(self): |
| 49 | + data = { |
| 50 | + "ocsf.activity_name": "Other", |
| 51 | + "ocsf.activity_id": "99", |
| 52 | + "ocsf.category_name": "System Activity" |
| 53 | + } |
| 54 | + schema = { |
| 55 | + "additionalProperties": { |
| 56 | + "type": "string" |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + result, imports = format_data_with_schema( |
| 61 | + data, |
| 62 | + schema, |
| 63 | + version="v1" |
| 64 | + ) |
| 65 | + |
| 66 | + assert result.startswith("{") |
| 67 | + assert result.endswith("}") |
| 68 | + assert '"ocsf.activity_name": \'Other\'' in result |
| 69 | + assert '"ocsf.activity_id": \'99\'' in result |
| 70 | + assert '"ocsf.category_name": \'System Activity\'' in result |
| 71 | + assert "dict(" not in result |
| 72 | + |
| 73 | + def test_dict_with_valid_identifiers_uses_constructor(self): |
| 74 | + data = { |
| 75 | + "normal_key": "value1", |
| 76 | + "another_key": "value2" |
| 77 | + } |
| 78 | + schema = { |
| 79 | + "additionalProperties": { |
| 80 | + "type": "string" |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + result, imports = format_data_with_schema( |
| 85 | + data, |
| 86 | + schema, |
| 87 | + version="v1" |
| 88 | + ) |
| 89 | + |
| 90 | + assert result.startswith("dict(") |
| 91 | + assert result.endswith(")") |
| 92 | + assert "normal_key='value1'" in result |
| 93 | + assert "another_key='value2'" in result |
0 commit comments